blob: 420915a138f1ad8bf4cca070931efb57c87e231b [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000065#include "llvm/ADT/SmallPtrSet.h"
66#include "llvm/ADT/Statistic.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000067#include "llvm/Analysis/AssumptionCache.h"
John Criswellfe5f33b2005-10-27 15:54:34 +000068#include "llvm/Analysis/ConstantFolding.h"
Duncan Sandsd06f50e2010-11-17 04:18:45 +000069#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000070#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000071#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000072#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman1ee696d2009-06-16 19:52:01 +000073#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000074#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000075#include "llvm/IR/Constants.h"
76#include "llvm/IR/DataLayout.h"
77#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000078#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000079#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000080#include "llvm/IR/GlobalAlias.h"
81#include "llvm/IR/GlobalVariable.h"
Chandler Carruth83948572014-03-04 10:30:26 +000082#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000083#include "llvm/IR/Instructions.h"
84#include "llvm/IR/LLVMContext.h"
Sanjoy Das1f05c512014-10-10 21:22:34 +000085#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000086#include "llvm/IR/Operator.h"
Sanjoy Dasc88f5d32015-10-28 21:27:14 +000087#include "llvm/IR/PatternMatch.h"
Chris Lattner996795b2006-06-28 23:17:24 +000088#include "llvm/Support/CommandLine.h"
David Greene2330f782009-12-23 22:58:38 +000089#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000090#include "llvm/Support/ErrorHandling.h"
Chris Lattner0a1e9932006-12-19 01:16:02 +000091#include "llvm/Support/MathExtras.h"
Dan Gohmane20f8242009-04-21 00:47:46 +000092#include "llvm/Support/raw_ostream.h"
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +000093#include "llvm/Support/SaveAndRestore.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000094#include <algorithm>
Chris Lattnerd934c702004-04-02 20:23:17 +000095using namespace llvm;
96
Chandler Carruthf1221bd2014-04-22 02:48:03 +000097#define DEBUG_TYPE "scalar-evolution"
98
Chris Lattner57ef9422006-12-19 22:30:33 +000099STATISTIC(NumArrayLenItCounts,
100 "Number of trip counts computed with array length");
101STATISTIC(NumTripCountsComputed,
102 "Number of loops with predictable loop counts");
103STATISTIC(NumTripCountsNotComputed,
104 "Number of loops without predictable loop counts");
105STATISTIC(NumBruteForceTripCountsComputed,
106 "Number of loops with trip counts computed by force");
107
Dan Gohmand78c4002008-05-13 00:00:25 +0000108static cl::opt<unsigned>
Chris Lattner57ef9422006-12-19 22:30:33 +0000109MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
110 cl::desc("Maximum number of iterations SCEV will "
Dan Gohmance973df2009-06-24 04:48:43 +0000111 "symbolically execute a constant "
112 "derived loop"),
Chris Lattner57ef9422006-12-19 22:30:33 +0000113 cl::init(100));
114
Filipe Cabecinhas0da99372016-04-29 15:22:48 +0000115// FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
Benjamin Kramer214935e2012-10-26 17:31:32 +0000116static cl::opt<bool>
117VerifySCEV("verify-scev",
118 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
Wei Mia49559b2016-02-04 01:27:38 +0000119static cl::opt<bool>
120 VerifySCEVMap("verify-scev-maps",
Jeroen Ketemae48e3932016-04-12 23:21:46 +0000121 cl::desc("Verify no dangling value in ScalarEvolution's "
Wei Mia49559b2016-02-04 01:27:38 +0000122 "ExprValueMap (slow)"));
Benjamin Kramer214935e2012-10-26 17:31:32 +0000123
Chris Lattnerd934c702004-04-02 20:23:17 +0000124//===----------------------------------------------------------------------===//
125// SCEV class definitions
126//===----------------------------------------------------------------------===//
127
128//===----------------------------------------------------------------------===//
129// Implementation of the SCEV class.
130//
Dan Gohman3423e722009-06-30 20:13:32 +0000131
Davide Italiano2071f4c2015-10-25 19:55:24 +0000132LLVM_DUMP_METHOD
133void SCEV::dump() const {
134 print(dbgs());
135 dbgs() << '\n';
136}
137
Dan Gohman534749b2010-11-17 22:27:42 +0000138void SCEV::print(raw_ostream &OS) const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000139 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000140 case scConstant:
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000141 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000142 return;
143 case scTruncate: {
144 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
145 const SCEV *Op = Trunc->getOperand();
146 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
147 << *Trunc->getType() << ")";
148 return;
149 }
150 case scZeroExtend: {
151 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
152 const SCEV *Op = ZExt->getOperand();
153 OS << "(zext " << *Op->getType() << " " << *Op << " to "
154 << *ZExt->getType() << ")";
155 return;
156 }
157 case scSignExtend: {
158 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
159 const SCEV *Op = SExt->getOperand();
160 OS << "(sext " << *Op->getType() << " " << *Op << " to "
161 << *SExt->getType() << ")";
162 return;
163 }
164 case scAddRecExpr: {
165 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
166 OS << "{" << *AR->getOperand(0);
167 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
168 OS << ",+," << *AR->getOperand(i);
169 OS << "}<";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000170 if (AR->hasNoUnsignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000171 OS << "nuw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000172 if (AR->hasNoSignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000173 OS << "nsw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000174 if (AR->hasNoSelfWrap() &&
Andrew Trick8b55b732011-03-14 16:50:06 +0000175 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
176 OS << "nw><";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000177 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman534749b2010-11-17 22:27:42 +0000178 OS << ">";
179 return;
180 }
181 case scAddExpr:
182 case scMulExpr:
183 case scUMaxExpr:
184 case scSMaxExpr: {
185 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
Craig Topper9f008862014-04-15 04:59:12 +0000186 const char *OpStr = nullptr;
Dan Gohman534749b2010-11-17 22:27:42 +0000187 switch (NAry->getSCEVType()) {
188 case scAddExpr: OpStr = " + "; break;
189 case scMulExpr: OpStr = " * "; break;
190 case scUMaxExpr: OpStr = " umax "; break;
191 case scSMaxExpr: OpStr = " smax "; break;
192 }
193 OS << "(";
194 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
195 I != E; ++I) {
196 OS << **I;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000197 if (std::next(I) != E)
Dan Gohman534749b2010-11-17 22:27:42 +0000198 OS << OpStr;
199 }
200 OS << ")";
Andrew Trickd912a5b2011-11-29 02:06:35 +0000201 switch (NAry->getSCEVType()) {
202 case scAddExpr:
203 case scMulExpr:
Sanjoy Das76c48e02016-02-04 18:21:54 +0000204 if (NAry->hasNoUnsignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000205 OS << "<nuw>";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000206 if (NAry->hasNoSignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000207 OS << "<nsw>";
208 }
Dan Gohman534749b2010-11-17 22:27:42 +0000209 return;
210 }
211 case scUDivExpr: {
212 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
213 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
214 return;
215 }
216 case scUnknown: {
217 const SCEVUnknown *U = cast<SCEVUnknown>(this);
Chris Lattner229907c2011-07-18 04:54:35 +0000218 Type *AllocTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000219 if (U->isSizeOf(AllocTy)) {
220 OS << "sizeof(" << *AllocTy << ")";
221 return;
222 }
223 if (U->isAlignOf(AllocTy)) {
224 OS << "alignof(" << *AllocTy << ")";
225 return;
226 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000227
Chris Lattner229907c2011-07-18 04:54:35 +0000228 Type *CTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000229 Constant *FieldNo;
230 if (U->isOffsetOf(CTy, FieldNo)) {
231 OS << "offsetof(" << *CTy << ", ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000232 FieldNo->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000233 OS << ")";
234 return;
235 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000236
Dan Gohman534749b2010-11-17 22:27:42 +0000237 // Otherwise just print it normally.
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000238 U->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000239 return;
240 }
241 case scCouldNotCompute:
242 OS << "***COULDNOTCOMPUTE***";
243 return;
Dan Gohman534749b2010-11-17 22:27:42 +0000244 }
245 llvm_unreachable("Unknown SCEV kind!");
246}
247
Chris Lattner229907c2011-07-18 04:54:35 +0000248Type *SCEV::getType() const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000249 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000250 case scConstant:
251 return cast<SCEVConstant>(this)->getType();
252 case scTruncate:
253 case scZeroExtend:
254 case scSignExtend:
255 return cast<SCEVCastExpr>(this)->getType();
256 case scAddRecExpr:
257 case scMulExpr:
258 case scUMaxExpr:
259 case scSMaxExpr:
260 return cast<SCEVNAryExpr>(this)->getType();
261 case scAddExpr:
262 return cast<SCEVAddExpr>(this)->getType();
263 case scUDivExpr:
264 return cast<SCEVUDivExpr>(this)->getType();
265 case scUnknown:
266 return cast<SCEVUnknown>(this)->getType();
267 case scCouldNotCompute:
268 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman534749b2010-11-17 22:27:42 +0000269 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000270 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman534749b2010-11-17 22:27:42 +0000271}
272
Dan Gohmanbe928e32008-06-18 16:23:07 +0000273bool SCEV::isZero() const {
274 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
275 return SC->getValue()->isZero();
276 return false;
277}
278
Dan Gohmanba7f6d82009-05-18 15:22:39 +0000279bool SCEV::isOne() const {
280 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
281 return SC->getValue()->isOne();
282 return false;
283}
Chris Lattnerd934c702004-04-02 20:23:17 +0000284
Dan Gohman18a96bb2009-06-24 00:30:26 +0000285bool SCEV::isAllOnesValue() const {
286 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
287 return SC->getValue()->isAllOnesValue();
288 return false;
289}
290
Andrew Trick881a7762012-01-07 00:27:31 +0000291bool SCEV::isNonConstantNegative() const {
292 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
293 if (!Mul) return false;
294
295 // If there is a constant factor, it will be first.
296 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
297 if (!SC) return false;
298
299 // Return true if the value is negative, this matches things like (-42 * V).
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000300 return SC->getAPInt().isNegative();
Andrew Trick881a7762012-01-07 00:27:31 +0000301}
302
Owen Anderson04052ec2009-06-22 21:57:23 +0000303SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman24ceda82010-06-18 19:54:20 +0000304 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000305
Chris Lattnerd934c702004-04-02 20:23:17 +0000306bool SCEVCouldNotCompute::classof(const SCEV *S) {
307 return S->getSCEVType() == scCouldNotCompute;
308}
309
Dan Gohmanaf752342009-07-07 17:06:11 +0000310const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000311 FoldingSetNodeID ID;
312 ID.AddInteger(scConstant);
313 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +0000314 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000315 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman24ceda82010-06-18 19:54:20 +0000316 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000317 UniqueSCEVs.InsertNode(S, IP);
318 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000319}
Chris Lattnerd934c702004-04-02 20:23:17 +0000320
Nick Lewycky31eaca52014-01-27 10:04:03 +0000321const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000322 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman0a76e7f2007-07-09 15:25:17 +0000323}
324
Dan Gohmanaf752342009-07-07 17:06:11 +0000325const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +0000326ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
327 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Dan Gohmana029cbe2010-04-21 16:04:04 +0000328 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000329}
330
Dan Gohman24ceda82010-06-18 19:54:20 +0000331SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000332 unsigned SCEVTy, const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000333 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000334
Dan Gohman24ceda82010-06-18 19:54:20 +0000335SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000336 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000337 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000338 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
339 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000340 "Cannot truncate non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000341}
Chris Lattnerd934c702004-04-02 20:23:17 +0000342
Dan Gohman24ceda82010-06-18 19:54:20 +0000343SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000344 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000345 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000346 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
347 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000348 "Cannot zero extend non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000349}
350
Dan Gohman24ceda82010-06-18 19:54:20 +0000351SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000352 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000353 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000354 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
355 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000356 "Cannot sign extend non-integer value!");
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000357}
358
Dan Gohman7cac9572010-08-02 23:49:30 +0000359void SCEVUnknown::deleted() {
Dan Gohman761065e2010-11-17 02:44:44 +0000360 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000361 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000362
363 // Remove this SCEVUnknown from the uniquing map.
364 SE->UniqueSCEVs.RemoveNode(this);
365
366 // Release the value.
Craig Topper9f008862014-04-15 04:59:12 +0000367 setValPtr(nullptr);
Dan Gohman7cac9572010-08-02 23:49:30 +0000368}
369
370void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman761065e2010-11-17 02:44:44 +0000371 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000372 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000373
374 // Remove this SCEVUnknown from the uniquing map.
375 SE->UniqueSCEVs.RemoveNode(this);
376
377 // Update this SCEVUnknown to point to the new value. This is needed
378 // because there may still be outstanding SCEVs which still point to
379 // this SCEVUnknown.
380 setValPtr(New);
381}
382
Chris Lattner229907c2011-07-18 04:54:35 +0000383bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000384 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000385 if (VCE->getOpcode() == Instruction::PtrToInt)
386 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000387 if (CE->getOpcode() == Instruction::GetElementPtr &&
388 CE->getOperand(0)->isNullValue() &&
389 CE->getNumOperands() == 2)
390 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
391 if (CI->isOne()) {
392 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
393 ->getElementType();
394 return true;
395 }
Dan Gohmancf913832010-01-28 02:15:55 +0000396
397 return false;
398}
399
Chris Lattner229907c2011-07-18 04:54:35 +0000400bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000401 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000402 if (VCE->getOpcode() == Instruction::PtrToInt)
403 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000404 if (CE->getOpcode() == Instruction::GetElementPtr &&
405 CE->getOperand(0)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000406 Type *Ty =
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000407 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000408 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000409 if (!STy->isPacked() &&
410 CE->getNumOperands() == 3 &&
411 CE->getOperand(1)->isNullValue()) {
412 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
413 if (CI->isOne() &&
414 STy->getNumElements() == 2 &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000415 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000416 AllocTy = STy->getElementType(1);
417 return true;
418 }
419 }
420 }
Dan Gohmancf913832010-01-28 02:15:55 +0000421
422 return false;
423}
424
Chris Lattner229907c2011-07-18 04:54:35 +0000425bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000426 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000427 if (VCE->getOpcode() == Instruction::PtrToInt)
428 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
429 if (CE->getOpcode() == Instruction::GetElementPtr &&
430 CE->getNumOperands() == 3 &&
431 CE->getOperand(0)->isNullValue() &&
432 CE->getOperand(1)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000433 Type *Ty =
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000434 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
435 // Ignore vector types here so that ScalarEvolutionExpander doesn't
436 // emit getelementptrs that index into vectors.
Duncan Sands19d0b472010-02-16 11:11:14 +0000437 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000438 CTy = Ty;
439 FieldNo = CE->getOperand(2);
440 return true;
441 }
442 }
443
444 return false;
445}
446
Chris Lattnereb3e8402004-06-20 06:23:15 +0000447//===----------------------------------------------------------------------===//
448// SCEV Utilities
449//===----------------------------------------------------------------------===//
450
451namespace {
Sanjoy Das7881abd2015-12-08 04:32:51 +0000452/// SCEVComplexityCompare - Return true if the complexity of the LHS is less
453/// than the complexity of the RHS. This comparator is used to canonicalize
454/// expressions.
455class SCEVComplexityCompare {
456 const LoopInfo *const LI;
457public:
458 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman9ba542c2009-05-07 14:39:04 +0000459
Sanjoy Das7881abd2015-12-08 04:32:51 +0000460 // Return true or false if LHS is less than, or at least RHS, respectively.
461 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
462 return compare(LHS, RHS) < 0;
463 }
Dan Gohman27065672010-08-27 15:26:01 +0000464
Sanjoy Das7881abd2015-12-08 04:32:51 +0000465 // Return negative, zero, or positive, if LHS is less than, equal to, or
466 // greater than RHS, respectively. A three-way result allows recursive
467 // comparisons to be more efficient.
468 int compare(const SCEV *LHS, const SCEV *RHS) const {
469 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
470 if (LHS == RHS)
471 return 0;
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000472
Sanjoy Das7881abd2015-12-08 04:32:51 +0000473 // Primarily, sort the SCEVs by their getSCEVType().
474 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
475 if (LType != RType)
476 return (int)LType - (int)RType;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000477
Sanjoy Das7881abd2015-12-08 04:32:51 +0000478 // Aside from the getSCEVType() ordering, the particular ordering
479 // isn't very important except that it's beneficial to be consistent,
480 // so that (a + b) and (b + a) don't end up as different expressions.
481 switch (static_cast<SCEVTypes>(LType)) {
482 case scUnknown: {
483 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
484 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000485
Sanjoy Das7881abd2015-12-08 04:32:51 +0000486 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
487 // not as complete as it could be.
488 const Value *LV = LU->getValue(), *RV = RU->getValue();
Dan Gohman24ceda82010-06-18 19:54:20 +0000489
Sanjoy Das7881abd2015-12-08 04:32:51 +0000490 // Order pointer values after integer values. This helps SCEVExpander
491 // form GEPs.
492 bool LIsPointer = LV->getType()->isPointerTy(),
493 RIsPointer = RV->getType()->isPointerTy();
494 if (LIsPointer != RIsPointer)
495 return (int)LIsPointer - (int)RIsPointer;
Dan Gohman24ceda82010-06-18 19:54:20 +0000496
Sanjoy Das7881abd2015-12-08 04:32:51 +0000497 // Compare getValueID values.
498 unsigned LID = LV->getValueID(),
499 RID = RV->getValueID();
500 if (LID != RID)
501 return (int)LID - (int)RID;
Dan Gohman24ceda82010-06-18 19:54:20 +0000502
Sanjoy Das7881abd2015-12-08 04:32:51 +0000503 // Sort arguments by their position.
504 if (const Argument *LA = dyn_cast<Argument>(LV)) {
505 const Argument *RA = cast<Argument>(RV);
506 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
507 return (int)LArgNo - (int)RArgNo;
Dan Gohman24ceda82010-06-18 19:54:20 +0000508 }
509
Sanjoy Das7881abd2015-12-08 04:32:51 +0000510 // For instructions, compare their loop depth, and their operand
511 // count. This is pretty loose.
512 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
513 const Instruction *RInst = cast<Instruction>(RV);
Dan Gohman27065672010-08-27 15:26:01 +0000514
Sanjoy Das7881abd2015-12-08 04:32:51 +0000515 // Compare loop depths.
516 const BasicBlock *LParent = LInst->getParent(),
517 *RParent = RInst->getParent();
518 if (LParent != RParent) {
519 unsigned LDepth = LI->getLoopDepth(LParent),
520 RDepth = LI->getLoopDepth(RParent);
Dan Gohman0c436ab2010-08-13 21:24:58 +0000521 if (LDepth != RDepth)
Dan Gohman27065672010-08-27 15:26:01 +0000522 return (int)LDepth - (int)RDepth;
Dan Gohman0c436ab2010-08-13 21:24:58 +0000523 }
Dan Gohman27065672010-08-27 15:26:01 +0000524
Sanjoy Das7881abd2015-12-08 04:32:51 +0000525 // Compare the number of operands.
526 unsigned LNumOps = LInst->getNumOperands(),
527 RNumOps = RInst->getNumOperands();
Dan Gohman27065672010-08-27 15:26:01 +0000528 return (int)LNumOps - (int)RNumOps;
Dan Gohman24ceda82010-06-18 19:54:20 +0000529 }
530
Sanjoy Das7881abd2015-12-08 04:32:51 +0000531 return 0;
532 }
Dan Gohman27065672010-08-27 15:26:01 +0000533
Sanjoy Das7881abd2015-12-08 04:32:51 +0000534 case scConstant: {
535 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
536 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
537
538 // Compare constant values.
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000539 const APInt &LA = LC->getAPInt();
540 const APInt &RA = RC->getAPInt();
Sanjoy Das7881abd2015-12-08 04:32:51 +0000541 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
542 if (LBitWidth != RBitWidth)
543 return (int)LBitWidth - (int)RBitWidth;
544 return LA.ult(RA) ? -1 : 1;
545 }
546
547 case scAddRecExpr: {
548 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
549 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
550
551 // Compare addrec loop depths.
552 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
553 if (LLoop != RLoop) {
554 unsigned LDepth = LLoop->getLoopDepth(),
555 RDepth = RLoop->getLoopDepth();
556 if (LDepth != RDepth)
557 return (int)LDepth - (int)RDepth;
558 }
559
560 // Addrec complexity grows with operand count.
561 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
562 if (LNumOps != RNumOps)
563 return (int)LNumOps - (int)RNumOps;
564
565 // Lexicographically compare.
566 for (unsigned i = 0; i != LNumOps; ++i) {
567 long X = compare(LA->getOperand(i), RA->getOperand(i));
Dan Gohman27065672010-08-27 15:26:01 +0000568 if (X != 0)
569 return X;
Dan Gohman24ceda82010-06-18 19:54:20 +0000570 }
571
Sanjoy Das7881abd2015-12-08 04:32:51 +0000572 return 0;
Chris Lattnereb3e8402004-06-20 06:23:15 +0000573 }
Sanjoy Das7881abd2015-12-08 04:32:51 +0000574
575 case scAddExpr:
576 case scMulExpr:
577 case scSMaxExpr:
578 case scUMaxExpr: {
579 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
580 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
581
582 // Lexicographically compare n-ary expressions.
583 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
584 if (LNumOps != RNumOps)
585 return (int)LNumOps - (int)RNumOps;
586
587 for (unsigned i = 0; i != LNumOps; ++i) {
588 if (i >= RNumOps)
589 return 1;
590 long X = compare(LC->getOperand(i), RC->getOperand(i));
591 if (X != 0)
592 return X;
593 }
594 return (int)LNumOps - (int)RNumOps;
595 }
596
597 case scUDivExpr: {
598 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
599 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
600
601 // Lexicographically compare udiv expressions.
602 long X = compare(LC->getLHS(), RC->getLHS());
603 if (X != 0)
604 return X;
605 return compare(LC->getRHS(), RC->getRHS());
606 }
607
608 case scTruncate:
609 case scZeroExtend:
610 case scSignExtend: {
611 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
612 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
613
614 // Compare cast expressions by operand.
615 return compare(LC->getOperand(), RC->getOperand());
616 }
617
618 case scCouldNotCompute:
619 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
620 }
621 llvm_unreachable("Unknown SCEV kind!");
622 }
623};
624} // end anonymous namespace
Chris Lattnereb3e8402004-06-20 06:23:15 +0000625
Sanjoy Dasf8570812016-05-29 00:38:22 +0000626/// Given a list of SCEV objects, order them by their complexity, and group
627/// objects of the same complexity together by value. When this routine is
628/// finished, we know that any duplicates in the vector are consecutive and that
629/// complexity is monotonically increasing.
Chris Lattnereb3e8402004-06-20 06:23:15 +0000630///
Dan Gohman8b0a4192010-03-01 17:49:51 +0000631/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattnereb3e8402004-06-20 06:23:15 +0000632/// results from this routine. In other words, we don't want the results of
633/// this to depend on where the addresses of various SCEV objects happened to
634/// land in memory.
635///
Dan Gohmanaf752342009-07-07 17:06:11 +0000636static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman9ba542c2009-05-07 14:39:04 +0000637 LoopInfo *LI) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000638 if (Ops.size() < 2) return; // Noop
639 if (Ops.size() == 2) {
640 // This is the common case, which also happens to be trivially simple.
641 // Special case it.
Dan Gohman7712d292010-08-29 15:07:13 +0000642 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
643 if (SCEVComplexityCompare(LI)(RHS, LHS))
644 std::swap(LHS, RHS);
Chris Lattnereb3e8402004-06-20 06:23:15 +0000645 return;
646 }
647
Dan Gohman24ceda82010-06-18 19:54:20 +0000648 // Do the rough sort by complexity.
649 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
650
651 // Now that we are sorted by complexity, group elements of the same
652 // complexity. Note that this is, at worst, N^2, but the vector is likely to
653 // be extremely short in practice. Note that we take this approach because we
654 // do not want to depend on the addresses of the objects we are grouping.
655 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
656 const SCEV *S = Ops[i];
657 unsigned Complexity = S->getSCEVType();
658
659 // If there are any objects of the same complexity and same value as this
660 // one, group them.
661 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
662 if (Ops[j] == S) { // Found a duplicate.
663 // Move it to immediately after i'th element.
664 std::swap(Ops[i+1], Ops[j]);
665 ++i; // no need to rescan it.
666 if (i == e-2) return; // Done!
667 }
668 }
669 }
Chris Lattnereb3e8402004-06-20 06:23:15 +0000670}
671
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000672// Returns the size of the SCEV S.
673static inline int sizeOfSCEV(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +0000674 struct FindSCEVSize {
675 int Size;
676 FindSCEVSize() : Size(0) {}
677
678 bool follow(const SCEV *S) {
679 ++Size;
680 // Keep looking at all operands of S.
681 return true;
682 }
683 bool isDone() const {
684 return false;
685 }
686 };
687
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000688 FindSCEVSize F;
689 SCEVTraversal<FindSCEVSize> ST(F);
690 ST.visitAll(S);
691 return F.Size;
692}
693
694namespace {
695
David Majnemer4e879362014-12-14 09:12:33 +0000696struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000697public:
698 // Computes the Quotient and Remainder of the division of Numerator by
699 // Denominator.
700 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
701 const SCEV *Denominator, const SCEV **Quotient,
702 const SCEV **Remainder) {
703 assert(Numerator && Denominator && "Uninitialized SCEV");
704
David Majnemer4e879362014-12-14 09:12:33 +0000705 SCEVDivision D(SE, Numerator, Denominator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000706
707 // Check for the trivial case here to avoid having to check for it in the
708 // rest of the code.
709 if (Numerator == Denominator) {
710 *Quotient = D.One;
711 *Remainder = D.Zero;
712 return;
713 }
714
715 if (Numerator->isZero()) {
716 *Quotient = D.Zero;
717 *Remainder = D.Zero;
718 return;
719 }
720
Brendon Cahoona57cc8b2015-04-20 16:03:28 +0000721 // A simple case when N/1. The quotient is N.
722 if (Denominator->isOne()) {
723 *Quotient = Numerator;
724 *Remainder = D.Zero;
725 return;
726 }
727
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000728 // Split the Denominator when it is a product.
Sanjoy Dasb277a422016-06-15 06:53:55 +0000729 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000730 const SCEV *Q, *R;
731 *Quotient = Numerator;
732 for (const SCEV *Op : T->operands()) {
733 divide(SE, *Quotient, Op, &Q, &R);
734 *Quotient = Q;
735
736 // Bail out when the Numerator is not divisible by one of the terms of
737 // the Denominator.
738 if (!R->isZero()) {
739 *Quotient = D.Zero;
740 *Remainder = Numerator;
741 return;
742 }
743 }
744 *Remainder = D.Zero;
745 return;
746 }
747
748 D.visit(Numerator);
749 *Quotient = D.Quotient;
750 *Remainder = D.Remainder;
751 }
752
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000753 // Except in the trivial case described above, we do not know how to divide
754 // Expr by Denominator for the following functions with empty implementation.
755 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
756 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
757 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
758 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
759 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
760 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
761 void visitUnknown(const SCEVUnknown *Numerator) {}
762 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
763
David Majnemer4e879362014-12-14 09:12:33 +0000764 void visitConstant(const SCEVConstant *Numerator) {
765 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000766 APInt NumeratorVal = Numerator->getAPInt();
767 APInt DenominatorVal = D->getAPInt();
David Majnemer4e879362014-12-14 09:12:33 +0000768 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
769 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
770
771 if (NumeratorBW > DenominatorBW)
772 DenominatorVal = DenominatorVal.sext(NumeratorBW);
773 else if (NumeratorBW < DenominatorBW)
774 NumeratorVal = NumeratorVal.sext(DenominatorBW);
775
776 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
777 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
778 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
779 Quotient = SE.getConstant(QuotientVal);
780 Remainder = SE.getConstant(RemainderVal);
781 return;
782 }
783 }
784
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000785 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
786 const SCEV *StartQ, *StartR, *StepQ, *StepR;
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000787 if (!Numerator->isAffine())
788 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000789 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
790 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
Brendon Cahoonf9751ad2015-04-22 15:06:40 +0000791 // Bail out if the types do not match.
792 Type *Ty = Denominator->getType();
793 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000794 Ty != StepQ->getType() || Ty != StepR->getType())
795 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000796 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
797 Numerator->getNoWrapFlags());
798 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
799 Numerator->getNoWrapFlags());
800 }
801
802 void visitAddExpr(const SCEVAddExpr *Numerator) {
803 SmallVector<const SCEV *, 2> Qs, Rs;
804 Type *Ty = Denominator->getType();
805
806 for (const SCEV *Op : Numerator->operands()) {
807 const SCEV *Q, *R;
808 divide(SE, Op, Denominator, &Q, &R);
809
810 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000811 if (Ty != Q->getType() || Ty != R->getType())
812 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000813
814 Qs.push_back(Q);
815 Rs.push_back(R);
816 }
817
818 if (Qs.size() == 1) {
819 Quotient = Qs[0];
820 Remainder = Rs[0];
821 return;
822 }
823
824 Quotient = SE.getAddExpr(Qs);
825 Remainder = SE.getAddExpr(Rs);
826 }
827
828 void visitMulExpr(const SCEVMulExpr *Numerator) {
829 SmallVector<const SCEV *, 2> Qs;
830 Type *Ty = Denominator->getType();
831
832 bool FoundDenominatorTerm = false;
833 for (const SCEV *Op : Numerator->operands()) {
834 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000835 if (Ty != Op->getType())
836 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000837
838 if (FoundDenominatorTerm) {
839 Qs.push_back(Op);
840 continue;
841 }
842
843 // Check whether Denominator divides one of the product operands.
844 const SCEV *Q, *R;
845 divide(SE, Op, Denominator, &Q, &R);
846 if (!R->isZero()) {
847 Qs.push_back(Op);
848 continue;
849 }
850
851 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000852 if (Ty != Q->getType())
853 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000854
855 FoundDenominatorTerm = true;
856 Qs.push_back(Q);
857 }
858
859 if (FoundDenominatorTerm) {
860 Remainder = Zero;
861 if (Qs.size() == 1)
862 Quotient = Qs[0];
863 else
864 Quotient = SE.getMulExpr(Qs);
865 return;
866 }
867
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000868 if (!isa<SCEVUnknown>(Denominator))
869 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000870
871 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
872 ValueToValueMap RewriteMap;
873 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
874 cast<SCEVConstant>(Zero)->getValue();
875 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
876
877 if (Remainder->isZero()) {
878 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
879 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
880 cast<SCEVConstant>(One)->getValue();
881 Quotient =
882 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
883 return;
884 }
885
886 // Quotient is (Numerator - Remainder) divided by Denominator.
887 const SCEV *Q, *R;
888 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000889 // This SCEV does not seem to simplify: fail the division here.
890 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
891 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000892 divide(SE, Diff, Denominator, &Q, &R);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000893 if (R != Zero)
894 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000895 Quotient = Q;
896 }
897
898private:
David Majnemer5d2670c2014-11-17 11:27:45 +0000899 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
900 const SCEV *Denominator)
901 : SE(S), Denominator(Denominator) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000902 Zero = SE.getZero(Denominator->getType());
903 One = SE.getOne(Denominator->getType());
David Majnemer5d2670c2014-11-17 11:27:45 +0000904
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000905 // We generally do not know how to divide Expr by Denominator. We
906 // initialize the division to a "cannot divide" state to simplify the rest
907 // of the code.
908 cannotDivide(Numerator);
909 }
910
911 // Convenience function for giving up on the division. We set the quotient to
912 // be equal to zero and the remainder to be equal to the numerator.
913 void cannotDivide(const SCEV *Numerator) {
David Majnemer5d2670c2014-11-17 11:27:45 +0000914 Quotient = Zero;
915 Remainder = Numerator;
916 }
917
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000918 ScalarEvolution &SE;
919 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
David Majnemer32b8ccf2014-11-16 20:35:19 +0000920};
921
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000922}
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000923
Chris Lattnerd934c702004-04-02 20:23:17 +0000924//===----------------------------------------------------------------------===//
925// Simple SCEV method implementations
926//===----------------------------------------------------------------------===//
927
Sanjoy Dasf8570812016-05-29 00:38:22 +0000928/// Compute BC(It, K). The result has width W. Assume, K > 0.
Dan Gohmanaf752342009-07-07 17:06:11 +0000929static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohman32291b12009-07-21 00:38:55 +0000930 ScalarEvolution &SE,
Nick Lewycky702cf1e2011-09-06 06:39:54 +0000931 Type *ResultTy) {
Eli Friedman61f67622008-08-04 23:49:06 +0000932 // Handle the simplest case efficiently.
933 if (K == 1)
934 return SE.getTruncateOrZeroExtend(It, ResultTy);
935
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000936 // We are using the following formula for BC(It, K):
937 //
938 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
939 //
Eli Friedman61f67622008-08-04 23:49:06 +0000940 // Suppose, W is the bitwidth of the return value. We must be prepared for
941 // overflow. Hence, we must assure that the result of our computation is
942 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
943 // safe in modular arithmetic.
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000944 //
Eli Friedman61f67622008-08-04 23:49:06 +0000945 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohmance973df2009-06-24 04:48:43 +0000946 // is something like the following, where T is the number of factors of 2 in
Eli Friedman61f67622008-08-04 23:49:06 +0000947 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
948 // exponentiation:
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000949 //
Eli Friedman61f67622008-08-04 23:49:06 +0000950 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000951 //
Eli Friedman61f67622008-08-04 23:49:06 +0000952 // This formula is trivially equivalent to the previous formula. However,
953 // this formula can be implemented much more efficiently. The trick is that
954 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
955 // arithmetic. To do exact division in modular arithmetic, all we have
956 // to do is multiply by the inverse. Therefore, this step can be done at
957 // width W.
Dan Gohmance973df2009-06-24 04:48:43 +0000958 //
Eli Friedman61f67622008-08-04 23:49:06 +0000959 // The next issue is how to safely do the division by 2^T. The way this
960 // is done is by doing the multiplication step at a width of at least W + T
961 // bits. This way, the bottom W+T bits of the product are accurate. Then,
962 // when we perform the division by 2^T (which is equivalent to a right shift
963 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
964 // truncated out after the division by 2^T.
965 //
966 // In comparison to just directly using the first formula, this technique
967 // is much more efficient; using the first formula requires W * K bits,
968 // but this formula less than W + K bits. Also, the first formula requires
969 // a division step, whereas this formula only requires multiplies and shifts.
970 //
971 // It doesn't matter whether the subtraction step is done in the calculation
972 // width or the input iteration count's width; if the subtraction overflows,
973 // the result must be zero anyway. We prefer here to do it in the width of
974 // the induction variable because it helps a lot for certain cases; CodeGen
975 // isn't smart enough to ignore the overflow, which leads to much less
976 // efficient code if the width of the subtraction is wider than the native
977 // register width.
978 //
979 // (It's possible to not widen at all by pulling out factors of 2 before
980 // the multiplication; for example, K=2 can be calculated as
981 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
982 // extra arithmetic, so it's not an obvious win, and it gets
983 // much more complicated for K > 3.)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000984
Eli Friedman61f67622008-08-04 23:49:06 +0000985 // Protection from insane SCEVs; this bound is conservative,
986 // but it probably doesn't matter.
987 if (K > 1000)
Dan Gohman31efa302009-04-18 17:58:19 +0000988 return SE.getCouldNotCompute();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000989
Dan Gohmanb397e1a2009-04-21 01:07:12 +0000990 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000991
Eli Friedman61f67622008-08-04 23:49:06 +0000992 // Calculate K! / 2^T and T; we divide out the factors of two before
993 // multiplying for calculating K! / 2^T to avoid overflow.
994 // Other overflow doesn't matter because we only care about the bottom
995 // W bits of the result.
996 APInt OddFactorial(W, 1);
997 unsigned T = 1;
998 for (unsigned i = 3; i <= K; ++i) {
999 APInt Mult(W, i);
1000 unsigned TwoFactors = Mult.countTrailingZeros();
1001 T += TwoFactors;
1002 Mult = Mult.lshr(TwoFactors);
1003 OddFactorial *= Mult;
Chris Lattnerd934c702004-04-02 20:23:17 +00001004 }
Nick Lewyckyed169d52008-06-13 04:38:55 +00001005
Eli Friedman61f67622008-08-04 23:49:06 +00001006 // We need at least W + T bits for the multiplication step
Nick Lewycky21add8f2009-01-25 08:16:27 +00001007 unsigned CalculationBits = W + T;
Eli Friedman61f67622008-08-04 23:49:06 +00001008
Dan Gohman8b0a4192010-03-01 17:49:51 +00001009 // Calculate 2^T, at width T+W.
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00001010 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
Eli Friedman61f67622008-08-04 23:49:06 +00001011
1012 // Calculate the multiplicative inverse of K! / 2^T;
1013 // this multiplication factor will perform the exact division by
1014 // K! / 2^T.
1015 APInt Mod = APInt::getSignedMinValue(W+1);
1016 APInt MultiplyFactor = OddFactorial.zext(W+1);
1017 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1018 MultiplyFactor = MultiplyFactor.trunc(W);
1019
1020 // Calculate the product, at width T+W
Chris Lattner229907c2011-07-18 04:54:35 +00001021 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001022 CalculationBits);
Dan Gohmanaf752342009-07-07 17:06:11 +00001023 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman61f67622008-08-04 23:49:06 +00001024 for (unsigned i = 1; i != K; ++i) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00001025 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedman61f67622008-08-04 23:49:06 +00001026 Dividend = SE.getMulExpr(Dividend,
1027 SE.getTruncateOrZeroExtend(S, CalculationTy));
1028 }
1029
1030 // Divide by 2^T
Dan Gohmanaf752342009-07-07 17:06:11 +00001031 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman61f67622008-08-04 23:49:06 +00001032
1033 // Truncate the result, and divide by K! / 2^T.
1034
1035 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1036 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattnerd934c702004-04-02 20:23:17 +00001037}
1038
Sanjoy Dasf8570812016-05-29 00:38:22 +00001039/// Return the value of this chain of recurrences at the specified iteration
1040/// number. We can evaluate this recurrence by multiplying each element in the
1041/// chain by the binomial coefficient corresponding to it. In other words, we
1042/// can evaluate {A,+,B,+,C,+,D} as:
Chris Lattnerd934c702004-04-02 20:23:17 +00001043///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001044/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattnerd934c702004-04-02 20:23:17 +00001045///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001046/// where BC(It, k) stands for binomial coefficient.
Chris Lattnerd934c702004-04-02 20:23:17 +00001047///
Dan Gohmanaf752342009-07-07 17:06:11 +00001048const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman32291b12009-07-21 00:38:55 +00001049 ScalarEvolution &SE) const {
Dan Gohmanaf752342009-07-07 17:06:11 +00001050 const SCEV *Result = getStart();
Chris Lattnerd934c702004-04-02 20:23:17 +00001051 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001052 // The computation is correct in the face of overflow provided that the
1053 // multiplication is performed _after_ the evaluation of the binomial
1054 // coefficient.
Dan Gohmanaf752342009-07-07 17:06:11 +00001055 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewycky707663e2008-10-13 03:58:02 +00001056 if (isa<SCEVCouldNotCompute>(Coeff))
1057 return Coeff;
1058
1059 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattnerd934c702004-04-02 20:23:17 +00001060 }
1061 return Result;
1062}
1063
Chris Lattnerd934c702004-04-02 20:23:17 +00001064//===----------------------------------------------------------------------===//
1065// SCEV Expression folder implementations
1066//===----------------------------------------------------------------------===//
1067
Dan Gohmanaf752342009-07-07 17:06:11 +00001068const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001069 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001070 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001071 "This is not a truncating conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001072 assert(isSCEVable(Ty) &&
1073 "This is not a conversion to a SCEVable type!");
1074 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001075
Dan Gohman3a302cb2009-07-13 20:50:19 +00001076 FoldingSetNodeID ID;
1077 ID.AddInteger(scTruncate);
1078 ID.AddPointer(Op);
1079 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001080 void *IP = nullptr;
Dan Gohman3a302cb2009-07-13 20:50:19 +00001081 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1082
Dan Gohman3423e722009-06-30 20:13:32 +00001083 // Fold if the operand is constant.
Dan Gohmana30370b2009-05-04 22:02:23 +00001084 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman8d7576e2009-06-24 00:38:39 +00001085 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001086 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001087
Dan Gohman79af8542009-04-22 16:20:48 +00001088 // trunc(trunc(x)) --> trunc(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001089 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001090 return getTruncateExpr(ST->getOperand(), Ty);
1091
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001092 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001093 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001094 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1095
1096 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001097 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001098 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1099
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001100 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
Nick Lewycky2ce28322015-03-20 02:52:23 +00001101 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001102 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1103 SmallVector<const SCEV *, 4> Operands;
1104 bool hasTrunc = false;
1105 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1106 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001107 if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1108 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001109 Operands.push_back(S);
1110 }
1111 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001112 return getAddExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001113 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001114 }
1115
Nick Lewycky5c901f32011-01-19 18:56:00 +00001116 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
Nick Lewyckybe8af482015-03-20 02:25:00 +00001117 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001118 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1119 SmallVector<const SCEV *, 4> Operands;
1120 bool hasTrunc = false;
1121 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1122 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001123 if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1124 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5c901f32011-01-19 18:56:00 +00001125 Operands.push_back(S);
1126 }
1127 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001128 return getMulExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001129 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001130 }
1131
Dan Gohman5a728c92009-06-18 16:24:47 +00001132 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmana30370b2009-05-04 22:02:23 +00001133 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001134 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00001135 for (const SCEV *Op : AddRec->operands())
1136 Operands.push_back(getTruncateExpr(Op, Ty));
Andrew Trick8b55b732011-03-14 16:50:06 +00001137 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00001138 }
1139
Dan Gohman89dd42a2010-06-25 18:47:08 +00001140 // The cast wasn't folded; create an explicit cast node. We can reuse
1141 // the existing insert position since if we get here, we won't have
1142 // made any changes which would invalidate it.
Dan Gohman01c65a22010-03-18 18:49:47 +00001143 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1144 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001145 UniqueSCEVs.InsertNode(S, IP);
1146 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001147}
1148
Sanjoy Das4153f472015-02-18 01:47:07 +00001149// Get the limit of a recurrence such that incrementing by Step cannot cause
1150// signed overflow as long as the value of the recurrence within the
1151// loop does not exceed this limit before incrementing.
1152static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1153 ICmpInst::Predicate *Pred,
1154 ScalarEvolution *SE) {
1155 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1156 if (SE->isKnownPositive(Step)) {
1157 *Pred = ICmpInst::ICMP_SLT;
1158 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1159 SE->getSignedRange(Step).getSignedMax());
1160 }
1161 if (SE->isKnownNegative(Step)) {
1162 *Pred = ICmpInst::ICMP_SGT;
1163 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1164 SE->getSignedRange(Step).getSignedMin());
1165 }
1166 return nullptr;
1167}
1168
1169// Get the limit of a recurrence such that incrementing by Step cannot cause
1170// unsigned overflow as long as the value of the recurrence within the loop does
1171// not exceed this limit before incrementing.
1172static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1173 ICmpInst::Predicate *Pred,
1174 ScalarEvolution *SE) {
1175 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1176 *Pred = ICmpInst::ICMP_ULT;
1177
1178 return SE->getConstant(APInt::getMinValue(BitWidth) -
1179 SE->getUnsignedRange(Step).getUnsignedMax());
1180}
1181
1182namespace {
1183
1184struct ExtendOpTraitsBase {
1185 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *);
1186};
1187
1188// Used to make code generic over signed and unsigned overflow.
1189template <typename ExtendOp> struct ExtendOpTraits {
1190 // Members present:
1191 //
1192 // static const SCEV::NoWrapFlags WrapType;
1193 //
1194 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1195 //
1196 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1197 // ICmpInst::Predicate *Pred,
1198 // ScalarEvolution *SE);
1199};
1200
1201template <>
1202struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1203 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1204
1205 static const GetExtendExprTy GetExtendExpr;
1206
1207 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1208 ICmpInst::Predicate *Pred,
1209 ScalarEvolution *SE) {
1210 return getSignedOverflowLimitForStep(Step, Pred, SE);
1211 }
1212};
1213
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001214const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001215 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1216
1217template <>
1218struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1219 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1220
1221 static const GetExtendExprTy GetExtendExpr;
1222
1223 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1224 ICmpInst::Predicate *Pred,
1225 ScalarEvolution *SE) {
1226 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1227 }
1228};
1229
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001230const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001231 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001232}
Sanjoy Das4153f472015-02-18 01:47:07 +00001233
1234// The recurrence AR has been shown to have no signed/unsigned wrap or something
1235// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1236// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1237// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1238// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1239// expression "Step + sext/zext(PreIncAR)" is congruent with
1240// "sext/zext(PostIncAR)"
1241template <typename ExtendOpTy>
1242static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1243 ScalarEvolution *SE) {
1244 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1245 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1246
1247 const Loop *L = AR->getLoop();
1248 const SCEV *Start = AR->getStart();
1249 const SCEV *Step = AR->getStepRecurrence(*SE);
1250
1251 // Check for a simple looking step prior to loop entry.
1252 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1253 if (!SA)
1254 return nullptr;
1255
1256 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1257 // subtraction is expensive. For this purpose, perform a quick and dirty
1258 // difference, by checking for Step in the operand list.
1259 SmallVector<const SCEV *, 4> DiffOps;
1260 for (const SCEV *Op : SA->operands())
1261 if (Op != Step)
1262 DiffOps.push_back(Op);
1263
1264 if (DiffOps.size() == SA->getNumOperands())
1265 return nullptr;
1266
1267 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1268 // `Step`:
1269
1270 // 1. NSW/NUW flags on the step increment.
Sanjoy Das0714e3e2015-10-23 06:33:47 +00001271 auto PreStartFlags =
1272 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1273 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
Sanjoy Das4153f472015-02-18 01:47:07 +00001274 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1275 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1276
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001277 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1278 // "S+X does not sign/unsign-overflow".
Sanjoy Das4153f472015-02-18 01:47:07 +00001279 //
1280
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001281 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1282 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1283 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
Sanjoy Das4153f472015-02-18 01:47:07 +00001284 return PreStart;
1285
1286 // 2. Direct overflow check on the step operation's expression.
1287 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1288 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1289 const SCEV *OperandExtendedStart =
1290 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1291 (SE->*GetExtendExpr)(Step, WideTy));
1292 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1293 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1294 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1295 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1296 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1297 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1298 }
1299 return PreStart;
1300 }
1301
1302 // 3. Loop precondition.
1303 ICmpInst::Predicate Pred;
1304 const SCEV *OverflowLimit =
1305 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1306
1307 if (OverflowLimit &&
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001308 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
Sanjoy Das4153f472015-02-18 01:47:07 +00001309 return PreStart;
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001310
Sanjoy Das4153f472015-02-18 01:47:07 +00001311 return nullptr;
1312}
1313
1314// Get the normalized zero or sign extended expression for this AddRec's Start.
1315template <typename ExtendOpTy>
1316static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1317 ScalarEvolution *SE) {
1318 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1319
1320 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1321 if (!PreStart)
1322 return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1323
1324 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1325 (SE->*GetExtendExpr)(PreStart, Ty));
1326}
1327
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001328// Try to prove away overflow by looking at "nearby" add recurrences. A
1329// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1330// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1331//
1332// Formally:
1333//
1334// {S,+,X} == {S-T,+,X} + T
1335// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1336//
1337// If ({S-T,+,X} + T) does not overflow ... (1)
1338//
1339// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1340//
1341// If {S-T,+,X} does not overflow ... (2)
1342//
1343// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1344// == {Ext(S-T)+Ext(T),+,Ext(X)}
1345//
1346// If (S-T)+T does not overflow ... (3)
1347//
1348// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1349// == {Ext(S),+,Ext(X)} == LHS
1350//
1351// Thus, if (1), (2) and (3) are true for some T, then
1352// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1353//
1354// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1355// does not overflow" restricted to the 0th iteration. Therefore we only need
1356// to check for (1) and (2).
1357//
1358// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1359// is `Delta` (defined below).
1360//
1361template <typename ExtendOpTy>
1362bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1363 const SCEV *Step,
1364 const Loop *L) {
1365 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1366
1367 // We restrict `Start` to a constant to prevent SCEV from spending too much
1368 // time here. It is correct (but more expensive) to continue with a
1369 // non-constant `Start` and do a general SCEV subtraction to compute
1370 // `PreStart` below.
1371 //
1372 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1373 if (!StartC)
1374 return false;
1375
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001376 APInt StartAI = StartC->getAPInt();
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001377
1378 for (unsigned Delta : {-2, -1, 1, 2}) {
1379 const SCEV *PreStart = getConstant(StartAI - Delta);
1380
Sanjoy Das42801102015-10-23 06:57:21 +00001381 FoldingSetNodeID ID;
1382 ID.AddInteger(scAddRecExpr);
1383 ID.AddPointer(PreStart);
1384 ID.AddPointer(Step);
1385 ID.AddPointer(L);
1386 void *IP = nullptr;
1387 const auto *PreAR =
1388 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1389
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001390 // Give up if we don't already have the add recurrence we need because
1391 // actually constructing an add recurrence is relatively expensive.
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001392 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1393 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1394 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1395 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1396 DeltaS, &Pred, this);
1397 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1398 return true;
1399 }
1400 }
1401
1402 return false;
1403}
1404
Dan Gohmanaf752342009-07-07 17:06:11 +00001405const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001406 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001407 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001408 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001409 assert(isSCEVable(Ty) &&
1410 "This is not a conversion to a SCEVable type!");
1411 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001412
Dan Gohman3423e722009-06-30 20:13:32 +00001413 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001414 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1415 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001416 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001417
Dan Gohman79af8542009-04-22 16:20:48 +00001418 // zext(zext(x)) --> zext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001419 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001420 return getZeroExtendExpr(SZ->getOperand(), Ty);
1421
Dan Gohman74a0ba12009-07-13 20:55:53 +00001422 // Before doing any expensive analysis, check to see if we've already
1423 // computed a SCEV for this Op and Ty.
1424 FoldingSetNodeID ID;
1425 ID.AddInteger(scZeroExtend);
1426 ID.AddPointer(Op);
1427 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001428 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001429 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1430
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001431 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1432 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1433 // It's possible the bits taken off by the truncate were all zero bits. If
1434 // so, we should be able to simplify this further.
1435 const SCEV *X = ST->getOperand();
1436 ConstantRange CR = getUnsignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001437 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1438 unsigned NewBits = getTypeSizeInBits(Ty);
1439 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001440 CR.zextOrTrunc(NewBits)))
1441 return getTruncateOrZeroExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001442 }
1443
Dan Gohman76466372009-04-27 20:16:15 +00001444 // If the input value is a chrec scev, and we can prove that the value
Chris Lattnerd934c702004-04-02 20:23:17 +00001445 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001446 // operands (often constants). This allows analysis of something like
Chris Lattnerd934c702004-04-02 20:23:17 +00001447 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001448 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001449 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001450 const SCEV *Start = AR->getStart();
1451 const SCEV *Step = AR->getStepRecurrence(*this);
1452 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1453 const Loop *L = AR->getLoop();
1454
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001455 if (!AR->hasNoUnsignedWrap()) {
1456 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1457 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1458 }
1459
Dan Gohman62ef6a72009-07-25 01:22:26 +00001460 // If we have special knowledge that this addrec won't overflow,
1461 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001462 if (AR->hasNoUnsignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001463 return getAddRecExpr(
1464 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1465 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman62ef6a72009-07-25 01:22:26 +00001466
Dan Gohman76466372009-04-27 20:16:15 +00001467 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1468 // Note that this serves two purposes: It filters out loops that are
1469 // simply not analyzable, and it covers the case where this code is
1470 // being called from within backedge-taken count analysis, such that
1471 // attempting to ask for the backedge-taken count would likely result
1472 // in infinite recursion. In the later case, the analysis code will
1473 // cope with a conservative value, and it will take care to purge
1474 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001475 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001476 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001477 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001478 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001479
1480 // Check whether the backedge-taken count can be losslessly casted to
1481 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001482 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001483 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001484 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001485 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1486 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001487 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001488 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001489 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001490 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1491 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1492 const SCEV *WideMaxBECount =
1493 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001494 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001495 getAddExpr(WideStart,
1496 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001497 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001498 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001499 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1500 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohman494dac32009-04-29 22:28:28 +00001501 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001502 return getAddRecExpr(
1503 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1504 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001505 }
Dan Gohman76466372009-04-27 20:16:15 +00001506 // Similar to above, only this time treat the step value as signed.
1507 // This covers loops that count down.
Dan Gohman4fc36682009-05-18 15:58:39 +00001508 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001509 getAddExpr(WideStart,
1510 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001511 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001512 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001513 // Cache knowledge of AR NW, which is propagated to this AddRec.
1514 // Negative step causes unsigned wrap, but it still can't self-wrap.
1515 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
Dan Gohman494dac32009-04-29 22:28:28 +00001516 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001517 return getAddRecExpr(
1518 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1519 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001520 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001521 }
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001522 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001523
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001524 // Normally, in the cases we can prove no-overflow via a
1525 // backedge guarding condition, we can also compute a backedge
1526 // taken count for the loop. The exceptions are assumptions and
1527 // guards present in the loop -- SCEV is not great at exploiting
1528 // these to compute max backedge taken counts, but can still use
1529 // these to prove lack of overflow. Use this fact to avoid
1530 // doing extra work that may not pay off.
1531 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1532 !AC.assumptions().empty()) {
1533 // If the backedge is guarded by a comparison with the pre-inc
1534 // value the addrec is safe. Also, if the entry is guarded by
1535 // a comparison with the start value and the backedge is
1536 // guarded by a comparison with the post-inc value, the addrec
1537 // is safe.
Dan Gohmane65c9172009-07-13 21:35:55 +00001538 if (isKnownPositive(Step)) {
1539 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1540 getUnsignedRange(Step).getUnsignedMax());
1541 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohmanb50349a2010-04-11 19:27:13 +00001542 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001543 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001544 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001545 // Cache knowledge of AR NUW, which is propagated to this
1546 // AddRec.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001547 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohmane65c9172009-07-13 21:35:55 +00001548 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001549 return getAddRecExpr(
1550 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1551 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001552 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001553 } else if (isKnownNegative(Step)) {
1554 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1555 getSignedRange(Step).getSignedMin());
Dan Gohman5f18c542010-05-04 01:11:15 +00001556 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1557 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001558 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001559 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001560 // Cache knowledge of AR NW, which is propagated to this
1561 // AddRec. Negative step causes unsigned wrap, but it
1562 // still can't self-wrap.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001563 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1564 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001565 return getAddRecExpr(
1566 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1567 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001568 }
Dan Gohman76466372009-04-27 20:16:15 +00001569 }
1570 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001571
1572 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1573 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1574 return getAddRecExpr(
1575 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1576 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1577 }
Dan Gohman76466372009-04-27 20:16:15 +00001578 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001579
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001580 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1581 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001582 if (SA->hasNoUnsignedWrap()) {
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001583 // If the addition does not unsign overflow then we can, by definition,
1584 // commute the zero extension with the addition operation.
1585 SmallVector<const SCEV *, 4> Ops;
1586 for (const auto *Op : SA->operands())
1587 Ops.push_back(getZeroExtendExpr(Op, Ty));
1588 return getAddExpr(Ops, SCEV::FlagNUW);
1589 }
1590 }
1591
Dan Gohman74a0ba12009-07-13 20:55:53 +00001592 // The cast wasn't folded; create an explicit cast node.
1593 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001594 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001595 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1596 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001597 UniqueSCEVs.InsertNode(S, IP);
1598 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001599}
1600
Dan Gohmanaf752342009-07-07 17:06:11 +00001601const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001602 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001603 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001604 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001605 assert(isSCEVable(Ty) &&
1606 "This is not a conversion to a SCEVable type!");
1607 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001608
Dan Gohman3423e722009-06-30 20:13:32 +00001609 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001610 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1611 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001612 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001613
Dan Gohman79af8542009-04-22 16:20:48 +00001614 // sext(sext(x)) --> sext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001615 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001616 return getSignExtendExpr(SS->getOperand(), Ty);
1617
Nick Lewyckye9ea75e2011-01-19 15:56:12 +00001618 // sext(zext(x)) --> zext(x)
1619 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1620 return getZeroExtendExpr(SZ->getOperand(), Ty);
1621
Dan Gohman74a0ba12009-07-13 20:55:53 +00001622 // Before doing any expensive analysis, check to see if we've already
1623 // computed a SCEV for this Op and Ty.
1624 FoldingSetNodeID ID;
1625 ID.AddInteger(scSignExtend);
1626 ID.AddPointer(Op);
1627 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001628 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001629 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1630
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001631 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1632 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1633 // It's possible the bits taken off by the truncate were all sign bits. If
1634 // so, we should be able to simplify this further.
1635 const SCEV *X = ST->getOperand();
1636 ConstantRange CR = getSignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001637 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1638 unsigned NewBits = getTypeSizeInBits(Ty);
1639 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001640 CR.sextOrTrunc(NewBits)))
1641 return getTruncateOrSignExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001642 }
1643
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001644 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001645 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001646 if (SA->getNumOperands() == 2) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001647 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1648 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001649 if (SMul && SC1) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001650 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001651 const APInt &C1 = SC1->getAPInt();
1652 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001653 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001654 C2.ugt(C1) && C2.isPowerOf2())
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001655 return getAddExpr(getSignExtendExpr(SC1, Ty),
1656 getSignExtendExpr(SMul, Ty));
1657 }
1658 }
1659 }
Sanjoy Dasa060e602015-10-22 19:57:25 +00001660
1661 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001662 if (SA->hasNoSignedWrap()) {
Sanjoy Dasa060e602015-10-22 19:57:25 +00001663 // If the addition does not sign overflow then we can, by definition,
1664 // commute the sign extension with the addition operation.
1665 SmallVector<const SCEV *, 4> Ops;
1666 for (const auto *Op : SA->operands())
1667 Ops.push_back(getSignExtendExpr(Op, Ty));
1668 return getAddExpr(Ops, SCEV::FlagNSW);
1669 }
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001670 }
Dan Gohman76466372009-04-27 20:16:15 +00001671 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001672 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001673 // operands (often constants). This allows analysis of something like
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001674 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001675 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001676 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001677 const SCEV *Start = AR->getStart();
1678 const SCEV *Step = AR->getStepRecurrence(*this);
1679 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1680 const Loop *L = AR->getLoop();
1681
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001682 if (!AR->hasNoSignedWrap()) {
1683 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1684 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1685 }
1686
Dan Gohman62ef6a72009-07-25 01:22:26 +00001687 // If we have special knowledge that this addrec won't overflow,
1688 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001689 if (AR->hasNoSignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001690 return getAddRecExpr(
1691 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1692 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
Dan Gohman62ef6a72009-07-25 01:22:26 +00001693
Dan Gohman76466372009-04-27 20:16:15 +00001694 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1695 // Note that this serves two purposes: It filters out loops that are
1696 // simply not analyzable, and it covers the case where this code is
1697 // being called from within backedge-taken count analysis, such that
1698 // attempting to ask for the backedge-taken count would likely result
1699 // in infinite recursion. In the later case, the analysis code will
1700 // cope with a conservative value, and it will take care to purge
1701 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001702 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001703 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001704 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001705 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001706
1707 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman494dac32009-04-29 22:28:28 +00001708 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001709 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001710 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001711 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001712 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1713 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001714 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001715 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001716 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001717 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1718 const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1719 const SCEV *WideMaxBECount =
1720 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001721 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001722 getAddExpr(WideStart,
1723 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001724 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001725 if (SAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001726 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1727 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman494dac32009-04-29 22:28:28 +00001728 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001729 return getAddRecExpr(
1730 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1731 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001732 }
Dan Gohman8c129d72009-07-16 17:34:36 +00001733 // Similar to above, only this time treat the step value as unsigned.
1734 // This covers loops that count up with an unsigned step.
Dan Gohman8c129d72009-07-16 17:34:36 +00001735 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001736 getAddExpr(WideStart,
1737 getMulExpr(WideMaxBECount,
Dan Gohman8c129d72009-07-16 17:34:36 +00001738 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001739 if (SAdd == OperandExtendedAdd) {
Sanjoy Dasbf5d8702015-02-09 18:34:55 +00001740 // If AR wraps around then
1741 //
1742 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1743 // => SAdd != OperandExtendedAdd
1744 //
1745 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1746 // (SAdd == OperandExtendedAdd => AR is NW)
1747
1748 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1749
Dan Gohman8c129d72009-07-16 17:34:36 +00001750 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001751 return getAddRecExpr(
1752 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1753 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001754 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001755 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001756 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001757
Sanjoy Das787c2462016-05-11 17:41:26 +00001758 // Normally, in the cases we can prove no-overflow via a
1759 // backedge guarding condition, we can also compute a backedge
1760 // taken count for the loop. The exceptions are assumptions and
1761 // guards present in the loop -- SCEV is not great at exploiting
1762 // these to compute max backedge taken counts, but can still use
1763 // these to prove lack of overflow. Use this fact to avoid
1764 // doing extra work that may not pay off.
1765
1766 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1767 !AC.assumptions().empty()) {
1768 // If the backedge is guarded by a comparison with the pre-inc
1769 // value the addrec is safe. Also, if the entry is guarded by
1770 // a comparison with the start value and the backedge is
1771 // guarded by a comparison with the post-inc value, the addrec
1772 // is safe.
Andrew Trick812276e2011-05-31 21:17:47 +00001773 ICmpInst::Predicate Pred;
Sanjoy Das4153f472015-02-18 01:47:07 +00001774 const SCEV *OverflowLimit =
1775 getSignedOverflowLimitForStep(Step, &Pred, this);
Andrew Trick812276e2011-05-31 21:17:47 +00001776 if (OverflowLimit &&
1777 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1778 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1779 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1780 OverflowLimit)))) {
1781 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1782 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Sanjoy Das4153f472015-02-18 01:47:07 +00001783 return getAddRecExpr(
1784 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1785 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman76466372009-04-27 20:16:15 +00001786 }
1787 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001788
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001789 // If Start and Step are constants, check if we can apply this
1790 // transformation:
1791 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001792 auto *SC1 = dyn_cast<SCEVConstant>(Start);
1793 auto *SC2 = dyn_cast<SCEVConstant>(Step);
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001794 if (SC1 && SC2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001795 const APInt &C1 = SC1->getAPInt();
1796 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001797 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1798 C2.isPowerOf2()) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001799 Start = getSignExtendExpr(Start, Ty);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001800 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1801 AR->getNoWrapFlags());
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001802 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1803 }
1804 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001805
1806 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1807 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1808 return getAddRecExpr(
1809 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1810 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1811 }
Dan Gohman76466372009-04-27 20:16:15 +00001812 }
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001813
Sanjoy Das11ef6062016-03-03 18:31:23 +00001814 // If the input value is provably positive and we could not simplify
1815 // away the sext build a zext instead.
1816 if (isKnownNonNegative(Op))
1817 return getZeroExtendExpr(Op, Ty);
1818
Dan Gohman74a0ba12009-07-13 20:55:53 +00001819 // The cast wasn't folded; create an explicit cast node.
1820 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001821 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001822 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1823 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001824 UniqueSCEVs.InsertNode(S, IP);
1825 return S;
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001826}
1827
Dan Gohman8db2edc2009-06-13 15:56:47 +00001828/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1829/// unspecified bits out to the given type.
1830///
Dan Gohmanaf752342009-07-07 17:06:11 +00001831const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001832 Type *Ty) {
Dan Gohman8db2edc2009-06-13 15:56:47 +00001833 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1834 "This is not an extending conversion!");
1835 assert(isSCEVable(Ty) &&
1836 "This is not a conversion to a SCEVable type!");
1837 Ty = getEffectiveSCEVType(Ty);
1838
1839 // Sign-extend negative constants.
1840 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001841 if (SC->getAPInt().isNegative())
Dan Gohman8db2edc2009-06-13 15:56:47 +00001842 return getSignExtendExpr(Op, Ty);
1843
1844 // Peel off a truncate cast.
1845 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001846 const SCEV *NewOp = T->getOperand();
Dan Gohman8db2edc2009-06-13 15:56:47 +00001847 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1848 return getAnyExtendExpr(NewOp, Ty);
1849 return getTruncateOrNoop(NewOp, Ty);
1850 }
1851
1852 // Next try a zext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001853 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001854 if (!isa<SCEVZeroExtendExpr>(ZExt))
1855 return ZExt;
1856
1857 // Next try a sext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001858 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001859 if (!isa<SCEVSignExtendExpr>(SExt))
1860 return SExt;
1861
Dan Gohman51ad99d2010-01-21 02:09:26 +00001862 // Force the cast to be folded into the operands of an addrec.
1863 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1864 SmallVector<const SCEV *, 4> Ops;
Tobias Grosser924221c2014-05-07 06:07:47 +00001865 for (const SCEV *Op : AR->operands())
1866 Ops.push_back(getAnyExtendExpr(Op, Ty));
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001867 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001868 }
1869
Dan Gohman8db2edc2009-06-13 15:56:47 +00001870 // If the expression is obviously signed, use the sext cast value.
1871 if (isa<SCEVSMaxExpr>(Op))
1872 return SExt;
1873
1874 // Absent any other information, use the zext cast value.
1875 return ZExt;
1876}
1877
Sanjoy Dasf8570812016-05-29 00:38:22 +00001878/// Process the given Ops list, which is a list of operands to be added under
1879/// the given scale, update the given map. This is a helper function for
1880/// getAddRecExpr. As an example of what it does, given a sequence of operands
1881/// that would form an add expression like this:
Dan Gohman038d02e2009-06-14 22:58:51 +00001882///
Tobias Grosserba49e422014-03-05 10:37:17 +00001883/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
Dan Gohman038d02e2009-06-14 22:58:51 +00001884///
1885/// where A and B are constants, update the map with these values:
1886///
1887/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1888///
1889/// and add 13 + A*B*29 to AccumulatedConstant.
1890/// This will allow getAddRecExpr to produce this:
1891///
1892/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1893///
1894/// This form often exposes folding opportunities that are hidden in
1895/// the original operand list.
1896///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001897/// Return true iff it appears that any interesting folding opportunities
Dan Gohman038d02e2009-06-14 22:58:51 +00001898/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1899/// the common case where no interesting opportunities are present, and
1900/// is also used as a check to avoid infinite recursion.
1901///
1902static bool
Dan Gohmanaf752342009-07-07 17:06:11 +00001903CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
Craig Topper2cd5ff82013-07-11 16:22:38 +00001904 SmallVectorImpl<const SCEV *> &NewOps,
Dan Gohman038d02e2009-06-14 22:58:51 +00001905 APInt &AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001906 const SCEV *const *Ops, size_t NumOperands,
Dan Gohman038d02e2009-06-14 22:58:51 +00001907 const APInt &Scale,
1908 ScalarEvolution &SE) {
1909 bool Interesting = false;
1910
Dan Gohman45073042010-06-18 19:12:32 +00001911 // Iterate over the add operands. They are sorted, with constants first.
1912 unsigned i = 0;
1913 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1914 ++i;
1915 // Pull a buried constant out to the outside.
1916 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1917 Interesting = true;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001918 AccumulatedConstant += Scale * C->getAPInt();
Dan Gohman45073042010-06-18 19:12:32 +00001919 }
1920
1921 // Next comes everything else. We're especially interested in multiplies
1922 // here, but they're in the middle, so just visit the rest with one loop.
1923 for (; i != NumOperands; ++i) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001924 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1925 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1926 APInt NewScale =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001927 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
Dan Gohman038d02e2009-06-14 22:58:51 +00001928 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1929 // A multiplication of a constant with another add; recurse.
Dan Gohman00524492010-03-18 01:17:13 +00001930 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohman038d02e2009-06-14 22:58:51 +00001931 Interesting |=
1932 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001933 Add->op_begin(), Add->getNumOperands(),
Dan Gohman038d02e2009-06-14 22:58:51 +00001934 NewScale, SE);
1935 } else {
1936 // A multiplication of a constant with some other value. Update
1937 // the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00001938 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1939 const SCEV *Key = SE.getMulExpr(MulOps);
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00001940 auto Pair = M.insert({Key, NewScale});
Dan Gohman038d02e2009-06-14 22:58:51 +00001941 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001942 NewOps.push_back(Pair.first->first);
1943 } else {
1944 Pair.first->second += NewScale;
1945 // The map already had an entry for this value, which may indicate
1946 // a folding opportunity.
1947 Interesting = true;
1948 }
1949 }
Dan Gohman038d02e2009-06-14 22:58:51 +00001950 } else {
1951 // An ordinary operand. Update the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00001952 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00001953 M.insert({Ops[i], Scale});
Dan Gohman038d02e2009-06-14 22:58:51 +00001954 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001955 NewOps.push_back(Pair.first->first);
1956 } else {
1957 Pair.first->second += Scale;
1958 // The map already had an entry for this value, which may indicate
1959 // a folding opportunity.
1960 Interesting = true;
1961 }
1962 }
1963 }
1964
1965 return Interesting;
1966}
1967
Sanjoy Das81401d42015-01-10 23:41:24 +00001968// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
1969// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
1970// can't-overflow flags for the operation if possible.
1971static SCEV::NoWrapFlags
1972StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
1973 const SmallVectorImpl<const SCEV *> &Ops,
Sanjoy Das8f274152015-10-22 19:57:19 +00001974 SCEV::NoWrapFlags Flags) {
Sanjoy Das81401d42015-01-10 23:41:24 +00001975 using namespace std::placeholders;
Sanjoy Das8f274152015-10-22 19:57:19 +00001976 typedef OverflowingBinaryOperator OBO;
Sanjoy Das81401d42015-01-10 23:41:24 +00001977
1978 bool CanAnalyze =
1979 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
1980 (void)CanAnalyze;
1981 assert(CanAnalyze && "don't call from other places!");
1982
1983 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1984 SCEV::NoWrapFlags SignOrUnsignWrap =
Sanjoy Das8f274152015-10-22 19:57:19 +00001985 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00001986
1987 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Sanjoy Das9b0015f2015-11-29 23:40:57 +00001988 auto IsKnownNonNegative = [&](const SCEV *S) {
1989 return SE->isKnownNonNegative(S);
1990 };
Sanjoy Das81401d42015-01-10 23:41:24 +00001991
Sanjoy Das3b827c72015-11-29 23:40:53 +00001992 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
Sanjoy Das8f274152015-10-22 19:57:19 +00001993 Flags =
1994 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00001995
Sanjoy Das8f274152015-10-22 19:57:19 +00001996 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
1997
1998 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
1999 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2000
2001 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2002 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2003
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002004 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
Sanjoy Das8f274152015-10-22 19:57:19 +00002005 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002006 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2007 Instruction::Add, C, OBO::NoSignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002008 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2009 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2010 }
2011 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002012 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2013 Instruction::Add, C, OBO::NoUnsignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002014 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2015 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2016 }
2017 }
2018
2019 return Flags;
Sanjoy Das81401d42015-01-10 23:41:24 +00002020}
2021
Sanjoy Dasf8570812016-05-29 00:38:22 +00002022/// Get a canonical add expression, or something simpler if possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002023const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002024 SCEV::NoWrapFlags Flags) {
2025 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2026 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002027 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +00002028 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002029#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002030 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002031 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohman9136d9f2010-06-18 19:09:27 +00002032 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002033 "SCEVAddExpr operand types don't match!");
2034#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002035
2036 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002037 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002038
Sanjoy Das64895612015-10-09 02:44:45 +00002039 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2040
Chris Lattnerd934c702004-04-02 20:23:17 +00002041 // If there are any constants, fold them together.
2042 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002043 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002044 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +00002045 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002046 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002047 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002048 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
Dan Gohman011cf682009-06-14 22:53:57 +00002049 if (Ops.size() == 2) return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002050 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002051 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002052 }
2053
2054 // If we are left with a constant zero being added, strip it off.
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002055 if (LHSC->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002056 Ops.erase(Ops.begin());
2057 --Idx;
2058 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002059
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002060 if (Ops.size() == 1) return Ops[0];
2061 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002062
Dan Gohman15871f22010-08-27 21:39:59 +00002063 // Okay, check to see if the same value occurs in the operand list more than
2064 // once. If so, merge them together into an multiply expression. Since we
2065 // sorted the list, these values are required to be adjacent.
Chris Lattner229907c2011-07-18 04:54:35 +00002066 Type *Ty = Ops[0]->getType();
Dan Gohmane67b2872010-08-12 14:46:54 +00002067 bool FoundMatch = false;
Dan Gohman15871f22010-08-27 21:39:59 +00002068 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattnerd934c702004-04-02 20:23:17 +00002069 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman15871f22010-08-27 21:39:59 +00002070 // Scan ahead to count how many equal operands there are.
2071 unsigned Count = 2;
2072 while (i+Count != e && Ops[i+Count] == Ops[i])
2073 ++Count;
2074 // Merge the values into a multiply.
2075 const SCEV *Scale = getConstant(Ty, Count);
2076 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2077 if (Ops.size() == Count)
Chris Lattnerd934c702004-04-02 20:23:17 +00002078 return Mul;
Dan Gohmane67b2872010-08-12 14:46:54 +00002079 Ops[i] = Mul;
Dan Gohman15871f22010-08-27 21:39:59 +00002080 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohmanfe22f1d2010-08-28 00:39:27 +00002081 --i; e -= Count - 1;
Dan Gohmane67b2872010-08-12 14:46:54 +00002082 FoundMatch = true;
Chris Lattnerd934c702004-04-02 20:23:17 +00002083 }
Dan Gohmane67b2872010-08-12 14:46:54 +00002084 if (FoundMatch)
Andrew Trick8b55b732011-03-14 16:50:06 +00002085 return getAddExpr(Ops, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002086
Dan Gohman2e55cc52009-05-08 21:03:19 +00002087 // Check for truncates. If all the operands are truncated from the same
2088 // type, see if factoring out the truncate would permit the result to be
2089 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2090 // if the contents of the resulting outer trunc fold to something simple.
2091 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2092 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
Chris Lattner229907c2011-07-18 04:54:35 +00002093 Type *DstType = Trunc->getType();
2094 Type *SrcType = Trunc->getOperand()->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00002095 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002096 bool Ok = true;
2097 // Check all the operands to see if they can be represented in the
2098 // source type of the truncate.
2099 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2100 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2101 if (T->getOperand()->getType() != SrcType) {
2102 Ok = false;
2103 break;
2104 }
2105 LargeOps.push_back(T->getOperand());
2106 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002107 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002108 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002109 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002110 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2111 if (const SCEVTruncateExpr *T =
2112 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2113 if (T->getOperand()->getType() != SrcType) {
2114 Ok = false;
2115 break;
2116 }
2117 LargeMulOps.push_back(T->getOperand());
Sanjoy Das63914592015-10-18 00:29:20 +00002118 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002119 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002120 } else {
2121 Ok = false;
2122 break;
2123 }
2124 }
2125 if (Ok)
2126 LargeOps.push_back(getMulExpr(LargeMulOps));
2127 } else {
2128 Ok = false;
2129 break;
2130 }
2131 }
2132 if (Ok) {
2133 // Evaluate the expression in the larger type.
Andrew Trick8b55b732011-03-14 16:50:06 +00002134 const SCEV *Fold = getAddExpr(LargeOps, Flags);
Dan Gohman2e55cc52009-05-08 21:03:19 +00002135 // If it folds to something simple, use it. Otherwise, don't.
2136 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2137 return getTruncateExpr(Fold, DstType);
2138 }
2139 }
2140
2141 // Skip past any other cast SCEVs.
Dan Gohmaneed125f2007-06-18 19:30:09 +00002142 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2143 ++Idx;
2144
2145 // If there are add operands they would be next.
Chris Lattnerd934c702004-04-02 20:23:17 +00002146 if (Idx < Ops.size()) {
2147 bool DeletedAdd = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002148 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002149 // If we have an add, expand the add operands onto the end of the operands
2150 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002151 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002152 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002153 DeletedAdd = true;
2154 }
2155
2156 // If we deleted at least one add, we added operands to the end of the list,
2157 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002158 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002159 if (DeletedAdd)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002160 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002161 }
2162
2163 // Skip over the add expression until we get to a multiply.
2164 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2165 ++Idx;
2166
Dan Gohman038d02e2009-06-14 22:58:51 +00002167 // Check to see if there are any folding opportunities present with
2168 // operands multiplied by constant values.
2169 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2170 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohmanaf752342009-07-07 17:06:11 +00002171 DenseMap<const SCEV *, APInt> M;
2172 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman038d02e2009-06-14 22:58:51 +00002173 APInt AccumulatedConstant(BitWidth, 0);
2174 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002175 Ops.data(), Ops.size(),
2176 APInt(BitWidth, 1), *this)) {
Sanjoy Das7d752672015-12-08 04:32:54 +00002177 struct APIntCompare {
2178 bool operator()(const APInt &LHS, const APInt &RHS) const {
2179 return LHS.ult(RHS);
2180 }
2181 };
2182
Dan Gohman038d02e2009-06-14 22:58:51 +00002183 // Some interesting folding opportunity is present, so its worthwhile to
2184 // re-generate the operands list. Group the operands by constant scale,
2185 // to avoid multiplying by the same constant scale multiple times.
Dan Gohmanaf752342009-07-07 17:06:11 +00002186 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002187 for (const SCEV *NewOp : NewOps)
2188 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
Dan Gohman038d02e2009-06-14 22:58:51 +00002189 // Re-generate the operands list.
2190 Ops.clear();
2191 if (AccumulatedConstant != 0)
2192 Ops.push_back(getConstant(AccumulatedConstant));
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002193 for (auto &MulOp : MulOpLists)
2194 if (MulOp.first != 0)
2195 Ops.push_back(getMulExpr(getConstant(MulOp.first),
2196 getAddExpr(MulOp.second)));
Dan Gohman038d02e2009-06-14 22:58:51 +00002197 if (Ops.empty())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002198 return getZero(Ty);
Dan Gohman038d02e2009-06-14 22:58:51 +00002199 if (Ops.size() == 1)
2200 return Ops[0];
2201 return getAddExpr(Ops);
2202 }
2203 }
2204
Chris Lattnerd934c702004-04-02 20:23:17 +00002205 // If we are adding something to a multiply expression, make sure the
2206 // something is not already an operand of the multiply. If so, merge it into
2207 // the multiply.
2208 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002209 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002210 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman48f82222009-05-04 22:30:44 +00002211 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman157847f2010-08-12 14:52:55 +00002212 if (isa<SCEVConstant>(MulOpSCEV))
2213 continue;
Chris Lattnerd934c702004-04-02 20:23:17 +00002214 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman157847f2010-08-12 14:52:55 +00002215 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002216 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohmanaf752342009-07-07 17:06:11 +00002217 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002218 if (Mul->getNumOperands() != 2) {
2219 // If the multiply has more than two operands, we must get the
2220 // Y*Z term.
Dan Gohman797a1db2010-08-16 16:57:24 +00002221 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2222 Mul->op_begin()+MulOp);
2223 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002224 InnerMul = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002225 }
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002226 const SCEV *One = getOne(Ty);
Dan Gohmancf32f2b2010-08-13 20:17:14 +00002227 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman157847f2010-08-12 14:52:55 +00002228 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattnerd934c702004-04-02 20:23:17 +00002229 if (Ops.size() == 2) return OuterMul;
2230 if (AddOp < Idx) {
2231 Ops.erase(Ops.begin()+AddOp);
2232 Ops.erase(Ops.begin()+Idx-1);
2233 } else {
2234 Ops.erase(Ops.begin()+Idx);
2235 Ops.erase(Ops.begin()+AddOp-1);
2236 }
2237 Ops.push_back(OuterMul);
Dan Gohmana37eaf22007-10-22 18:31:58 +00002238 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002239 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002240
Chris Lattnerd934c702004-04-02 20:23:17 +00002241 // Check this multiply against other multiplies being added together.
2242 for (unsigned OtherMulIdx = Idx+1;
2243 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2244 ++OtherMulIdx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002245 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002246 // If MulOp occurs in OtherMul, we can fold the two multiplies
2247 // together.
2248 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2249 OMulOp != e; ++OMulOp)
2250 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2251 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohmanaf752342009-07-07 17:06:11 +00002252 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002253 if (Mul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002254 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002255 Mul->op_begin()+MulOp);
2256 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002257 InnerMul1 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002258 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002259 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002260 if (OtherMul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002261 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002262 OtherMul->op_begin()+OMulOp);
2263 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002264 InnerMul2 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002265 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002266 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2267 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattnerd934c702004-04-02 20:23:17 +00002268 if (Ops.size() == 2) return OuterMul;
Dan Gohmanaabfc522010-08-31 22:50:31 +00002269 Ops.erase(Ops.begin()+Idx);
2270 Ops.erase(Ops.begin()+OtherMulIdx-1);
2271 Ops.push_back(OuterMul);
2272 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002273 }
2274 }
2275 }
2276 }
2277
2278 // If there are any add recurrences in the operands list, see if any other
2279 // added values are loop invariant. If so, we can fold them into the
2280 // recurrence.
2281 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2282 ++Idx;
2283
2284 // Scan over all recurrences, trying to fold loop invariants into them.
2285 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2286 // Scan all of the other operands to this add and add them to the vector if
2287 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002288 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002289 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002290 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002291 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002292 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002293 LIOps.push_back(Ops[i]);
2294 Ops.erase(Ops.begin()+i);
2295 --i; --e;
2296 }
2297
2298 // If we found some loop invariants, fold them into the recurrence.
2299 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002300 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattnerd934c702004-04-02 20:23:17 +00002301 LIOps.push_back(AddRec->getStart());
2302
Dan Gohmanaf752342009-07-07 17:06:11 +00002303 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman7a2dab82009-12-18 03:57:04 +00002304 AddRec->op_end());
Oleg Ranevskyyeb4ecca2016-05-25 13:01:33 +00002305 // This follows from the fact that the no-wrap flags on the outer add
2306 // expression are applicable on the 0th iteration, when the add recurrence
2307 // will be equal to its start value.
2308 AddRecOps[0] = getAddExpr(LIOps, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002309
Dan Gohman16206132010-06-30 07:16:37 +00002310 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher23bf3ba2011-01-11 09:02:09 +00002311 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002312 // Always propagate NW.
2313 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick8b55b732011-03-14 16:50:06 +00002314 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman51f13052009-12-18 18:45:31 +00002315
Chris Lattnerd934c702004-04-02 20:23:17 +00002316 // If all of the other operands were loop invariant, we are done.
2317 if (Ops.size() == 1) return NewRec;
2318
Nick Lewyckydb66b822011-09-06 05:08:09 +00002319 // Otherwise, add the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002320 for (unsigned i = 0;; ++i)
2321 if (Ops[i] == AddRec) {
2322 Ops[i] = NewRec;
2323 break;
2324 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002325 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002326 }
2327
2328 // Okay, if there weren't any loop invariants to be folded, check to see if
2329 // there are multiple AddRec's with the same loop induction variable being
2330 // added together. If so, we can fold them.
2331 for (unsigned OtherIdx = Idx+1;
Dan Gohmanc866bf42010-08-27 20:45:56 +00002332 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2333 ++OtherIdx)
2334 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2335 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2336 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2337 AddRec->op_end());
2338 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2339 ++OtherIdx)
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002340 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman028c1812010-08-29 14:53:34 +00002341 if (OtherAddRec->getLoop() == AddRecLoop) {
2342 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2343 i != e; ++i) {
Dan Gohmanc866bf42010-08-27 20:45:56 +00002344 if (i >= AddRecOps.size()) {
Dan Gohman028c1812010-08-29 14:53:34 +00002345 AddRecOps.append(OtherAddRec->op_begin()+i,
2346 OtherAddRec->op_end());
Dan Gohmanc866bf42010-08-27 20:45:56 +00002347 break;
2348 }
Dan Gohman028c1812010-08-29 14:53:34 +00002349 AddRecOps[i] = getAddExpr(AddRecOps[i],
2350 OtherAddRec->getOperand(i));
Dan Gohmanc866bf42010-08-27 20:45:56 +00002351 }
2352 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattnerd934c702004-04-02 20:23:17 +00002353 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002354 // Step size has changed, so we cannot guarantee no self-wraparound.
2355 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Dan Gohmanc866bf42010-08-27 20:45:56 +00002356 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002357 }
2358
2359 // Otherwise couldn't fold anything into this recurrence. Move onto the
2360 // next one.
2361 }
2362
2363 // Okay, it looks like we really DO need an add expr. Check to see if we
2364 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002365 FoldingSetNodeID ID;
2366 ID.AddInteger(scAddExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002367 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2368 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002369 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002370 SCEVAddExpr *S =
2371 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2372 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002373 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2374 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002375 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2376 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002377 UniqueSCEVs.InsertNode(S, IP);
2378 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002379 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002380 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002381}
2382
Nick Lewycky287682e2011-10-04 06:51:26 +00002383static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2384 uint64_t k = i*j;
2385 if (j > 1 && k / j != i) Overflow = true;
2386 return k;
2387}
2388
2389/// Compute the result of "n choose k", the binomial coefficient. If an
2390/// intermediate computation overflows, Overflow will be set and the return will
Benjamin Kramerbde91762012-06-02 10:20:22 +00002391/// be garbage. Overflow is not cleared on absence of overflow.
Nick Lewycky287682e2011-10-04 06:51:26 +00002392static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2393 // We use the multiplicative formula:
2394 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2395 // At each iteration, we take the n-th term of the numeral and divide by the
2396 // (k-n)th term of the denominator. This division will always produce an
2397 // integral result, and helps reduce the chance of overflow in the
2398 // intermediate computations. However, we can still overflow even when the
2399 // final result would fit.
2400
2401 if (n == 0 || n == k) return 1;
2402 if (k > n) return 0;
2403
2404 if (k > n/2)
2405 k = n-k;
2406
2407 uint64_t r = 1;
2408 for (uint64_t i = 1; i <= k; ++i) {
2409 r = umul_ov(r, n-(i-1), Overflow);
2410 r /= i;
2411 }
2412 return r;
2413}
2414
Nick Lewycky05044c22014-12-06 00:45:50 +00002415/// Determine if any of the operands in this SCEV are a constant or if
2416/// any of the add or multiply expressions in this SCEV contain a constant.
2417static bool containsConstantSomewhere(const SCEV *StartExpr) {
2418 SmallVector<const SCEV *, 4> Ops;
2419 Ops.push_back(StartExpr);
2420 while (!Ops.empty()) {
2421 const SCEV *CurrentExpr = Ops.pop_back_val();
2422 if (isa<SCEVConstant>(*CurrentExpr))
2423 return true;
2424
2425 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2426 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002427 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
Nick Lewycky05044c22014-12-06 00:45:50 +00002428 }
2429 }
2430 return false;
2431}
2432
Sanjoy Dasf8570812016-05-29 00:38:22 +00002433/// Get a canonical multiply expression, or something simpler if possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002434const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002435 SCEV::NoWrapFlags Flags) {
2436 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2437 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002438 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohman51ad99d2010-01-21 02:09:26 +00002439 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002440#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002441 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002442 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002443 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002444 "SCEVMulExpr operand types don't match!");
2445#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002446
2447 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002448 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002449
Sanjoy Das64895612015-10-09 02:44:45 +00002450 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2451
Chris Lattnerd934c702004-04-02 20:23:17 +00002452 // If there are any constants, fold them together.
2453 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002454 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002455
2456 // C1*(C2+V) -> C1*C2 + C1*V
2457 if (Ops.size() == 2)
Nick Lewycky05044c22014-12-06 00:45:50 +00002458 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2459 // If any of Add's ops are Adds or Muls with a constant,
2460 // apply this transformation as well.
2461 if (Add->getNumOperands() == 2)
2462 if (containsConstantSomewhere(Add))
2463 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2464 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002465
Chris Lattnerd934c702004-04-02 20:23:17 +00002466 ++Idx;
Dan Gohmana30370b2009-05-04 22:02:23 +00002467 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002468 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002469 ConstantInt *Fold =
2470 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002471 Ops[0] = getConstant(Fold);
2472 Ops.erase(Ops.begin()+1); // Erase the folded element
2473 if (Ops.size() == 1) return Ops[0];
2474 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002475 }
2476
2477 // If we are left with a constant one being multiplied, strip it off.
2478 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2479 Ops.erase(Ops.begin());
2480 --Idx;
Reid Spencer2e54a152007-03-02 00:28:52 +00002481 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002482 // If we have a multiply of zero, it will always be zero.
2483 return Ops[0];
Dan Gohman51ad99d2010-01-21 02:09:26 +00002484 } else if (Ops[0]->isAllOnesValue()) {
2485 // If we have a mul by -1 of an add, try distributing the -1 among the
2486 // add operands.
Andrew Trick8b55b732011-03-14 16:50:06 +00002487 if (Ops.size() == 2) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002488 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2489 SmallVector<const SCEV *, 4> NewOps;
2490 bool AnyFolded = false;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002491 for (const SCEV *AddOp : Add->operands()) {
2492 const SCEV *Mul = getMulExpr(Ops[0], AddOp);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002493 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2494 NewOps.push_back(Mul);
2495 }
2496 if (AnyFolded)
2497 return getAddExpr(NewOps);
Sanjoy Das63914592015-10-18 00:29:20 +00002498 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
Andrew Tricke92dcce2011-03-14 17:38:54 +00002499 // Negation preserves a recurrence's no self-wrap property.
2500 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002501 for (const SCEV *AddRecOp : AddRec->operands())
2502 Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2503
Andrew Tricke92dcce2011-03-14 17:38:54 +00002504 return getAddRecExpr(Operands, AddRec->getLoop(),
2505 AddRec->getNoWrapFlags(SCEV::FlagNW));
2506 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002507 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002508 }
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002509
2510 if (Ops.size() == 1)
2511 return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00002512 }
2513
2514 // Skip over the add expression until we get to a multiply.
2515 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2516 ++Idx;
2517
Chris Lattnerd934c702004-04-02 20:23:17 +00002518 // If there are mul operands inline them all into this expression.
2519 if (Idx < Ops.size()) {
2520 bool DeletedMul = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002521 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002522 // If we have an mul, expand the mul operands onto the end of the operands
2523 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002524 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002525 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002526 DeletedMul = true;
2527 }
2528
2529 // If we deleted at least one mul, we added operands to the end of the list,
2530 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002531 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002532 if (DeletedMul)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002533 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002534 }
2535
2536 // If there are any add recurrences in the operands list, see if any other
2537 // added values are loop invariant. If so, we can fold them into the
2538 // recurrence.
2539 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2540 ++Idx;
2541
2542 // Scan over all recurrences, trying to fold loop invariants into them.
2543 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2544 // Scan all of the other operands to this mul and add them to the vector if
2545 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002546 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002547 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f2de012010-08-29 14:55:19 +00002548 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002549 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002550 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002551 LIOps.push_back(Ops[i]);
2552 Ops.erase(Ops.begin()+i);
2553 --i; --e;
2554 }
2555
2556 // If we found some loop invariants, fold them into the recurrence.
2557 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002558 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanaf752342009-07-07 17:06:11 +00002559 SmallVector<const SCEV *, 4> NewOps;
Chris Lattnerd934c702004-04-02 20:23:17 +00002560 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman8f5954f2010-06-17 23:34:09 +00002561 const SCEV *Scale = getMulExpr(LIOps);
2562 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2563 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002564
Dan Gohman16206132010-06-30 07:16:37 +00002565 // Build the new addrec. Propagate the NUW and NSW flags if both the
2566 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick8b55b732011-03-14 16:50:06 +00002567 //
2568 // No self-wrap cannot be guaranteed after changing the step size, but
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002569 // will be inferred if either NUW or NSW is true.
Andrew Trick8b55b732011-03-14 16:50:06 +00002570 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2571 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002572
2573 // If all of the other operands were loop invariant, we are done.
2574 if (Ops.size() == 1) return NewRec;
2575
Nick Lewyckydb66b822011-09-06 05:08:09 +00002576 // Otherwise, multiply the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002577 for (unsigned i = 0;; ++i)
2578 if (Ops[i] == AddRec) {
2579 Ops[i] = NewRec;
2580 break;
2581 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002582 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002583 }
2584
2585 // Okay, if there weren't any loop invariants to be folded, check to see if
2586 // there are multiple AddRec's with the same loop induction variable being
2587 // multiplied together. If so, we can fold them.
Nick Lewycky97756402014-09-01 05:17:15 +00002588
2589 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2590 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2591 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2592 // ]]],+,...up to x=2n}.
2593 // Note that the arguments to choose() are always integers with values
2594 // known at compile time, never SCEV objects.
2595 //
2596 // The implementation avoids pointless extra computations when the two
2597 // addrec's are of different length (mathematically, it's equivalent to
2598 // an infinite stream of zeros on the right).
2599 bool OpsModified = false;
Chris Lattnerd934c702004-04-02 20:23:17 +00002600 for (unsigned OtherIdx = Idx+1;
Nick Lewycky97756402014-09-01 05:17:15 +00002601 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002602 ++OtherIdx) {
Nick Lewycky97756402014-09-01 05:17:15 +00002603 const SCEVAddRecExpr *OtherAddRec =
2604 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2605 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
Andrew Trick946f76b2012-05-30 03:35:17 +00002606 continue;
2607
Nick Lewycky97756402014-09-01 05:17:15 +00002608 bool Overflow = false;
2609 Type *Ty = AddRec->getType();
2610 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2611 SmallVector<const SCEV*, 7> AddRecOps;
2612 for (int x = 0, xe = AddRec->getNumOperands() +
2613 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002614 const SCEV *Term = getZero(Ty);
Nick Lewycky97756402014-09-01 05:17:15 +00002615 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2616 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2617 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2618 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2619 z < ze && !Overflow; ++z) {
2620 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2621 uint64_t Coeff;
2622 if (LargerThan64Bits)
2623 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2624 else
2625 Coeff = Coeff1*Coeff2;
2626 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2627 const SCEV *Term1 = AddRec->getOperand(y-z);
2628 const SCEV *Term2 = OtherAddRec->getOperand(z);
2629 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
Andrew Trick946f76b2012-05-30 03:35:17 +00002630 }
Andrew Trick946f76b2012-05-30 03:35:17 +00002631 }
Nick Lewycky97756402014-09-01 05:17:15 +00002632 AddRecOps.push_back(Term);
Chris Lattnerd934c702004-04-02 20:23:17 +00002633 }
Nick Lewycky97756402014-09-01 05:17:15 +00002634 if (!Overflow) {
2635 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2636 SCEV::FlagAnyWrap);
2637 if (Ops.size() == 2) return NewAddRec;
2638 Ops[Idx] = NewAddRec;
2639 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2640 OpsModified = true;
2641 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2642 if (!AddRec)
2643 break;
2644 }
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002645 }
Nick Lewycky97756402014-09-01 05:17:15 +00002646 if (OpsModified)
2647 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002648
2649 // Otherwise couldn't fold anything into this recurrence. Move onto the
2650 // next one.
2651 }
2652
2653 // Okay, it looks like we really DO need an mul expr. Check to see if we
2654 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002655 FoldingSetNodeID ID;
2656 ID.AddInteger(scMulExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002657 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2658 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002659 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002660 SCEVMulExpr *S =
2661 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2662 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002663 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2664 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002665 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2666 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002667 UniqueSCEVs.InsertNode(S, IP);
2668 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002669 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002670 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002671}
2672
Sanjoy Dasf8570812016-05-29 00:38:22 +00002673/// Get a canonical unsigned division expression, or something simpler if
2674/// possible.
Dan Gohmanabd17092009-06-24 14:49:00 +00002675const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2676 const SCEV *RHS) {
Dan Gohmand33f36e2009-05-18 15:44:58 +00002677 assert(getEffectiveSCEVType(LHS->getType()) ==
2678 getEffectiveSCEVType(RHS->getType()) &&
2679 "SCEVUDivExpr operand types don't match!");
2680
Dan Gohmana30370b2009-05-04 22:02:23 +00002681 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002682 if (RHSC->getValue()->equalsInt(1))
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00002683 return LHS; // X udiv 1 --> x
Dan Gohmanacd700a2010-04-22 01:35:11 +00002684 // If the denominator is zero, the result of the udiv is undefined. Don't
2685 // try to analyze it, because the resolution chosen here may differ from
2686 // the resolution chosen in other parts of the compiler.
2687 if (!RHSC->getValue()->isZero()) {
2688 // Determine if the division can be folded into the operands of
2689 // its operands.
2690 // TODO: Generalize this to non-constants by using known-bits information.
Chris Lattner229907c2011-07-18 04:54:35 +00002691 Type *Ty = LHS->getType();
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002692 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
Dan Gohmandb764c62010-08-04 19:52:50 +00002693 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanacd700a2010-04-22 01:35:11 +00002694 // For non-power-of-two values, effectively round the value up to the
2695 // nearest power of two.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002696 if (!RHSC->getAPInt().isPowerOf2())
Dan Gohmanacd700a2010-04-22 01:35:11 +00002697 ++MaxShiftAmt;
Chris Lattner229907c2011-07-18 04:54:35 +00002698 IntegerType *ExtTy =
Dan Gohmanacd700a2010-04-22 01:35:11 +00002699 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohmanacd700a2010-04-22 01:35:11 +00002700 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2701 if (const SCEVConstant *Step =
Andrew Trick6d45a012011-08-06 07:00:37 +00002702 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2703 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002704 const APInt &StepInt = Step->getAPInt();
2705 const APInt &DivInt = RHSC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002706 if (!StepInt.urem(DivInt) &&
Dan Gohmanacd700a2010-04-22 01:35:11 +00002707 getZeroExtendExpr(AR, ExtTy) ==
2708 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2709 getZeroExtendExpr(Step, ExtTy),
Andrew Trick8b55b732011-03-14 16:50:06 +00002710 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002711 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002712 for (const SCEV *Op : AR->operands())
2713 Operands.push_back(getUDivExpr(Op, RHS));
2714 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002715 }
Andrew Trick6d45a012011-08-06 07:00:37 +00002716 /// Get a canonical UDivExpr for a recurrence.
2717 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2718 // We can currently only fold X%N if X is constant.
2719 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2720 if (StartC && !DivInt.urem(StepInt) &&
2721 getZeroExtendExpr(AR, ExtTy) ==
2722 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2723 getZeroExtendExpr(Step, ExtTy),
2724 AR->getLoop(), SCEV::FlagAnyWrap)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002725 const APInt &StartInt = StartC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002726 const APInt &StartRem = StartInt.urem(StepInt);
2727 if (StartRem != 0)
2728 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2729 AR->getLoop(), SCEV::FlagNW);
2730 }
2731 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002732 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2733 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2734 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002735 for (const SCEV *Op : M->operands())
2736 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002737 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2738 // Find an operand that's safely divisible.
2739 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2740 const SCEV *Op = M->getOperand(i);
2741 const SCEV *Div = getUDivExpr(Op, RHSC);
2742 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2743 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2744 M->op_end());
2745 Operands[i] = Div;
2746 return getMulExpr(Operands);
2747 }
2748 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002749 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002750 // (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 +00002751 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002752 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002753 for (const SCEV *Op : A->operands())
2754 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002755 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2756 Operands.clear();
2757 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2758 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2759 if (isa<SCEVUDivExpr>(Op) ||
2760 getMulExpr(Op, RHS) != A->getOperand(i))
2761 break;
2762 Operands.push_back(Op);
2763 }
2764 if (Operands.size() == A->getNumOperands())
2765 return getAddExpr(Operands);
2766 }
2767 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002768
Dan Gohmanacd700a2010-04-22 01:35:11 +00002769 // Fold if both operands are constant.
2770 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2771 Constant *LHSCV = LHSC->getValue();
2772 Constant *RHSCV = RHSC->getValue();
2773 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2774 RHSCV)));
2775 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002776 }
2777 }
2778
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002779 FoldingSetNodeID ID;
2780 ID.AddInteger(scUDivExpr);
2781 ID.AddPointer(LHS);
2782 ID.AddPointer(RHS);
Craig Topper9f008862014-04-15 04:59:12 +00002783 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002784 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00002785 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2786 LHS, RHS);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002787 UniqueSCEVs.InsertNode(S, IP);
2788 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002789}
2790
Nick Lewycky31eaca52014-01-27 10:04:03 +00002791static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002792 APInt A = C1->getAPInt().abs();
2793 APInt B = C2->getAPInt().abs();
Nick Lewycky31eaca52014-01-27 10:04:03 +00002794 uint32_t ABW = A.getBitWidth();
2795 uint32_t BBW = B.getBitWidth();
2796
2797 if (ABW > BBW)
2798 B = B.zext(ABW);
2799 else if (ABW < BBW)
2800 A = A.zext(BBW);
2801
2802 return APIntOps::GreatestCommonDivisor(A, B);
2803}
2804
Sanjoy Dasf8570812016-05-29 00:38:22 +00002805/// Get a canonical unsigned division expression, or something simpler if
2806/// possible. There is no representation for an exact udiv in SCEV IR, but we
2807/// can attempt to remove factors from the LHS and RHS. We can't do this when
2808/// it's not exact because the udiv may be clearing bits.
Nick Lewycky31eaca52014-01-27 10:04:03 +00002809const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2810 const SCEV *RHS) {
2811 // TODO: we could try to find factors in all sorts of things, but for now we
2812 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2813 // end of this file for inspiration.
2814
2815 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2816 if (!Mul)
2817 return getUDivExpr(LHS, RHS);
2818
2819 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2820 // If the mulexpr multiplies by a constant, then that constant must be the
2821 // first element of the mulexpr.
Sanjoy Das63914592015-10-18 00:29:20 +00002822 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
Nick Lewycky31eaca52014-01-27 10:04:03 +00002823 if (LHSCst == RHSCst) {
2824 SmallVector<const SCEV *, 2> Operands;
2825 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2826 return getMulExpr(Operands);
2827 }
2828
2829 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2830 // that there's a factor provided by one of the other terms. We need to
2831 // check.
2832 APInt Factor = gcd(LHSCst, RHSCst);
2833 if (!Factor.isIntN(1)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002834 LHSCst =
2835 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
2836 RHSCst =
2837 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
Nick Lewycky31eaca52014-01-27 10:04:03 +00002838 SmallVector<const SCEV *, 2> Operands;
2839 Operands.push_back(LHSCst);
2840 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2841 LHS = getMulExpr(Operands);
2842 RHS = RHSCst;
Nick Lewycky629199c2014-01-27 10:47:44 +00002843 Mul = dyn_cast<SCEVMulExpr>(LHS);
2844 if (!Mul)
2845 return getUDivExactExpr(LHS, RHS);
Nick Lewycky31eaca52014-01-27 10:04:03 +00002846 }
2847 }
2848 }
2849
2850 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2851 if (Mul->getOperand(i) == RHS) {
2852 SmallVector<const SCEV *, 2> Operands;
2853 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2854 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2855 return getMulExpr(Operands);
2856 }
2857 }
2858
2859 return getUDivExpr(LHS, RHS);
2860}
Chris Lattnerd934c702004-04-02 20:23:17 +00002861
Sanjoy Dasf8570812016-05-29 00:38:22 +00002862/// Get an add recurrence expression for the specified loop. Simplify the
2863/// expression as much as possible.
Andrew Trick8b55b732011-03-14 16:50:06 +00002864const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2865 const Loop *L,
2866 SCEV::NoWrapFlags Flags) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002867 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00002868 Operands.push_back(Start);
Dan Gohmana30370b2009-05-04 22:02:23 +00002869 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattnerd934c702004-04-02 20:23:17 +00002870 if (StepChrec->getLoop() == L) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00002871 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002872 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattnerd934c702004-04-02 20:23:17 +00002873 }
2874
2875 Operands.push_back(Step);
Andrew Trick8b55b732011-03-14 16:50:06 +00002876 return getAddRecExpr(Operands, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002877}
2878
Sanjoy Dasf8570812016-05-29 00:38:22 +00002879/// Get an add recurrence expression for the specified loop. Simplify the
2880/// expression as much as possible.
Dan Gohmance973df2009-06-24 04:48:43 +00002881const SCEV *
Dan Gohmanaf752342009-07-07 17:06:11 +00002882ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick8b55b732011-03-14 16:50:06 +00002883 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002884 if (Operands.size() == 1) return Operands[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002885#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002886 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002887 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002888 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002889 "SCEVAddRecExpr operand types don't match!");
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002890 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002891 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002892 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmand33f36e2009-05-18 15:44:58 +00002893#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002894
Dan Gohmanbe928e32008-06-18 16:23:07 +00002895 if (Operands.back()->isZero()) {
2896 Operands.pop_back();
Andrew Trick8b55b732011-03-14 16:50:06 +00002897 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmanbe928e32008-06-18 16:23:07 +00002898 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002899
Dan Gohmancf9c64e2010-02-19 18:49:22 +00002900 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2901 // use that information to infer NUW and NSW flags. However, computing a
2902 // BE count requires calling getAddRecExpr, so we may not yet have a
2903 // meaningful BE count at this point (and if we don't, we'd be stuck
2904 // with a SCEVCouldNotCompute as the cached BE count).
2905
Sanjoy Das81401d42015-01-10 23:41:24 +00002906 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002907
Dan Gohman223a5d22008-08-08 18:33:12 +00002908 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmana30370b2009-05-04 22:02:23 +00002909 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00002910 const Loop *NestedLoop = NestedAR->getLoop();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002911 if (L->contains(NestedLoop)
2912 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
2913 : (!NestedLoop->contains(L) &&
2914 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002915 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmancb0efec2009-12-18 01:14:11 +00002916 NestedAR->op_end());
Dan Gohman223a5d22008-08-08 18:33:12 +00002917 Operands[0] = NestedAR->getStart();
Dan Gohmancc030b72009-06-26 22:36:20 +00002918 // AddRecs require their operands be loop-invariant with respect to their
2919 // loops. Don't perform this transformation if it would break this
2920 // requirement.
Sanjoy Das3b827c72015-11-29 23:40:53 +00002921 bool AllInvariant = all_of(
2922 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00002923
Dan Gohmancc030b72009-06-26 22:36:20 +00002924 if (AllInvariant) {
Andrew Trick8b55b732011-03-14 16:50:06 +00002925 // Create a recurrence for the outer loop with the same step size.
2926 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002927 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2928 // inner recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002929 SCEV::NoWrapFlags OuterFlags =
2930 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick8b55b732011-03-14 16:50:06 +00002931
2932 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Sanjoy Das3b827c72015-11-29 23:40:53 +00002933 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
2934 return isLoopInvariant(Op, NestedLoop);
2935 });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00002936
Andrew Trick8b55b732011-03-14 16:50:06 +00002937 if (AllInvariant) {
Dan Gohmancc030b72009-06-26 22:36:20 +00002938 // Ok, both add recurrences are valid after the transformation.
Andrew Trick8b55b732011-03-14 16:50:06 +00002939 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002940 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2941 // the outer recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002942 SCEV::NoWrapFlags InnerFlags =
2943 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick8b55b732011-03-14 16:50:06 +00002944 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2945 }
Dan Gohmancc030b72009-06-26 22:36:20 +00002946 }
2947 // Reset Operands to its original state.
2948 Operands[0] = NestedAR;
Dan Gohman223a5d22008-08-08 18:33:12 +00002949 }
2950 }
2951
Dan Gohman8d67d2f2010-01-19 22:27:22 +00002952 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2953 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002954 FoldingSetNodeID ID;
2955 ID.AddInteger(scAddRecExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002956 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2957 ID.AddPointer(Operands[i]);
2958 ID.AddPointer(L);
Craig Topper9f008862014-04-15 04:59:12 +00002959 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002960 SCEVAddRecExpr *S =
2961 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2962 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002963 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2964 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002965 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2966 O, Operands.size(), L);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002967 UniqueSCEVs.InsertNode(S, IP);
2968 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002969 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002970 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002971}
2972
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002973const SCEV *
2974ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr,
2975 const SmallVectorImpl<const SCEV *> &IndexExprs,
2976 bool InBounds) {
2977 // getSCEV(Base)->getType() has the same address space as Base->getType()
2978 // because SCEV::getType() preserves the address space.
2979 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
2980 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
2981 // instruction to its SCEV, because the Instruction may be guarded by control
2982 // flow and the no-overflow bits may not be valid for the expression in any
Jingyue Wu42f1d672015-07-28 18:22:40 +00002983 // context. This can be fixed similarly to how these flags are handled for
2984 // adds.
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002985 SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
2986
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002987 const SCEV *TotalOffset = getZero(IntPtrTy);
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002988 // The address space is unimportant. The first thing we do on CurTy is getting
2989 // its element type.
2990 Type *CurTy = PointerType::getUnqual(PointeeType);
2991 for (const SCEV *IndexExpr : IndexExprs) {
2992 // Compute the (potentially symbolic) offset in bytes for this index.
2993 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2994 // For a struct, add the member offset.
2995 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
2996 unsigned FieldNo = Index->getZExtValue();
2997 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
2998
2999 // Add the field offset to the running total offset.
3000 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3001
3002 // Update CurTy to the type of the field at Index.
3003 CurTy = STy->getTypeAtIndex(Index);
3004 } else {
3005 // Update CurTy to its element type.
3006 CurTy = cast<SequentialType>(CurTy)->getElementType();
3007 // For an array, add the element offset, explicitly scaled.
3008 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3009 // Getelementptr indices are signed.
3010 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3011
3012 // Multiply the index by the element size to compute the element offset.
3013 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3014
3015 // Add the element offset to the running total offset.
3016 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3017 }
3018 }
3019
3020 // Add the total offset from all the GEP indices to the base.
3021 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3022}
3023
Dan Gohmanabd17092009-06-24 14:49:00 +00003024const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3025 const SCEV *RHS) {
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003026 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003027 return getSMaxExpr(Ops);
3028}
3029
Dan Gohmanaf752342009-07-07 17:06:11 +00003030const SCEV *
3031ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003032 assert(!Ops.empty() && "Cannot get empty smax!");
3033 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003034#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003035 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003036 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003037 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003038 "SCEVSMaxExpr operand types don't match!");
3039#endif
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003040
3041 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003042 GroupByComplexity(Ops, &LI);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003043
3044 // If there are any constants, fold them together.
3045 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003046 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003047 ++Idx;
3048 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003049 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003050 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003051 ConstantInt *Fold = ConstantInt::get(
3052 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003053 Ops[0] = getConstant(Fold);
3054 Ops.erase(Ops.begin()+1); // Erase the folded element
3055 if (Ops.size() == 1) return Ops[0];
3056 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003057 }
3058
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003059 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003060 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3061 Ops.erase(Ops.begin());
3062 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003063 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3064 // If we have an smax with a constant maximum-int, it will always be
3065 // maximum-int.
3066 return Ops[0];
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003067 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003068
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003069 if (Ops.size() == 1) return Ops[0];
3070 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003071
3072 // Find the first SMax
3073 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3074 ++Idx;
3075
3076 // Check to see if one of the operands is an SMax. If so, expand its operands
3077 // onto our operand list, and recurse to simplify.
3078 if (Idx < Ops.size()) {
3079 bool DeletedSMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003080 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003081 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003082 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003083 DeletedSMax = true;
3084 }
3085
3086 if (DeletedSMax)
3087 return getSMaxExpr(Ops);
3088 }
3089
3090 // Okay, check to see if the same value occurs in the operand list twice. If
3091 // so, delete one. Since we sorted the list, these values are required to
3092 // be adjacent.
3093 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003094 // X smax Y smax Y --> X smax Y
3095 // X smax Y --> X, if X is always greater than Y
3096 if (Ops[i] == Ops[i+1] ||
3097 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3098 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3099 --i; --e;
3100 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003101 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3102 --i; --e;
3103 }
3104
3105 if (Ops.size() == 1) return Ops[0];
3106
3107 assert(!Ops.empty() && "Reduced smax down to nothing!");
3108
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003109 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003110 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003111 FoldingSetNodeID ID;
3112 ID.AddInteger(scSMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003113 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3114 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003115 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003116 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003117 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3118 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003119 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3120 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003121 UniqueSCEVs.InsertNode(S, IP);
3122 return S;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003123}
3124
Dan Gohmanabd17092009-06-24 14:49:00 +00003125const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3126 const SCEV *RHS) {
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003127 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003128 return getUMaxExpr(Ops);
3129}
3130
Dan Gohmanaf752342009-07-07 17:06:11 +00003131const SCEV *
3132ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003133 assert(!Ops.empty() && "Cannot get empty umax!");
3134 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003135#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003136 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003137 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003138 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003139 "SCEVUMaxExpr operand types don't match!");
3140#endif
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003141
3142 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003143 GroupByComplexity(Ops, &LI);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003144
3145 // If there are any constants, fold them together.
3146 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003147 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003148 ++Idx;
3149 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003150 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003151 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003152 ConstantInt *Fold = ConstantInt::get(
3153 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003154 Ops[0] = getConstant(Fold);
3155 Ops.erase(Ops.begin()+1); // Erase the folded element
3156 if (Ops.size() == 1) return Ops[0];
3157 LHSC = cast<SCEVConstant>(Ops[0]);
3158 }
3159
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003160 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003161 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3162 Ops.erase(Ops.begin());
3163 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003164 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3165 // If we have an umax with a constant maximum-int, it will always be
3166 // maximum-int.
3167 return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003168 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003169
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003170 if (Ops.size() == 1) return Ops[0];
3171 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003172
3173 // Find the first UMax
3174 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3175 ++Idx;
3176
3177 // Check to see if one of the operands is a UMax. If so, expand its operands
3178 // onto our operand list, and recurse to simplify.
3179 if (Idx < Ops.size()) {
3180 bool DeletedUMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003181 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003182 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003183 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003184 DeletedUMax = true;
3185 }
3186
3187 if (DeletedUMax)
3188 return getUMaxExpr(Ops);
3189 }
3190
3191 // Okay, check to see if the same value occurs in the operand list twice. If
3192 // so, delete one. Since we sorted the list, these values are required to
3193 // be adjacent.
3194 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003195 // X umax Y umax Y --> X umax Y
3196 // X umax Y --> X, if X is always greater than Y
3197 if (Ops[i] == Ops[i+1] ||
3198 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3199 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3200 --i; --e;
3201 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003202 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3203 --i; --e;
3204 }
3205
3206 if (Ops.size() == 1) return Ops[0];
3207
3208 assert(!Ops.empty() && "Reduced umax down to nothing!");
3209
3210 // Okay, it looks like we really DO need a umax expr. Check to see if we
3211 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003212 FoldingSetNodeID ID;
3213 ID.AddInteger(scUMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003214 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3215 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003216 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003217 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003218 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3219 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003220 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3221 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003222 UniqueSCEVs.InsertNode(S, IP);
3223 return S;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003224}
3225
Dan Gohmanabd17092009-06-24 14:49:00 +00003226const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3227 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003228 // ~smax(~x, ~y) == smin(x, y).
3229 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3230}
3231
Dan Gohmanabd17092009-06-24 14:49:00 +00003232const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3233 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003234 // ~umax(~x, ~y) == umin(x, y)
3235 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3236}
3237
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003238const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003239 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003240 // constant expression and then folding it back into a ConstantInt.
3241 // This is just a compile-time optimization.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003242 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003243}
3244
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003245const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3246 StructType *STy,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003247 unsigned FieldNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003248 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003249 // constant expression and then folding it back into a ConstantInt.
3250 // This is just a compile-time optimization.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003251 return getConstant(
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003252 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003253}
3254
Dan Gohmanaf752342009-07-07 17:06:11 +00003255const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf436bac2009-06-24 00:54:57 +00003256 // Don't attempt to do anything other than create a SCEVUnknown object
3257 // here. createSCEV only calls getUnknown after checking for all other
3258 // interesting possibilities, and any other code that calls getUnknown
3259 // is doing so in order to hide a value from SCEV canonicalization.
3260
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003261 FoldingSetNodeID ID;
3262 ID.AddInteger(scUnknown);
3263 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +00003264 void *IP = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00003265 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3266 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3267 "Stale SCEVUnknown in uniquing map!");
3268 return S;
3269 }
3270 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3271 FirstUnknown);
3272 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003273 UniqueSCEVs.InsertNode(S, IP);
3274 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +00003275}
3276
Chris Lattnerd934c702004-04-02 20:23:17 +00003277//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00003278// Basic SCEV Analysis and PHI Idiom Recognition Code
3279//
3280
Sanjoy Dasf8570812016-05-29 00:38:22 +00003281/// Test if values of the given type are analyzable within the SCEV
3282/// framework. This primarily includes integer types, and it can optionally
3283/// include pointer types if the ScalarEvolution class has access to
3284/// target-specific information.
Chris Lattner229907c2011-07-18 04:54:35 +00003285bool ScalarEvolution::isSCEVable(Type *Ty) const {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003286 // Integers and pointers are always SCEVable.
Duncan Sands19d0b472010-02-16 11:11:14 +00003287 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003288}
3289
Sanjoy Dasf8570812016-05-29 00:38:22 +00003290/// Return the size in bits of the specified type, for which isSCEVable must
3291/// return true.
Chris Lattner229907c2011-07-18 04:54:35 +00003292uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003293 assert(isSCEVable(Ty) && "Type is not SCEVable!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003294 return getDataLayout().getTypeSizeInBits(Ty);
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003295}
3296
Sanjoy Dasf8570812016-05-29 00:38:22 +00003297/// Return a type with the same bitwidth as the given type and which represents
3298/// how SCEV will treat the given type, for which isSCEVable must return
3299/// true. For pointer types, this is the pointer-sized integer type.
Chris Lattner229907c2011-07-18 04:54:35 +00003300Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003301 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3302
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003303 if (Ty->isIntegerTy())
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003304 return Ty;
3305
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003306 // The only other support type is pointer.
Duncan Sands19d0b472010-02-16 11:11:14 +00003307 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003308 return getDataLayout().getIntPtrType(Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003309}
Chris Lattnerd934c702004-04-02 20:23:17 +00003310
Dan Gohmanaf752342009-07-07 17:06:11 +00003311const SCEV *ScalarEvolution::getCouldNotCompute() {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003312 return CouldNotCompute.get();
Dan Gohman31efa302009-04-18 17:58:19 +00003313}
3314
Sanjoy Das7d752672015-12-08 04:32:54 +00003315
3316bool ScalarEvolution::checkValidity(const SCEV *S) const {
Shuxin Yangefc4c012013-07-08 17:33:13 +00003317 // Helper class working with SCEVTraversal to figure out if a SCEV contains
3318 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
3319 // is set iff if find such SCEVUnknown.
3320 //
3321 struct FindInvalidSCEVUnknown {
3322 bool FindOne;
3323 FindInvalidSCEVUnknown() { FindOne = false; }
3324 bool follow(const SCEV *S) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00003325 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Shuxin Yangefc4c012013-07-08 17:33:13 +00003326 case scConstant:
3327 return false;
3328 case scUnknown:
Shuxin Yang23773b32013-07-12 07:25:38 +00003329 if (!cast<SCEVUnknown>(S)->getValue())
Shuxin Yangefc4c012013-07-08 17:33:13 +00003330 FindOne = true;
3331 return false;
3332 default:
3333 return true;
3334 }
3335 }
3336 bool isDone() const { return FindOne; }
3337 };
Shuxin Yangefc4c012013-07-08 17:33:13 +00003338
Shuxin Yangefc4c012013-07-08 17:33:13 +00003339 FindInvalidSCEVUnknown F;
3340 SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
3341 ST.visitAll(S);
3342
3343 return !F.FindOne;
3344}
3345
Wei Mia49559b2016-02-04 01:27:38 +00003346bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
Sanjoy Dasc220ac72016-09-27 18:01:44 +00003347 // Helper class working with SCEVTraversal to figure out if a SCEV contains a
3348 // sub SCEV of scAddRecExpr type. FindInvalidSCEVUnknown::FoundOne is set iff
3349 // if such sub scAddRecExpr type SCEV is found.
3350 struct FindAddRecurrence {
3351 bool FoundOne;
3352 FindAddRecurrence() : FoundOne(false) {}
3353
3354 bool follow(const SCEV *S) {
3355 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
3356 case scAddRecExpr:
3357 FoundOne = true;
3358 case scConstant:
3359 case scUnknown:
3360 case scCouldNotCompute:
3361 return false;
3362 default:
3363 return true;
3364 }
3365 }
3366 bool isDone() const { return FoundOne; }
3367 };
3368
Sanjoy Dasa2602142016-09-27 18:01:46 +00003369 HasRecMapType::iterator I = HasRecMap.find(S);
Wei Mia49559b2016-02-04 01:27:38 +00003370 if (I != HasRecMap.end())
3371 return I->second;
3372
3373 FindAddRecurrence F;
3374 SCEVTraversal<FindAddRecurrence> ST(F);
3375 ST.visitAll(S);
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003376 HasRecMap.insert({S, F.FoundOne});
Wei Mia49559b2016-02-04 01:27:38 +00003377 return F.FoundOne;
3378}
3379
Wei Mi785858c2016-08-09 20:37:50 +00003380/// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3381/// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3382/// offset I, then return {S', I}, else return {\p S, nullptr}.
3383static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3384 const auto *Add = dyn_cast<SCEVAddExpr>(S);
3385 if (!Add)
3386 return {S, nullptr};
3387
3388 if (Add->getNumOperands() != 2)
3389 return {S, nullptr};
3390
3391 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3392 if (!ConstOp)
3393 return {S, nullptr};
3394
3395 return {Add->getOperand(1), ConstOp->getValue()};
3396}
3397
3398/// Return the ValueOffsetPair set for \p S. \p S can be represented
3399/// by the value and offset from any ValueOffsetPair in the set.
3400SetVector<ScalarEvolution::ValueOffsetPair> *
3401ScalarEvolution::getSCEVValues(const SCEV *S) {
Wei Mia49559b2016-02-04 01:27:38 +00003402 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3403 if (SI == ExprValueMap.end())
3404 return nullptr;
3405#ifndef NDEBUG
3406 if (VerifySCEVMap) {
3407 // Check there is no dangling Value in the set returned.
3408 for (const auto &VE : SI->second)
Wei Mi785858c2016-08-09 20:37:50 +00003409 assert(ValueExprMap.count(VE.first));
Wei Mia49559b2016-02-04 01:27:38 +00003410 }
3411#endif
3412 return &SI->second;
3413}
3414
Wei Mi785858c2016-08-09 20:37:50 +00003415/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3416/// cannot be used separately. eraseValueFromMap should be used to remove
3417/// V from ValueExprMap and ExprValueMap at the same time.
Wei Mia49559b2016-02-04 01:27:38 +00003418void ScalarEvolution::eraseValueFromMap(Value *V) {
3419 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3420 if (I != ValueExprMap.end()) {
3421 const SCEV *S = I->second;
Wei Mi785858c2016-08-09 20:37:50 +00003422 // Remove {V, 0} from the set of ExprValueMap[S]
3423 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3424 SV->remove({V, nullptr});
3425
3426 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3427 const SCEV *Stripped;
3428 ConstantInt *Offset;
3429 std::tie(Stripped, Offset) = splitAddExpr(S);
3430 if (Offset != nullptr) {
3431 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3432 SV->remove({V, Offset});
3433 }
Wei Mia49559b2016-02-04 01:27:38 +00003434 ValueExprMap.erase(V);
3435 }
3436}
3437
Sanjoy Dasf8570812016-05-29 00:38:22 +00003438/// Return an existing SCEV if it exists, otherwise analyze the expression and
3439/// create a new one.
Dan Gohmanaf752342009-07-07 17:06:11 +00003440const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003441 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattnerd934c702004-04-02 20:23:17 +00003442
Jingyue Wu42f1d672015-07-28 18:22:40 +00003443 const SCEV *S = getExistingSCEV(V);
3444 if (S == nullptr) {
3445 S = createSCEV(V);
Wei Mia49559b2016-02-04 01:27:38 +00003446 // During PHI resolution, it is possible to create two SCEVs for the same
3447 // V, so it is needed to double check whether V->S is inserted into
Wei Mi785858c2016-08-09 20:37:50 +00003448 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
Wei Mia49559b2016-02-04 01:27:38 +00003449 std::pair<ValueExprMapType::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003450 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
Wei Mi785858c2016-08-09 20:37:50 +00003451 if (Pair.second) {
3452 ExprValueMap[S].insert({V, nullptr});
3453
3454 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3455 // ExprValueMap.
3456 const SCEV *Stripped = S;
3457 ConstantInt *Offset = nullptr;
3458 std::tie(Stripped, Offset) = splitAddExpr(S);
3459 // If stripped is SCEVUnknown, don't bother to save
3460 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3461 // increase the complexity of the expansion code.
3462 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3463 // because it may generate add/sub instead of GEP in SCEV expansion.
3464 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3465 !isa<GetElementPtrInst>(V))
3466 ExprValueMap[Stripped].insert({V, Offset});
3467 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003468 }
3469 return S;
3470}
3471
3472const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3473 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3474
Shuxin Yangefc4c012013-07-08 17:33:13 +00003475 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3476 if (I != ValueExprMap.end()) {
3477 const SCEV *S = I->second;
Shuxin Yang23773b32013-07-12 07:25:38 +00003478 if (checkValidity(S))
Shuxin Yangefc4c012013-07-08 17:33:13 +00003479 return S;
Wei Mi785858c2016-08-09 20:37:50 +00003480 eraseValueFromMap(V);
Wei Mia49559b2016-02-04 01:27:38 +00003481 forgetMemoizedResults(S);
Shuxin Yangefc4c012013-07-08 17:33:13 +00003482 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003483 return nullptr;
Chris Lattnerd934c702004-04-02 20:23:17 +00003484}
3485
Sanjoy Dasf8570812016-05-29 00:38:22 +00003486/// Return a SCEV corresponding to -V = -1*V
Dan Gohman0a40ad92009-04-16 03:18:22 +00003487///
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003488const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3489 SCEV::NoWrapFlags Flags) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003490 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson53a52212009-07-13 04:09:18 +00003491 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003492 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003493
Chris Lattner229907c2011-07-18 04:54:35 +00003494 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003495 Ty = getEffectiveSCEVType(Ty);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003496 return getMulExpr(
3497 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003498}
3499
Sanjoy Dasf8570812016-05-29 00:38:22 +00003500/// Return a SCEV corresponding to ~V = -1-V
Dan Gohmanaf752342009-07-07 17:06:11 +00003501const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003502 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson542619e2009-07-13 20:58:05 +00003503 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003504 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003505
Chris Lattner229907c2011-07-18 04:54:35 +00003506 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003507 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003508 const SCEV *AllOnes =
Owen Anderson5a1acd92009-07-31 20:28:14 +00003509 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003510 return getMinusSCEV(AllOnes, V);
3511}
3512
Chris Lattnerfc877522011-01-09 22:26:35 +00003513const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00003514 SCEV::NoWrapFlags Flags) {
Dan Gohman46f00a22010-07-20 16:53:00 +00003515 // Fast path: X - X --> 0.
3516 if (LHS == RHS)
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003517 return getZero(LHS->getType());
Dan Gohman46f00a22010-07-20 16:53:00 +00003518
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003519 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3520 // makes it so that we cannot make much use of NUW.
3521 auto AddFlags = SCEV::FlagAnyWrap;
3522 const bool RHSIsNotMinSigned =
3523 !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3524 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3525 // Let M be the minimum representable signed value. Then (-1)*RHS
3526 // signed-wraps if and only if RHS is M. That can happen even for
3527 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3528 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3529 // (-1)*RHS, we need to prove that RHS != M.
3530 //
3531 // If LHS is non-negative and we know that LHS - RHS does not
3532 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3533 // either by proving that RHS > M or that LHS >= 0.
3534 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3535 AddFlags = SCEV::FlagNSW;
3536 }
3537 }
3538
3539 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3540 // RHS is NSW and LHS >= 0.
3541 //
3542 // The difficulty here is that the NSW flag may have been proven
3543 // relative to a loop that is to be found in a recurrence in LHS and
3544 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3545 // larger scope than intended.
3546 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3547
3548 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003549}
3550
Dan Gohmanaf752342009-07-07 17:06:11 +00003551const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003552ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3553 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003554 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3555 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003556 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003557 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003558 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003559 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003560 return getTruncateExpr(V, Ty);
3561 return getZeroExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003562}
3563
Dan Gohmanaf752342009-07-07 17:06:11 +00003564const SCEV *
3565ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattner229907c2011-07-18 04:54:35 +00003566 Type *Ty) {
3567 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003568 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3569 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003570 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003571 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003572 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003573 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003574 return getTruncateExpr(V, Ty);
3575 return getSignExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003576}
3577
Dan Gohmanaf752342009-07-07 17:06:11 +00003578const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003579ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3580 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003581 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3582 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003583 "Cannot noop or zero extend with non-integer arguments!");
3584 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3585 "getNoopOrZeroExtend cannot truncate!");
3586 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3587 return V; // No conversion
3588 return getZeroExtendExpr(V, Ty);
3589}
3590
Dan Gohmanaf752342009-07-07 17:06:11 +00003591const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003592ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3593 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003594 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3595 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003596 "Cannot noop or sign extend with non-integer arguments!");
3597 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3598 "getNoopOrSignExtend cannot truncate!");
3599 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3600 return V; // No conversion
3601 return getSignExtendExpr(V, Ty);
3602}
3603
Dan Gohmanaf752342009-07-07 17:06:11 +00003604const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003605ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3606 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003607 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3608 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman8db2edc2009-06-13 15:56:47 +00003609 "Cannot noop or any extend with non-integer arguments!");
3610 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3611 "getNoopOrAnyExtend cannot truncate!");
3612 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3613 return V; // No conversion
3614 return getAnyExtendExpr(V, Ty);
3615}
3616
Dan Gohmanaf752342009-07-07 17:06:11 +00003617const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003618ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3619 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003620 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3621 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003622 "Cannot truncate or noop with non-integer arguments!");
3623 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3624 "getTruncateOrNoop cannot extend!");
3625 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3626 return V; // No conversion
3627 return getTruncateExpr(V, Ty);
3628}
3629
Dan Gohmanabd17092009-06-24 14:49:00 +00003630const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3631 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003632 const SCEV *PromotedLHS = LHS;
3633 const SCEV *PromotedRHS = RHS;
Dan Gohman96212b62009-06-22 00:31:57 +00003634
3635 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3636 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3637 else
3638 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3639
3640 return getUMaxExpr(PromotedLHS, PromotedRHS);
3641}
3642
Dan Gohmanabd17092009-06-24 14:49:00 +00003643const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3644 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003645 const SCEV *PromotedLHS = LHS;
3646 const SCEV *PromotedRHS = RHS;
Dan Gohman2bc22302009-06-22 15:03:27 +00003647
3648 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3649 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3650 else
3651 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3652
3653 return getUMinExpr(PromotedLHS, PromotedRHS);
3654}
3655
Andrew Trick87716c92011-03-17 23:51:11 +00003656const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3657 // A pointer operand may evaluate to a nonpointer expression, such as null.
3658 if (!V->getType()->isPointerTy())
3659 return V;
3660
3661 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3662 return getPointerBase(Cast->getOperand());
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003663 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
Craig Topper9f008862014-04-15 04:59:12 +00003664 const SCEV *PtrOp = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003665 for (const SCEV *NAryOp : NAry->operands()) {
3666 if (NAryOp->getType()->isPointerTy()) {
Andrew Trick87716c92011-03-17 23:51:11 +00003667 // Cannot find the base of an expression with multiple pointer operands.
3668 if (PtrOp)
3669 return V;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003670 PtrOp = NAryOp;
Andrew Trick87716c92011-03-17 23:51:11 +00003671 }
3672 }
3673 if (!PtrOp)
3674 return V;
3675 return getPointerBase(PtrOp);
3676 }
3677 return V;
3678}
3679
Sanjoy Dasf8570812016-05-29 00:38:22 +00003680/// Push users of the given Instruction onto the given Worklist.
Dan Gohman0b89dff2009-07-25 01:13:03 +00003681static void
3682PushDefUseChildren(Instruction *I,
3683 SmallVectorImpl<Instruction *> &Worklist) {
3684 // Push the def-use children onto the Worklist stack.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003685 for (User *U : I->users())
3686 Worklist.push_back(cast<Instruction>(U));
Dan Gohman0b89dff2009-07-25 01:13:03 +00003687}
3688
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00003689void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohman0b89dff2009-07-25 01:13:03 +00003690 SmallVector<Instruction *, 16> Worklist;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003691 PushDefUseChildren(PN, Worklist);
Chris Lattnerd934c702004-04-02 20:23:17 +00003692
Dan Gohman0b89dff2009-07-25 01:13:03 +00003693 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003694 Visited.insert(PN);
Dan Gohman0b89dff2009-07-25 01:13:03 +00003695 while (!Worklist.empty()) {
Dan Gohmana9c205c2010-02-25 06:57:05 +00003696 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00003697 if (!Visited.insert(I).second)
3698 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003699
Sanjoy Das63914592015-10-18 00:29:20 +00003700 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003701 if (It != ValueExprMap.end()) {
Dan Gohman761065e2010-11-17 02:44:44 +00003702 const SCEV *Old = It->second;
3703
Dan Gohman0b89dff2009-07-25 01:13:03 +00003704 // Short-circuit the def-use traversal if the symbolic name
3705 // ceases to appear in expressions.
Dan Gohman534749b2010-11-17 22:27:42 +00003706 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohman0b89dff2009-07-25 01:13:03 +00003707 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003708
Dan Gohman0b89dff2009-07-25 01:13:03 +00003709 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohmana9c205c2010-02-25 06:57:05 +00003710 // structure, it's a PHI that's in the progress of being computed
3711 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3712 // additional loop trip count information isn't going to change anything.
3713 // In the second case, createNodeForPHI will perform the necessary
3714 // updates on its own when it gets to that point. In the third, we do
3715 // want to forget the SCEVUnknown.
3716 if (!isa<PHINode>(I) ||
Dan Gohman761065e2010-11-17 02:44:44 +00003717 !isa<SCEVUnknown>(Old) ||
3718 (I != PN && Old == SymName)) {
Wei Mi785858c2016-08-09 20:37:50 +00003719 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00003720 forgetMemoizedResults(Old);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00003721 }
Dan Gohman0b89dff2009-07-25 01:13:03 +00003722 }
3723
3724 PushDefUseChildren(I, Worklist);
3725 }
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003726}
Chris Lattnerd934c702004-04-02 20:23:17 +00003727
Benjamin Kramer83709b12015-11-16 09:01:28 +00003728namespace {
Silviu Barangaf91c8072015-10-30 15:02:28 +00003729class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3730public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003731 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003732 ScalarEvolution &SE) {
3733 SCEVInitRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003734 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003735 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3736 }
3737
3738 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3739 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3740
3741 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3742 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3743 Valid = false;
3744 return Expr;
3745 }
3746
3747 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3748 // Only allow AddRecExprs for this loop.
3749 if (Expr->getLoop() == L)
3750 return Expr->getStart();
3751 Valid = false;
3752 return Expr;
3753 }
3754
3755 bool isValid() { return Valid; }
3756
3757private:
3758 const Loop *L;
3759 bool Valid;
3760};
3761
3762class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3763public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003764 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003765 ScalarEvolution &SE) {
3766 SCEVShiftRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003767 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003768 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3769 }
3770
3771 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3772 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3773
3774 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3775 // Only allow AddRecExprs for this loop.
3776 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3777 Valid = false;
3778 return Expr;
3779 }
3780
3781 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3782 if (Expr->getLoop() == L && Expr->isAffine())
3783 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3784 Valid = false;
3785 return Expr;
3786 }
3787 bool isValid() { return Valid; }
3788
3789private:
3790 const Loop *L;
3791 bool Valid;
3792};
Benjamin Kramer83709b12015-11-16 09:01:28 +00003793} // end anonymous namespace
Silviu Barangaf91c8072015-10-30 15:02:28 +00003794
Sanjoy Das724f5cf2016-03-03 18:31:29 +00003795SCEV::NoWrapFlags
3796ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3797 if (!AR->isAffine())
3798 return SCEV::FlagAnyWrap;
3799
3800 typedef OverflowingBinaryOperator OBO;
3801 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3802
3803 if (!AR->hasNoSignedWrap()) {
3804 ConstantRange AddRecRange = getSignedRange(AR);
3805 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3806
3807 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3808 Instruction::Add, IncRange, OBO::NoSignedWrap);
3809 if (NSWRegion.contains(AddRecRange))
3810 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3811 }
3812
3813 if (!AR->hasNoUnsignedWrap()) {
3814 ConstantRange AddRecRange = getUnsignedRange(AR);
3815 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3816
3817 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3818 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3819 if (NUWRegion.contains(AddRecRange))
3820 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3821 }
3822
3823 return Result;
3824}
3825
Sanjoy Das118d9192016-03-31 05:14:22 +00003826namespace {
3827/// Represents an abstract binary operation. This may exist as a
3828/// normal instruction or constant expression, or may have been
3829/// derived from an expression tree.
3830struct BinaryOp {
3831 unsigned Opcode;
3832 Value *LHS;
3833 Value *RHS;
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003834 bool IsNSW;
3835 bool IsNUW;
Sanjoy Das118d9192016-03-31 05:14:22 +00003836
3837 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3838 /// constant expression.
3839 Operator *Op;
3840
3841 explicit BinaryOp(Operator *Op)
3842 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003843 IsNSW(false), IsNUW(false), Op(Op) {
3844 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3845 IsNSW = OBO->hasNoSignedWrap();
3846 IsNUW = OBO->hasNoUnsignedWrap();
3847 }
3848 }
Sanjoy Das118d9192016-03-31 05:14:22 +00003849
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003850 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3851 bool IsNUW = false)
3852 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3853 Op(nullptr) {}
Sanjoy Das118d9192016-03-31 05:14:22 +00003854};
3855}
3856
3857
3858/// Try to map \p V into a BinaryOp, and return \c None on failure.
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003859static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
Sanjoy Das118d9192016-03-31 05:14:22 +00003860 auto *Op = dyn_cast<Operator>(V);
3861 if (!Op)
3862 return None;
3863
3864 // Implementation detail: all the cleverness here should happen without
3865 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3866 // SCEV expressions when possible, and we should not break that.
3867
3868 switch (Op->getOpcode()) {
3869 case Instruction::Add:
3870 case Instruction::Sub:
3871 case Instruction::Mul:
3872 case Instruction::UDiv:
3873 case Instruction::And:
3874 case Instruction::Or:
3875 case Instruction::AShr:
3876 case Instruction::Shl:
3877 return BinaryOp(Op);
3878
3879 case Instruction::Xor:
3880 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
3881 // If the RHS of the xor is a signbit, then this is just an add.
3882 // Instcombine turns add of signbit into xor as a strength reduction step.
3883 if (RHSC->getValue().isSignBit())
3884 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
3885 return BinaryOp(Op);
3886
3887 case Instruction::LShr:
3888 // Turn logical shift right of a constant into a unsigned divide.
3889 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
3890 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
3891
3892 // If the shift count is not less than the bitwidth, the result of
3893 // the shift is undefined. Don't try to analyze it, because the
3894 // resolution chosen here may differ from the resolution chosen in
3895 // other parts of the compiler.
3896 if (SA->getValue().ult(BitWidth)) {
3897 Constant *X =
3898 ConstantInt::get(SA->getContext(),
3899 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
3900 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
3901 }
3902 }
3903 return BinaryOp(Op);
3904
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003905 case Instruction::ExtractValue: {
3906 auto *EVI = cast<ExtractValueInst>(Op);
3907 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
3908 break;
3909
3910 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
3911 if (!CI)
3912 break;
3913
3914 if (auto *F = CI->getCalledFunction())
3915 switch (F->getIntrinsicID()) {
3916 case Intrinsic::sadd_with_overflow:
3917 case Intrinsic::uadd_with_overflow: {
3918 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
3919 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3920 CI->getArgOperand(1));
3921
3922 // Now that we know that all uses of the arithmetic-result component of
3923 // CI are guarded by the overflow check, we can go ahead and pretend
3924 // that the arithmetic is non-overflowing.
3925 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
3926 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3927 CI->getArgOperand(1), /* IsNSW = */ true,
3928 /* IsNUW = */ false);
3929 else
3930 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3931 CI->getArgOperand(1), /* IsNSW = */ false,
3932 /* IsNUW*/ true);
3933 }
3934
3935 case Intrinsic::ssub_with_overflow:
3936 case Intrinsic::usub_with_overflow:
3937 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
3938 CI->getArgOperand(1));
3939
3940 case Intrinsic::smul_with_overflow:
3941 case Intrinsic::umul_with_overflow:
3942 return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
3943 CI->getArgOperand(1));
3944 default:
3945 break;
3946 }
3947 }
3948
Sanjoy Das118d9192016-03-31 05:14:22 +00003949 default:
3950 break;
3951 }
3952
3953 return None;
3954}
3955
Sanjoy Das55015d22015-10-02 23:09:44 +00003956const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
3957 const Loop *L = LI.getLoopFor(PN->getParent());
3958 if (!L || L->getHeader() != PN->getParent())
3959 return nullptr;
3960
3961 // The loop may have multiple entrances or multiple exits; we can analyze
3962 // this phi as an addrec if it has a unique entry value and a unique
3963 // backedge value.
3964 Value *BEValueV = nullptr, *StartValueV = nullptr;
3965 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3966 Value *V = PN->getIncomingValue(i);
3967 if (L->contains(PN->getIncomingBlock(i))) {
3968 if (!BEValueV) {
3969 BEValueV = V;
3970 } else if (BEValueV != V) {
3971 BEValueV = nullptr;
3972 break;
3973 }
3974 } else if (!StartValueV) {
3975 StartValueV = V;
3976 } else if (StartValueV != V) {
3977 StartValueV = nullptr;
3978 break;
3979 }
3980 }
3981 if (BEValueV && StartValueV) {
3982 // While we are analyzing this PHI node, handle its value symbolically.
3983 const SCEV *SymbolicName = getUnknown(PN);
3984 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
3985 "PHI node already processed?");
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003986 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
Sanjoy Das55015d22015-10-02 23:09:44 +00003987
3988 // Using this symbolic name for the PHI, analyze the value coming around
3989 // the back-edge.
3990 const SCEV *BEValue = getSCEV(BEValueV);
3991
3992 // NOTE: If BEValue is loop invariant, we know that the PHI node just
3993 // has a special value for the first iteration of the loop.
3994
3995 // If the value coming around the backedge is an add with the symbolic
3996 // value we just inserted, then we found a simple induction variable!
3997 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
3998 // If there is a single occurrence of the symbolic value, replace it
3999 // with a recurrence.
4000 unsigned FoundIndex = Add->getNumOperands();
4001 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4002 if (Add->getOperand(i) == SymbolicName)
4003 if (FoundIndex == e) {
4004 FoundIndex = i;
Dan Gohman6635bb22010-04-12 07:49:36 +00004005 break;
4006 }
Sanjoy Das55015d22015-10-02 23:09:44 +00004007
4008 if (FoundIndex != Add->getNumOperands()) {
4009 // Create an add with everything but the specified operand.
4010 SmallVector<const SCEV *, 8> Ops;
4011 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4012 if (i != FoundIndex)
4013 Ops.push_back(Add->getOperand(i));
4014 const SCEV *Accum = getAddExpr(Ops);
4015
4016 // This is not a valid addrec if the step amount is varying each
4017 // loop iteration, but is not itself an addrec in this loop.
4018 if (isLoopInvariant(Accum, L) ||
4019 (isa<SCEVAddRecExpr>(Accum) &&
4020 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4021 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4022
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004023 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004024 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4025 if (BO->IsNUW)
Sanjoy Das55015d22015-10-02 23:09:44 +00004026 Flags = setFlags(Flags, SCEV::FlagNUW);
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004027 if (BO->IsNSW)
Sanjoy Das55015d22015-10-02 23:09:44 +00004028 Flags = setFlags(Flags, SCEV::FlagNSW);
4029 }
4030 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4031 // If the increment is an inbounds GEP, then we know the address
4032 // space cannot be wrapped around. We cannot make any guarantee
4033 // about signed or unsigned overflow because pointers are
4034 // unsigned but we may have a negative index from the base
4035 // pointer. We can guarantee that no unsigned wrap occurs if the
4036 // indices form a positive value.
4037 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4038 Flags = setFlags(Flags, SCEV::FlagNW);
4039
4040 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4041 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4042 Flags = setFlags(Flags, SCEV::FlagNUW);
4043 }
4044
4045 // We cannot transfer nuw and nsw flags from subtraction
4046 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4047 // for instance.
4048 }
4049
4050 const SCEV *StartVal = getSCEV(StartValueV);
4051 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4052
Sanjoy Das55015d22015-10-02 23:09:44 +00004053 // Okay, for the entire analysis of this edge we assumed the PHI
4054 // to be symbolic. We now need to go back and purge all of the
4055 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004056 forgetSymbolicName(PN, SymbolicName);
Sanjoy Das55015d22015-10-02 23:09:44 +00004057 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004058
4059 // We can add Flags to the post-inc expression only if we
4060 // know that it us *undefined behavior* for BEValueV to
4061 // overflow.
4062 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4063 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4064 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4065
Sanjoy Das55015d22015-10-02 23:09:44 +00004066 return PHISCEV;
Dan Gohman6635bb22010-04-12 07:49:36 +00004067 }
4068 }
Silviu Barangaf91c8072015-10-30 15:02:28 +00004069 } else {
Sanjoy Das55015d22015-10-02 23:09:44 +00004070 // Otherwise, this could be a loop like this:
4071 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
4072 // In this case, j = {1,+,1} and BEValue is j.
4073 // Because the other in-value of i (0) fits the evolution of BEValue
4074 // i really is an addrec evolution.
Silviu Barangaf91c8072015-10-30 15:02:28 +00004075 //
4076 // We can generalize this saying that i is the shifted value of BEValue
4077 // by one iteration:
4078 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
4079 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4080 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4081 if (Shifted != getCouldNotCompute() &&
4082 Start != getCouldNotCompute()) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004083 const SCEV *StartVal = getSCEV(StartValueV);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004084 if (Start == StartVal) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004085 // Okay, for the entire analysis of this edge we assumed the PHI
4086 // to be symbolic. We now need to go back and purge all of the
4087 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004088 forgetSymbolicName(PN, SymbolicName);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004089 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4090 return Shifted;
Chris Lattnerd934c702004-04-02 20:23:17 +00004091 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004092 }
Dan Gohman6635bb22010-04-12 07:49:36 +00004093 }
Tobias Grosser934fcf42016-02-21 18:50:09 +00004094
4095 // Remove the temporary PHI node SCEV that has been inserted while intending
4096 // to create an AddRecExpr for this PHI node. We can not keep this temporary
4097 // as it will prevent later (possibly simpler) SCEV expressions to be added
4098 // to the ValueExprMap.
Wei Mi785858c2016-08-09 20:37:50 +00004099 eraseValueFromMap(PN);
Sanjoy Das55015d22015-10-02 23:09:44 +00004100 }
4101
4102 return nullptr;
4103}
4104
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004105// Checks if the SCEV S is available at BB. S is considered available at BB
4106// if S can be materialized at BB without introducing a fault.
4107static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4108 BasicBlock *BB) {
4109 struct CheckAvailable {
4110 bool TraversalDone = false;
4111 bool Available = true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004112
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004113 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
4114 BasicBlock *BB = nullptr;
4115 DominatorTree &DT;
Sanjoy Das55015d22015-10-02 23:09:44 +00004116
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004117 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4118 : L(L), BB(BB), DT(DT) {}
Sanjoy Das55015d22015-10-02 23:09:44 +00004119
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004120 bool setUnavailable() {
4121 TraversalDone = true;
4122 Available = false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004123 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004124 }
4125
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004126 bool follow(const SCEV *S) {
4127 switch (S->getSCEVType()) {
4128 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4129 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
Sanjoy Dasbb5ffc52015-10-24 05:37:28 +00004130 // These expressions are available if their operand(s) is/are.
4131 return true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004132
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004133 case scAddRecExpr: {
4134 // We allow add recurrences that are on the loop BB is in, or some
4135 // outer loop. This guarantees availability because the value of the
4136 // add recurrence at BB is simply the "current" value of the induction
4137 // variable. We can relax this in the future; for instance an add
4138 // recurrence on a sibling dominating loop is also available at BB.
4139 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4140 if (L && (ARLoop == L || ARLoop->contains(L)))
Sanjoy Das55015d22015-10-02 23:09:44 +00004141 return true;
4142
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004143 return setUnavailable();
Sanjoy Das55015d22015-10-02 23:09:44 +00004144 }
4145
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004146 case scUnknown: {
4147 // For SCEVUnknown, we check for simple dominance.
4148 const auto *SU = cast<SCEVUnknown>(S);
4149 Value *V = SU->getValue();
Sanjoy Das55015d22015-10-02 23:09:44 +00004150
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004151 if (isa<Argument>(V))
4152 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004153
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004154 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4155 return false;
4156
4157 return setUnavailable();
4158 }
4159
4160 case scUDivExpr:
4161 case scCouldNotCompute:
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00004162 // We do not try to smart about these at all.
4163 return setUnavailable();
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004164 }
4165 llvm_unreachable("switch should be fully covered!");
4166 }
4167
4168 bool isDone() { return TraversalDone; }
Sanjoy Das55015d22015-10-02 23:09:44 +00004169 };
4170
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004171 CheckAvailable CA(L, BB, DT);
4172 SCEVTraversal<CheckAvailable> ST(CA);
4173
4174 ST.visitAll(S);
4175 return CA.Available;
4176}
4177
4178// Try to match a control flow sequence that branches out at BI and merges back
4179// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
4180// match.
4181static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4182 Value *&C, Value *&LHS, Value *&RHS) {
4183 C = BI->getCondition();
4184
4185 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4186 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4187
4188 if (!LeftEdge.isSingleEdge())
4189 return false;
4190
4191 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4192
4193 Use &LeftUse = Merge->getOperandUse(0);
4194 Use &RightUse = Merge->getOperandUse(1);
4195
4196 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4197 LHS = LeftUse;
4198 RHS = RightUse;
4199 return true;
4200 }
4201
4202 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4203 LHS = RightUse;
4204 RHS = LeftUse;
4205 return true;
4206 }
4207
4208 return false;
4209}
4210
4211const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
Sanjoy Dasb0b4e862016-08-05 18:34:14 +00004212 auto IsReachable =
4213 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4214 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004215 const Loop *L = LI.getLoopFor(PN->getParent());
4216
Sanjoy Das337d4782015-10-31 23:21:40 +00004217 // We don't want to break LCSSA, even in a SCEV expression tree.
4218 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4219 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4220 return nullptr;
4221
Sanjoy Das55015d22015-10-02 23:09:44 +00004222 // Try to match
4223 //
4224 // br %cond, label %left, label %right
4225 // left:
4226 // br label %merge
4227 // right:
4228 // br label %merge
4229 // merge:
4230 // V = phi [ %x, %left ], [ %y, %right ]
4231 //
4232 // as "select %cond, %x, %y"
4233
4234 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4235 assert(IDom && "At least the entry block should dominate PN");
4236
4237 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4238 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4239
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004240 if (BI && BI->isConditional() &&
4241 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4242 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4243 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
Sanjoy Das55015d22015-10-02 23:09:44 +00004244 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4245 }
4246
4247 return nullptr;
4248}
4249
4250const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4251 if (const SCEV *S = createAddRecFromPHI(PN))
4252 return S;
4253
4254 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4255 return S;
Misha Brukman01808ca2005-04-21 21:13:18 +00004256
Dan Gohmana9c205c2010-02-25 06:57:05 +00004257 // If the PHI has a single incoming value, follow that value, unless the
4258 // PHI's incoming blocks are in a different loop, in which case doing so
4259 // risks breaking LCSSA form. Instcombine would normally zap these, but
4260 // it doesn't have DominatorTree information, so it may miss cases.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004261 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004262 if (LI.replacementPreservesLCSSAForm(PN, V))
Dan Gohmana9c205c2010-02-25 06:57:05 +00004263 return getSCEV(V);
Duncan Sands39d771312010-11-17 20:49:12 +00004264
Chris Lattnerd934c702004-04-02 20:23:17 +00004265 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanc8e23622009-04-21 23:15:49 +00004266 return getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00004267}
4268
Sanjoy Das55015d22015-10-02 23:09:44 +00004269const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4270 Value *Cond,
4271 Value *TrueVal,
4272 Value *FalseVal) {
Mehdi Amini044cb342015-10-07 18:14:25 +00004273 // Handle "constant" branch or select. This can occur for instance when a
4274 // loop pass transforms an inner loop and moves on to process the outer loop.
4275 if (auto *CI = dyn_cast<ConstantInt>(Cond))
4276 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4277
Sanjoy Dasd0671342015-10-02 19:39:59 +00004278 // Try to match some simple smax or umax patterns.
4279 auto *ICI = dyn_cast<ICmpInst>(Cond);
4280 if (!ICI)
4281 return getUnknown(I);
4282
4283 Value *LHS = ICI->getOperand(0);
4284 Value *RHS = ICI->getOperand(1);
4285
4286 switch (ICI->getPredicate()) {
4287 case ICmpInst::ICMP_SLT:
4288 case ICmpInst::ICMP_SLE:
4289 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004290 LLVM_FALLTHROUGH;
Sanjoy Dasd0671342015-10-02 19:39:59 +00004291 case ICmpInst::ICMP_SGT:
4292 case ICmpInst::ICMP_SGE:
4293 // a >s b ? a+x : b+x -> smax(a, b)+x
4294 // a >s b ? b+x : a+x -> smin(a, b)+x
4295 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4296 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4297 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4298 const SCEV *LA = getSCEV(TrueVal);
4299 const SCEV *RA = getSCEV(FalseVal);
4300 const SCEV *LDiff = getMinusSCEV(LA, LS);
4301 const SCEV *RDiff = getMinusSCEV(RA, RS);
4302 if (LDiff == RDiff)
4303 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4304 LDiff = getMinusSCEV(LA, RS);
4305 RDiff = getMinusSCEV(RA, LS);
4306 if (LDiff == RDiff)
4307 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4308 }
4309 break;
4310 case ICmpInst::ICMP_ULT:
4311 case ICmpInst::ICMP_ULE:
4312 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004313 LLVM_FALLTHROUGH;
Sanjoy Dasd0671342015-10-02 19:39:59 +00004314 case ICmpInst::ICMP_UGT:
4315 case ICmpInst::ICMP_UGE:
4316 // a >u b ? a+x : b+x -> umax(a, b)+x
4317 // a >u b ? b+x : a+x -> umin(a, b)+x
4318 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4319 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4320 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4321 const SCEV *LA = getSCEV(TrueVal);
4322 const SCEV *RA = getSCEV(FalseVal);
4323 const SCEV *LDiff = getMinusSCEV(LA, LS);
4324 const SCEV *RDiff = getMinusSCEV(RA, RS);
4325 if (LDiff == RDiff)
4326 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4327 LDiff = getMinusSCEV(LA, RS);
4328 RDiff = getMinusSCEV(RA, LS);
4329 if (LDiff == RDiff)
4330 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4331 }
4332 break;
4333 case ICmpInst::ICMP_NE:
4334 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4335 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4336 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4337 const SCEV *One = getOne(I->getType());
4338 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4339 const SCEV *LA = getSCEV(TrueVal);
4340 const SCEV *RA = getSCEV(FalseVal);
4341 const SCEV *LDiff = getMinusSCEV(LA, LS);
4342 const SCEV *RDiff = getMinusSCEV(RA, One);
4343 if (LDiff == RDiff)
4344 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4345 }
4346 break;
4347 case ICmpInst::ICMP_EQ:
4348 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4349 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4350 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4351 const SCEV *One = getOne(I->getType());
4352 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4353 const SCEV *LA = getSCEV(TrueVal);
4354 const SCEV *RA = getSCEV(FalseVal);
4355 const SCEV *LDiff = getMinusSCEV(LA, One);
4356 const SCEV *RDiff = getMinusSCEV(RA, LS);
4357 if (LDiff == RDiff)
4358 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4359 }
4360 break;
4361 default:
4362 break;
4363 }
4364
4365 return getUnknown(I);
4366}
4367
Sanjoy Dasf8570812016-05-29 00:38:22 +00004368/// Expand GEP instructions into add and multiply operations. This allows them
4369/// to be analyzed by regular SCEV code.
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004370const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman30f24fe2009-05-09 00:14:52 +00004371 // Don't attempt to analyze GEPs over unsized objects.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004372 if (!GEP->getSourceElementType()->isSized())
Dan Gohman30f24fe2009-05-09 00:14:52 +00004373 return getUnknown(GEP);
Matt Arsenault4c265902013-09-27 22:38:23 +00004374
Jingyue Wu2982d4d2015-05-18 17:03:25 +00004375 SmallVector<const SCEV *, 4> IndexExprs;
4376 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4377 IndexExprs.push_back(getSCEV(*Index));
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004378 return getGEPExpr(GEP->getSourceElementType(),
4379 getSCEV(GEP->getPointerOperand()),
4380 IndexExprs, GEP->isInBounds());
Dan Gohmanee750d12009-05-08 20:26:55 +00004381}
4382
Dan Gohmanc702fc02009-06-19 23:29:04 +00004383uint32_t
Dan Gohmanaf752342009-07-07 17:06:11 +00004384ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmana30370b2009-05-04 22:02:23 +00004385 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004386 return C->getAPInt().countTrailingZeros();
Chris Lattner49b090e2006-12-12 02:26:09 +00004387
Dan Gohmana30370b2009-05-04 22:02:23 +00004388 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanc702fc02009-06-19 23:29:04 +00004389 return std::min(GetMinTrailingZeros(T->getOperand()),
4390 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky3783b462007-11-22 07:59:40 +00004391
Dan Gohmana30370b2009-05-04 22:02:23 +00004392 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004393 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4394 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4395 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004396 }
4397
Dan Gohmana30370b2009-05-04 22:02:23 +00004398 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004399 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4400 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4401 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004402 }
4403
Dan Gohmana30370b2009-05-04 22:02:23 +00004404 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004405 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004406 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004407 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004408 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004409 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004410 }
4411
Dan Gohmana30370b2009-05-04 22:02:23 +00004412 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004413 // The result is the sum of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004414 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4415 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky3783b462007-11-22 07:59:40 +00004416 for (unsigned i = 1, e = M->getNumOperands();
4417 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004418 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky3783b462007-11-22 07:59:40 +00004419 BitWidth);
4420 return SumOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004421 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004422
Dan Gohmana30370b2009-05-04 22:02:23 +00004423 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004424 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004425 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004426 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004427 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004428 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004429 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004430
Dan Gohmana30370b2009-05-04 22:02:23 +00004431 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004432 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004433 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004434 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004435 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004436 return MinOpRes;
4437 }
4438
Dan Gohmana30370b2009-05-04 22:02:23 +00004439 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004440 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004441 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004442 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004443 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004444 return MinOpRes;
4445 }
4446
Dan Gohmanc702fc02009-06-19 23:29:04 +00004447 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4448 // For a SCEVUnknown, ask ValueTracking.
4449 unsigned BitWidth = getTypeSizeInBits(U->getType());
Dan Gohmanc702fc02009-06-19 23:29:04 +00004450 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004451 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
4452 nullptr, &DT);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004453 return Zeros.countTrailingOnes();
4454 }
4455
4456 // SCEVUDivExpr
Nick Lewycky3783b462007-11-22 07:59:40 +00004457 return 0;
Chris Lattner49b090e2006-12-12 02:26:09 +00004458}
Chris Lattnerd934c702004-04-02 20:23:17 +00004459
Sanjoy Dasf8570812016-05-29 00:38:22 +00004460/// Helper method to assign a range to V from metadata present in the IR.
Sanjoy Das1f05c512014-10-10 21:22:34 +00004461static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004462 if (Instruction *I = dyn_cast<Instruction>(V))
4463 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4464 return getConstantRangeFromMetadata(*MD);
Sanjoy Das1f05c512014-10-10 21:22:34 +00004465
4466 return None;
4467}
4468
Sanjoy Dasf8570812016-05-29 00:38:22 +00004469/// Determine the range for a particular SCEV. If SignHint is
Sanjoy Das91b54772015-03-09 21:43:43 +00004470/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4471/// with a "cleaner" unsigned (resp. signed) representation.
Dan Gohmane65c9172009-07-13 21:35:55 +00004472ConstantRange
Sanjoy Das91b54772015-03-09 21:43:43 +00004473ScalarEvolution::getRange(const SCEV *S,
4474 ScalarEvolution::RangeSignHint SignHint) {
4475 DenseMap<const SCEV *, ConstantRange> &Cache =
4476 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4477 : SignedRanges;
4478
Dan Gohman761065e2010-11-17 02:44:44 +00004479 // See if we've computed this range already.
Sanjoy Das91b54772015-03-09 21:43:43 +00004480 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4481 if (I != Cache.end())
Dan Gohman761065e2010-11-17 02:44:44 +00004482 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00004483
4484 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004485 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
Dan Gohmanc702fc02009-06-19 23:29:04 +00004486
Dan Gohman85be4332010-01-26 19:19:05 +00004487 unsigned BitWidth = getTypeSizeInBits(S->getType());
4488 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4489
Sanjoy Das91b54772015-03-09 21:43:43 +00004490 // If the value has known zeros, the maximum value will have those known zeros
4491 // as well.
Dan Gohman85be4332010-01-26 19:19:05 +00004492 uint32_t TZ = GetMinTrailingZeros(S);
Sanjoy Das91b54772015-03-09 21:43:43 +00004493 if (TZ != 0) {
4494 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4495 ConservativeResult =
4496 ConstantRange(APInt::getMinValue(BitWidth),
4497 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4498 else
4499 ConservativeResult = ConstantRange(
4500 APInt::getSignedMinValue(BitWidth),
4501 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4502 }
Dan Gohman85be4332010-01-26 19:19:05 +00004503
Dan Gohmane65c9172009-07-13 21:35:55 +00004504 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004505 ConstantRange X = getRange(Add->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004506 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004507 X = X.add(getRange(Add->getOperand(i), SignHint));
4508 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004509 }
4510
4511 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004512 ConstantRange X = getRange(Mul->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004513 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004514 X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4515 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004516 }
4517
4518 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004519 ConstantRange X = getRange(SMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004520 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004521 X = X.smax(getRange(SMax->getOperand(i), SignHint));
4522 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004523 }
4524
4525 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004526 ConstantRange X = getRange(UMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004527 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004528 X = X.umax(getRange(UMax->getOperand(i), SignHint));
4529 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004530 }
4531
4532 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004533 ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4534 ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4535 return setRange(UDiv, SignHint,
4536 ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004537 }
4538
4539 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004540 ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4541 return setRange(ZExt, SignHint,
4542 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004543 }
4544
4545 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004546 ConstantRange X = getRange(SExt->getOperand(), SignHint);
4547 return setRange(SExt, SignHint,
4548 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004549 }
4550
4551 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004552 ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4553 return setRange(Trunc, SignHint,
4554 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004555 }
4556
Dan Gohmane65c9172009-07-13 21:35:55 +00004557 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004558 // If there's no unsigned wrap, the value will never be less than its
4559 // initial value.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004560 if (AddRec->hasNoUnsignedWrap())
Dan Gohman51ad99d2010-01-21 02:09:26 +00004561 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanebbd05f2010-04-12 23:08:18 +00004562 if (!C->getValue()->isZero())
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004563 ConservativeResult = ConservativeResult.intersectWith(
4564 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004565
Dan Gohman51ad99d2010-01-21 02:09:26 +00004566 // If there's no signed wrap, and all the operands have the same sign or
4567 // zero, the value won't ever change sign.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004568 if (AddRec->hasNoSignedWrap()) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004569 bool AllNonNeg = true;
4570 bool AllNonPos = true;
4571 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4572 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4573 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4574 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004575 if (AllNonNeg)
Dan Gohman51aaf022010-01-26 04:40:18 +00004576 ConservativeResult = ConservativeResult.intersectWith(
4577 ConstantRange(APInt(BitWidth, 0),
4578 APInt::getSignedMinValue(BitWidth)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004579 else if (AllNonPos)
Dan Gohman51aaf022010-01-26 04:40:18 +00004580 ConservativeResult = ConservativeResult.intersectWith(
4581 ConstantRange(APInt::getSignedMinValue(BitWidth),
4582 APInt(BitWidth, 1)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004583 }
Dan Gohmane65c9172009-07-13 21:35:55 +00004584
4585 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00004586 if (AddRec->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00004587 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00004588 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4589 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Sanjoy Dasb765b632016-03-02 00:57:39 +00004590 auto RangeFromAffine = getRangeForAffineAR(
4591 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4592 BitWidth);
4593 if (!RangeFromAffine.isFullSet())
4594 ConservativeResult =
4595 ConservativeResult.intersectWith(RangeFromAffine);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004596
4597 auto RangeFromFactoring = getRangeViaFactoring(
4598 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4599 BitWidth);
4600 if (!RangeFromFactoring.isFullSet())
4601 ConservativeResult =
4602 ConservativeResult.intersectWith(RangeFromFactoring);
Dan Gohmand261d272009-06-24 01:05:09 +00004603 }
Dan Gohmand261d272009-06-24 01:05:09 +00004604 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004605
Sanjoy Das91b54772015-03-09 21:43:43 +00004606 return setRange(AddRec, SignHint, ConservativeResult);
Dan Gohmand261d272009-06-24 01:05:09 +00004607 }
4608
Dan Gohmanc702fc02009-06-19 23:29:04 +00004609 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00004610 // Check if the IR explicitly contains !range metadata.
4611 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4612 if (MDRange.hasValue())
4613 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4614
Sanjoy Das91b54772015-03-09 21:43:43 +00004615 // Split here to avoid paying the compile-time cost of calling both
4616 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
4617 // if needed.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004618 const DataLayout &DL = getDataLayout();
Sanjoy Das91b54772015-03-09 21:43:43 +00004619 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4620 // For a SCEVUnknown, ask ValueTracking.
4621 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004622 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
Sanjoy Das91b54772015-03-09 21:43:43 +00004623 if (Ones != ~Zeros + 1)
4624 ConservativeResult =
4625 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4626 } else {
4627 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4628 "generalize as needed!");
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004629 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004630 if (NS > 1)
4631 ConservativeResult = ConservativeResult.intersectWith(
4632 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4633 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
Sanjoy Das91b54772015-03-09 21:43:43 +00004634 }
4635
4636 return setRange(U, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004637 }
4638
Sanjoy Das91b54772015-03-09 21:43:43 +00004639 return setRange(S, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004640}
4641
Sanjoy Dasb765b632016-03-02 00:57:39 +00004642ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4643 const SCEV *Step,
4644 const SCEV *MaxBECount,
4645 unsigned BitWidth) {
4646 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4647 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4648 "Precondition!");
4649
4650 ConstantRange Result(BitWidth, /* isFullSet = */ true);
4651
4652 // Check for overflow. This must be done with ConstantRange arithmetic
4653 // because we could be called from within the ScalarEvolution overflow
4654 // checking code.
4655
4656 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4657 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4658 ConstantRange ZExtMaxBECountRange =
4659 MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1);
4660
4661 ConstantRange StepSRange = getSignedRange(Step);
4662 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1);
4663
4664 ConstantRange StartURange = getUnsignedRange(Start);
4665 ConstantRange EndURange =
4666 StartURange.add(MaxBECountRange.multiply(StepSRange));
4667
4668 // Check for unsigned overflow.
4669 ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1);
4670 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1);
4671 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4672 ZExtEndURange) {
4673 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(),
4674 EndURange.getUnsignedMin());
4675 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(),
4676 EndURange.getUnsignedMax());
4677 bool IsFullRange = Min.isMinValue() && Max.isMaxValue();
4678 if (!IsFullRange)
4679 Result =
4680 Result.intersectWith(ConstantRange(Min, Max + 1));
4681 }
4682
4683 ConstantRange StartSRange = getSignedRange(Start);
4684 ConstantRange EndSRange =
4685 StartSRange.add(MaxBECountRange.multiply(StepSRange));
4686
4687 // Check for signed overflow. This must be done with ConstantRange
4688 // arithmetic because we could be called from within the ScalarEvolution
4689 // overflow checking code.
4690 ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1);
4691 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1);
4692 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4693 SExtEndSRange) {
4694 APInt Min =
4695 APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin());
4696 APInt Max =
4697 APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax());
4698 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue();
4699 if (!IsFullRange)
4700 Result =
4701 Result.intersectWith(ConstantRange(Min, Max + 1));
4702 }
4703
4704 return Result;
4705}
4706
Sanjoy Dasbf730982016-03-02 00:57:54 +00004707ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4708 const SCEV *Step,
4709 const SCEV *MaxBECount,
4710 unsigned BitWidth) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004711 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4712 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4713
4714 struct SelectPattern {
4715 Value *Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004716 APInt TrueValue;
4717 APInt FalseValue;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004718
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004719 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4720 const SCEV *S) {
4721 Optional<unsigned> CastOp;
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004722 APInt Offset(BitWidth, 0);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004723
4724 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4725 "Should be!");
4726
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004727 // Peel off a constant offset:
4728 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4729 // In the future we could consider being smarter here and handle
4730 // {Start+Step,+,Step} too.
4731 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4732 return;
4733
4734 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4735 S = SA->getOperand(1);
4736 }
4737
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004738 // Peel off a cast operation
4739 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4740 CastOp = SCast->getSCEVType();
4741 S = SCast->getOperand();
4742 }
4743
Sanjoy Dasbf730982016-03-02 00:57:54 +00004744 using namespace llvm::PatternMatch;
4745
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004746 auto *SU = dyn_cast<SCEVUnknown>(S);
4747 const APInt *TrueVal, *FalseVal;
4748 if (!SU ||
4749 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4750 m_APInt(FalseVal)))) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004751 Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004752 return;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004753 }
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004754
4755 TrueValue = *TrueVal;
4756 FalseValue = *FalseVal;
4757
4758 // Re-apply the cast we peeled off earlier
4759 if (CastOp.hasValue())
4760 switch (*CastOp) {
4761 default:
4762 llvm_unreachable("Unknown SCEV cast type!");
4763
4764 case scTruncate:
4765 TrueValue = TrueValue.trunc(BitWidth);
4766 FalseValue = FalseValue.trunc(BitWidth);
4767 break;
4768 case scZeroExtend:
4769 TrueValue = TrueValue.zext(BitWidth);
4770 FalseValue = FalseValue.zext(BitWidth);
4771 break;
4772 case scSignExtend:
4773 TrueValue = TrueValue.sext(BitWidth);
4774 FalseValue = FalseValue.sext(BitWidth);
4775 break;
4776 }
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004777
4778 // Re-apply the constant offset we peeled off earlier
4779 TrueValue += Offset;
4780 FalseValue += Offset;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004781 }
4782
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004783 bool isRecognized() { return Condition != nullptr; }
Sanjoy Dasbf730982016-03-02 00:57:54 +00004784 };
4785
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004786 SelectPattern StartPattern(*this, BitWidth, Start);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004787 if (!StartPattern.isRecognized())
4788 return ConstantRange(BitWidth, /* isFullSet = */ true);
4789
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004790 SelectPattern StepPattern(*this, BitWidth, Step);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004791 if (!StepPattern.isRecognized())
4792 return ConstantRange(BitWidth, /* isFullSet = */ true);
4793
4794 if (StartPattern.Condition != StepPattern.Condition) {
4795 // We don't handle this case today; but we could, by considering four
4796 // possibilities below instead of two. I'm not sure if there are cases where
4797 // that will help over what getRange already does, though.
4798 return ConstantRange(BitWidth, /* isFullSet = */ true);
4799 }
4800
4801 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4802 // construct arbitrary general SCEV expressions here. This function is called
4803 // from deep in the call stack, and calling getSCEV (on a sext instruction,
4804 // say) can end up caching a suboptimal value.
4805
Sanjoy Das6b017a12016-03-02 02:56:29 +00004806 // FIXME: without the explicit `this` receiver below, MSVC errors out with
4807 // C2352 and C2512 (otherwise it isn't needed).
4808
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004809 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004810 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004811 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004812 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
Sanjoy Das62a1c332016-03-02 02:15:42 +00004813
Sanjoy Das1168f932016-03-02 02:34:20 +00004814 ConstantRange TrueRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004815 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
Sanjoy Das1168f932016-03-02 02:34:20 +00004816 ConstantRange FalseRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004817 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004818
4819 return TrueRange.unionWith(FalseRange);
4820}
4821
Jingyue Wu42f1d672015-07-28 18:22:40 +00004822SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004823 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004824 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4825
4826 // Return early if there are no flags to propagate to the SCEV.
4827 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4828 if (BinOp->hasNoUnsignedWrap())
4829 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4830 if (BinOp->hasNoSignedWrap())
4831 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004832 if (Flags == SCEV::FlagAnyWrap)
Jingyue Wu42f1d672015-07-28 18:22:40 +00004833 return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004834
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004835 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
4836}
4837
4838bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
4839 // Here we check that I is in the header of the innermost loop containing I,
4840 // since we only deal with instructions in the loop header. The actual loop we
4841 // need to check later will come from an add recurrence, but getting that
4842 // requires computing the SCEV of the operands, which can be expensive. This
4843 // check we can do cheaply to rule out some cases early.
4844 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004845 if (InnermostContainingLoop == nullptr ||
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004846 InnermostContainingLoop->getHeader() != I->getParent())
4847 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004848
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004849 // Only proceed if we can prove that I does not yield poison.
4850 if (!isKnownNotFullPoison(I)) return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004851
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004852 // At this point we know that if I is executed, then it does not wrap
4853 // according to at least one of NSW or NUW. If I is not executed, then we do
4854 // not know if the calculation that I represents would wrap. Multiple
4855 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
Jingyue Wu42f1d672015-07-28 18:22:40 +00004856 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4857 // derived from other instructions that map to the same SCEV. We cannot make
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004858 // that guarantee for cases where I is not executed. So we need to find the
4859 // loop that I is considered in relation to and prove that I is executed for
4860 // every iteration of that loop. That implies that the value that I
Jingyue Wu42f1d672015-07-28 18:22:40 +00004861 // calculates does not wrap anywhere in the loop, so then we can apply the
4862 // flags to the SCEV.
4863 //
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004864 // We check isLoopInvariant to disambiguate in case we are adding recurrences
4865 // from different loops, so that we know which loop to prove that I is
4866 // executed in.
4867 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
Hans Wennborg38790352016-08-17 22:50:18 +00004868 // I could be an extractvalue from a call to an overflow intrinsic.
4869 // TODO: We can do better here in some cases.
4870 if (!isSCEVable(I->getOperand(OpIndex)->getType()))
4871 return false;
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004872 const SCEV *Op = getSCEV(I->getOperand(OpIndex));
Jingyue Wu42f1d672015-07-28 18:22:40 +00004873 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004874 bool AllOtherOpsLoopInvariant = true;
4875 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
4876 ++OtherOpIndex) {
4877 if (OtherOpIndex != OpIndex) {
4878 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
4879 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
4880 AllOtherOpsLoopInvariant = false;
4881 break;
4882 }
4883 }
4884 }
4885 if (AllOtherOpsLoopInvariant &&
4886 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
4887 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004888 }
4889 }
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004890 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004891}
4892
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004893bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
4894 // If we know that \c I can never be poison period, then that's enough.
4895 if (isSCEVExprNeverPoison(I))
4896 return true;
4897
4898 // For an add recurrence specifically, we assume that infinite loops without
4899 // side effects are undefined behavior, and then reason as follows:
4900 //
4901 // If the add recurrence is poison in any iteration, it is poison on all
4902 // future iterations (since incrementing poison yields poison). If the result
4903 // of the add recurrence is fed into the loop latch condition and the loop
4904 // does not contain any throws or exiting blocks other than the latch, we now
4905 // have the ability to "choose" whether the backedge is taken or not (by
4906 // choosing a sufficiently evil value for the poison feeding into the branch)
4907 // for every iteration including and after the one in which \p I first became
4908 // poison. There are two possibilities (let's call the iteration in which \p
4909 // I first became poison as K):
4910 //
4911 // 1. In the set of iterations including and after K, the loop body executes
4912 // no side effects. In this case executing the backege an infinte number
4913 // of times will yield undefined behavior.
4914 //
4915 // 2. In the set of iterations including and after K, the loop body executes
4916 // at least one side effect. In this case, that specific instance of side
4917 // effect is control dependent on poison, which also yields undefined
4918 // behavior.
4919
4920 auto *ExitingBB = L->getExitingBlock();
4921 auto *LatchBB = L->getLoopLatch();
4922 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
4923 return false;
4924
4925 SmallPtrSet<const Instruction *, 16> Pushed;
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004926 SmallVector<const Instruction *, 8> PoisonStack;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004927
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004928 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
4929 // things that are known to be fully poison under that assumption go on the
4930 // PoisonStack.
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004931 Pushed.insert(I);
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004932 PoisonStack.push_back(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004933
4934 bool LatchControlDependentOnPoison = false;
Sanjoy Das2401c982016-06-08 17:48:46 +00004935 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004936 const Instruction *Poison = PoisonStack.pop_back_val();
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004937
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004938 for (auto *PoisonUser : Poison->users()) {
4939 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
4940 if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
4941 PoisonStack.push_back(cast<Instruction>(PoisonUser));
4942 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004943 assert(BI->isConditional() && "Only possibility!");
4944 if (BI->getParent() == LatchBB) {
4945 LatchControlDependentOnPoison = true;
4946 break;
4947 }
4948 }
4949 }
4950 }
4951
Sanjoy Das97cd7d52016-06-09 01:13:54 +00004952 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
4953}
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004954
Sanjoy Das5603fc02016-09-26 02:44:07 +00004955ScalarEvolution::LoopProperties
4956ScalarEvolution::getLoopProperties(const Loop *L) {
4957 typedef ScalarEvolution::LoopProperties LoopProperties;
David L Kreitzer8bbabee2016-09-16 14:38:13 +00004958
Sanjoy Das5603fc02016-09-26 02:44:07 +00004959 auto Itr = LoopPropertiesCache.find(L);
4960 if (Itr == LoopPropertiesCache.end()) {
4961 auto HasSideEffects = [](Instruction *I) {
4962 if (auto *SI = dyn_cast<StoreInst>(I))
4963 return !SI->isSimple();
4964
4965 return I->mayHaveSideEffects();
David L Kreitzer8bbabee2016-09-16 14:38:13 +00004966 };
4967
Sanjoy Das5603fc02016-09-26 02:44:07 +00004968 LoopProperties LP = {/* HasNoAbnormalExits */ true,
4969 /*HasNoSideEffects*/ true};
David L Kreitzer8bbabee2016-09-16 14:38:13 +00004970
Sanjoy Das5603fc02016-09-26 02:44:07 +00004971 for (auto *BB : L->getBlocks())
4972 for (auto &I : *BB) {
4973 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
4974 LP.HasNoAbnormalExits = false;
4975 if (HasSideEffects(&I))
4976 LP.HasNoSideEffects = false;
4977 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
4978 break; // We're already as pessimistic as we can get.
4979 }
David L Kreitzer8bbabee2016-09-16 14:38:13 +00004980
Sanjoy Das5603fc02016-09-26 02:44:07 +00004981 auto InsertPair = LoopPropertiesCache.insert({L, LP});
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004982 assert(InsertPair.second && "We just checked!");
4983 Itr = InsertPair.first;
4984 }
4985
Sanjoy Das97cd7d52016-06-09 01:13:54 +00004986 return Itr->second;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004987}
4988
Dan Gohmanaf752342009-07-07 17:06:11 +00004989const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00004990 if (!isSCEVable(V->getType()))
Dan Gohmanc8e23622009-04-21 23:15:49 +00004991 return getUnknown(V);
Dan Gohman0a40ad92009-04-16 03:18:22 +00004992
Dan Gohman69451a02010-03-09 23:46:50 +00004993 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman69451a02010-03-09 23:46:50 +00004994 // Don't attempt to analyze instructions in blocks that aren't
4995 // reachable. Such instructions don't matter, and they aren't required
4996 // to obey basic rules for definitions dominating uses which this
4997 // analysis depends on.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004998 if (!DT.isReachableFromEntry(I->getParent()))
Dan Gohman69451a02010-03-09 23:46:50 +00004999 return getUnknown(V);
Sanjoy Das260ad4d2016-03-29 16:40:39 +00005000 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohmanf436bac2009-06-24 00:54:57 +00005001 return getConstant(CI);
5002 else if (isa<ConstantPointerNull>(V))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005003 return getZero(V->getType());
Dan Gohmanf161e06e2009-08-25 17:49:57 +00005004 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Sanjoy Das5ce32722016-04-08 00:48:30 +00005005 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
Sanjoy Das260ad4d2016-03-29 16:40:39 +00005006 else if (!isa<ConstantExpr>(V))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005007 return getUnknown(V);
Chris Lattnera3e0bb42007-04-02 05:41:38 +00005008
Dan Gohman80ca01c2009-07-17 20:47:02 +00005009 Operator *U = cast<Operator>(V);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005010 if (auto BO = MatchBinaryOp(U, DT)) {
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005011 switch (BO->Opcode) {
5012 case Instruction::Add: {
5013 // The simple thing to do would be to just call getSCEV on both operands
5014 // and call getAddExpr with the result. However if we're looking at a
5015 // bunch of things all added together, this can be quite inefficient,
5016 // because it leads to N-1 getAddExpr calls for N ultimate operands.
5017 // Instead, gather up all the operands and make a single getAddExpr call.
5018 // LLVM IR canonical form means we need only traverse the left operands.
5019 SmallVector<const SCEV *, 4> AddOps;
5020 do {
5021 if (BO->Op) {
5022 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5023 AddOps.push_back(OpSCEV);
5024 break;
5025 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00005026
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005027 // If a NUW or NSW flag can be applied to the SCEV for this
5028 // addition, then compute the SCEV for this addition by itself
5029 // with a separate call to getAddExpr. We need to do that
5030 // instead of pushing the operands of the addition onto AddOps,
5031 // since the flags are only known to apply to this particular
5032 // addition - they may not apply to other additions that can be
5033 // formed with operands from AddOps.
5034 const SCEV *RHS = getSCEV(BO->RHS);
5035 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5036 if (Flags != SCEV::FlagAnyWrap) {
5037 const SCEV *LHS = getSCEV(BO->LHS);
5038 if (BO->Opcode == Instruction::Sub)
5039 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5040 else
5041 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5042 break;
5043 }
Dan Gohman36bad002009-09-17 18:05:20 +00005044 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005045
5046 if (BO->Opcode == Instruction::Sub)
5047 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5048 else
5049 AddOps.push_back(getSCEV(BO->RHS));
5050
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005051 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005052 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5053 NewBO->Opcode != Instruction::Sub)) {
5054 AddOps.push_back(getSCEV(BO->LHS));
5055 break;
5056 }
5057 BO = NewBO;
5058 } while (true);
5059
5060 return getAddExpr(AddOps);
5061 }
5062
5063 case Instruction::Mul: {
5064 SmallVector<const SCEV *, 4> MulOps;
5065 do {
5066 if (BO->Op) {
5067 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5068 MulOps.push_back(OpSCEV);
5069 break;
5070 }
5071
5072 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5073 if (Flags != SCEV::FlagAnyWrap) {
5074 MulOps.push_back(
5075 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5076 break;
5077 }
5078 }
5079
5080 MulOps.push_back(getSCEV(BO->RHS));
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005081 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005082 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5083 MulOps.push_back(getSCEV(BO->LHS));
5084 break;
5085 }
NAKAMURA Takumi940cd932016-07-04 01:26:21 +00005086 BO = NewBO;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005087 } while (true);
5088
5089 return getMulExpr(MulOps);
5090 }
5091 case Instruction::UDiv:
5092 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5093 case Instruction::Sub: {
5094 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5095 if (BO->Op)
5096 Flags = getNoWrapFlagsFromUB(BO->Op);
5097 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5098 }
5099 case Instruction::And:
5100 // For an expression like x&255 that merely masks off the high bits,
5101 // use zext(trunc(x)) as the SCEV expression.
5102 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5103 if (CI->isNullValue())
5104 return getSCEV(BO->RHS);
5105 if (CI->isAllOnesValue())
5106 return getSCEV(BO->LHS);
5107 const APInt &A = CI->getValue();
5108
5109 // Instcombine's ShrinkDemandedConstant may strip bits out of
5110 // constants, obscuring what would otherwise be a low-bits mask.
5111 // Use computeKnownBits to compute what ShrinkDemandedConstant
5112 // knew about to reconstruct a low-bits mask value.
5113 unsigned LZ = A.countLeadingZeros();
5114 unsigned TZ = A.countTrailingZeros();
5115 unsigned BitWidth = A.getBitWidth();
5116 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5117 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(),
5118 0, &AC, nullptr, &DT);
5119
5120 APInt EffectiveMask =
5121 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5122 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
5123 const SCEV *MulCount = getConstant(ConstantInt::get(
5124 getContext(), APInt::getOneBitSet(BitWidth, TZ)));
5125 return getMulExpr(
5126 getZeroExtendExpr(
5127 getTruncateExpr(
5128 getUDivExactExpr(getSCEV(BO->LHS), MulCount),
5129 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5130 BO->LHS->getType()),
5131 MulCount);
5132 }
Dan Gohman36bad002009-09-17 18:05:20 +00005133 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005134 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005135
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005136 case Instruction::Or:
5137 // If the RHS of the Or is a constant, we may have something like:
5138 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
5139 // optimizations will transparently handle this case.
5140 //
5141 // In order for this transformation to be safe, the LHS must be of the
5142 // form X*(2^n) and the Or constant must be less than 2^n.
5143 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5144 const SCEV *LHS = getSCEV(BO->LHS);
5145 const APInt &CIVal = CI->getValue();
5146 if (GetMinTrailingZeros(LHS) >=
5147 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5148 // Build a plain add SCEV.
5149 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5150 // If the LHS of the add was an addrec and it has no-wrap flags,
5151 // transfer the no-wrap flags, since an or won't introduce a wrap.
5152 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5153 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5154 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5155 OldAR->getNoWrapFlags());
5156 }
5157 return S;
5158 }
5159 }
5160 break;
Dan Gohman6350296e2009-05-18 16:29:04 +00005161
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005162 case Instruction::Xor:
5163 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5164 // If the RHS of xor is -1, then this is a not operation.
5165 if (CI->isAllOnesValue())
5166 return getNotSCEV(getSCEV(BO->LHS));
Dan Gohmaneddf7712009-06-18 00:00:20 +00005167
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005168 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5169 // This is a variant of the check for xor with -1, and it handles
5170 // the case where instcombine has trimmed non-demanded bits out
5171 // of an xor with -1.
5172 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5173 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5174 if (LBO->getOpcode() == Instruction::And &&
5175 LCI->getValue() == CI->getValue())
5176 if (const SCEVZeroExtendExpr *Z =
5177 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5178 Type *UTy = BO->LHS->getType();
5179 const SCEV *Z0 = Z->getOperand();
5180 Type *Z0Ty = Z0->getType();
5181 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
Dan Gohmaneddf7712009-06-18 00:00:20 +00005182
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005183 // If C is a low-bits mask, the zero extend is serving to
5184 // mask off the high bits. Complement the operand and
5185 // re-apply the zext.
5186 if (APIntOps::isMask(Z0TySize, CI->getValue()))
5187 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5188
5189 // If C is a single bit, it may be in the sign-bit position
5190 // before the zero-extend. In this case, represent the xor
5191 // using an add, which is equivalent, and re-apply the zext.
5192 APInt Trunc = CI->getValue().trunc(Z0TySize);
5193 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5194 Trunc.isSignBit())
5195 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5196 UTy);
5197 }
5198 }
5199 break;
Dan Gohman05e89732008-06-22 19:56:46 +00005200
5201 case Instruction::Shl:
5202 // Turn shift left of a constant amount into a multiply.
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005203 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5204 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00005205
5206 // If the shift count is not less than the bitwidth, the result of
5207 // the shift is undefined. Don't try to analyze it, because the
5208 // resolution chosen here may differ from the resolution chosen in
5209 // other parts of the compiler.
5210 if (SA->getValue().uge(BitWidth))
5211 break;
5212
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005213 // It is currently not resolved how to interpret NSW for left
5214 // shift by BitWidth - 1, so we avoid applying flags in that
5215 // case. Remove this check (or this comment) once the situation
5216 // is resolved. See
5217 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5218 // and http://reviews.llvm.org/D8890 .
5219 auto Flags = SCEV::FlagAnyWrap;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005220 if (BO->Op && SA->getValue().ult(BitWidth - 1))
5221 Flags = getNoWrapFlagsFromUB(BO->Op);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005222
Owen Andersonedb4a702009-07-24 23:12:02 +00005223 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00005224 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005225 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
Dan Gohman05e89732008-06-22 19:56:46 +00005226 }
5227 break;
5228
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005229 case Instruction::AShr:
5230 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
5231 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS))
5232 if (Operator *L = dyn_cast<Operator>(BO->LHS))
5233 if (L->getOpcode() == Instruction::Shl &&
5234 L->getOperand(1) == BO->RHS) {
5235 uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType());
Dan Gohmanacd700a2010-04-22 01:35:11 +00005236
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005237 // If the shift count is not less than the bitwidth, the result of
5238 // the shift is undefined. Don't try to analyze it, because the
5239 // resolution chosen here may differ from the resolution chosen in
5240 // other parts of the compiler.
5241 if (CI->getValue().uge(BitWidth))
5242 break;
Dan Gohmanacd700a2010-04-22 01:35:11 +00005243
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005244 uint64_t Amt = BitWidth - CI->getZExtValue();
5245 if (Amt == BitWidth)
5246 return getSCEV(L->getOperand(0)); // shift by zero --> noop
5247 return getSignExtendExpr(
5248 getTruncateExpr(getSCEV(L->getOperand(0)),
5249 IntegerType::get(getContext(), Amt)),
5250 BO->LHS->getType());
5251 }
5252 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005253 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005254 }
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005255
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005256 switch (U->getOpcode()) {
Dan Gohman05e89732008-06-22 19:56:46 +00005257 case Instruction::Trunc:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005258 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005259
5260 case Instruction::ZExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005261 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005262
5263 case Instruction::SExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005264 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005265
5266 case Instruction::BitCast:
5267 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00005268 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman05e89732008-06-22 19:56:46 +00005269 return getSCEV(U->getOperand(0));
5270 break;
5271
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00005272 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5273 // lead to pointer expressions which cannot safely be expanded to GEPs,
5274 // because ScalarEvolution doesn't respect the GEP aliasing rules when
5275 // simplifying integer expressions.
Dan Gohman0a40ad92009-04-16 03:18:22 +00005276
Dan Gohmanee750d12009-05-08 20:26:55 +00005277 case Instruction::GetElementPtr:
Dan Gohmanb256ccf2009-12-18 02:09:29 +00005278 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman0a40ad92009-04-16 03:18:22 +00005279
Dan Gohman05e89732008-06-22 19:56:46 +00005280 case Instruction::PHI:
5281 return createNodeForPHI(cast<PHINode>(U));
5282
5283 case Instruction::Select:
Sanjoy Dasd0671342015-10-02 19:39:59 +00005284 // U can also be a select constant expr, which let fall through. Since
5285 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5286 // constant expressions cannot have instructions as operands, we'd have
5287 // returned getUnknown for a select constant expressions anyway.
5288 if (isa<Instruction>(U))
Sanjoy Das55015d22015-10-02 23:09:44 +00005289 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5290 U->getOperand(1), U->getOperand(2));
Hal Finkele186deb2016-07-11 02:48:23 +00005291 break;
5292
5293 case Instruction::Call:
5294 case Instruction::Invoke:
5295 if (Value *RV = CallSite(U).getReturnedArgOperand())
5296 return getSCEV(RV);
5297 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00005298 }
5299
Dan Gohmanc8e23622009-04-21 23:15:49 +00005300 return getUnknown(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00005301}
5302
5303
5304
5305//===----------------------------------------------------------------------===//
5306// Iteration Count Computation Code
5307//
5308
Chandler Carruth6666c272014-10-11 00:12:11 +00005309unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
5310 if (BasicBlock *ExitingBB = L->getExitingBlock())
5311 return getSmallConstantTripCount(L, ExitingBB);
5312
5313 // No trip count information for multiple exits.
5314 return 0;
5315}
5316
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005317unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
5318 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005319 assert(ExitingBlock && "Must pass a non-null exiting block!");
5320 assert(L->isLoopExiting(ExitingBlock) &&
5321 "Exiting block must actually branch out of the loop!");
Andrew Trick2b6860f2011-08-11 23:36:16 +00005322 const SCEVConstant *ExitCount =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005323 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005324 if (!ExitCount)
5325 return 0;
5326
5327 ConstantInt *ExitConst = ExitCount->getValue();
5328
5329 // Guard against huge trip counts.
5330 if (ExitConst->getValue().getActiveBits() > 32)
5331 return 0;
5332
5333 // In case of integer overflow, this returns 0, which is correct.
5334 return ((unsigned)ExitConst->getZExtValue()) + 1;
5335}
5336
Chandler Carruth6666c272014-10-11 00:12:11 +00005337unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
5338 if (BasicBlock *ExitingBB = L->getExitingBlock())
5339 return getSmallConstantTripMultiple(L, ExitingBB);
5340
5341 // No trip multiple information for multiple exits.
5342 return 0;
5343}
5344
Sanjoy Dasf8570812016-05-29 00:38:22 +00005345/// Returns the largest constant divisor of the trip count of this loop as a
5346/// normal unsigned value, if possible. This means that the actual trip count is
5347/// always a multiple of the returned value (don't forget the trip count could
5348/// very well be zero as well!).
Andrew Trick2b6860f2011-08-11 23:36:16 +00005349///
5350/// Returns 1 if the trip count is unknown or not guaranteed to be the
5351/// multiple of a constant (which is also the case if the trip count is simply
5352/// constant, use getSmallConstantTripCount for that case), Will also return 1
5353/// if the trip count is very large (>= 2^32).
Andrew Tricke81211f2012-01-11 06:52:55 +00005354///
5355/// As explained in the comments for getSmallConstantTripCount, this assumes
5356/// that control exits the loop via ExitingBlock.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005357unsigned
5358ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
5359 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005360 assert(ExitingBlock && "Must pass a non-null exiting block!");
5361 assert(L->isLoopExiting(ExitingBlock) &&
5362 "Exiting block must actually branch out of the loop!");
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005363 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +00005364 if (ExitCount == getCouldNotCompute())
5365 return 1;
5366
5367 // Get the trip count from the BE count by adding 1.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005368 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType()));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005369 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
5370 // to factor simple cases.
5371 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
5372 TCMul = Mul->getOperand(0);
5373
5374 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
5375 if (!MulC)
5376 return 1;
5377
5378 ConstantInt *Result = MulC->getValue();
5379
Hal Finkel30bd9342012-10-24 19:46:44 +00005380 // Guard against huge trip counts (this requires checking
5381 // for zero to handle the case where the trip count == -1 and the
5382 // addition wraps).
5383 if (!Result || Result->getValue().getActiveBits() > 32 ||
5384 Result->getValue().getActiveBits() == 0)
Andrew Trick2b6860f2011-08-11 23:36:16 +00005385 return 1;
5386
5387 return (unsigned)Result->getZExtValue();
5388}
5389
Sanjoy Dasf8570812016-05-29 00:38:22 +00005390/// Get the expression for the number of loop iterations for which this loop is
5391/// guaranteed not to exit via ExitingBlock. Otherwise return
5392/// SCEVCouldNotCompute.
Andrew Trick77c55422011-08-02 04:23:35 +00005393const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
5394 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005395}
5396
Silviu Baranga6f444df2016-04-08 14:29:09 +00005397const SCEV *
5398ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5399 SCEVUnionPredicate &Preds) {
5400 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5401}
5402
Dan Gohmanaf752342009-07-07 17:06:11 +00005403const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005404 return getBackedgeTakenInfo(L).getExact(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005405}
5406
Sanjoy Dasf8570812016-05-29 00:38:22 +00005407/// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5408/// known never to be less than the actual backedge taken count.
Dan Gohmanaf752342009-07-07 17:06:11 +00005409const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005410 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005411}
5412
Sanjoy Dasf8570812016-05-29 00:38:22 +00005413/// Push PHI nodes in the header of the given loop onto the given Worklist.
Dan Gohmandc191042009-07-08 19:23:34 +00005414static void
5415PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5416 BasicBlock *Header = L->getHeader();
5417
5418 // Push all Loop-header PHIs onto the Worklist stack.
5419 for (BasicBlock::iterator I = Header->begin();
5420 PHINode *PN = dyn_cast<PHINode>(I); ++I)
5421 Worklist.push_back(PN);
5422}
5423
Dan Gohman2b8da352009-04-30 20:47:05 +00005424const ScalarEvolution::BackedgeTakenInfo &
Silviu Baranga6f444df2016-04-08 14:29:09 +00005425ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5426 auto &BTI = getBackedgeTakenInfo(L);
5427 if (BTI.hasFullInfo())
5428 return BTI;
5429
5430 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5431
5432 if (!Pair.second)
5433 return Pair.first->second;
5434
5435 BackedgeTakenInfo Result =
5436 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5437
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005438 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
Silviu Baranga6f444df2016-04-08 14:29:09 +00005439}
5440
5441const ScalarEvolution::BackedgeTakenInfo &
Dan Gohman2b8da352009-04-30 20:47:05 +00005442ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005443 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman8b0a4192010-03-01 17:49:51 +00005444 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman76466372009-04-27 20:16:15 +00005445 // update the value. The temporary CouldNotCompute value tells SCEV
5446 // code elsewhere that it shouldn't attempt to request a new
5447 // backedge-taken count, which could result in infinite recursion.
Dan Gohman0daf6872011-05-09 18:44:09 +00005448 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00005449 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
Chris Lattnera337f5e2011-01-09 02:16:18 +00005450 if (!Pair.second)
5451 return Pair.first->second;
Dan Gohman76466372009-04-27 20:16:15 +00005452
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005453 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
Andrew Trick3ca3f982011-07-26 17:19:55 +00005454 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5455 // must be cleared in this scope.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005456 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005457
5458 if (Result.getExact(this) != getCouldNotCompute()) {
5459 assert(isLoopInvariant(Result.getExact(this), L) &&
5460 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnera337f5e2011-01-09 02:16:18 +00005461 "Computed backedge-taken count isn't loop invariant for loop!");
5462 ++NumTripCountsComputed;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005463 }
5464 else if (Result.getMax(this) == getCouldNotCompute() &&
5465 isa<PHINode>(L->getHeader()->begin())) {
5466 // Only count loops that have phi nodes as not being computable.
5467 ++NumTripCountsNotComputed;
Chris Lattnera337f5e2011-01-09 02:16:18 +00005468 }
Dan Gohman2b8da352009-04-30 20:47:05 +00005469
Chris Lattnera337f5e2011-01-09 02:16:18 +00005470 // Now that we know more about the trip count for this loop, forget any
5471 // existing SCEV values for PHI nodes in this loop since they are only
5472 // conservative estimates made without the benefit of trip count
5473 // information. This is similar to the code in forgetLoop, except that
5474 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005475 if (Result.hasAnyInfo()) {
Chris Lattnera337f5e2011-01-09 02:16:18 +00005476 SmallVector<Instruction *, 16> Worklist;
5477 PushLoopPHIs(L, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005478
Chris Lattnera337f5e2011-01-09 02:16:18 +00005479 SmallPtrSet<Instruction *, 8> Visited;
5480 while (!Worklist.empty()) {
5481 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005482 if (!Visited.insert(I).second)
5483 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005484
Chris Lattnera337f5e2011-01-09 02:16:18 +00005485 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005486 ValueExprMap.find_as(static_cast<Value *>(I));
Chris Lattnera337f5e2011-01-09 02:16:18 +00005487 if (It != ValueExprMap.end()) {
5488 const SCEV *Old = It->second;
Dan Gohman761065e2010-11-17 02:44:44 +00005489
Chris Lattnera337f5e2011-01-09 02:16:18 +00005490 // SCEVUnknown for a PHI either means that it has an unrecognized
5491 // structure, or it's a PHI that's in the progress of being computed
5492 // by createNodeForPHI. In the former case, additional loop trip
5493 // count information isn't going to change anything. In the later
5494 // case, createNodeForPHI will perform the necessary updates on its
5495 // own when it gets to that point.
5496 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
Wei Mi785858c2016-08-09 20:37:50 +00005497 eraseValueFromMap(It->first);
Chris Lattnera337f5e2011-01-09 02:16:18 +00005498 forgetMemoizedResults(Old);
Dan Gohmandc191042009-07-08 19:23:34 +00005499 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005500 if (PHINode *PN = dyn_cast<PHINode>(I))
5501 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmandc191042009-07-08 19:23:34 +00005502 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005503
5504 PushDefUseChildren(I, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005505 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005506 }
Dan Gohman6acd95b2011-04-25 22:48:29 +00005507
5508 // Re-lookup the insert position, since the call to
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005509 // computeBackedgeTakenCount above could result in a
Dan Gohman6acd95b2011-04-25 22:48:29 +00005510 // recusive call to getBackedgeTakenInfo (on a different
5511 // loop), which would invalidate the iterator computed
5512 // earlier.
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005513 return BackedgeTakenCounts.find(L)->second = std::move(Result);
Chris Lattnerd934c702004-04-02 20:23:17 +00005514}
5515
Dan Gohman880c92a2009-10-31 15:04:55 +00005516void ScalarEvolution::forgetLoop(const Loop *L) {
5517 // Drop any stored trip count value.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005518 auto RemoveLoopFromBackedgeMap =
5519 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5520 auto BTCPos = Map.find(L);
5521 if (BTCPos != Map.end()) {
5522 BTCPos->second.clear();
5523 Map.erase(BTCPos);
5524 }
5525 };
5526
5527 RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5528 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohmanf1505722009-05-02 17:43:35 +00005529
Dan Gohman880c92a2009-10-31 15:04:55 +00005530 // Drop information about expressions based on loop-header PHIs.
Dan Gohman48f82222009-05-04 22:30:44 +00005531 SmallVector<Instruction *, 16> Worklist;
Dan Gohmandc191042009-07-08 19:23:34 +00005532 PushLoopPHIs(L, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005533
Dan Gohmandc191042009-07-08 19:23:34 +00005534 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00005535 while (!Worklist.empty()) {
5536 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005537 if (!Visited.insert(I).second)
5538 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005539
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005540 ValueExprMapType::iterator It =
5541 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005542 if (It != ValueExprMap.end()) {
Wei Mi785858c2016-08-09 20:37:50 +00005543 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00005544 forgetMemoizedResults(It->second);
Dan Gohmandc191042009-07-08 19:23:34 +00005545 if (PHINode *PN = dyn_cast<PHINode>(I))
5546 ConstantEvolutionLoopExitValue.erase(PN);
5547 }
5548
5549 PushDefUseChildren(I, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005550 }
Dan Gohmandcb354b2010-10-29 20:16:10 +00005551
5552 // Forget all contained loops too, to avoid dangling entries in the
5553 // ValuesAtScopes map.
Benjamin Krameraa209152016-06-26 17:27:42 +00005554 for (Loop *I : *L)
5555 forgetLoop(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005556
Sanjoy Das5603fc02016-09-26 02:44:07 +00005557 LoopPropertiesCache.erase(L);
Dan Gohman43300342009-02-17 20:49:49 +00005558}
5559
Eric Christopheref6d5932010-07-29 01:25:38 +00005560void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005561 Instruction *I = dyn_cast<Instruction>(V);
5562 if (!I) return;
5563
5564 // Drop information about expressions based on loop-header PHIs.
5565 SmallVector<Instruction *, 16> Worklist;
5566 Worklist.push_back(I);
5567
5568 SmallPtrSet<Instruction *, 8> Visited;
5569 while (!Worklist.empty()) {
5570 I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005571 if (!Visited.insert(I).second)
5572 continue;
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005573
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005574 ValueExprMapType::iterator It =
5575 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005576 if (It != ValueExprMap.end()) {
Wei Mi785858c2016-08-09 20:37:50 +00005577 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00005578 forgetMemoizedResults(It->second);
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005579 if (PHINode *PN = dyn_cast<PHINode>(I))
5580 ConstantEvolutionLoopExitValue.erase(PN);
5581 }
5582
5583 PushDefUseChildren(I, Worklist);
5584 }
5585}
5586
Sanjoy Dasf8570812016-05-29 00:38:22 +00005587/// Get the exact loop backedge taken count considering all loop exits. A
5588/// computable result can only be returned for loops with a single exit.
5589/// Returning the minimum taken count among all exits is incorrect because one
5590/// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5591/// the limit of each loop test is never skipped. This is a valid assumption as
5592/// long as the loop exits via that test. For precise results, it is the
5593/// caller's responsibility to specify the relevant loop exit using
Andrew Trick90c7a102011-11-16 00:52:40 +00005594/// getExact(ExitingBlock, SE).
Andrew Trick3ca3f982011-07-26 17:19:55 +00005595const SCEV *
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005596ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5597 SCEVUnionPredicate *Preds) const {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005598 // If any exits were not computable, the loop is not computable.
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005599 if (!isComplete() || ExitNotTaken.empty())
5600 return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005601
Craig Topper9f008862014-04-15 04:59:12 +00005602 const SCEV *BECount = nullptr;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005603 for (auto &ENT : ExitNotTaken) {
5604 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005605
5606 if (!BECount)
Silviu Baranga6f444df2016-04-08 14:29:09 +00005607 BECount = ENT.ExactNotTaken;
5608 else if (BECount != ENT.ExactNotTaken)
Andrew Trick90c7a102011-11-16 00:52:40 +00005609 return SE->getCouldNotCompute();
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005610 if (Preds && !ENT.hasAlwaysTruePredicate())
5611 Preds->add(ENT.Predicate.get());
Silviu Baranga6f444df2016-04-08 14:29:09 +00005612
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005613 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
Silviu Baranga6f444df2016-04-08 14:29:09 +00005614 "Predicate should be always true!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005615 }
Silviu Baranga6f444df2016-04-08 14:29:09 +00005616
Andrew Trickbbb226a2011-09-02 21:20:46 +00005617 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005618 return BECount;
5619}
5620
Sanjoy Dasf8570812016-05-29 00:38:22 +00005621/// Get the exact not taken count for this loop exit.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005622const SCEV *
Andrew Trick77c55422011-08-02 04:23:35 +00005623ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005624 ScalarEvolution *SE) const {
Silviu Baranga6f444df2016-04-08 14:29:09 +00005625 for (auto &ENT : ExitNotTaken)
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005626 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
Silviu Baranga6f444df2016-04-08 14:29:09 +00005627 return ENT.ExactNotTaken;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005628
Andrew Trick3ca3f982011-07-26 17:19:55 +00005629 return SE->getCouldNotCompute();
5630}
5631
5632/// getMax - Get the max backedge taken count for the loop.
5633const SCEV *
5634ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
Sanjoy Das73268612016-09-26 01:10:22 +00005635 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5636 return !ENT.hasAlwaysTruePredicate();
5637 };
Silviu Baranga6f444df2016-04-08 14:29:09 +00005638
Sanjoy Das73268612016-09-26 01:10:22 +00005639 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
5640 return SE->getCouldNotCompute();
5641
5642 return getMax();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005643}
5644
Andrew Trick9093e152013-03-26 03:14:53 +00005645bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5646 ScalarEvolution *SE) const {
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005647 if (getMax() && getMax() != SE->getCouldNotCompute() &&
5648 SE->hasOperand(getMax(), S))
Andrew Trick9093e152013-03-26 03:14:53 +00005649 return true;
5650
Silviu Baranga6f444df2016-04-08 14:29:09 +00005651 for (auto &ENT : ExitNotTaken)
5652 if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5653 SE->hasOperand(ENT.ExactNotTaken, S))
Silviu Barangaa393baf2016-04-06 14:06:32 +00005654 return true;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005655
Andrew Trick9093e152013-03-26 03:14:53 +00005656 return false;
5657}
5658
Andrew Trick3ca3f982011-07-26 17:19:55 +00005659/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5660/// computable exit into a persistent ExitNotTakenInfo array.
5661ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
Sanjoy Das5c4869b2016-09-26 01:10:27 +00005662 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
5663 &&ExitCounts,
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005664 bool Complete, const SCEV *MaxCount)
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005665 : MaxAndComplete(MaxCount, Complete) {
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005666 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
Sanjoy Dase935c772016-09-25 23:12:08 +00005667 ExitNotTaken.reserve(ExitCounts.size());
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005668 std::transform(
5669 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005670 [&](const EdgeExitInfo &EEI) {
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005671 BasicBlock *ExitBB = EEI.first;
5672 const ExitLimit &EL = EEI.second;
5673 if (EL.Predicate.isAlwaysTrue())
5674 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
5675 return ExitNotTakenInfo(
5676 ExitBB, EL.ExactNotTaken,
5677 llvm::make_unique<SCEVUnionPredicate>(std::move(EL.Predicate)));
5678 });
Andrew Trick3ca3f982011-07-26 17:19:55 +00005679}
5680
Sanjoy Dasf8570812016-05-29 00:38:22 +00005681/// Invalidate this result and free the ExitNotTakenInfo array.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005682void ScalarEvolution::BackedgeTakenInfo::clear() {
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005683 ExitNotTaken.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005684}
5685
Sanjoy Dasf8570812016-05-29 00:38:22 +00005686/// Compute the number of times the backedge of the specified loop will execute.
Dan Gohman2b8da352009-04-30 20:47:05 +00005687ScalarEvolution::BackedgeTakenInfo
Silviu Baranga6f444df2016-04-08 14:29:09 +00005688ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5689 bool AllowPredicates) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00005690 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohman96212b62009-06-22 00:31:57 +00005691 L->getExitingBlocks(ExitingBlocks);
Chris Lattnerd934c702004-04-02 20:23:17 +00005692
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005693 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5694
5695 SmallVector<EdgeExitInfo, 4> ExitCounts;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005696 bool CouldComputeBECount = true;
Andrew Trickee5aa7f2014-01-15 06:42:11 +00005697 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
Andrew Trick839e30b2014-05-23 19:47:13 +00005698 const SCEV *MustExitMaxBECount = nullptr;
5699 const SCEV *MayExitMaxBECount = nullptr;
5700
5701 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5702 // and compute maxBECount.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005703 // Do a union of all the predicates here.
Dan Gohman96212b62009-06-22 00:31:57 +00005704 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005705 BasicBlock *ExitBB = ExitingBlocks[i];
Silviu Baranga6f444df2016-04-08 14:29:09 +00005706 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
5707
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005708 assert((AllowPredicates || EL.Predicate.isAlwaysTrue()) &&
Silviu Baranga6f444df2016-04-08 14:29:09 +00005709 "Predicated exit limit when predicates are not allowed!");
Andrew Trick839e30b2014-05-23 19:47:13 +00005710
5711 // 1. For each exit that can be computed, add an entry to ExitCounts.
5712 // CouldComputeBECount is true only if all exits can be computed.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005713 if (EL.ExactNotTaken == getCouldNotCompute())
Dan Gohman96212b62009-06-22 00:31:57 +00005714 // We couldn't compute an exact value for this exit, so
Dan Gohman8885b372009-06-22 21:10:22 +00005715 // we won't be able to compute an exact value for the loop.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005716 CouldComputeBECount = false;
5717 else
Sanjoy Dasbdd97102016-09-25 23:11:55 +00005718 ExitCounts.emplace_back(ExitBB, EL);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005719
Andrew Trick839e30b2014-05-23 19:47:13 +00005720 // 2. Derive the loop's MaxBECount from each exit's max number of
5721 // non-exiting iterations. Partition the loop exits into two kinds:
5722 // LoopMustExits and LoopMayExits.
5723 //
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005724 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5725 // is a LoopMayExit. If any computable LoopMustExit is found, then
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005726 // MaxBECount is the minimum EL.MaxNotTaken of computable
5727 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
5728 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
5729 // computable EL.MaxNotTaken.
5730 if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005731 DT.dominates(ExitBB, Latch)) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005732 if (!MustExitMaxBECount)
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005733 MustExitMaxBECount = EL.MaxNotTaken;
Andrew Trick839e30b2014-05-23 19:47:13 +00005734 else {
5735 MustExitMaxBECount =
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005736 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
Andrew Tricke2553592014-05-22 00:37:03 +00005737 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005738 } else if (MayExitMaxBECount != getCouldNotCompute()) {
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005739 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
5740 MayExitMaxBECount = EL.MaxNotTaken;
Andrew Trick839e30b2014-05-23 19:47:13 +00005741 else {
5742 MayExitMaxBECount =
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005743 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
Andrew Trick839e30b2014-05-23 19:47:13 +00005744 }
Andrew Trick90c7a102011-11-16 00:52:40 +00005745 }
Dan Gohman96212b62009-06-22 00:31:57 +00005746 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005747 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5748 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
Sanjoy Das5c4869b2016-09-26 01:10:27 +00005749 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
5750 MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00005751}
5752
Andrew Trick3ca3f982011-07-26 17:19:55 +00005753ScalarEvolution::ExitLimit
Silviu Baranga6f444df2016-04-08 14:29:09 +00005754ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
5755 bool AllowPredicates) {
Dan Gohman96212b62009-06-22 00:31:57 +00005756
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005757 // Okay, we've chosen an exiting block. See what condition causes us to exit
5758 // at this block and remember the exit block and whether all other targets
Benjamin Kramer5a188542014-02-11 15:44:32 +00005759 // lead to the loop header.
5760 bool MustExecuteLoopHeader = true;
Craig Topper9f008862014-04-15 04:59:12 +00005761 BasicBlock *Exit = nullptr;
Sanjoy Das0ff07872016-01-19 20:53:46 +00005762 for (auto *SBB : successors(ExitingBlock))
5763 if (!L->contains(SBB)) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005764 if (Exit) // Multiple exit successors.
5765 return getCouldNotCompute();
Sanjoy Das0ff07872016-01-19 20:53:46 +00005766 Exit = SBB;
5767 } else if (SBB != L->getHeader()) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005768 MustExecuteLoopHeader = false;
5769 }
Dan Gohmance973df2009-06-24 04:48:43 +00005770
Chris Lattner18954852007-01-07 02:24:26 +00005771 // At this point, we know we have a conditional branch that determines whether
5772 // the loop is exited. However, we don't know if the branch is executed each
5773 // time through the loop. If not, then the execution count of the branch will
5774 // not be equal to the trip count of the loop.
5775 //
5776 // Currently we check for this by checking to see if the Exit branch goes to
5777 // the loop header. If so, we know it will always execute the same number of
Chris Lattner5a554762007-01-14 01:24:47 +00005778 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman96212b62009-06-22 00:31:57 +00005779 // loop header. This is common for un-rotated loops.
5780 //
5781 // If both of those tests fail, walk up the unique predecessor chain to the
5782 // header, stopping if there is an edge that doesn't exit the loop. If the
5783 // header is reached, the execution count of the branch will be equal to the
5784 // trip count of the loop.
5785 //
5786 // More extensive analysis could be done to handle more cases here.
5787 //
Benjamin Kramer5a188542014-02-11 15:44:32 +00005788 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005789 // The simple checks failed, try climbing the unique predecessor chain
5790 // up to the header.
5791 bool Ok = false;
Benjamin Kramer5a188542014-02-11 15:44:32 +00005792 for (BasicBlock *BB = ExitingBlock; BB; ) {
Dan Gohman96212b62009-06-22 00:31:57 +00005793 BasicBlock *Pred = BB->getUniquePredecessor();
5794 if (!Pred)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005795 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005796 TerminatorInst *PredTerm = Pred->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +00005797 for (const BasicBlock *PredSucc : PredTerm->successors()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005798 if (PredSucc == BB)
5799 continue;
5800 // If the predecessor has a successor that isn't BB and isn't
5801 // outside the loop, assume the worst.
5802 if (L->contains(PredSucc))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005803 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005804 }
5805 if (Pred == L->getHeader()) {
5806 Ok = true;
5807 break;
5808 }
5809 BB = Pred;
5810 }
5811 if (!Ok)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005812 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005813 }
5814
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005815 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005816 TerminatorInst *Term = ExitingBlock->getTerminator();
5817 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
5818 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
5819 // Proceed to the next level to examine the exit condition expression.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005820 return computeExitLimitFromCond(
5821 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
5822 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005823 }
5824
5825 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005826 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005827 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005828
5829 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005830}
5831
Andrew Trick3ca3f982011-07-26 17:19:55 +00005832ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005833ScalarEvolution::computeExitLimitFromCond(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005834 Value *ExitCond,
5835 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005836 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005837 bool ControlsExit,
5838 bool AllowPredicates) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00005839 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman96212b62009-06-22 00:31:57 +00005840 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
5841 if (BO->getOpcode() == Instruction::And) {
5842 // Recurse on the operands of the and.
Andrew Trick5b245a12013-05-31 06:43:25 +00005843 bool EitherMayExit = L->contains(TBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005844 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005845 ControlsExit && !EitherMayExit,
5846 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005847 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005848 ControlsExit && !EitherMayExit,
5849 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00005850 const SCEV *BECount = getCouldNotCompute();
5851 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005852 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005853 // Both conditions must be true for the loop to continue executing.
5854 // Choose the less conservative count.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005855 if (EL0.ExactNotTaken == getCouldNotCompute() ||
5856 EL1.ExactNotTaken == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005857 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005858 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005859 BECount =
5860 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
5861 if (EL0.MaxNotTaken == getCouldNotCompute())
5862 MaxBECount = EL1.MaxNotTaken;
5863 else if (EL1.MaxNotTaken == getCouldNotCompute())
5864 MaxBECount = EL0.MaxNotTaken;
Dan Gohmaned627382009-06-22 15:09:28 +00005865 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005866 MaxBECount =
5867 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
Dan Gohman96212b62009-06-22 00:31:57 +00005868 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005869 // Both conditions must be true at the same time for the loop to exit.
5870 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005871 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005872 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
5873 MaxBECount = EL0.MaxNotTaken;
5874 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
5875 BECount = EL0.ExactNotTaken;
Dan Gohman96212b62009-06-22 00:31:57 +00005876 }
5877
Silviu Baranga6f444df2016-04-08 14:29:09 +00005878 SCEVUnionPredicate NP;
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005879 NP.add(&EL0.Predicate);
5880 NP.add(&EL1.Predicate);
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00005881 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
5882 // to be more aggressive when computing BECount than when computing
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005883 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
5884 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
5885 // to not.
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00005886 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
5887 !isa<SCEVCouldNotCompute>(BECount))
5888 MaxBECount = BECount;
5889
Silviu Baranga6f444df2016-04-08 14:29:09 +00005890 return ExitLimit(BECount, MaxBECount, NP);
Dan Gohman96212b62009-06-22 00:31:57 +00005891 }
5892 if (BO->getOpcode() == Instruction::Or) {
5893 // Recurse on the operands of the or.
Andrew Trick5b245a12013-05-31 06:43:25 +00005894 bool EitherMayExit = L->contains(FBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005895 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005896 ControlsExit && !EitherMayExit,
5897 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005898 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005899 ControlsExit && !EitherMayExit,
5900 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00005901 const SCEV *BECount = getCouldNotCompute();
5902 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005903 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005904 // Both conditions must be false for the loop to continue executing.
5905 // Choose the less conservative count.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005906 if (EL0.ExactNotTaken == getCouldNotCompute() ||
5907 EL1.ExactNotTaken == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005908 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005909 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005910 BECount =
5911 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
5912 if (EL0.MaxNotTaken == getCouldNotCompute())
5913 MaxBECount = EL1.MaxNotTaken;
5914 else if (EL1.MaxNotTaken == getCouldNotCompute())
5915 MaxBECount = EL0.MaxNotTaken;
Dan Gohmaned627382009-06-22 15:09:28 +00005916 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005917 MaxBECount =
5918 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
Dan Gohman96212b62009-06-22 00:31:57 +00005919 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005920 // Both conditions must be false at the same time for the loop to exit.
5921 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005922 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005923 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
5924 MaxBECount = EL0.MaxNotTaken;
5925 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
5926 BECount = EL0.ExactNotTaken;
Dan Gohman96212b62009-06-22 00:31:57 +00005927 }
5928
Silviu Baranga6f444df2016-04-08 14:29:09 +00005929 SCEVUnionPredicate NP;
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005930 NP.add(&EL0.Predicate);
5931 NP.add(&EL1.Predicate);
Silviu Baranga6f444df2016-04-08 14:29:09 +00005932 return ExitLimit(BECount, MaxBECount, NP);
Dan Gohman96212b62009-06-22 00:31:57 +00005933 }
5934 }
5935
5936 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman8b0a4192010-03-01 17:49:51 +00005937 // Proceed to the next level to examine the icmp.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005938 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
5939 ExitLimit EL =
5940 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
5941 if (EL.hasFullInfo() || !AllowPredicates)
5942 return EL;
5943
5944 // Try again, but use SCEV predicates this time.
5945 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
5946 /*AllowPredicates=*/true);
5947 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005948
Dan Gohman6b1e2a82010-02-19 18:12:07 +00005949 // Check for a constant condition. These are normally stripped out by
5950 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
5951 // preserve the CFG and is temporarily leaving constant conditions
5952 // in place.
5953 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
5954 if (L->contains(FBB) == !CI->getZExtValue())
5955 // The backedge is always taken.
5956 return getCouldNotCompute();
5957 else
5958 // The backedge is never taken.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005959 return getZero(CI->getType());
Dan Gohman6b1e2a82010-02-19 18:12:07 +00005960 }
5961
Eli Friedmanebf98b02009-05-09 12:32:42 +00005962 // If it's not an integer or pointer comparison then compute it the hard way.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005963 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohman96212b62009-06-22 00:31:57 +00005964}
5965
Andrew Trick3ca3f982011-07-26 17:19:55 +00005966ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005967ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005968 ICmpInst *ExitCond,
5969 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005970 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005971 bool ControlsExit,
5972 bool AllowPredicates) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005973
Reid Spencer266e42b2006-12-23 06:05:41 +00005974 // If the condition was exit on true, convert the condition to exit on false
5975 ICmpInst::Predicate Cond;
Dan Gohman96212b62009-06-22 00:31:57 +00005976 if (!L->contains(FBB))
Reid Spencer266e42b2006-12-23 06:05:41 +00005977 Cond = ExitCond->getPredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005978 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005979 Cond = ExitCond->getInversePredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005980
5981 // Handle common loops like: for (X = "string"; *X; ++X)
5982 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
5983 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005984 ExitLimit ItCnt =
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005985 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanba820342010-02-24 17:31:30 +00005986 if (ItCnt.hasAnyInfo())
5987 return ItCnt;
Chris Lattnerec901cc2004-10-12 01:49:27 +00005988 }
5989
Dan Gohmanaf752342009-07-07 17:06:11 +00005990 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
5991 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattnerd934c702004-04-02 20:23:17 +00005992
5993 // Try to evaluate any dependencies out of the loop.
Dan Gohman8ca08852009-05-24 23:25:42 +00005994 LHS = getSCEVAtScope(LHS, L);
5995 RHS = getSCEVAtScope(RHS, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00005996
Dan Gohmance973df2009-06-24 04:48:43 +00005997 // At this point, we would like to compute how many iterations of the
Reid Spencer266e42b2006-12-23 06:05:41 +00005998 // loop the predicate will return true for these inputs.
Dan Gohmanafd6db92010-11-17 21:23:15 +00005999 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohmandc5f5cb2008-09-16 18:52:57 +00006000 // If there is a loop-invariant, force it into the RHS.
Chris Lattnerd934c702004-04-02 20:23:17 +00006001 std::swap(LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00006002 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattnerd934c702004-04-02 20:23:17 +00006003 }
6004
Dan Gohman81585c12010-05-03 16:35:17 +00006005 // Simplify the operands before analyzing them.
6006 (void)SimplifyICmpOperands(Cond, LHS, RHS);
6007
Chris Lattnerd934c702004-04-02 20:23:17 +00006008 // If we have a comparison of a chrec against a constant, try to use value
6009 // ranges to answer this query.
Dan Gohmana30370b2009-05-04 22:02:23 +00006010 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6011 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattnerd934c702004-04-02 20:23:17 +00006012 if (AddRec->getLoop() == L) {
Eli Friedmanebf98b02009-05-09 12:32:42 +00006013 // Form the constant range.
6014 ConstantRange CompRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006015 ICmpInst::makeConstantRange(Cond, RHSC->getAPInt()));
Misha Brukman01808ca2005-04-21 21:13:18 +00006016
Dan Gohmanaf752342009-07-07 17:06:11 +00006017 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedmanebf98b02009-05-09 12:32:42 +00006018 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattnerd934c702004-04-02 20:23:17 +00006019 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006020
Chris Lattnerd934c702004-04-02 20:23:17 +00006021 switch (Cond) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006022 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattnerd934c702004-04-02 20:23:17 +00006023 // Convert to: while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006024 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006025 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006026 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006027 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006028 }
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00006029 case ICmpInst::ICMP_EQ: { // while (X == Y)
6030 // Convert to: while (X-Y == 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006031 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006032 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006033 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006034 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006035 case ICmpInst::ICMP_SLT:
6036 case ICmpInst::ICMP_ULT: { // while (X < Y)
6037 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
Sanjoy Das108fcf22016-05-29 00:38:00 +00006038 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006039 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006040 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006041 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006042 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006043 case ICmpInst::ICMP_SGT:
6044 case ICmpInst::ICMP_UGT: { // while (X > Y)
6045 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
Silviu Baranga6f444df2016-04-08 14:29:09 +00006046 ExitLimit EL =
Sanjoy Das108fcf22016-05-29 00:38:00 +00006047 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006048 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006049 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006050 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006051 }
Chris Lattnerd934c702004-04-02 20:23:17 +00006052 default:
Chris Lattner0defaa12004-04-03 00:43:03 +00006053 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00006054 }
Sanjoy Das0da2d142016-06-30 02:47:28 +00006055
6056 auto *ExhaustiveCount =
6057 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6058
6059 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6060 return ExhaustiveCount;
6061
6062 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6063 ExitCond->getOperand(1), L, Cond);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006064}
6065
Benjamin Kramer5a188542014-02-11 15:44:32 +00006066ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006067ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
Benjamin Kramer5a188542014-02-11 15:44:32 +00006068 SwitchInst *Switch,
6069 BasicBlock *ExitingBlock,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006070 bool ControlsExit) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00006071 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6072
6073 // Give up if the exit is the default dest of a switch.
6074 if (Switch->getDefaultDest() == ExitingBlock)
6075 return getCouldNotCompute();
6076
6077 assert(L->contains(Switch->getDefaultDest()) &&
6078 "Default case must not exit the loop!");
6079 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6080 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6081
6082 // while (X != Y) --> while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006083 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006084 if (EL.hasAnyInfo())
6085 return EL;
6086
6087 return getCouldNotCompute();
6088}
6089
Chris Lattnerec901cc2004-10-12 01:49:27 +00006090static ConstantInt *
Dan Gohmana37eaf22007-10-22 18:31:58 +00006091EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6092 ScalarEvolution &SE) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006093 const SCEV *InVal = SE.getConstant(C);
6094 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006095 assert(isa<SCEVConstant>(Val) &&
6096 "Evaluation of SCEV at constant didn't fold correctly?");
6097 return cast<SCEVConstant>(Val)->getValue();
6098}
6099
Sanjoy Dasf8570812016-05-29 00:38:22 +00006100/// Given an exit condition of 'icmp op load X, cst', try to see if we can
6101/// compute the backedge execution count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006102ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006103ScalarEvolution::computeLoadConstantCompareExitLimit(
Andrew Trick3ca3f982011-07-26 17:19:55 +00006104 LoadInst *LI,
6105 Constant *RHS,
6106 const Loop *L,
6107 ICmpInst::Predicate predicate) {
6108
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006109 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006110
6111 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanba820342010-02-24 17:31:30 +00006112 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006113 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006114 if (!GEP) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006115
6116 // Make sure that it is really a constant global we are gepping, with an
6117 // initializer, and make sure the first IDX is really 0.
6118 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00006119 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006120 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6121 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006122 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006123
6124 // Okay, we allow one non-constant index into the GEP instruction.
Craig Topper9f008862014-04-15 04:59:12 +00006125 Value *VarIdx = nullptr;
Chris Lattnere166a852012-01-24 05:49:24 +00006126 std::vector<Constant*> Indexes;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006127 unsigned VarIdxNum = 0;
6128 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6129 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6130 Indexes.push_back(CI);
6131 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006132 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006133 VarIdx = GEP->getOperand(i);
6134 VarIdxNum = i-2;
Craig Topper9f008862014-04-15 04:59:12 +00006135 Indexes.push_back(nullptr);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006136 }
6137
Andrew Trick7004e4b2012-03-26 22:33:59 +00006138 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6139 if (!VarIdx)
6140 return getCouldNotCompute();
6141
Chris Lattnerec901cc2004-10-12 01:49:27 +00006142 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6143 // Check to see if X is a loop variant variable value now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006144 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohman8ca08852009-05-24 23:25:42 +00006145 Idx = getSCEVAtScope(Idx, L);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006146
6147 // We can only recognize very limited forms of loop index expressions, in
6148 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman48f82222009-05-04 22:30:44 +00006149 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanafd6db92010-11-17 21:23:15 +00006150 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006151 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6152 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006153 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006154
6155 unsigned MaxSteps = MaxBruteForceIterations;
6156 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersonedb4a702009-07-24 23:12:02 +00006157 ConstantInt *ItCst = ConstantInt::get(
Owen Andersonb6b25302009-07-14 23:09:55 +00006158 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanc8e23622009-04-21 23:15:49 +00006159 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006160
6161 // Form the GEP offset.
6162 Indexes[VarIdxNum] = Val;
6163
Chris Lattnere166a852012-01-24 05:49:24 +00006164 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6165 Indexes);
Craig Topper9f008862014-04-15 04:59:12 +00006166 if (!Result) break; // Cannot compute!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006167
6168 // Evaluate the condition for this iteration.
Reid Spencer266e42b2006-12-23 06:05:41 +00006169 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00006170 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer983e3b32007-03-01 07:25:48 +00006171 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00006172 ++NumArrayLenItCounts;
Dan Gohmanc8e23622009-04-21 23:15:49 +00006173 return getConstant(ItCst); // Found terminating iteration!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006174 }
6175 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006176 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006177}
6178
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006179ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6180 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6181 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6182 if (!RHS)
6183 return getCouldNotCompute();
6184
6185 const BasicBlock *Latch = L->getLoopLatch();
6186 if (!Latch)
6187 return getCouldNotCompute();
6188
6189 const BasicBlock *Predecessor = L->getLoopPredecessor();
6190 if (!Predecessor)
6191 return getCouldNotCompute();
6192
6193 // Return true if V is of the form "LHS `shift_op` <positive constant>".
6194 // Return LHS in OutLHS and shift_opt in OutOpCode.
6195 auto MatchPositiveShift =
6196 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6197
6198 using namespace PatternMatch;
6199
6200 ConstantInt *ShiftAmt;
6201 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6202 OutOpCode = Instruction::LShr;
6203 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6204 OutOpCode = Instruction::AShr;
6205 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6206 OutOpCode = Instruction::Shl;
6207 else
6208 return false;
6209
6210 return ShiftAmt->getValue().isStrictlyPositive();
6211 };
6212
6213 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6214 //
6215 // loop:
6216 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6217 // %iv.shifted = lshr i32 %iv, <positive constant>
6218 //
6219 // Return true on a succesful match. Return the corresponding PHI node (%iv
6220 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6221 auto MatchShiftRecurrence =
6222 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6223 Optional<Instruction::BinaryOps> PostShiftOpCode;
6224
6225 {
6226 Instruction::BinaryOps OpC;
6227 Value *V;
6228
6229 // If we encounter a shift instruction, "peel off" the shift operation,
6230 // and remember that we did so. Later when we inspect %iv's backedge
6231 // value, we will make sure that the backedge value uses the same
6232 // operation.
6233 //
6234 // Note: the peeled shift operation does not have to be the same
6235 // instruction as the one feeding into the PHI's backedge value. We only
6236 // really care about it being the same *kind* of shift instruction --
6237 // that's all that is required for our later inferences to hold.
6238 if (MatchPositiveShift(LHS, V, OpC)) {
6239 PostShiftOpCode = OpC;
6240 LHS = V;
6241 }
6242 }
6243
6244 PNOut = dyn_cast<PHINode>(LHS);
6245 if (!PNOut || PNOut->getParent() != L->getHeader())
6246 return false;
6247
6248 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6249 Value *OpLHS;
6250
6251 return
6252 // The backedge value for the PHI node must be a shift by a positive
6253 // amount
6254 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6255
6256 // of the PHI node itself
6257 OpLHS == PNOut &&
6258
6259 // and the kind of shift should be match the kind of shift we peeled
6260 // off, if any.
6261 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6262 };
6263
6264 PHINode *PN;
6265 Instruction::BinaryOps OpCode;
6266 if (!MatchShiftRecurrence(LHS, PN, OpCode))
6267 return getCouldNotCompute();
6268
6269 const DataLayout &DL = getDataLayout();
6270
6271 // The key rationale for this optimization is that for some kinds of shift
6272 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6273 // within a finite number of iterations. If the condition guarding the
6274 // backedge (in the sense that the backedge is taken if the condition is true)
6275 // is false for the value the shift recurrence stabilizes to, then we know
6276 // that the backedge is taken only a finite number of times.
6277
6278 ConstantInt *StableValue = nullptr;
6279 switch (OpCode) {
6280 default:
6281 llvm_unreachable("Impossible case!");
6282
6283 case Instruction::AShr: {
6284 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6285 // bitwidth(K) iterations.
6286 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6287 bool KnownZero, KnownOne;
6288 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
6289 Predecessor->getTerminator(), &DT);
6290 auto *Ty = cast<IntegerType>(RHS->getType());
6291 if (KnownZero)
6292 StableValue = ConstantInt::get(Ty, 0);
6293 else if (KnownOne)
6294 StableValue = ConstantInt::get(Ty, -1, true);
6295 else
6296 return getCouldNotCompute();
6297
6298 break;
6299 }
6300 case Instruction::LShr:
6301 case Instruction::Shl:
6302 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6303 // stabilize to 0 in at most bitwidth(K) iterations.
6304 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6305 break;
6306 }
6307
6308 auto *Result =
6309 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6310 assert(Result->getType()->isIntegerTy(1) &&
6311 "Otherwise cannot be an operand to a branch instruction");
6312
6313 if (Result->isZeroValue()) {
6314 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6315 const SCEV *UpperBound =
6316 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
Silviu Baranga6f444df2016-04-08 14:29:09 +00006317 SCEVUnionPredicate P;
6318 return ExitLimit(getCouldNotCompute(), UpperBound, P);
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006319 }
6320
6321 return getCouldNotCompute();
6322}
Chris Lattnerec901cc2004-10-12 01:49:27 +00006323
Sanjoy Dasf8570812016-05-29 00:38:22 +00006324/// Return true if we can constant fold an instruction of the specified type,
6325/// assuming that all operands were constants.
Chris Lattnerdd730472004-04-17 22:58:41 +00006326static bool CanConstantFold(const Instruction *I) {
Reid Spencer2341c222007-02-02 02:16:23 +00006327 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Nick Lewyckya6674c72011-10-22 19:58:20 +00006328 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6329 isa<LoadInst>(I))
Chris Lattnerdd730472004-04-17 22:58:41 +00006330 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00006331
Chris Lattnerdd730472004-04-17 22:58:41 +00006332 if (const CallInst *CI = dyn_cast<CallInst>(I))
6333 if (const Function *F = CI->getCalledFunction())
Dan Gohmana65951f2008-01-31 01:05:10 +00006334 return canConstantFoldCallTo(F);
Chris Lattnerdd730472004-04-17 22:58:41 +00006335 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00006336}
6337
Andrew Trick3a86ba72011-10-05 03:25:31 +00006338/// Determine whether this instruction can constant evolve within this loop
6339/// assuming its operands can all constant evolve.
6340static bool canConstantEvolve(Instruction *I, const Loop *L) {
6341 // An instruction outside of the loop can't be derived from a loop PHI.
6342 if (!L->contains(I)) return false;
6343
6344 if (isa<PHINode>(I)) {
David Blaikie19ef0d32015-03-24 16:33:19 +00006345 // We don't currently keep track of the control flow needed to evaluate
6346 // PHIs, so we cannot handle PHIs inside of loops.
6347 return L->getHeader() == I->getParent();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006348 }
6349
6350 // If we won't be able to constant fold this expression even if the operands
6351 // are constants, bail early.
6352 return CanConstantFold(I);
6353}
6354
6355/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6356/// recursing through each instruction operand until reaching a loop header phi.
6357static PHINode *
6358getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
Andrew Tricke9162f12011-10-05 05:58:49 +00006359 DenseMap<Instruction *, PHINode *> &PHIMap) {
Andrew Trick3a86ba72011-10-05 03:25:31 +00006360
6361 // Otherwise, we can evaluate this instruction if all of its operands are
6362 // constant or derived from a PHI node themselves.
Craig Topper9f008862014-04-15 04:59:12 +00006363 PHINode *PHI = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006364 for (Value *Op : UseInst->operands()) {
6365 if (isa<Constant>(Op)) continue;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006366
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006367 Instruction *OpInst = dyn_cast<Instruction>(Op);
Craig Topper9f008862014-04-15 04:59:12 +00006368 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006369
6370 PHINode *P = dyn_cast<PHINode>(OpInst);
Andrew Trick3e8a5762011-10-05 22:06:53 +00006371 if (!P)
6372 // If this operand is already visited, reuse the prior result.
6373 // We may have P != PHI if this is the deepest point at which the
6374 // inconsistent paths meet.
6375 P = PHIMap.lookup(OpInst);
6376 if (!P) {
6377 // Recurse and memoize the results, whether a phi is found or not.
6378 // This recursive call invalidates pointers into PHIMap.
6379 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
6380 PHIMap[OpInst] = P;
Andrew Tricke9162f12011-10-05 05:58:49 +00006381 }
Craig Topper9f008862014-04-15 04:59:12 +00006382 if (!P)
6383 return nullptr; // Not evolving from PHI
6384 if (PHI && PHI != P)
6385 return nullptr; // Evolving from multiple different PHIs.
Andrew Tricke9162f12011-10-05 05:58:49 +00006386 PHI = P;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006387 }
6388 // This is a expression evolving from a constant PHI!
6389 return PHI;
6390}
6391
Chris Lattnerdd730472004-04-17 22:58:41 +00006392/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6393/// in the loop that V is derived from. We allow arbitrary operations along the
6394/// way, but the operands of an operation must either be constants or a value
6395/// derived from a constant PHI. If this expression does not fit with these
6396/// constraints, return null.
6397static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006398 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006399 if (!I || !canConstantEvolve(I, L)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006400
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00006401 if (PHINode *PN = dyn_cast<PHINode>(I))
Andrew Trick3a86ba72011-10-05 03:25:31 +00006402 return PN;
Chris Lattnerdd730472004-04-17 22:58:41 +00006403
Andrew Trick3a86ba72011-10-05 03:25:31 +00006404 // Record non-constant instructions contained by the loop.
Andrew Tricke9162f12011-10-05 05:58:49 +00006405 DenseMap<Instruction *, PHINode *> PHIMap;
6406 return getConstantEvolvingPHIOperands(I, L, PHIMap);
Chris Lattnerdd730472004-04-17 22:58:41 +00006407}
6408
6409/// EvaluateExpression - Given an expression that passes the
6410/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6411/// in the loop has the value PHIVal. If we can't fold this expression for some
6412/// reason, return null.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006413static Constant *EvaluateExpression(Value *V, const Loop *L,
6414 DenseMap<Instruction *, Constant *> &Vals,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006415 const DataLayout &DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00006416 const TargetLibraryInfo *TLI) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006417 // Convenient constant check, but redundant for recursive calls.
Reid Spencer30d69a52004-07-18 00:18:30 +00006418 if (Constant *C = dyn_cast<Constant>(V)) return C;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006419 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006420 if (!I) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006421
Andrew Trick3a86ba72011-10-05 03:25:31 +00006422 if (Constant *C = Vals.lookup(I)) return C;
6423
Nick Lewyckya6674c72011-10-22 19:58:20 +00006424 // An instruction inside the loop depends on a value outside the loop that we
6425 // weren't given a mapping for, or a value such as a call inside the loop.
Craig Topper9f008862014-04-15 04:59:12 +00006426 if (!canConstantEvolve(I, L)) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006427
6428 // An unmapped PHI can be due to a branch or another loop inside this loop,
6429 // or due to this not being the initial iteration through a loop where we
6430 // couldn't compute the evolution of this particular PHI last time.
Craig Topper9f008862014-04-15 04:59:12 +00006431 if (isa<PHINode>(I)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006432
Dan Gohmanf820bd32010-06-22 13:15:46 +00006433 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattnerdd730472004-04-17 22:58:41 +00006434
6435 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006436 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6437 if (!Operand) {
Nick Lewyckya447e0f32011-10-14 09:38:46 +00006438 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006439 if (!Operands[i]) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006440 continue;
6441 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006442 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Andrew Tricke9162f12011-10-05 05:58:49 +00006443 Vals[Operand] = C;
Craig Topper9f008862014-04-15 04:59:12 +00006444 if (!C) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006445 Operands[i] = C;
Chris Lattnerdd730472004-04-17 22:58:41 +00006446 }
6447
Nick Lewyckya6674c72011-10-22 19:58:20 +00006448 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00006449 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006450 Operands[1], DL, TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006451 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6452 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006453 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006454 }
Manuel Jacobe9024592016-01-21 06:33:22 +00006455 return ConstantFoldInstOperands(I, Operands, DL, TLI);
Chris Lattnerdd730472004-04-17 22:58:41 +00006456}
6457
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006458
6459// If every incoming value to PN except the one for BB is a specific Constant,
6460// return that, else return nullptr.
6461static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6462 Constant *IncomingVal = nullptr;
6463
6464 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6465 if (PN->getIncomingBlock(i) == BB)
6466 continue;
6467
6468 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6469 if (!CurrentVal)
6470 return nullptr;
6471
6472 if (IncomingVal != CurrentVal) {
6473 if (IncomingVal)
6474 return nullptr;
6475 IncomingVal = CurrentVal;
6476 }
6477 }
6478
6479 return IncomingVal;
6480}
6481
Chris Lattnerdd730472004-04-17 22:58:41 +00006482/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6483/// in the header of its containing loop, we know the loop executes a
6484/// constant number of times, and the PHI node is just a recurrence
6485/// involving constants, fold it.
Dan Gohmance973df2009-06-24 04:48:43 +00006486Constant *
6487ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohmancb0efec2009-12-18 01:14:11 +00006488 const APInt &BEs,
Dan Gohmance973df2009-06-24 04:48:43 +00006489 const Loop *L) {
Sanjoy Das4493b402015-10-07 17:38:25 +00006490 auto I = ConstantEvolutionLoopExitValue.find(PN);
Chris Lattnerdd730472004-04-17 22:58:41 +00006491 if (I != ConstantEvolutionLoopExitValue.end())
6492 return I->second;
6493
Dan Gohman4ce1fb12010-04-08 23:03:40 +00006494 if (BEs.ugt(MaxBruteForceIterations))
Craig Topper9f008862014-04-15 04:59:12 +00006495 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
Chris Lattnerdd730472004-04-17 22:58:41 +00006496
6497 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6498
Andrew Trick3a86ba72011-10-05 03:25:31 +00006499 DenseMap<Instruction *, Constant *> CurrentIterVals;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006500 BasicBlock *Header = L->getHeader();
6501 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
Andrew Trick3a86ba72011-10-05 03:25:31 +00006502
Sanjoy Dasdd709962015-10-08 18:28:36 +00006503 BasicBlock *Latch = L->getLoopLatch();
6504 if (!Latch)
6505 return nullptr;
6506
Sanjoy Das4493b402015-10-07 17:38:25 +00006507 for (auto &I : *Header) {
6508 PHINode *PHI = dyn_cast<PHINode>(&I);
6509 if (!PHI) break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006510 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006511 if (!StartCST) continue;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006512 CurrentIterVals[PHI] = StartCST;
6513 }
6514 if (!CurrentIterVals.count(PN))
Craig Topper9f008862014-04-15 04:59:12 +00006515 return RetVal = nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006516
Sanjoy Dasdd709962015-10-08 18:28:36 +00006517 Value *BEValue = PN->getIncomingValueForBlock(Latch);
Chris Lattnerdd730472004-04-17 22:58:41 +00006518
6519 // Execute the loop symbolically to determine the exit value.
Dan Gohman0bddac12009-02-24 18:55:53 +00006520 if (BEs.getActiveBits() >= 32)
Craig Topper9f008862014-04-15 04:59:12 +00006521 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
Chris Lattnerdd730472004-04-17 22:58:41 +00006522
Dan Gohman0bddac12009-02-24 18:55:53 +00006523 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencer983e3b32007-03-01 07:25:48 +00006524 unsigned IterationNum = 0;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006525 const DataLayout &DL = getDataLayout();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006526 for (; ; ++IterationNum) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006527 if (IterationNum == NumIterations)
Andrew Trick3a86ba72011-10-05 03:25:31 +00006528 return RetVal = CurrentIterVals[PN]; // Got exit value!
Chris Lattnerdd730472004-04-17 22:58:41 +00006529
Nick Lewyckya6674c72011-10-22 19:58:20 +00006530 // Compute the value of the PHIs for the next iteration.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006531 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006532 DenseMap<Instruction *, Constant *> NextIterVals;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006533 Constant *NextPHI =
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006534 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Craig Topper9f008862014-04-15 04:59:12 +00006535 if (!NextPHI)
6536 return nullptr; // Couldn't evaluate!
Andrew Trick3a86ba72011-10-05 03:25:31 +00006537 NextIterVals[PN] = NextPHI;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006538
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006539 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6540
Nick Lewyckya6674c72011-10-22 19:58:20 +00006541 // Also evaluate the other PHI nodes. However, we don't get to stop if we
6542 // cease to be able to evaluate one of them or if they stop evolving,
6543 // because that doesn't necessarily prevent us from computing PN.
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006544 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006545 for (const auto &I : CurrentIterVals) {
6546 PHINode *PHI = dyn_cast<PHINode>(I.first);
Nick Lewycky8e904de2011-10-24 05:51:01 +00006547 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
Sanjoy Das4493b402015-10-07 17:38:25 +00006548 PHIsToCompute.emplace_back(PHI, I.second);
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006549 }
6550 // We use two distinct loops because EvaluateExpression may invalidate any
6551 // iterators into CurrentIterVals.
Sanjoy Das4493b402015-10-07 17:38:25 +00006552 for (const auto &I : PHIsToCompute) {
6553 PHINode *PHI = I.first;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006554 Constant *&NextPHI = NextIterVals[PHI];
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006555 if (!NextPHI) { // Not already computed.
Sanjoy Dasdd709962015-10-08 18:28:36 +00006556 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006557 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006558 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006559 if (NextPHI != I.second)
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006560 StoppedEvolving = false;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006561 }
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006562
6563 // If all entries in CurrentIterVals == NextIterVals then we can stop
6564 // iterating, the loop can't continue to change.
6565 if (StoppedEvolving)
6566 return RetVal = CurrentIterVals[PN];
6567
Andrew Trick3a86ba72011-10-05 03:25:31 +00006568 CurrentIterVals.swap(NextIterVals);
Chris Lattnerdd730472004-04-17 22:58:41 +00006569 }
6570}
6571
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006572const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
Nick Lewyckya6674c72011-10-22 19:58:20 +00006573 Value *Cond,
6574 bool ExitWhen) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006575 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Craig Topper9f008862014-04-15 04:59:12 +00006576 if (!PN) return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006577
Dan Gohman866971e2010-06-19 14:17:24 +00006578 // If the loop is canonicalized, the PHI will have exactly two entries.
6579 // That's the only form we support here.
6580 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6581
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006582 DenseMap<Instruction *, Constant *> CurrentIterVals;
6583 BasicBlock *Header = L->getHeader();
6584 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6585
Sanjoy Dasdd709962015-10-08 18:28:36 +00006586 BasicBlock *Latch = L->getLoopLatch();
6587 assert(Latch && "Should follow from NumIncomingValues == 2!");
6588
Sanjoy Das4493b402015-10-07 17:38:25 +00006589 for (auto &I : *Header) {
6590 PHINode *PHI = dyn_cast<PHINode>(&I);
6591 if (!PHI)
6592 break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006593 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006594 if (!StartCST) continue;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006595 CurrentIterVals[PHI] = StartCST;
6596 }
6597 if (!CurrentIterVals.count(PN))
6598 return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006599
6600 // Okay, we find a PHI node that defines the trip count of this loop. Execute
6601 // the loop symbolically to determine when the condition gets a value of
6602 // "ExitWhen".
Andrew Trick90c7a102011-11-16 00:52:40 +00006603 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006604 const DataLayout &DL = getDataLayout();
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006605 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
Sanjoy Das4493b402015-10-07 17:38:25 +00006606 auto *CondVal = dyn_cast_or_null<ConstantInt>(
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006607 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
Chris Lattnerdd730472004-04-17 22:58:41 +00006608
Zhou Sheng75b871f2007-01-11 12:24:14 +00006609 // Couldn't symbolically evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006610 if (!CondVal) return getCouldNotCompute();
Zhou Sheng75b871f2007-01-11 12:24:14 +00006611
Reid Spencer983e3b32007-03-01 07:25:48 +00006612 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006613 ++NumBruteForceTripCountsComputed;
Owen Anderson55f1c092009-08-13 21:58:54 +00006614 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006615 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006616
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006617 // Update all the PHI nodes for the next iteration.
6618 DenseMap<Instruction *, Constant *> NextIterVals;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006619
6620 // Create a list of which PHIs we need to compute. We want to do this before
6621 // calling EvaluateExpression on them because that may invalidate iterators
6622 // into CurrentIterVals.
6623 SmallVector<PHINode *, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006624 for (const auto &I : CurrentIterVals) {
6625 PHINode *PHI = dyn_cast<PHINode>(I.first);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006626 if (!PHI || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006627 PHIsToCompute.push_back(PHI);
6628 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006629 for (PHINode *PHI : PHIsToCompute) {
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006630 Constant *&NextPHI = NextIterVals[PHI];
6631 if (NextPHI) continue; // Already computed!
6632
Sanjoy Dasdd709962015-10-08 18:28:36 +00006633 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006634 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006635 }
6636 CurrentIterVals.swap(NextIterVals);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006637 }
6638
6639 // Too many iterations were needed to evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006640 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006641}
6642
Dan Gohmanaf752342009-07-07 17:06:11 +00006643const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Sanjoy Das01947432015-11-22 21:20:13 +00006644 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6645 ValuesAtScopes[V];
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006646 // Check to see if we've folded this expression at this loop before.
Sanjoy Das01947432015-11-22 21:20:13 +00006647 for (auto &LS : Values)
6648 if (LS.first == L)
6649 return LS.second ? LS.second : V;
6650
6651 Values.emplace_back(L, nullptr);
6652
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006653 // Otherwise compute it.
6654 const SCEV *C = computeSCEVAtScope(V, L);
Sanjoy Das01947432015-11-22 21:20:13 +00006655 for (auto &LS : reverse(ValuesAtScopes[V]))
6656 if (LS.first == L) {
6657 LS.second = C;
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00006658 break;
6659 }
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006660 return C;
6661}
6662
Nick Lewyckya6674c72011-10-22 19:58:20 +00006663/// This builds up a Constant using the ConstantExpr interface. That way, we
6664/// will return Constants for objects which aren't represented by a
6665/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6666/// Returns NULL if the SCEV isn't representable as a Constant.
6667static Constant *BuildConstantFromSCEV(const SCEV *V) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00006668 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
Nick Lewyckya6674c72011-10-22 19:58:20 +00006669 case scCouldNotCompute:
6670 case scAddRecExpr:
6671 break;
6672 case scConstant:
6673 return cast<SCEVConstant>(V)->getValue();
6674 case scUnknown:
6675 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6676 case scSignExtend: {
6677 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6678 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6679 return ConstantExpr::getSExt(CastOp, SS->getType());
6680 break;
6681 }
6682 case scZeroExtend: {
6683 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6684 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6685 return ConstantExpr::getZExt(CastOp, SZ->getType());
6686 break;
6687 }
6688 case scTruncate: {
6689 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6690 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6691 return ConstantExpr::getTrunc(CastOp, ST->getType());
6692 break;
6693 }
6694 case scAddExpr: {
6695 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6696 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006697 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6698 unsigned AS = PTy->getAddressSpace();
6699 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6700 C = ConstantExpr::getBitCast(C, DestPtrTy);
6701 }
Nick Lewyckya6674c72011-10-22 19:58:20 +00006702 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6703 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006704 if (!C2) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006705
6706 // First pointer!
6707 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006708 unsigned AS = C2->getType()->getPointerAddressSpace();
Nick Lewyckya6674c72011-10-22 19:58:20 +00006709 std::swap(C, C2);
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006710 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006711 // The offsets have been converted to bytes. We can add bytes to an
6712 // i8* by GEP with the byte count in the first index.
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006713 C = ConstantExpr::getBitCast(C, DestPtrTy);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006714 }
6715
6716 // Don't bother trying to sum two pointers. We probably can't
6717 // statically compute a load that results from it anyway.
6718 if (C2->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +00006719 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006720
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006721 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6722 if (PTy->getElementType()->isStructTy())
Nick Lewyckya6674c72011-10-22 19:58:20 +00006723 C2 = ConstantExpr::getIntegerCast(
6724 C2, Type::getInt32Ty(C->getContext()), true);
David Blaikie4a2e73b2015-04-02 18:55:32 +00006725 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006726 } else
6727 C = ConstantExpr::getAdd(C, C2);
6728 }
6729 return C;
6730 }
6731 break;
6732 }
6733 case scMulExpr: {
6734 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6735 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6736 // Don't bother with pointers at all.
Craig Topper9f008862014-04-15 04:59:12 +00006737 if (C->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006738 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6739 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006740 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006741 C = ConstantExpr::getMul(C, C2);
6742 }
6743 return C;
6744 }
6745 break;
6746 }
6747 case scUDivExpr: {
6748 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6749 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6750 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6751 if (LHS->getType() == RHS->getType())
6752 return ConstantExpr::getUDiv(LHS, RHS);
6753 break;
6754 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00006755 case scSMaxExpr:
6756 case scUMaxExpr:
6757 break; // TODO: smax, umax.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006758 }
Craig Topper9f008862014-04-15 04:59:12 +00006759 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006760}
6761
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006762const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006763 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00006764
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006765 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattnerdd730472004-04-17 22:58:41 +00006766 // exit value from the loop without using SCEVs.
Dan Gohmana30370b2009-05-04 22:02:23 +00006767 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006768 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006769 const Loop *LI = this->LI[I->getParent()];
Chris Lattnerdd730472004-04-17 22:58:41 +00006770 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
6771 if (PHINode *PN = dyn_cast<PHINode>(I))
6772 if (PN->getParent() == LI->getHeader()) {
6773 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman0bddac12009-02-24 18:55:53 +00006774 // to see if the loop that contains it has a known backedge-taken
6775 // count. If so, we may be able to force computation of the exit
6776 // value.
Dan Gohmanaf752342009-07-07 17:06:11 +00006777 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmana30370b2009-05-04 22:02:23 +00006778 if (const SCEVConstant *BTCC =
Dan Gohman0bddac12009-02-24 18:55:53 +00006779 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006780 // Okay, we know how many times the containing loop executes. If
6781 // this is a constant evolving PHI node, get the final value at
6782 // the specified iteration number.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006783 Constant *RV =
6784 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
Dan Gohman9d203c62009-06-29 21:31:18 +00006785 if (RV) return getSCEV(RV);
Chris Lattnerdd730472004-04-17 22:58:41 +00006786 }
6787 }
6788
Reid Spencere6328ca2006-12-04 21:33:23 +00006789 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattnerdd730472004-04-17 22:58:41 +00006790 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencere6328ca2006-12-04 21:33:23 +00006791 // the arguments into constants, and if so, try to constant propagate the
Chris Lattnerdd730472004-04-17 22:58:41 +00006792 // result. This is particularly useful for computing loop exit values.
6793 if (CanConstantFold(I)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006794 SmallVector<Constant *, 4> Operands;
6795 bool MadeImprovement = false;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00006796 for (Value *Op : I->operands()) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006797 if (Constant *C = dyn_cast<Constant>(Op)) {
6798 Operands.push_back(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006799 continue;
Chris Lattnerdd730472004-04-17 22:58:41 +00006800 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006801
6802 // If any of the operands is non-constant and if they are
6803 // non-integer and non-pointer, don't even try to analyze them
6804 // with scev techniques.
6805 if (!isSCEVable(Op->getType()))
6806 return V;
6807
6808 const SCEV *OrigV = getSCEV(Op);
6809 const SCEV *OpV = getSCEVAtScope(OrigV, L);
6810 MadeImprovement |= OrigV != OpV;
6811
Nick Lewyckya6674c72011-10-22 19:58:20 +00006812 Constant *C = BuildConstantFromSCEV(OpV);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006813 if (!C) return V;
6814 if (C->getType() != Op->getType())
6815 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
6816 Op->getType(),
6817 false),
6818 C, Op->getType());
6819 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00006820 }
Dan Gohmance973df2009-06-24 04:48:43 +00006821
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006822 // Check to see if getSCEVAtScope actually made an improvement.
6823 if (MadeImprovement) {
Craig Topper9f008862014-04-15 04:59:12 +00006824 Constant *C = nullptr;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006825 const DataLayout &DL = getDataLayout();
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006826 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006827 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006828 Operands[1], DL, &TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006829 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
6830 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006831 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006832 } else
Manuel Jacobe9024592016-01-21 06:33:22 +00006833 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006834 if (!C) return V;
Dan Gohman4aad7502010-02-24 19:31:47 +00006835 return getSCEV(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006836 }
Chris Lattnerdd730472004-04-17 22:58:41 +00006837 }
6838 }
6839
6840 // This is some other type of SCEVUnknown, just return it.
6841 return V;
6842 }
6843
Dan Gohmana30370b2009-05-04 22:02:23 +00006844 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006845 // Avoid performing the look-up in the common case where the specified
6846 // expression has no loop-variant portions.
6847 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006848 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006849 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006850 // Okay, at least one of these operands is loop variant but might be
6851 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmance973df2009-06-24 04:48:43 +00006852 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
6853 Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00006854 NewOps.push_back(OpAtScope);
6855
6856 for (++i; i != e; ++i) {
6857 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006858 NewOps.push_back(OpAtScope);
6859 }
6860 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006861 return getAddExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006862 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006863 return getMulExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006864 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006865 return getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006866 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006867 return getUMaxExpr(NewOps);
Torok Edwinfbcc6632009-07-14 16:55:14 +00006868 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00006869 }
6870 }
6871 // If we got here, all operands are loop invariant.
6872 return Comm;
6873 }
6874
Dan Gohmana30370b2009-05-04 22:02:23 +00006875 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006876 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
6877 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky52348302009-01-13 09:18:58 +00006878 if (LHS == Div->getLHS() && RHS == Div->getRHS())
6879 return Div; // must be loop invariant
Dan Gohmanc8e23622009-04-21 23:15:49 +00006880 return getUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00006881 }
6882
6883 // If this is a loop recurrence for a loop that does not contain L, then we
6884 // are dealing with the final value computed by the loop.
Dan Gohmana30370b2009-05-04 22:02:23 +00006885 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006886 // First, attempt to evaluate each operand.
6887 // Avoid performing the look-up in the common case where the specified
6888 // expression has no loop-variant portions.
6889 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
6890 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
6891 if (OpAtScope == AddRec->getOperand(i))
6892 continue;
6893
6894 // Okay, at least one of these operands is loop variant but might be
6895 // foldable. Build a new instance of the folded commutative expression.
6896 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
6897 AddRec->op_begin()+i);
6898 NewOps.push_back(OpAtScope);
6899 for (++i; i != e; ++i)
6900 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
6901
Andrew Trick759ba082011-04-27 01:21:25 +00006902 const SCEV *FoldedRec =
Andrew Trick8b55b732011-03-14 16:50:06 +00006903 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick759ba082011-04-27 01:21:25 +00006904 AddRec->getNoWrapFlags(SCEV::FlagNW));
6905 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick01eff822011-04-27 05:42:17 +00006906 // The addrec may be folded to a nonrecurrence, for example, if the
6907 // induction variable is multiplied by zero after constant folding. Go
6908 // ahead and return the folded value.
Andrew Trick759ba082011-04-27 01:21:25 +00006909 if (!AddRec)
6910 return FoldedRec;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006911 break;
6912 }
6913
6914 // If the scope is outside the addrec's loop, evaluate it by using the
6915 // loop exit value of the addrec.
6916 if (!AddRec->getLoop()->contains(L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006917 // To evaluate this recurrence, we need to know how many times the AddRec
6918 // loop iterates. Compute this now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006919 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006920 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman01808ca2005-04-21 21:13:18 +00006921
Eli Friedman61f67622008-08-04 23:49:06 +00006922 // Then, evaluate the AddRec.
Dan Gohmanc8e23622009-04-21 23:15:49 +00006923 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattnerd934c702004-04-02 20:23:17 +00006924 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006925
Dan Gohman8ca08852009-05-24 23:25:42 +00006926 return AddRec;
Chris Lattnerd934c702004-04-02 20:23:17 +00006927 }
6928
Dan Gohmana30370b2009-05-04 22:02:23 +00006929 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006930 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006931 if (Op == Cast->getOperand())
6932 return Cast; // must be loop invariant
6933 return getZeroExtendExpr(Op, Cast->getType());
6934 }
6935
Dan Gohmana30370b2009-05-04 22:02:23 +00006936 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006937 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006938 if (Op == Cast->getOperand())
6939 return Cast; // must be loop invariant
6940 return getSignExtendExpr(Op, Cast->getType());
6941 }
6942
Dan Gohmana30370b2009-05-04 22:02:23 +00006943 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006944 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006945 if (Op == Cast->getOperand())
6946 return Cast; // must be loop invariant
6947 return getTruncateExpr(Op, Cast->getType());
6948 }
6949
Torok Edwinfbcc6632009-07-14 16:55:14 +00006950 llvm_unreachable("Unknown SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00006951}
6952
Dan Gohmanaf752342009-07-07 17:06:11 +00006953const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00006954 return getSCEVAtScope(getSCEV(V), L);
6955}
6956
Sanjoy Dasf8570812016-05-29 00:38:22 +00006957/// Finds the minimum unsigned root of the following equation:
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006958///
6959/// A * X = B (mod N)
6960///
6961/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
6962/// A and B isn't important.
6963///
6964/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00006965static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006966 ScalarEvolution &SE) {
6967 uint32_t BW = A.getBitWidth();
6968 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
6969 assert(A != 0 && "A must be non-zero.");
6970
6971 // 1. D = gcd(A, N)
6972 //
6973 // The gcd of A and N may have only one prime factor: 2. The number of
6974 // trailing zeros in A is its multiplicity
6975 uint32_t Mult2 = A.countTrailingZeros();
6976 // D = 2^Mult2
6977
6978 // 2. Check if B is divisible by D.
6979 //
6980 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
6981 // is not less than multiplicity of this prime factor for D.
6982 if (B.countTrailingZeros() < Mult2)
Dan Gohman31efa302009-04-18 17:58:19 +00006983 return SE.getCouldNotCompute();
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006984
6985 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
6986 // modulo (N / D).
6987 //
6988 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
6989 // bit width during computations.
6990 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
6991 APInt Mod(BW + 1, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00006992 Mod.setBit(BW - Mult2); // Mod = N / D
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006993 APInt I = AD.multiplicativeInverse(Mod);
6994
6995 // 4. Compute the minimum unsigned root of the equation:
6996 // I * (B / D) mod (N / D)
6997 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
6998
6999 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
7000 // bits.
7001 return SE.getConstant(Result.trunc(BW));
7002}
Chris Lattnerd934c702004-04-02 20:23:17 +00007003
Sanjoy Dasf8570812016-05-29 00:38:22 +00007004/// Find the roots of the quadratic equation for the given quadratic chrec
7005/// {L,+,M,+,N}. This returns either the two roots (which might be the same) or
7006/// two SCEVCouldNotCompute objects.
Chris Lattnerd934c702004-04-02 20:23:17 +00007007///
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007008static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
Dan Gohmana37eaf22007-10-22 18:31:58 +00007009SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007010 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman48f82222009-05-04 22:30:44 +00007011 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7012 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7013 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00007014
Chris Lattnerd934c702004-04-02 20:23:17 +00007015 // We currently can only solve this if the coefficients are constants.
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007016 if (!LC || !MC || !NC)
7017 return None;
Chris Lattnerd934c702004-04-02 20:23:17 +00007018
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007019 uint32_t BitWidth = LC->getAPInt().getBitWidth();
7020 const APInt &L = LC->getAPInt();
7021 const APInt &M = MC->getAPInt();
7022 const APInt &N = NC->getAPInt();
Reid Spencer983e3b32007-03-01 07:25:48 +00007023 APInt Two(BitWidth, 2);
7024 APInt Four(BitWidth, 4);
Misha Brukman01808ca2005-04-21 21:13:18 +00007025
Dan Gohmance973df2009-06-24 04:48:43 +00007026 {
Reid Spencer983e3b32007-03-01 07:25:48 +00007027 using namespace APIntOps;
Zhou Sheng2852d992007-04-07 17:48:27 +00007028 const APInt& C = L;
Reid Spencer983e3b32007-03-01 07:25:48 +00007029 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7030 // The B coefficient is M-N/2
7031 APInt B(M);
7032 B -= sdiv(N,Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00007033
Reid Spencer983e3b32007-03-01 07:25:48 +00007034 // The A coefficient is N/2
Zhou Sheng2852d992007-04-07 17:48:27 +00007035 APInt A(N.sdiv(Two));
Chris Lattnerd934c702004-04-02 20:23:17 +00007036
Reid Spencer983e3b32007-03-01 07:25:48 +00007037 // Compute the B^2-4ac term.
7038 APInt SqrtTerm(B);
7039 SqrtTerm *= B;
7040 SqrtTerm -= Four * (A * C);
Chris Lattnerd934c702004-04-02 20:23:17 +00007041
Nick Lewyckyfb780832012-08-01 09:14:36 +00007042 if (SqrtTerm.isNegative()) {
7043 // The loop is provably infinite.
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007044 return None;
Nick Lewyckyfb780832012-08-01 09:14:36 +00007045 }
7046
Reid Spencer983e3b32007-03-01 07:25:48 +00007047 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7048 // integer value or else APInt::sqrt() will assert.
7049 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman01808ca2005-04-21 21:13:18 +00007050
Dan Gohmance973df2009-06-24 04:48:43 +00007051 // Compute the two solutions for the quadratic formula.
Reid Spencer983e3b32007-03-01 07:25:48 +00007052 // The divisions must be performed as signed divisions.
7053 APInt NegB(-B);
Nick Lewycky31555522011-10-03 07:10:45 +00007054 APInt TwoA(A << 1);
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007055 if (TwoA.isMinValue())
7056 return None;
Nick Lewycky7b14e202008-11-03 02:43:49 +00007057
Owen Anderson47db9412009-07-22 00:24:57 +00007058 LLVMContext &Context = SE.getContext();
Owen Andersonf1f17432009-07-06 22:37:39 +00007059
7060 ConstantInt *Solution1 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007061 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Andersonf1f17432009-07-06 22:37:39 +00007062 ConstantInt *Solution2 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007063 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman01808ca2005-04-21 21:13:18 +00007064
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007065 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7066 cast<SCEVConstant>(SE.getConstant(Solution2)));
Nick Lewycky31555522011-10-03 07:10:45 +00007067 } // end APIntOps namespace
Chris Lattnerd934c702004-04-02 20:23:17 +00007068}
7069
Andrew Trick3ca3f982011-07-26 17:19:55 +00007070ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007071ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00007072 bool AllowPredicates) {
Sanjoy Dasf8570812016-05-29 00:38:22 +00007073
7074 // This is only used for loops with a "x != y" exit test. The exit condition
7075 // is now expressed as a single expression, V = x-y. So the exit test is
7076 // effectively V != 0. We know and take advantage of the fact that this
7077 // expression only being used in a comparison by zero context.
7078
Silviu Baranga6f444df2016-04-08 14:29:09 +00007079 SCEVUnionPredicate P;
Chris Lattnerd934c702004-04-02 20:23:17 +00007080 // If the value is a constant
Dan Gohmana30370b2009-05-04 22:02:23 +00007081 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007082 // If the value is already zero, the branch will execute zero times.
Reid Spencer2e54a152007-03-02 00:28:52 +00007083 if (C->getValue()->isZero()) return C;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007084 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007085 }
7086
Dan Gohman48f82222009-05-04 22:30:44 +00007087 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007088 if (!AddRec && AllowPredicates)
7089 // Try to make this an AddRec using runtime tests, in the first X
7090 // iterations of this loop, where X is the SCEV expression found by the
7091 // algorithm below.
7092 AddRec = convertSCEVToAddRecWithPredicates(V, L, P);
7093
Chris Lattnerd934c702004-04-02 20:23:17 +00007094 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007095 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007096
Chris Lattnerdff679f2011-01-09 22:39:48 +00007097 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7098 // the quadratic equation to solve it.
7099 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007100 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7101 const SCEVConstant *R1 = Roots->first;
7102 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00007103 // Pick the smallest positive root value.
Sanjoy Das0e392d52016-06-15 04:37:50 +00007104 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7105 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00007106 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00007107 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick2a3b7162011-03-09 17:23:39 +00007108
Chris Lattnerd934c702004-04-02 20:23:17 +00007109 // We can only use this value if the chrec ends up with an exact zero
7110 // value at this index. When solving for "X*X != 5", for example, we
7111 // should not accept a root of 2.
Dan Gohmanaf752342009-07-07 17:06:11 +00007112 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmanbe928e32008-06-18 16:23:07 +00007113 if (Val->isZero())
Silviu Baranga6f444df2016-04-08 14:29:09 +00007114 return ExitLimit(R1, R1, P); // We found a quadratic root!
Chris Lattnerd934c702004-04-02 20:23:17 +00007115 }
7116 }
Chris Lattnerdff679f2011-01-09 22:39:48 +00007117 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007118 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007119
Chris Lattnerdff679f2011-01-09 22:39:48 +00007120 // Otherwise we can only handle this if it is affine.
7121 if (!AddRec->isAffine())
7122 return getCouldNotCompute();
7123
7124 // If this is an affine expression, the execution count of this branch is
7125 // the minimum unsigned root of the following equation:
7126 //
7127 // Start + Step*N = 0 (mod 2^BW)
7128 //
7129 // equivalent to:
7130 //
7131 // Step*N = -Start (mod 2^BW)
7132 //
7133 // where BW is the common bit width of Start and Step.
7134
7135 // Get the initial value for the loop.
7136 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7137 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7138
7139 // For now we handle only constant steps.
Andrew Trick8b55b732011-03-14 16:50:06 +00007140 //
7141 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7142 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7143 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7144 // We have not yet seen any such cases.
Chris Lattnerdff679f2011-01-09 22:39:48 +00007145 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
Craig Topper9f008862014-04-15 04:59:12 +00007146 if (!StepC || StepC->getValue()->equalsInt(0))
Chris Lattnerdff679f2011-01-09 22:39:48 +00007147 return getCouldNotCompute();
7148
Andrew Trick8b55b732011-03-14 16:50:06 +00007149 // For positive steps (counting up until unsigned overflow):
7150 // N = -Start/Step (as unsigned)
7151 // For negative steps (counting down to zero):
7152 // N = Start/-Step
7153 // First compute the unsigned distance from zero in the direction of Step.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007154 bool CountDown = StepC->getAPInt().isNegative();
Andrew Trickf1781db2011-03-14 17:28:02 +00007155 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick8b55b732011-03-14 16:50:06 +00007156
7157 // Handle unitary steps, which cannot wraparound.
Andrew Trickf1781db2011-03-14 17:28:02 +00007158 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7159 // N = Distance (as unsigned)
Nick Lewycky31555522011-10-03 07:10:45 +00007160 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
7161 ConstantRange CR = getUnsignedRange(Start);
7162 const SCEV *MaxBECount;
7163 if (!CountDown && CR.getUnsignedMin().isMinValue())
7164 // When counting up, the worst starting value is 1, not 0.
7165 MaxBECount = CR.getUnsignedMax().isMinValue()
7166 ? getConstant(APInt::getMinValue(CR.getBitWidth()))
7167 : getConstant(APInt::getMaxValue(CR.getBitWidth()));
7168 else
7169 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
7170 : -CR.getUnsignedMin());
Silviu Baranga6f444df2016-04-08 14:29:09 +00007171 return ExitLimit(Distance, MaxBECount, P);
Nick Lewycky31555522011-10-03 07:10:45 +00007172 }
Andrew Trick2a3b7162011-03-09 17:23:39 +00007173
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007174 // As a special case, handle the instance where Step is a positive power of
7175 // two. In this case, determining whether Step divides Distance evenly can be
7176 // done by counting and comparing the number of trailing zeros of Step and
7177 // Distance.
7178 if (!CountDown) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007179 const APInt &StepV = StepC->getAPInt();
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007180 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It
7181 // also returns true if StepV is maximally negative (eg, INT_MIN), but that
7182 // case is not handled as this code is guarded by !CountDown.
7183 if (StepV.isPowerOf2() &&
Sanjoy Dasf3132d32015-09-10 05:27:38 +00007184 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) {
7185 // Here we've constrained the equation to be of the form
7186 //
7187 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0)
7188 //
7189 // where we're operating on a W bit wide integer domain and k is
7190 // non-negative. The smallest unsigned solution for X is the trip count.
7191 //
7192 // (0) is equivalent to:
7193 //
7194 // 2^(N + k) * Distance' - 2^N * X = L * 2^W
7195 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N
7196 // <=> 2^k * Distance' - X = L * 2^(W - N)
7197 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1)
7198 //
7199 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS
7200 // by 2^(W - N).
7201 //
7202 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2)
7203 //
7204 // E.g. say we're solving
7205 //
7206 // 2 * Val = 2 * X (in i8) ... (3)
7207 //
7208 // then from (2), we get X = Val URem i8 128 (k = 0 in this case).
7209 //
7210 // Note: It is tempting to solve (3) by setting X = Val, but Val is not
7211 // necessarily the smallest unsigned value of X that satisfies (3).
7212 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3)
7213 // is i8 1, not i8 -127
7214
7215 const auto *ModuloResult = getUDivExactExpr(Distance, Step);
7216
7217 // Since SCEV does not have a URem node, we construct one using a truncate
7218 // and a zero extend.
7219
7220 unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros();
7221 auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth);
7222 auto *WideTy = Distance->getType();
7223
Silviu Baranga6f444df2016-04-08 14:29:09 +00007224 const SCEV *Limit =
7225 getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy);
7226 return ExitLimit(Limit, Limit, P);
Sanjoy Dasf3132d32015-09-10 05:27:38 +00007227 }
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007228 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007229
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007230 // If the condition controls loop exit (the loop exits only if the expression
7231 // is true) and the addition is no-wrap we can use unsigned divide to
7232 // compute the backedge count. In this case, the step may not divide the
7233 // distance, but we don't care because if the condition is "missed" the loop
7234 // will have undefined behavior due to wrapping.
Sanjoy Dasc7f69b92016-06-09 01:13:59 +00007235 if (ControlsExit && AddRec->hasNoSelfWrap() &&
7236 loopHasNoAbnormalExits(AddRec->getLoop())) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007237 const SCEV *Exact =
7238 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007239 return ExitLimit(Exact, Exact, P);
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007240 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007241
Chris Lattnerdff679f2011-01-09 22:39:48 +00007242 // Then, try to solve the above equation provided that Start is constant.
Silviu Baranga6f444df2016-04-08 14:29:09 +00007243 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
7244 const SCEV *E = SolveLinEquationWithOverflow(
7245 StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this);
7246 return ExitLimit(E, E, P);
7247 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007248 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007249}
7250
Andrew Trick3ca3f982011-07-26 17:19:55 +00007251ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007252ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007253 // Loops that look like: while (X == 0) are very strange indeed. We don't
7254 // handle them yet except for the trivial case. This could be expanded in the
7255 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00007256
Chris Lattnerd934c702004-04-02 20:23:17 +00007257 // If the value is a constant, check to see if it is known to be non-zero
7258 // already. If so, the backedge will execute zero times.
Dan Gohmana30370b2009-05-04 22:02:23 +00007259 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky5a3db142008-02-21 09:14:53 +00007260 if (!C->getValue()->isNullValue())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00007261 return getZero(C->getType());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007262 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007263 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007264
Chris Lattnerd934c702004-04-02 20:23:17 +00007265 // We could implement others, but I really doubt anyone writes loops like
7266 // this, and if they did, they would already be constant folded.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007267 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007268}
7269
Dan Gohman4e3c1132010-04-15 16:19:08 +00007270std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanc8e23622009-04-21 23:15:49 +00007271ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohmanfa066ef2009-04-30 20:48:53 +00007272 // If the block has a unique predecessor, then there is no path from the
7273 // predecessor to the block that does not go through the direct edge
7274 // from the predecessor to the block.
Dan Gohmanf9081a22008-09-15 22:18:04 +00007275 if (BasicBlock *Pred = BB->getSinglePredecessor())
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007276 return {Pred, BB};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007277
7278 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman8c77f1a2009-05-18 15:36:09 +00007279 // If the header has a unique predecessor outside the loop, it must be
7280 // a block that has exactly one successor that can reach the loop.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007281 if (Loop *L = LI.getLoopFor(BB))
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007282 return {L->getLoopPredecessor(), L->getHeader()};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007283
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007284 return {nullptr, nullptr};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007285}
7286
Sanjoy Dasf8570812016-05-29 00:38:22 +00007287/// SCEV structural equivalence is usually sufficient for testing whether two
7288/// expressions are equal, however for the purposes of looking for a condition
7289/// guarding a loop, it can be useful to be a little more general, since a
7290/// front-end may have replicated the controlling expression.
Dan Gohman450f4e02009-06-20 00:35:32 +00007291///
Dan Gohmanaf752342009-07-07 17:06:11 +00007292static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman450f4e02009-06-20 00:35:32 +00007293 // Quick check to see if they are the same SCEV.
7294 if (A == B) return true;
7295
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007296 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7297 // Not all instructions that are "identical" compute the same value. For
7298 // instance, two distinct alloca instructions allocating the same type are
7299 // identical and do not read memory; but compute distinct values.
7300 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7301 };
7302
Dan Gohman450f4e02009-06-20 00:35:32 +00007303 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7304 // two different instructions with the same value. Check for this case.
7305 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7306 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7307 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7308 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007309 if (ComputesEqualValues(AI, BI))
Dan Gohman450f4e02009-06-20 00:35:32 +00007310 return true;
7311
7312 // Otherwise assume they may have a different value.
7313 return false;
7314}
7315
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007316bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007317 const SCEV *&LHS, const SCEV *&RHS,
7318 unsigned Depth) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007319 bool Changed = false;
7320
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007321 // If we hit the max recursion limit bail out.
7322 if (Depth >= 3)
7323 return false;
7324
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007325 // Canonicalize a constant to the right side.
7326 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7327 // Check for both operands constant.
7328 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7329 if (ConstantExpr::getICmp(Pred,
7330 LHSC->getValue(),
7331 RHSC->getValue())->isNullValue())
7332 goto trivially_false;
7333 else
7334 goto trivially_true;
7335 }
7336 // Otherwise swap the operands to put the constant on the right.
7337 std::swap(LHS, RHS);
7338 Pred = ICmpInst::getSwappedPredicate(Pred);
7339 Changed = true;
7340 }
7341
7342 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohmandf564ca2010-05-03 17:00:11 +00007343 // addrec's loop, put the addrec on the left. Also make a dominance check,
7344 // as both operands could be addrecs loop-invariant in each other's loop.
7345 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7346 const Loop *L = AR->getLoop();
Dan Gohman20d9ce22010-11-17 21:41:58 +00007347 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007348 std::swap(LHS, RHS);
7349 Pred = ICmpInst::getSwappedPredicate(Pred);
7350 Changed = true;
7351 }
Dan Gohmandf564ca2010-05-03 17:00:11 +00007352 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007353
7354 // If there's a constant operand, canonicalize comparisons with boundary
7355 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7356 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007357 const APInt &RA = RC->getAPInt();
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007358 switch (Pred) {
7359 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
7360 case ICmpInst::ICMP_EQ:
7361 case ICmpInst::ICMP_NE:
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007362 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7363 if (!RA)
7364 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7365 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
Benjamin Kramer406a2db2012-05-30 18:42:43 +00007366 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7367 ME->getOperand(0)->isAllOnesValue()) {
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007368 RHS = AE->getOperand(1);
7369 LHS = ME->getOperand(1);
7370 Changed = true;
7371 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007372 break;
7373 case ICmpInst::ICMP_UGE:
7374 if ((RA - 1).isMinValue()) {
7375 Pred = ICmpInst::ICMP_NE;
7376 RHS = getConstant(RA - 1);
7377 Changed = true;
7378 break;
7379 }
7380 if (RA.isMaxValue()) {
7381 Pred = ICmpInst::ICMP_EQ;
7382 Changed = true;
7383 break;
7384 }
7385 if (RA.isMinValue()) goto trivially_true;
7386
7387 Pred = ICmpInst::ICMP_UGT;
7388 RHS = getConstant(RA - 1);
7389 Changed = true;
7390 break;
7391 case ICmpInst::ICMP_ULE:
7392 if ((RA + 1).isMaxValue()) {
7393 Pred = ICmpInst::ICMP_NE;
7394 RHS = getConstant(RA + 1);
7395 Changed = true;
7396 break;
7397 }
7398 if (RA.isMinValue()) {
7399 Pred = ICmpInst::ICMP_EQ;
7400 Changed = true;
7401 break;
7402 }
7403 if (RA.isMaxValue()) goto trivially_true;
7404
7405 Pred = ICmpInst::ICMP_ULT;
7406 RHS = getConstant(RA + 1);
7407 Changed = true;
7408 break;
7409 case ICmpInst::ICMP_SGE:
7410 if ((RA - 1).isMinSignedValue()) {
7411 Pred = ICmpInst::ICMP_NE;
7412 RHS = getConstant(RA - 1);
7413 Changed = true;
7414 break;
7415 }
7416 if (RA.isMaxSignedValue()) {
7417 Pred = ICmpInst::ICMP_EQ;
7418 Changed = true;
7419 break;
7420 }
7421 if (RA.isMinSignedValue()) goto trivially_true;
7422
7423 Pred = ICmpInst::ICMP_SGT;
7424 RHS = getConstant(RA - 1);
7425 Changed = true;
7426 break;
7427 case ICmpInst::ICMP_SLE:
7428 if ((RA + 1).isMaxSignedValue()) {
7429 Pred = ICmpInst::ICMP_NE;
7430 RHS = getConstant(RA + 1);
7431 Changed = true;
7432 break;
7433 }
7434 if (RA.isMinSignedValue()) {
7435 Pred = ICmpInst::ICMP_EQ;
7436 Changed = true;
7437 break;
7438 }
7439 if (RA.isMaxSignedValue()) goto trivially_true;
7440
7441 Pred = ICmpInst::ICMP_SLT;
7442 RHS = getConstant(RA + 1);
7443 Changed = true;
7444 break;
7445 case ICmpInst::ICMP_UGT:
7446 if (RA.isMinValue()) {
7447 Pred = ICmpInst::ICMP_NE;
7448 Changed = true;
7449 break;
7450 }
7451 if ((RA + 1).isMaxValue()) {
7452 Pred = ICmpInst::ICMP_EQ;
7453 RHS = getConstant(RA + 1);
7454 Changed = true;
7455 break;
7456 }
7457 if (RA.isMaxValue()) goto trivially_false;
7458 break;
7459 case ICmpInst::ICMP_ULT:
7460 if (RA.isMaxValue()) {
7461 Pred = ICmpInst::ICMP_NE;
7462 Changed = true;
7463 break;
7464 }
7465 if ((RA - 1).isMinValue()) {
7466 Pred = ICmpInst::ICMP_EQ;
7467 RHS = getConstant(RA - 1);
7468 Changed = true;
7469 break;
7470 }
7471 if (RA.isMinValue()) goto trivially_false;
7472 break;
7473 case ICmpInst::ICMP_SGT:
7474 if (RA.isMinSignedValue()) {
7475 Pred = ICmpInst::ICMP_NE;
7476 Changed = true;
7477 break;
7478 }
7479 if ((RA + 1).isMaxSignedValue()) {
7480 Pred = ICmpInst::ICMP_EQ;
7481 RHS = getConstant(RA + 1);
7482 Changed = true;
7483 break;
7484 }
7485 if (RA.isMaxSignedValue()) goto trivially_false;
7486 break;
7487 case ICmpInst::ICMP_SLT:
7488 if (RA.isMaxSignedValue()) {
7489 Pred = ICmpInst::ICMP_NE;
7490 Changed = true;
7491 break;
7492 }
7493 if ((RA - 1).isMinSignedValue()) {
7494 Pred = ICmpInst::ICMP_EQ;
7495 RHS = getConstant(RA - 1);
7496 Changed = true;
7497 break;
7498 }
7499 if (RA.isMinSignedValue()) goto trivially_false;
7500 break;
7501 }
7502 }
7503
7504 // Check for obvious equality.
7505 if (HasSameValue(LHS, RHS)) {
7506 if (ICmpInst::isTrueWhenEqual(Pred))
7507 goto trivially_true;
7508 if (ICmpInst::isFalseWhenEqual(Pred))
7509 goto trivially_false;
7510 }
7511
Dan Gohman81585c12010-05-03 16:35:17 +00007512 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7513 // adding or subtracting 1 from one of the operands.
7514 switch (Pred) {
7515 case ICmpInst::ICMP_SLE:
7516 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7517 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007518 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007519 Pred = ICmpInst::ICMP_SLT;
7520 Changed = true;
7521 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007522 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007523 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007524 Pred = ICmpInst::ICMP_SLT;
7525 Changed = true;
7526 }
7527 break;
7528 case ICmpInst::ICMP_SGE:
7529 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007530 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007531 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007532 Pred = ICmpInst::ICMP_SGT;
7533 Changed = true;
7534 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7535 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007536 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007537 Pred = ICmpInst::ICMP_SGT;
7538 Changed = true;
7539 }
7540 break;
7541 case ICmpInst::ICMP_ULE:
7542 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007543 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007544 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007545 Pred = ICmpInst::ICMP_ULT;
7546 Changed = true;
7547 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007548 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007549 Pred = ICmpInst::ICMP_ULT;
7550 Changed = true;
7551 }
7552 break;
7553 case ICmpInst::ICMP_UGE:
7554 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007555 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007556 Pred = ICmpInst::ICMP_UGT;
7557 Changed = true;
7558 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007559 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007560 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007561 Pred = ICmpInst::ICMP_UGT;
7562 Changed = true;
7563 }
7564 break;
7565 default:
7566 break;
7567 }
7568
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007569 // TODO: More simplifications are possible here.
7570
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007571 // Recursively simplify until we either hit a recursion limit or nothing
7572 // changes.
7573 if (Changed)
7574 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7575
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007576 return Changed;
7577
7578trivially_true:
7579 // Return 0 == 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007580 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007581 Pred = ICmpInst::ICMP_EQ;
7582 return true;
7583
7584trivially_false:
7585 // Return 0 != 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007586 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007587 Pred = ICmpInst::ICMP_NE;
7588 return true;
7589}
7590
Dan Gohmane65c9172009-07-13 21:35:55 +00007591bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7592 return getSignedRange(S).getSignedMax().isNegative();
7593}
7594
7595bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7596 return getSignedRange(S).getSignedMin().isStrictlyPositive();
7597}
7598
7599bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7600 return !getSignedRange(S).getSignedMin().isNegative();
7601}
7602
7603bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7604 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7605}
7606
7607bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7608 return isKnownNegative(S) || isKnownPositive(S);
7609}
7610
7611bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7612 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman36cce7e2010-04-24 01:38:36 +00007613 // Canonicalize the inputs first.
7614 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7615
Dan Gohman07591692010-04-11 22:16:48 +00007616 // If LHS or RHS is an addrec, check to see if the condition is true in
7617 // every iteration of the loop.
Justin Bognercbb84382014-05-23 00:06:56 +00007618 // If LHS and RHS are both addrec, both conditions must be true in
7619 // every iteration of the loop.
7620 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7621 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7622 bool LeftGuarded = false;
7623 bool RightGuarded = false;
7624 if (LAR) {
7625 const Loop *L = LAR->getLoop();
7626 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7627 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7628 if (!RAR) return true;
7629 LeftGuarded = true;
7630 }
7631 }
7632 if (RAR) {
7633 const Loop *L = RAR->getLoop();
7634 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7635 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7636 if (!LAR) return true;
7637 RightGuarded = true;
7638 }
7639 }
7640 if (LeftGuarded && RightGuarded)
7641 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007642
Sanjoy Das7d910f22015-10-02 18:50:30 +00007643 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7644 return true;
7645
Dan Gohman07591692010-04-11 22:16:48 +00007646 // Otherwise see what can be done with known constant ranges.
Sanjoy Das401e6312016-02-01 20:48:10 +00007647 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
Dan Gohman07591692010-04-11 22:16:48 +00007648}
7649
Sanjoy Das5dab2052015-07-27 21:42:49 +00007650bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7651 ICmpInst::Predicate Pred,
7652 bool &Increasing) {
7653 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7654
7655#ifndef NDEBUG
7656 // Verify an invariant: inverting the predicate should turn a monotonically
7657 // increasing change to a monotonically decreasing one, and vice versa.
7658 bool IncreasingSwapped;
7659 bool ResultSwapped = isMonotonicPredicateImpl(
7660 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7661
7662 assert(Result == ResultSwapped && "should be able to analyze both!");
7663 if (ResultSwapped)
7664 assert(Increasing == !IncreasingSwapped &&
7665 "monotonicity should flip as we flip the predicate");
7666#endif
7667
7668 return Result;
7669}
7670
7671bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7672 ICmpInst::Predicate Pred,
7673 bool &Increasing) {
Sanjoy Das5dab2052015-07-27 21:42:49 +00007674
7675 // A zero step value for LHS means the induction variable is essentially a
7676 // loop invariant value. We don't really depend on the predicate actually
7677 // flipping from false to true (for increasing predicates, and the other way
7678 // around for decreasing predicates), all we care about is that *if* the
7679 // predicate changes then it only changes from false to true.
7680 //
7681 // A zero step value in itself is not very useful, but there may be places
7682 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7683 // as general as possible.
7684
Sanjoy Das366acc12015-08-06 20:43:41 +00007685 switch (Pred) {
7686 default:
7687 return false; // Conservative answer
7688
7689 case ICmpInst::ICMP_UGT:
7690 case ICmpInst::ICMP_UGE:
7691 case ICmpInst::ICMP_ULT:
7692 case ICmpInst::ICMP_ULE:
Sanjoy Das76c48e02016-02-04 18:21:54 +00007693 if (!LHS->hasNoUnsignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007694 return false;
7695
7696 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007697 return true;
Sanjoy Das366acc12015-08-06 20:43:41 +00007698
7699 case ICmpInst::ICMP_SGT:
7700 case ICmpInst::ICMP_SGE:
7701 case ICmpInst::ICMP_SLT:
7702 case ICmpInst::ICMP_SLE: {
Sanjoy Das76c48e02016-02-04 18:21:54 +00007703 if (!LHS->hasNoSignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007704 return false;
7705
7706 const SCEV *Step = LHS->getStepRecurrence(*this);
7707
7708 if (isKnownNonNegative(Step)) {
7709 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7710 return true;
7711 }
7712
7713 if (isKnownNonPositive(Step)) {
7714 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7715 return true;
7716 }
7717
7718 return false;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007719 }
7720
Sanjoy Das5dab2052015-07-27 21:42:49 +00007721 }
7722
Sanjoy Das366acc12015-08-06 20:43:41 +00007723 llvm_unreachable("switch has default clause!");
Sanjoy Das5dab2052015-07-27 21:42:49 +00007724}
7725
7726bool ScalarEvolution::isLoopInvariantPredicate(
7727 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7728 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7729 const SCEV *&InvariantRHS) {
7730
7731 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7732 if (!isLoopInvariant(RHS, L)) {
7733 if (!isLoopInvariant(LHS, L))
7734 return false;
7735
7736 std::swap(LHS, RHS);
7737 Pred = ICmpInst::getSwappedPredicate(Pred);
7738 }
7739
7740 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7741 if (!ArLHS || ArLHS->getLoop() != L)
7742 return false;
7743
7744 bool Increasing;
7745 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7746 return false;
7747
7748 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7749 // true as the loop iterates, and the backedge is control dependent on
7750 // "ArLHS `Pred` RHS" == true then we can reason as follows:
7751 //
7752 // * if the predicate was false in the first iteration then the predicate
7753 // is never evaluated again, since the loop exits without taking the
7754 // backedge.
7755 // * if the predicate was true in the first iteration then it will
7756 // continue to be true for all future iterations since it is
7757 // monotonically increasing.
7758 //
7759 // For both the above possibilities, we can replace the loop varying
7760 // predicate with its value on the first iteration of the loop (which is
7761 // loop invariant).
7762 //
7763 // A similar reasoning applies for a monotonically decreasing predicate, by
7764 // replacing true with false and false with true in the above two bullets.
7765
7766 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7767
7768 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7769 return false;
7770
7771 InvariantPred = Pred;
7772 InvariantLHS = ArLHS->getStart();
7773 InvariantRHS = RHS;
7774 return true;
7775}
7776
Sanjoy Das401e6312016-02-01 20:48:10 +00007777bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7778 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00007779 if (HasSameValue(LHS, RHS))
7780 return ICmpInst::isTrueWhenEqual(Pred);
7781
Dan Gohman07591692010-04-11 22:16:48 +00007782 // This code is split out from isKnownPredicate because it is called from
7783 // within isLoopEntryGuardedByCond.
Dan Gohmane65c9172009-07-13 21:35:55 +00007784
Sanjoy Das4c7b6d72016-02-01 20:48:14 +00007785 auto CheckRanges =
7786 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7787 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7788 .contains(RangeLHS);
7789 };
7790
7791 // The check at the top of the function catches the case where the values are
7792 // known to be equal.
7793 if (Pred == CmpInst::ICMP_EQ)
7794 return false;
7795
7796 if (Pred == CmpInst::ICMP_NE)
7797 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7798 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7799 isKnownNonZero(getMinusSCEV(LHS, RHS));
7800
7801 if (CmpInst::isSigned(Pred))
7802 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7803
7804 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
Dan Gohmane65c9172009-07-13 21:35:55 +00007805}
7806
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007807bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7808 const SCEV *LHS,
7809 const SCEV *RHS) {
7810
7811 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7812 // Return Y via OutY.
7813 auto MatchBinaryAddToConst =
7814 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7815 SCEV::NoWrapFlags ExpectedFlags) {
7816 const SCEV *NonConstOp, *ConstOp;
7817 SCEV::NoWrapFlags FlagsPresent;
7818
7819 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7820 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7821 return false;
7822
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007823 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007824 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7825 };
7826
7827 APInt C;
7828
7829 switch (Pred) {
7830 default:
7831 break;
7832
7833 case ICmpInst::ICMP_SGE:
7834 std::swap(LHS, RHS);
7835 case ICmpInst::ICMP_SLE:
7836 // X s<= (X + C)<nsw> if C >= 0
7837 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7838 return true;
7839
7840 // (X + C)<nsw> s<= X if C <= 0
7841 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7842 !C.isStrictlyPositive())
7843 return true;
7844 break;
7845
7846 case ICmpInst::ICMP_SGT:
7847 std::swap(LHS, RHS);
7848 case ICmpInst::ICMP_SLT:
7849 // X s< (X + C)<nsw> if C > 0
7850 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7851 C.isStrictlyPositive())
7852 return true;
7853
7854 // (X + C)<nsw> s< X if C < 0
7855 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7856 return true;
7857 break;
7858 }
7859
7860 return false;
7861}
7862
Sanjoy Das7d910f22015-10-02 18:50:30 +00007863bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7864 const SCEV *LHS,
7865 const SCEV *RHS) {
Sanjoy Das10dffcb2015-10-08 03:46:00 +00007866 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
Sanjoy Das7d910f22015-10-02 18:50:30 +00007867 return false;
7868
7869 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7870 // the stack can result in exponential time complexity.
7871 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7872
7873 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7874 //
7875 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7876 // isKnownPredicate. isKnownPredicate is more powerful, but also more
7877 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7878 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
7879 // use isKnownPredicate later if needed.
Alexander Kornienko484e48e32015-11-05 21:07:12 +00007880 return isKnownNonNegative(RHS) &&
7881 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7882 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
Sanjoy Das7d910f22015-10-02 18:50:30 +00007883}
7884
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007885bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
7886 ICmpInst::Predicate Pred,
7887 const SCEV *LHS, const SCEV *RHS) {
7888 // No need to even try if we know the module has no guards.
7889 if (!HasGuards)
7890 return false;
7891
7892 return any_of(*BB, [&](Instruction &I) {
7893 using namespace llvm::PatternMatch;
7894
7895 Value *Condition;
7896 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
7897 m_Value(Condition))) &&
7898 isImpliedCond(Pred, LHS, RHS, Condition, false);
7899 });
7900}
7901
Dan Gohmane65c9172009-07-13 21:35:55 +00007902/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7903/// protected by a conditional between LHS and RHS. This is used to
7904/// to eliminate casts.
7905bool
7906ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7907 ICmpInst::Predicate Pred,
7908 const SCEV *LHS, const SCEV *RHS) {
7909 // Interpret a null as meaning no loop, where there is obviously no guard
7910 // (interprocedural conditions notwithstanding).
7911 if (!L) return true;
7912
Sanjoy Das401e6312016-02-01 20:48:10 +00007913 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7914 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00007915
Dan Gohmane65c9172009-07-13 21:35:55 +00007916 BasicBlock *Latch = L->getLoopLatch();
7917 if (!Latch)
7918 return false;
7919
7920 BranchInst *LoopContinuePredicate =
7921 dyn_cast<BranchInst>(Latch->getTerminator());
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007922 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7923 isImpliedCond(Pred, LHS, RHS,
7924 LoopContinuePredicate->getCondition(),
7925 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7926 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007927
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007928 // We don't want more than one activation of the following loops on the stack
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007929 // -- that can lead to O(n!) time complexity.
7930 if (WalkingBEDominatingConds)
7931 return false;
7932
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +00007933 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007934
Sanjoy Dasb174f9a2015-09-25 23:53:50 +00007935 // See if we can exploit a trip count to prove the predicate.
7936 const auto &BETakenInfo = getBackedgeTakenInfo(L);
7937 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
7938 if (LatchBECount != getCouldNotCompute()) {
7939 // We know that Latch branches back to the loop header exactly
7940 // LatchBECount times. This means the backdege condition at Latch is
7941 // equivalent to "{0,+,1} u< LatchBECount".
7942 Type *Ty = LatchBECount->getType();
7943 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
7944 const SCEV *LoopCounter =
7945 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
7946 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
7947 LatchBECount))
7948 return true;
7949 }
7950
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007951 // Check conditions due to any @llvm.assume intrinsics.
7952 for (auto &AssumeVH : AC.assumptions()) {
7953 if (!AssumeVH)
7954 continue;
7955 auto *CI = cast<CallInst>(AssumeVH);
7956 if (!DT.dominates(CI, Latch->getTerminator()))
7957 continue;
7958
7959 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7960 return true;
7961 }
7962
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007963 // If the loop is not reachable from the entry block, we risk running into an
7964 // infinite loop as we walk up into the dom tree. These loops do not matter
7965 // anyway, so we just return a conservative answer when we see them.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007966 if (!DT.isReachableFromEntry(L->getHeader()))
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007967 return false;
7968
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007969 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
7970 return true;
7971
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007972 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
7973 DTN != HeaderDTN; DTN = DTN->getIDom()) {
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007974
7975 assert(DTN && "should reach the loop header before reaching the root!");
7976
7977 BasicBlock *BB = DTN->getBlock();
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007978 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
7979 return true;
7980
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007981 BasicBlock *PBB = BB->getSinglePredecessor();
7982 if (!PBB)
7983 continue;
7984
7985 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
7986 if (!ContinuePredicate || !ContinuePredicate->isConditional())
7987 continue;
7988
7989 Value *Condition = ContinuePredicate->getCondition();
7990
7991 // If we have an edge `E` within the loop body that dominates the only
7992 // latch, the condition guarding `E` also guards the backedge. This
7993 // reasoning works only for loops with a single latch.
7994
7995 BasicBlockEdge DominatingEdge(PBB, BB);
7996 if (DominatingEdge.isSingleEdge()) {
7997 // We're constructively (and conservatively) enumerating edges within the
7998 // loop body that dominate the latch. The dominator tree better agree
7999 // with us on this:
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008000 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008001
8002 if (isImpliedCond(Pred, LHS, RHS, Condition,
8003 BB != ContinuePredicate->getSuccessor(0)))
8004 return true;
8005 }
8006 }
8007
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008008 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008009}
8010
Dan Gohmane65c9172009-07-13 21:35:55 +00008011bool
Dan Gohmanb50349a2010-04-11 19:27:13 +00008012ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
8013 ICmpInst::Predicate Pred,
8014 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman9cf09f82009-05-18 16:03:58 +00008015 // Interpret a null as meaning no loop, where there is obviously no guard
8016 // (interprocedural conditions notwithstanding).
8017 if (!L) return false;
8018
Sanjoy Das401e6312016-02-01 20:48:10 +00008019 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8020 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00008021
Dan Gohman8c77f1a2009-05-18 15:36:09 +00008022 // Starting at the loop predecessor, climb up the predecessor chain, as long
8023 // as there are predecessors that can be found that have unique successors
Dan Gohmanf9081a22008-09-15 22:18:04 +00008024 // leading to the original header.
Dan Gohman4e3c1132010-04-15 16:19:08 +00008025 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman75c6b0b2010-06-22 23:43:28 +00008026 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman4e3c1132010-04-15 16:19:08 +00008027 Pair.first;
8028 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman2a62fd92008-08-12 20:17:31 +00008029
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008030 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8031 return true;
8032
Dan Gohman2a62fd92008-08-12 20:17:31 +00008033 BranchInst *LoopEntryPredicate =
Dan Gohman4e3c1132010-04-15 16:19:08 +00008034 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman2a62fd92008-08-12 20:17:31 +00008035 if (!LoopEntryPredicate ||
8036 LoopEntryPredicate->isUnconditional())
8037 continue;
8038
Dan Gohmane18c2d62010-08-10 23:46:30 +00008039 if (isImpliedCond(Pred, LHS, RHS,
8040 LoopEntryPredicate->getCondition(),
Dan Gohman4e3c1132010-04-15 16:19:08 +00008041 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman2a62fd92008-08-12 20:17:31 +00008042 return true;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008043 }
8044
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008045 // Check conditions due to any @llvm.assume intrinsics.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008046 for (auto &AssumeVH : AC.assumptions()) {
Chandler Carruth66b31302015-01-04 12:03:27 +00008047 if (!AssumeVH)
8048 continue;
8049 auto *CI = cast<CallInst>(AssumeVH);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008050 if (!DT.dominates(CI, L->getHeader()))
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008051 continue;
8052
8053 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8054 return true;
8055 }
8056
Dan Gohman2a62fd92008-08-12 20:17:31 +00008057 return false;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008058}
8059
Dan Gohmane18c2d62010-08-10 23:46:30 +00008060bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008061 const SCEV *LHS, const SCEV *RHS,
Dan Gohmane18c2d62010-08-10 23:46:30 +00008062 Value *FoundCondValue,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008063 bool Inverse) {
Sanjoy Dasc46bceb2016-09-27 18:01:42 +00008064 if (!PendingLoopPredicates.insert(FoundCondValue).second)
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008065 return false;
8066
Sanjoy Dasc46bceb2016-09-27 18:01:42 +00008067 auto ClearOnExit =
8068 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8069
Dan Gohman8b0a4192010-03-01 17:49:51 +00008070 // Recursively handle And and Or conditions.
Dan Gohmane18c2d62010-08-10 23:46:30 +00008071 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008072 if (BO->getOpcode() == Instruction::And) {
8073 if (!Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008074 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8075 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008076 } else if (BO->getOpcode() == Instruction::Or) {
8077 if (Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008078 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8079 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008080 }
8081 }
8082
Dan Gohmane18c2d62010-08-10 23:46:30 +00008083 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008084 if (!ICI) return false;
8085
Andrew Trickfa594032012-11-29 18:35:13 +00008086 // Now that we found a conditional branch that dominates the loop or controls
8087 // the loop latch. Check to see if it is the comparison we are looking for.
Dan Gohman430f0cc2009-07-21 23:03:19 +00008088 ICmpInst::Predicate FoundPred;
8089 if (Inverse)
8090 FoundPred = ICI->getInversePredicate();
8091 else
8092 FoundPred = ICI->getPredicate();
8093
8094 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8095 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohmane65c9172009-07-13 21:35:55 +00008096
Sanjoy Dasdf1635d2015-09-25 19:59:52 +00008097 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8098}
8099
8100bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8101 const SCEV *RHS,
8102 ICmpInst::Predicate FoundPred,
8103 const SCEV *FoundLHS,
8104 const SCEV *FoundRHS) {
Sanjoy Das14598832015-03-26 17:28:26 +00008105 // Balance the types.
8106 if (getTypeSizeInBits(LHS->getType()) <
8107 getTypeSizeInBits(FoundLHS->getType())) {
8108 if (CmpInst::isSigned(Pred)) {
8109 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8110 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8111 } else {
8112 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8113 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8114 }
8115 } else if (getTypeSizeInBits(LHS->getType()) >
Dan Gohmane65c9172009-07-13 21:35:55 +00008116 getTypeSizeInBits(FoundLHS->getType())) {
Stepan Dyatkovskiy431993b2014-01-09 12:26:12 +00008117 if (CmpInst::isSigned(FoundPred)) {
Dan Gohmane65c9172009-07-13 21:35:55 +00008118 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8119 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8120 } else {
8121 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8122 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8123 }
8124 }
8125
Dan Gohman430f0cc2009-07-21 23:03:19 +00008126 // Canonicalize the query to match the way instcombine will have
8127 // canonicalized the comparison.
Dan Gohman3673aa12010-04-24 01:34:53 +00008128 if (SimplifyICmpOperands(Pred, LHS, RHS))
8129 if (LHS == RHS)
Dan Gohmanb5025c72010-05-03 18:00:24 +00008130 return CmpInst::isTrueWhenEqual(Pred);
Benjamin Kramerba11a982012-11-29 19:07:57 +00008131 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8132 if (FoundLHS == FoundRHS)
8133 return CmpInst::isFalseWhenEqual(FoundPred);
Dan Gohman430f0cc2009-07-21 23:03:19 +00008134
8135 // Check to see if we can make the LHS or RHS match.
8136 if (LHS == FoundRHS || RHS == FoundLHS) {
8137 if (isa<SCEVConstant>(RHS)) {
8138 std::swap(FoundLHS, FoundRHS);
8139 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8140 } else {
8141 std::swap(LHS, RHS);
8142 Pred = ICmpInst::getSwappedPredicate(Pred);
8143 }
8144 }
8145
8146 // Check whether the found predicate is the same as the desired predicate.
8147 if (FoundPred == Pred)
8148 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8149
8150 // Check whether swapping the found predicate makes it the same as the
8151 // desired predicate.
8152 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8153 if (isa<SCEVConstant>(RHS))
8154 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8155 else
8156 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8157 RHS, LHS, FoundLHS, FoundRHS);
8158 }
8159
Sanjoy Das6e78b172015-10-22 19:57:34 +00008160 // Unsigned comparison is the same as signed comparison when both the operands
8161 // are non-negative.
8162 if (CmpInst::isUnsigned(FoundPred) &&
8163 CmpInst::getSignedPredicate(FoundPred) == Pred &&
8164 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8165 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8166
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008167 // Check if we can make progress by sharpening ranges.
8168 if (FoundPred == ICmpInst::ICMP_NE &&
8169 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8170
8171 const SCEVConstant *C = nullptr;
8172 const SCEV *V = nullptr;
8173
8174 if (isa<SCEVConstant>(FoundLHS)) {
8175 C = cast<SCEVConstant>(FoundLHS);
8176 V = FoundRHS;
8177 } else {
8178 C = cast<SCEVConstant>(FoundRHS);
8179 V = FoundLHS;
8180 }
8181
8182 // The guarding predicate tells us that C != V. If the known range
8183 // of V is [C, t), we can sharpen the range to [C + 1, t). The
8184 // range we consider has to correspond to same signedness as the
8185 // predicate we're interested in folding.
8186
8187 APInt Min = ICmpInst::isSigned(Pred) ?
8188 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8189
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008190 if (Min == C->getAPInt()) {
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008191 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8192 // This is true even if (Min + 1) wraps around -- in case of
8193 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8194
8195 APInt SharperMin = Min + 1;
8196
8197 switch (Pred) {
8198 case ICmpInst::ICMP_SGE:
8199 case ICmpInst::ICMP_UGE:
8200 // We know V `Pred` SharperMin. If this implies LHS `Pred`
8201 // RHS, we're done.
8202 if (isImpliedCondOperands(Pred, LHS, RHS, V,
8203 getConstant(SharperMin)))
8204 return true;
8205
8206 case ICmpInst::ICMP_SGT:
8207 case ICmpInst::ICMP_UGT:
8208 // We know from the range information that (V `Pred` Min ||
8209 // V == Min). We know from the guarding condition that !(V
8210 // == Min). This gives us
8211 //
8212 // V `Pred` Min || V == Min && !(V == Min)
8213 // => V `Pred` Min
8214 //
8215 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8216
8217 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8218 return true;
8219
8220 default:
8221 // No change
8222 break;
8223 }
8224 }
8225 }
8226
Dan Gohman430f0cc2009-07-21 23:03:19 +00008227 // Check whether the actual condition is beyond sufficient.
8228 if (FoundPred == ICmpInst::ICMP_EQ)
8229 if (ICmpInst::isTrueWhenEqual(Pred))
8230 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8231 return true;
8232 if (Pred == ICmpInst::ICMP_NE)
8233 if (!ICmpInst::isTrueWhenEqual(FoundPred))
8234 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8235 return true;
8236
8237 // Otherwise assume the worst.
8238 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008239}
8240
Sanjoy Das1ed69102015-10-13 02:53:27 +00008241bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8242 const SCEV *&L, const SCEV *&R,
8243 SCEV::NoWrapFlags &Flags) {
8244 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8245 if (!AE || AE->getNumOperands() != 2)
8246 return false;
8247
8248 L = AE->getOperand(0);
8249 R = AE->getOperand(1);
8250 Flags = AE->getNoWrapFlags();
8251 return true;
8252}
8253
Sanjoy Das0b1af852016-07-23 00:28:56 +00008254Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8255 const SCEV *Less) {
Sanjoy Das96709c42015-09-25 23:53:45 +00008256 // We avoid subtracting expressions here because this function is usually
8257 // fairly deep in the call stack (i.e. is called many times).
8258
Sanjoy Das96709c42015-09-25 23:53:45 +00008259 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8260 const auto *LAR = cast<SCEVAddRecExpr>(Less);
8261 const auto *MAR = cast<SCEVAddRecExpr>(More);
8262
8263 if (LAR->getLoop() != MAR->getLoop())
Sanjoy Das0b1af852016-07-23 00:28:56 +00008264 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008265
8266 // We look at affine expressions only; not for correctness but to keep
8267 // getStepRecurrence cheap.
8268 if (!LAR->isAffine() || !MAR->isAffine())
Sanjoy Das0b1af852016-07-23 00:28:56 +00008269 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008270
Sanjoy Das1ed69102015-10-13 02:53:27 +00008271 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008272 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008273
8274 Less = LAR->getStart();
8275 More = MAR->getStart();
8276
8277 // fall through
8278 }
8279
8280 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008281 const auto &M = cast<SCEVConstant>(More)->getAPInt();
8282 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
Sanjoy Das0b1af852016-07-23 00:28:56 +00008283 return M - L;
Sanjoy Das96709c42015-09-25 23:53:45 +00008284 }
8285
8286 const SCEV *L, *R;
Sanjoy Das1ed69102015-10-13 02:53:27 +00008287 SCEV::NoWrapFlags Flags;
8288 if (splitBinaryAdd(Less, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008289 if (const auto *LC = dyn_cast<SCEVConstant>(L))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008290 if (R == More)
8291 return -(LC->getAPInt());
Sanjoy Das96709c42015-09-25 23:53:45 +00008292
Sanjoy Das1ed69102015-10-13 02:53:27 +00008293 if (splitBinaryAdd(More, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008294 if (const auto *LC = dyn_cast<SCEVConstant>(L))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008295 if (R == Less)
8296 return LC->getAPInt();
Sanjoy Das96709c42015-09-25 23:53:45 +00008297
Sanjoy Das0b1af852016-07-23 00:28:56 +00008298 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008299}
8300
8301bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8302 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8303 const SCEV *FoundLHS, const SCEV *FoundRHS) {
8304 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8305 return false;
8306
8307 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8308 if (!AddRecLHS)
8309 return false;
8310
8311 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8312 if (!AddRecFoundLHS)
8313 return false;
8314
8315 // We'd like to let SCEV reason about control dependencies, so we constrain
8316 // both the inequalities to be about add recurrences on the same loop. This
8317 // way we can use isLoopEntryGuardedByCond later.
8318
8319 const Loop *L = AddRecFoundLHS->getLoop();
8320 if (L != AddRecLHS->getLoop())
8321 return false;
8322
8323 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
8324 //
8325 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8326 // ... (2)
8327 //
8328 // Informal proof for (2), assuming (1) [*]:
8329 //
8330 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8331 //
8332 // Then
8333 //
8334 // FoundLHS s< FoundRHS s< INT_MIN - C
8335 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
8336 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8337 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
8338 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8339 // <=> FoundLHS + C s< FoundRHS + C
8340 //
8341 // [*]: (1) can be proved by ruling out overflow.
8342 //
8343 // [**]: This can be proved by analyzing all the four possibilities:
8344 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8345 // (A s>= 0, B s>= 0).
8346 //
8347 // Note:
8348 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8349 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
8350 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
8351 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
8352 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8353 // C)".
8354
Sanjoy Das0b1af852016-07-23 00:28:56 +00008355 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8356 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8357 if (!LDiff || !RDiff || *LDiff != *RDiff)
Sanjoy Das96709c42015-09-25 23:53:45 +00008358 return false;
8359
Sanjoy Das0b1af852016-07-23 00:28:56 +00008360 if (LDiff->isMinValue())
Sanjoy Das96709c42015-09-25 23:53:45 +00008361 return true;
8362
Sanjoy Das96709c42015-09-25 23:53:45 +00008363 APInt FoundRHSLimit;
8364
8365 if (Pred == CmpInst::ICMP_ULT) {
Sanjoy Das0b1af852016-07-23 00:28:56 +00008366 FoundRHSLimit = -(*RDiff);
Sanjoy Das96709c42015-09-25 23:53:45 +00008367 } else {
8368 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
Sanjoy Das0b1af852016-07-23 00:28:56 +00008369 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
Sanjoy Das96709c42015-09-25 23:53:45 +00008370 }
8371
8372 // Try to prove (1) or (2), as needed.
8373 return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8374 getConstant(FoundRHSLimit));
8375}
8376
Dan Gohman430f0cc2009-07-21 23:03:19 +00008377bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8378 const SCEV *LHS, const SCEV *RHS,
8379 const SCEV *FoundLHS,
8380 const SCEV *FoundRHS) {
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008381 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8382 return true;
8383
Sanjoy Das96709c42015-09-25 23:53:45 +00008384 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8385 return true;
8386
Dan Gohman430f0cc2009-07-21 23:03:19 +00008387 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8388 FoundLHS, FoundRHS) ||
8389 // ~x < ~y --> x > y
8390 isImpliedCondOperandsHelper(Pred, LHS, RHS,
8391 getNotSCEV(FoundRHS),
8392 getNotSCEV(FoundLHS));
8393}
8394
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008395
8396/// If Expr computes ~A, return A else return nullptr
8397static const SCEV *MatchNotExpr(const SCEV *Expr) {
8398 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008399 if (!Add || Add->getNumOperands() != 2 ||
8400 !Add->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008401 return nullptr;
8402
8403 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008404 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8405 !AddRHS->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008406 return nullptr;
8407
8408 return AddRHS->getOperand(1);
8409}
8410
8411
8412/// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8413template<typename MaxExprType>
8414static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8415 const SCEV *Candidate) {
8416 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8417 if (!MaxExpr) return false;
8418
Sanjoy Das347d2722015-12-01 07:49:27 +00008419 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008420}
8421
8422
8423/// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8424template<typename MaxExprType>
8425static bool IsMinConsistingOf(ScalarEvolution &SE,
8426 const SCEV *MaybeMinExpr,
8427 const SCEV *Candidate) {
8428 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8429 if (!MaybeMaxExpr)
8430 return false;
8431
8432 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8433}
8434
Hal Finkela8d205f2015-08-19 01:51:51 +00008435static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8436 ICmpInst::Predicate Pred,
8437 const SCEV *LHS, const SCEV *RHS) {
8438
8439 // If both sides are affine addrecs for the same loop, with equal
8440 // steps, and we know the recurrences don't wrap, then we only
8441 // need to check the predicate on the starting values.
8442
8443 if (!ICmpInst::isRelational(Pred))
8444 return false;
8445
8446 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8447 if (!LAR)
8448 return false;
8449 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8450 if (!RAR)
8451 return false;
8452 if (LAR->getLoop() != RAR->getLoop())
8453 return false;
8454 if (!LAR->isAffine() || !RAR->isAffine())
8455 return false;
8456
8457 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8458 return false;
8459
Hal Finkelff08a2e2015-08-19 17:26:07 +00008460 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8461 SCEV::FlagNSW : SCEV::FlagNUW;
8462 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
Hal Finkela8d205f2015-08-19 01:51:51 +00008463 return false;
8464
8465 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8466}
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008467
8468/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8469/// expression?
8470static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8471 ICmpInst::Predicate Pred,
8472 const SCEV *LHS, const SCEV *RHS) {
8473 switch (Pred) {
8474 default:
8475 return false;
8476
8477 case ICmpInst::ICMP_SGE:
8478 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008479 LLVM_FALLTHROUGH;
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008480 case ICmpInst::ICMP_SLE:
8481 return
8482 // min(A, ...) <= A
8483 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8484 // A <= max(A, ...)
8485 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8486
8487 case ICmpInst::ICMP_UGE:
8488 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008489 LLVM_FALLTHROUGH;
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008490 case ICmpInst::ICMP_ULE:
8491 return
8492 // min(A, ...) <= A
8493 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8494 // A <= max(A, ...)
8495 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8496 }
8497
8498 llvm_unreachable("covered switch fell through?!");
8499}
8500
Dan Gohmane65c9172009-07-13 21:35:55 +00008501bool
Dan Gohman430f0cc2009-07-21 23:03:19 +00008502ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8503 const SCEV *LHS, const SCEV *RHS,
8504 const SCEV *FoundLHS,
8505 const SCEV *FoundRHS) {
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008506 auto IsKnownPredicateFull =
8507 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Sanjoy Das401e6312016-02-01 20:48:10 +00008508 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
Sanjoy Das11231482015-10-22 19:57:29 +00008509 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
Sanjoy Dasc1a29772015-11-05 23:45:38 +00008510 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8511 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008512 };
8513
Dan Gohmane65c9172009-07-13 21:35:55 +00008514 switch (Pred) {
Dan Gohman8c129d72009-07-16 17:34:36 +00008515 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8516 case ICmpInst::ICMP_EQ:
8517 case ICmpInst::ICMP_NE:
8518 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8519 return true;
8520 break;
Dan Gohmane65c9172009-07-13 21:35:55 +00008521 case ICmpInst::ICMP_SLT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008522 case ICmpInst::ICMP_SLE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008523 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8524 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008525 return true;
8526 break;
8527 case ICmpInst::ICMP_SGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008528 case ICmpInst::ICMP_SGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008529 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8530 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008531 return true;
8532 break;
8533 case ICmpInst::ICMP_ULT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008534 case ICmpInst::ICMP_ULE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008535 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8536 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008537 return true;
8538 break;
8539 case ICmpInst::ICMP_UGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008540 case ICmpInst::ICMP_UGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008541 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8542 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008543 return true;
8544 break;
8545 }
8546
8547 return false;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008548}
8549
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008550bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8551 const SCEV *LHS,
8552 const SCEV *RHS,
8553 const SCEV *FoundLHS,
8554 const SCEV *FoundRHS) {
8555 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8556 // The restriction on `FoundRHS` be lifted easily -- it exists only to
8557 // reduce the compile time impact of this optimization.
8558 return false;
8559
Sanjoy Dasa7d9ec82016-07-23 00:54:36 +00008560 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
Sanjoy Das095f5b22016-07-22 20:47:55 +00008561 if (!Addend)
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008562 return false;
8563
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008564 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008565
8566 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8567 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8568 ConstantRange FoundLHSRange =
8569 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8570
Sanjoy Das095f5b22016-07-22 20:47:55 +00008571 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
8572 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008573
8574 // We can also compute the range of values for `LHS` that satisfy the
8575 // consequent, "`LHS` `Pred` `RHS`":
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008576 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008577 ConstantRange SatisfyingLHSRange =
8578 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8579
8580 // The antecedent implies the consequent if every value of `LHS` that
8581 // satisfies the antecedent also satisfies the consequent.
8582 return SatisfyingLHSRange.contains(LHSRange);
8583}
8584
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008585bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8586 bool IsSigned, bool NoWrap) {
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008587 assert(isKnownPositive(Stride) && "Positive stride expected!");
8588
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008589 if (NoWrap) return false;
Dan Gohman51aaf022010-01-26 04:40:18 +00008590
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008591 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008592 const SCEV *One = getOne(Stride->getType());
Andrew Trick2afa3252011-03-09 17:29:58 +00008593
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008594 if (IsSigned) {
8595 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8596 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8597 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8598 .getSignedMax();
Andrew Trick2afa3252011-03-09 17:29:58 +00008599
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008600 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8601 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
Dan Gohman36bad002009-09-17 18:05:20 +00008602 }
Dan Gohman01048422009-06-21 23:46:38 +00008603
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008604 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8605 APInt MaxValue = APInt::getMaxValue(BitWidth);
8606 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8607 .getUnsignedMax();
8608
8609 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8610 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8611}
8612
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008613bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8614 bool IsSigned, bool NoWrap) {
8615 if (NoWrap) return false;
8616
8617 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008618 const SCEV *One = getOne(Stride->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008619
8620 if (IsSigned) {
8621 APInt MinRHS = getSignedRange(RHS).getSignedMin();
8622 APInt MinValue = APInt::getSignedMinValue(BitWidth);
8623 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8624 .getSignedMax();
8625
8626 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8627 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8628 }
8629
8630 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8631 APInt MinValue = APInt::getMinValue(BitWidth);
8632 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8633 .getUnsignedMax();
8634
8635 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8636 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8637}
8638
Johannes Doerfert2683e562015-02-09 12:34:23 +00008639const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008640 bool Equality) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008641 const SCEV *One = getOne(Step->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008642 Delta = Equality ? getAddExpr(Delta, Step)
8643 : getAddExpr(Delta, getMinusSCEV(Step, One));
8644 return getUDivExpr(Delta, Step);
Dan Gohman01048422009-06-21 23:46:38 +00008645}
8646
Andrew Trick3ca3f982011-07-26 17:19:55 +00008647ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00008648ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008649 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008650 bool ControlsExit, bool AllowPredicates) {
8651 SCEVUnionPredicate P;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008652 // We handle only IV < Invariant
8653 if (!isLoopInvariant(RHS, L))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00008654 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008655
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008656 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008657 bool PredicatedIV = false;
8658
8659 if (!IV && AllowPredicates) {
Silviu Baranga6f444df2016-04-08 14:29:09 +00008660 // Try to make this an AddRec using runtime tests, in the first X
8661 // iterations of this loop, where X is the SCEV expression found by the
8662 // algorithm below.
8663 IV = convertSCEVToAddRecWithPredicates(LHS, L, P);
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008664 PredicatedIV = true;
8665 }
Dan Gohman2b8da352009-04-30 20:47:05 +00008666
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008667 // Avoid weird loops
8668 if (!IV || IV->getLoop() != L || !IV->isAffine())
8669 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008670
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008671 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008672 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008673
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008674 const SCEV *Stride = IV->getStepRecurrence(*this);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008675
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008676 bool PositiveStride = isKnownPositive(Stride);
Dan Gohman2b8da352009-04-30 20:47:05 +00008677
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008678 // Avoid negative or zero stride values.
8679 if (!PositiveStride) {
8680 // We can compute the correct backedge taken count for loops with unknown
8681 // strides if we can prove that the loop is not an infinite loop with side
8682 // effects. Here's the loop structure we are trying to handle -
8683 //
8684 // i = start
8685 // do {
8686 // A[i] = i;
8687 // i += s;
8688 // } while (i < end);
8689 //
8690 // The backedge taken count for such loops is evaluated as -
8691 // (max(end, start + stride) - start - 1) /u stride
8692 //
8693 // The additional preconditions that we need to check to prove correctness
8694 // of the above formula is as follows -
8695 //
8696 // a) IV is either nuw or nsw depending upon signedness (indicated by the
8697 // NoWrap flag).
8698 // b) loop is single exit with no side effects.
8699 //
8700 //
8701 // Precondition a) implies that if the stride is negative, this is a single
8702 // trip loop. The backedge taken count formula reduces to zero in this case.
8703 //
8704 // Precondition b) implies that the unknown stride cannot be zero otherwise
8705 // we have UB.
8706 //
8707 // The positive stride case is the same as isKnownPositive(Stride) returning
8708 // true (original behavior of the function).
8709 //
8710 // We want to make sure that the stride is truly unknown as there are edge
8711 // cases where ScalarEvolution propagates no wrap flags to the
8712 // post-increment/decrement IV even though the increment/decrement operation
8713 // itself is wrapping. The computed backedge taken count may be wrong in
8714 // such cases. This is prevented by checking that the stride is not known to
8715 // be either positive or non-positive. For example, no wrap flags are
8716 // propagated to the post-increment IV of this loop with a trip count of 2 -
8717 //
8718 // unsigned char i;
8719 // for(i=127; i<128; i+=129)
8720 // A[i] = i;
8721 //
8722 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
8723 !loopHasNoSideEffects(L))
8724 return getCouldNotCompute();
8725
8726 } else if (!Stride->isOne() &&
8727 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8728 // Avoid proven overflow cases: this will ensure that the backedge taken
8729 // count will not generate any unsigned overflow. Relaxed no-overflow
8730 // conditions exploit NoWrapFlags, allowing to optimize in presence of
8731 // undefined behaviors like the case of C language.
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008732 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00008733
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008734 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8735 : ICmpInst::ICMP_ULT;
8736 const SCEV *Start = IV->getStart();
8737 const SCEV *End = RHS;
Sanjoy Dase8fd9562016-06-18 04:38:31 +00008738 if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
8739 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
Dan Gohman51aaf022010-01-26 04:40:18 +00008740
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008741 const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
Dan Gohman2b8da352009-04-30 20:47:05 +00008742
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008743 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8744 : getUnsignedRange(Start).getUnsignedMin();
Andrew Trick2afa3252011-03-09 17:29:58 +00008745
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008746 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008747
8748 APInt StrideForMaxBECount;
8749
8750 if (PositiveStride)
8751 StrideForMaxBECount = IsSigned ? getSignedRange(Stride).getSignedMin()
8752 : getUnsignedRange(Stride).getUnsignedMin();
8753 else
8754 // Using a stride of 1 is safe when computing max backedge taken count for
8755 // a loop with unknown stride.
8756 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
8757
8758 APInt Limit =
8759 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
8760 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
Chris Lattner587a75b2005-08-15 23:33:51 +00008761
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008762 // Although End can be a MAX expression we estimate MaxEnd considering only
8763 // the case End = RHS. This is safe because in the other case (End - Start)
8764 // is zero, leading to a zero maximum backedge taken count.
8765 APInt MaxEnd =
8766 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8767 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8768
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +00008769 const SCEV *MaxBECount;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008770 if (isa<SCEVConstant>(BECount))
8771 MaxBECount = BECount;
8772 else
8773 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008774 getConstant(StrideForMaxBECount), false);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008775
8776 if (isa<SCEVCouldNotCompute>(MaxBECount))
8777 MaxBECount = BECount;
8778
Silviu Baranga6f444df2016-04-08 14:29:09 +00008779 return ExitLimit(BECount, MaxBECount, P);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008780}
8781
8782ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00008783ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008784 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008785 bool ControlsExit, bool AllowPredicates) {
8786 SCEVUnionPredicate P;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008787 // We handle only IV > Invariant
8788 if (!isLoopInvariant(RHS, L))
8789 return getCouldNotCompute();
8790
8791 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Silviu Baranga6f444df2016-04-08 14:29:09 +00008792 if (!IV && AllowPredicates)
8793 // Try to make this an AddRec using runtime tests, in the first X
8794 // iterations of this loop, where X is the SCEV expression found by the
8795 // algorithm below.
8796 IV = convertSCEVToAddRecWithPredicates(LHS, L, P);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008797
8798 // Avoid weird loops
8799 if (!IV || IV->getLoop() != L || !IV->isAffine())
8800 return getCouldNotCompute();
8801
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008802 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008803 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8804
8805 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8806
8807 // Avoid negative or zero stride values
8808 if (!isKnownPositive(Stride))
8809 return getCouldNotCompute();
8810
8811 // Avoid proven overflow cases: this will ensure that the backedge taken count
8812 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00008813 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008814 // behaviors like the case of C language.
8815 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8816 return getCouldNotCompute();
8817
8818 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8819 : ICmpInst::ICMP_UGT;
8820
8821 const SCEV *Start = IV->getStart();
8822 const SCEV *End = RHS;
Sanjoy Dase8fd9562016-06-18 04:38:31 +00008823 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
8824 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008825
8826 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8827
8828 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8829 : getUnsignedRange(Start).getUnsignedMax();
8830
8831 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8832 : getUnsignedRange(Stride).getUnsignedMin();
8833
8834 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8835 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8836 : APInt::getMinValue(BitWidth) + (MinStride - 1);
8837
8838 // Although End can be a MIN expression we estimate MinEnd considering only
8839 // the case End = RHS. This is safe because in the other case (Start - End)
8840 // is zero, leading to a zero maximum backedge taken count.
8841 APInt MinEnd =
8842 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8843 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8844
8845
8846 const SCEV *MaxBECount = getCouldNotCompute();
8847 if (isa<SCEVConstant>(BECount))
8848 MaxBECount = BECount;
8849 else
Johannes Doerfert2683e562015-02-09 12:34:23 +00008850 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008851 getConstant(MinStride), false);
8852
8853 if (isa<SCEVCouldNotCompute>(MaxBECount))
8854 MaxBECount = BECount;
8855
Silviu Baranga6f444df2016-04-08 14:29:09 +00008856 return ExitLimit(BECount, MaxBECount, P);
Chris Lattner587a75b2005-08-15 23:33:51 +00008857}
8858
Benjamin Kramerc321e532016-06-08 19:09:22 +00008859const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
Dan Gohmance973df2009-06-24 04:48:43 +00008860 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00008861 if (Range.isFullSet()) // Infinite loop.
Dan Gohman31efa302009-04-18 17:58:19 +00008862 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008863
8864 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmana30370b2009-05-04 22:02:23 +00008865 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencer2e54a152007-03-02 00:28:52 +00008866 if (!SC->getValue()->isZero()) {
Dan Gohmanaf752342009-07-07 17:06:11 +00008867 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008868 Operands[0] = SE.getZero(SC->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00008869 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00008870 getNoWrapFlags(FlagNW));
Sanjoy Das63914592015-10-18 00:29:20 +00008871 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattnerd934c702004-04-02 20:23:17 +00008872 return ShiftedAddRec->getNumIterationsInRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008873 Range.subtract(SC->getAPInt()), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00008874 // This is strange and shouldn't happen.
Dan Gohman31efa302009-04-18 17:58:19 +00008875 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008876 }
8877
8878 // The only time we can solve this is when we have all constant indices.
8879 // Otherwise, we cannot determine the overflow conditions.
Sanjoy Dasff3b8b42015-12-01 07:49:23 +00008880 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00008881 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008882
8883 // Okay at this point we know that all elements of the chrec are constants and
8884 // that the start element is zero.
8885
8886 // First check to see if the range contains zero. If not, the first
8887 // iteration exits.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00008888 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +00008889 if (!Range.contains(APInt(BitWidth, 0)))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008890 return SE.getZero(getType());
Misha Brukman01808ca2005-04-21 21:13:18 +00008891
Chris Lattnerd934c702004-04-02 20:23:17 +00008892 if (isAffine()) {
8893 // If this is an affine expression then we have this situation:
8894 // Solve {0,+,A} in Range === Ax in Range
8895
Nick Lewycky52460262007-07-16 02:08:00 +00008896 // We know that zero is in the range. If A is positive then we know that
8897 // the upper value of the range must be the first possible exit value.
8898 // If A is negative then the lower of the range is the last possible loop
8899 // value. Also note that we already checked for a full range.
Dan Gohman0a40ad92009-04-16 03:18:22 +00008900 APInt One(BitWidth,1);
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008901 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
Nick Lewycky52460262007-07-16 02:08:00 +00008902 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattnerd934c702004-04-02 20:23:17 +00008903
Nick Lewycky52460262007-07-16 02:08:00 +00008904 // The exit value should be (End+A)/A.
Nick Lewycky39349612007-09-27 14:12:54 +00008905 APInt ExitVal = (End + A).udiv(A);
Owen Andersonedb4a702009-07-24 23:12:02 +00008906 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00008907
8908 // Evaluate at the exit value. If we really did fall out of the valid
8909 // range, then we computed our trip count, otherwise wrap around or other
8910 // things must have happened.
Dan Gohmana37eaf22007-10-22 18:31:58 +00008911 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008912 if (Range.contains(Val->getValue()))
Dan Gohman31efa302009-04-18 17:58:19 +00008913 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008914
8915 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00008916 assert(Range.contains(
Dan Gohmance973df2009-06-24 04:48:43 +00008917 EvaluateConstantChrecAtConstant(this,
Owen Andersonedb4a702009-07-24 23:12:02 +00008918 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattnerd934c702004-04-02 20:23:17 +00008919 "Linear scev computation is off in a bad way!");
Dan Gohmana37eaf22007-10-22 18:31:58 +00008920 return SE.getConstant(ExitValue);
Chris Lattnerd934c702004-04-02 20:23:17 +00008921 } else if (isQuadratic()) {
8922 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
8923 // quadratic equation to solve it. To do this, we must frame our problem in
8924 // terms of figuring out when zero is crossed, instead of when
8925 // Range.getUpper() is crossed.
Dan Gohmanaf752342009-07-07 17:06:11 +00008926 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00008927 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Andrew Trick8b55b732011-03-14 16:50:06 +00008928 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
8929 // getNoWrapFlags(FlagNW)
8930 FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00008931
8932 // Next, solve the constructed addrec
Sanjoy Das0e392d52016-06-15 04:37:50 +00008933 if (auto Roots =
8934 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00008935 const SCEVConstant *R1 = Roots->first;
8936 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00008937 // Pick the smallest positive root value.
Sanjoy Das01947432015-11-22 21:20:13 +00008938 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8939 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00008940 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00008941 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00008942
Chris Lattnerd934c702004-04-02 20:23:17 +00008943 // Make sure the root is not off by one. The returned iteration should
8944 // not be in the range, but the previous one should be. When solving
8945 // for "X*X < 5", for example, we should not return a root of 2.
Sanjoy Das0e392d52016-06-15 04:37:50 +00008946 ConstantInt *R1Val =
8947 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008948 if (Range.contains(R1Val->getValue())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00008949 // The next iteration must be out of the range...
Owen Andersonf1f17432009-07-06 22:37:39 +00008950 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008951 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
Misha Brukman01808ca2005-04-21 21:13:18 +00008952
Dan Gohmana37eaf22007-10-22 18:31:58 +00008953 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008954 if (!Range.contains(R1Val->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00008955 return SE.getConstant(NextVal);
Sanjoy Das0e392d52016-06-15 04:37:50 +00008956 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008957 }
Misha Brukman01808ca2005-04-21 21:13:18 +00008958
Chris Lattnerd934c702004-04-02 20:23:17 +00008959 // If R1 was not in the range, then it is a good return value. Make
8960 // sure that R1-1 WAS in the range though, just in case.
Owen Andersonf1f17432009-07-06 22:37:39 +00008961 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008962 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
Dan Gohmana37eaf22007-10-22 18:31:58 +00008963 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008964 if (Range.contains(R1Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00008965 return R1;
Sanjoy Das0e392d52016-06-15 04:37:50 +00008966 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008967 }
8968 }
8969 }
8970
Dan Gohman31efa302009-04-18 17:58:19 +00008971 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008972}
8973
Sebastian Pop448712b2014-05-07 18:01:20 +00008974namespace {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008975struct FindUndefs {
8976 bool Found;
8977 FindUndefs() : Found(false) {}
8978
8979 bool follow(const SCEV *S) {
8980 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
8981 if (isa<UndefValue>(C->getValue()))
8982 Found = true;
8983 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
8984 if (isa<UndefValue>(C->getValue()))
8985 Found = true;
8986 }
8987
8988 // Keep looking if we haven't found it yet.
8989 return !Found;
8990 }
8991 bool isDone() const {
8992 // Stop recursion if we have found an undef.
8993 return Found;
8994 }
8995};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00008996}
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008997
8998// Return true when S contains at least an undef value.
8999static inline bool
9000containsUndefs(const SCEV *S) {
9001 FindUndefs F;
9002 SCEVTraversal<FindUndefs> ST(F);
9003 ST.visitAll(S);
9004
9005 return F.Found;
9006}
9007
9008namespace {
Sebastian Pop448712b2014-05-07 18:01:20 +00009009// Collect all steps of SCEV expressions.
9010struct SCEVCollectStrides {
9011 ScalarEvolution &SE;
9012 SmallVectorImpl<const SCEV *> &Strides;
9013
9014 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
9015 : SE(SE), Strides(S) {}
9016
9017 bool follow(const SCEV *S) {
9018 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
9019 Strides.push_back(AR->getStepRecurrence(SE));
9020 return true;
9021 }
9022 bool isDone() const { return false; }
9023};
9024
9025// Collect all SCEVUnknown and SCEVMulExpr expressions.
9026struct SCEVCollectTerms {
9027 SmallVectorImpl<const SCEV *> &Terms;
9028
9029 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9030 : Terms(T) {}
9031
9032 bool follow(const SCEV *S) {
Sebastian Popa6e58602014-05-27 22:41:45 +00009033 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009034 if (!containsUndefs(S))
9035 Terms.push_back(S);
Sebastian Pop448712b2014-05-07 18:01:20 +00009036
9037 // Stop recursion: once we collected a term, do not walk its operands.
9038 return false;
9039 }
9040
9041 // Keep looking.
9042 return true;
9043 }
9044 bool isDone() const { return false; }
9045};
Tobias Grosser374bce02015-10-12 08:02:00 +00009046
9047// Check if a SCEV contains an AddRecExpr.
9048struct SCEVHasAddRec {
9049 bool &ContainsAddRec;
9050
9051 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9052 ContainsAddRec = false;
9053 }
9054
9055 bool follow(const SCEV *S) {
9056 if (isa<SCEVAddRecExpr>(S)) {
9057 ContainsAddRec = true;
9058
9059 // Stop recursion: once we collected a term, do not walk its operands.
9060 return false;
9061 }
9062
9063 // Keep looking.
9064 return true;
9065 }
9066 bool isDone() const { return false; }
9067};
9068
9069// Find factors that are multiplied with an expression that (possibly as a
9070// subexpression) contains an AddRecExpr. In the expression:
9071//
9072// 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
9073//
9074// "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9075// that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9076// parameters as they form a product with an induction variable.
9077//
9078// This collector expects all array size parameters to be in the same MulExpr.
9079// It might be necessary to later add support for collecting parameters that are
9080// spread over different nested MulExpr.
9081struct SCEVCollectAddRecMultiplies {
9082 SmallVectorImpl<const SCEV *> &Terms;
9083 ScalarEvolution &SE;
9084
9085 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9086 : Terms(T), SE(SE) {}
9087
9088 bool follow(const SCEV *S) {
9089 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9090 bool HasAddRec = false;
9091 SmallVector<const SCEV *, 0> Operands;
9092 for (auto Op : Mul->operands()) {
9093 if (isa<SCEVUnknown>(Op)) {
9094 Operands.push_back(Op);
9095 } else {
9096 bool ContainsAddRec;
9097 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9098 visitAll(Op, ContiansAddRec);
9099 HasAddRec |= ContainsAddRec;
9100 }
9101 }
9102 if (Operands.size() == 0)
9103 return true;
9104
9105 if (!HasAddRec)
9106 return false;
9107
9108 Terms.push_back(SE.getMulExpr(Operands));
9109 // Stop recursion: once we collected a term, do not walk its operands.
9110 return false;
9111 }
9112
9113 // Keep looking.
9114 return true;
9115 }
9116 bool isDone() const { return false; }
9117};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00009118}
Sebastian Pop448712b2014-05-07 18:01:20 +00009119
Tobias Grosser374bce02015-10-12 08:02:00 +00009120/// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9121/// two places:
9122/// 1) The strides of AddRec expressions.
9123/// 2) Unknowns that are multiplied with AddRec expressions.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009124void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9125 SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009126 SmallVector<const SCEV *, 4> Strides;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009127 SCEVCollectStrides StrideCollector(*this, Strides);
9128 visitAll(Expr, StrideCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009129
9130 DEBUG({
9131 dbgs() << "Strides:\n";
9132 for (const SCEV *S : Strides)
9133 dbgs() << *S << "\n";
9134 });
9135
9136 for (const SCEV *S : Strides) {
9137 SCEVCollectTerms TermCollector(Terms);
9138 visitAll(S, TermCollector);
9139 }
9140
9141 DEBUG({
9142 dbgs() << "Terms:\n";
9143 for (const SCEV *T : Terms)
9144 dbgs() << *T << "\n";
9145 });
Tobias Grosser374bce02015-10-12 08:02:00 +00009146
9147 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9148 visitAll(Expr, MulCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009149}
9150
Sebastian Popb1a548f2014-05-12 19:01:53 +00009151static bool findArrayDimensionsRec(ScalarEvolution &SE,
Sebastian Pop448712b2014-05-07 18:01:20 +00009152 SmallVectorImpl<const SCEV *> &Terms,
Sebastian Pop47fe7de2014-05-09 22:45:07 +00009153 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pope30bd352014-05-27 22:41:56 +00009154 int Last = Terms.size() - 1;
9155 const SCEV *Step = Terms[Last];
Sebastian Popc62c6792013-11-12 22:47:20 +00009156
Sebastian Pop448712b2014-05-07 18:01:20 +00009157 // End of recursion.
Sebastian Pope30bd352014-05-27 22:41:56 +00009158 if (Last == 0) {
9159 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009160 SmallVector<const SCEV *, 2> Qs;
9161 for (const SCEV *Op : M->operands())
9162 if (!isa<SCEVConstant>(Op))
9163 Qs.push_back(Op);
Sebastian Popc62c6792013-11-12 22:47:20 +00009164
Sebastian Pope30bd352014-05-27 22:41:56 +00009165 Step = SE.getMulExpr(Qs);
Sebastian Popc62c6792013-11-12 22:47:20 +00009166 }
9167
Sebastian Pope30bd352014-05-27 22:41:56 +00009168 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009169 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00009170 }
9171
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009172 for (const SCEV *&Term : Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009173 // Normalize the terms before the next call to findArrayDimensionsRec.
9174 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009175 SCEVDivision::divide(SE, Term, Step, &Q, &R);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009176
9177 // Bail out when GCD does not evenly divide one of the terms.
9178 if (!R->isZero())
9179 return false;
9180
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009181 Term = Q;
Sebastian Popc62c6792013-11-12 22:47:20 +00009182 }
9183
Tobias Grosser3080cf12014-05-08 07:55:34 +00009184 // Remove all SCEVConstants.
David Majnemerc7004902016-08-12 04:32:37 +00009185 Terms.erase(
9186 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9187 Terms.end());
Sebastian Popc62c6792013-11-12 22:47:20 +00009188
Sebastian Pop448712b2014-05-07 18:01:20 +00009189 if (Terms.size() > 0)
Sebastian Popb1a548f2014-05-12 19:01:53 +00009190 if (!findArrayDimensionsRec(SE, Terms, Sizes))
9191 return false;
9192
Sebastian Pope30bd352014-05-27 22:41:56 +00009193 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009194 return true;
Sebastian Pop448712b2014-05-07 18:01:20 +00009195}
Sebastian Popc62c6792013-11-12 22:47:20 +00009196
Sebastian Pop448712b2014-05-07 18:01:20 +00009197// Returns true when S contains at least a SCEVUnknown parameter.
9198static inline bool
9199containsParameters(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +00009200 struct FindParameter {
9201 bool FoundParameter;
9202 FindParameter() : FoundParameter(false) {}
9203
9204 bool follow(const SCEV *S) {
9205 if (isa<SCEVUnknown>(S)) {
9206 FoundParameter = true;
9207 // Stop recursion: we found a parameter.
9208 return false;
9209 }
9210 // Keep looking.
9211 return true;
9212 }
9213 bool isDone() const {
9214 // Stop recursion if we have found a parameter.
9215 return FoundParameter;
9216 }
9217 };
9218
Sebastian Pop448712b2014-05-07 18:01:20 +00009219 FindParameter F;
9220 SCEVTraversal<FindParameter> ST(F);
9221 ST.visitAll(S);
9222
9223 return F.FoundParameter;
9224}
9225
9226// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
9227static inline bool
9228containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
9229 for (const SCEV *T : Terms)
9230 if (containsParameters(T))
9231 return true;
9232 return false;
9233}
9234
9235// Return the number of product terms in S.
9236static inline int numberOfTerms(const SCEV *S) {
9237 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9238 return Expr->getNumOperands();
9239 return 1;
9240}
9241
Sebastian Popa6e58602014-05-27 22:41:45 +00009242static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9243 if (isa<SCEVConstant>(T))
9244 return nullptr;
9245
9246 if (isa<SCEVUnknown>(T))
9247 return T;
9248
9249 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9250 SmallVector<const SCEV *, 2> Factors;
9251 for (const SCEV *Op : M->operands())
9252 if (!isa<SCEVConstant>(Op))
9253 Factors.push_back(Op);
9254
9255 return SE.getMulExpr(Factors);
9256 }
9257
9258 return T;
9259}
9260
9261/// Return the size of an element read or written by Inst.
9262const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9263 Type *Ty;
9264 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9265 Ty = Store->getValueOperand()->getType();
9266 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
Tobias Grosser40ac1002014-06-08 19:21:20 +00009267 Ty = Load->getType();
Sebastian Popa6e58602014-05-27 22:41:45 +00009268 else
9269 return nullptr;
9270
9271 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9272 return getSizeOfExpr(ETy, Ty);
9273}
9274
Sebastian Popa6e58602014-05-27 22:41:45 +00009275void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9276 SmallVectorImpl<const SCEV *> &Sizes,
9277 const SCEV *ElementSize) const {
Sebastian Pop53524082014-05-29 19:44:05 +00009278 if (Terms.size() < 1 || !ElementSize)
Sebastian Pop448712b2014-05-07 18:01:20 +00009279 return;
9280
9281 // Early return when Terms do not contain parameters: we do not delinearize
9282 // non parametric SCEVs.
9283 if (!containsParameters(Terms))
9284 return;
9285
9286 DEBUG({
9287 dbgs() << "Terms:\n";
9288 for (const SCEV *T : Terms)
9289 dbgs() << *T << "\n";
9290 });
9291
9292 // Remove duplicates.
9293 std::sort(Terms.begin(), Terms.end());
9294 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9295
9296 // Put larger terms first.
9297 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9298 return numberOfTerms(LHS) > numberOfTerms(RHS);
9299 });
9300
Sebastian Popa6e58602014-05-27 22:41:45 +00009301 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9302
Tobias Grosser374bce02015-10-12 08:02:00 +00009303 // Try to divide all terms by the element size. If term is not divisible by
9304 // element size, proceed with the original term.
Sebastian Popa6e58602014-05-27 22:41:45 +00009305 for (const SCEV *&Term : Terms) {
9306 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009307 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
Tobias Grosser374bce02015-10-12 08:02:00 +00009308 if (!Q->isZero())
9309 Term = Q;
Sebastian Popa6e58602014-05-27 22:41:45 +00009310 }
9311
9312 SmallVector<const SCEV *, 4> NewTerms;
9313
9314 // Remove constant factors.
9315 for (const SCEV *T : Terms)
9316 if (const SCEV *NewT = removeConstantFactors(SE, T))
9317 NewTerms.push_back(NewT);
9318
Sebastian Pop448712b2014-05-07 18:01:20 +00009319 DEBUG({
9320 dbgs() << "Terms after sorting:\n";
Sebastian Popa6e58602014-05-27 22:41:45 +00009321 for (const SCEV *T : NewTerms)
Sebastian Pop448712b2014-05-07 18:01:20 +00009322 dbgs() << *T << "\n";
9323 });
9324
Sebastian Popa6e58602014-05-27 22:41:45 +00009325 if (NewTerms.empty() ||
9326 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
Sebastian Popb1a548f2014-05-12 19:01:53 +00009327 Sizes.clear();
9328 return;
9329 }
Sebastian Pop448712b2014-05-07 18:01:20 +00009330
Sebastian Popa6e58602014-05-27 22:41:45 +00009331 // The last element to be pushed into Sizes is the size of an element.
9332 Sizes.push_back(ElementSize);
9333
Sebastian Pop448712b2014-05-07 18:01:20 +00009334 DEBUG({
9335 dbgs() << "Sizes:\n";
9336 for (const SCEV *S : Sizes)
9337 dbgs() << *S << "\n";
9338 });
9339}
9340
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009341void ScalarEvolution::computeAccessFunctions(
9342 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9343 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009344
Sebastian Popb1a548f2014-05-12 19:01:53 +00009345 // Early exit in case this SCEV is not an affine multivariate function.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009346 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009347 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009348
Sanjoy Das1195dbe2015-10-08 03:45:58 +00009349 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009350 if (!AR->isAffine())
9351 return;
9352
9353 const SCEV *Res = Expr;
Sebastian Pop448712b2014-05-07 18:01:20 +00009354 int Last = Sizes.size() - 1;
9355 for (int i = Last; i >= 0; i--) {
9356 const SCEV *Q, *R;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009357 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
Sebastian Pop448712b2014-05-07 18:01:20 +00009358
9359 DEBUG({
9360 dbgs() << "Res: " << *Res << "\n";
9361 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9362 dbgs() << "Res divided by Sizes[i]:\n";
9363 dbgs() << "Quotient: " << *Q << "\n";
9364 dbgs() << "Remainder: " << *R << "\n";
9365 });
9366
9367 Res = Q;
9368
Sebastian Popa6e58602014-05-27 22:41:45 +00009369 // Do not record the last subscript corresponding to the size of elements in
9370 // the array.
Sebastian Pop448712b2014-05-07 18:01:20 +00009371 if (i == Last) {
Sebastian Popa6e58602014-05-27 22:41:45 +00009372
9373 // Bail out if the remainder is too complex.
Sebastian Pop28e6b972014-05-27 22:41:51 +00009374 if (isa<SCEVAddRecExpr>(R)) {
9375 Subscripts.clear();
9376 Sizes.clear();
9377 return;
9378 }
Sebastian Popa6e58602014-05-27 22:41:45 +00009379
Sebastian Pop448712b2014-05-07 18:01:20 +00009380 continue;
9381 }
9382
9383 // Record the access function for the current subscript.
9384 Subscripts.push_back(R);
9385 }
9386
9387 // Also push in last position the remainder of the last division: it will be
9388 // the access function of the innermost dimension.
9389 Subscripts.push_back(Res);
9390
9391 std::reverse(Subscripts.begin(), Subscripts.end());
9392
9393 DEBUG({
9394 dbgs() << "Subscripts:\n";
9395 for (const SCEV *S : Subscripts)
9396 dbgs() << *S << "\n";
9397 });
Sebastian Pop448712b2014-05-07 18:01:20 +00009398}
9399
Sebastian Popc62c6792013-11-12 22:47:20 +00009400/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9401/// sizes of an array access. Returns the remainder of the delinearization that
Sebastian Pop7ee14722013-11-13 22:37:58 +00009402/// is the offset start of the array. The SCEV->delinearize algorithm computes
9403/// the multiples of SCEV coefficients: that is a pattern matching of sub
9404/// expressions in the stride and base of a SCEV corresponding to the
9405/// computation of a GCD (greatest common divisor) of base and stride. When
9406/// SCEV->delinearize fails, it returns the SCEV unchanged.
9407///
9408/// For example: when analyzing the memory access A[i][j][k] in this loop nest
9409///
9410/// void foo(long n, long m, long o, double A[n][m][o]) {
9411///
9412/// for (long i = 0; i < n; i++)
9413/// for (long j = 0; j < m; j++)
9414/// for (long k = 0; k < o; k++)
9415/// A[i][j][k] = 1.0;
9416/// }
9417///
9418/// the delinearization input is the following AddRec SCEV:
9419///
9420/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9421///
9422/// From this SCEV, we are able to say that the base offset of the access is %A
9423/// because it appears as an offset that does not divide any of the strides in
9424/// the loops:
9425///
9426/// CHECK: Base offset: %A
9427///
9428/// and then SCEV->delinearize determines the size of some of the dimensions of
9429/// the array as these are the multiples by which the strides are happening:
9430///
9431/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9432///
9433/// Note that the outermost dimension remains of UnknownSize because there are
9434/// no strides that would help identifying the size of the last dimension: when
9435/// the array has been statically allocated, one could compute the size of that
9436/// dimension by dividing the overall size of the array by the size of the known
9437/// dimensions: %m * %o * 8.
9438///
9439/// Finally delinearize provides the access functions for the array reference
9440/// that does correspond to A[i][j][k] of the above C testcase:
9441///
9442/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9443///
9444/// The testcases are checking the output of a function pass:
9445/// DelinearizationPass that walks through all loads and stores of a function
9446/// asking for the SCEV of the memory access with respect to all enclosing
9447/// loops, calling SCEV->delinearize on that and printing the results.
9448
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009449void ScalarEvolution::delinearize(const SCEV *Expr,
Sebastian Pop28e6b972014-05-27 22:41:51 +00009450 SmallVectorImpl<const SCEV *> &Subscripts,
9451 SmallVectorImpl<const SCEV *> &Sizes,
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009452 const SCEV *ElementSize) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009453 // First step: collect parametric terms.
9454 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009455 collectParametricTerms(Expr, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00009456
Sebastian Popb1a548f2014-05-12 19:01:53 +00009457 if (Terms.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009458 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009459
Sebastian Pop448712b2014-05-07 18:01:20 +00009460 // Second step: find subscript sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009461 findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop7ee14722013-11-13 22:37:58 +00009462
Sebastian Popb1a548f2014-05-12 19:01:53 +00009463 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009464 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009465
Sebastian Pop448712b2014-05-07 18:01:20 +00009466 // Third step: compute the access functions for each subscript.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009467 computeAccessFunctions(Expr, Subscripts, Sizes);
Sebastian Popc62c6792013-11-12 22:47:20 +00009468
Sebastian Pop28e6b972014-05-27 22:41:51 +00009469 if (Subscripts.empty())
9470 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009471
Sebastian Pop448712b2014-05-07 18:01:20 +00009472 DEBUG({
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009473 dbgs() << "succeeded to delinearize " << *Expr << "\n";
Sebastian Pop448712b2014-05-07 18:01:20 +00009474 dbgs() << "ArrayDecl[UnknownSize]";
9475 for (const SCEV *S : Sizes)
9476 dbgs() << "[" << *S << "]";
Sebastian Popc62c6792013-11-12 22:47:20 +00009477
Sebastian Pop444621a2014-05-09 22:45:02 +00009478 dbgs() << "\nArrayRef";
9479 for (const SCEV *S : Subscripts)
Sebastian Pop448712b2014-05-07 18:01:20 +00009480 dbgs() << "[" << *S << "]";
9481 dbgs() << "\n";
9482 });
Sebastian Popc62c6792013-11-12 22:47:20 +00009483}
Chris Lattnerd934c702004-04-02 20:23:17 +00009484
9485//===----------------------------------------------------------------------===//
Dan Gohman48f82222009-05-04 22:30:44 +00009486// SCEVCallbackVH Class Implementation
9487//===----------------------------------------------------------------------===//
9488
Dan Gohmand33a0902009-05-19 19:22:47 +00009489void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmandd707af2009-07-13 22:20:53 +00009490 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman48f82222009-05-04 22:30:44 +00009491 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9492 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009493 SE->eraseValueFromMap(getValPtr());
Dan Gohman48f82222009-05-04 22:30:44 +00009494 // this now dangles!
9495}
9496
Dan Gohman7a066722010-07-28 01:09:07 +00009497void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmandd707af2009-07-13 22:20:53 +00009498 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christopheref6d5932010-07-29 01:25:38 +00009499
Dan Gohman48f82222009-05-04 22:30:44 +00009500 // Forget all the expressions associated with users of the old value,
9501 // so that future queries will recompute the expressions using the new
9502 // value.
Dan Gohman7cac9572010-08-02 23:49:30 +00009503 Value *Old = getValPtr();
Chandler Carruthcdf47882014-03-09 03:16:01 +00009504 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
Dan Gohmanf34f8632009-07-14 14:34:04 +00009505 SmallPtrSet<User *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00009506 while (!Worklist.empty()) {
9507 User *U = Worklist.pop_back_val();
9508 // Deleting the Old value will cause this to dangle. Postpone
9509 // that until everything else is done.
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009510 if (U == Old)
Dan Gohman48f82222009-05-04 22:30:44 +00009511 continue;
David Blaikie70573dc2014-11-19 07:49:26 +00009512 if (!Visited.insert(U).second)
Dan Gohmanf34f8632009-07-14 14:34:04 +00009513 continue;
Dan Gohman48f82222009-05-04 22:30:44 +00009514 if (PHINode *PN = dyn_cast<PHINode>(U))
9515 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009516 SE->eraseValueFromMap(U);
Chandler Carruthcdf47882014-03-09 03:16:01 +00009517 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
Dan Gohman48f82222009-05-04 22:30:44 +00009518 }
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009519 // Delete the Old value.
9520 if (PHINode *PN = dyn_cast<PHINode>(Old))
9521 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009522 SE->eraseValueFromMap(Old);
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009523 // this now dangles!
Dan Gohman48f82222009-05-04 22:30:44 +00009524}
9525
Dan Gohmand33a0902009-05-19 19:22:47 +00009526ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman48f82222009-05-04 22:30:44 +00009527 : CallbackVH(V), SE(se) {}
9528
9529//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00009530// ScalarEvolution Class Implementation
9531//===----------------------------------------------------------------------===//
9532
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009533ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
9534 AssumptionCache &AC, DominatorTree &DT,
9535 LoopInfo &LI)
9536 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
9537 CouldNotCompute(new SCEVCouldNotCompute()),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009538 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9539 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009540 FirstUnknown(nullptr) {
9541
9542 // To use guards for proving predicates, we need to scan every instruction in
9543 // relevant basic blocks, and not just terminators. Doing this is a waste of
9544 // time if the IR does not actually contain any calls to
9545 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9546 //
9547 // This pessimizes the case where a pass that preserves ScalarEvolution wants
9548 // to _add_ guards to the module when there weren't any before, and wants
9549 // ScalarEvolution to optimize based on those guards. For now we prefer to be
9550 // efficient in lieu of being smart in that rather obscure case.
9551
9552 auto *GuardDecl = F.getParent()->getFunction(
9553 Intrinsic::getName(Intrinsic::experimental_guard));
9554 HasGuards = GuardDecl && !GuardDecl->use_empty();
9555}
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009556
9557ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009558 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
9559 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009560 ValueExprMap(std::move(Arg.ValueExprMap)),
Sanjoy Dasdb933752016-09-27 18:01:38 +00009561 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009562 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009563 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
Silviu Baranga6f444df2016-04-08 14:29:09 +00009564 PredicatedBackedgeTakenCounts(
9565 std::move(Arg.PredicatedBackedgeTakenCounts)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009566 ConstantEvolutionLoopExitValue(
9567 std::move(Arg.ConstantEvolutionLoopExitValue)),
9568 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9569 LoopDispositions(std::move(Arg.LoopDispositions)),
Sanjoy Das5cb11b62016-09-26 02:44:10 +00009570 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
Chandler Carruth68abda52016-09-26 04:49:58 +00009571 BlockDispositions(std::move(Arg.BlockDispositions)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009572 UnsignedRanges(std::move(Arg.UnsignedRanges)),
9573 SignedRanges(std::move(Arg.SignedRanges)),
9574 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
Silviu Barangae3c05342015-11-02 14:41:02 +00009575 UniquePreds(std::move(Arg.UniquePreds)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009576 SCEVAllocator(std::move(Arg.SCEVAllocator)),
9577 FirstUnknown(Arg.FirstUnknown) {
9578 Arg.FirstUnknown = nullptr;
Dan Gohmanc8e23622009-04-21 23:15:49 +00009579}
9580
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009581ScalarEvolution::~ScalarEvolution() {
Dan Gohman7cac9572010-08-02 23:49:30 +00009582 // Iterate through all the SCEVUnknown instances and call their
9583 // destructors, so that they release their references to their values.
Naomi Musgravef90c1be2015-09-16 23:46:40 +00009584 for (SCEVUnknown *U = FirstUnknown; U;) {
9585 SCEVUnknown *Tmp = U;
9586 U = U->Next;
9587 Tmp->~SCEVUnknown();
9588 }
Craig Topper9f008862014-04-15 04:59:12 +00009589 FirstUnknown = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00009590
Wei Mia49559b2016-02-04 01:27:38 +00009591 ExprValueMap.clear();
Dan Gohman9bad2fb2010-08-27 18:55:03 +00009592 ValueExprMap.clear();
Wei Mia49559b2016-02-04 01:27:38 +00009593 HasRecMap.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009594
9595 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9596 // that a loop had multiple computable exits.
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009597 for (auto &BTCI : BackedgeTakenCounts)
9598 BTCI.second.clear();
Silviu Baranga6f444df2016-04-08 14:29:09 +00009599 for (auto &BTCI : PredicatedBackedgeTakenCounts)
9600 BTCI.second.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009601
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00009602 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00009603 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
Sanjoy Das7d910f22015-10-02 18:50:30 +00009604 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
Dan Gohman0a40ad92009-04-16 03:18:22 +00009605}
9606
Dan Gohmanc8e23622009-04-21 23:15:49 +00009607bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman0bddac12009-02-24 18:55:53 +00009608 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattnerd934c702004-04-02 20:23:17 +00009609}
9610
Dan Gohmanc8e23622009-04-21 23:15:49 +00009611static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +00009612 const Loop *L) {
9613 // Print all inner loops first
Benjamin Krameraa209152016-06-26 17:27:42 +00009614 for (Loop *I : *L)
9615 PrintLoopInfo(OS, SE, I);
Misha Brukman01808ca2005-04-21 21:13:18 +00009616
Dan Gohmanbc694912010-01-09 18:17:45 +00009617 OS << "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009618 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009619 OS << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009620
Dan Gohmancb0efec2009-12-18 01:14:11 +00009621 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009622 L->getExitBlocks(ExitBlocks);
9623 if (ExitBlocks.size() != 1)
Nick Lewyckyd1200b02008-01-02 02:49:20 +00009624 OS << "<multiple exits> ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009625
Dan Gohman0bddac12009-02-24 18:55:53 +00009626 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9627 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattnerd934c702004-04-02 20:23:17 +00009628 } else {
Dan Gohman0bddac12009-02-24 18:55:53 +00009629 OS << "Unpredictable backedge-taken count. ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009630 }
9631
Dan Gohmanbc694912010-01-09 18:17:45 +00009632 OS << "\n"
9633 "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009634 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009635 OS << ": ";
Dan Gohman69942932009-06-24 00:33:16 +00009636
9637 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9638 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
9639 } else {
9640 OS << "Unpredictable max backedge-taken count. ";
9641 }
9642
Silviu Baranga6f444df2016-04-08 14:29:09 +00009643 OS << "\n"
9644 "Loop ";
9645 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9646 OS << ": ";
9647
9648 SCEVUnionPredicate Pred;
9649 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
9650 if (!isa<SCEVCouldNotCompute>(PBT)) {
9651 OS << "Predicated backedge-taken count is " << *PBT << "\n";
9652 OS << " Predicates:\n";
9653 Pred.print(OS, 4);
9654 } else {
9655 OS << "Unpredictable predicated backedge-taken count. ";
9656 }
Dan Gohman69942932009-06-24 00:33:16 +00009657 OS << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00009658}
9659
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009660static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
9661 switch (LD) {
9662 case ScalarEvolution::LoopVariant:
9663 return "Variant";
9664 case ScalarEvolution::LoopInvariant:
9665 return "Invariant";
9666 case ScalarEvolution::LoopComputable:
9667 return "Computable";
9668 }
Simon Pilgrim33ae13d2016-05-01 15:52:31 +00009669 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009670}
9671
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009672void ScalarEvolution::print(raw_ostream &OS) const {
Dan Gohman8b0a4192010-03-01 17:49:51 +00009673 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanc8e23622009-04-21 23:15:49 +00009674 // out SCEV values of all instructions that are interesting. Doing
9675 // this potentially causes it to create new SCEV objects though,
9676 // which technically conflicts with the const qualifier. This isn't
Dan Gohman028e6152009-07-10 20:25:29 +00009677 // observable from outside the class though, so casting away the
9678 // const isn't dangerous.
Dan Gohmancb0efec2009-12-18 01:14:11 +00009679 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattnerd934c702004-04-02 20:23:17 +00009680
Dan Gohmanbc694912010-01-09 18:17:45 +00009681 OS << "Classifying expressions for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009682 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009683 OS << "\n";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009684 for (Instruction &I : instructions(F))
9685 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9686 OS << I << '\n';
Dan Gohman81313fd2008-09-14 17:21:12 +00009687 OS << " --> ";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009688 const SCEV *SV = SE.getSCEV(&I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009689 SV->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009690 if (!isa<SCEVCouldNotCompute>(SV)) {
9691 OS << " U: ";
9692 SE.getUnsignedRange(SV).print(OS);
9693 OS << " S: ";
9694 SE.getSignedRange(SV).print(OS);
9695 }
Misha Brukman01808ca2005-04-21 21:13:18 +00009696
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009697 const Loop *L = LI.getLoopFor(I.getParent());
Dan Gohmanb9063a82009-06-19 17:49:54 +00009698
Dan Gohmanaf752342009-07-07 17:06:11 +00009699 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohmanb9063a82009-06-19 17:49:54 +00009700 if (AtUse != SV) {
9701 OS << " --> ";
9702 AtUse->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009703 if (!isa<SCEVCouldNotCompute>(AtUse)) {
9704 OS << " U: ";
9705 SE.getUnsignedRange(AtUse).print(OS);
9706 OS << " S: ";
9707 SE.getSignedRange(AtUse).print(OS);
9708 }
Dan Gohmanb9063a82009-06-19 17:49:54 +00009709 }
9710
9711 if (L) {
Dan Gohman94c468f2009-06-18 00:37:45 +00009712 OS << "\t\t" "Exits: ";
Dan Gohmanaf752342009-07-07 17:06:11 +00009713 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanafd6db92010-11-17 21:23:15 +00009714 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00009715 OS << "<<Unknown>>";
9716 } else {
9717 OS << *ExitValue;
9718 }
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009719
9720 bool First = true;
9721 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
9722 if (First) {
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009723 OS << "\t\t" "LoopDispositions: { ";
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009724 First = false;
9725 } else {
9726 OS << ", ";
9727 }
9728
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009729 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9730 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009731 }
9732
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009733 for (auto *InnerL : depth_first(L)) {
9734 if (InnerL == L)
9735 continue;
9736 if (First) {
9737 OS << "\t\t" "LoopDispositions: { ";
9738 First = false;
9739 } else {
9740 OS << ", ";
9741 }
9742
9743 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9744 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
9745 }
9746
9747 OS << " }";
Chris Lattnerd934c702004-04-02 20:23:17 +00009748 }
9749
Chris Lattnerd934c702004-04-02 20:23:17 +00009750 OS << "\n";
9751 }
9752
Dan Gohmanbc694912010-01-09 18:17:45 +00009753 OS << "Determining loop execution counts for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009754 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009755 OS << "\n";
Benjamin Krameraa209152016-06-26 17:27:42 +00009756 for (Loop *I : LI)
9757 PrintLoopInfo(OS, &SE, I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009758}
Dan Gohmane20f8242009-04-21 00:47:46 +00009759
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009760ScalarEvolution::LoopDisposition
9761ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009762 auto &Values = LoopDispositions[S];
9763 for (auto &V : Values) {
9764 if (V.getPointer() == L)
9765 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009766 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009767 Values.emplace_back(L, LoopVariant);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009768 LoopDisposition D = computeLoopDisposition(S, L);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009769 auto &Values2 = LoopDispositions[S];
9770 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9771 if (V.getPointer() == L) {
9772 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009773 break;
9774 }
9775 }
9776 return D;
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009777}
9778
9779ScalarEvolution::LoopDisposition
9780ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009781 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009782 case scConstant:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009783 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009784 case scTruncate:
9785 case scZeroExtend:
9786 case scSignExtend:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009787 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohmanafd6db92010-11-17 21:23:15 +00009788 case scAddRecExpr: {
9789 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9790
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009791 // If L is the addrec's loop, it's computable.
9792 if (AR->getLoop() == L)
9793 return LoopComputable;
9794
Dan Gohmanafd6db92010-11-17 21:23:15 +00009795 // Add recurrences are never invariant in the function-body (null loop).
9796 if (!L)
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009797 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009798
9799 // This recurrence is variant w.r.t. L if L contains AR's loop.
9800 if (L->contains(AR->getLoop()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009801 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009802
9803 // This recurrence is invariant w.r.t. L if AR's loop contains L.
9804 if (AR->getLoop()->contains(L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009805 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009806
9807 // This recurrence is variant w.r.t. L if any of its operands
9808 // are variant.
Sanjoy Das01947432015-11-22 21:20:13 +00009809 for (auto *Op : AR->operands())
9810 if (!isLoopInvariant(Op, L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009811 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009812
9813 // Otherwise it's loop-invariant.
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009814 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009815 }
9816 case scAddExpr:
9817 case scMulExpr:
9818 case scUMaxExpr:
9819 case scSMaxExpr: {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009820 bool HasVarying = false;
Sanjoy Das01947432015-11-22 21:20:13 +00009821 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
9822 LoopDisposition D = getLoopDisposition(Op, L);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009823 if (D == LoopVariant)
9824 return LoopVariant;
9825 if (D == LoopComputable)
9826 HasVarying = true;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009827 }
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009828 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009829 }
9830 case scUDivExpr: {
9831 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009832 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9833 if (LD == LoopVariant)
9834 return LoopVariant;
9835 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9836 if (RD == LoopVariant)
9837 return LoopVariant;
9838 return (LD == LoopInvariant && RD == LoopInvariant) ?
9839 LoopInvariant : LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009840 }
9841 case scUnknown:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009842 // All non-instruction values are loop invariant. All instructions are loop
9843 // invariant if they are not contained in the specified loop.
9844 // Instructions are never considered invariant in the function body
9845 // (null loop) because they are defined within the "loop".
Sanjoy Das01947432015-11-22 21:20:13 +00009846 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009847 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9848 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009849 case scCouldNotCompute:
9850 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanafd6db92010-11-17 21:23:15 +00009851 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009852 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009853}
9854
9855bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9856 return getLoopDisposition(S, L) == LoopInvariant;
9857}
9858
9859bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9860 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009861}
Dan Gohman20d9ce22010-11-17 21:41:58 +00009862
Dan Gohman8ea83d82010-11-18 00:34:22 +00009863ScalarEvolution::BlockDisposition
9864ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009865 auto &Values = BlockDispositions[S];
9866 for (auto &V : Values) {
9867 if (V.getPointer() == BB)
9868 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009869 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009870 Values.emplace_back(BB, DoesNotDominateBlock);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009871 BlockDisposition D = computeBlockDisposition(S, BB);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009872 auto &Values2 = BlockDispositions[S];
9873 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9874 if (V.getPointer() == BB) {
9875 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009876 break;
9877 }
9878 }
9879 return D;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009880}
9881
Dan Gohman8ea83d82010-11-18 00:34:22 +00009882ScalarEvolution::BlockDisposition
9883ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009884 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohman20d9ce22010-11-17 21:41:58 +00009885 case scConstant:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009886 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009887 case scTruncate:
9888 case scZeroExtend:
9889 case scSignExtend:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009890 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohman20d9ce22010-11-17 21:41:58 +00009891 case scAddRecExpr: {
9892 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman8ea83d82010-11-18 00:34:22 +00009893 // to test for proper dominance too, because the instruction which
9894 // produces the addrec's value is a PHI, and a PHI effectively properly
9895 // dominates its entire containing block.
Dan Gohman20d9ce22010-11-17 21:41:58 +00009896 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009897 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009898 return DoesNotDominateBlock;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00009899
9900 // Fall through into SCEVNAryExpr handling.
9901 LLVM_FALLTHROUGH;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009902 }
Dan Gohman20d9ce22010-11-17 21:41:58 +00009903 case scAddExpr:
9904 case scMulExpr:
9905 case scUMaxExpr:
9906 case scSMaxExpr: {
9907 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009908 bool Proper = true;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00009909 for (const SCEV *NAryOp : NAry->operands()) {
9910 BlockDisposition D = getBlockDisposition(NAryOp, BB);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009911 if (D == DoesNotDominateBlock)
9912 return DoesNotDominateBlock;
9913 if (D == DominatesBlock)
9914 Proper = false;
9915 }
9916 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009917 }
9918 case scUDivExpr: {
9919 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009920 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
9921 BlockDisposition LD = getBlockDisposition(LHS, BB);
9922 if (LD == DoesNotDominateBlock)
9923 return DoesNotDominateBlock;
9924 BlockDisposition RD = getBlockDisposition(RHS, BB);
9925 if (RD == DoesNotDominateBlock)
9926 return DoesNotDominateBlock;
9927 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
9928 ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009929 }
9930 case scUnknown:
9931 if (Instruction *I =
Dan Gohman8ea83d82010-11-18 00:34:22 +00009932 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
9933 if (I->getParent() == BB)
9934 return DominatesBlock;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009935 if (DT.properlyDominates(I->getParent(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009936 return ProperlyDominatesBlock;
9937 return DoesNotDominateBlock;
9938 }
9939 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009940 case scCouldNotCompute:
9941 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman20d9ce22010-11-17 21:41:58 +00009942 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009943 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman8ea83d82010-11-18 00:34:22 +00009944}
9945
9946bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
9947 return getBlockDisposition(S, BB) >= DominatesBlock;
9948}
9949
9950bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
9951 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009952}
Dan Gohman534749b2010-11-17 22:27:42 +00009953
9954bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
Sanjoy Das7d752672015-12-08 04:32:54 +00009955 // Search for a SCEV expression node within an expression tree.
9956 // Implements SCEVTraversal::Visitor.
9957 struct SCEVSearch {
9958 const SCEV *Node;
9959 bool IsFound;
9960
9961 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
9962
9963 bool follow(const SCEV *S) {
9964 IsFound |= (S == Node);
9965 return !IsFound;
9966 }
9967 bool isDone() const { return IsFound; }
9968 };
9969
Andrew Trick365e31c2012-07-13 23:33:03 +00009970 SCEVSearch Search(Op);
9971 visitAll(S, Search);
9972 return Search.IsFound;
Dan Gohman534749b2010-11-17 22:27:42 +00009973}
Dan Gohman7e6b3932010-11-17 23:28:48 +00009974
9975void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
9976 ValuesAtScopes.erase(S);
9977 LoopDispositions.erase(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009978 BlockDispositions.erase(S);
Dan Gohman7e6b3932010-11-17 23:28:48 +00009979 UnsignedRanges.erase(S);
9980 SignedRanges.erase(S);
Wei Mia49559b2016-02-04 01:27:38 +00009981 ExprValueMap.erase(S);
9982 HasRecMap.erase(S);
Andrew Trick9093e152013-03-26 03:14:53 +00009983
Silviu Baranga6f444df2016-04-08 14:29:09 +00009984 auto RemoveSCEVFromBackedgeMap =
9985 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
9986 for (auto I = Map.begin(), E = Map.end(); I != E;) {
9987 BackedgeTakenInfo &BEInfo = I->second;
9988 if (BEInfo.hasOperand(S, this)) {
9989 BEInfo.clear();
9990 Map.erase(I++);
9991 } else
9992 ++I;
9993 }
9994 };
9995
9996 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
9997 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohman7e6b3932010-11-17 23:28:48 +00009998}
Benjamin Kramer214935e2012-10-26 17:31:32 +00009999
10000typedef DenseMap<const Loop *, std::string> VerifyMap;
Benjamin Kramer24d270d2012-10-27 10:45:01 +000010001
Alp Tokercb402912014-01-24 17:20:08 +000010002/// replaceSubString - Replaces all occurrences of From in Str with To.
Benjamin Kramer24d270d2012-10-27 10:45:01 +000010003static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
10004 size_t Pos = 0;
10005 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
10006 Str.replace(Pos, From.size(), To.data(), To.size());
10007 Pos += To.size();
10008 }
10009}
10010
Benjamin Kramer214935e2012-10-26 17:31:32 +000010011/// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
10012static void
10013getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
Sanjoy Das2fbfb252015-12-23 17:48:14 +000010014 std::string &S = Map[L];
10015 if (S.empty()) {
10016 raw_string_ostream OS(S);
10017 SE.getBackedgeTakenCount(L)->print(OS);
Benjamin Kramer214935e2012-10-26 17:31:32 +000010018
Sanjoy Das2fbfb252015-12-23 17:48:14 +000010019 // false and 0 are semantically equivalent. This can happen in dead loops.
10020 replaceSubString(OS.str(), "false", "0");
10021 // Remove wrap flags, their use in SCEV is highly fragile.
10022 // FIXME: Remove this when SCEV gets smarter about them.
10023 replaceSubString(OS.str(), "<nw>", "");
10024 replaceSubString(OS.str(), "<nsw>", "");
10025 replaceSubString(OS.str(), "<nuw>", "");
Benjamin Kramer214935e2012-10-26 17:31:32 +000010026 }
Sanjoy Das2fbfb252015-12-23 17:48:14 +000010027
JF Bastien61ad8b32015-12-23 18:18:53 +000010028 for (auto *R : reverse(*L))
10029 getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
Benjamin Kramer214935e2012-10-26 17:31:32 +000010030}
10031
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010032void ScalarEvolution::verify() const {
Benjamin Kramer214935e2012-10-26 17:31:32 +000010033 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10034
10035 // Gather stringified backedge taken counts for all loops using SCEV's caches.
10036 // FIXME: It would be much better to store actual values instead of strings,
10037 // but SCEV pointers will change if we drop the caches.
10038 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010039 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
Benjamin Kramer214935e2012-10-26 17:31:32 +000010040 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
10041
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010042 // Gather stringified backedge taken counts for all loops using a fresh
10043 // ScalarEvolution object.
10044 ScalarEvolution SE2(F, TLI, AC, DT, LI);
10045 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10046 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
Benjamin Kramer214935e2012-10-26 17:31:32 +000010047
10048 // Now compare whether they're the same with and without caches. This allows
10049 // verifying that no pass changed the cache.
10050 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
10051 "New loops suddenly appeared!");
10052
10053 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
10054 OldE = BackedgeDumpsOld.end(),
10055 NewI = BackedgeDumpsNew.begin();
10056 OldI != OldE; ++OldI, ++NewI) {
10057 assert(OldI->first == NewI->first && "Loop order changed!");
10058
10059 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
10060 // changes.
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010061 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
Benjamin Kramer214935e2012-10-26 17:31:32 +000010062 // means that a pass is buggy or SCEV has to learn a new pattern but is
10063 // usually not harmful.
10064 if (OldI->second != NewI->second &&
10065 OldI->second.find("undef") == std::string::npos &&
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010066 NewI->second.find("undef") == std::string::npos &&
10067 OldI->second != "***COULDNOTCOMPUTE***" &&
Benjamin Kramer214935e2012-10-26 17:31:32 +000010068 NewI->second != "***COULDNOTCOMPUTE***") {
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010069 dbgs() << "SCEVValidator: SCEV for loop '"
Benjamin Kramer214935e2012-10-26 17:31:32 +000010070 << OldI->first->getHeader()->getName()
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010071 << "' changed from '" << OldI->second
10072 << "' to '" << NewI->second << "'!\n";
Benjamin Kramer214935e2012-10-26 17:31:32 +000010073 std::abort();
10074 }
10075 }
10076
10077 // TODO: Verify more things.
10078}
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010079
Chandler Carruthb4faf132016-03-11 10:22:49 +000010080char ScalarEvolutionAnalysis::PassID;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +000010081
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010082ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +000010083 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +000010084 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
10085 AM.getResult<AssumptionAnalysis>(F),
10086 AM.getResult<DominatorTreeAnalysis>(F),
10087 AM.getResult<LoopAnalysis>(F));
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010088}
10089
10090PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +000010091ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +000010092 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010093 return PreservedAnalyses::all();
10094}
10095
10096INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10097 "Scalar Evolution Analysis", false, true)
10098INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10099INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10100INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10101INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10102INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10103 "Scalar Evolution Analysis", false, true)
10104char ScalarEvolutionWrapperPass::ID = 0;
10105
10106ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10107 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10108}
10109
10110bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10111 SE.reset(new ScalarEvolution(
10112 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
10113 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
10114 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10115 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10116 return false;
10117}
10118
10119void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10120
10121void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10122 SE->print(OS);
10123}
10124
10125void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10126 if (!VerifySCEV)
10127 return;
10128
10129 SE->verify();
10130}
10131
10132void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10133 AU.setPreservesAll();
10134 AU.addRequiredTransitive<AssumptionCacheTracker>();
10135 AU.addRequiredTransitive<LoopInfoWrapperPass>();
10136 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10137 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10138}
Silviu Barangae3c05342015-11-02 14:41:02 +000010139
10140const SCEVPredicate *
10141ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10142 const SCEVConstant *RHS) {
10143 FoldingSetNodeID ID;
10144 // Unique this node based on the arguments
10145 ID.AddInteger(SCEVPredicate::P_Equal);
10146 ID.AddPointer(LHS);
10147 ID.AddPointer(RHS);
10148 void *IP = nullptr;
10149 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10150 return S;
10151 SCEVEqualPredicate *Eq = new (SCEVAllocator)
10152 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10153 UniquePreds.InsertNode(Eq, IP);
10154 return Eq;
10155}
10156
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010157const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10158 const SCEVAddRecExpr *AR,
10159 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10160 FoldingSetNodeID ID;
10161 // Unique this node based on the arguments
10162 ID.AddInteger(SCEVPredicate::P_Wrap);
10163 ID.AddPointer(AR);
10164 ID.AddInteger(AddedFlags);
10165 void *IP = nullptr;
10166 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10167 return S;
10168 auto *OF = new (SCEVAllocator)
10169 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10170 UniquePreds.InsertNode(OF, IP);
10171 return OF;
10172}
10173
Benjamin Kramer83709b12015-11-16 09:01:28 +000010174namespace {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010175
Silviu Barangae3c05342015-11-02 14:41:02 +000010176class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10177public:
Sanjoy Das807d33d2016-02-20 01:44:10 +000010178 // Rewrites \p S in the context of a loop L and the predicate A.
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010179 // If Assume is true, rewrite is free to add further predicates to A
10180 // such that the result will be an AddRecExpr.
Sanjoy Das807d33d2016-02-20 01:44:10 +000010181 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
10182 SCEVUnionPredicate &A, bool Assume) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010183 SCEVPredicateRewriter Rewriter(L, SE, A, Assume);
Sanjoy Das807d33d2016-02-20 01:44:10 +000010184 return Rewriter.visit(S);
Silviu Barangae3c05342015-11-02 14:41:02 +000010185 }
10186
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010187 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
10188 SCEVUnionPredicate &P, bool Assume)
10189 : SCEVRewriteVisitor(SE), P(P), L(L), Assume(Assume) {}
Silviu Barangae3c05342015-11-02 14:41:02 +000010190
10191 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10192 auto ExprPreds = P.getPredicatesForExpr(Expr);
10193 for (auto *Pred : ExprPreds)
Sanjoy Dasb277a422016-06-15 06:53:55 +000010194 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
Silviu Barangae3c05342015-11-02 14:41:02 +000010195 if (IPred->getLHS() == Expr)
10196 return IPred->getRHS();
10197
10198 return Expr;
10199 }
10200
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010201 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10202 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010203 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010204 if (AR && AR->getLoop() == L && AR->isAffine()) {
10205 // This couldn't be folded because the operand didn't have the nuw
10206 // flag. Add the nusw flag as an assumption that we could make.
10207 const SCEV *Step = AR->getStepRecurrence(SE);
10208 Type *Ty = Expr->getType();
10209 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10210 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10211 SE.getSignExtendExpr(Step, Ty), L,
10212 AR->getNoWrapFlags());
10213 }
10214 return SE.getZeroExtendExpr(Operand, Expr->getType());
10215 }
10216
10217 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10218 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010219 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010220 if (AR && AR->getLoop() == L && AR->isAffine()) {
10221 // This couldn't be folded because the operand didn't have the nsw
10222 // flag. Add the nssw flag as an assumption that we could make.
10223 const SCEV *Step = AR->getStepRecurrence(SE);
10224 Type *Ty = Expr->getType();
10225 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10226 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10227 SE.getSignExtendExpr(Step, Ty), L,
10228 AR->getNoWrapFlags());
10229 }
10230 return SE.getSignExtendExpr(Operand, Expr->getType());
10231 }
10232
Silviu Barangae3c05342015-11-02 14:41:02 +000010233private:
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010234 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10235 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10236 auto *A = SE.getWrapPredicate(AR, AddedFlags);
10237 if (!Assume) {
10238 // Check if we've already made this assumption.
10239 if (P.implies(A))
10240 return true;
10241 return false;
10242 }
10243 P.add(A);
10244 return true;
10245 }
10246
Silviu Barangae3c05342015-11-02 14:41:02 +000010247 SCEVUnionPredicate &P;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010248 const Loop *L;
10249 bool Assume;
Silviu Barangae3c05342015-11-02 14:41:02 +000010250};
Benjamin Kramer83709b12015-11-16 09:01:28 +000010251} // end anonymous namespace
Silviu Barangae3c05342015-11-02 14:41:02 +000010252
Sanjoy Das807d33d2016-02-20 01:44:10 +000010253const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
Silviu Barangae3c05342015-11-02 14:41:02 +000010254 SCEVUnionPredicate &Preds) {
Sanjoy Das807d33d2016-02-20 01:44:10 +000010255 return SCEVPredicateRewriter::rewrite(S, L, *this, Preds, false);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010256}
10257
Silviu Barangad68ed852016-03-23 15:29:30 +000010258const SCEVAddRecExpr *
Sanjoy Das807d33d2016-02-20 01:44:10 +000010259ScalarEvolution::convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L,
10260 SCEVUnionPredicate &Preds) {
Silviu Barangad68ed852016-03-23 15:29:30 +000010261 SCEVUnionPredicate TransformPreds;
10262 S = SCEVPredicateRewriter::rewrite(S, L, *this, TransformPreds, true);
10263 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10264
10265 if (!AddRec)
10266 return nullptr;
10267
10268 // Since the transformation was successful, we can now transfer the SCEV
10269 // predicates.
10270 Preds.add(&TransformPreds);
10271 return AddRec;
Silviu Barangae3c05342015-11-02 14:41:02 +000010272}
10273
10274/// SCEV predicates
10275SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10276 SCEVPredicateKind Kind)
10277 : FastID(ID), Kind(Kind) {}
10278
10279SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10280 const SCEVUnknown *LHS,
10281 const SCEVConstant *RHS)
10282 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10283
10284bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010285 const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
Silviu Barangae3c05342015-11-02 14:41:02 +000010286
10287 if (!Op)
10288 return false;
10289
10290 return Op->LHS == LHS && Op->RHS == RHS;
10291}
10292
10293bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10294
10295const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10296
10297void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10298 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10299}
10300
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010301SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10302 const SCEVAddRecExpr *AR,
10303 IncrementWrapFlags Flags)
10304 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10305
10306const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10307
10308bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10309 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10310
10311 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10312}
10313
10314bool SCEVWrapPredicate::isAlwaysTrue() const {
10315 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10316 IncrementWrapFlags IFlags = Flags;
10317
10318 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10319 IFlags = clearFlags(IFlags, IncrementNSSW);
10320
10321 return IFlags == IncrementAnyWrap;
10322}
10323
10324void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10325 OS.indent(Depth) << *getExpr() << " Added Flags: ";
10326 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10327 OS << "<nusw>";
10328 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10329 OS << "<nssw>";
10330 OS << "\n";
10331}
10332
10333SCEVWrapPredicate::IncrementWrapFlags
10334SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10335 ScalarEvolution &SE) {
10336 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10337 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10338
10339 // We can safely transfer the NSW flag as NSSW.
10340 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10341 ImpliedFlags = IncrementNSSW;
10342
10343 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10344 // If the increment is positive, the SCEV NUW flag will also imply the
10345 // WrapPredicate NUSW flag.
10346 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10347 if (Step->getValue()->getValue().isNonNegative())
10348 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10349 }
10350
10351 return ImpliedFlags;
10352}
10353
Silviu Barangae3c05342015-11-02 14:41:02 +000010354/// Union predicates don't get cached so create a dummy set ID for it.
10355SCEVUnionPredicate::SCEVUnionPredicate()
10356 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10357
10358bool SCEVUnionPredicate::isAlwaysTrue() const {
Sanjoy Das3b827c72015-11-29 23:40:53 +000010359 return all_of(Preds,
10360 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010361}
10362
10363ArrayRef<const SCEVPredicate *>
10364SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10365 auto I = SCEVToPreds.find(Expr);
10366 if (I == SCEVToPreds.end())
10367 return ArrayRef<const SCEVPredicate *>();
10368 return I->second;
10369}
10370
10371bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010372 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
Sanjoy Das3b827c72015-11-29 23:40:53 +000010373 return all_of(Set->Preds,
10374 [this](const SCEVPredicate *I) { return this->implies(I); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010375
10376 auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10377 if (ScevPredsIt == SCEVToPreds.end())
10378 return false;
10379 auto &SCEVPreds = ScevPredsIt->second;
10380
Sanjoy Dasff3b8b42015-12-01 07:49:23 +000010381 return any_of(SCEVPreds,
10382 [N](const SCEVPredicate *I) { return I->implies(N); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010383}
10384
10385const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10386
10387void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10388 for (auto Pred : Preds)
10389 Pred->print(OS, Depth);
10390}
10391
10392void SCEVUnionPredicate::add(const SCEVPredicate *N) {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010393 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
Silviu Barangae3c05342015-11-02 14:41:02 +000010394 for (auto Pred : Set->Preds)
10395 add(Pred);
10396 return;
10397 }
10398
10399 if (implies(N))
10400 return;
10401
10402 const SCEV *Key = N->getExpr();
10403 assert(Key && "Only SCEVUnionPredicate doesn't have an "
10404 " associated expression!");
10405
10406 SCEVToPreds[Key].push_back(N);
10407 Preds.push_back(N);
10408}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010409
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010410PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10411 Loop &L)
Silviu Baranga6f444df2016-04-08 14:29:09 +000010412 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010413
10414const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10415 const SCEV *Expr = SE.getSCEV(V);
10416 RewriteEntry &Entry = RewriteMap[Expr];
10417
10418 // If we already have an entry and the version matches, return it.
10419 if (Entry.second && Generation == Entry.first)
10420 return Entry.second;
10421
10422 // We found an entry but it's stale. Rewrite the stale entry
10423 // acording to the current predicate.
10424 if (Entry.second)
10425 Expr = Entry.second;
10426
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010427 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010428 Entry = {Generation, NewSCEV};
10429
10430 return NewSCEV;
10431}
10432
Silviu Baranga6f444df2016-04-08 14:29:09 +000010433const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10434 if (!BackedgeCount) {
10435 SCEVUnionPredicate BackedgePred;
10436 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10437 addPredicate(BackedgePred);
10438 }
10439 return BackedgeCount;
10440}
10441
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010442void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10443 if (Preds.implies(&Pred))
10444 return;
10445 Preds.add(&Pred);
10446 updateGeneration();
10447}
10448
10449const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10450 return Preds;
10451}
10452
10453void PredicatedScalarEvolution::updateGeneration() {
10454 // If the generation number wrapped recompute everything.
10455 if (++Generation == 0) {
10456 for (auto &II : RewriteMap) {
10457 const SCEV *Rewritten = II.second.second;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010458 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010459 }
10460 }
10461}
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010462
10463void PredicatedScalarEvolution::setNoOverflow(
10464 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10465 const SCEV *Expr = getSCEV(V);
10466 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10467
10468 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10469
10470 // Clear the statically implied flags.
10471 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10472 addPredicate(*SE.getWrapPredicate(AR, Flags));
10473
10474 auto II = FlagsMap.insert({V, Flags});
10475 if (!II.second)
10476 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10477}
10478
10479bool PredicatedScalarEvolution::hasNoOverflow(
10480 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10481 const SCEV *Expr = getSCEV(V);
10482 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10483
10484 Flags = SCEVWrapPredicate::clearFlags(
10485 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10486
10487 auto II = FlagsMap.find(V);
10488
10489 if (II != FlagsMap.end())
10490 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10491
10492 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10493}
10494
Silviu Barangad68ed852016-03-23 15:29:30 +000010495const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010496 const SCEV *Expr = this->getSCEV(V);
Silviu Barangad68ed852016-03-23 15:29:30 +000010497 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, Preds);
10498
10499 if (!New)
10500 return nullptr;
10501
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010502 updateGeneration();
10503 RewriteMap[SE.getSCEV(V)] = {Generation, New};
10504 return New;
10505}
10506
Silviu Baranga6f444df2016-04-08 14:29:09 +000010507PredicatedScalarEvolution::PredicatedScalarEvolution(
10508 const PredicatedScalarEvolution &Init)
10509 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10510 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
Benjamin Krameraa209152016-06-26 17:27:42 +000010511 for (const auto &I : Init.FlagsMap)
10512 FlagsMap.insert(I);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010513}
Silviu Barangab77365b2016-04-14 16:08:45 +000010514
10515void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10516 // For each block.
10517 for (auto *BB : L.getBlocks())
10518 for (auto &I : *BB) {
10519 if (!SE.isSCEVable(I.getType()))
10520 continue;
10521
10522 auto *Expr = SE.getSCEV(&I);
10523 auto II = RewriteMap.find(Expr);
10524
10525 if (II == RewriteMap.end())
10526 continue;
10527
10528 // Don't print things that are not interesting.
10529 if (II->second.second == Expr)
10530 continue;
10531
10532 OS.indent(Depth) << "[PSE]" << I << ":\n";
10533 OS.indent(Depth + 2) << *Expr << "\n";
10534 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
10535 }
10536}