blob: 7962222a210a04d921df17ca1e4f4abe058c22c3 [file] [log] [blame]
Nick Lewycky97756402014-09-01 05:17:15 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
Misha Brukman01808ca2005-04-21 21:13:18 +00002//
Chris Lattnerd934c702004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman01808ca2005-04-21 21:13:18 +00007//
Chris Lattnerd934c702004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
Dan Gohmanef2ae2c2009-07-25 16:18:07 +000017// can handle. We only create one SCEV of a particular shape, so
18// pointer-comparisons for equality are legal.
Chris Lattnerd934c702004-04-02 20:23:17 +000019//
20// One important aspect of the SCEV objects is that they are never cyclic, even
21// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
22// the PHI node is one of the idioms that we can represent (e.g., a polynomial
23// recurrence) then we represent it directly as a recurrence node, otherwise we
24// represent it as a SCEVUnknown node.
25//
26// In addition to being able to represent expressions of various types, we also
27// have folders that are used to build the *canonical* representation for a
28// particular expression. These folders are capable of using a variety of
29// rewrite rules to simplify the expressions.
Misha Brukman01808ca2005-04-21 21:13:18 +000030//
Chris Lattnerd934c702004-04-02 20:23:17 +000031// Once the folders are defined, we can implement the more interesting
32// higher-level code, such as the code that recognizes PHI nodes of various
33// types, computes the execution count of a loop, etc.
34//
Chris Lattnerd934c702004-04-02 20:23:17 +000035// TODO: We should use these routines and value representations to implement
36// dependence analysis!
37//
38//===----------------------------------------------------------------------===//
39//
40// There are several good references for the techniques used in this analysis.
41//
42// Chains of recurrences -- a method to expedite the evaluation
43// of closed-form functions
44// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45//
46// On computational properties of chains of recurrences
47// Eugene V. Zima
48//
49// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50// Robert A. van Engelen
51//
52// Efficient Symbolic Analysis for Optimizing Compilers
53// Robert A. van Engelen
54//
55// Using the chains of recurrences algebra for data dependence testing and
56// induction variable substitution
57// MS Thesis, Johnie Birch
58//
59//===----------------------------------------------------------------------===//
60
Chandler Carruthed0881b2012-12-03 16:50:05 +000061#include "llvm/Analysis/ScalarEvolution.h"
Sanjoy Das1f05c512014-10-10 21:22:34 +000062#include "llvm/ADT/Optional.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000063#include "llvm/ADT/STLExtras.h"
Sanjoy Dasc46bceb2016-09-27 18:01:42 +000064#include "llvm/ADT/ScopeExit.h"
Sanjoy Das17078692016-10-31 03:32:43 +000065#include "llvm/ADT/Sequence.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000066#include "llvm/ADT/SmallPtrSet.h"
67#include "llvm/ADT/Statistic.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000068#include "llvm/Analysis/AssumptionCache.h"
John Criswellfe5f33b2005-10-27 15:54:34 +000069#include "llvm/Analysis/ConstantFolding.h"
Duncan Sandsd06f50e2010-11-17 04:18:45 +000070#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000071#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000072#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000073#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman1ee696d2009-06-16 19:52:01 +000074#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000075#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000076#include "llvm/IR/Constants.h"
77#include "llvm/IR/DataLayout.h"
78#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000079#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000080#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000081#include "llvm/IR/GlobalAlias.h"
82#include "llvm/IR/GlobalVariable.h"
Chandler Carruth83948572014-03-04 10:30:26 +000083#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000084#include "llvm/IR/Instructions.h"
85#include "llvm/IR/LLVMContext.h"
Sanjoy Das1f05c512014-10-10 21:22:34 +000086#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000087#include "llvm/IR/Operator.h"
Sanjoy Dasc88f5d32015-10-28 21:27:14 +000088#include "llvm/IR/PatternMatch.h"
Chris Lattner996795b2006-06-28 23:17:24 +000089#include "llvm/Support/CommandLine.h"
David Greene2330f782009-12-23 22:58:38 +000090#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000091#include "llvm/Support/ErrorHandling.h"
Chris Lattner0a1e9932006-12-19 01:16:02 +000092#include "llvm/Support/MathExtras.h"
Dan Gohmane20f8242009-04-21 00:47:46 +000093#include "llvm/Support/raw_ostream.h"
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +000094#include "llvm/Support/SaveAndRestore.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000095#include <algorithm>
Chris Lattnerd934c702004-04-02 20:23:17 +000096using namespace llvm;
97
Chandler Carruthf1221bd2014-04-22 02:48:03 +000098#define DEBUG_TYPE "scalar-evolution"
99
Chris Lattner57ef9422006-12-19 22:30:33 +0000100STATISTIC(NumArrayLenItCounts,
101 "Number of trip counts computed with array length");
102STATISTIC(NumTripCountsComputed,
103 "Number of loops with predictable loop counts");
104STATISTIC(NumTripCountsNotComputed,
105 "Number of loops without predictable loop counts");
106STATISTIC(NumBruteForceTripCountsComputed,
107 "Number of loops with trip counts computed by force");
108
Dan Gohmand78c4002008-05-13 00:00:25 +0000109static cl::opt<unsigned>
Chris Lattner57ef9422006-12-19 22:30:33 +0000110MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
111 cl::desc("Maximum number of iterations SCEV will "
Dan Gohmance973df2009-06-24 04:48:43 +0000112 "symbolically execute a constant "
113 "derived loop"),
Chris Lattner57ef9422006-12-19 22:30:33 +0000114 cl::init(100));
115
Filipe Cabecinhas0da99372016-04-29 15:22:48 +0000116// FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
Benjamin Kramer214935e2012-10-26 17:31:32 +0000117static cl::opt<bool>
118VerifySCEV("verify-scev",
119 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
Wei Mia49559b2016-02-04 01:27:38 +0000120static cl::opt<bool>
121 VerifySCEVMap("verify-scev-maps",
Jeroen Ketemae48e3932016-04-12 23:21:46 +0000122 cl::desc("Verify no dangling value in ScalarEvolution's "
Wei Mia49559b2016-02-04 01:27:38 +0000123 "ExprValueMap (slow)"));
Benjamin Kramer214935e2012-10-26 17:31:32 +0000124
Li Huangfcfe8cd2016-10-20 21:38:39 +0000125static cl::opt<unsigned> MulOpsInlineThreshold(
126 "scev-mulops-inline-threshold", cl::Hidden,
127 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
128 cl::init(1000));
129
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000130static cl::opt<unsigned>
131 MaxCompareDepth("scalar-evolution-max-compare-depth", cl::Hidden,
132 cl::desc("Maximum depth of recursive compare complexity"),
133 cl::init(32));
134
Chris Lattnerd934c702004-04-02 20:23:17 +0000135//===----------------------------------------------------------------------===//
136// SCEV class definitions
137//===----------------------------------------------------------------------===//
138
139//===----------------------------------------------------------------------===//
140// Implementation of the SCEV class.
141//
Dan Gohman3423e722009-06-30 20:13:32 +0000142
Davide Italiano2071f4c2015-10-25 19:55:24 +0000143LLVM_DUMP_METHOD
144void SCEV::dump() const {
145 print(dbgs());
146 dbgs() << '\n';
147}
148
Dan Gohman534749b2010-11-17 22:27:42 +0000149void SCEV::print(raw_ostream &OS) const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000150 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000151 case scConstant:
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000152 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000153 return;
154 case scTruncate: {
155 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
156 const SCEV *Op = Trunc->getOperand();
157 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
158 << *Trunc->getType() << ")";
159 return;
160 }
161 case scZeroExtend: {
162 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
163 const SCEV *Op = ZExt->getOperand();
164 OS << "(zext " << *Op->getType() << " " << *Op << " to "
165 << *ZExt->getType() << ")";
166 return;
167 }
168 case scSignExtend: {
169 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
170 const SCEV *Op = SExt->getOperand();
171 OS << "(sext " << *Op->getType() << " " << *Op << " to "
172 << *SExt->getType() << ")";
173 return;
174 }
175 case scAddRecExpr: {
176 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
177 OS << "{" << *AR->getOperand(0);
178 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
179 OS << ",+," << *AR->getOperand(i);
180 OS << "}<";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000181 if (AR->hasNoUnsignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000182 OS << "nuw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000183 if (AR->hasNoSignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000184 OS << "nsw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000185 if (AR->hasNoSelfWrap() &&
Andrew Trick8b55b732011-03-14 16:50:06 +0000186 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
187 OS << "nw><";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000188 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman534749b2010-11-17 22:27:42 +0000189 OS << ">";
190 return;
191 }
192 case scAddExpr:
193 case scMulExpr:
194 case scUMaxExpr:
195 case scSMaxExpr: {
196 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
Craig Topper9f008862014-04-15 04:59:12 +0000197 const char *OpStr = nullptr;
Dan Gohman534749b2010-11-17 22:27:42 +0000198 switch (NAry->getSCEVType()) {
199 case scAddExpr: OpStr = " + "; break;
200 case scMulExpr: OpStr = " * "; break;
201 case scUMaxExpr: OpStr = " umax "; break;
202 case scSMaxExpr: OpStr = " smax "; break;
203 }
204 OS << "(";
205 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
206 I != E; ++I) {
207 OS << **I;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000208 if (std::next(I) != E)
Dan Gohman534749b2010-11-17 22:27:42 +0000209 OS << OpStr;
210 }
211 OS << ")";
Andrew Trickd912a5b2011-11-29 02:06:35 +0000212 switch (NAry->getSCEVType()) {
213 case scAddExpr:
214 case scMulExpr:
Sanjoy Das76c48e02016-02-04 18:21:54 +0000215 if (NAry->hasNoUnsignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000216 OS << "<nuw>";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000217 if (NAry->hasNoSignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000218 OS << "<nsw>";
219 }
Dan Gohman534749b2010-11-17 22:27:42 +0000220 return;
221 }
222 case scUDivExpr: {
223 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
224 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
225 return;
226 }
227 case scUnknown: {
228 const SCEVUnknown *U = cast<SCEVUnknown>(this);
Chris Lattner229907c2011-07-18 04:54:35 +0000229 Type *AllocTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000230 if (U->isSizeOf(AllocTy)) {
231 OS << "sizeof(" << *AllocTy << ")";
232 return;
233 }
234 if (U->isAlignOf(AllocTy)) {
235 OS << "alignof(" << *AllocTy << ")";
236 return;
237 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000238
Chris Lattner229907c2011-07-18 04:54:35 +0000239 Type *CTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000240 Constant *FieldNo;
241 if (U->isOffsetOf(CTy, FieldNo)) {
242 OS << "offsetof(" << *CTy << ", ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000243 FieldNo->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000244 OS << ")";
245 return;
246 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000247
Dan Gohman534749b2010-11-17 22:27:42 +0000248 // Otherwise just print it normally.
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000249 U->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000250 return;
251 }
252 case scCouldNotCompute:
253 OS << "***COULDNOTCOMPUTE***";
254 return;
Dan Gohman534749b2010-11-17 22:27:42 +0000255 }
256 llvm_unreachable("Unknown SCEV kind!");
257}
258
Chris Lattner229907c2011-07-18 04:54:35 +0000259Type *SCEV::getType() const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000260 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000261 case scConstant:
262 return cast<SCEVConstant>(this)->getType();
263 case scTruncate:
264 case scZeroExtend:
265 case scSignExtend:
266 return cast<SCEVCastExpr>(this)->getType();
267 case scAddRecExpr:
268 case scMulExpr:
269 case scUMaxExpr:
270 case scSMaxExpr:
271 return cast<SCEVNAryExpr>(this)->getType();
272 case scAddExpr:
273 return cast<SCEVAddExpr>(this)->getType();
274 case scUDivExpr:
275 return cast<SCEVUDivExpr>(this)->getType();
276 case scUnknown:
277 return cast<SCEVUnknown>(this)->getType();
278 case scCouldNotCompute:
279 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman534749b2010-11-17 22:27:42 +0000280 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000281 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman534749b2010-11-17 22:27:42 +0000282}
283
Dan Gohmanbe928e32008-06-18 16:23:07 +0000284bool SCEV::isZero() const {
285 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
286 return SC->getValue()->isZero();
287 return false;
288}
289
Dan Gohmanba7f6d82009-05-18 15:22:39 +0000290bool SCEV::isOne() const {
291 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
292 return SC->getValue()->isOne();
293 return false;
294}
Chris Lattnerd934c702004-04-02 20:23:17 +0000295
Dan Gohman18a96bb2009-06-24 00:30:26 +0000296bool SCEV::isAllOnesValue() const {
297 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
298 return SC->getValue()->isAllOnesValue();
299 return false;
300}
301
Andrew Trick881a7762012-01-07 00:27:31 +0000302bool SCEV::isNonConstantNegative() const {
303 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
304 if (!Mul) return false;
305
306 // If there is a constant factor, it will be first.
307 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
308 if (!SC) return false;
309
310 // Return true if the value is negative, this matches things like (-42 * V).
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000311 return SC->getAPInt().isNegative();
Andrew Trick881a7762012-01-07 00:27:31 +0000312}
313
Owen Anderson04052ec2009-06-22 21:57:23 +0000314SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman24ceda82010-06-18 19:54:20 +0000315 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000316
Chris Lattnerd934c702004-04-02 20:23:17 +0000317bool SCEVCouldNotCompute::classof(const SCEV *S) {
318 return S->getSCEVType() == scCouldNotCompute;
319}
320
Dan Gohmanaf752342009-07-07 17:06:11 +0000321const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000322 FoldingSetNodeID ID;
323 ID.AddInteger(scConstant);
324 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +0000325 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000326 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman24ceda82010-06-18 19:54:20 +0000327 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000328 UniqueSCEVs.InsertNode(S, IP);
329 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000330}
Chris Lattnerd934c702004-04-02 20:23:17 +0000331
Nick Lewycky31eaca52014-01-27 10:04:03 +0000332const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000333 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman0a76e7f2007-07-09 15:25:17 +0000334}
335
Dan Gohmanaf752342009-07-07 17:06:11 +0000336const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +0000337ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
338 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Dan Gohmana029cbe2010-04-21 16:04:04 +0000339 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000340}
341
Dan Gohman24ceda82010-06-18 19:54:20 +0000342SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000343 unsigned SCEVTy, const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000344 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000345
Dan Gohman24ceda82010-06-18 19:54:20 +0000346SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000347 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000348 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000349 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
350 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000351 "Cannot truncate non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000352}
Chris Lattnerd934c702004-04-02 20:23:17 +0000353
Dan Gohman24ceda82010-06-18 19:54:20 +0000354SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000355 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000356 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000357 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
358 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000359 "Cannot zero extend non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000360}
361
Dan Gohman24ceda82010-06-18 19:54:20 +0000362SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000363 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000364 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000365 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
366 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000367 "Cannot sign extend non-integer value!");
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000368}
369
Dan Gohman7cac9572010-08-02 23:49:30 +0000370void SCEVUnknown::deleted() {
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 // Release the value.
Craig Topper9f008862014-04-15 04:59:12 +0000378 setValPtr(nullptr);
Dan Gohman7cac9572010-08-02 23:49:30 +0000379}
380
381void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman761065e2010-11-17 02:44:44 +0000382 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000383 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000384
385 // Remove this SCEVUnknown from the uniquing map.
386 SE->UniqueSCEVs.RemoveNode(this);
387
388 // Update this SCEVUnknown to point to the new value. This is needed
389 // because there may still be outstanding SCEVs which still point to
390 // this SCEVUnknown.
391 setValPtr(New);
392}
393
Chris Lattner229907c2011-07-18 04:54:35 +0000394bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000395 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000396 if (VCE->getOpcode() == Instruction::PtrToInt)
397 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000398 if (CE->getOpcode() == Instruction::GetElementPtr &&
399 CE->getOperand(0)->isNullValue() &&
400 CE->getNumOperands() == 2)
401 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
402 if (CI->isOne()) {
403 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
404 ->getElementType();
405 return true;
406 }
Dan Gohmancf913832010-01-28 02:15:55 +0000407
408 return false;
409}
410
Chris Lattner229907c2011-07-18 04:54:35 +0000411bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000412 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000413 if (VCE->getOpcode() == Instruction::PtrToInt)
414 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000415 if (CE->getOpcode() == Instruction::GetElementPtr &&
416 CE->getOperand(0)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000417 Type *Ty =
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000418 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000419 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000420 if (!STy->isPacked() &&
421 CE->getNumOperands() == 3 &&
422 CE->getOperand(1)->isNullValue()) {
423 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
424 if (CI->isOne() &&
425 STy->getNumElements() == 2 &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000426 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000427 AllocTy = STy->getElementType(1);
428 return true;
429 }
430 }
431 }
Dan Gohmancf913832010-01-28 02:15:55 +0000432
433 return false;
434}
435
Chris Lattner229907c2011-07-18 04:54:35 +0000436bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000437 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000438 if (VCE->getOpcode() == Instruction::PtrToInt)
439 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
440 if (CE->getOpcode() == Instruction::GetElementPtr &&
441 CE->getNumOperands() == 3 &&
442 CE->getOperand(0)->isNullValue() &&
443 CE->getOperand(1)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000444 Type *Ty =
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000445 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
446 // Ignore vector types here so that ScalarEvolutionExpander doesn't
447 // emit getelementptrs that index into vectors.
Duncan Sands19d0b472010-02-16 11:11:14 +0000448 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000449 CTy = Ty;
450 FieldNo = CE->getOperand(2);
451 return true;
452 }
453 }
454
455 return false;
456}
457
Chris Lattnereb3e8402004-06-20 06:23:15 +0000458//===----------------------------------------------------------------------===//
459// SCEV Utilities
460//===----------------------------------------------------------------------===//
461
Sanjoy Das17078692016-10-31 03:32:43 +0000462/// Compare the two values \p LV and \p RV in terms of their "complexity" where
463/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
464/// operands in SCEV expressions. \p EqCache is a set of pairs of values that
465/// have been previously deemed to be "equally complex" by this routine. It is
466/// intended to avoid exponential time complexity in cases like:
467///
468/// %a = f(%x, %y)
469/// %b = f(%a, %a)
470/// %c = f(%b, %b)
471///
472/// %d = f(%x, %y)
473/// %e = f(%d, %d)
474/// %f = f(%e, %e)
475///
476/// CompareValueComplexity(%f, %c)
477///
478/// Since we do not continue running this routine on expression trees once we
479/// have seen unequal values, there is no need to track them in the cache.
480static int
481CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache,
482 const LoopInfo *const LI, Value *LV, Value *RV,
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000483 unsigned Depth) {
484 if (Depth > MaxCompareDepth || EqCache.count({LV, RV}))
Sanjoy Das507dd402016-10-18 17:45:16 +0000485 return 0;
486
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000487 // Order pointer values after integer values. This helps SCEVExpander form
488 // GEPs.
489 bool LIsPointer = LV->getType()->isPointerTy(),
490 RIsPointer = RV->getType()->isPointerTy();
491 if (LIsPointer != RIsPointer)
492 return (int)LIsPointer - (int)RIsPointer;
493
494 // Compare getValueID values.
495 unsigned LID = LV->getValueID(), RID = RV->getValueID();
496 if (LID != RID)
497 return (int)LID - (int)RID;
498
499 // Sort arguments by their position.
Sanjoy Dasb4830a82016-10-30 23:52:53 +0000500 if (const auto *LA = dyn_cast<Argument>(LV)) {
501 const auto *RA = cast<Argument>(RV);
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000502 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
503 return (int)LArgNo - (int)RArgNo;
504 }
505
Sanjoy Das299e6722016-10-30 23:52:56 +0000506 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
507 const auto *RGV = cast<GlobalValue>(RV);
508
509 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
510 auto LT = GV->getLinkage();
511 return !(GlobalValue::isPrivateLinkage(LT) ||
512 GlobalValue::isInternalLinkage(LT));
513 };
514
515 // Use the names to distinguish the two values, but only if the
516 // names are semantically important.
517 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
518 return LGV->getName().compare(RGV->getName());
519 }
520
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000521 // For instructions, compare their loop depth, and their operand count. This
522 // is pretty loose.
Sanjoy Dasb4830a82016-10-30 23:52:53 +0000523 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
524 const auto *RInst = cast<Instruction>(RV);
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000525
526 // Compare loop depths.
527 const BasicBlock *LParent = LInst->getParent(),
528 *RParent = RInst->getParent();
529 if (LParent != RParent) {
530 unsigned LDepth = LI->getLoopDepth(LParent),
531 RDepth = LI->getLoopDepth(RParent);
532 if (LDepth != RDepth)
533 return (int)LDepth - (int)RDepth;
534 }
535
536 // Compare the number of operands.
537 unsigned LNumOps = LInst->getNumOperands(),
538 RNumOps = RInst->getNumOperands();
Sanjoy Das17078692016-10-31 03:32:43 +0000539 if (LNumOps != RNumOps)
Sanjoy Das507dd402016-10-18 17:45:16 +0000540 return (int)LNumOps - (int)RNumOps;
541
Sanjoy Das17078692016-10-31 03:32:43 +0000542 for (unsigned Idx : seq(0u, LNumOps)) {
543 int Result =
544 CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx),
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000545 RInst->getOperand(Idx), Depth + 1);
Sanjoy Das17078692016-10-31 03:32:43 +0000546 if (Result != 0)
Daniil Fukalove8703982016-11-16 16:41:40 +0000547 return Result;
Sanjoy Das17078692016-10-31 03:32:43 +0000548 }
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000549 }
550
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000551 EqCache.insert({LV, RV});
Sanjoy Das9cd877a2016-10-18 17:45:13 +0000552 return 0;
553}
554
Sanjoy Das237c8452016-09-27 18:01:48 +0000555// Return negative, zero, or positive, if LHS is less than, equal to, or greater
556// than RHS, respectively. A three-way result allows recursive comparisons to be
557// more efficient.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000558static int CompareSCEVComplexity(
559 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV,
560 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
561 unsigned Depth = 0) {
Sanjoy Das237c8452016-09-27 18:01:48 +0000562 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
563 if (LHS == RHS)
564 return 0;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000565
Sanjoy Das237c8452016-09-27 18:01:48 +0000566 // Primarily, sort the SCEVs by their getSCEVType().
567 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
568 if (LType != RType)
569 return (int)LType - (int)RType;
Dan Gohman27065672010-08-27 15:26:01 +0000570
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000571 if (Depth > MaxCompareDepth || EqCacheSCEV.count({LHS, RHS}))
572 return 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000573 // Aside from the getSCEVType() ordering, the particular ordering
574 // isn't very important except that it's beneficial to be consistent,
575 // so that (a + b) and (b + a) don't end up as different expressions.
576 switch (static_cast<SCEVTypes>(LType)) {
577 case scUnknown: {
578 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
579 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000580
Sanjoy Das17078692016-10-31 03:32:43 +0000581 SmallSet<std::pair<Value *, Value *>, 8> EqCache;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000582 int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(),
583 Depth + 1);
584 if (X == 0)
585 EqCacheSCEV.insert({LHS, RHS});
586 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000587 }
Sanjoy Das7881abd2015-12-08 04:32:51 +0000588
Sanjoy Das237c8452016-09-27 18:01:48 +0000589 case scConstant: {
590 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
591 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
592
593 // Compare constant values.
594 const APInt &LA = LC->getAPInt();
595 const APInt &RA = RC->getAPInt();
596 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
597 if (LBitWidth != RBitWidth)
598 return (int)LBitWidth - (int)RBitWidth;
599 return LA.ult(RA) ? -1 : 1;
600 }
601
602 case scAddRecExpr: {
603 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
604 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
605
606 // Compare addrec loop depths.
607 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
608 if (LLoop != RLoop) {
609 unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth();
610 if (LDepth != RDepth)
611 return (int)LDepth - (int)RDepth;
612 }
613
614 // Addrec complexity grows with operand count.
615 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
616 if (LNumOps != RNumOps)
617 return (int)LNumOps - (int)RNumOps;
618
619 // Lexicographically compare.
620 for (unsigned i = 0; i != LNumOps; ++i) {
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000621 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i),
622 RA->getOperand(i), Depth + 1);
Sanjoy Das7881abd2015-12-08 04:32:51 +0000623 if (X != 0)
624 return X;
Sanjoy Das7881abd2015-12-08 04:32:51 +0000625 }
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000626 EqCacheSCEV.insert({LHS, RHS});
Sanjoy Das237c8452016-09-27 18:01:48 +0000627 return 0;
Sanjoy Das7881abd2015-12-08 04:32:51 +0000628 }
Sanjoy Das237c8452016-09-27 18:01:48 +0000629
630 case scAddExpr:
631 case scMulExpr:
632 case scSMaxExpr:
633 case scUMaxExpr: {
634 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
635 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
636
637 // Lexicographically compare n-ary expressions.
638 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
639 if (LNumOps != RNumOps)
640 return (int)LNumOps - (int)RNumOps;
641
642 for (unsigned i = 0; i != LNumOps; ++i) {
643 if (i >= RNumOps)
644 return 1;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000645 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i),
646 RC->getOperand(i), Depth + 1);
Sanjoy Das237c8452016-09-27 18:01:48 +0000647 if (X != 0)
648 return X;
649 }
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000650 EqCacheSCEV.insert({LHS, RHS});
651 return 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000652 }
653
654 case scUDivExpr: {
655 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
656 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
657
658 // Lexicographically compare udiv expressions.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000659 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(),
660 Depth + 1);
Sanjoy Das237c8452016-09-27 18:01:48 +0000661 if (X != 0)
662 return X;
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000663 X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(),
664 Depth + 1);
665 if (X == 0)
666 EqCacheSCEV.insert({LHS, RHS});
667 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000668 }
669
670 case scTruncate:
671 case scZeroExtend:
672 case scSignExtend: {
673 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
674 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
675
676 // Compare cast expressions by operand.
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000677 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(),
678 RC->getOperand(), Depth + 1);
679 if (X == 0)
680 EqCacheSCEV.insert({LHS, RHS});
681 return X;
Sanjoy Das237c8452016-09-27 18:01:48 +0000682 }
683
684 case scCouldNotCompute:
685 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
686 }
687 llvm_unreachable("Unknown SCEV kind!");
688}
Chris Lattnereb3e8402004-06-20 06:23:15 +0000689
Sanjoy Dasf8570812016-05-29 00:38:22 +0000690/// Given a list of SCEV objects, order them by their complexity, and group
691/// objects of the same complexity together by value. When this routine is
692/// finished, we know that any duplicates in the vector are consecutive and that
693/// complexity is monotonically increasing.
Chris Lattnereb3e8402004-06-20 06:23:15 +0000694///
Dan Gohman8b0a4192010-03-01 17:49:51 +0000695/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattnereb3e8402004-06-20 06:23:15 +0000696/// results from this routine. In other words, we don't want the results of
697/// this to depend on where the addresses of various SCEV objects happened to
698/// land in memory.
699///
Dan Gohmanaf752342009-07-07 17:06:11 +0000700static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman9ba542c2009-05-07 14:39:04 +0000701 LoopInfo *LI) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000702 if (Ops.size() < 2) return; // Noop
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000703
704 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache;
Chris Lattnereb3e8402004-06-20 06:23:15 +0000705 if (Ops.size() == 2) {
706 // This is the common case, which also happens to be trivially simple.
707 // Special case it.
Dan Gohman7712d292010-08-29 15:07:13 +0000708 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000709 if (CompareSCEVComplexity(EqCache, LI, RHS, LHS) < 0)
Dan Gohman7712d292010-08-29 15:07:13 +0000710 std::swap(LHS, RHS);
Chris Lattnereb3e8402004-06-20 06:23:15 +0000711 return;
712 }
713
Dan Gohman24ceda82010-06-18 19:54:20 +0000714 // Do the rough sort by complexity.
Sanjoy Das237c8452016-09-27 18:01:48 +0000715 std::stable_sort(Ops.begin(), Ops.end(),
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000716 [&EqCache, LI](const SCEV *LHS, const SCEV *RHS) {
717 return CompareSCEVComplexity(EqCache, LI, LHS, RHS) < 0;
Sanjoy Das237c8452016-09-27 18:01:48 +0000718 });
Dan Gohman24ceda82010-06-18 19:54:20 +0000719
720 // Now that we are sorted by complexity, group elements of the same
721 // complexity. Note that this is, at worst, N^2, but the vector is likely to
722 // be extremely short in practice. Note that we take this approach because we
723 // do not want to depend on the addresses of the objects we are grouping.
724 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
725 const SCEV *S = Ops[i];
726 unsigned Complexity = S->getSCEVType();
727
728 // If there are any objects of the same complexity and same value as this
729 // one, group them.
730 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
731 if (Ops[j] == S) { // Found a duplicate.
732 // Move it to immediately after i'th element.
733 std::swap(Ops[i+1], Ops[j]);
734 ++i; // no need to rescan it.
735 if (i == e-2) return; // Done!
736 }
737 }
738 }
Chris Lattnereb3e8402004-06-20 06:23:15 +0000739}
740
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000741// Returns the size of the SCEV S.
742static inline int sizeOfSCEV(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +0000743 struct FindSCEVSize {
744 int Size;
745 FindSCEVSize() : Size(0) {}
746
747 bool follow(const SCEV *S) {
748 ++Size;
749 // Keep looking at all operands of S.
750 return true;
751 }
752 bool isDone() const {
753 return false;
754 }
755 };
756
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000757 FindSCEVSize F;
758 SCEVTraversal<FindSCEVSize> ST(F);
759 ST.visitAll(S);
760 return F.Size;
761}
762
763namespace {
764
David Majnemer4e879362014-12-14 09:12:33 +0000765struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000766public:
767 // Computes the Quotient and Remainder of the division of Numerator by
768 // Denominator.
769 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
770 const SCEV *Denominator, const SCEV **Quotient,
771 const SCEV **Remainder) {
772 assert(Numerator && Denominator && "Uninitialized SCEV");
773
David Majnemer4e879362014-12-14 09:12:33 +0000774 SCEVDivision D(SE, Numerator, Denominator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000775
776 // Check for the trivial case here to avoid having to check for it in the
777 // rest of the code.
778 if (Numerator == Denominator) {
779 *Quotient = D.One;
780 *Remainder = D.Zero;
781 return;
782 }
783
784 if (Numerator->isZero()) {
785 *Quotient = D.Zero;
786 *Remainder = D.Zero;
787 return;
788 }
789
Brendon Cahoona57cc8b2015-04-20 16:03:28 +0000790 // A simple case when N/1. The quotient is N.
791 if (Denominator->isOne()) {
792 *Quotient = Numerator;
793 *Remainder = D.Zero;
794 return;
795 }
796
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000797 // Split the Denominator when it is a product.
Sanjoy Dasb277a422016-06-15 06:53:55 +0000798 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000799 const SCEV *Q, *R;
800 *Quotient = Numerator;
801 for (const SCEV *Op : T->operands()) {
802 divide(SE, *Quotient, Op, &Q, &R);
803 *Quotient = Q;
804
805 // Bail out when the Numerator is not divisible by one of the terms of
806 // the Denominator.
807 if (!R->isZero()) {
808 *Quotient = D.Zero;
809 *Remainder = Numerator;
810 return;
811 }
812 }
813 *Remainder = D.Zero;
814 return;
815 }
816
817 D.visit(Numerator);
818 *Quotient = D.Quotient;
819 *Remainder = D.Remainder;
820 }
821
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000822 // Except in the trivial case described above, we do not know how to divide
823 // Expr by Denominator for the following functions with empty implementation.
824 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
825 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
826 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
827 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
828 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
829 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
830 void visitUnknown(const SCEVUnknown *Numerator) {}
831 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
832
David Majnemer4e879362014-12-14 09:12:33 +0000833 void visitConstant(const SCEVConstant *Numerator) {
834 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000835 APInt NumeratorVal = Numerator->getAPInt();
836 APInt DenominatorVal = D->getAPInt();
David Majnemer4e879362014-12-14 09:12:33 +0000837 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
838 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
839
840 if (NumeratorBW > DenominatorBW)
841 DenominatorVal = DenominatorVal.sext(NumeratorBW);
842 else if (NumeratorBW < DenominatorBW)
843 NumeratorVal = NumeratorVal.sext(DenominatorBW);
844
845 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
846 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
847 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
848 Quotient = SE.getConstant(QuotientVal);
849 Remainder = SE.getConstant(RemainderVal);
850 return;
851 }
852 }
853
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000854 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
855 const SCEV *StartQ, *StartR, *StepQ, *StepR;
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000856 if (!Numerator->isAffine())
857 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000858 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
859 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
Brendon Cahoonf9751ad2015-04-22 15:06:40 +0000860 // Bail out if the types do not match.
861 Type *Ty = Denominator->getType();
862 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000863 Ty != StepQ->getType() || Ty != StepR->getType())
864 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000865 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
866 Numerator->getNoWrapFlags());
867 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
868 Numerator->getNoWrapFlags());
869 }
870
871 void visitAddExpr(const SCEVAddExpr *Numerator) {
872 SmallVector<const SCEV *, 2> Qs, Rs;
873 Type *Ty = Denominator->getType();
874
875 for (const SCEV *Op : Numerator->operands()) {
876 const SCEV *Q, *R;
877 divide(SE, Op, Denominator, &Q, &R);
878
879 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000880 if (Ty != Q->getType() || Ty != R->getType())
881 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000882
883 Qs.push_back(Q);
884 Rs.push_back(R);
885 }
886
887 if (Qs.size() == 1) {
888 Quotient = Qs[0];
889 Remainder = Rs[0];
890 return;
891 }
892
893 Quotient = SE.getAddExpr(Qs);
894 Remainder = SE.getAddExpr(Rs);
895 }
896
897 void visitMulExpr(const SCEVMulExpr *Numerator) {
898 SmallVector<const SCEV *, 2> Qs;
899 Type *Ty = Denominator->getType();
900
901 bool FoundDenominatorTerm = false;
902 for (const SCEV *Op : Numerator->operands()) {
903 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000904 if (Ty != Op->getType())
905 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000906
907 if (FoundDenominatorTerm) {
908 Qs.push_back(Op);
909 continue;
910 }
911
912 // Check whether Denominator divides one of the product operands.
913 const SCEV *Q, *R;
914 divide(SE, Op, Denominator, &Q, &R);
915 if (!R->isZero()) {
916 Qs.push_back(Op);
917 continue;
918 }
919
920 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000921 if (Ty != Q->getType())
922 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000923
924 FoundDenominatorTerm = true;
925 Qs.push_back(Q);
926 }
927
928 if (FoundDenominatorTerm) {
929 Remainder = Zero;
930 if (Qs.size() == 1)
931 Quotient = Qs[0];
932 else
933 Quotient = SE.getMulExpr(Qs);
934 return;
935 }
936
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000937 if (!isa<SCEVUnknown>(Denominator))
938 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000939
940 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
941 ValueToValueMap RewriteMap;
942 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
943 cast<SCEVConstant>(Zero)->getValue();
944 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
945
946 if (Remainder->isZero()) {
947 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
948 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
949 cast<SCEVConstant>(One)->getValue();
950 Quotient =
951 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
952 return;
953 }
954
955 // Quotient is (Numerator - Remainder) divided by Denominator.
956 const SCEV *Q, *R;
957 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000958 // This SCEV does not seem to simplify: fail the division here.
959 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
960 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000961 divide(SE, Diff, Denominator, &Q, &R);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000962 if (R != Zero)
963 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000964 Quotient = Q;
965 }
966
967private:
David Majnemer5d2670c2014-11-17 11:27:45 +0000968 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
969 const SCEV *Denominator)
970 : SE(S), Denominator(Denominator) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000971 Zero = SE.getZero(Denominator->getType());
972 One = SE.getOne(Denominator->getType());
David Majnemer5d2670c2014-11-17 11:27:45 +0000973
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000974 // We generally do not know how to divide Expr by Denominator. We
975 // initialize the division to a "cannot divide" state to simplify the rest
976 // of the code.
977 cannotDivide(Numerator);
978 }
979
980 // Convenience function for giving up on the division. We set the quotient to
981 // be equal to zero and the remainder to be equal to the numerator.
982 void cannotDivide(const SCEV *Numerator) {
David Majnemer5d2670c2014-11-17 11:27:45 +0000983 Quotient = Zero;
984 Remainder = Numerator;
985 }
986
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000987 ScalarEvolution &SE;
988 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
David Majnemer32b8ccf2014-11-16 20:35:19 +0000989};
990
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000991}
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000992
Chris Lattnerd934c702004-04-02 20:23:17 +0000993//===----------------------------------------------------------------------===//
994// Simple SCEV method implementations
995//===----------------------------------------------------------------------===//
996
Sanjoy Dasf8570812016-05-29 00:38:22 +0000997/// Compute BC(It, K). The result has width W. Assume, K > 0.
Dan Gohmanaf752342009-07-07 17:06:11 +0000998static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohman32291b12009-07-21 00:38:55 +0000999 ScalarEvolution &SE,
Nick Lewycky702cf1e2011-09-06 06:39:54 +00001000 Type *ResultTy) {
Eli Friedman61f67622008-08-04 23:49:06 +00001001 // Handle the simplest case efficiently.
1002 if (K == 1)
1003 return SE.getTruncateOrZeroExtend(It, ResultTy);
1004
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001005 // We are using the following formula for BC(It, K):
1006 //
1007 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1008 //
Eli Friedman61f67622008-08-04 23:49:06 +00001009 // Suppose, W is the bitwidth of the return value. We must be prepared for
1010 // overflow. Hence, we must assure that the result of our computation is
1011 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1012 // safe in modular arithmetic.
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001013 //
Eli Friedman61f67622008-08-04 23:49:06 +00001014 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohmance973df2009-06-24 04:48:43 +00001015 // is something like the following, where T is the number of factors of 2 in
Eli Friedman61f67622008-08-04 23:49:06 +00001016 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1017 // exponentiation:
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001018 //
Eli Friedman61f67622008-08-04 23:49:06 +00001019 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001020 //
Eli Friedman61f67622008-08-04 23:49:06 +00001021 // This formula is trivially equivalent to the previous formula. However,
1022 // this formula can be implemented much more efficiently. The trick is that
1023 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1024 // arithmetic. To do exact division in modular arithmetic, all we have
1025 // to do is multiply by the inverse. Therefore, this step can be done at
1026 // width W.
Dan Gohmance973df2009-06-24 04:48:43 +00001027 //
Eli Friedman61f67622008-08-04 23:49:06 +00001028 // The next issue is how to safely do the division by 2^T. The way this
1029 // is done is by doing the multiplication step at a width of at least W + T
1030 // bits. This way, the bottom W+T bits of the product are accurate. Then,
1031 // when we perform the division by 2^T (which is equivalent to a right shift
1032 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1033 // truncated out after the division by 2^T.
1034 //
1035 // In comparison to just directly using the first formula, this technique
1036 // is much more efficient; using the first formula requires W * K bits,
1037 // but this formula less than W + K bits. Also, the first formula requires
1038 // a division step, whereas this formula only requires multiplies and shifts.
1039 //
1040 // It doesn't matter whether the subtraction step is done in the calculation
1041 // width or the input iteration count's width; if the subtraction overflows,
1042 // the result must be zero anyway. We prefer here to do it in the width of
1043 // the induction variable because it helps a lot for certain cases; CodeGen
1044 // isn't smart enough to ignore the overflow, which leads to much less
1045 // efficient code if the width of the subtraction is wider than the native
1046 // register width.
1047 //
1048 // (It's possible to not widen at all by pulling out factors of 2 before
1049 // the multiplication; for example, K=2 can be calculated as
1050 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1051 // extra arithmetic, so it's not an obvious win, and it gets
1052 // much more complicated for K > 3.)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001053
Eli Friedman61f67622008-08-04 23:49:06 +00001054 // Protection from insane SCEVs; this bound is conservative,
1055 // but it probably doesn't matter.
1056 if (K > 1000)
Dan Gohman31efa302009-04-18 17:58:19 +00001057 return SE.getCouldNotCompute();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001058
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001059 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001060
Eli Friedman61f67622008-08-04 23:49:06 +00001061 // Calculate K! / 2^T and T; we divide out the factors of two before
1062 // multiplying for calculating K! / 2^T to avoid overflow.
1063 // Other overflow doesn't matter because we only care about the bottom
1064 // W bits of the result.
1065 APInt OddFactorial(W, 1);
1066 unsigned T = 1;
1067 for (unsigned i = 3; i <= K; ++i) {
1068 APInt Mult(W, i);
1069 unsigned TwoFactors = Mult.countTrailingZeros();
1070 T += TwoFactors;
1071 Mult = Mult.lshr(TwoFactors);
1072 OddFactorial *= Mult;
Chris Lattnerd934c702004-04-02 20:23:17 +00001073 }
Nick Lewyckyed169d52008-06-13 04:38:55 +00001074
Eli Friedman61f67622008-08-04 23:49:06 +00001075 // We need at least W + T bits for the multiplication step
Nick Lewycky21add8f2009-01-25 08:16:27 +00001076 unsigned CalculationBits = W + T;
Eli Friedman61f67622008-08-04 23:49:06 +00001077
Dan Gohman8b0a4192010-03-01 17:49:51 +00001078 // Calculate 2^T, at width T+W.
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00001079 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
Eli Friedman61f67622008-08-04 23:49:06 +00001080
1081 // Calculate the multiplicative inverse of K! / 2^T;
1082 // this multiplication factor will perform the exact division by
1083 // K! / 2^T.
1084 APInt Mod = APInt::getSignedMinValue(W+1);
1085 APInt MultiplyFactor = OddFactorial.zext(W+1);
1086 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1087 MultiplyFactor = MultiplyFactor.trunc(W);
1088
1089 // Calculate the product, at width T+W
Chris Lattner229907c2011-07-18 04:54:35 +00001090 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001091 CalculationBits);
Dan Gohmanaf752342009-07-07 17:06:11 +00001092 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman61f67622008-08-04 23:49:06 +00001093 for (unsigned i = 1; i != K; ++i) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00001094 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedman61f67622008-08-04 23:49:06 +00001095 Dividend = SE.getMulExpr(Dividend,
1096 SE.getTruncateOrZeroExtend(S, CalculationTy));
1097 }
1098
1099 // Divide by 2^T
Dan Gohmanaf752342009-07-07 17:06:11 +00001100 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman61f67622008-08-04 23:49:06 +00001101
1102 // Truncate the result, and divide by K! / 2^T.
1103
1104 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1105 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattnerd934c702004-04-02 20:23:17 +00001106}
1107
Sanjoy Dasf8570812016-05-29 00:38:22 +00001108/// Return the value of this chain of recurrences at the specified iteration
1109/// number. We can evaluate this recurrence by multiplying each element in the
1110/// chain by the binomial coefficient corresponding to it. In other words, we
1111/// can evaluate {A,+,B,+,C,+,D} as:
Chris Lattnerd934c702004-04-02 20:23:17 +00001112///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001113/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattnerd934c702004-04-02 20:23:17 +00001114///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001115/// where BC(It, k) stands for binomial coefficient.
Chris Lattnerd934c702004-04-02 20:23:17 +00001116///
Dan Gohmanaf752342009-07-07 17:06:11 +00001117const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman32291b12009-07-21 00:38:55 +00001118 ScalarEvolution &SE) const {
Dan Gohmanaf752342009-07-07 17:06:11 +00001119 const SCEV *Result = getStart();
Chris Lattnerd934c702004-04-02 20:23:17 +00001120 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001121 // The computation is correct in the face of overflow provided that the
1122 // multiplication is performed _after_ the evaluation of the binomial
1123 // coefficient.
Dan Gohmanaf752342009-07-07 17:06:11 +00001124 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewycky707663e2008-10-13 03:58:02 +00001125 if (isa<SCEVCouldNotCompute>(Coeff))
1126 return Coeff;
1127
1128 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattnerd934c702004-04-02 20:23:17 +00001129 }
1130 return Result;
1131}
1132
Chris Lattnerd934c702004-04-02 20:23:17 +00001133//===----------------------------------------------------------------------===//
1134// SCEV Expression folder implementations
1135//===----------------------------------------------------------------------===//
1136
Dan Gohmanaf752342009-07-07 17:06:11 +00001137const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001138 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001139 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001140 "This is not a truncating conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001141 assert(isSCEVable(Ty) &&
1142 "This is not a conversion to a SCEVable type!");
1143 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001144
Dan Gohman3a302cb2009-07-13 20:50:19 +00001145 FoldingSetNodeID ID;
1146 ID.AddInteger(scTruncate);
1147 ID.AddPointer(Op);
1148 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001149 void *IP = nullptr;
Dan Gohman3a302cb2009-07-13 20:50:19 +00001150 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1151
Dan Gohman3423e722009-06-30 20:13:32 +00001152 // Fold if the operand is constant.
Dan Gohmana30370b2009-05-04 22:02:23 +00001153 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman8d7576e2009-06-24 00:38:39 +00001154 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001155 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001156
Dan Gohman79af8542009-04-22 16:20:48 +00001157 // trunc(trunc(x)) --> trunc(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001158 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001159 return getTruncateExpr(ST->getOperand(), Ty);
1160
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001161 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001162 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001163 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1164
1165 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001166 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001167 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1168
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001169 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
Nick Lewycky2ce28322015-03-20 02:52:23 +00001170 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001171 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1172 SmallVector<const SCEV *, 4> Operands;
1173 bool hasTrunc = false;
1174 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1175 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001176 if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1177 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001178 Operands.push_back(S);
1179 }
1180 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001181 return getAddExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001182 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001183 }
1184
Nick Lewycky5c901f32011-01-19 18:56:00 +00001185 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
Nick Lewyckybe8af482015-03-20 02:25:00 +00001186 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001187 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1188 SmallVector<const SCEV *, 4> Operands;
1189 bool hasTrunc = false;
1190 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1191 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001192 if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1193 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5c901f32011-01-19 18:56:00 +00001194 Operands.push_back(S);
1195 }
1196 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001197 return getMulExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001198 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001199 }
1200
Dan Gohman5a728c92009-06-18 16:24:47 +00001201 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmana30370b2009-05-04 22:02:23 +00001202 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001203 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00001204 for (const SCEV *Op : AddRec->operands())
1205 Operands.push_back(getTruncateExpr(Op, Ty));
Andrew Trick8b55b732011-03-14 16:50:06 +00001206 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00001207 }
1208
Dan Gohman89dd42a2010-06-25 18:47:08 +00001209 // The cast wasn't folded; create an explicit cast node. We can reuse
1210 // the existing insert position since if we get here, we won't have
1211 // made any changes which would invalidate it.
Dan Gohman01c65a22010-03-18 18:49:47 +00001212 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1213 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001214 UniqueSCEVs.InsertNode(S, IP);
1215 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001216}
1217
Sanjoy Das4153f472015-02-18 01:47:07 +00001218// Get the limit of a recurrence such that incrementing by Step cannot cause
1219// signed overflow as long as the value of the recurrence within the
1220// loop does not exceed this limit before incrementing.
1221static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1222 ICmpInst::Predicate *Pred,
1223 ScalarEvolution *SE) {
1224 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1225 if (SE->isKnownPositive(Step)) {
1226 *Pred = ICmpInst::ICMP_SLT;
1227 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1228 SE->getSignedRange(Step).getSignedMax());
1229 }
1230 if (SE->isKnownNegative(Step)) {
1231 *Pred = ICmpInst::ICMP_SGT;
1232 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1233 SE->getSignedRange(Step).getSignedMin());
1234 }
1235 return nullptr;
1236}
1237
1238// Get the limit of a recurrence such that incrementing by Step cannot cause
1239// unsigned overflow as long as the value of the recurrence within the loop does
1240// not exceed this limit before incrementing.
1241static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1242 ICmpInst::Predicate *Pred,
1243 ScalarEvolution *SE) {
1244 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1245 *Pred = ICmpInst::ICMP_ULT;
1246
1247 return SE->getConstant(APInt::getMinValue(BitWidth) -
1248 SE->getUnsignedRange(Step).getUnsignedMax());
1249}
1250
1251namespace {
1252
1253struct ExtendOpTraitsBase {
1254 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *);
1255};
1256
1257// Used to make code generic over signed and unsigned overflow.
1258template <typename ExtendOp> struct ExtendOpTraits {
1259 // Members present:
1260 //
1261 // static const SCEV::NoWrapFlags WrapType;
1262 //
1263 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1264 //
1265 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1266 // ICmpInst::Predicate *Pred,
1267 // ScalarEvolution *SE);
1268};
1269
1270template <>
1271struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1272 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1273
1274 static const GetExtendExprTy GetExtendExpr;
1275
1276 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1277 ICmpInst::Predicate *Pred,
1278 ScalarEvolution *SE) {
1279 return getSignedOverflowLimitForStep(Step, Pred, SE);
1280 }
1281};
1282
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001283const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001284 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1285
1286template <>
1287struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1288 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1289
1290 static const GetExtendExprTy GetExtendExpr;
1291
1292 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1293 ICmpInst::Predicate *Pred,
1294 ScalarEvolution *SE) {
1295 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1296 }
1297};
1298
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001299const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001300 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001301}
Sanjoy Das4153f472015-02-18 01:47:07 +00001302
1303// The recurrence AR has been shown to have no signed/unsigned wrap or something
1304// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1305// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1306// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1307// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1308// expression "Step + sext/zext(PreIncAR)" is congruent with
1309// "sext/zext(PostIncAR)"
1310template <typename ExtendOpTy>
1311static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1312 ScalarEvolution *SE) {
1313 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1314 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1315
1316 const Loop *L = AR->getLoop();
1317 const SCEV *Start = AR->getStart();
1318 const SCEV *Step = AR->getStepRecurrence(*SE);
1319
1320 // Check for a simple looking step prior to loop entry.
1321 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1322 if (!SA)
1323 return nullptr;
1324
1325 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1326 // subtraction is expensive. For this purpose, perform a quick and dirty
1327 // difference, by checking for Step in the operand list.
1328 SmallVector<const SCEV *, 4> DiffOps;
1329 for (const SCEV *Op : SA->operands())
1330 if (Op != Step)
1331 DiffOps.push_back(Op);
1332
1333 if (DiffOps.size() == SA->getNumOperands())
1334 return nullptr;
1335
1336 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1337 // `Step`:
1338
1339 // 1. NSW/NUW flags on the step increment.
Sanjoy Das0714e3e2015-10-23 06:33:47 +00001340 auto PreStartFlags =
1341 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1342 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
Sanjoy Das4153f472015-02-18 01:47:07 +00001343 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1344 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1345
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001346 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1347 // "S+X does not sign/unsign-overflow".
Sanjoy Das4153f472015-02-18 01:47:07 +00001348 //
1349
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001350 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1351 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1352 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
Sanjoy Das4153f472015-02-18 01:47:07 +00001353 return PreStart;
1354
1355 // 2. Direct overflow check on the step operation's expression.
1356 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1357 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1358 const SCEV *OperandExtendedStart =
1359 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1360 (SE->*GetExtendExpr)(Step, WideTy));
1361 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1362 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1363 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1364 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1365 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1366 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1367 }
1368 return PreStart;
1369 }
1370
1371 // 3. Loop precondition.
1372 ICmpInst::Predicate Pred;
1373 const SCEV *OverflowLimit =
1374 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1375
1376 if (OverflowLimit &&
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001377 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
Sanjoy Das4153f472015-02-18 01:47:07 +00001378 return PreStart;
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001379
Sanjoy Das4153f472015-02-18 01:47:07 +00001380 return nullptr;
1381}
1382
1383// Get the normalized zero or sign extended expression for this AddRec's Start.
1384template <typename ExtendOpTy>
1385static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1386 ScalarEvolution *SE) {
1387 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1388
1389 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1390 if (!PreStart)
1391 return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1392
1393 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1394 (SE->*GetExtendExpr)(PreStart, Ty));
1395}
1396
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001397// Try to prove away overflow by looking at "nearby" add recurrences. A
1398// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1399// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1400//
1401// Formally:
1402//
1403// {S,+,X} == {S-T,+,X} + T
1404// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1405//
1406// If ({S-T,+,X} + T) does not overflow ... (1)
1407//
1408// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1409//
1410// If {S-T,+,X} does not overflow ... (2)
1411//
1412// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1413// == {Ext(S-T)+Ext(T),+,Ext(X)}
1414//
1415// If (S-T)+T does not overflow ... (3)
1416//
1417// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1418// == {Ext(S),+,Ext(X)} == LHS
1419//
1420// Thus, if (1), (2) and (3) are true for some T, then
1421// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1422//
1423// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1424// does not overflow" restricted to the 0th iteration. Therefore we only need
1425// to check for (1) and (2).
1426//
1427// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1428// is `Delta` (defined below).
1429//
1430template <typename ExtendOpTy>
1431bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1432 const SCEV *Step,
1433 const Loop *L) {
1434 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1435
1436 // We restrict `Start` to a constant to prevent SCEV from spending too much
1437 // time here. It is correct (but more expensive) to continue with a
1438 // non-constant `Start` and do a general SCEV subtraction to compute
1439 // `PreStart` below.
1440 //
1441 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1442 if (!StartC)
1443 return false;
1444
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001445 APInt StartAI = StartC->getAPInt();
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001446
1447 for (unsigned Delta : {-2, -1, 1, 2}) {
1448 const SCEV *PreStart = getConstant(StartAI - Delta);
1449
Sanjoy Das42801102015-10-23 06:57:21 +00001450 FoldingSetNodeID ID;
1451 ID.AddInteger(scAddRecExpr);
1452 ID.AddPointer(PreStart);
1453 ID.AddPointer(Step);
1454 ID.AddPointer(L);
1455 void *IP = nullptr;
1456 const auto *PreAR =
1457 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1458
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001459 // Give up if we don't already have the add recurrence we need because
1460 // actually constructing an add recurrence is relatively expensive.
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001461 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1462 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1463 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1464 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1465 DeltaS, &Pred, this);
1466 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1467 return true;
1468 }
1469 }
1470
1471 return false;
1472}
1473
Dan Gohmanaf752342009-07-07 17:06:11 +00001474const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001475 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001476 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001477 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001478 assert(isSCEVable(Ty) &&
1479 "This is not a conversion to a SCEVable type!");
1480 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001481
Dan Gohman3423e722009-06-30 20:13:32 +00001482 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001483 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1484 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001485 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001486
Dan Gohman79af8542009-04-22 16:20:48 +00001487 // zext(zext(x)) --> zext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001488 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001489 return getZeroExtendExpr(SZ->getOperand(), Ty);
1490
Dan Gohman74a0ba12009-07-13 20:55:53 +00001491 // Before doing any expensive analysis, check to see if we've already
1492 // computed a SCEV for this Op and Ty.
1493 FoldingSetNodeID ID;
1494 ID.AddInteger(scZeroExtend);
1495 ID.AddPointer(Op);
1496 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001497 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001498 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1499
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001500 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1501 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1502 // It's possible the bits taken off by the truncate were all zero bits. If
1503 // so, we should be able to simplify this further.
1504 const SCEV *X = ST->getOperand();
1505 ConstantRange CR = getUnsignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001506 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1507 unsigned NewBits = getTypeSizeInBits(Ty);
1508 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001509 CR.zextOrTrunc(NewBits)))
1510 return getTruncateOrZeroExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001511 }
1512
Dan Gohman76466372009-04-27 20:16:15 +00001513 // If the input value is a chrec scev, and we can prove that the value
Chris Lattnerd934c702004-04-02 20:23:17 +00001514 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001515 // operands (often constants). This allows analysis of something like
Chris Lattnerd934c702004-04-02 20:23:17 +00001516 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001517 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001518 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001519 const SCEV *Start = AR->getStart();
1520 const SCEV *Step = AR->getStepRecurrence(*this);
1521 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1522 const Loop *L = AR->getLoop();
1523
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001524 if (!AR->hasNoUnsignedWrap()) {
1525 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1526 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1527 }
1528
Dan Gohman62ef6a72009-07-25 01:22:26 +00001529 // If we have special knowledge that this addrec won't overflow,
1530 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001531 if (AR->hasNoUnsignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001532 return getAddRecExpr(
1533 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1534 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman62ef6a72009-07-25 01:22:26 +00001535
Dan Gohman76466372009-04-27 20:16:15 +00001536 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1537 // Note that this serves two purposes: It filters out loops that are
1538 // simply not analyzable, and it covers the case where this code is
1539 // being called from within backedge-taken count analysis, such that
1540 // attempting to ask for the backedge-taken count would likely result
1541 // in infinite recursion. In the later case, the analysis code will
1542 // cope with a conservative value, and it will take care to purge
1543 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001544 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001545 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001546 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001547 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001548
1549 // Check whether the backedge-taken count can be losslessly casted to
1550 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001551 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001552 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001553 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001554 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1555 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001556 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001557 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001558 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001559 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1560 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1561 const SCEV *WideMaxBECount =
1562 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001563 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001564 getAddExpr(WideStart,
1565 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001566 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001567 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001568 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1569 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohman494dac32009-04-29 22:28:28 +00001570 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001571 return getAddRecExpr(
1572 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1573 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001574 }
Dan Gohman76466372009-04-27 20:16:15 +00001575 // Similar to above, only this time treat the step value as signed.
1576 // This covers loops that count down.
Dan Gohman4fc36682009-05-18 15:58:39 +00001577 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001578 getAddExpr(WideStart,
1579 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001580 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001581 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001582 // Cache knowledge of AR NW, which is propagated to this AddRec.
1583 // Negative step causes unsigned wrap, but it still can't self-wrap.
1584 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
Dan Gohman494dac32009-04-29 22:28:28 +00001585 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001586 return getAddRecExpr(
1587 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1588 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001589 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001590 }
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001591 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001592
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001593 // Normally, in the cases we can prove no-overflow via a
1594 // backedge guarding condition, we can also compute a backedge
1595 // taken count for the loop. The exceptions are assumptions and
1596 // guards present in the loop -- SCEV is not great at exploiting
1597 // these to compute max backedge taken counts, but can still use
1598 // these to prove lack of overflow. Use this fact to avoid
1599 // doing extra work that may not pay off.
1600 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001601 !AC.assumptions().empty()) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001602 // If the backedge is guarded by a comparison with the pre-inc
1603 // value the addrec is safe. Also, if the entry is guarded by
1604 // a comparison with the start value and the backedge is
1605 // guarded by a comparison with the post-inc value, the addrec
1606 // is safe.
Dan Gohmane65c9172009-07-13 21:35:55 +00001607 if (isKnownPositive(Step)) {
1608 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1609 getUnsignedRange(Step).getUnsignedMax());
1610 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohmanb50349a2010-04-11 19:27:13 +00001611 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001612 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001613 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001614 // Cache knowledge of AR NUW, which is propagated to this
1615 // AddRec.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001616 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohmane65c9172009-07-13 21:35:55 +00001617 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001618 return getAddRecExpr(
1619 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1620 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001621 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001622 } else if (isKnownNegative(Step)) {
1623 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1624 getSignedRange(Step).getSignedMin());
Dan Gohman5f18c542010-05-04 01:11:15 +00001625 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1626 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001627 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001628 AR->getPostIncExpr(*this), N))) {
Sanjoy Dasf5d40d52016-05-17 17:51:14 +00001629 // Cache knowledge of AR NW, which is propagated to this
1630 // AddRec. Negative step causes unsigned wrap, but it
1631 // still can't self-wrap.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001632 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1633 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001634 return getAddRecExpr(
1635 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1636 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001637 }
Dan Gohman76466372009-04-27 20:16:15 +00001638 }
1639 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001640
1641 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1642 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1643 return getAddRecExpr(
1644 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1645 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1646 }
Dan Gohman76466372009-04-27 20:16:15 +00001647 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001648
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001649 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1650 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001651 if (SA->hasNoUnsignedWrap()) {
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001652 // If the addition does not unsign overflow then we can, by definition,
1653 // commute the zero extension with the addition operation.
1654 SmallVector<const SCEV *, 4> Ops;
1655 for (const auto *Op : SA->operands())
1656 Ops.push_back(getZeroExtendExpr(Op, Ty));
1657 return getAddExpr(Ops, SCEV::FlagNUW);
1658 }
1659 }
1660
Dan Gohman74a0ba12009-07-13 20:55:53 +00001661 // The cast wasn't folded; create an explicit cast node.
1662 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001663 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001664 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1665 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001666 UniqueSCEVs.InsertNode(S, IP);
1667 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001668}
1669
Dan Gohmanaf752342009-07-07 17:06:11 +00001670const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001671 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001672 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001673 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001674 assert(isSCEVable(Ty) &&
1675 "This is not a conversion to a SCEVable type!");
1676 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001677
Dan Gohman3423e722009-06-30 20:13:32 +00001678 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001679 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1680 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001681 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001682
Dan Gohman79af8542009-04-22 16:20:48 +00001683 // sext(sext(x)) --> sext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001684 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001685 return getSignExtendExpr(SS->getOperand(), Ty);
1686
Nick Lewyckye9ea75e2011-01-19 15:56:12 +00001687 // sext(zext(x)) --> zext(x)
1688 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1689 return getZeroExtendExpr(SZ->getOperand(), Ty);
1690
Dan Gohman74a0ba12009-07-13 20:55:53 +00001691 // Before doing any expensive analysis, check to see if we've already
1692 // computed a SCEV for this Op and Ty.
1693 FoldingSetNodeID ID;
1694 ID.AddInteger(scSignExtend);
1695 ID.AddPointer(Op);
1696 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001697 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001698 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1699
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001700 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1701 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1702 // It's possible the bits taken off by the truncate were all sign bits. If
1703 // so, we should be able to simplify this further.
1704 const SCEV *X = ST->getOperand();
1705 ConstantRange CR = getSignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001706 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1707 unsigned NewBits = getTypeSizeInBits(Ty);
1708 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001709 CR.sextOrTrunc(NewBits)))
1710 return getTruncateOrSignExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001711 }
1712
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001713 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001714 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001715 if (SA->getNumOperands() == 2) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001716 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1717 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001718 if (SMul && SC1) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001719 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001720 const APInt &C1 = SC1->getAPInt();
1721 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001722 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001723 C2.ugt(C1) && C2.isPowerOf2())
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001724 return getAddExpr(getSignExtendExpr(SC1, Ty),
1725 getSignExtendExpr(SMul, Ty));
1726 }
1727 }
1728 }
Sanjoy Dasa060e602015-10-22 19:57:25 +00001729
1730 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001731 if (SA->hasNoSignedWrap()) {
Sanjoy Dasa060e602015-10-22 19:57:25 +00001732 // If the addition does not sign overflow then we can, by definition,
1733 // commute the sign extension with the addition operation.
1734 SmallVector<const SCEV *, 4> Ops;
1735 for (const auto *Op : SA->operands())
1736 Ops.push_back(getSignExtendExpr(Op, Ty));
1737 return getAddExpr(Ops, SCEV::FlagNSW);
1738 }
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001739 }
Dan Gohman76466372009-04-27 20:16:15 +00001740 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001741 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001742 // operands (often constants). This allows analysis of something like
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001743 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001744 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001745 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001746 const SCEV *Start = AR->getStart();
1747 const SCEV *Step = AR->getStepRecurrence(*this);
1748 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1749 const Loop *L = AR->getLoop();
1750
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001751 if (!AR->hasNoSignedWrap()) {
1752 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1753 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1754 }
1755
Dan Gohman62ef6a72009-07-25 01:22:26 +00001756 // If we have special knowledge that this addrec won't overflow,
1757 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001758 if (AR->hasNoSignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001759 return getAddRecExpr(
1760 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1761 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
Dan Gohman62ef6a72009-07-25 01:22:26 +00001762
Dan Gohman76466372009-04-27 20:16:15 +00001763 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1764 // Note that this serves two purposes: It filters out loops that are
1765 // simply not analyzable, and it covers the case where this code is
1766 // being called from within backedge-taken count analysis, such that
1767 // attempting to ask for the backedge-taken count would likely result
1768 // in infinite recursion. In the later case, the analysis code will
1769 // cope with a conservative value, and it will take care to purge
1770 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001771 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001772 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001773 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001774 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001775
1776 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman494dac32009-04-29 22:28:28 +00001777 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001778 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001779 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001780 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001781 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1782 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001783 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001784 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001785 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001786 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1787 const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1788 const SCEV *WideMaxBECount =
1789 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001790 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001791 getAddExpr(WideStart,
1792 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001793 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001794 if (SAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001795 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1796 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman494dac32009-04-29 22:28:28 +00001797 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001798 return getAddRecExpr(
1799 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1800 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001801 }
Dan Gohman8c129d72009-07-16 17:34:36 +00001802 // Similar to above, only this time treat the step value as unsigned.
1803 // This covers loops that count up with an unsigned step.
Dan Gohman8c129d72009-07-16 17:34:36 +00001804 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001805 getAddExpr(WideStart,
1806 getMulExpr(WideMaxBECount,
Dan Gohman8c129d72009-07-16 17:34:36 +00001807 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001808 if (SAdd == OperandExtendedAdd) {
Sanjoy Dasbf5d8702015-02-09 18:34:55 +00001809 // If AR wraps around then
1810 //
1811 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1812 // => SAdd != OperandExtendedAdd
1813 //
1814 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1815 // (SAdd == OperandExtendedAdd => AR is NW)
1816
1817 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1818
Dan Gohman8c129d72009-07-16 17:34:36 +00001819 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001820 return getAddRecExpr(
1821 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1822 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001823 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001824 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001825 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001826
Sanjoy Das787c2462016-05-11 17:41:26 +00001827 // Normally, in the cases we can prove no-overflow via a
1828 // backedge guarding condition, we can also compute a backedge
1829 // taken count for the loop. The exceptions are assumptions and
1830 // guards present in the loop -- SCEV is not great at exploiting
1831 // these to compute max backedge taken counts, but can still use
1832 // these to prove lack of overflow. Use this fact to avoid
1833 // doing extra work that may not pay off.
1834
1835 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001836 !AC.assumptions().empty()) {
Sanjoy Das787c2462016-05-11 17:41:26 +00001837 // If the backedge is guarded by a comparison with the pre-inc
1838 // value the addrec is safe. Also, if the entry is guarded by
1839 // a comparison with the start value and the backedge is
1840 // guarded by a comparison with the post-inc value, the addrec
1841 // is safe.
Andrew Trick812276e2011-05-31 21:17:47 +00001842 ICmpInst::Predicate Pred;
Sanjoy Das4153f472015-02-18 01:47:07 +00001843 const SCEV *OverflowLimit =
1844 getSignedOverflowLimitForStep(Step, &Pred, this);
Andrew Trick812276e2011-05-31 21:17:47 +00001845 if (OverflowLimit &&
1846 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1847 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1848 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1849 OverflowLimit)))) {
1850 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1851 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Sanjoy Das4153f472015-02-18 01:47:07 +00001852 return getAddRecExpr(
1853 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1854 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman76466372009-04-27 20:16:15 +00001855 }
1856 }
Sanjoy Das787c2462016-05-11 17:41:26 +00001857
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001858 // If Start and Step are constants, check if we can apply this
1859 // transformation:
1860 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001861 auto *SC1 = dyn_cast<SCEVConstant>(Start);
1862 auto *SC2 = dyn_cast<SCEVConstant>(Step);
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001863 if (SC1 && SC2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001864 const APInt &C1 = SC1->getAPInt();
1865 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001866 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1867 C2.isPowerOf2()) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001868 Start = getSignExtendExpr(Start, Ty);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001869 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1870 AR->getNoWrapFlags());
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001871 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1872 }
1873 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001874
1875 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1876 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1877 return getAddRecExpr(
1878 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1879 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1880 }
Dan Gohman76466372009-04-27 20:16:15 +00001881 }
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001882
Sanjoy Das11ef6062016-03-03 18:31:23 +00001883 // If the input value is provably positive and we could not simplify
1884 // away the sext build a zext instead.
1885 if (isKnownNonNegative(Op))
1886 return getZeroExtendExpr(Op, Ty);
1887
Dan Gohman74a0ba12009-07-13 20:55:53 +00001888 // The cast wasn't folded; create an explicit cast node.
1889 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001890 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001891 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1892 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001893 UniqueSCEVs.InsertNode(S, IP);
1894 return S;
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001895}
1896
Dan Gohman8db2edc2009-06-13 15:56:47 +00001897/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1898/// unspecified bits out to the given type.
1899///
Dan Gohmanaf752342009-07-07 17:06:11 +00001900const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001901 Type *Ty) {
Dan Gohman8db2edc2009-06-13 15:56:47 +00001902 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1903 "This is not an extending conversion!");
1904 assert(isSCEVable(Ty) &&
1905 "This is not a conversion to a SCEVable type!");
1906 Ty = getEffectiveSCEVType(Ty);
1907
1908 // Sign-extend negative constants.
1909 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001910 if (SC->getAPInt().isNegative())
Dan Gohman8db2edc2009-06-13 15:56:47 +00001911 return getSignExtendExpr(Op, Ty);
1912
1913 // Peel off a truncate cast.
1914 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001915 const SCEV *NewOp = T->getOperand();
Dan Gohman8db2edc2009-06-13 15:56:47 +00001916 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1917 return getAnyExtendExpr(NewOp, Ty);
1918 return getTruncateOrNoop(NewOp, Ty);
1919 }
1920
1921 // Next try a zext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001922 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001923 if (!isa<SCEVZeroExtendExpr>(ZExt))
1924 return ZExt;
1925
1926 // Next try a sext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001927 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001928 if (!isa<SCEVSignExtendExpr>(SExt))
1929 return SExt;
1930
Dan Gohman51ad99d2010-01-21 02:09:26 +00001931 // Force the cast to be folded into the operands of an addrec.
1932 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1933 SmallVector<const SCEV *, 4> Ops;
Tobias Grosser924221c2014-05-07 06:07:47 +00001934 for (const SCEV *Op : AR->operands())
1935 Ops.push_back(getAnyExtendExpr(Op, Ty));
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001936 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001937 }
1938
Dan Gohman8db2edc2009-06-13 15:56:47 +00001939 // If the expression is obviously signed, use the sext cast value.
1940 if (isa<SCEVSMaxExpr>(Op))
1941 return SExt;
1942
1943 // Absent any other information, use the zext cast value.
1944 return ZExt;
1945}
1946
Sanjoy Dasf8570812016-05-29 00:38:22 +00001947/// Process the given Ops list, which is a list of operands to be added under
1948/// the given scale, update the given map. This is a helper function for
1949/// getAddRecExpr. As an example of what it does, given a sequence of operands
1950/// that would form an add expression like this:
Dan Gohman038d02e2009-06-14 22:58:51 +00001951///
Tobias Grosserba49e422014-03-05 10:37:17 +00001952/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
Dan Gohman038d02e2009-06-14 22:58:51 +00001953///
1954/// where A and B are constants, update the map with these values:
1955///
1956/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1957///
1958/// and add 13 + A*B*29 to AccumulatedConstant.
1959/// This will allow getAddRecExpr to produce this:
1960///
1961/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1962///
1963/// This form often exposes folding opportunities that are hidden in
1964/// the original operand list.
1965///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001966/// Return true iff it appears that any interesting folding opportunities
Dan Gohman038d02e2009-06-14 22:58:51 +00001967/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1968/// the common case where no interesting opportunities are present, and
1969/// is also used as a check to avoid infinite recursion.
1970///
1971static bool
Dan Gohmanaf752342009-07-07 17:06:11 +00001972CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
Craig Topper2cd5ff82013-07-11 16:22:38 +00001973 SmallVectorImpl<const SCEV *> &NewOps,
Dan Gohman038d02e2009-06-14 22:58:51 +00001974 APInt &AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001975 const SCEV *const *Ops, size_t NumOperands,
Dan Gohman038d02e2009-06-14 22:58:51 +00001976 const APInt &Scale,
1977 ScalarEvolution &SE) {
1978 bool Interesting = false;
1979
Dan Gohman45073042010-06-18 19:12:32 +00001980 // Iterate over the add operands. They are sorted, with constants first.
1981 unsigned i = 0;
1982 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1983 ++i;
1984 // Pull a buried constant out to the outside.
1985 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1986 Interesting = true;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001987 AccumulatedConstant += Scale * C->getAPInt();
Dan Gohman45073042010-06-18 19:12:32 +00001988 }
1989
1990 // Next comes everything else. We're especially interested in multiplies
1991 // here, but they're in the middle, so just visit the rest with one loop.
1992 for (; i != NumOperands; ++i) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001993 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1994 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1995 APInt NewScale =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001996 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
Dan Gohman038d02e2009-06-14 22:58:51 +00001997 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1998 // A multiplication of a constant with another add; recurse.
Dan Gohman00524492010-03-18 01:17:13 +00001999 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohman038d02e2009-06-14 22:58:51 +00002000 Interesting |=
2001 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002002 Add->op_begin(), Add->getNumOperands(),
Dan Gohman038d02e2009-06-14 22:58:51 +00002003 NewScale, SE);
2004 } else {
2005 // A multiplication of a constant with some other value. Update
2006 // the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00002007 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2008 const SCEV *Key = SE.getMulExpr(MulOps);
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00002009 auto Pair = M.insert({Key, NewScale});
Dan Gohman038d02e2009-06-14 22:58:51 +00002010 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002011 NewOps.push_back(Pair.first->first);
2012 } else {
2013 Pair.first->second += NewScale;
2014 // The map already had an entry for this value, which may indicate
2015 // a folding opportunity.
2016 Interesting = true;
2017 }
2018 }
Dan Gohman038d02e2009-06-14 22:58:51 +00002019 } else {
2020 // An ordinary operand. Update the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00002021 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00002022 M.insert({Ops[i], Scale});
Dan Gohman038d02e2009-06-14 22:58:51 +00002023 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002024 NewOps.push_back(Pair.first->first);
2025 } else {
2026 Pair.first->second += Scale;
2027 // The map already had an entry for this value, which may indicate
2028 // a folding opportunity.
2029 Interesting = true;
2030 }
2031 }
2032 }
2033
2034 return Interesting;
2035}
2036
Sanjoy Das81401d42015-01-10 23:41:24 +00002037// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2038// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2039// can't-overflow flags for the operation if possible.
2040static SCEV::NoWrapFlags
2041StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2042 const SmallVectorImpl<const SCEV *> &Ops,
Sanjoy Das8f274152015-10-22 19:57:19 +00002043 SCEV::NoWrapFlags Flags) {
Sanjoy Das81401d42015-01-10 23:41:24 +00002044 using namespace std::placeholders;
Sanjoy Das8f274152015-10-22 19:57:19 +00002045 typedef OverflowingBinaryOperator OBO;
Sanjoy Das81401d42015-01-10 23:41:24 +00002046
2047 bool CanAnalyze =
2048 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2049 (void)CanAnalyze;
2050 assert(CanAnalyze && "don't call from other places!");
2051
2052 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2053 SCEV::NoWrapFlags SignOrUnsignWrap =
Sanjoy Das8f274152015-10-22 19:57:19 +00002054 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00002055
2056 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Sanjoy Das9b0015f2015-11-29 23:40:57 +00002057 auto IsKnownNonNegative = [&](const SCEV *S) {
2058 return SE->isKnownNonNegative(S);
2059 };
Sanjoy Das81401d42015-01-10 23:41:24 +00002060
Sanjoy Das3b827c72015-11-29 23:40:53 +00002061 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
Sanjoy Das8f274152015-10-22 19:57:19 +00002062 Flags =
2063 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00002064
Sanjoy Das8f274152015-10-22 19:57:19 +00002065 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2066
2067 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2068 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2069
2070 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2071 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2072
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002073 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
Sanjoy Das8f274152015-10-22 19:57:19 +00002074 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002075 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2076 Instruction::Add, C, OBO::NoSignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002077 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2078 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2079 }
2080 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00002081 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2082 Instruction::Add, C, OBO::NoUnsignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00002083 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2084 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2085 }
2086 }
2087
2088 return Flags;
Sanjoy Das81401d42015-01-10 23:41:24 +00002089}
2090
Sanjoy Dasf8570812016-05-29 00:38:22 +00002091/// Get a canonical add expression, or something simpler if possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002092const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002093 SCEV::NoWrapFlags Flags) {
2094 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2095 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002096 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +00002097 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002098#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002099 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002100 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohman9136d9f2010-06-18 19:09:27 +00002101 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002102 "SCEVAddExpr operand types don't match!");
2103#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002104
2105 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002106 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002107
Sanjoy Das64895612015-10-09 02:44:45 +00002108 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2109
Chris Lattnerd934c702004-04-02 20:23:17 +00002110 // If there are any constants, fold them together.
2111 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002112 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002113 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +00002114 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002115 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002116 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002117 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
Dan Gohman011cf682009-06-14 22:53:57 +00002118 if (Ops.size() == 2) return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002119 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002120 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002121 }
2122
2123 // If we are left with a constant zero being added, strip it off.
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002124 if (LHSC->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002125 Ops.erase(Ops.begin());
2126 --Idx;
2127 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002128
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002129 if (Ops.size() == 1) return Ops[0];
2130 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002131
Dan Gohman15871f22010-08-27 21:39:59 +00002132 // Okay, check to see if the same value occurs in the operand list more than
Reid Kleckner30422ee2016-12-12 18:52:32 +00002133 // once. If so, merge them together into an multiply expression. Since we
Dan Gohman15871f22010-08-27 21:39:59 +00002134 // sorted the list, these values are required to be adjacent.
Chris Lattner229907c2011-07-18 04:54:35 +00002135 Type *Ty = Ops[0]->getType();
Dan Gohmane67b2872010-08-12 14:46:54 +00002136 bool FoundMatch = false;
Dan Gohman15871f22010-08-27 21:39:59 +00002137 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattnerd934c702004-04-02 20:23:17 +00002138 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman15871f22010-08-27 21:39:59 +00002139 // Scan ahead to count how many equal operands there are.
2140 unsigned Count = 2;
2141 while (i+Count != e && Ops[i+Count] == Ops[i])
2142 ++Count;
2143 // Merge the values into a multiply.
2144 const SCEV *Scale = getConstant(Ty, Count);
2145 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2146 if (Ops.size() == Count)
Chris Lattnerd934c702004-04-02 20:23:17 +00002147 return Mul;
Dan Gohmane67b2872010-08-12 14:46:54 +00002148 Ops[i] = Mul;
Dan Gohman15871f22010-08-27 21:39:59 +00002149 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohmanfe22f1d2010-08-28 00:39:27 +00002150 --i; e -= Count - 1;
Dan Gohmane67b2872010-08-12 14:46:54 +00002151 FoundMatch = true;
Chris Lattnerd934c702004-04-02 20:23:17 +00002152 }
Dan Gohmane67b2872010-08-12 14:46:54 +00002153 if (FoundMatch)
Andrew Trick8b55b732011-03-14 16:50:06 +00002154 return getAddExpr(Ops, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002155
Dan Gohman2e55cc52009-05-08 21:03:19 +00002156 // Check for truncates. If all the operands are truncated from the same
2157 // type, see if factoring out the truncate would permit the result to be
2158 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2159 // if the contents of the resulting outer trunc fold to something simple.
2160 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2161 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
Chris Lattner229907c2011-07-18 04:54:35 +00002162 Type *DstType = Trunc->getType();
2163 Type *SrcType = Trunc->getOperand()->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00002164 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002165 bool Ok = true;
2166 // Check all the operands to see if they can be represented in the
2167 // source type of the truncate.
2168 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2169 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2170 if (T->getOperand()->getType() != SrcType) {
2171 Ok = false;
2172 break;
2173 }
2174 LargeOps.push_back(T->getOperand());
2175 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002176 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002177 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002178 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002179 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2180 if (const SCEVTruncateExpr *T =
2181 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2182 if (T->getOperand()->getType() != SrcType) {
2183 Ok = false;
2184 break;
2185 }
2186 LargeMulOps.push_back(T->getOperand());
Sanjoy Das63914592015-10-18 00:29:20 +00002187 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002188 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002189 } else {
2190 Ok = false;
2191 break;
2192 }
2193 }
2194 if (Ok)
2195 LargeOps.push_back(getMulExpr(LargeMulOps));
2196 } else {
2197 Ok = false;
2198 break;
2199 }
2200 }
2201 if (Ok) {
2202 // Evaluate the expression in the larger type.
Andrew Trick8b55b732011-03-14 16:50:06 +00002203 const SCEV *Fold = getAddExpr(LargeOps, Flags);
Dan Gohman2e55cc52009-05-08 21:03:19 +00002204 // If it folds to something simple, use it. Otherwise, don't.
2205 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2206 return getTruncateExpr(Fold, DstType);
2207 }
2208 }
2209
2210 // Skip past any other cast SCEVs.
Dan Gohmaneed125f2007-06-18 19:30:09 +00002211 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2212 ++Idx;
2213
2214 // If there are add operands they would be next.
Chris Lattnerd934c702004-04-02 20:23:17 +00002215 if (Idx < Ops.size()) {
2216 bool DeletedAdd = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002217 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002218 // If we have an add, expand the add operands onto the end of the operands
2219 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002220 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002221 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002222 DeletedAdd = true;
2223 }
2224
2225 // If we deleted at least one add, we added operands to the end of the list,
2226 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002227 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002228 if (DeletedAdd)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002229 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002230 }
2231
2232 // Skip over the add expression until we get to a multiply.
2233 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2234 ++Idx;
2235
Dan Gohman038d02e2009-06-14 22:58:51 +00002236 // Check to see if there are any folding opportunities present with
2237 // operands multiplied by constant values.
2238 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2239 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohmanaf752342009-07-07 17:06:11 +00002240 DenseMap<const SCEV *, APInt> M;
2241 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman038d02e2009-06-14 22:58:51 +00002242 APInt AccumulatedConstant(BitWidth, 0);
2243 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002244 Ops.data(), Ops.size(),
2245 APInt(BitWidth, 1), *this)) {
Sanjoy Das7d752672015-12-08 04:32:54 +00002246 struct APIntCompare {
2247 bool operator()(const APInt &LHS, const APInt &RHS) const {
2248 return LHS.ult(RHS);
2249 }
2250 };
2251
Dan Gohman038d02e2009-06-14 22:58:51 +00002252 // Some interesting folding opportunity is present, so its worthwhile to
2253 // re-generate the operands list. Group the operands by constant scale,
2254 // to avoid multiplying by the same constant scale multiple times.
Dan Gohmanaf752342009-07-07 17:06:11 +00002255 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002256 for (const SCEV *NewOp : NewOps)
2257 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
Dan Gohman038d02e2009-06-14 22:58:51 +00002258 // Re-generate the operands list.
2259 Ops.clear();
2260 if (AccumulatedConstant != 0)
2261 Ops.push_back(getConstant(AccumulatedConstant));
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002262 for (auto &MulOp : MulOpLists)
2263 if (MulOp.first != 0)
2264 Ops.push_back(getMulExpr(getConstant(MulOp.first),
2265 getAddExpr(MulOp.second)));
Dan Gohman038d02e2009-06-14 22:58:51 +00002266 if (Ops.empty())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002267 return getZero(Ty);
Dan Gohman038d02e2009-06-14 22:58:51 +00002268 if (Ops.size() == 1)
2269 return Ops[0];
2270 return getAddExpr(Ops);
2271 }
2272 }
2273
Chris Lattnerd934c702004-04-02 20:23:17 +00002274 // If we are adding something to a multiply expression, make sure the
2275 // something is not already an operand of the multiply. If so, merge it into
2276 // the multiply.
2277 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002278 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002279 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman48f82222009-05-04 22:30:44 +00002280 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman157847f2010-08-12 14:52:55 +00002281 if (isa<SCEVConstant>(MulOpSCEV))
2282 continue;
Chris Lattnerd934c702004-04-02 20:23:17 +00002283 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman157847f2010-08-12 14:52:55 +00002284 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002285 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohmanaf752342009-07-07 17:06:11 +00002286 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002287 if (Mul->getNumOperands() != 2) {
2288 // If the multiply has more than two operands, we must get the
2289 // Y*Z term.
Dan Gohman797a1db2010-08-16 16:57:24 +00002290 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2291 Mul->op_begin()+MulOp);
2292 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002293 InnerMul = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002294 }
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002295 const SCEV *One = getOne(Ty);
Dan Gohmancf32f2b2010-08-13 20:17:14 +00002296 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman157847f2010-08-12 14:52:55 +00002297 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattnerd934c702004-04-02 20:23:17 +00002298 if (Ops.size() == 2) return OuterMul;
2299 if (AddOp < Idx) {
2300 Ops.erase(Ops.begin()+AddOp);
2301 Ops.erase(Ops.begin()+Idx-1);
2302 } else {
2303 Ops.erase(Ops.begin()+Idx);
2304 Ops.erase(Ops.begin()+AddOp-1);
2305 }
2306 Ops.push_back(OuterMul);
Dan Gohmana37eaf22007-10-22 18:31:58 +00002307 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002308 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002309
Chris Lattnerd934c702004-04-02 20:23:17 +00002310 // Check this multiply against other multiplies being added together.
2311 for (unsigned OtherMulIdx = Idx+1;
2312 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2313 ++OtherMulIdx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002314 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002315 // If MulOp occurs in OtherMul, we can fold the two multiplies
2316 // together.
2317 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2318 OMulOp != e; ++OMulOp)
2319 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2320 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohmanaf752342009-07-07 17:06:11 +00002321 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002322 if (Mul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002323 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002324 Mul->op_begin()+MulOp);
2325 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002326 InnerMul1 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002327 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002328 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002329 if (OtherMul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002330 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002331 OtherMul->op_begin()+OMulOp);
2332 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002333 InnerMul2 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002334 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002335 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2336 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattnerd934c702004-04-02 20:23:17 +00002337 if (Ops.size() == 2) return OuterMul;
Dan Gohmanaabfc522010-08-31 22:50:31 +00002338 Ops.erase(Ops.begin()+Idx);
2339 Ops.erase(Ops.begin()+OtherMulIdx-1);
2340 Ops.push_back(OuterMul);
2341 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002342 }
2343 }
2344 }
2345 }
2346
2347 // If there are any add recurrences in the operands list, see if any other
2348 // added values are loop invariant. If so, we can fold them into the
2349 // recurrence.
2350 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2351 ++Idx;
2352
2353 // Scan over all recurrences, trying to fold loop invariants into them.
2354 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2355 // Scan all of the other operands to this add and add them to the vector if
2356 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002357 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002358 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002359 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002360 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002361 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002362 LIOps.push_back(Ops[i]);
2363 Ops.erase(Ops.begin()+i);
2364 --i; --e;
2365 }
2366
2367 // If we found some loop invariants, fold them into the recurrence.
2368 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002369 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattnerd934c702004-04-02 20:23:17 +00002370 LIOps.push_back(AddRec->getStart());
2371
Dan Gohmanaf752342009-07-07 17:06:11 +00002372 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman7a2dab82009-12-18 03:57:04 +00002373 AddRec->op_end());
Oleg Ranevskyyeb4ecca2016-05-25 13:01:33 +00002374 // This follows from the fact that the no-wrap flags on the outer add
2375 // expression are applicable on the 0th iteration, when the add recurrence
2376 // will be equal to its start value.
2377 AddRecOps[0] = getAddExpr(LIOps, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002378
Dan Gohman16206132010-06-30 07:16:37 +00002379 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher23bf3ba2011-01-11 09:02:09 +00002380 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002381 // Always propagate NW.
2382 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick8b55b732011-03-14 16:50:06 +00002383 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman51f13052009-12-18 18:45:31 +00002384
Chris Lattnerd934c702004-04-02 20:23:17 +00002385 // If all of the other operands were loop invariant, we are done.
2386 if (Ops.size() == 1) return NewRec;
2387
Nick Lewyckydb66b822011-09-06 05:08:09 +00002388 // Otherwise, add the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002389 for (unsigned i = 0;; ++i)
2390 if (Ops[i] == AddRec) {
2391 Ops[i] = NewRec;
2392 break;
2393 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002394 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002395 }
2396
2397 // Okay, if there weren't any loop invariants to be folded, check to see if
2398 // there are multiple AddRec's with the same loop induction variable being
2399 // added together. If so, we can fold them.
2400 for (unsigned OtherIdx = Idx+1;
Dan Gohmanc866bf42010-08-27 20:45:56 +00002401 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2402 ++OtherIdx)
2403 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2404 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2405 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2406 AddRec->op_end());
2407 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2408 ++OtherIdx)
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002409 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman028c1812010-08-29 14:53:34 +00002410 if (OtherAddRec->getLoop() == AddRecLoop) {
2411 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2412 i != e; ++i) {
Dan Gohmanc866bf42010-08-27 20:45:56 +00002413 if (i >= AddRecOps.size()) {
Dan Gohman028c1812010-08-29 14:53:34 +00002414 AddRecOps.append(OtherAddRec->op_begin()+i,
2415 OtherAddRec->op_end());
Dan Gohmanc866bf42010-08-27 20:45:56 +00002416 break;
2417 }
Dan Gohman028c1812010-08-29 14:53:34 +00002418 AddRecOps[i] = getAddExpr(AddRecOps[i],
2419 OtherAddRec->getOperand(i));
Dan Gohmanc866bf42010-08-27 20:45:56 +00002420 }
2421 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattnerd934c702004-04-02 20:23:17 +00002422 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002423 // Step size has changed, so we cannot guarantee no self-wraparound.
2424 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Dan Gohmanc866bf42010-08-27 20:45:56 +00002425 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002426 }
2427
2428 // Otherwise couldn't fold anything into this recurrence. Move onto the
2429 // next one.
2430 }
2431
2432 // Okay, it looks like we really DO need an add expr. Check to see if we
2433 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002434 FoldingSetNodeID ID;
2435 ID.AddInteger(scAddExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002436 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2437 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002438 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002439 SCEVAddExpr *S =
2440 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2441 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002442 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2443 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002444 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2445 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002446 UniqueSCEVs.InsertNode(S, IP);
2447 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002448 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002449 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002450}
2451
Nick Lewycky287682e2011-10-04 06:51:26 +00002452static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2453 uint64_t k = i*j;
2454 if (j > 1 && k / j != i) Overflow = true;
2455 return k;
2456}
2457
2458/// Compute the result of "n choose k", the binomial coefficient. If an
2459/// intermediate computation overflows, Overflow will be set and the return will
Benjamin Kramerbde91762012-06-02 10:20:22 +00002460/// be garbage. Overflow is not cleared on absence of overflow.
Nick Lewycky287682e2011-10-04 06:51:26 +00002461static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2462 // We use the multiplicative formula:
2463 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2464 // At each iteration, we take the n-th term of the numeral and divide by the
2465 // (k-n)th term of the denominator. This division will always produce an
2466 // integral result, and helps reduce the chance of overflow in the
2467 // intermediate computations. However, we can still overflow even when the
2468 // final result would fit.
2469
2470 if (n == 0 || n == k) return 1;
2471 if (k > n) return 0;
2472
2473 if (k > n/2)
2474 k = n-k;
2475
2476 uint64_t r = 1;
2477 for (uint64_t i = 1; i <= k; ++i) {
2478 r = umul_ov(r, n-(i-1), Overflow);
2479 r /= i;
2480 }
2481 return r;
2482}
2483
Nick Lewycky05044c22014-12-06 00:45:50 +00002484/// Determine if any of the operands in this SCEV are a constant or if
2485/// any of the add or multiply expressions in this SCEV contain a constant.
2486static bool containsConstantSomewhere(const SCEV *StartExpr) {
2487 SmallVector<const SCEV *, 4> Ops;
2488 Ops.push_back(StartExpr);
2489 while (!Ops.empty()) {
2490 const SCEV *CurrentExpr = Ops.pop_back_val();
2491 if (isa<SCEVConstant>(*CurrentExpr))
2492 return true;
2493
2494 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2495 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002496 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
Nick Lewycky05044c22014-12-06 00:45:50 +00002497 }
2498 }
2499 return false;
2500}
2501
Sanjoy Dasf8570812016-05-29 00:38:22 +00002502/// Get a canonical multiply expression, or something simpler if possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002503const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002504 SCEV::NoWrapFlags Flags) {
2505 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2506 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002507 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohman51ad99d2010-01-21 02:09:26 +00002508 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002509#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002510 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002511 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002512 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002513 "SCEVMulExpr operand types don't match!");
2514#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002515
2516 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002517 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002518
Sanjoy Das64895612015-10-09 02:44:45 +00002519 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2520
Chris Lattnerd934c702004-04-02 20:23:17 +00002521 // If there are any constants, fold them together.
2522 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002523 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002524
2525 // C1*(C2+V) -> C1*C2 + C1*V
2526 if (Ops.size() == 2)
Nick Lewycky05044c22014-12-06 00:45:50 +00002527 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2528 // If any of Add's ops are Adds or Muls with a constant,
2529 // apply this transformation as well.
2530 if (Add->getNumOperands() == 2)
2531 if (containsConstantSomewhere(Add))
2532 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2533 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002534
Chris Lattnerd934c702004-04-02 20:23:17 +00002535 ++Idx;
Dan Gohmana30370b2009-05-04 22:02:23 +00002536 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002537 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002538 ConstantInt *Fold =
2539 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002540 Ops[0] = getConstant(Fold);
2541 Ops.erase(Ops.begin()+1); // Erase the folded element
2542 if (Ops.size() == 1) return Ops[0];
2543 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002544 }
2545
2546 // If we are left with a constant one being multiplied, strip it off.
2547 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2548 Ops.erase(Ops.begin());
2549 --Idx;
Reid Spencer2e54a152007-03-02 00:28:52 +00002550 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002551 // If we have a multiply of zero, it will always be zero.
2552 return Ops[0];
Dan Gohman51ad99d2010-01-21 02:09:26 +00002553 } else if (Ops[0]->isAllOnesValue()) {
2554 // If we have a mul by -1 of an add, try distributing the -1 among the
2555 // add operands.
Andrew Trick8b55b732011-03-14 16:50:06 +00002556 if (Ops.size() == 2) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002557 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2558 SmallVector<const SCEV *, 4> NewOps;
2559 bool AnyFolded = false;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002560 for (const SCEV *AddOp : Add->operands()) {
2561 const SCEV *Mul = getMulExpr(Ops[0], AddOp);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002562 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2563 NewOps.push_back(Mul);
2564 }
2565 if (AnyFolded)
2566 return getAddExpr(NewOps);
Sanjoy Das63914592015-10-18 00:29:20 +00002567 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
Andrew Tricke92dcce2011-03-14 17:38:54 +00002568 // Negation preserves a recurrence's no self-wrap property.
2569 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002570 for (const SCEV *AddRecOp : AddRec->operands())
2571 Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2572
Andrew Tricke92dcce2011-03-14 17:38:54 +00002573 return getAddRecExpr(Operands, AddRec->getLoop(),
2574 AddRec->getNoWrapFlags(SCEV::FlagNW));
2575 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002576 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002577 }
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002578
2579 if (Ops.size() == 1)
2580 return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00002581 }
2582
2583 // Skip over the add expression until we get to a multiply.
2584 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2585 ++Idx;
2586
Chris Lattnerd934c702004-04-02 20:23:17 +00002587 // If there are mul operands inline them all into this expression.
2588 if (Idx < Ops.size()) {
2589 bool DeletedMul = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002590 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Li Huangfcfe8cd2016-10-20 21:38:39 +00002591 if (Ops.size() > MulOpsInlineThreshold)
2592 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00002593 // If we have an mul, expand the mul operands onto the end of the operands
2594 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002595 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002596 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002597 DeletedMul = true;
2598 }
2599
2600 // If we deleted at least one mul, we added operands to the end of the list,
2601 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002602 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002603 if (DeletedMul)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002604 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002605 }
2606
2607 // If there are any add recurrences in the operands list, see if any other
2608 // added values are loop invariant. If so, we can fold them into the
2609 // recurrence.
2610 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2611 ++Idx;
2612
2613 // Scan over all recurrences, trying to fold loop invariants into them.
2614 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2615 // Scan all of the other operands to this mul and add them to the vector if
2616 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002617 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002618 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f2de012010-08-29 14:55:19 +00002619 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002620 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002621 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002622 LIOps.push_back(Ops[i]);
2623 Ops.erase(Ops.begin()+i);
2624 --i; --e;
2625 }
2626
2627 // If we found some loop invariants, fold them into the recurrence.
2628 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002629 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanaf752342009-07-07 17:06:11 +00002630 SmallVector<const SCEV *, 4> NewOps;
Chris Lattnerd934c702004-04-02 20:23:17 +00002631 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman8f5954f2010-06-17 23:34:09 +00002632 const SCEV *Scale = getMulExpr(LIOps);
2633 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2634 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002635
Dan Gohman16206132010-06-30 07:16:37 +00002636 // Build the new addrec. Propagate the NUW and NSW flags if both the
2637 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick8b55b732011-03-14 16:50:06 +00002638 //
2639 // No self-wrap cannot be guaranteed after changing the step size, but
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002640 // will be inferred if either NUW or NSW is true.
Andrew Trick8b55b732011-03-14 16:50:06 +00002641 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2642 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002643
2644 // If all of the other operands were loop invariant, we are done.
2645 if (Ops.size() == 1) return NewRec;
2646
Nick Lewyckydb66b822011-09-06 05:08:09 +00002647 // Otherwise, multiply the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002648 for (unsigned i = 0;; ++i)
2649 if (Ops[i] == AddRec) {
2650 Ops[i] = NewRec;
2651 break;
2652 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002653 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002654 }
2655
2656 // Okay, if there weren't any loop invariants to be folded, check to see if
2657 // there are multiple AddRec's with the same loop induction variable being
2658 // multiplied together. If so, we can fold them.
Nick Lewycky97756402014-09-01 05:17:15 +00002659
2660 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2661 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2662 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2663 // ]]],+,...up to x=2n}.
2664 // Note that the arguments to choose() are always integers with values
2665 // known at compile time, never SCEV objects.
2666 //
2667 // The implementation avoids pointless extra computations when the two
2668 // addrec's are of different length (mathematically, it's equivalent to
2669 // an infinite stream of zeros on the right).
2670 bool OpsModified = false;
Chris Lattnerd934c702004-04-02 20:23:17 +00002671 for (unsigned OtherIdx = Idx+1;
Nick Lewycky97756402014-09-01 05:17:15 +00002672 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002673 ++OtherIdx) {
Nick Lewycky97756402014-09-01 05:17:15 +00002674 const SCEVAddRecExpr *OtherAddRec =
2675 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2676 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
Andrew Trick946f76b2012-05-30 03:35:17 +00002677 continue;
2678
Nick Lewycky97756402014-09-01 05:17:15 +00002679 bool Overflow = false;
2680 Type *Ty = AddRec->getType();
2681 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2682 SmallVector<const SCEV*, 7> AddRecOps;
2683 for (int x = 0, xe = AddRec->getNumOperands() +
2684 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002685 const SCEV *Term = getZero(Ty);
Nick Lewycky97756402014-09-01 05:17:15 +00002686 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2687 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2688 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2689 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2690 z < ze && !Overflow; ++z) {
2691 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2692 uint64_t Coeff;
2693 if (LargerThan64Bits)
2694 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2695 else
2696 Coeff = Coeff1*Coeff2;
2697 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2698 const SCEV *Term1 = AddRec->getOperand(y-z);
2699 const SCEV *Term2 = OtherAddRec->getOperand(z);
2700 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
Andrew Trick946f76b2012-05-30 03:35:17 +00002701 }
Andrew Trick946f76b2012-05-30 03:35:17 +00002702 }
Nick Lewycky97756402014-09-01 05:17:15 +00002703 AddRecOps.push_back(Term);
Chris Lattnerd934c702004-04-02 20:23:17 +00002704 }
Nick Lewycky97756402014-09-01 05:17:15 +00002705 if (!Overflow) {
2706 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2707 SCEV::FlagAnyWrap);
2708 if (Ops.size() == 2) return NewAddRec;
2709 Ops[Idx] = NewAddRec;
2710 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2711 OpsModified = true;
2712 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2713 if (!AddRec)
2714 break;
2715 }
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002716 }
Nick Lewycky97756402014-09-01 05:17:15 +00002717 if (OpsModified)
2718 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002719
2720 // Otherwise couldn't fold anything into this recurrence. Move onto the
2721 // next one.
2722 }
2723
2724 // Okay, it looks like we really DO need an mul expr. Check to see if we
2725 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002726 FoldingSetNodeID ID;
2727 ID.AddInteger(scMulExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002728 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2729 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002730 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002731 SCEVMulExpr *S =
2732 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2733 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002734 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2735 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002736 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2737 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002738 UniqueSCEVs.InsertNode(S, IP);
2739 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002740 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002741 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002742}
2743
Sanjoy Dasf8570812016-05-29 00:38:22 +00002744/// Get a canonical unsigned division expression, or something simpler if
2745/// possible.
Dan Gohmanabd17092009-06-24 14:49:00 +00002746const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2747 const SCEV *RHS) {
Dan Gohmand33f36e2009-05-18 15:44:58 +00002748 assert(getEffectiveSCEVType(LHS->getType()) ==
2749 getEffectiveSCEVType(RHS->getType()) &&
2750 "SCEVUDivExpr operand types don't match!");
2751
Dan Gohmana30370b2009-05-04 22:02:23 +00002752 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002753 if (RHSC->getValue()->equalsInt(1))
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00002754 return LHS; // X udiv 1 --> x
Dan Gohmanacd700a2010-04-22 01:35:11 +00002755 // If the denominator is zero, the result of the udiv is undefined. Don't
2756 // try to analyze it, because the resolution chosen here may differ from
2757 // the resolution chosen in other parts of the compiler.
2758 if (!RHSC->getValue()->isZero()) {
2759 // Determine if the division can be folded into the operands of
2760 // its operands.
2761 // TODO: Generalize this to non-constants by using known-bits information.
Chris Lattner229907c2011-07-18 04:54:35 +00002762 Type *Ty = LHS->getType();
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002763 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
Dan Gohmandb764c62010-08-04 19:52:50 +00002764 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanacd700a2010-04-22 01:35:11 +00002765 // For non-power-of-two values, effectively round the value up to the
2766 // nearest power of two.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002767 if (!RHSC->getAPInt().isPowerOf2())
Dan Gohmanacd700a2010-04-22 01:35:11 +00002768 ++MaxShiftAmt;
Chris Lattner229907c2011-07-18 04:54:35 +00002769 IntegerType *ExtTy =
Dan Gohmanacd700a2010-04-22 01:35:11 +00002770 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohmanacd700a2010-04-22 01:35:11 +00002771 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2772 if (const SCEVConstant *Step =
Andrew Trick6d45a012011-08-06 07:00:37 +00002773 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2774 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002775 const APInt &StepInt = Step->getAPInt();
2776 const APInt &DivInt = RHSC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002777 if (!StepInt.urem(DivInt) &&
Dan Gohmanacd700a2010-04-22 01:35:11 +00002778 getZeroExtendExpr(AR, ExtTy) ==
2779 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2780 getZeroExtendExpr(Step, ExtTy),
Andrew Trick8b55b732011-03-14 16:50:06 +00002781 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002782 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002783 for (const SCEV *Op : AR->operands())
2784 Operands.push_back(getUDivExpr(Op, RHS));
2785 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002786 }
Andrew Trick6d45a012011-08-06 07:00:37 +00002787 /// Get a canonical UDivExpr for a recurrence.
2788 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2789 // We can currently only fold X%N if X is constant.
2790 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2791 if (StartC && !DivInt.urem(StepInt) &&
2792 getZeroExtendExpr(AR, ExtTy) ==
2793 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2794 getZeroExtendExpr(Step, ExtTy),
2795 AR->getLoop(), SCEV::FlagAnyWrap)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002796 const APInt &StartInt = StartC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002797 const APInt &StartRem = StartInt.urem(StepInt);
2798 if (StartRem != 0)
2799 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2800 AR->getLoop(), SCEV::FlagNW);
2801 }
2802 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002803 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2804 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2805 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002806 for (const SCEV *Op : M->operands())
2807 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002808 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2809 // Find an operand that's safely divisible.
2810 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2811 const SCEV *Op = M->getOperand(i);
2812 const SCEV *Div = getUDivExpr(Op, RHSC);
2813 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2814 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2815 M->op_end());
2816 Operands[i] = Div;
2817 return getMulExpr(Operands);
2818 }
2819 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002820 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002821 // (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 +00002822 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002823 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002824 for (const SCEV *Op : A->operands())
2825 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002826 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2827 Operands.clear();
2828 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2829 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2830 if (isa<SCEVUDivExpr>(Op) ||
2831 getMulExpr(Op, RHS) != A->getOperand(i))
2832 break;
2833 Operands.push_back(Op);
2834 }
2835 if (Operands.size() == A->getNumOperands())
2836 return getAddExpr(Operands);
2837 }
2838 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002839
Dan Gohmanacd700a2010-04-22 01:35:11 +00002840 // Fold if both operands are constant.
2841 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2842 Constant *LHSCV = LHSC->getValue();
2843 Constant *RHSCV = RHSC->getValue();
2844 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2845 RHSCV)));
2846 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002847 }
2848 }
2849
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002850 FoldingSetNodeID ID;
2851 ID.AddInteger(scUDivExpr);
2852 ID.AddPointer(LHS);
2853 ID.AddPointer(RHS);
Craig Topper9f008862014-04-15 04:59:12 +00002854 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002855 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00002856 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2857 LHS, RHS);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002858 UniqueSCEVs.InsertNode(S, IP);
2859 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002860}
2861
Nick Lewycky31eaca52014-01-27 10:04:03 +00002862static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002863 APInt A = C1->getAPInt().abs();
2864 APInt B = C2->getAPInt().abs();
Nick Lewycky31eaca52014-01-27 10:04:03 +00002865 uint32_t ABW = A.getBitWidth();
2866 uint32_t BBW = B.getBitWidth();
2867
2868 if (ABW > BBW)
2869 B = B.zext(ABW);
2870 else if (ABW < BBW)
2871 A = A.zext(BBW);
2872
2873 return APIntOps::GreatestCommonDivisor(A, B);
2874}
2875
Sanjoy Dasf8570812016-05-29 00:38:22 +00002876/// Get a canonical unsigned division expression, or something simpler if
2877/// possible. There is no representation for an exact udiv in SCEV IR, but we
2878/// can attempt to remove factors from the LHS and RHS. We can't do this when
2879/// it's not exact because the udiv may be clearing bits.
Nick Lewycky31eaca52014-01-27 10:04:03 +00002880const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2881 const SCEV *RHS) {
2882 // TODO: we could try to find factors in all sorts of things, but for now we
2883 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2884 // end of this file for inspiration.
2885
2886 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2887 if (!Mul)
2888 return getUDivExpr(LHS, RHS);
2889
2890 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2891 // If the mulexpr multiplies by a constant, then that constant must be the
2892 // first element of the mulexpr.
Sanjoy Das63914592015-10-18 00:29:20 +00002893 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
Nick Lewycky31eaca52014-01-27 10:04:03 +00002894 if (LHSCst == RHSCst) {
2895 SmallVector<const SCEV *, 2> Operands;
2896 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2897 return getMulExpr(Operands);
2898 }
2899
2900 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2901 // that there's a factor provided by one of the other terms. We need to
2902 // check.
2903 APInt Factor = gcd(LHSCst, RHSCst);
2904 if (!Factor.isIntN(1)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002905 LHSCst =
2906 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
2907 RHSCst =
2908 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
Nick Lewycky31eaca52014-01-27 10:04:03 +00002909 SmallVector<const SCEV *, 2> Operands;
2910 Operands.push_back(LHSCst);
2911 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2912 LHS = getMulExpr(Operands);
2913 RHS = RHSCst;
Nick Lewycky629199c2014-01-27 10:47:44 +00002914 Mul = dyn_cast<SCEVMulExpr>(LHS);
2915 if (!Mul)
2916 return getUDivExactExpr(LHS, RHS);
Nick Lewycky31eaca52014-01-27 10:04:03 +00002917 }
2918 }
2919 }
2920
2921 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2922 if (Mul->getOperand(i) == RHS) {
2923 SmallVector<const SCEV *, 2> Operands;
2924 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2925 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2926 return getMulExpr(Operands);
2927 }
2928 }
2929
2930 return getUDivExpr(LHS, RHS);
2931}
Chris Lattnerd934c702004-04-02 20:23:17 +00002932
Sanjoy Dasf8570812016-05-29 00:38:22 +00002933/// Get an add recurrence expression for the specified loop. Simplify the
2934/// expression as much as possible.
Andrew Trick8b55b732011-03-14 16:50:06 +00002935const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2936 const Loop *L,
2937 SCEV::NoWrapFlags Flags) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002938 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00002939 Operands.push_back(Start);
Dan Gohmana30370b2009-05-04 22:02:23 +00002940 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattnerd934c702004-04-02 20:23:17 +00002941 if (StepChrec->getLoop() == L) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00002942 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002943 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattnerd934c702004-04-02 20:23:17 +00002944 }
2945
2946 Operands.push_back(Step);
Andrew Trick8b55b732011-03-14 16:50:06 +00002947 return getAddRecExpr(Operands, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002948}
2949
Sanjoy Dasf8570812016-05-29 00:38:22 +00002950/// Get an add recurrence expression for the specified loop. Simplify the
2951/// expression as much as possible.
Dan Gohmance973df2009-06-24 04:48:43 +00002952const SCEV *
Dan Gohmanaf752342009-07-07 17:06:11 +00002953ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick8b55b732011-03-14 16:50:06 +00002954 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002955 if (Operands.size() == 1) return Operands[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002956#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002957 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002958 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002959 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002960 "SCEVAddRecExpr operand types don't match!");
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002961 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002962 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002963 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmand33f36e2009-05-18 15:44:58 +00002964#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002965
Dan Gohmanbe928e32008-06-18 16:23:07 +00002966 if (Operands.back()->isZero()) {
2967 Operands.pop_back();
Andrew Trick8b55b732011-03-14 16:50:06 +00002968 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmanbe928e32008-06-18 16:23:07 +00002969 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002970
Dan Gohmancf9c64e2010-02-19 18:49:22 +00002971 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2972 // use that information to infer NUW and NSW flags. However, computing a
2973 // BE count requires calling getAddRecExpr, so we may not yet have a
2974 // meaningful BE count at this point (and if we don't, we'd be stuck
2975 // with a SCEVCouldNotCompute as the cached BE count).
2976
Sanjoy Das81401d42015-01-10 23:41:24 +00002977 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002978
Dan Gohman223a5d22008-08-08 18:33:12 +00002979 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmana30370b2009-05-04 22:02:23 +00002980 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00002981 const Loop *NestedLoop = NestedAR->getLoop();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002982 if (L->contains(NestedLoop)
2983 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
2984 : (!NestedLoop->contains(L) &&
2985 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002986 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmancb0efec2009-12-18 01:14:11 +00002987 NestedAR->op_end());
Dan Gohman223a5d22008-08-08 18:33:12 +00002988 Operands[0] = NestedAR->getStart();
Dan Gohmancc030b72009-06-26 22:36:20 +00002989 // AddRecs require their operands be loop-invariant with respect to their
2990 // loops. Don't perform this transformation if it would break this
2991 // requirement.
Sanjoy Das3b827c72015-11-29 23:40:53 +00002992 bool AllInvariant = all_of(
2993 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00002994
Dan Gohmancc030b72009-06-26 22:36:20 +00002995 if (AllInvariant) {
Andrew Trick8b55b732011-03-14 16:50:06 +00002996 // Create a recurrence for the outer loop with the same step size.
2997 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002998 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2999 // inner recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00003000 SCEV::NoWrapFlags OuterFlags =
3001 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick8b55b732011-03-14 16:50:06 +00003002
3003 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Sanjoy Das3b827c72015-11-29 23:40:53 +00003004 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3005 return isLoopInvariant(Op, NestedLoop);
3006 });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00003007
Andrew Trick8b55b732011-03-14 16:50:06 +00003008 if (AllInvariant) {
Dan Gohmancc030b72009-06-26 22:36:20 +00003009 // Ok, both add recurrences are valid after the transformation.
Andrew Trick8b55b732011-03-14 16:50:06 +00003010 //
Andrew Trick8b55b732011-03-14 16:50:06 +00003011 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3012 // the outer recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00003013 SCEV::NoWrapFlags InnerFlags =
3014 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick8b55b732011-03-14 16:50:06 +00003015 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3016 }
Dan Gohmancc030b72009-06-26 22:36:20 +00003017 }
3018 // Reset Operands to its original state.
3019 Operands[0] = NestedAR;
Dan Gohman223a5d22008-08-08 18:33:12 +00003020 }
3021 }
3022
Dan Gohman8d67d2f2010-01-19 22:27:22 +00003023 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3024 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003025 FoldingSetNodeID ID;
3026 ID.AddInteger(scAddRecExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003027 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3028 ID.AddPointer(Operands[i]);
3029 ID.AddPointer(L);
Craig Topper9f008862014-04-15 04:59:12 +00003030 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00003031 SCEVAddRecExpr *S =
3032 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3033 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00003034 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3035 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003036 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3037 O, Operands.size(), L);
Dan Gohman51ad99d2010-01-21 02:09:26 +00003038 UniqueSCEVs.InsertNode(S, IP);
3039 }
Andrew Trick8b55b732011-03-14 16:50:06 +00003040 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003041 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00003042}
3043
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003044const SCEV *
Peter Collingbourne8dff0392016-11-13 06:59:50 +00003045ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3046 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3047 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003048 // getSCEV(Base)->getType() has the same address space as Base->getType()
3049 // because SCEV::getType() preserves the address space.
3050 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3051 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3052 // instruction to its SCEV, because the Instruction may be guarded by control
3053 // flow and the no-overflow bits may not be valid for the expression in any
Jingyue Wu42f1d672015-07-28 18:22:40 +00003054 // context. This can be fixed similarly to how these flags are handled for
3055 // adds.
Peter Collingbourne8dff0392016-11-13 06:59:50 +00003056 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3057 : SCEV::FlagAnyWrap;
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003058
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003059 const SCEV *TotalOffset = getZero(IntPtrTy);
Peter Collingbourne45681582016-12-02 03:05:41 +00003060 // The array size is unimportant. The first thing we do on CurTy is getting
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003061 // its element type.
Peter Collingbourne45681582016-12-02 03:05:41 +00003062 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
Jingyue Wu2982d4d2015-05-18 17:03:25 +00003063 for (const SCEV *IndexExpr : IndexExprs) {
3064 // Compute the (potentially symbolic) offset in bytes for this index.
3065 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3066 // For a struct, add the member offset.
3067 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3068 unsigned FieldNo = Index->getZExtValue();
3069 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3070
3071 // Add the field offset to the running total offset.
3072 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3073
3074 // Update CurTy to the type of the field at Index.
3075 CurTy = STy->getTypeAtIndex(Index);
3076 } else {
3077 // Update CurTy to its element type.
3078 CurTy = cast<SequentialType>(CurTy)->getElementType();
3079 // For an array, add the element offset, explicitly scaled.
3080 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3081 // Getelementptr indices are signed.
3082 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3083
3084 // Multiply the index by the element size to compute the element offset.
3085 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3086
3087 // Add the element offset to the running total offset.
3088 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3089 }
3090 }
3091
3092 // Add the total offset from all the GEP indices to the base.
3093 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3094}
3095
Dan Gohmanabd17092009-06-24 14:49:00 +00003096const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3097 const SCEV *RHS) {
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003098 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003099 return getSMaxExpr(Ops);
3100}
3101
Dan Gohmanaf752342009-07-07 17:06:11 +00003102const SCEV *
3103ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003104 assert(!Ops.empty() && "Cannot get empty smax!");
3105 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003106#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003107 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003108 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003109 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003110 "SCEVSMaxExpr operand types don't match!");
3111#endif
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003112
3113 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003114 GroupByComplexity(Ops, &LI);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003115
3116 // If there are any constants, fold them together.
3117 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003118 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003119 ++Idx;
3120 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003121 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003122 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003123 ConstantInt *Fold = ConstantInt::get(
3124 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003125 Ops[0] = getConstant(Fold);
3126 Ops.erase(Ops.begin()+1); // Erase the folded element
3127 if (Ops.size() == 1) return Ops[0];
3128 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003129 }
3130
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003131 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003132 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3133 Ops.erase(Ops.begin());
3134 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003135 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3136 // If we have an smax with a constant maximum-int, it will always be
3137 // maximum-int.
3138 return Ops[0];
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003139 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003140
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003141 if (Ops.size() == 1) return Ops[0];
3142 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003143
3144 // Find the first SMax
3145 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3146 ++Idx;
3147
3148 // Check to see if one of the operands is an SMax. If so, expand its operands
3149 // onto our operand list, and recurse to simplify.
3150 if (Idx < Ops.size()) {
3151 bool DeletedSMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003152 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003153 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003154 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003155 DeletedSMax = true;
3156 }
3157
3158 if (DeletedSMax)
3159 return getSMaxExpr(Ops);
3160 }
3161
3162 // Okay, check to see if the same value occurs in the operand list twice. If
3163 // so, delete one. Since we sorted the list, these values are required to
3164 // be adjacent.
3165 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003166 // X smax Y smax Y --> X smax Y
3167 // X smax Y --> X, if X is always greater than Y
3168 if (Ops[i] == Ops[i+1] ||
3169 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3170 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3171 --i; --e;
3172 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003173 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3174 --i; --e;
3175 }
3176
3177 if (Ops.size() == 1) return Ops[0];
3178
3179 assert(!Ops.empty() && "Reduced smax down to nothing!");
3180
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003181 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003182 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003183 FoldingSetNodeID ID;
3184 ID.AddInteger(scSMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003185 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3186 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003187 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003188 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003189 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3190 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003191 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3192 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003193 UniqueSCEVs.InsertNode(S, IP);
3194 return S;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003195}
3196
Dan Gohmanabd17092009-06-24 14:49:00 +00003197const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3198 const SCEV *RHS) {
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003199 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003200 return getUMaxExpr(Ops);
3201}
3202
Dan Gohmanaf752342009-07-07 17:06:11 +00003203const SCEV *
3204ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003205 assert(!Ops.empty() && "Cannot get empty umax!");
3206 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003207#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003208 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003209 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003210 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003211 "SCEVUMaxExpr operand types don't match!");
3212#endif
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003213
3214 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003215 GroupByComplexity(Ops, &LI);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003216
3217 // If there are any constants, fold them together.
3218 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003219 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003220 ++Idx;
3221 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003222 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003223 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003224 ConstantInt *Fold = ConstantInt::get(
3225 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003226 Ops[0] = getConstant(Fold);
3227 Ops.erase(Ops.begin()+1); // Erase the folded element
3228 if (Ops.size() == 1) return Ops[0];
3229 LHSC = cast<SCEVConstant>(Ops[0]);
3230 }
3231
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003232 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003233 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3234 Ops.erase(Ops.begin());
3235 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003236 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3237 // If we have an umax with a constant maximum-int, it will always be
3238 // maximum-int.
3239 return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003240 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003241
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003242 if (Ops.size() == 1) return Ops[0];
3243 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003244
3245 // Find the first UMax
3246 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3247 ++Idx;
3248
3249 // Check to see if one of the operands is a UMax. If so, expand its operands
3250 // onto our operand list, and recurse to simplify.
3251 if (Idx < Ops.size()) {
3252 bool DeletedUMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003253 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003254 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003255 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003256 DeletedUMax = true;
3257 }
3258
3259 if (DeletedUMax)
3260 return getUMaxExpr(Ops);
3261 }
3262
3263 // Okay, check to see if the same value occurs in the operand list twice. If
3264 // so, delete one. Since we sorted the list, these values are required to
3265 // be adjacent.
3266 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003267 // X umax Y umax Y --> X umax Y
3268 // X umax Y --> X, if X is always greater than Y
3269 if (Ops[i] == Ops[i+1] ||
3270 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3271 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3272 --i; --e;
3273 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003274 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3275 --i; --e;
3276 }
3277
3278 if (Ops.size() == 1) return Ops[0];
3279
3280 assert(!Ops.empty() && "Reduced umax down to nothing!");
3281
3282 // Okay, it looks like we really DO need a umax expr. Check to see if we
3283 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003284 FoldingSetNodeID ID;
3285 ID.AddInteger(scUMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003286 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3287 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003288 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003289 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003290 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3291 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003292 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3293 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003294 UniqueSCEVs.InsertNode(S, IP);
3295 return S;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003296}
3297
Dan Gohmanabd17092009-06-24 14:49:00 +00003298const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3299 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003300 // ~smax(~x, ~y) == smin(x, y).
3301 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3302}
3303
Dan Gohmanabd17092009-06-24 14:49:00 +00003304const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3305 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003306 // ~umax(~x, ~y) == umin(x, y)
3307 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3308}
3309
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003310const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003311 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003312 // constant expression and then folding it back into a ConstantInt.
3313 // This is just a compile-time optimization.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003314 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003315}
3316
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003317const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3318 StructType *STy,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003319 unsigned FieldNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003320 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003321 // constant expression and then folding it back into a ConstantInt.
3322 // This is just a compile-time optimization.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003323 return getConstant(
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003324 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003325}
3326
Dan Gohmanaf752342009-07-07 17:06:11 +00003327const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf436bac2009-06-24 00:54:57 +00003328 // Don't attempt to do anything other than create a SCEVUnknown object
3329 // here. createSCEV only calls getUnknown after checking for all other
3330 // interesting possibilities, and any other code that calls getUnknown
3331 // is doing so in order to hide a value from SCEV canonicalization.
3332
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003333 FoldingSetNodeID ID;
3334 ID.AddInteger(scUnknown);
3335 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +00003336 void *IP = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00003337 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3338 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3339 "Stale SCEVUnknown in uniquing map!");
3340 return S;
3341 }
3342 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3343 FirstUnknown);
3344 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003345 UniqueSCEVs.InsertNode(S, IP);
3346 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +00003347}
3348
Chris Lattnerd934c702004-04-02 20:23:17 +00003349//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00003350// Basic SCEV Analysis and PHI Idiom Recognition Code
3351//
3352
Sanjoy Dasf8570812016-05-29 00:38:22 +00003353/// Test if values of the given type are analyzable within the SCEV
3354/// framework. This primarily includes integer types, and it can optionally
3355/// include pointer types if the ScalarEvolution class has access to
3356/// target-specific information.
Chris Lattner229907c2011-07-18 04:54:35 +00003357bool ScalarEvolution::isSCEVable(Type *Ty) const {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003358 // Integers and pointers are always SCEVable.
Duncan Sands19d0b472010-02-16 11:11:14 +00003359 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003360}
3361
Sanjoy Dasf8570812016-05-29 00:38:22 +00003362/// Return the size in bits of the specified type, for which isSCEVable must
3363/// return true.
Chris Lattner229907c2011-07-18 04:54:35 +00003364uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003365 assert(isSCEVable(Ty) && "Type is not SCEVable!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003366 return getDataLayout().getTypeSizeInBits(Ty);
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003367}
3368
Sanjoy Dasf8570812016-05-29 00:38:22 +00003369/// Return a type with the same bitwidth as the given type and which represents
3370/// how SCEV will treat the given type, for which isSCEVable must return
3371/// true. For pointer types, this is the pointer-sized integer type.
Chris Lattner229907c2011-07-18 04:54:35 +00003372Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003373 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3374
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003375 if (Ty->isIntegerTy())
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003376 return Ty;
3377
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003378 // The only other support type is pointer.
Duncan Sands19d0b472010-02-16 11:11:14 +00003379 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003380 return getDataLayout().getIntPtrType(Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003381}
Chris Lattnerd934c702004-04-02 20:23:17 +00003382
Dan Gohmanaf752342009-07-07 17:06:11 +00003383const SCEV *ScalarEvolution::getCouldNotCompute() {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003384 return CouldNotCompute.get();
Dan Gohman31efa302009-04-18 17:58:19 +00003385}
3386
Sanjoy Das7d752672015-12-08 04:32:54 +00003387bool ScalarEvolution::checkValidity(const SCEV *S) const {
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003388 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3389 auto *SU = dyn_cast<SCEVUnknown>(S);
3390 return SU && SU->getValue() == nullptr;
3391 });
Shuxin Yangefc4c012013-07-08 17:33:13 +00003392
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003393 return !ContainsNulls;
Shuxin Yangefc4c012013-07-08 17:33:13 +00003394}
3395
Wei Mia49559b2016-02-04 01:27:38 +00003396bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
Sanjoy Dasa2602142016-09-27 18:01:46 +00003397 HasRecMapType::iterator I = HasRecMap.find(S);
Wei Mia49559b2016-02-04 01:27:38 +00003398 if (I != HasRecMap.end())
3399 return I->second;
3400
Sanjoy Das0ae390a2016-11-10 06:33:54 +00003401 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00003402 HasRecMap.insert({S, FoundAddRec});
3403 return FoundAddRec;
Wei Mia49559b2016-02-04 01:27:38 +00003404}
3405
Wei Mi785858c2016-08-09 20:37:50 +00003406/// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3407/// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3408/// offset I, then return {S', I}, else return {\p S, nullptr}.
3409static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3410 const auto *Add = dyn_cast<SCEVAddExpr>(S);
3411 if (!Add)
3412 return {S, nullptr};
3413
3414 if (Add->getNumOperands() != 2)
3415 return {S, nullptr};
3416
3417 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3418 if (!ConstOp)
3419 return {S, nullptr};
3420
3421 return {Add->getOperand(1), ConstOp->getValue()};
3422}
3423
3424/// Return the ValueOffsetPair set for \p S. \p S can be represented
3425/// by the value and offset from any ValueOffsetPair in the set.
3426SetVector<ScalarEvolution::ValueOffsetPair> *
3427ScalarEvolution::getSCEVValues(const SCEV *S) {
Wei Mia49559b2016-02-04 01:27:38 +00003428 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3429 if (SI == ExprValueMap.end())
3430 return nullptr;
3431#ifndef NDEBUG
3432 if (VerifySCEVMap) {
3433 // Check there is no dangling Value in the set returned.
3434 for (const auto &VE : SI->second)
Wei Mi785858c2016-08-09 20:37:50 +00003435 assert(ValueExprMap.count(VE.first));
Wei Mia49559b2016-02-04 01:27:38 +00003436 }
3437#endif
3438 return &SI->second;
3439}
3440
Wei Mi785858c2016-08-09 20:37:50 +00003441/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3442/// cannot be used separately. eraseValueFromMap should be used to remove
3443/// V from ValueExprMap and ExprValueMap at the same time.
Wei Mia49559b2016-02-04 01:27:38 +00003444void ScalarEvolution::eraseValueFromMap(Value *V) {
3445 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3446 if (I != ValueExprMap.end()) {
3447 const SCEV *S = I->second;
Wei Mi785858c2016-08-09 20:37:50 +00003448 // Remove {V, 0} from the set of ExprValueMap[S]
3449 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3450 SV->remove({V, nullptr});
3451
3452 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3453 const SCEV *Stripped;
3454 ConstantInt *Offset;
3455 std::tie(Stripped, Offset) = splitAddExpr(S);
3456 if (Offset != nullptr) {
3457 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3458 SV->remove({V, Offset});
3459 }
Wei Mia49559b2016-02-04 01:27:38 +00003460 ValueExprMap.erase(V);
3461 }
3462}
3463
Sanjoy Dasf8570812016-05-29 00:38:22 +00003464/// Return an existing SCEV if it exists, otherwise analyze the expression and
3465/// create a new one.
Dan Gohmanaf752342009-07-07 17:06:11 +00003466const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003467 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattnerd934c702004-04-02 20:23:17 +00003468
Jingyue Wu42f1d672015-07-28 18:22:40 +00003469 const SCEV *S = getExistingSCEV(V);
3470 if (S == nullptr) {
3471 S = createSCEV(V);
Wei Mia49559b2016-02-04 01:27:38 +00003472 // During PHI resolution, it is possible to create two SCEVs for the same
3473 // V, so it is needed to double check whether V->S is inserted into
Wei Mi785858c2016-08-09 20:37:50 +00003474 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
Wei Mia49559b2016-02-04 01:27:38 +00003475 std::pair<ValueExprMapType::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003476 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
Wei Mi785858c2016-08-09 20:37:50 +00003477 if (Pair.second) {
3478 ExprValueMap[S].insert({V, nullptr});
3479
3480 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3481 // ExprValueMap.
3482 const SCEV *Stripped = S;
3483 ConstantInt *Offset = nullptr;
3484 std::tie(Stripped, Offset) = splitAddExpr(S);
3485 // If stripped is SCEVUnknown, don't bother to save
3486 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3487 // increase the complexity of the expansion code.
3488 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3489 // because it may generate add/sub instead of GEP in SCEV expansion.
3490 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3491 !isa<GetElementPtrInst>(V))
3492 ExprValueMap[Stripped].insert({V, Offset});
3493 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003494 }
3495 return S;
3496}
3497
3498const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3499 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3500
Shuxin Yangefc4c012013-07-08 17:33:13 +00003501 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3502 if (I != ValueExprMap.end()) {
3503 const SCEV *S = I->second;
Shuxin Yang23773b32013-07-12 07:25:38 +00003504 if (checkValidity(S))
Shuxin Yangefc4c012013-07-08 17:33:13 +00003505 return S;
Wei Mi785858c2016-08-09 20:37:50 +00003506 eraseValueFromMap(V);
Wei Mia49559b2016-02-04 01:27:38 +00003507 forgetMemoizedResults(S);
Shuxin Yangefc4c012013-07-08 17:33:13 +00003508 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003509 return nullptr;
Chris Lattnerd934c702004-04-02 20:23:17 +00003510}
3511
Sanjoy Dasf8570812016-05-29 00:38:22 +00003512/// Return a SCEV corresponding to -V = -1*V
Dan Gohman0a40ad92009-04-16 03:18:22 +00003513///
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003514const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3515 SCEV::NoWrapFlags Flags) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003516 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson53a52212009-07-13 04:09:18 +00003517 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003518 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003519
Chris Lattner229907c2011-07-18 04:54:35 +00003520 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003521 Ty = getEffectiveSCEVType(Ty);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003522 return getMulExpr(
3523 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003524}
3525
Sanjoy Dasf8570812016-05-29 00:38:22 +00003526/// Return a SCEV corresponding to ~V = -1-V
Dan Gohmanaf752342009-07-07 17:06:11 +00003527const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003528 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson542619e2009-07-13 20:58:05 +00003529 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003530 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003531
Chris Lattner229907c2011-07-18 04:54:35 +00003532 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003533 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003534 const SCEV *AllOnes =
Owen Anderson5a1acd92009-07-31 20:28:14 +00003535 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003536 return getMinusSCEV(AllOnes, V);
3537}
3538
Chris Lattnerfc877522011-01-09 22:26:35 +00003539const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00003540 SCEV::NoWrapFlags Flags) {
Dan Gohman46f00a22010-07-20 16:53:00 +00003541 // Fast path: X - X --> 0.
3542 if (LHS == RHS)
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003543 return getZero(LHS->getType());
Dan Gohman46f00a22010-07-20 16:53:00 +00003544
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003545 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3546 // makes it so that we cannot make much use of NUW.
3547 auto AddFlags = SCEV::FlagAnyWrap;
3548 const bool RHSIsNotMinSigned =
3549 !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3550 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3551 // Let M be the minimum representable signed value. Then (-1)*RHS
3552 // signed-wraps if and only if RHS is M. That can happen even for
3553 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3554 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3555 // (-1)*RHS, we need to prove that RHS != M.
3556 //
3557 // If LHS is non-negative and we know that LHS - RHS does not
3558 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3559 // either by proving that RHS > M or that LHS >= 0.
3560 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3561 AddFlags = SCEV::FlagNSW;
3562 }
3563 }
3564
3565 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3566 // RHS is NSW and LHS >= 0.
3567 //
3568 // The difficulty here is that the NSW flag may have been proven
3569 // relative to a loop that is to be found in a recurrence in LHS and
3570 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3571 // larger scope than intended.
3572 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3573
3574 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003575}
3576
Dan Gohmanaf752342009-07-07 17:06:11 +00003577const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003578ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3579 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003580 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3581 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003582 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003583 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003584 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003585 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003586 return getTruncateExpr(V, Ty);
3587 return getZeroExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003588}
3589
Dan Gohmanaf752342009-07-07 17:06:11 +00003590const SCEV *
3591ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattner229907c2011-07-18 04:54:35 +00003592 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 Gohman0a40ad92009-04-16 03:18:22 +00003596 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003597 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003598 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003599 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003600 return getTruncateExpr(V, Ty);
3601 return getSignExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003602}
3603
Dan Gohmanaf752342009-07-07 17:06:11 +00003604const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003605ScalarEvolution::getNoopOrZeroExtend(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 Gohmane712a2f2009-05-13 03:46:30 +00003609 "Cannot noop or zero extend with non-integer arguments!");
3610 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3611 "getNoopOrZeroExtend cannot truncate!");
3612 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3613 return V; // No conversion
3614 return getZeroExtendExpr(V, Ty);
3615}
3616
Dan Gohmanaf752342009-07-07 17:06:11 +00003617const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003618ScalarEvolution::getNoopOrSignExtend(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 noop or sign extend with non-integer arguments!");
3623 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3624 "getNoopOrSignExtend cannot truncate!");
3625 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3626 return V; // No conversion
3627 return getSignExtendExpr(V, Ty);
3628}
3629
Dan Gohmanaf752342009-07-07 17:06:11 +00003630const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003631ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3632 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003633 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3634 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman8db2edc2009-06-13 15:56:47 +00003635 "Cannot noop or any extend with non-integer arguments!");
3636 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3637 "getNoopOrAnyExtend cannot truncate!");
3638 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3639 return V; // No conversion
3640 return getAnyExtendExpr(V, Ty);
3641}
3642
Dan Gohmanaf752342009-07-07 17:06:11 +00003643const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003644ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3645 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003646 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3647 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003648 "Cannot truncate or noop with non-integer arguments!");
3649 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3650 "getTruncateOrNoop cannot extend!");
3651 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3652 return V; // No conversion
3653 return getTruncateExpr(V, Ty);
3654}
3655
Dan Gohmanabd17092009-06-24 14:49:00 +00003656const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3657 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003658 const SCEV *PromotedLHS = LHS;
3659 const SCEV *PromotedRHS = RHS;
Dan Gohman96212b62009-06-22 00:31:57 +00003660
3661 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3662 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3663 else
3664 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3665
3666 return getUMaxExpr(PromotedLHS, PromotedRHS);
3667}
3668
Dan Gohmanabd17092009-06-24 14:49:00 +00003669const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3670 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003671 const SCEV *PromotedLHS = LHS;
3672 const SCEV *PromotedRHS = RHS;
Dan Gohman2bc22302009-06-22 15:03:27 +00003673
3674 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3675 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3676 else
3677 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3678
3679 return getUMinExpr(PromotedLHS, PromotedRHS);
3680}
3681
Andrew Trick87716c92011-03-17 23:51:11 +00003682const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3683 // A pointer operand may evaluate to a nonpointer expression, such as null.
3684 if (!V->getType()->isPointerTy())
3685 return V;
3686
3687 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3688 return getPointerBase(Cast->getOperand());
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003689 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
Craig Topper9f008862014-04-15 04:59:12 +00003690 const SCEV *PtrOp = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003691 for (const SCEV *NAryOp : NAry->operands()) {
3692 if (NAryOp->getType()->isPointerTy()) {
Andrew Trick87716c92011-03-17 23:51:11 +00003693 // Cannot find the base of an expression with multiple pointer operands.
3694 if (PtrOp)
3695 return V;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003696 PtrOp = NAryOp;
Andrew Trick87716c92011-03-17 23:51:11 +00003697 }
3698 }
3699 if (!PtrOp)
3700 return V;
3701 return getPointerBase(PtrOp);
3702 }
3703 return V;
3704}
3705
Sanjoy Dasf8570812016-05-29 00:38:22 +00003706/// Push users of the given Instruction onto the given Worklist.
Dan Gohman0b89dff2009-07-25 01:13:03 +00003707static void
3708PushDefUseChildren(Instruction *I,
3709 SmallVectorImpl<Instruction *> &Worklist) {
3710 // Push the def-use children onto the Worklist stack.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003711 for (User *U : I->users())
3712 Worklist.push_back(cast<Instruction>(U));
Dan Gohman0b89dff2009-07-25 01:13:03 +00003713}
3714
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00003715void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohman0b89dff2009-07-25 01:13:03 +00003716 SmallVector<Instruction *, 16> Worklist;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003717 PushDefUseChildren(PN, Worklist);
Chris Lattnerd934c702004-04-02 20:23:17 +00003718
Dan Gohman0b89dff2009-07-25 01:13:03 +00003719 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003720 Visited.insert(PN);
Dan Gohman0b89dff2009-07-25 01:13:03 +00003721 while (!Worklist.empty()) {
Dan Gohmana9c205c2010-02-25 06:57:05 +00003722 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00003723 if (!Visited.insert(I).second)
3724 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003725
Sanjoy Das63914592015-10-18 00:29:20 +00003726 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003727 if (It != ValueExprMap.end()) {
Dan Gohman761065e2010-11-17 02:44:44 +00003728 const SCEV *Old = It->second;
3729
Dan Gohman0b89dff2009-07-25 01:13:03 +00003730 // Short-circuit the def-use traversal if the symbolic name
3731 // ceases to appear in expressions.
Dan Gohman534749b2010-11-17 22:27:42 +00003732 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohman0b89dff2009-07-25 01:13:03 +00003733 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003734
Dan Gohman0b89dff2009-07-25 01:13:03 +00003735 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohmana9c205c2010-02-25 06:57:05 +00003736 // structure, it's a PHI that's in the progress of being computed
3737 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3738 // additional loop trip count information isn't going to change anything.
3739 // In the second case, createNodeForPHI will perform the necessary
3740 // updates on its own when it gets to that point. In the third, we do
3741 // want to forget the SCEVUnknown.
3742 if (!isa<PHINode>(I) ||
Dan Gohman761065e2010-11-17 02:44:44 +00003743 !isa<SCEVUnknown>(Old) ||
3744 (I != PN && Old == SymName)) {
Wei Mi785858c2016-08-09 20:37:50 +00003745 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00003746 forgetMemoizedResults(Old);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00003747 }
Dan Gohman0b89dff2009-07-25 01:13:03 +00003748 }
3749
3750 PushDefUseChildren(I, Worklist);
3751 }
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003752}
Chris Lattnerd934c702004-04-02 20:23:17 +00003753
Benjamin Kramer83709b12015-11-16 09:01:28 +00003754namespace {
Silviu Barangaf91c8072015-10-30 15:02:28 +00003755class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3756public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003757 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003758 ScalarEvolution &SE) {
3759 SCEVInitRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003760 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003761 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3762 }
3763
3764 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3765 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3766
3767 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3768 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3769 Valid = false;
3770 return Expr;
3771 }
3772
3773 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3774 // Only allow AddRecExprs for this loop.
3775 if (Expr->getLoop() == L)
3776 return Expr->getStart();
3777 Valid = false;
3778 return Expr;
3779 }
3780
3781 bool isValid() { return Valid; }
3782
3783private:
3784 const Loop *L;
3785 bool Valid;
3786};
3787
3788class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3789public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003790 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003791 ScalarEvolution &SE) {
3792 SCEVShiftRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003793 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003794 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3795 }
3796
3797 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3798 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3799
3800 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3801 // Only allow AddRecExprs for this loop.
3802 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3803 Valid = false;
3804 return Expr;
3805 }
3806
3807 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3808 if (Expr->getLoop() == L && Expr->isAffine())
3809 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3810 Valid = false;
3811 return Expr;
3812 }
3813 bool isValid() { return Valid; }
3814
3815private:
3816 const Loop *L;
3817 bool Valid;
3818};
Benjamin Kramer83709b12015-11-16 09:01:28 +00003819} // end anonymous namespace
Silviu Barangaf91c8072015-10-30 15:02:28 +00003820
Sanjoy Das724f5cf2016-03-03 18:31:29 +00003821SCEV::NoWrapFlags
3822ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3823 if (!AR->isAffine())
3824 return SCEV::FlagAnyWrap;
3825
3826 typedef OverflowingBinaryOperator OBO;
3827 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3828
3829 if (!AR->hasNoSignedWrap()) {
3830 ConstantRange AddRecRange = getSignedRange(AR);
3831 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3832
3833 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3834 Instruction::Add, IncRange, OBO::NoSignedWrap);
3835 if (NSWRegion.contains(AddRecRange))
3836 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3837 }
3838
3839 if (!AR->hasNoUnsignedWrap()) {
3840 ConstantRange AddRecRange = getUnsignedRange(AR);
3841 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3842
3843 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3844 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3845 if (NUWRegion.contains(AddRecRange))
3846 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3847 }
3848
3849 return Result;
3850}
3851
Sanjoy Das118d9192016-03-31 05:14:22 +00003852namespace {
3853/// Represents an abstract binary operation. This may exist as a
3854/// normal instruction or constant expression, or may have been
3855/// derived from an expression tree.
3856struct BinaryOp {
3857 unsigned Opcode;
3858 Value *LHS;
3859 Value *RHS;
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003860 bool IsNSW;
3861 bool IsNUW;
Sanjoy Das118d9192016-03-31 05:14:22 +00003862
3863 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3864 /// constant expression.
3865 Operator *Op;
3866
3867 explicit BinaryOp(Operator *Op)
3868 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003869 IsNSW(false), IsNUW(false), Op(Op) {
3870 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3871 IsNSW = OBO->hasNoSignedWrap();
3872 IsNUW = OBO->hasNoUnsignedWrap();
3873 }
3874 }
Sanjoy Das118d9192016-03-31 05:14:22 +00003875
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003876 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3877 bool IsNUW = false)
3878 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3879 Op(nullptr) {}
Sanjoy Das118d9192016-03-31 05:14:22 +00003880};
3881}
3882
3883
3884/// Try to map \p V into a BinaryOp, and return \c None on failure.
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003885static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
Sanjoy Das118d9192016-03-31 05:14:22 +00003886 auto *Op = dyn_cast<Operator>(V);
3887 if (!Op)
3888 return None;
3889
3890 // Implementation detail: all the cleverness here should happen without
3891 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3892 // SCEV expressions when possible, and we should not break that.
3893
3894 switch (Op->getOpcode()) {
3895 case Instruction::Add:
3896 case Instruction::Sub:
3897 case Instruction::Mul:
3898 case Instruction::UDiv:
3899 case Instruction::And:
3900 case Instruction::Or:
3901 case Instruction::AShr:
3902 case Instruction::Shl:
3903 return BinaryOp(Op);
3904
3905 case Instruction::Xor:
3906 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
3907 // If the RHS of the xor is a signbit, then this is just an add.
3908 // Instcombine turns add of signbit into xor as a strength reduction step.
3909 if (RHSC->getValue().isSignBit())
3910 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
3911 return BinaryOp(Op);
3912
3913 case Instruction::LShr:
3914 // Turn logical shift right of a constant into a unsigned divide.
3915 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
3916 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
3917
3918 // If the shift count is not less than the bitwidth, the result of
3919 // the shift is undefined. Don't try to analyze it, because the
3920 // resolution chosen here may differ from the resolution chosen in
3921 // other parts of the compiler.
3922 if (SA->getValue().ult(BitWidth)) {
3923 Constant *X =
3924 ConstantInt::get(SA->getContext(),
3925 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
3926 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
3927 }
3928 }
3929 return BinaryOp(Op);
3930
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003931 case Instruction::ExtractValue: {
3932 auto *EVI = cast<ExtractValueInst>(Op);
3933 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
3934 break;
3935
3936 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
3937 if (!CI)
3938 break;
3939
3940 if (auto *F = CI->getCalledFunction())
3941 switch (F->getIntrinsicID()) {
3942 case Intrinsic::sadd_with_overflow:
3943 case Intrinsic::uadd_with_overflow: {
3944 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
3945 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3946 CI->getArgOperand(1));
3947
3948 // Now that we know that all uses of the arithmetic-result component of
3949 // CI are guarded by the overflow check, we can go ahead and pretend
3950 // that the arithmetic is non-overflowing.
3951 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
3952 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3953 CI->getArgOperand(1), /* IsNSW = */ true,
3954 /* IsNUW = */ false);
3955 else
3956 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3957 CI->getArgOperand(1), /* IsNSW = */ false,
3958 /* IsNUW*/ true);
3959 }
3960
3961 case Intrinsic::ssub_with_overflow:
3962 case Intrinsic::usub_with_overflow:
3963 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
3964 CI->getArgOperand(1));
3965
3966 case Intrinsic::smul_with_overflow:
3967 case Intrinsic::umul_with_overflow:
3968 return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
3969 CI->getArgOperand(1));
3970 default:
3971 break;
3972 }
3973 }
3974
Sanjoy Das118d9192016-03-31 05:14:22 +00003975 default:
3976 break;
3977 }
3978
3979 return None;
3980}
3981
Sanjoy Das55015d22015-10-02 23:09:44 +00003982const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
3983 const Loop *L = LI.getLoopFor(PN->getParent());
3984 if (!L || L->getHeader() != PN->getParent())
3985 return nullptr;
3986
3987 // The loop may have multiple entrances or multiple exits; we can analyze
3988 // this phi as an addrec if it has a unique entry value and a unique
3989 // backedge value.
3990 Value *BEValueV = nullptr, *StartValueV = nullptr;
3991 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3992 Value *V = PN->getIncomingValue(i);
3993 if (L->contains(PN->getIncomingBlock(i))) {
3994 if (!BEValueV) {
3995 BEValueV = V;
3996 } else if (BEValueV != V) {
3997 BEValueV = nullptr;
3998 break;
3999 }
4000 } else if (!StartValueV) {
4001 StartValueV = V;
4002 } else if (StartValueV != V) {
4003 StartValueV = nullptr;
4004 break;
4005 }
4006 }
4007 if (BEValueV && StartValueV) {
4008 // While we are analyzing this PHI node, handle its value symbolically.
4009 const SCEV *SymbolicName = getUnknown(PN);
4010 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4011 "PHI node already processed?");
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00004012 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
Sanjoy Das55015d22015-10-02 23:09:44 +00004013
4014 // Using this symbolic name for the PHI, analyze the value coming around
4015 // the back-edge.
4016 const SCEV *BEValue = getSCEV(BEValueV);
4017
4018 // NOTE: If BEValue is loop invariant, we know that the PHI node just
4019 // has a special value for the first iteration of the loop.
4020
4021 // If the value coming around the backedge is an add with the symbolic
4022 // value we just inserted, then we found a simple induction variable!
4023 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4024 // If there is a single occurrence of the symbolic value, replace it
4025 // with a recurrence.
4026 unsigned FoundIndex = Add->getNumOperands();
4027 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4028 if (Add->getOperand(i) == SymbolicName)
4029 if (FoundIndex == e) {
4030 FoundIndex = i;
Dan Gohman6635bb22010-04-12 07:49:36 +00004031 break;
4032 }
Sanjoy Das55015d22015-10-02 23:09:44 +00004033
4034 if (FoundIndex != Add->getNumOperands()) {
4035 // Create an add with everything but the specified operand.
4036 SmallVector<const SCEV *, 8> Ops;
4037 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4038 if (i != FoundIndex)
4039 Ops.push_back(Add->getOperand(i));
4040 const SCEV *Accum = getAddExpr(Ops);
4041
4042 // This is not a valid addrec if the step amount is varying each
4043 // loop iteration, but is not itself an addrec in this loop.
4044 if (isLoopInvariant(Accum, L) ||
4045 (isa<SCEVAddRecExpr>(Accum) &&
4046 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4047 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4048
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004049 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004050 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4051 if (BO->IsNUW)
Sanjoy Das55015d22015-10-02 23:09:44 +00004052 Flags = setFlags(Flags, SCEV::FlagNUW);
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004053 if (BO->IsNSW)
Sanjoy Das55015d22015-10-02 23:09:44 +00004054 Flags = setFlags(Flags, SCEV::FlagNSW);
4055 }
4056 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4057 // If the increment is an inbounds GEP, then we know the address
4058 // space cannot be wrapped around. We cannot make any guarantee
4059 // about signed or unsigned overflow because pointers are
4060 // unsigned but we may have a negative index from the base
4061 // pointer. We can guarantee that no unsigned wrap occurs if the
4062 // indices form a positive value.
4063 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4064 Flags = setFlags(Flags, SCEV::FlagNW);
4065
4066 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4067 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4068 Flags = setFlags(Flags, SCEV::FlagNUW);
4069 }
4070
4071 // We cannot transfer nuw and nsw flags from subtraction
4072 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4073 // for instance.
4074 }
4075
4076 const SCEV *StartVal = getSCEV(StartValueV);
4077 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4078
Sanjoy Das55015d22015-10-02 23:09:44 +00004079 // Okay, for the entire analysis of this edge we assumed the PHI
4080 // to be symbolic. We now need to go back and purge all of the
4081 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004082 forgetSymbolicName(PN, SymbolicName);
Sanjoy Das55015d22015-10-02 23:09:44 +00004083 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004084
4085 // We can add Flags to the post-inc expression only if we
4086 // know that it us *undefined behavior* for BEValueV to
4087 // overflow.
4088 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4089 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4090 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4091
Sanjoy Das55015d22015-10-02 23:09:44 +00004092 return PHISCEV;
Dan Gohman6635bb22010-04-12 07:49:36 +00004093 }
4094 }
Silviu Barangaf91c8072015-10-30 15:02:28 +00004095 } else {
Sanjoy Das55015d22015-10-02 23:09:44 +00004096 // Otherwise, this could be a loop like this:
4097 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
4098 // In this case, j = {1,+,1} and BEValue is j.
4099 // Because the other in-value of i (0) fits the evolution of BEValue
4100 // i really is an addrec evolution.
Silviu Barangaf91c8072015-10-30 15:02:28 +00004101 //
4102 // We can generalize this saying that i is the shifted value of BEValue
4103 // by one iteration:
4104 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
4105 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4106 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4107 if (Shifted != getCouldNotCompute() &&
4108 Start != getCouldNotCompute()) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004109 const SCEV *StartVal = getSCEV(StartValueV);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004110 if (Start == StartVal) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004111 // Okay, for the entire analysis of this edge we assumed the PHI
4112 // to be symbolic. We now need to go back and purge all of the
4113 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004114 forgetSymbolicName(PN, SymbolicName);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004115 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4116 return Shifted;
Chris Lattnerd934c702004-04-02 20:23:17 +00004117 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004118 }
Dan Gohman6635bb22010-04-12 07:49:36 +00004119 }
Tobias Grosser934fcf42016-02-21 18:50:09 +00004120
4121 // Remove the temporary PHI node SCEV that has been inserted while intending
4122 // to create an AddRecExpr for this PHI node. We can not keep this temporary
4123 // as it will prevent later (possibly simpler) SCEV expressions to be added
4124 // to the ValueExprMap.
Wei Mi785858c2016-08-09 20:37:50 +00004125 eraseValueFromMap(PN);
Sanjoy Das55015d22015-10-02 23:09:44 +00004126 }
4127
4128 return nullptr;
4129}
4130
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004131// Checks if the SCEV S is available at BB. S is considered available at BB
4132// if S can be materialized at BB without introducing a fault.
4133static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4134 BasicBlock *BB) {
4135 struct CheckAvailable {
4136 bool TraversalDone = false;
4137 bool Available = true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004138
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004139 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
4140 BasicBlock *BB = nullptr;
4141 DominatorTree &DT;
Sanjoy Das55015d22015-10-02 23:09:44 +00004142
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004143 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4144 : L(L), BB(BB), DT(DT) {}
Sanjoy Das55015d22015-10-02 23:09:44 +00004145
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004146 bool setUnavailable() {
4147 TraversalDone = true;
4148 Available = false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004149 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004150 }
4151
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004152 bool follow(const SCEV *S) {
4153 switch (S->getSCEVType()) {
4154 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4155 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
Sanjoy Dasbb5ffc52015-10-24 05:37:28 +00004156 // These expressions are available if their operand(s) is/are.
4157 return true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004158
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004159 case scAddRecExpr: {
4160 // We allow add recurrences that are on the loop BB is in, or some
4161 // outer loop. This guarantees availability because the value of the
4162 // add recurrence at BB is simply the "current" value of the induction
4163 // variable. We can relax this in the future; for instance an add
4164 // recurrence on a sibling dominating loop is also available at BB.
4165 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4166 if (L && (ARLoop == L || ARLoop->contains(L)))
Sanjoy Das55015d22015-10-02 23:09:44 +00004167 return true;
4168
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004169 return setUnavailable();
Sanjoy Das55015d22015-10-02 23:09:44 +00004170 }
4171
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004172 case scUnknown: {
4173 // For SCEVUnknown, we check for simple dominance.
4174 const auto *SU = cast<SCEVUnknown>(S);
4175 Value *V = SU->getValue();
Sanjoy Das55015d22015-10-02 23:09:44 +00004176
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004177 if (isa<Argument>(V))
4178 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004179
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004180 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4181 return false;
4182
4183 return setUnavailable();
4184 }
4185
4186 case scUDivExpr:
4187 case scCouldNotCompute:
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00004188 // We do not try to smart about these at all.
4189 return setUnavailable();
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004190 }
4191 llvm_unreachable("switch should be fully covered!");
4192 }
4193
4194 bool isDone() { return TraversalDone; }
Sanjoy Das55015d22015-10-02 23:09:44 +00004195 };
4196
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004197 CheckAvailable CA(L, BB, DT);
4198 SCEVTraversal<CheckAvailable> ST(CA);
4199
4200 ST.visitAll(S);
4201 return CA.Available;
4202}
4203
4204// Try to match a control flow sequence that branches out at BI and merges back
4205// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
4206// match.
4207static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4208 Value *&C, Value *&LHS, Value *&RHS) {
4209 C = BI->getCondition();
4210
4211 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4212 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4213
4214 if (!LeftEdge.isSingleEdge())
4215 return false;
4216
4217 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4218
4219 Use &LeftUse = Merge->getOperandUse(0);
4220 Use &RightUse = Merge->getOperandUse(1);
4221
4222 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4223 LHS = LeftUse;
4224 RHS = RightUse;
4225 return true;
4226 }
4227
4228 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4229 LHS = RightUse;
4230 RHS = LeftUse;
4231 return true;
4232 }
4233
4234 return false;
4235}
4236
4237const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
Sanjoy Dasb0b4e862016-08-05 18:34:14 +00004238 auto IsReachable =
4239 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4240 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004241 const Loop *L = LI.getLoopFor(PN->getParent());
4242
Sanjoy Das337d4782015-10-31 23:21:40 +00004243 // We don't want to break LCSSA, even in a SCEV expression tree.
4244 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4245 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4246 return nullptr;
4247
Sanjoy Das55015d22015-10-02 23:09:44 +00004248 // Try to match
4249 //
4250 // br %cond, label %left, label %right
4251 // left:
4252 // br label %merge
4253 // right:
4254 // br label %merge
4255 // merge:
4256 // V = phi [ %x, %left ], [ %y, %right ]
4257 //
4258 // as "select %cond, %x, %y"
4259
4260 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4261 assert(IDom && "At least the entry block should dominate PN");
4262
4263 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4264 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4265
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004266 if (BI && BI->isConditional() &&
4267 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4268 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4269 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
Sanjoy Das55015d22015-10-02 23:09:44 +00004270 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4271 }
4272
4273 return nullptr;
4274}
4275
4276const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4277 if (const SCEV *S = createAddRecFromPHI(PN))
4278 return S;
4279
4280 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4281 return S;
Misha Brukman01808ca2005-04-21 21:13:18 +00004282
Dan Gohmana9c205c2010-02-25 06:57:05 +00004283 // If the PHI has a single incoming value, follow that value, unless the
4284 // PHI's incoming blocks are in a different loop, in which case doing so
4285 // risks breaking LCSSA form. Instcombine would normally zap these, but
4286 // it doesn't have DominatorTree information, so it may miss cases.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004287 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004288 if (LI.replacementPreservesLCSSAForm(PN, V))
Dan Gohmana9c205c2010-02-25 06:57:05 +00004289 return getSCEV(V);
Duncan Sands39d771312010-11-17 20:49:12 +00004290
Chris Lattnerd934c702004-04-02 20:23:17 +00004291 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanc8e23622009-04-21 23:15:49 +00004292 return getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00004293}
4294
Sanjoy Das55015d22015-10-02 23:09:44 +00004295const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4296 Value *Cond,
4297 Value *TrueVal,
4298 Value *FalseVal) {
Mehdi Amini044cb342015-10-07 18:14:25 +00004299 // Handle "constant" branch or select. This can occur for instance when a
4300 // loop pass transforms an inner loop and moves on to process the outer loop.
4301 if (auto *CI = dyn_cast<ConstantInt>(Cond))
4302 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4303
Sanjoy Dasd0671342015-10-02 19:39:59 +00004304 // Try to match some simple smax or umax patterns.
4305 auto *ICI = dyn_cast<ICmpInst>(Cond);
4306 if (!ICI)
4307 return getUnknown(I);
4308
4309 Value *LHS = ICI->getOperand(0);
4310 Value *RHS = ICI->getOperand(1);
4311
4312 switch (ICI->getPredicate()) {
4313 case ICmpInst::ICMP_SLT:
4314 case ICmpInst::ICMP_SLE:
4315 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004316 LLVM_FALLTHROUGH;
Sanjoy Dasd0671342015-10-02 19:39:59 +00004317 case ICmpInst::ICMP_SGT:
4318 case ICmpInst::ICMP_SGE:
4319 // a >s b ? a+x : b+x -> smax(a, b)+x
4320 // a >s b ? b+x : a+x -> smin(a, b)+x
4321 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4322 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4323 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4324 const SCEV *LA = getSCEV(TrueVal);
4325 const SCEV *RA = getSCEV(FalseVal);
4326 const SCEV *LDiff = getMinusSCEV(LA, LS);
4327 const SCEV *RDiff = getMinusSCEV(RA, RS);
4328 if (LDiff == RDiff)
4329 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4330 LDiff = getMinusSCEV(LA, RS);
4331 RDiff = getMinusSCEV(RA, LS);
4332 if (LDiff == RDiff)
4333 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4334 }
4335 break;
4336 case ICmpInst::ICMP_ULT:
4337 case ICmpInst::ICMP_ULE:
4338 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004339 LLVM_FALLTHROUGH;
Sanjoy Dasd0671342015-10-02 19:39:59 +00004340 case ICmpInst::ICMP_UGT:
4341 case ICmpInst::ICMP_UGE:
4342 // a >u b ? a+x : b+x -> umax(a, b)+x
4343 // a >u b ? b+x : a+x -> umin(a, b)+x
4344 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4345 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4346 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4347 const SCEV *LA = getSCEV(TrueVal);
4348 const SCEV *RA = getSCEV(FalseVal);
4349 const SCEV *LDiff = getMinusSCEV(LA, LS);
4350 const SCEV *RDiff = getMinusSCEV(RA, RS);
4351 if (LDiff == RDiff)
4352 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4353 LDiff = getMinusSCEV(LA, RS);
4354 RDiff = getMinusSCEV(RA, LS);
4355 if (LDiff == RDiff)
4356 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4357 }
4358 break;
4359 case ICmpInst::ICMP_NE:
4360 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4361 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4362 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4363 const SCEV *One = getOne(I->getType());
4364 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4365 const SCEV *LA = getSCEV(TrueVal);
4366 const SCEV *RA = getSCEV(FalseVal);
4367 const SCEV *LDiff = getMinusSCEV(LA, LS);
4368 const SCEV *RDiff = getMinusSCEV(RA, One);
4369 if (LDiff == RDiff)
4370 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4371 }
4372 break;
4373 case ICmpInst::ICMP_EQ:
4374 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4375 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4376 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4377 const SCEV *One = getOne(I->getType());
4378 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4379 const SCEV *LA = getSCEV(TrueVal);
4380 const SCEV *RA = getSCEV(FalseVal);
4381 const SCEV *LDiff = getMinusSCEV(LA, One);
4382 const SCEV *RDiff = getMinusSCEV(RA, LS);
4383 if (LDiff == RDiff)
4384 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4385 }
4386 break;
4387 default:
4388 break;
4389 }
4390
4391 return getUnknown(I);
4392}
4393
Sanjoy Dasf8570812016-05-29 00:38:22 +00004394/// Expand GEP instructions into add and multiply operations. This allows them
4395/// to be analyzed by regular SCEV code.
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004396const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman30f24fe2009-05-09 00:14:52 +00004397 // Don't attempt to analyze GEPs over unsized objects.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004398 if (!GEP->getSourceElementType()->isSized())
Dan Gohman30f24fe2009-05-09 00:14:52 +00004399 return getUnknown(GEP);
Matt Arsenault4c265902013-09-27 22:38:23 +00004400
Jingyue Wu2982d4d2015-05-18 17:03:25 +00004401 SmallVector<const SCEV *, 4> IndexExprs;
4402 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4403 IndexExprs.push_back(getSCEV(*Index));
Peter Collingbourne8dff0392016-11-13 06:59:50 +00004404 return getGEPExpr(GEP, IndexExprs);
Dan Gohmanee750d12009-05-08 20:26:55 +00004405}
4406
Dan Gohmanc702fc02009-06-19 23:29:04 +00004407uint32_t
Dan Gohmanaf752342009-07-07 17:06:11 +00004408ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmana30370b2009-05-04 22:02:23 +00004409 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004410 return C->getAPInt().countTrailingZeros();
Chris Lattner49b090e2006-12-12 02:26:09 +00004411
Dan Gohmana30370b2009-05-04 22:02:23 +00004412 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanc702fc02009-06-19 23:29:04 +00004413 return std::min(GetMinTrailingZeros(T->getOperand()),
4414 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky3783b462007-11-22 07:59:40 +00004415
Dan Gohmana30370b2009-05-04 22:02:23 +00004416 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004417 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4418 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4419 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004420 }
4421
Dan Gohmana30370b2009-05-04 22:02:23 +00004422 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004423 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4424 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4425 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004426 }
4427
Dan Gohmana30370b2009-05-04 22:02:23 +00004428 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004429 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004430 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004431 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004432 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004433 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004434 }
4435
Dan Gohmana30370b2009-05-04 22:02:23 +00004436 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004437 // The result is the sum of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004438 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4439 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky3783b462007-11-22 07:59:40 +00004440 for (unsigned i = 1, e = M->getNumOperands();
4441 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004442 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky3783b462007-11-22 07:59:40 +00004443 BitWidth);
4444 return SumOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004445 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004446
Dan Gohmana30370b2009-05-04 22:02:23 +00004447 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004448 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004449 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004450 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004451 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004452 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004453 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004454
Dan Gohmana30370b2009-05-04 22:02:23 +00004455 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004456 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004457 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004458 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004459 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004460 return MinOpRes;
4461 }
4462
Dan Gohmana30370b2009-05-04 22:02:23 +00004463 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004464 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004465 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004466 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004467 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004468 return MinOpRes;
4469 }
4470
Dan Gohmanc702fc02009-06-19 23:29:04 +00004471 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4472 // For a SCEVUnknown, ask ValueTracking.
4473 unsigned BitWidth = getTypeSizeInBits(U->getType());
Dan Gohmanc702fc02009-06-19 23:29:04 +00004474 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004475 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004476 nullptr, &DT);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004477 return Zeros.countTrailingOnes();
4478 }
4479
4480 // SCEVUDivExpr
Nick Lewycky3783b462007-11-22 07:59:40 +00004481 return 0;
Chris Lattner49b090e2006-12-12 02:26:09 +00004482}
Chris Lattnerd934c702004-04-02 20:23:17 +00004483
Sanjoy Dasf8570812016-05-29 00:38:22 +00004484/// Helper method to assign a range to V from metadata present in the IR.
Sanjoy Das1f05c512014-10-10 21:22:34 +00004485static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004486 if (Instruction *I = dyn_cast<Instruction>(V))
4487 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4488 return getConstantRangeFromMetadata(*MD);
Sanjoy Das1f05c512014-10-10 21:22:34 +00004489
4490 return None;
4491}
4492
Sanjoy Dasf8570812016-05-29 00:38:22 +00004493/// Determine the range for a particular SCEV. If SignHint is
Sanjoy Das91b54772015-03-09 21:43:43 +00004494/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4495/// with a "cleaner" unsigned (resp. signed) representation.
Dan Gohmane65c9172009-07-13 21:35:55 +00004496ConstantRange
Sanjoy Das91b54772015-03-09 21:43:43 +00004497ScalarEvolution::getRange(const SCEV *S,
4498 ScalarEvolution::RangeSignHint SignHint) {
4499 DenseMap<const SCEV *, ConstantRange> &Cache =
4500 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4501 : SignedRanges;
4502
Dan Gohman761065e2010-11-17 02:44:44 +00004503 // See if we've computed this range already.
Sanjoy Das91b54772015-03-09 21:43:43 +00004504 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4505 if (I != Cache.end())
Dan Gohman761065e2010-11-17 02:44:44 +00004506 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00004507
4508 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004509 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
Dan Gohmanc702fc02009-06-19 23:29:04 +00004510
Dan Gohman85be4332010-01-26 19:19:05 +00004511 unsigned BitWidth = getTypeSizeInBits(S->getType());
4512 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4513
Sanjoy Das91b54772015-03-09 21:43:43 +00004514 // If the value has known zeros, the maximum value will have those known zeros
4515 // as well.
Dan Gohman85be4332010-01-26 19:19:05 +00004516 uint32_t TZ = GetMinTrailingZeros(S);
Sanjoy Das91b54772015-03-09 21:43:43 +00004517 if (TZ != 0) {
4518 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4519 ConservativeResult =
4520 ConstantRange(APInt::getMinValue(BitWidth),
4521 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4522 else
4523 ConservativeResult = ConstantRange(
4524 APInt::getSignedMinValue(BitWidth),
4525 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4526 }
Dan Gohman85be4332010-01-26 19:19:05 +00004527
Dan Gohmane65c9172009-07-13 21:35:55 +00004528 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004529 ConstantRange X = getRange(Add->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004530 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004531 X = X.add(getRange(Add->getOperand(i), SignHint));
4532 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004533 }
4534
4535 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004536 ConstantRange X = getRange(Mul->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004537 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004538 X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4539 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004540 }
4541
4542 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004543 ConstantRange X = getRange(SMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004544 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004545 X = X.smax(getRange(SMax->getOperand(i), SignHint));
4546 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004547 }
4548
4549 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004550 ConstantRange X = getRange(UMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004551 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004552 X = X.umax(getRange(UMax->getOperand(i), SignHint));
4553 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004554 }
4555
4556 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004557 ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4558 ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4559 return setRange(UDiv, SignHint,
4560 ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004561 }
4562
4563 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004564 ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4565 return setRange(ZExt, SignHint,
4566 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004567 }
4568
4569 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004570 ConstantRange X = getRange(SExt->getOperand(), SignHint);
4571 return setRange(SExt, SignHint,
4572 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004573 }
4574
4575 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004576 ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4577 return setRange(Trunc, SignHint,
4578 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004579 }
4580
Dan Gohmane65c9172009-07-13 21:35:55 +00004581 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004582 // If there's no unsigned wrap, the value will never be less than its
4583 // initial value.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004584 if (AddRec->hasNoUnsignedWrap())
Dan Gohman51ad99d2010-01-21 02:09:26 +00004585 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanebbd05f2010-04-12 23:08:18 +00004586 if (!C->getValue()->isZero())
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004587 ConservativeResult = ConservativeResult.intersectWith(
4588 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004589
Dan Gohman51ad99d2010-01-21 02:09:26 +00004590 // If there's no signed wrap, and all the operands have the same sign or
4591 // zero, the value won't ever change sign.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004592 if (AddRec->hasNoSignedWrap()) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004593 bool AllNonNeg = true;
4594 bool AllNonPos = true;
4595 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4596 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4597 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4598 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004599 if (AllNonNeg)
Dan Gohman51aaf022010-01-26 04:40:18 +00004600 ConservativeResult = ConservativeResult.intersectWith(
4601 ConstantRange(APInt(BitWidth, 0),
4602 APInt::getSignedMinValue(BitWidth)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004603 else if (AllNonPos)
Dan Gohman51aaf022010-01-26 04:40:18 +00004604 ConservativeResult = ConservativeResult.intersectWith(
4605 ConstantRange(APInt::getSignedMinValue(BitWidth),
4606 APInt(BitWidth, 1)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004607 }
Dan Gohmane65c9172009-07-13 21:35:55 +00004608
4609 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00004610 if (AddRec->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00004611 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00004612 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4613 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Sanjoy Dasb765b632016-03-02 00:57:39 +00004614 auto RangeFromAffine = getRangeForAffineAR(
4615 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4616 BitWidth);
4617 if (!RangeFromAffine.isFullSet())
4618 ConservativeResult =
4619 ConservativeResult.intersectWith(RangeFromAffine);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004620
4621 auto RangeFromFactoring = getRangeViaFactoring(
4622 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4623 BitWidth);
4624 if (!RangeFromFactoring.isFullSet())
4625 ConservativeResult =
4626 ConservativeResult.intersectWith(RangeFromFactoring);
Dan Gohmand261d272009-06-24 01:05:09 +00004627 }
Dan Gohmand261d272009-06-24 01:05:09 +00004628 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004629
Sanjoy Das91b54772015-03-09 21:43:43 +00004630 return setRange(AddRec, SignHint, ConservativeResult);
Dan Gohmand261d272009-06-24 01:05:09 +00004631 }
4632
Dan Gohmanc702fc02009-06-19 23:29:04 +00004633 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00004634 // Check if the IR explicitly contains !range metadata.
4635 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4636 if (MDRange.hasValue())
4637 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4638
Sanjoy Das91b54772015-03-09 21:43:43 +00004639 // Split here to avoid paying the compile-time cost of calling both
4640 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
4641 // if needed.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004642 const DataLayout &DL = getDataLayout();
Sanjoy Das91b54772015-03-09 21:43:43 +00004643 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4644 // For a SCEVUnknown, ask ValueTracking.
4645 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004646 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
Sanjoy Das91b54772015-03-09 21:43:43 +00004647 if (Ones != ~Zeros + 1)
4648 ConservativeResult =
4649 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4650 } else {
4651 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4652 "generalize as needed!");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004653 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004654 if (NS > 1)
4655 ConservativeResult = ConservativeResult.intersectWith(
4656 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4657 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
Sanjoy Das91b54772015-03-09 21:43:43 +00004658 }
4659
4660 return setRange(U, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004661 }
4662
Sanjoy Das91b54772015-03-09 21:43:43 +00004663 return setRange(S, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004664}
4665
Sanjoy Dasb765b632016-03-02 00:57:39 +00004666ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4667 const SCEV *Step,
4668 const SCEV *MaxBECount,
4669 unsigned BitWidth) {
4670 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4671 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4672 "Precondition!");
4673
4674 ConstantRange Result(BitWidth, /* isFullSet = */ true);
4675
4676 // Check for overflow. This must be done with ConstantRange arithmetic
4677 // because we could be called from within the ScalarEvolution overflow
4678 // checking code.
4679
4680 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4681 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4682 ConstantRange ZExtMaxBECountRange =
4683 MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1);
4684
4685 ConstantRange StepSRange = getSignedRange(Step);
4686 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1);
4687
4688 ConstantRange StartURange = getUnsignedRange(Start);
4689 ConstantRange EndURange =
4690 StartURange.add(MaxBECountRange.multiply(StepSRange));
4691
4692 // Check for unsigned overflow.
4693 ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1);
4694 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1);
4695 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4696 ZExtEndURange) {
4697 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(),
4698 EndURange.getUnsignedMin());
4699 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(),
4700 EndURange.getUnsignedMax());
4701 bool IsFullRange = Min.isMinValue() && Max.isMaxValue();
4702 if (!IsFullRange)
4703 Result =
4704 Result.intersectWith(ConstantRange(Min, Max + 1));
4705 }
4706
4707 ConstantRange StartSRange = getSignedRange(Start);
4708 ConstantRange EndSRange =
4709 StartSRange.add(MaxBECountRange.multiply(StepSRange));
4710
4711 // Check for signed overflow. This must be done with ConstantRange
4712 // arithmetic because we could be called from within the ScalarEvolution
4713 // overflow checking code.
4714 ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1);
4715 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1);
4716 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4717 SExtEndSRange) {
4718 APInt Min =
4719 APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin());
4720 APInt Max =
4721 APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax());
4722 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue();
4723 if (!IsFullRange)
4724 Result =
4725 Result.intersectWith(ConstantRange(Min, Max + 1));
4726 }
4727
4728 return Result;
4729}
4730
Sanjoy Dasbf730982016-03-02 00:57:54 +00004731ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4732 const SCEV *Step,
4733 const SCEV *MaxBECount,
4734 unsigned BitWidth) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004735 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4736 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4737
4738 struct SelectPattern {
4739 Value *Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004740 APInt TrueValue;
4741 APInt FalseValue;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004742
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004743 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4744 const SCEV *S) {
4745 Optional<unsigned> CastOp;
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004746 APInt Offset(BitWidth, 0);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004747
4748 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4749 "Should be!");
4750
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004751 // Peel off a constant offset:
4752 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4753 // In the future we could consider being smarter here and handle
4754 // {Start+Step,+,Step} too.
4755 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4756 return;
4757
4758 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4759 S = SA->getOperand(1);
4760 }
4761
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004762 // Peel off a cast operation
4763 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4764 CastOp = SCast->getSCEVType();
4765 S = SCast->getOperand();
4766 }
4767
Sanjoy Dasbf730982016-03-02 00:57:54 +00004768 using namespace llvm::PatternMatch;
4769
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004770 auto *SU = dyn_cast<SCEVUnknown>(S);
4771 const APInt *TrueVal, *FalseVal;
4772 if (!SU ||
4773 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4774 m_APInt(FalseVal)))) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004775 Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004776 return;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004777 }
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004778
4779 TrueValue = *TrueVal;
4780 FalseValue = *FalseVal;
4781
4782 // Re-apply the cast we peeled off earlier
4783 if (CastOp.hasValue())
4784 switch (*CastOp) {
4785 default:
4786 llvm_unreachable("Unknown SCEV cast type!");
4787
4788 case scTruncate:
4789 TrueValue = TrueValue.trunc(BitWidth);
4790 FalseValue = FalseValue.trunc(BitWidth);
4791 break;
4792 case scZeroExtend:
4793 TrueValue = TrueValue.zext(BitWidth);
4794 FalseValue = FalseValue.zext(BitWidth);
4795 break;
4796 case scSignExtend:
4797 TrueValue = TrueValue.sext(BitWidth);
4798 FalseValue = FalseValue.sext(BitWidth);
4799 break;
4800 }
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004801
4802 // Re-apply the constant offset we peeled off earlier
4803 TrueValue += Offset;
4804 FalseValue += Offset;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004805 }
4806
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004807 bool isRecognized() { return Condition != nullptr; }
Sanjoy Dasbf730982016-03-02 00:57:54 +00004808 };
4809
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004810 SelectPattern StartPattern(*this, BitWidth, Start);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004811 if (!StartPattern.isRecognized())
4812 return ConstantRange(BitWidth, /* isFullSet = */ true);
4813
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004814 SelectPattern StepPattern(*this, BitWidth, Step);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004815 if (!StepPattern.isRecognized())
4816 return ConstantRange(BitWidth, /* isFullSet = */ true);
4817
4818 if (StartPattern.Condition != StepPattern.Condition) {
4819 // We don't handle this case today; but we could, by considering four
4820 // possibilities below instead of two. I'm not sure if there are cases where
4821 // that will help over what getRange already does, though.
4822 return ConstantRange(BitWidth, /* isFullSet = */ true);
4823 }
4824
4825 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4826 // construct arbitrary general SCEV expressions here. This function is called
4827 // from deep in the call stack, and calling getSCEV (on a sext instruction,
4828 // say) can end up caching a suboptimal value.
4829
Sanjoy Das6b017a12016-03-02 02:56:29 +00004830 // FIXME: without the explicit `this` receiver below, MSVC errors out with
4831 // C2352 and C2512 (otherwise it isn't needed).
4832
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004833 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004834 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004835 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004836 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
Sanjoy Das62a1c332016-03-02 02:15:42 +00004837
Sanjoy Das1168f932016-03-02 02:34:20 +00004838 ConstantRange TrueRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004839 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
Sanjoy Das1168f932016-03-02 02:34:20 +00004840 ConstantRange FalseRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004841 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004842
4843 return TrueRange.unionWith(FalseRange);
4844}
4845
Jingyue Wu42f1d672015-07-28 18:22:40 +00004846SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004847 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004848 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4849
4850 // Return early if there are no flags to propagate to the SCEV.
4851 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4852 if (BinOp->hasNoUnsignedWrap())
4853 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4854 if (BinOp->hasNoSignedWrap())
4855 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004856 if (Flags == SCEV::FlagAnyWrap)
Jingyue Wu42f1d672015-07-28 18:22:40 +00004857 return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004858
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004859 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
4860}
4861
4862bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
4863 // Here we check that I is in the header of the innermost loop containing I,
4864 // since we only deal with instructions in the loop header. The actual loop we
4865 // need to check later will come from an add recurrence, but getting that
4866 // requires computing the SCEV of the operands, which can be expensive. This
4867 // check we can do cheaply to rule out some cases early.
4868 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004869 if (InnermostContainingLoop == nullptr ||
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004870 InnermostContainingLoop->getHeader() != I->getParent())
4871 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004872
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004873 // Only proceed if we can prove that I does not yield poison.
4874 if (!isKnownNotFullPoison(I)) return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004875
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004876 // At this point we know that if I is executed, then it does not wrap
4877 // according to at least one of NSW or NUW. If I is not executed, then we do
4878 // not know if the calculation that I represents would wrap. Multiple
4879 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
Jingyue Wu42f1d672015-07-28 18:22:40 +00004880 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4881 // derived from other instructions that map to the same SCEV. We cannot make
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004882 // that guarantee for cases where I is not executed. So we need to find the
4883 // loop that I is considered in relation to and prove that I is executed for
4884 // every iteration of that loop. That implies that the value that I
Jingyue Wu42f1d672015-07-28 18:22:40 +00004885 // calculates does not wrap anywhere in the loop, so then we can apply the
4886 // flags to the SCEV.
4887 //
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004888 // We check isLoopInvariant to disambiguate in case we are adding recurrences
4889 // from different loops, so that we know which loop to prove that I is
4890 // executed in.
4891 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
Hans Wennborg38790352016-08-17 22:50:18 +00004892 // I could be an extractvalue from a call to an overflow intrinsic.
4893 // TODO: We can do better here in some cases.
4894 if (!isSCEVable(I->getOperand(OpIndex)->getType()))
4895 return false;
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004896 const SCEV *Op = getSCEV(I->getOperand(OpIndex));
Jingyue Wu42f1d672015-07-28 18:22:40 +00004897 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004898 bool AllOtherOpsLoopInvariant = true;
4899 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
4900 ++OtherOpIndex) {
4901 if (OtherOpIndex != OpIndex) {
4902 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
4903 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
4904 AllOtherOpsLoopInvariant = false;
4905 break;
4906 }
4907 }
4908 }
4909 if (AllOtherOpsLoopInvariant &&
4910 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
4911 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004912 }
4913 }
Sanjoy Dasefdeb452016-04-22 05:38:54 +00004914 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004915}
4916
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004917bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
4918 // If we know that \c I can never be poison period, then that's enough.
4919 if (isSCEVExprNeverPoison(I))
4920 return true;
4921
4922 // For an add recurrence specifically, we assume that infinite loops without
4923 // side effects are undefined behavior, and then reason as follows:
4924 //
4925 // If the add recurrence is poison in any iteration, it is poison on all
4926 // future iterations (since incrementing poison yields poison). If the result
4927 // of the add recurrence is fed into the loop latch condition and the loop
4928 // does not contain any throws or exiting blocks other than the latch, we now
4929 // have the ability to "choose" whether the backedge is taken or not (by
4930 // choosing a sufficiently evil value for the poison feeding into the branch)
4931 // for every iteration including and after the one in which \p I first became
4932 // poison. There are two possibilities (let's call the iteration in which \p
4933 // I first became poison as K):
4934 //
4935 // 1. In the set of iterations including and after K, the loop body executes
4936 // no side effects. In this case executing the backege an infinte number
4937 // of times will yield undefined behavior.
4938 //
4939 // 2. In the set of iterations including and after K, the loop body executes
4940 // at least one side effect. In this case, that specific instance of side
4941 // effect is control dependent on poison, which also yields undefined
4942 // behavior.
4943
4944 auto *ExitingBB = L->getExitingBlock();
4945 auto *LatchBB = L->getLoopLatch();
4946 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
4947 return false;
4948
4949 SmallPtrSet<const Instruction *, 16> Pushed;
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004950 SmallVector<const Instruction *, 8> PoisonStack;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004951
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004952 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
4953 // things that are known to be fully poison under that assumption go on the
4954 // PoisonStack.
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004955 Pushed.insert(I);
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004956 PoisonStack.push_back(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004957
4958 bool LatchControlDependentOnPoison = false;
Sanjoy Das2401c982016-06-08 17:48:46 +00004959 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004960 const Instruction *Poison = PoisonStack.pop_back_val();
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004961
Sanjoy Dasa19edc42016-06-08 17:48:31 +00004962 for (auto *PoisonUser : Poison->users()) {
4963 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
4964 if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
4965 PoisonStack.push_back(cast<Instruction>(PoisonUser));
4966 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004967 assert(BI->isConditional() && "Only possibility!");
4968 if (BI->getParent() == LatchBB) {
4969 LatchControlDependentOnPoison = true;
4970 break;
4971 }
4972 }
4973 }
4974 }
4975
Sanjoy Das97cd7d52016-06-09 01:13:54 +00004976 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
4977}
Sanjoy Das7e4a6412016-05-29 00:32:17 +00004978
Sanjoy Das5603fc02016-09-26 02:44:07 +00004979ScalarEvolution::LoopProperties
4980ScalarEvolution::getLoopProperties(const Loop *L) {
4981 typedef ScalarEvolution::LoopProperties LoopProperties;
David L Kreitzer8bbabee2016-09-16 14:38:13 +00004982
Sanjoy Das5603fc02016-09-26 02:44:07 +00004983 auto Itr = LoopPropertiesCache.find(L);
4984 if (Itr == LoopPropertiesCache.end()) {
4985 auto HasSideEffects = [](Instruction *I) {
4986 if (auto *SI = dyn_cast<StoreInst>(I))
4987 return !SI->isSimple();
4988
4989 return I->mayHaveSideEffects();
David L Kreitzer8bbabee2016-09-16 14:38:13 +00004990 };
4991
Sanjoy Das5603fc02016-09-26 02:44:07 +00004992 LoopProperties LP = {/* HasNoAbnormalExits */ true,
4993 /*HasNoSideEffects*/ true};
David L Kreitzer8bbabee2016-09-16 14:38:13 +00004994
Sanjoy Das5603fc02016-09-26 02:44:07 +00004995 for (auto *BB : L->getBlocks())
4996 for (auto &I : *BB) {
4997 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
4998 LP.HasNoAbnormalExits = false;
4999 if (HasSideEffects(&I))
5000 LP.HasNoSideEffects = false;
5001 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5002 break; // We're already as pessimistic as we can get.
5003 }
David L Kreitzer8bbabee2016-09-16 14:38:13 +00005004
Sanjoy Das5603fc02016-09-26 02:44:07 +00005005 auto InsertPair = LoopPropertiesCache.insert({L, LP});
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005006 assert(InsertPair.second && "We just checked!");
5007 Itr = InsertPair.first;
5008 }
5009
Sanjoy Das97cd7d52016-06-09 01:13:54 +00005010 return Itr->second;
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005011}
5012
Dan Gohmanaf752342009-07-07 17:06:11 +00005013const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00005014 if (!isSCEVable(V->getType()))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005015 return getUnknown(V);
Dan Gohman0a40ad92009-04-16 03:18:22 +00005016
Dan Gohman69451a02010-03-09 23:46:50 +00005017 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman69451a02010-03-09 23:46:50 +00005018 // Don't attempt to analyze instructions in blocks that aren't
5019 // reachable. Such instructions don't matter, and they aren't required
5020 // to obey basic rules for definitions dominating uses which this
5021 // analysis depends on.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005022 if (!DT.isReachableFromEntry(I->getParent()))
Dan Gohman69451a02010-03-09 23:46:50 +00005023 return getUnknown(V);
Sanjoy Das260ad4d2016-03-29 16:40:39 +00005024 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohmanf436bac2009-06-24 00:54:57 +00005025 return getConstant(CI);
5026 else if (isa<ConstantPointerNull>(V))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005027 return getZero(V->getType());
Dan Gohmanf161e06e2009-08-25 17:49:57 +00005028 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Sanjoy Das5ce32722016-04-08 00:48:30 +00005029 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
Sanjoy Das260ad4d2016-03-29 16:40:39 +00005030 else if (!isa<ConstantExpr>(V))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005031 return getUnknown(V);
Chris Lattnera3e0bb42007-04-02 05:41:38 +00005032
Dan Gohman80ca01c2009-07-17 20:47:02 +00005033 Operator *U = cast<Operator>(V);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005034 if (auto BO = MatchBinaryOp(U, DT)) {
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005035 switch (BO->Opcode) {
5036 case Instruction::Add: {
5037 // The simple thing to do would be to just call getSCEV on both operands
5038 // and call getAddExpr with the result. However if we're looking at a
5039 // bunch of things all added together, this can be quite inefficient,
5040 // because it leads to N-1 getAddExpr calls for N ultimate operands.
5041 // Instead, gather up all the operands and make a single getAddExpr call.
5042 // LLVM IR canonical form means we need only traverse the left operands.
5043 SmallVector<const SCEV *, 4> AddOps;
5044 do {
5045 if (BO->Op) {
5046 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5047 AddOps.push_back(OpSCEV);
5048 break;
5049 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00005050
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005051 // If a NUW or NSW flag can be applied to the SCEV for this
5052 // addition, then compute the SCEV for this addition by itself
5053 // with a separate call to getAddExpr. We need to do that
5054 // instead of pushing the operands of the addition onto AddOps,
5055 // since the flags are only known to apply to this particular
5056 // addition - they may not apply to other additions that can be
5057 // formed with operands from AddOps.
5058 const SCEV *RHS = getSCEV(BO->RHS);
5059 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5060 if (Flags != SCEV::FlagAnyWrap) {
5061 const SCEV *LHS = getSCEV(BO->LHS);
5062 if (BO->Opcode == Instruction::Sub)
5063 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5064 else
5065 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5066 break;
5067 }
Dan Gohman36bad002009-09-17 18:05:20 +00005068 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005069
5070 if (BO->Opcode == Instruction::Sub)
5071 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5072 else
5073 AddOps.push_back(getSCEV(BO->RHS));
5074
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005075 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005076 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5077 NewBO->Opcode != Instruction::Sub)) {
5078 AddOps.push_back(getSCEV(BO->LHS));
5079 break;
5080 }
5081 BO = NewBO;
5082 } while (true);
5083
5084 return getAddExpr(AddOps);
5085 }
5086
5087 case Instruction::Mul: {
5088 SmallVector<const SCEV *, 4> MulOps;
5089 do {
5090 if (BO->Op) {
5091 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5092 MulOps.push_back(OpSCEV);
5093 break;
5094 }
5095
5096 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5097 if (Flags != SCEV::FlagAnyWrap) {
5098 MulOps.push_back(
5099 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5100 break;
5101 }
5102 }
5103
5104 MulOps.push_back(getSCEV(BO->RHS));
Sanjoy Dasf49ca522016-05-29 00:34:42 +00005105 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005106 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5107 MulOps.push_back(getSCEV(BO->LHS));
5108 break;
5109 }
NAKAMURA Takumi940cd932016-07-04 01:26:21 +00005110 BO = NewBO;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005111 } while (true);
5112
5113 return getMulExpr(MulOps);
5114 }
5115 case Instruction::UDiv:
5116 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5117 case Instruction::Sub: {
5118 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5119 if (BO->Op)
5120 Flags = getNoWrapFlagsFromUB(BO->Op);
5121 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5122 }
5123 case Instruction::And:
5124 // For an expression like x&255 that merely masks off the high bits,
5125 // use zext(trunc(x)) as the SCEV expression.
5126 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5127 if (CI->isNullValue())
5128 return getSCEV(BO->RHS);
5129 if (CI->isAllOnesValue())
5130 return getSCEV(BO->LHS);
5131 const APInt &A = CI->getValue();
5132
5133 // Instcombine's ShrinkDemandedConstant may strip bits out of
5134 // constants, obscuring what would otherwise be a low-bits mask.
5135 // Use computeKnownBits to compute what ShrinkDemandedConstant
5136 // knew about to reconstruct a low-bits mask value.
5137 unsigned LZ = A.countLeadingZeros();
5138 unsigned TZ = A.countTrailingZeros();
5139 unsigned BitWidth = A.getBitWidth();
5140 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5141 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005142 0, &AC, nullptr, &DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005143
5144 APInt EffectiveMask =
5145 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5146 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
5147 const SCEV *MulCount = getConstant(ConstantInt::get(
5148 getContext(), APInt::getOneBitSet(BitWidth, TZ)));
5149 return getMulExpr(
5150 getZeroExtendExpr(
5151 getTruncateExpr(
5152 getUDivExactExpr(getSCEV(BO->LHS), MulCount),
5153 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5154 BO->LHS->getType()),
5155 MulCount);
5156 }
Dan Gohman36bad002009-09-17 18:05:20 +00005157 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005158 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005159
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005160 case Instruction::Or:
5161 // If the RHS of the Or is a constant, we may have something like:
5162 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
5163 // optimizations will transparently handle this case.
5164 //
5165 // In order for this transformation to be safe, the LHS must be of the
5166 // form X*(2^n) and the Or constant must be less than 2^n.
5167 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5168 const SCEV *LHS = getSCEV(BO->LHS);
5169 const APInt &CIVal = CI->getValue();
5170 if (GetMinTrailingZeros(LHS) >=
5171 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5172 // Build a plain add SCEV.
5173 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5174 // If the LHS of the add was an addrec and it has no-wrap flags,
5175 // transfer the no-wrap flags, since an or won't introduce a wrap.
5176 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5177 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5178 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5179 OldAR->getNoWrapFlags());
5180 }
5181 return S;
5182 }
5183 }
5184 break;
Dan Gohman6350296e2009-05-18 16:29:04 +00005185
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005186 case Instruction::Xor:
5187 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5188 // If the RHS of xor is -1, then this is a not operation.
5189 if (CI->isAllOnesValue())
5190 return getNotSCEV(getSCEV(BO->LHS));
Dan Gohmaneddf7712009-06-18 00:00:20 +00005191
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005192 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5193 // This is a variant of the check for xor with -1, and it handles
5194 // the case where instcombine has trimmed non-demanded bits out
5195 // of an xor with -1.
5196 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5197 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5198 if (LBO->getOpcode() == Instruction::And &&
5199 LCI->getValue() == CI->getValue())
5200 if (const SCEVZeroExtendExpr *Z =
5201 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5202 Type *UTy = BO->LHS->getType();
5203 const SCEV *Z0 = Z->getOperand();
5204 Type *Z0Ty = Z0->getType();
5205 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
Dan Gohmaneddf7712009-06-18 00:00:20 +00005206
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005207 // If C is a low-bits mask, the zero extend is serving to
5208 // mask off the high bits. Complement the operand and
5209 // re-apply the zext.
5210 if (APIntOps::isMask(Z0TySize, CI->getValue()))
5211 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5212
5213 // If C is a single bit, it may be in the sign-bit position
5214 // before the zero-extend. In this case, represent the xor
5215 // using an add, which is equivalent, and re-apply the zext.
5216 APInt Trunc = CI->getValue().trunc(Z0TySize);
5217 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5218 Trunc.isSignBit())
5219 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5220 UTy);
5221 }
5222 }
5223 break;
Dan Gohman05e89732008-06-22 19:56:46 +00005224
5225 case Instruction::Shl:
5226 // Turn shift left of a constant amount into a multiply.
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005227 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5228 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00005229
5230 // If the shift count is not less than the bitwidth, the result of
5231 // the shift is undefined. Don't try to analyze it, because the
5232 // resolution chosen here may differ from the resolution chosen in
5233 // other parts of the compiler.
5234 if (SA->getValue().uge(BitWidth))
5235 break;
5236
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005237 // It is currently not resolved how to interpret NSW for left
5238 // shift by BitWidth - 1, so we avoid applying flags in that
5239 // case. Remove this check (or this comment) once the situation
5240 // is resolved. See
5241 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5242 // and http://reviews.llvm.org/D8890 .
5243 auto Flags = SCEV::FlagAnyWrap;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005244 if (BO->Op && SA->getValue().ult(BitWidth - 1))
5245 Flags = getNoWrapFlagsFromUB(BO->Op);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005246
Owen Andersonedb4a702009-07-24 23:12:02 +00005247 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00005248 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005249 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
Dan Gohman05e89732008-06-22 19:56:46 +00005250 }
5251 break;
5252
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005253 case Instruction::AShr:
5254 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
5255 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS))
5256 if (Operator *L = dyn_cast<Operator>(BO->LHS))
5257 if (L->getOpcode() == Instruction::Shl &&
5258 L->getOperand(1) == BO->RHS) {
5259 uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType());
Dan Gohmanacd700a2010-04-22 01:35:11 +00005260
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005261 // If the shift count is not less than the bitwidth, the result of
5262 // the shift is undefined. Don't try to analyze it, because the
5263 // resolution chosen here may differ from the resolution chosen in
5264 // other parts of the compiler.
5265 if (CI->getValue().uge(BitWidth))
5266 break;
Dan Gohmanacd700a2010-04-22 01:35:11 +00005267
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005268 uint64_t Amt = BitWidth - CI->getZExtValue();
5269 if (Amt == BitWidth)
5270 return getSCEV(L->getOperand(0)); // shift by zero --> noop
5271 return getSignExtendExpr(
5272 getTruncateExpr(getSCEV(L->getOperand(0)),
5273 IntegerType::get(getContext(), Amt)),
5274 BO->LHS->getType());
5275 }
5276 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005277 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005278 }
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005279
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005280 switch (U->getOpcode()) {
Dan Gohman05e89732008-06-22 19:56:46 +00005281 case Instruction::Trunc:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005282 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005283
5284 case Instruction::ZExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005285 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005286
5287 case Instruction::SExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005288 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005289
5290 case Instruction::BitCast:
5291 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00005292 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman05e89732008-06-22 19:56:46 +00005293 return getSCEV(U->getOperand(0));
5294 break;
5295
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00005296 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5297 // lead to pointer expressions which cannot safely be expanded to GEPs,
5298 // because ScalarEvolution doesn't respect the GEP aliasing rules when
5299 // simplifying integer expressions.
Dan Gohman0a40ad92009-04-16 03:18:22 +00005300
Dan Gohmanee750d12009-05-08 20:26:55 +00005301 case Instruction::GetElementPtr:
Dan Gohmanb256ccf2009-12-18 02:09:29 +00005302 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman0a40ad92009-04-16 03:18:22 +00005303
Dan Gohman05e89732008-06-22 19:56:46 +00005304 case Instruction::PHI:
5305 return createNodeForPHI(cast<PHINode>(U));
5306
5307 case Instruction::Select:
Sanjoy Dasd0671342015-10-02 19:39:59 +00005308 // U can also be a select constant expr, which let fall through. Since
5309 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5310 // constant expressions cannot have instructions as operands, we'd have
5311 // returned getUnknown for a select constant expressions anyway.
5312 if (isa<Instruction>(U))
Sanjoy Das55015d22015-10-02 23:09:44 +00005313 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5314 U->getOperand(1), U->getOperand(2));
Hal Finkele186deb2016-07-11 02:48:23 +00005315 break;
5316
5317 case Instruction::Call:
5318 case Instruction::Invoke:
5319 if (Value *RV = CallSite(U).getReturnedArgOperand())
5320 return getSCEV(RV);
5321 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00005322 }
5323
Dan Gohmanc8e23622009-04-21 23:15:49 +00005324 return getUnknown(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00005325}
5326
5327
5328
5329//===----------------------------------------------------------------------===//
5330// Iteration Count Computation Code
5331//
5332
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005333static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
5334 if (!ExitCount)
5335 return 0;
5336
5337 ConstantInt *ExitConst = ExitCount->getValue();
5338
5339 // Guard against huge trip counts.
5340 if (ExitConst->getValue().getActiveBits() > 32)
5341 return 0;
5342
5343 // In case of integer overflow, this returns 0, which is correct.
5344 return ((unsigned)ExitConst->getZExtValue()) + 1;
5345}
5346
Chandler Carruth6666c272014-10-11 00:12:11 +00005347unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
5348 if (BasicBlock *ExitingBB = L->getExitingBlock())
5349 return getSmallConstantTripCount(L, ExitingBB);
5350
5351 // No trip count information for multiple exits.
5352 return 0;
5353}
5354
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005355unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
5356 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005357 assert(ExitingBlock && "Must pass a non-null exiting block!");
5358 assert(L->isLoopExiting(ExitingBlock) &&
5359 "Exiting block must actually branch out of the loop!");
Andrew Trick2b6860f2011-08-11 23:36:16 +00005360 const SCEVConstant *ExitCount =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005361 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005362 return getConstantTripCount(ExitCount);
5363}
Andrew Trick2b6860f2011-08-11 23:36:16 +00005364
Haicheng Wu1ef17e92016-10-12 21:29:38 +00005365unsigned ScalarEvolution::getSmallConstantMaxTripCount(Loop *L) {
5366 const auto *MaxExitCount =
5367 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
5368 return getConstantTripCount(MaxExitCount);
Andrew Trick2b6860f2011-08-11 23:36:16 +00005369}
5370
Chandler Carruth6666c272014-10-11 00:12:11 +00005371unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
5372 if (BasicBlock *ExitingBB = L->getExitingBlock())
5373 return getSmallConstantTripMultiple(L, ExitingBB);
5374
5375 // No trip multiple information for multiple exits.
5376 return 0;
5377}
5378
Sanjoy Dasf8570812016-05-29 00:38:22 +00005379/// Returns the largest constant divisor of the trip count of this loop as a
5380/// normal unsigned value, if possible. This means that the actual trip count is
5381/// always a multiple of the returned value (don't forget the trip count could
5382/// very well be zero as well!).
Andrew Trick2b6860f2011-08-11 23:36:16 +00005383///
5384/// Returns 1 if the trip count is unknown or not guaranteed to be the
5385/// multiple of a constant (which is also the case if the trip count is simply
5386/// constant, use getSmallConstantTripCount for that case), Will also return 1
5387/// if the trip count is very large (>= 2^32).
Andrew Tricke81211f2012-01-11 06:52:55 +00005388///
5389/// As explained in the comments for getSmallConstantTripCount, this assumes
5390/// that control exits the loop via ExitingBlock.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005391unsigned
5392ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
5393 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005394 assert(ExitingBlock && "Must pass a non-null exiting block!");
5395 assert(L->isLoopExiting(ExitingBlock) &&
5396 "Exiting block must actually branch out of the loop!");
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005397 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +00005398 if (ExitCount == getCouldNotCompute())
5399 return 1;
5400
5401 // Get the trip count from the BE count by adding 1.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005402 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType()));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005403 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
5404 // to factor simple cases.
5405 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
5406 TCMul = Mul->getOperand(0);
5407
5408 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
5409 if (!MulC)
5410 return 1;
5411
5412 ConstantInt *Result = MulC->getValue();
5413
Hal Finkel30bd9342012-10-24 19:46:44 +00005414 // Guard against huge trip counts (this requires checking
5415 // for zero to handle the case where the trip count == -1 and the
5416 // addition wraps).
5417 if (!Result || Result->getValue().getActiveBits() > 32 ||
5418 Result->getValue().getActiveBits() == 0)
Andrew Trick2b6860f2011-08-11 23:36:16 +00005419 return 1;
5420
5421 return (unsigned)Result->getZExtValue();
5422}
5423
Sanjoy Dasf8570812016-05-29 00:38:22 +00005424/// Get the expression for the number of loop iterations for which this loop is
5425/// guaranteed not to exit via ExitingBlock. Otherwise return
5426/// SCEVCouldNotCompute.
Andrew Trick77c55422011-08-02 04:23:35 +00005427const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
5428 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005429}
5430
Silviu Baranga6f444df2016-04-08 14:29:09 +00005431const SCEV *
5432ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5433 SCEVUnionPredicate &Preds) {
5434 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5435}
5436
Dan Gohmanaf752342009-07-07 17:06:11 +00005437const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005438 return getBackedgeTakenInfo(L).getExact(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005439}
5440
Sanjoy Dasf8570812016-05-29 00:38:22 +00005441/// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5442/// known never to be less than the actual backedge taken count.
Dan Gohmanaf752342009-07-07 17:06:11 +00005443const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005444 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005445}
5446
John Brawn84b21832016-10-21 11:08:48 +00005447bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
5448 return getBackedgeTakenInfo(L).isMaxOrZero(this);
5449}
5450
Sanjoy Dasf8570812016-05-29 00:38:22 +00005451/// Push PHI nodes in the header of the given loop onto the given Worklist.
Dan Gohmandc191042009-07-08 19:23:34 +00005452static void
5453PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5454 BasicBlock *Header = L->getHeader();
5455
5456 // Push all Loop-header PHIs onto the Worklist stack.
5457 for (BasicBlock::iterator I = Header->begin();
5458 PHINode *PN = dyn_cast<PHINode>(I); ++I)
5459 Worklist.push_back(PN);
5460}
5461
Dan Gohman2b8da352009-04-30 20:47:05 +00005462const ScalarEvolution::BackedgeTakenInfo &
Silviu Baranga6f444df2016-04-08 14:29:09 +00005463ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5464 auto &BTI = getBackedgeTakenInfo(L);
5465 if (BTI.hasFullInfo())
5466 return BTI;
5467
5468 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5469
5470 if (!Pair.second)
5471 return Pair.first->second;
5472
5473 BackedgeTakenInfo Result =
5474 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5475
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005476 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
Silviu Baranga6f444df2016-04-08 14:29:09 +00005477}
5478
5479const ScalarEvolution::BackedgeTakenInfo &
Dan Gohman2b8da352009-04-30 20:47:05 +00005480ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005481 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman8b0a4192010-03-01 17:49:51 +00005482 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman76466372009-04-27 20:16:15 +00005483 // update the value. The temporary CouldNotCompute value tells SCEV
5484 // code elsewhere that it shouldn't attempt to request a new
5485 // backedge-taken count, which could result in infinite recursion.
Dan Gohman0daf6872011-05-09 18:44:09 +00005486 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00005487 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
Chris Lattnera337f5e2011-01-09 02:16:18 +00005488 if (!Pair.second)
5489 return Pair.first->second;
Dan Gohman76466372009-04-27 20:16:15 +00005490
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005491 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
Andrew Trick3ca3f982011-07-26 17:19:55 +00005492 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5493 // must be cleared in this scope.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005494 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005495
5496 if (Result.getExact(this) != getCouldNotCompute()) {
5497 assert(isLoopInvariant(Result.getExact(this), L) &&
5498 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnera337f5e2011-01-09 02:16:18 +00005499 "Computed backedge-taken count isn't loop invariant for loop!");
5500 ++NumTripCountsComputed;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005501 }
5502 else if (Result.getMax(this) == getCouldNotCompute() &&
5503 isa<PHINode>(L->getHeader()->begin())) {
5504 // Only count loops that have phi nodes as not being computable.
5505 ++NumTripCountsNotComputed;
Chris Lattnera337f5e2011-01-09 02:16:18 +00005506 }
Dan Gohman2b8da352009-04-30 20:47:05 +00005507
Chris Lattnera337f5e2011-01-09 02:16:18 +00005508 // Now that we know more about the trip count for this loop, forget any
5509 // existing SCEV values for PHI nodes in this loop since they are only
5510 // conservative estimates made without the benefit of trip count
5511 // information. This is similar to the code in forgetLoop, except that
5512 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005513 if (Result.hasAnyInfo()) {
Chris Lattnera337f5e2011-01-09 02:16:18 +00005514 SmallVector<Instruction *, 16> Worklist;
5515 PushLoopPHIs(L, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005516
Chris Lattnera337f5e2011-01-09 02:16:18 +00005517 SmallPtrSet<Instruction *, 8> Visited;
5518 while (!Worklist.empty()) {
5519 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005520 if (!Visited.insert(I).second)
5521 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005522
Chris Lattnera337f5e2011-01-09 02:16:18 +00005523 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005524 ValueExprMap.find_as(static_cast<Value *>(I));
Chris Lattnera337f5e2011-01-09 02:16:18 +00005525 if (It != ValueExprMap.end()) {
5526 const SCEV *Old = It->second;
Dan Gohman761065e2010-11-17 02:44:44 +00005527
Chris Lattnera337f5e2011-01-09 02:16:18 +00005528 // SCEVUnknown for a PHI either means that it has an unrecognized
5529 // structure, or it's a PHI that's in the progress of being computed
5530 // by createNodeForPHI. In the former case, additional loop trip
5531 // count information isn't going to change anything. In the later
5532 // case, createNodeForPHI will perform the necessary updates on its
5533 // own when it gets to that point.
5534 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
Wei Mi785858c2016-08-09 20:37:50 +00005535 eraseValueFromMap(It->first);
Chris Lattnera337f5e2011-01-09 02:16:18 +00005536 forgetMemoizedResults(Old);
Dan Gohmandc191042009-07-08 19:23:34 +00005537 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005538 if (PHINode *PN = dyn_cast<PHINode>(I))
5539 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmandc191042009-07-08 19:23:34 +00005540 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005541
5542 PushDefUseChildren(I, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005543 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005544 }
Dan Gohman6acd95b2011-04-25 22:48:29 +00005545
5546 // Re-lookup the insert position, since the call to
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005547 // computeBackedgeTakenCount above could result in a
Dan Gohman6acd95b2011-04-25 22:48:29 +00005548 // recusive call to getBackedgeTakenInfo (on a different
5549 // loop), which would invalidate the iterator computed
5550 // earlier.
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005551 return BackedgeTakenCounts.find(L)->second = std::move(Result);
Chris Lattnerd934c702004-04-02 20:23:17 +00005552}
5553
Dan Gohman880c92a2009-10-31 15:04:55 +00005554void ScalarEvolution::forgetLoop(const Loop *L) {
5555 // Drop any stored trip count value.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005556 auto RemoveLoopFromBackedgeMap =
5557 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5558 auto BTCPos = Map.find(L);
5559 if (BTCPos != Map.end()) {
5560 BTCPos->second.clear();
5561 Map.erase(BTCPos);
5562 }
5563 };
5564
5565 RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5566 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohmanf1505722009-05-02 17:43:35 +00005567
Dan Gohman880c92a2009-10-31 15:04:55 +00005568 // Drop information about expressions based on loop-header PHIs.
Dan Gohman48f82222009-05-04 22:30:44 +00005569 SmallVector<Instruction *, 16> Worklist;
Dan Gohmandc191042009-07-08 19:23:34 +00005570 PushLoopPHIs(L, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005571
Dan Gohmandc191042009-07-08 19:23:34 +00005572 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00005573 while (!Worklist.empty()) {
5574 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005575 if (!Visited.insert(I).second)
5576 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005577
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005578 ValueExprMapType::iterator It =
5579 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005580 if (It != ValueExprMap.end()) {
Wei Mi785858c2016-08-09 20:37:50 +00005581 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00005582 forgetMemoizedResults(It->second);
Dan Gohmandc191042009-07-08 19:23:34 +00005583 if (PHINode *PN = dyn_cast<PHINode>(I))
5584 ConstantEvolutionLoopExitValue.erase(PN);
5585 }
5586
5587 PushDefUseChildren(I, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005588 }
Dan Gohmandcb354b2010-10-29 20:16:10 +00005589
5590 // Forget all contained loops too, to avoid dangling entries in the
5591 // ValuesAtScopes map.
Benjamin Krameraa209152016-06-26 17:27:42 +00005592 for (Loop *I : *L)
5593 forgetLoop(I);
Sanjoy Das7e4a6412016-05-29 00:32:17 +00005594
Sanjoy Das5603fc02016-09-26 02:44:07 +00005595 LoopPropertiesCache.erase(L);
Dan Gohman43300342009-02-17 20:49:49 +00005596}
5597
Eric Christopheref6d5932010-07-29 01:25:38 +00005598void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005599 Instruction *I = dyn_cast<Instruction>(V);
5600 if (!I) return;
5601
5602 // Drop information about expressions based on loop-header PHIs.
5603 SmallVector<Instruction *, 16> Worklist;
5604 Worklist.push_back(I);
5605
5606 SmallPtrSet<Instruction *, 8> Visited;
5607 while (!Worklist.empty()) {
5608 I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005609 if (!Visited.insert(I).second)
5610 continue;
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005611
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005612 ValueExprMapType::iterator It =
5613 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005614 if (It != ValueExprMap.end()) {
Wei Mi785858c2016-08-09 20:37:50 +00005615 eraseValueFromMap(It->first);
Dan Gohman7e6b3932010-11-17 23:28:48 +00005616 forgetMemoizedResults(It->second);
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005617 if (PHINode *PN = dyn_cast<PHINode>(I))
5618 ConstantEvolutionLoopExitValue.erase(PN);
5619 }
5620
5621 PushDefUseChildren(I, Worklist);
5622 }
5623}
5624
Sanjoy Dasf8570812016-05-29 00:38:22 +00005625/// Get the exact loop backedge taken count considering all loop exits. A
5626/// computable result can only be returned for loops with a single exit.
5627/// Returning the minimum taken count among all exits is incorrect because one
5628/// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5629/// the limit of each loop test is never skipped. This is a valid assumption as
5630/// long as the loop exits via that test. For precise results, it is the
5631/// caller's responsibility to specify the relevant loop exit using
Andrew Trick90c7a102011-11-16 00:52:40 +00005632/// getExact(ExitingBlock, SE).
Andrew Trick3ca3f982011-07-26 17:19:55 +00005633const SCEV *
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005634ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5635 SCEVUnionPredicate *Preds) const {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005636 // If any exits were not computable, the loop is not computable.
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005637 if (!isComplete() || ExitNotTaken.empty())
5638 return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005639
Craig Topper9f008862014-04-15 04:59:12 +00005640 const SCEV *BECount = nullptr;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005641 for (auto &ENT : ExitNotTaken) {
5642 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005643
5644 if (!BECount)
Silviu Baranga6f444df2016-04-08 14:29:09 +00005645 BECount = ENT.ExactNotTaken;
5646 else if (BECount != ENT.ExactNotTaken)
Andrew Trick90c7a102011-11-16 00:52:40 +00005647 return SE->getCouldNotCompute();
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005648 if (Preds && !ENT.hasAlwaysTruePredicate())
5649 Preds->add(ENT.Predicate.get());
Silviu Baranga6f444df2016-04-08 14:29:09 +00005650
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005651 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
Silviu Baranga6f444df2016-04-08 14:29:09 +00005652 "Predicate should be always true!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005653 }
Silviu Baranga6f444df2016-04-08 14:29:09 +00005654
Andrew Trickbbb226a2011-09-02 21:20:46 +00005655 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005656 return BECount;
5657}
5658
Sanjoy Dasf8570812016-05-29 00:38:22 +00005659/// Get the exact not taken count for this loop exit.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005660const SCEV *
Andrew Trick77c55422011-08-02 04:23:35 +00005661ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005662 ScalarEvolution *SE) const {
Silviu Baranga6f444df2016-04-08 14:29:09 +00005663 for (auto &ENT : ExitNotTaken)
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005664 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
Silviu Baranga6f444df2016-04-08 14:29:09 +00005665 return ENT.ExactNotTaken;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005666
Andrew Trick3ca3f982011-07-26 17:19:55 +00005667 return SE->getCouldNotCompute();
5668}
5669
5670/// getMax - Get the max backedge taken count for the loop.
5671const SCEV *
5672ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
Sanjoy Das73268612016-09-26 01:10:22 +00005673 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5674 return !ENT.hasAlwaysTruePredicate();
5675 };
Silviu Baranga6f444df2016-04-08 14:29:09 +00005676
Sanjoy Das73268612016-09-26 01:10:22 +00005677 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
5678 return SE->getCouldNotCompute();
5679
5680 return getMax();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005681}
5682
John Brawn84b21832016-10-21 11:08:48 +00005683bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
5684 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5685 return !ENT.hasAlwaysTruePredicate();
5686 };
5687 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
5688}
5689
Andrew Trick9093e152013-03-26 03:14:53 +00005690bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5691 ScalarEvolution *SE) const {
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005692 if (getMax() && getMax() != SE->getCouldNotCompute() &&
5693 SE->hasOperand(getMax(), S))
Andrew Trick9093e152013-03-26 03:14:53 +00005694 return true;
5695
Silviu Baranga6f444df2016-04-08 14:29:09 +00005696 for (auto &ENT : ExitNotTaken)
5697 if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5698 SE->hasOperand(ENT.ExactNotTaken, S))
Silviu Barangaa393baf2016-04-06 14:06:32 +00005699 return true;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005700
Andrew Trick9093e152013-03-26 03:14:53 +00005701 return false;
5702}
5703
Andrew Trick3ca3f982011-07-26 17:19:55 +00005704/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5705/// computable exit into a persistent ExitNotTakenInfo array.
5706ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
Sanjoy Das5c4869b2016-09-26 01:10:27 +00005707 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
5708 &&ExitCounts,
John Brawn84b21832016-10-21 11:08:48 +00005709 bool Complete, const SCEV *MaxCount, bool MaxOrZero)
5710 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005711 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
Sanjoy Dase935c772016-09-25 23:12:08 +00005712 ExitNotTaken.reserve(ExitCounts.size());
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005713 std::transform(
5714 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005715 [&](const EdgeExitInfo &EEI) {
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005716 BasicBlock *ExitBB = EEI.first;
5717 const ExitLimit &EL = EEI.second;
Sanjoy Dasf0022122016-09-28 17:14:58 +00005718 if (EL.Predicates.empty())
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005719 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
Sanjoy Dasf0022122016-09-28 17:14:58 +00005720
5721 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
5722 for (auto *Pred : EL.Predicates)
5723 Predicate->add(Pred);
5724
5725 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
Sanjoy Dasc9bbf562016-09-25 23:12:04 +00005726 });
Andrew Trick3ca3f982011-07-26 17:19:55 +00005727}
5728
Sanjoy Dasf8570812016-05-29 00:38:22 +00005729/// Invalidate this result and free the ExitNotTakenInfo array.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005730void ScalarEvolution::BackedgeTakenInfo::clear() {
Sanjoy Dasd1eb62a2016-09-25 23:12:00 +00005731 ExitNotTaken.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005732}
5733
Sanjoy Dasf8570812016-05-29 00:38:22 +00005734/// Compute the number of times the backedge of the specified loop will execute.
Dan Gohman2b8da352009-04-30 20:47:05 +00005735ScalarEvolution::BackedgeTakenInfo
Silviu Baranga6f444df2016-04-08 14:29:09 +00005736ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5737 bool AllowPredicates) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00005738 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohman96212b62009-06-22 00:31:57 +00005739 L->getExitingBlocks(ExitingBlocks);
Chris Lattnerd934c702004-04-02 20:23:17 +00005740
Sanjoy Das6b76cdf2016-09-26 01:10:25 +00005741 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5742
5743 SmallVector<EdgeExitInfo, 4> ExitCounts;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005744 bool CouldComputeBECount = true;
Andrew Trickee5aa7f2014-01-15 06:42:11 +00005745 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
Andrew Trick839e30b2014-05-23 19:47:13 +00005746 const SCEV *MustExitMaxBECount = nullptr;
5747 const SCEV *MayExitMaxBECount = nullptr;
John Brawn84b21832016-10-21 11:08:48 +00005748 bool MustExitMaxOrZero = false;
Andrew Trick839e30b2014-05-23 19:47:13 +00005749
5750 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5751 // and compute maxBECount.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005752 // Do a union of all the predicates here.
Dan Gohman96212b62009-06-22 00:31:57 +00005753 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005754 BasicBlock *ExitBB = ExitingBlocks[i];
Silviu Baranga6f444df2016-04-08 14:29:09 +00005755 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
5756
Sanjoy Dasf0022122016-09-28 17:14:58 +00005757 assert((AllowPredicates || EL.Predicates.empty()) &&
Silviu Baranga6f444df2016-04-08 14:29:09 +00005758 "Predicated exit limit when predicates are not allowed!");
Andrew Trick839e30b2014-05-23 19:47:13 +00005759
5760 // 1. For each exit that can be computed, add an entry to ExitCounts.
5761 // CouldComputeBECount is true only if all exits can be computed.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005762 if (EL.ExactNotTaken == getCouldNotCompute())
Dan Gohman96212b62009-06-22 00:31:57 +00005763 // We couldn't compute an exact value for this exit, so
Dan Gohman8885b372009-06-22 21:10:22 +00005764 // we won't be able to compute an exact value for the loop.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005765 CouldComputeBECount = false;
5766 else
Sanjoy Dasbdd97102016-09-25 23:11:55 +00005767 ExitCounts.emplace_back(ExitBB, EL);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005768
Andrew Trick839e30b2014-05-23 19:47:13 +00005769 // 2. Derive the loop's MaxBECount from each exit's max number of
5770 // non-exiting iterations. Partition the loop exits into two kinds:
5771 // LoopMustExits and LoopMayExits.
5772 //
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005773 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5774 // is a LoopMayExit. If any computable LoopMustExit is found, then
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005775 // MaxBECount is the minimum EL.MaxNotTaken of computable
5776 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
5777 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
5778 // computable EL.MaxNotTaken.
5779 if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005780 DT.dominates(ExitBB, Latch)) {
John Brawn84b21832016-10-21 11:08:48 +00005781 if (!MustExitMaxBECount) {
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005782 MustExitMaxBECount = EL.MaxNotTaken;
John Brawn84b21832016-10-21 11:08:48 +00005783 MustExitMaxOrZero = EL.MaxOrZero;
5784 } else {
Andrew Trick839e30b2014-05-23 19:47:13 +00005785 MustExitMaxBECount =
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005786 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
Andrew Tricke2553592014-05-22 00:37:03 +00005787 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005788 } else if (MayExitMaxBECount != getCouldNotCompute()) {
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005789 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
5790 MayExitMaxBECount = EL.MaxNotTaken;
Andrew Trick839e30b2014-05-23 19:47:13 +00005791 else {
5792 MayExitMaxBECount =
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005793 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
Andrew Trick839e30b2014-05-23 19:47:13 +00005794 }
Andrew Trick90c7a102011-11-16 00:52:40 +00005795 }
Dan Gohman96212b62009-06-22 00:31:57 +00005796 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005797 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5798 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
John Brawn84b21832016-10-21 11:08:48 +00005799 // The loop backedge will be taken the maximum or zero times if there's
5800 // a single exit that must be taken the maximum or zero times.
5801 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
Sanjoy Das5c4869b2016-09-26 01:10:27 +00005802 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
John Brawn84b21832016-10-21 11:08:48 +00005803 MaxBECount, MaxOrZero);
Dan Gohman96212b62009-06-22 00:31:57 +00005804}
5805
Andrew Trick3ca3f982011-07-26 17:19:55 +00005806ScalarEvolution::ExitLimit
Silviu Baranga6f444df2016-04-08 14:29:09 +00005807ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
5808 bool AllowPredicates) {
Dan Gohman96212b62009-06-22 00:31:57 +00005809
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005810 // Okay, we've chosen an exiting block. See what condition causes us to exit
5811 // at this block and remember the exit block and whether all other targets
Benjamin Kramer5a188542014-02-11 15:44:32 +00005812 // lead to the loop header.
5813 bool MustExecuteLoopHeader = true;
Craig Topper9f008862014-04-15 04:59:12 +00005814 BasicBlock *Exit = nullptr;
Sanjoy Das0ff07872016-01-19 20:53:46 +00005815 for (auto *SBB : successors(ExitingBlock))
5816 if (!L->contains(SBB)) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005817 if (Exit) // Multiple exit successors.
5818 return getCouldNotCompute();
Sanjoy Das0ff07872016-01-19 20:53:46 +00005819 Exit = SBB;
5820 } else if (SBB != L->getHeader()) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005821 MustExecuteLoopHeader = false;
5822 }
Dan Gohmance973df2009-06-24 04:48:43 +00005823
Chris Lattner18954852007-01-07 02:24:26 +00005824 // At this point, we know we have a conditional branch that determines whether
5825 // the loop is exited. However, we don't know if the branch is executed each
5826 // time through the loop. If not, then the execution count of the branch will
5827 // not be equal to the trip count of the loop.
5828 //
5829 // Currently we check for this by checking to see if the Exit branch goes to
5830 // the loop header. If so, we know it will always execute the same number of
Chris Lattner5a554762007-01-14 01:24:47 +00005831 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman96212b62009-06-22 00:31:57 +00005832 // loop header. This is common for un-rotated loops.
5833 //
5834 // If both of those tests fail, walk up the unique predecessor chain to the
5835 // header, stopping if there is an edge that doesn't exit the loop. If the
5836 // header is reached, the execution count of the branch will be equal to the
5837 // trip count of the loop.
5838 //
5839 // More extensive analysis could be done to handle more cases here.
5840 //
Benjamin Kramer5a188542014-02-11 15:44:32 +00005841 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005842 // The simple checks failed, try climbing the unique predecessor chain
5843 // up to the header.
5844 bool Ok = false;
Benjamin Kramer5a188542014-02-11 15:44:32 +00005845 for (BasicBlock *BB = ExitingBlock; BB; ) {
Dan Gohman96212b62009-06-22 00:31:57 +00005846 BasicBlock *Pred = BB->getUniquePredecessor();
5847 if (!Pred)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005848 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005849 TerminatorInst *PredTerm = Pred->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +00005850 for (const BasicBlock *PredSucc : PredTerm->successors()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005851 if (PredSucc == BB)
5852 continue;
5853 // If the predecessor has a successor that isn't BB and isn't
5854 // outside the loop, assume the worst.
5855 if (L->contains(PredSucc))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005856 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005857 }
5858 if (Pred == L->getHeader()) {
5859 Ok = true;
5860 break;
5861 }
5862 BB = Pred;
5863 }
5864 if (!Ok)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005865 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005866 }
5867
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005868 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005869 TerminatorInst *Term = ExitingBlock->getTerminator();
5870 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
5871 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
5872 // Proceed to the next level to examine the exit condition expression.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005873 return computeExitLimitFromCond(
5874 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
5875 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005876 }
5877
5878 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005879 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005880 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005881
5882 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005883}
5884
Andrew Trick3ca3f982011-07-26 17:19:55 +00005885ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005886ScalarEvolution::computeExitLimitFromCond(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005887 Value *ExitCond,
5888 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005889 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005890 bool ControlsExit,
5891 bool AllowPredicates) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00005892 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman96212b62009-06-22 00:31:57 +00005893 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
5894 if (BO->getOpcode() == Instruction::And) {
5895 // Recurse on the operands of the and.
Andrew Trick5b245a12013-05-31 06:43:25 +00005896 bool EitherMayExit = L->contains(TBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005897 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005898 ControlsExit && !EitherMayExit,
5899 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005900 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005901 ControlsExit && !EitherMayExit,
5902 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00005903 const SCEV *BECount = getCouldNotCompute();
5904 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005905 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005906 // Both conditions must be true for the loop to continue executing.
5907 // Choose the less conservative count.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005908 if (EL0.ExactNotTaken == getCouldNotCompute() ||
5909 EL1.ExactNotTaken == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005910 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005911 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005912 BECount =
5913 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
5914 if (EL0.MaxNotTaken == getCouldNotCompute())
5915 MaxBECount = EL1.MaxNotTaken;
5916 else if (EL1.MaxNotTaken == getCouldNotCompute())
5917 MaxBECount = EL0.MaxNotTaken;
Dan Gohmaned627382009-06-22 15:09:28 +00005918 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005919 MaxBECount =
5920 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
Dan Gohman96212b62009-06-22 00:31:57 +00005921 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005922 // Both conditions must be true at the same time for the loop to exit.
5923 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005924 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005925 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
5926 MaxBECount = EL0.MaxNotTaken;
5927 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
5928 BECount = EL0.ExactNotTaken;
Dan Gohman96212b62009-06-22 00:31:57 +00005929 }
5930
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00005931 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
5932 // to be more aggressive when computing BECount than when computing
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005933 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
5934 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
5935 // to not.
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00005936 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
5937 !isa<SCEVCouldNotCompute>(BECount))
5938 MaxBECount = BECount;
5939
John Brawn84b21832016-10-21 11:08:48 +00005940 return ExitLimit(BECount, MaxBECount, false,
5941 {&EL0.Predicates, &EL1.Predicates});
Dan Gohman96212b62009-06-22 00:31:57 +00005942 }
5943 if (BO->getOpcode() == Instruction::Or) {
5944 // Recurse on the operands of the or.
Andrew Trick5b245a12013-05-31 06:43:25 +00005945 bool EitherMayExit = L->contains(FBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005946 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005947 ControlsExit && !EitherMayExit,
5948 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005949 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005950 ControlsExit && !EitherMayExit,
5951 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00005952 const SCEV *BECount = getCouldNotCompute();
5953 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005954 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005955 // Both conditions must be false for the loop to continue executing.
5956 // Choose the less conservative count.
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005957 if (EL0.ExactNotTaken == getCouldNotCompute() ||
5958 EL1.ExactNotTaken == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005959 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005960 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005961 BECount =
5962 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
5963 if (EL0.MaxNotTaken == getCouldNotCompute())
5964 MaxBECount = EL1.MaxNotTaken;
5965 else if (EL1.MaxNotTaken == getCouldNotCompute())
5966 MaxBECount = EL0.MaxNotTaken;
Dan Gohmaned627382009-06-22 15:09:28 +00005967 else
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005968 MaxBECount =
5969 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
Dan Gohman96212b62009-06-22 00:31:57 +00005970 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005971 // Both conditions must be false at the same time for the loop to exit.
5972 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005973 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Sanjoy Das89eea6b2016-09-25 23:11:57 +00005974 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
5975 MaxBECount = EL0.MaxNotTaken;
5976 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
5977 BECount = EL0.ExactNotTaken;
Dan Gohman96212b62009-06-22 00:31:57 +00005978 }
5979
John Brawn84b21832016-10-21 11:08:48 +00005980 return ExitLimit(BECount, MaxBECount, false,
5981 {&EL0.Predicates, &EL1.Predicates});
Dan Gohman96212b62009-06-22 00:31:57 +00005982 }
5983 }
5984
5985 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman8b0a4192010-03-01 17:49:51 +00005986 // Proceed to the next level to examine the icmp.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005987 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
5988 ExitLimit EL =
5989 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
5990 if (EL.hasFullInfo() || !AllowPredicates)
5991 return EL;
5992
5993 // Try again, but use SCEV predicates this time.
5994 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
5995 /*AllowPredicates=*/true);
5996 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005997
Dan Gohman6b1e2a82010-02-19 18:12:07 +00005998 // Check for a constant condition. These are normally stripped out by
5999 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
6000 // preserve the CFG and is temporarily leaving constant conditions
6001 // in place.
6002 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6003 if (L->contains(FBB) == !CI->getZExtValue())
6004 // The backedge is always taken.
6005 return getCouldNotCompute();
6006 else
6007 // The backedge is never taken.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00006008 return getZero(CI->getType());
Dan Gohman6b1e2a82010-02-19 18:12:07 +00006009 }
6010
Eli Friedmanebf98b02009-05-09 12:32:42 +00006011 // If it's not an integer or pointer comparison then compute it the hard way.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006012 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohman96212b62009-06-22 00:31:57 +00006013}
6014
Andrew Trick3ca3f982011-07-26 17:19:55 +00006015ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006016ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00006017 ICmpInst *ExitCond,
6018 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00006019 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006020 bool ControlsExit,
6021 bool AllowPredicates) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006022
Reid Spencer266e42b2006-12-23 06:05:41 +00006023 // If the condition was exit on true, convert the condition to exit on false
6024 ICmpInst::Predicate Cond;
Dan Gohman96212b62009-06-22 00:31:57 +00006025 if (!L->contains(FBB))
Reid Spencer266e42b2006-12-23 06:05:41 +00006026 Cond = ExitCond->getPredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006027 else
Reid Spencer266e42b2006-12-23 06:05:41 +00006028 Cond = ExitCond->getInversePredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006029
6030 // Handle common loops like: for (X = "string"; *X; ++X)
6031 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
6032 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00006033 ExitLimit ItCnt =
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006034 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanba820342010-02-24 17:31:30 +00006035 if (ItCnt.hasAnyInfo())
6036 return ItCnt;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006037 }
6038
Dan Gohmanaf752342009-07-07 17:06:11 +00006039 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6040 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattnerd934c702004-04-02 20:23:17 +00006041
6042 // Try to evaluate any dependencies out of the loop.
Dan Gohman8ca08852009-05-24 23:25:42 +00006043 LHS = getSCEVAtScope(LHS, L);
6044 RHS = getSCEVAtScope(RHS, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006045
Dan Gohmance973df2009-06-24 04:48:43 +00006046 // At this point, we would like to compute how many iterations of the
Reid Spencer266e42b2006-12-23 06:05:41 +00006047 // loop the predicate will return true for these inputs.
Dan Gohmanafd6db92010-11-17 21:23:15 +00006048 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohmandc5f5cb2008-09-16 18:52:57 +00006049 // If there is a loop-invariant, force it into the RHS.
Chris Lattnerd934c702004-04-02 20:23:17 +00006050 std::swap(LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00006051 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattnerd934c702004-04-02 20:23:17 +00006052 }
6053
Dan Gohman81585c12010-05-03 16:35:17 +00006054 // Simplify the operands before analyzing them.
6055 (void)SimplifyICmpOperands(Cond, LHS, RHS);
6056
Chris Lattnerd934c702004-04-02 20:23:17 +00006057 // If we have a comparison of a chrec against a constant, try to use value
6058 // ranges to answer this query.
Dan Gohmana30370b2009-05-04 22:02:23 +00006059 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6060 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattnerd934c702004-04-02 20:23:17 +00006061 if (AddRec->getLoop() == L) {
Eli Friedmanebf98b02009-05-09 12:32:42 +00006062 // Form the constant range.
Sanjoy Das1f7b8132016-10-02 00:09:57 +00006063 ConstantRange CompRange =
6064 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
Misha Brukman01808ca2005-04-21 21:13:18 +00006065
Dan Gohmanaf752342009-07-07 17:06:11 +00006066 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedmanebf98b02009-05-09 12:32:42 +00006067 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattnerd934c702004-04-02 20:23:17 +00006068 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006069
Chris Lattnerd934c702004-04-02 20:23:17 +00006070 switch (Cond) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006071 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattnerd934c702004-04-02 20:23:17 +00006072 // Convert to: while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006073 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006074 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006075 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006076 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006077 }
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00006078 case ICmpInst::ICMP_EQ: { // while (X == Y)
6079 // Convert to: while (X-Y == 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006080 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006081 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00006082 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006083 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006084 case ICmpInst::ICMP_SLT:
6085 case ICmpInst::ICMP_ULT: { // while (X < Y)
6086 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
Sanjoy Das108fcf22016-05-29 00:38:00 +00006087 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006088 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006089 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006090 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006091 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006092 case ICmpInst::ICMP_SGT:
6093 case ICmpInst::ICMP_UGT: { // while (X > Y)
6094 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
Silviu Baranga6f444df2016-04-08 14:29:09 +00006095 ExitLimit EL =
Sanjoy Das108fcf22016-05-29 00:38:00 +00006096 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00006097 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00006098 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00006099 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00006100 }
Chris Lattnerd934c702004-04-02 20:23:17 +00006101 default:
Chris Lattner0defaa12004-04-03 00:43:03 +00006102 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00006103 }
Sanjoy Das0da2d142016-06-30 02:47:28 +00006104
6105 auto *ExhaustiveCount =
6106 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6107
6108 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6109 return ExhaustiveCount;
6110
6111 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6112 ExitCond->getOperand(1), L, Cond);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006113}
6114
Benjamin Kramer5a188542014-02-11 15:44:32 +00006115ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006116ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
Benjamin Kramer5a188542014-02-11 15:44:32 +00006117 SwitchInst *Switch,
6118 BasicBlock *ExitingBlock,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006119 bool ControlsExit) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00006120 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6121
6122 // Give up if the exit is the default dest of a switch.
6123 if (Switch->getDefaultDest() == ExitingBlock)
6124 return getCouldNotCompute();
6125
6126 assert(L->contains(Switch->getDefaultDest()) &&
6127 "Default case must not exit the loop!");
6128 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6129 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6130
6131 // while (X != Y) --> while (X-Y != 0)
Sanjoy Das108fcf22016-05-29 00:38:00 +00006132 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006133 if (EL.hasAnyInfo())
6134 return EL;
6135
6136 return getCouldNotCompute();
6137}
6138
Chris Lattnerec901cc2004-10-12 01:49:27 +00006139static ConstantInt *
Dan Gohmana37eaf22007-10-22 18:31:58 +00006140EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6141 ScalarEvolution &SE) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006142 const SCEV *InVal = SE.getConstant(C);
6143 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006144 assert(isa<SCEVConstant>(Val) &&
6145 "Evaluation of SCEV at constant didn't fold correctly?");
6146 return cast<SCEVConstant>(Val)->getValue();
6147}
6148
Sanjoy Dasf8570812016-05-29 00:38:22 +00006149/// Given an exit condition of 'icmp op load X, cst', try to see if we can
6150/// compute the backedge execution count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006151ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006152ScalarEvolution::computeLoadConstantCompareExitLimit(
Andrew Trick3ca3f982011-07-26 17:19:55 +00006153 LoadInst *LI,
6154 Constant *RHS,
6155 const Loop *L,
6156 ICmpInst::Predicate predicate) {
6157
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006158 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006159
6160 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanba820342010-02-24 17:31:30 +00006161 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006162 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006163 if (!GEP) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006164
6165 // Make sure that it is really a constant global we are gepping, with an
6166 // initializer, and make sure the first IDX is really 0.
6167 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00006168 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006169 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6170 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006171 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006172
6173 // Okay, we allow one non-constant index into the GEP instruction.
Craig Topper9f008862014-04-15 04:59:12 +00006174 Value *VarIdx = nullptr;
Chris Lattnere166a852012-01-24 05:49:24 +00006175 std::vector<Constant*> Indexes;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006176 unsigned VarIdxNum = 0;
6177 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6178 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6179 Indexes.push_back(CI);
6180 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006181 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006182 VarIdx = GEP->getOperand(i);
6183 VarIdxNum = i-2;
Craig Topper9f008862014-04-15 04:59:12 +00006184 Indexes.push_back(nullptr);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006185 }
6186
Andrew Trick7004e4b2012-03-26 22:33:59 +00006187 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6188 if (!VarIdx)
6189 return getCouldNotCompute();
6190
Chris Lattnerec901cc2004-10-12 01:49:27 +00006191 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6192 // Check to see if X is a loop variant variable value now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006193 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohman8ca08852009-05-24 23:25:42 +00006194 Idx = getSCEVAtScope(Idx, L);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006195
6196 // We can only recognize very limited forms of loop index expressions, in
6197 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman48f82222009-05-04 22:30:44 +00006198 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanafd6db92010-11-17 21:23:15 +00006199 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006200 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6201 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006202 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006203
6204 unsigned MaxSteps = MaxBruteForceIterations;
6205 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersonedb4a702009-07-24 23:12:02 +00006206 ConstantInt *ItCst = ConstantInt::get(
Owen Andersonb6b25302009-07-14 23:09:55 +00006207 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanc8e23622009-04-21 23:15:49 +00006208 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006209
6210 // Form the GEP offset.
6211 Indexes[VarIdxNum] = Val;
6212
Chris Lattnere166a852012-01-24 05:49:24 +00006213 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6214 Indexes);
Craig Topper9f008862014-04-15 04:59:12 +00006215 if (!Result) break; // Cannot compute!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006216
6217 // Evaluate the condition for this iteration.
Reid Spencer266e42b2006-12-23 06:05:41 +00006218 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00006219 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer983e3b32007-03-01 07:25:48 +00006220 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00006221 ++NumArrayLenItCounts;
Dan Gohmanc8e23622009-04-21 23:15:49 +00006222 return getConstant(ItCst); // Found terminating iteration!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006223 }
6224 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006225 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006226}
6227
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006228ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6229 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6230 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6231 if (!RHS)
6232 return getCouldNotCompute();
6233
6234 const BasicBlock *Latch = L->getLoopLatch();
6235 if (!Latch)
6236 return getCouldNotCompute();
6237
6238 const BasicBlock *Predecessor = L->getLoopPredecessor();
6239 if (!Predecessor)
6240 return getCouldNotCompute();
6241
6242 // Return true if V is of the form "LHS `shift_op` <positive constant>".
6243 // Return LHS in OutLHS and shift_opt in OutOpCode.
6244 auto MatchPositiveShift =
6245 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6246
6247 using namespace PatternMatch;
6248
6249 ConstantInt *ShiftAmt;
6250 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6251 OutOpCode = Instruction::LShr;
6252 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6253 OutOpCode = Instruction::AShr;
6254 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6255 OutOpCode = Instruction::Shl;
6256 else
6257 return false;
6258
6259 return ShiftAmt->getValue().isStrictlyPositive();
6260 };
6261
6262 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6263 //
6264 // loop:
6265 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6266 // %iv.shifted = lshr i32 %iv, <positive constant>
6267 //
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006268 // Return true on a successful match. Return the corresponding PHI node (%iv
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006269 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6270 auto MatchShiftRecurrence =
6271 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6272 Optional<Instruction::BinaryOps> PostShiftOpCode;
6273
6274 {
6275 Instruction::BinaryOps OpC;
6276 Value *V;
6277
6278 // If we encounter a shift instruction, "peel off" the shift operation,
6279 // and remember that we did so. Later when we inspect %iv's backedge
6280 // value, we will make sure that the backedge value uses the same
6281 // operation.
6282 //
6283 // Note: the peeled shift operation does not have to be the same
6284 // instruction as the one feeding into the PHI's backedge value. We only
6285 // really care about it being the same *kind* of shift instruction --
6286 // that's all that is required for our later inferences to hold.
6287 if (MatchPositiveShift(LHS, V, OpC)) {
6288 PostShiftOpCode = OpC;
6289 LHS = V;
6290 }
6291 }
6292
6293 PNOut = dyn_cast<PHINode>(LHS);
6294 if (!PNOut || PNOut->getParent() != L->getHeader())
6295 return false;
6296
6297 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6298 Value *OpLHS;
6299
6300 return
6301 // The backedge value for the PHI node must be a shift by a positive
6302 // amount
6303 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6304
6305 // of the PHI node itself
6306 OpLHS == PNOut &&
6307
6308 // and the kind of shift should be match the kind of shift we peeled
6309 // off, if any.
6310 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6311 };
6312
6313 PHINode *PN;
6314 Instruction::BinaryOps OpCode;
6315 if (!MatchShiftRecurrence(LHS, PN, OpCode))
6316 return getCouldNotCompute();
6317
6318 const DataLayout &DL = getDataLayout();
6319
6320 // The key rationale for this optimization is that for some kinds of shift
6321 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6322 // within a finite number of iterations. If the condition guarding the
6323 // backedge (in the sense that the backedge is taken if the condition is true)
6324 // is false for the value the shift recurrence stabilizes to, then we know
6325 // that the backedge is taken only a finite number of times.
6326
6327 ConstantInt *StableValue = nullptr;
6328 switch (OpCode) {
6329 default:
6330 llvm_unreachable("Impossible case!");
6331
6332 case Instruction::AShr: {
6333 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6334 // bitwidth(K) iterations.
6335 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6336 bool KnownZero, KnownOne;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00006337 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006338 Predecessor->getTerminator(), &DT);
6339 auto *Ty = cast<IntegerType>(RHS->getType());
6340 if (KnownZero)
6341 StableValue = ConstantInt::get(Ty, 0);
6342 else if (KnownOne)
6343 StableValue = ConstantInt::get(Ty, -1, true);
6344 else
6345 return getCouldNotCompute();
6346
6347 break;
6348 }
6349 case Instruction::LShr:
6350 case Instruction::Shl:
6351 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6352 // stabilize to 0 in at most bitwidth(K) iterations.
6353 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6354 break;
6355 }
6356
6357 auto *Result =
6358 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6359 assert(Result->getType()->isIntegerTy(1) &&
6360 "Otherwise cannot be an operand to a branch instruction");
6361
6362 if (Result->isZeroValue()) {
6363 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6364 const SCEV *UpperBound =
6365 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
John Brawn84b21832016-10-21 11:08:48 +00006366 return ExitLimit(getCouldNotCompute(), UpperBound, false);
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006367 }
6368
6369 return getCouldNotCompute();
6370}
Chris Lattnerec901cc2004-10-12 01:49:27 +00006371
Sanjoy Dasf8570812016-05-29 00:38:22 +00006372/// Return true if we can constant fold an instruction of the specified type,
6373/// assuming that all operands were constants.
Chris Lattnerdd730472004-04-17 22:58:41 +00006374static bool CanConstantFold(const Instruction *I) {
Reid Spencer2341c222007-02-02 02:16:23 +00006375 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Nick Lewyckya6674c72011-10-22 19:58:20 +00006376 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6377 isa<LoadInst>(I))
Chris Lattnerdd730472004-04-17 22:58:41 +00006378 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00006379
Chris Lattnerdd730472004-04-17 22:58:41 +00006380 if (const CallInst *CI = dyn_cast<CallInst>(I))
6381 if (const Function *F = CI->getCalledFunction())
Dan Gohmana65951f2008-01-31 01:05:10 +00006382 return canConstantFoldCallTo(F);
Chris Lattnerdd730472004-04-17 22:58:41 +00006383 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00006384}
6385
Andrew Trick3a86ba72011-10-05 03:25:31 +00006386/// Determine whether this instruction can constant evolve within this loop
6387/// assuming its operands can all constant evolve.
6388static bool canConstantEvolve(Instruction *I, const Loop *L) {
6389 // An instruction outside of the loop can't be derived from a loop PHI.
6390 if (!L->contains(I)) return false;
6391
6392 if (isa<PHINode>(I)) {
David Blaikie19ef0d32015-03-24 16:33:19 +00006393 // We don't currently keep track of the control flow needed to evaluate
6394 // PHIs, so we cannot handle PHIs inside of loops.
6395 return L->getHeader() == I->getParent();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006396 }
6397
6398 // If we won't be able to constant fold this expression even if the operands
6399 // are constants, bail early.
6400 return CanConstantFold(I);
6401}
6402
6403/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6404/// recursing through each instruction operand until reaching a loop header phi.
6405static PHINode *
6406getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
Andrew Tricke9162f12011-10-05 05:58:49 +00006407 DenseMap<Instruction *, PHINode *> &PHIMap) {
Andrew Trick3a86ba72011-10-05 03:25:31 +00006408
6409 // Otherwise, we can evaluate this instruction if all of its operands are
6410 // constant or derived from a PHI node themselves.
Craig Topper9f008862014-04-15 04:59:12 +00006411 PHINode *PHI = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006412 for (Value *Op : UseInst->operands()) {
6413 if (isa<Constant>(Op)) continue;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006414
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006415 Instruction *OpInst = dyn_cast<Instruction>(Op);
Craig Topper9f008862014-04-15 04:59:12 +00006416 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006417
6418 PHINode *P = dyn_cast<PHINode>(OpInst);
Andrew Trick3e8a5762011-10-05 22:06:53 +00006419 if (!P)
6420 // If this operand is already visited, reuse the prior result.
6421 // We may have P != PHI if this is the deepest point at which the
6422 // inconsistent paths meet.
6423 P = PHIMap.lookup(OpInst);
6424 if (!P) {
6425 // Recurse and memoize the results, whether a phi is found or not.
6426 // This recursive call invalidates pointers into PHIMap.
6427 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
6428 PHIMap[OpInst] = P;
Andrew Tricke9162f12011-10-05 05:58:49 +00006429 }
Craig Topper9f008862014-04-15 04:59:12 +00006430 if (!P)
6431 return nullptr; // Not evolving from PHI
6432 if (PHI && PHI != P)
6433 return nullptr; // Evolving from multiple different PHIs.
Andrew Tricke9162f12011-10-05 05:58:49 +00006434 PHI = P;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006435 }
6436 // This is a expression evolving from a constant PHI!
6437 return PHI;
6438}
6439
Chris Lattnerdd730472004-04-17 22:58:41 +00006440/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6441/// in the loop that V is derived from. We allow arbitrary operations along the
6442/// way, but the operands of an operation must either be constants or a value
6443/// derived from a constant PHI. If this expression does not fit with these
6444/// constraints, return null.
6445static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006446 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006447 if (!I || !canConstantEvolve(I, L)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006448
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00006449 if (PHINode *PN = dyn_cast<PHINode>(I))
Andrew Trick3a86ba72011-10-05 03:25:31 +00006450 return PN;
Chris Lattnerdd730472004-04-17 22:58:41 +00006451
Andrew Trick3a86ba72011-10-05 03:25:31 +00006452 // Record non-constant instructions contained by the loop.
Andrew Tricke9162f12011-10-05 05:58:49 +00006453 DenseMap<Instruction *, PHINode *> PHIMap;
6454 return getConstantEvolvingPHIOperands(I, L, PHIMap);
Chris Lattnerdd730472004-04-17 22:58:41 +00006455}
6456
6457/// EvaluateExpression - Given an expression that passes the
6458/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6459/// in the loop has the value PHIVal. If we can't fold this expression for some
6460/// reason, return null.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006461static Constant *EvaluateExpression(Value *V, const Loop *L,
6462 DenseMap<Instruction *, Constant *> &Vals,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006463 const DataLayout &DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00006464 const TargetLibraryInfo *TLI) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006465 // Convenient constant check, but redundant for recursive calls.
Reid Spencer30d69a52004-07-18 00:18:30 +00006466 if (Constant *C = dyn_cast<Constant>(V)) return C;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006467 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006468 if (!I) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006469
Andrew Trick3a86ba72011-10-05 03:25:31 +00006470 if (Constant *C = Vals.lookup(I)) return C;
6471
Nick Lewyckya6674c72011-10-22 19:58:20 +00006472 // An instruction inside the loop depends on a value outside the loop that we
6473 // weren't given a mapping for, or a value such as a call inside the loop.
Craig Topper9f008862014-04-15 04:59:12 +00006474 if (!canConstantEvolve(I, L)) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006475
6476 // An unmapped PHI can be due to a branch or another loop inside this loop,
6477 // or due to this not being the initial iteration through a loop where we
6478 // couldn't compute the evolution of this particular PHI last time.
Craig Topper9f008862014-04-15 04:59:12 +00006479 if (isa<PHINode>(I)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006480
Dan Gohmanf820bd32010-06-22 13:15:46 +00006481 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattnerdd730472004-04-17 22:58:41 +00006482
6483 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006484 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6485 if (!Operand) {
Nick Lewyckya447e0f32011-10-14 09:38:46 +00006486 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006487 if (!Operands[i]) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006488 continue;
6489 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006490 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Andrew Tricke9162f12011-10-05 05:58:49 +00006491 Vals[Operand] = C;
Craig Topper9f008862014-04-15 04:59:12 +00006492 if (!C) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006493 Operands[i] = C;
Chris Lattnerdd730472004-04-17 22:58:41 +00006494 }
6495
Nick Lewyckya6674c72011-10-22 19:58:20 +00006496 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00006497 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006498 Operands[1], DL, TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006499 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6500 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006501 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006502 }
Manuel Jacobe9024592016-01-21 06:33:22 +00006503 return ConstantFoldInstOperands(I, Operands, DL, TLI);
Chris Lattnerdd730472004-04-17 22:58:41 +00006504}
6505
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006506
6507// If every incoming value to PN except the one for BB is a specific Constant,
6508// return that, else return nullptr.
6509static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6510 Constant *IncomingVal = nullptr;
6511
6512 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6513 if (PN->getIncomingBlock(i) == BB)
6514 continue;
6515
6516 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6517 if (!CurrentVal)
6518 return nullptr;
6519
6520 if (IncomingVal != CurrentVal) {
6521 if (IncomingVal)
6522 return nullptr;
6523 IncomingVal = CurrentVal;
6524 }
6525 }
6526
6527 return IncomingVal;
6528}
6529
Chris Lattnerdd730472004-04-17 22:58:41 +00006530/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6531/// in the header of its containing loop, we know the loop executes a
6532/// constant number of times, and the PHI node is just a recurrence
6533/// involving constants, fold it.
Dan Gohmance973df2009-06-24 04:48:43 +00006534Constant *
6535ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohmancb0efec2009-12-18 01:14:11 +00006536 const APInt &BEs,
Dan Gohmance973df2009-06-24 04:48:43 +00006537 const Loop *L) {
Sanjoy Das4493b402015-10-07 17:38:25 +00006538 auto I = ConstantEvolutionLoopExitValue.find(PN);
Chris Lattnerdd730472004-04-17 22:58:41 +00006539 if (I != ConstantEvolutionLoopExitValue.end())
6540 return I->second;
6541
Dan Gohman4ce1fb12010-04-08 23:03:40 +00006542 if (BEs.ugt(MaxBruteForceIterations))
Craig Topper9f008862014-04-15 04:59:12 +00006543 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
Chris Lattnerdd730472004-04-17 22:58:41 +00006544
6545 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6546
Andrew Trick3a86ba72011-10-05 03:25:31 +00006547 DenseMap<Instruction *, Constant *> CurrentIterVals;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006548 BasicBlock *Header = L->getHeader();
6549 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
Andrew Trick3a86ba72011-10-05 03:25:31 +00006550
Sanjoy Dasdd709962015-10-08 18:28:36 +00006551 BasicBlock *Latch = L->getLoopLatch();
6552 if (!Latch)
6553 return nullptr;
6554
Sanjoy Das4493b402015-10-07 17:38:25 +00006555 for (auto &I : *Header) {
6556 PHINode *PHI = dyn_cast<PHINode>(&I);
6557 if (!PHI) break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006558 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006559 if (!StartCST) continue;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006560 CurrentIterVals[PHI] = StartCST;
6561 }
6562 if (!CurrentIterVals.count(PN))
Craig Topper9f008862014-04-15 04:59:12 +00006563 return RetVal = nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006564
Sanjoy Dasdd709962015-10-08 18:28:36 +00006565 Value *BEValue = PN->getIncomingValueForBlock(Latch);
Chris Lattnerdd730472004-04-17 22:58:41 +00006566
6567 // Execute the loop symbolically to determine the exit value.
Dan Gohman0bddac12009-02-24 18:55:53 +00006568 if (BEs.getActiveBits() >= 32)
Craig Topper9f008862014-04-15 04:59:12 +00006569 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
Chris Lattnerdd730472004-04-17 22:58:41 +00006570
Dan Gohman0bddac12009-02-24 18:55:53 +00006571 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencer983e3b32007-03-01 07:25:48 +00006572 unsigned IterationNum = 0;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006573 const DataLayout &DL = getDataLayout();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006574 for (; ; ++IterationNum) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006575 if (IterationNum == NumIterations)
Andrew Trick3a86ba72011-10-05 03:25:31 +00006576 return RetVal = CurrentIterVals[PN]; // Got exit value!
Chris Lattnerdd730472004-04-17 22:58:41 +00006577
Nick Lewyckya6674c72011-10-22 19:58:20 +00006578 // Compute the value of the PHIs for the next iteration.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006579 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006580 DenseMap<Instruction *, Constant *> NextIterVals;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006581 Constant *NextPHI =
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006582 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Craig Topper9f008862014-04-15 04:59:12 +00006583 if (!NextPHI)
6584 return nullptr; // Couldn't evaluate!
Andrew Trick3a86ba72011-10-05 03:25:31 +00006585 NextIterVals[PN] = NextPHI;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006586
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006587 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6588
Nick Lewyckya6674c72011-10-22 19:58:20 +00006589 // Also evaluate the other PHI nodes. However, we don't get to stop if we
6590 // cease to be able to evaluate one of them or if they stop evolving,
6591 // because that doesn't necessarily prevent us from computing PN.
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006592 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006593 for (const auto &I : CurrentIterVals) {
6594 PHINode *PHI = dyn_cast<PHINode>(I.first);
Nick Lewycky8e904de2011-10-24 05:51:01 +00006595 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
Sanjoy Das4493b402015-10-07 17:38:25 +00006596 PHIsToCompute.emplace_back(PHI, I.second);
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006597 }
6598 // We use two distinct loops because EvaluateExpression may invalidate any
6599 // iterators into CurrentIterVals.
Sanjoy Das4493b402015-10-07 17:38:25 +00006600 for (const auto &I : PHIsToCompute) {
6601 PHINode *PHI = I.first;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006602 Constant *&NextPHI = NextIterVals[PHI];
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006603 if (!NextPHI) { // Not already computed.
Sanjoy Dasdd709962015-10-08 18:28:36 +00006604 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006605 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006606 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006607 if (NextPHI != I.second)
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006608 StoppedEvolving = false;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006609 }
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006610
6611 // If all entries in CurrentIterVals == NextIterVals then we can stop
6612 // iterating, the loop can't continue to change.
6613 if (StoppedEvolving)
6614 return RetVal = CurrentIterVals[PN];
6615
Andrew Trick3a86ba72011-10-05 03:25:31 +00006616 CurrentIterVals.swap(NextIterVals);
Chris Lattnerdd730472004-04-17 22:58:41 +00006617 }
6618}
6619
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006620const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
Nick Lewyckya6674c72011-10-22 19:58:20 +00006621 Value *Cond,
6622 bool ExitWhen) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006623 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Craig Topper9f008862014-04-15 04:59:12 +00006624 if (!PN) return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006625
Dan Gohman866971e2010-06-19 14:17:24 +00006626 // If the loop is canonicalized, the PHI will have exactly two entries.
6627 // That's the only form we support here.
6628 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6629
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006630 DenseMap<Instruction *, Constant *> CurrentIterVals;
6631 BasicBlock *Header = L->getHeader();
6632 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6633
Sanjoy Dasdd709962015-10-08 18:28:36 +00006634 BasicBlock *Latch = L->getLoopLatch();
6635 assert(Latch && "Should follow from NumIncomingValues == 2!");
6636
Sanjoy Das4493b402015-10-07 17:38:25 +00006637 for (auto &I : *Header) {
6638 PHINode *PHI = dyn_cast<PHINode>(&I);
6639 if (!PHI)
6640 break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006641 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006642 if (!StartCST) continue;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006643 CurrentIterVals[PHI] = StartCST;
6644 }
6645 if (!CurrentIterVals.count(PN))
6646 return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006647
6648 // Okay, we find a PHI node that defines the trip count of this loop. Execute
6649 // the loop symbolically to determine when the condition gets a value of
6650 // "ExitWhen".
Andrew Trick90c7a102011-11-16 00:52:40 +00006651 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006652 const DataLayout &DL = getDataLayout();
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006653 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
Sanjoy Das4493b402015-10-07 17:38:25 +00006654 auto *CondVal = dyn_cast_or_null<ConstantInt>(
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006655 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
Chris Lattnerdd730472004-04-17 22:58:41 +00006656
Zhou Sheng75b871f2007-01-11 12:24:14 +00006657 // Couldn't symbolically evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006658 if (!CondVal) return getCouldNotCompute();
Zhou Sheng75b871f2007-01-11 12:24:14 +00006659
Reid Spencer983e3b32007-03-01 07:25:48 +00006660 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006661 ++NumBruteForceTripCountsComputed;
Owen Anderson55f1c092009-08-13 21:58:54 +00006662 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006663 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006664
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006665 // Update all the PHI nodes for the next iteration.
6666 DenseMap<Instruction *, Constant *> NextIterVals;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006667
6668 // Create a list of which PHIs we need to compute. We want to do this before
6669 // calling EvaluateExpression on them because that may invalidate iterators
6670 // into CurrentIterVals.
6671 SmallVector<PHINode *, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006672 for (const auto &I : CurrentIterVals) {
6673 PHINode *PHI = dyn_cast<PHINode>(I.first);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006674 if (!PHI || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006675 PHIsToCompute.push_back(PHI);
6676 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006677 for (PHINode *PHI : PHIsToCompute) {
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006678 Constant *&NextPHI = NextIterVals[PHI];
6679 if (NextPHI) continue; // Already computed!
6680
Sanjoy Dasdd709962015-10-08 18:28:36 +00006681 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006682 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006683 }
6684 CurrentIterVals.swap(NextIterVals);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006685 }
6686
6687 // Too many iterations were needed to evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006688 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006689}
6690
Dan Gohmanaf752342009-07-07 17:06:11 +00006691const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Sanjoy Das01947432015-11-22 21:20:13 +00006692 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6693 ValuesAtScopes[V];
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006694 // Check to see if we've folded this expression at this loop before.
Sanjoy Das01947432015-11-22 21:20:13 +00006695 for (auto &LS : Values)
6696 if (LS.first == L)
6697 return LS.second ? LS.second : V;
6698
6699 Values.emplace_back(L, nullptr);
6700
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006701 // Otherwise compute it.
6702 const SCEV *C = computeSCEVAtScope(V, L);
Sanjoy Das01947432015-11-22 21:20:13 +00006703 for (auto &LS : reverse(ValuesAtScopes[V]))
6704 if (LS.first == L) {
6705 LS.second = C;
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00006706 break;
6707 }
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006708 return C;
6709}
6710
Nick Lewyckya6674c72011-10-22 19:58:20 +00006711/// This builds up a Constant using the ConstantExpr interface. That way, we
6712/// will return Constants for objects which aren't represented by a
6713/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6714/// Returns NULL if the SCEV isn't representable as a Constant.
6715static Constant *BuildConstantFromSCEV(const SCEV *V) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00006716 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
Nick Lewyckya6674c72011-10-22 19:58:20 +00006717 case scCouldNotCompute:
6718 case scAddRecExpr:
6719 break;
6720 case scConstant:
6721 return cast<SCEVConstant>(V)->getValue();
6722 case scUnknown:
6723 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6724 case scSignExtend: {
6725 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6726 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6727 return ConstantExpr::getSExt(CastOp, SS->getType());
6728 break;
6729 }
6730 case scZeroExtend: {
6731 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6732 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6733 return ConstantExpr::getZExt(CastOp, SZ->getType());
6734 break;
6735 }
6736 case scTruncate: {
6737 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6738 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6739 return ConstantExpr::getTrunc(CastOp, ST->getType());
6740 break;
6741 }
6742 case scAddExpr: {
6743 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6744 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006745 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6746 unsigned AS = PTy->getAddressSpace();
6747 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6748 C = ConstantExpr::getBitCast(C, DestPtrTy);
6749 }
Nick Lewyckya6674c72011-10-22 19:58:20 +00006750 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6751 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006752 if (!C2) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006753
6754 // First pointer!
6755 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006756 unsigned AS = C2->getType()->getPointerAddressSpace();
Nick Lewyckya6674c72011-10-22 19:58:20 +00006757 std::swap(C, C2);
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006758 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006759 // The offsets have been converted to bytes. We can add bytes to an
6760 // i8* by GEP with the byte count in the first index.
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006761 C = ConstantExpr::getBitCast(C, DestPtrTy);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006762 }
6763
6764 // Don't bother trying to sum two pointers. We probably can't
6765 // statically compute a load that results from it anyway.
6766 if (C2->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +00006767 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006768
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006769 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6770 if (PTy->getElementType()->isStructTy())
Nick Lewyckya6674c72011-10-22 19:58:20 +00006771 C2 = ConstantExpr::getIntegerCast(
6772 C2, Type::getInt32Ty(C->getContext()), true);
David Blaikie4a2e73b2015-04-02 18:55:32 +00006773 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006774 } else
6775 C = ConstantExpr::getAdd(C, C2);
6776 }
6777 return C;
6778 }
6779 break;
6780 }
6781 case scMulExpr: {
6782 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6783 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6784 // Don't bother with pointers at all.
Craig Topper9f008862014-04-15 04:59:12 +00006785 if (C->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006786 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6787 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006788 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006789 C = ConstantExpr::getMul(C, C2);
6790 }
6791 return C;
6792 }
6793 break;
6794 }
6795 case scUDivExpr: {
6796 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6797 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6798 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6799 if (LHS->getType() == RHS->getType())
6800 return ConstantExpr::getUDiv(LHS, RHS);
6801 break;
6802 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00006803 case scSMaxExpr:
6804 case scUMaxExpr:
6805 break; // TODO: smax, umax.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006806 }
Craig Topper9f008862014-04-15 04:59:12 +00006807 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006808}
6809
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006810const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006811 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00006812
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006813 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattnerdd730472004-04-17 22:58:41 +00006814 // exit value from the loop without using SCEVs.
Dan Gohmana30370b2009-05-04 22:02:23 +00006815 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006816 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006817 const Loop *LI = this->LI[I->getParent()];
Chris Lattnerdd730472004-04-17 22:58:41 +00006818 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
6819 if (PHINode *PN = dyn_cast<PHINode>(I))
6820 if (PN->getParent() == LI->getHeader()) {
6821 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman0bddac12009-02-24 18:55:53 +00006822 // to see if the loop that contains it has a known backedge-taken
6823 // count. If so, we may be able to force computation of the exit
6824 // value.
Dan Gohmanaf752342009-07-07 17:06:11 +00006825 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmana30370b2009-05-04 22:02:23 +00006826 if (const SCEVConstant *BTCC =
Dan Gohman0bddac12009-02-24 18:55:53 +00006827 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006828 // Okay, we know how many times the containing loop executes. If
6829 // this is a constant evolving PHI node, get the final value at
6830 // the specified iteration number.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006831 Constant *RV =
6832 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
Dan Gohman9d203c62009-06-29 21:31:18 +00006833 if (RV) return getSCEV(RV);
Chris Lattnerdd730472004-04-17 22:58:41 +00006834 }
6835 }
6836
Reid Spencere6328ca2006-12-04 21:33:23 +00006837 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattnerdd730472004-04-17 22:58:41 +00006838 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencere6328ca2006-12-04 21:33:23 +00006839 // the arguments into constants, and if so, try to constant propagate the
Chris Lattnerdd730472004-04-17 22:58:41 +00006840 // result. This is particularly useful for computing loop exit values.
6841 if (CanConstantFold(I)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006842 SmallVector<Constant *, 4> Operands;
6843 bool MadeImprovement = false;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00006844 for (Value *Op : I->operands()) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006845 if (Constant *C = dyn_cast<Constant>(Op)) {
6846 Operands.push_back(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006847 continue;
Chris Lattnerdd730472004-04-17 22:58:41 +00006848 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006849
6850 // If any of the operands is non-constant and if they are
6851 // non-integer and non-pointer, don't even try to analyze them
6852 // with scev techniques.
6853 if (!isSCEVable(Op->getType()))
6854 return V;
6855
6856 const SCEV *OrigV = getSCEV(Op);
6857 const SCEV *OpV = getSCEVAtScope(OrigV, L);
6858 MadeImprovement |= OrigV != OpV;
6859
Nick Lewyckya6674c72011-10-22 19:58:20 +00006860 Constant *C = BuildConstantFromSCEV(OpV);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006861 if (!C) return V;
6862 if (C->getType() != Op->getType())
6863 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
6864 Op->getType(),
6865 false),
6866 C, Op->getType());
6867 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00006868 }
Dan Gohmance973df2009-06-24 04:48:43 +00006869
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006870 // Check to see if getSCEVAtScope actually made an improvement.
6871 if (MadeImprovement) {
Craig Topper9f008862014-04-15 04:59:12 +00006872 Constant *C = nullptr;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006873 const DataLayout &DL = getDataLayout();
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006874 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006875 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006876 Operands[1], DL, &TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006877 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
6878 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006879 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006880 } else
Manuel Jacobe9024592016-01-21 06:33:22 +00006881 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006882 if (!C) return V;
Dan Gohman4aad7502010-02-24 19:31:47 +00006883 return getSCEV(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006884 }
Chris Lattnerdd730472004-04-17 22:58:41 +00006885 }
6886 }
6887
6888 // This is some other type of SCEVUnknown, just return it.
6889 return V;
6890 }
6891
Dan Gohmana30370b2009-05-04 22:02:23 +00006892 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006893 // Avoid performing the look-up in the common case where the specified
6894 // expression has no loop-variant portions.
6895 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006896 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006897 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006898 // Okay, at least one of these operands is loop variant but might be
6899 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmance973df2009-06-24 04:48:43 +00006900 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
6901 Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00006902 NewOps.push_back(OpAtScope);
6903
6904 for (++i; i != e; ++i) {
6905 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006906 NewOps.push_back(OpAtScope);
6907 }
6908 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006909 return getAddExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006910 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006911 return getMulExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006912 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006913 return getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006914 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006915 return getUMaxExpr(NewOps);
Torok Edwinfbcc6632009-07-14 16:55:14 +00006916 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00006917 }
6918 }
6919 // If we got here, all operands are loop invariant.
6920 return Comm;
6921 }
6922
Dan Gohmana30370b2009-05-04 22:02:23 +00006923 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006924 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
6925 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky52348302009-01-13 09:18:58 +00006926 if (LHS == Div->getLHS() && RHS == Div->getRHS())
6927 return Div; // must be loop invariant
Dan Gohmanc8e23622009-04-21 23:15:49 +00006928 return getUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00006929 }
6930
6931 // If this is a loop recurrence for a loop that does not contain L, then we
6932 // are dealing with the final value computed by the loop.
Dan Gohmana30370b2009-05-04 22:02:23 +00006933 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006934 // First, attempt to evaluate each operand.
6935 // Avoid performing the look-up in the common case where the specified
6936 // expression has no loop-variant portions.
6937 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
6938 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
6939 if (OpAtScope == AddRec->getOperand(i))
6940 continue;
6941
6942 // Okay, at least one of these operands is loop variant but might be
6943 // foldable. Build a new instance of the folded commutative expression.
6944 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
6945 AddRec->op_begin()+i);
6946 NewOps.push_back(OpAtScope);
6947 for (++i; i != e; ++i)
6948 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
6949
Andrew Trick759ba082011-04-27 01:21:25 +00006950 const SCEV *FoldedRec =
Andrew Trick8b55b732011-03-14 16:50:06 +00006951 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick759ba082011-04-27 01:21:25 +00006952 AddRec->getNoWrapFlags(SCEV::FlagNW));
6953 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick01eff822011-04-27 05:42:17 +00006954 // The addrec may be folded to a nonrecurrence, for example, if the
6955 // induction variable is multiplied by zero after constant folding. Go
6956 // ahead and return the folded value.
Andrew Trick759ba082011-04-27 01:21:25 +00006957 if (!AddRec)
6958 return FoldedRec;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006959 break;
6960 }
6961
6962 // If the scope is outside the addrec's loop, evaluate it by using the
6963 // loop exit value of the addrec.
6964 if (!AddRec->getLoop()->contains(L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006965 // To evaluate this recurrence, we need to know how many times the AddRec
6966 // loop iterates. Compute this now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006967 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006968 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman01808ca2005-04-21 21:13:18 +00006969
Eli Friedman61f67622008-08-04 23:49:06 +00006970 // Then, evaluate the AddRec.
Dan Gohmanc8e23622009-04-21 23:15:49 +00006971 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattnerd934c702004-04-02 20:23:17 +00006972 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006973
Dan Gohman8ca08852009-05-24 23:25:42 +00006974 return AddRec;
Chris Lattnerd934c702004-04-02 20:23:17 +00006975 }
6976
Dan Gohmana30370b2009-05-04 22:02:23 +00006977 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006978 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006979 if (Op == Cast->getOperand())
6980 return Cast; // must be loop invariant
6981 return getZeroExtendExpr(Op, Cast->getType());
6982 }
6983
Dan Gohmana30370b2009-05-04 22:02:23 +00006984 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006985 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006986 if (Op == Cast->getOperand())
6987 return Cast; // must be loop invariant
6988 return getSignExtendExpr(Op, Cast->getType());
6989 }
6990
Dan Gohmana30370b2009-05-04 22:02:23 +00006991 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006992 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006993 if (Op == Cast->getOperand())
6994 return Cast; // must be loop invariant
6995 return getTruncateExpr(Op, Cast->getType());
6996 }
6997
Torok Edwinfbcc6632009-07-14 16:55:14 +00006998 llvm_unreachable("Unknown SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00006999}
7000
Dan Gohmanaf752342009-07-07 17:06:11 +00007001const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00007002 return getSCEVAtScope(getSCEV(V), L);
7003}
7004
Sanjoy Dasf8570812016-05-29 00:38:22 +00007005/// Finds the minimum unsigned root of the following equation:
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007006///
7007/// A * X = B (mod N)
7008///
7009/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
7010/// A and B isn't important.
7011///
7012/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00007013static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007014 ScalarEvolution &SE) {
7015 uint32_t BW = A.getBitWidth();
7016 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
7017 assert(A != 0 && "A must be non-zero.");
7018
7019 // 1. D = gcd(A, N)
7020 //
7021 // The gcd of A and N may have only one prime factor: 2. The number of
7022 // trailing zeros in A is its multiplicity
7023 uint32_t Mult2 = A.countTrailingZeros();
7024 // D = 2^Mult2
7025
7026 // 2. Check if B is divisible by D.
7027 //
7028 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
7029 // is not less than multiplicity of this prime factor for D.
7030 if (B.countTrailingZeros() < Mult2)
Dan Gohman31efa302009-04-18 17:58:19 +00007031 return SE.getCouldNotCompute();
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007032
7033 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
7034 // modulo (N / D).
7035 //
7036 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
7037 // bit width during computations.
7038 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
7039 APInt Mod(BW + 1, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00007040 Mod.setBit(BW - Mult2); // Mod = N / D
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00007041 APInt I = AD.multiplicativeInverse(Mod);
7042
7043 // 4. Compute the minimum unsigned root of the equation:
7044 // I * (B / D) mod (N / D)
7045 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
7046
7047 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
7048 // bits.
7049 return SE.getConstant(Result.trunc(BW));
7050}
Chris Lattnerd934c702004-04-02 20:23:17 +00007051
Sanjoy Dasf8570812016-05-29 00:38:22 +00007052/// Find the roots of the quadratic equation for the given quadratic chrec
7053/// {L,+,M,+,N}. This returns either the two roots (which might be the same) or
7054/// two SCEVCouldNotCompute objects.
Chris Lattnerd934c702004-04-02 20:23:17 +00007055///
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007056static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
Dan Gohmana37eaf22007-10-22 18:31:58 +00007057SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007058 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman48f82222009-05-04 22:30:44 +00007059 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7060 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7061 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00007062
Chris Lattnerd934c702004-04-02 20:23:17 +00007063 // We currently can only solve this if the coefficients are constants.
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007064 if (!LC || !MC || !NC)
7065 return None;
Chris Lattnerd934c702004-04-02 20:23:17 +00007066
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007067 uint32_t BitWidth = LC->getAPInt().getBitWidth();
7068 const APInt &L = LC->getAPInt();
7069 const APInt &M = MC->getAPInt();
7070 const APInt &N = NC->getAPInt();
Reid Spencer983e3b32007-03-01 07:25:48 +00007071 APInt Two(BitWidth, 2);
7072 APInt Four(BitWidth, 4);
Misha Brukman01808ca2005-04-21 21:13:18 +00007073
Dan Gohmance973df2009-06-24 04:48:43 +00007074 {
Reid Spencer983e3b32007-03-01 07:25:48 +00007075 using namespace APIntOps;
Zhou Sheng2852d992007-04-07 17:48:27 +00007076 const APInt& C = L;
Reid Spencer983e3b32007-03-01 07:25:48 +00007077 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7078 // The B coefficient is M-N/2
7079 APInt B(M);
7080 B -= sdiv(N,Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00007081
Reid Spencer983e3b32007-03-01 07:25:48 +00007082 // The A coefficient is N/2
Zhou Sheng2852d992007-04-07 17:48:27 +00007083 APInt A(N.sdiv(Two));
Chris Lattnerd934c702004-04-02 20:23:17 +00007084
Reid Spencer983e3b32007-03-01 07:25:48 +00007085 // Compute the B^2-4ac term.
7086 APInt SqrtTerm(B);
7087 SqrtTerm *= B;
7088 SqrtTerm -= Four * (A * C);
Chris Lattnerd934c702004-04-02 20:23:17 +00007089
Nick Lewyckyfb780832012-08-01 09:14:36 +00007090 if (SqrtTerm.isNegative()) {
7091 // The loop is provably infinite.
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007092 return None;
Nick Lewyckyfb780832012-08-01 09:14:36 +00007093 }
7094
Reid Spencer983e3b32007-03-01 07:25:48 +00007095 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7096 // integer value or else APInt::sqrt() will assert.
7097 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman01808ca2005-04-21 21:13:18 +00007098
Dan Gohmance973df2009-06-24 04:48:43 +00007099 // Compute the two solutions for the quadratic formula.
Reid Spencer983e3b32007-03-01 07:25:48 +00007100 // The divisions must be performed as signed divisions.
7101 APInt NegB(-B);
Nick Lewycky31555522011-10-03 07:10:45 +00007102 APInt TwoA(A << 1);
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007103 if (TwoA.isMinValue())
7104 return None;
Nick Lewycky7b14e202008-11-03 02:43:49 +00007105
Owen Anderson47db9412009-07-22 00:24:57 +00007106 LLVMContext &Context = SE.getContext();
Owen Andersonf1f17432009-07-06 22:37:39 +00007107
7108 ConstantInt *Solution1 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007109 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Andersonf1f17432009-07-06 22:37:39 +00007110 ConstantInt *Solution2 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007111 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman01808ca2005-04-21 21:13:18 +00007112
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007113 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7114 cast<SCEVConstant>(SE.getConstant(Solution2)));
Nick Lewycky31555522011-10-03 07:10:45 +00007115 } // end APIntOps namespace
Chris Lattnerd934c702004-04-02 20:23:17 +00007116}
7117
Andrew Trick3ca3f982011-07-26 17:19:55 +00007118ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007119ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
Silviu Baranga6f444df2016-04-08 14:29:09 +00007120 bool AllowPredicates) {
Sanjoy Dasf8570812016-05-29 00:38:22 +00007121
7122 // This is only used for loops with a "x != y" exit test. The exit condition
7123 // is now expressed as a single expression, V = x-y. So the exit test is
7124 // effectively V != 0. We know and take advantage of the fact that this
7125 // expression only being used in a comparison by zero context.
7126
Sanjoy Dasf0022122016-09-28 17:14:58 +00007127 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Chris Lattnerd934c702004-04-02 20:23:17 +00007128 // If the value is a constant
Dan Gohmana30370b2009-05-04 22:02:23 +00007129 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007130 // If the value is already zero, the branch will execute zero times.
Reid Spencer2e54a152007-03-02 00:28:52 +00007131 if (C->getValue()->isZero()) return C;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007132 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007133 }
7134
Dan Gohman48f82222009-05-04 22:30:44 +00007135 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007136 if (!AddRec && AllowPredicates)
7137 // Try to make this an AddRec using runtime tests, in the first X
7138 // iterations of this loop, where X is the SCEV expression found by the
7139 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00007140 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007141
Chris Lattnerd934c702004-04-02 20:23:17 +00007142 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007143 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007144
Chris Lattnerdff679f2011-01-09 22:39:48 +00007145 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7146 // the quadratic equation to solve it.
7147 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00007148 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7149 const SCEVConstant *R1 = Roots->first;
7150 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00007151 // Pick the smallest positive root value.
Sanjoy Das0e392d52016-06-15 04:37:50 +00007152 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7153 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00007154 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00007155 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick2a3b7162011-03-09 17:23:39 +00007156
Chris Lattnerd934c702004-04-02 20:23:17 +00007157 // We can only use this value if the chrec ends up with an exact zero
7158 // value at this index. When solving for "X*X != 5", for example, we
7159 // should not accept a root of 2.
Dan Gohmanaf752342009-07-07 17:06:11 +00007160 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmanbe928e32008-06-18 16:23:07 +00007161 if (Val->isZero())
John Brawn84b21832016-10-21 11:08:48 +00007162 // We found a quadratic root!
7163 return ExitLimit(R1, R1, false, Predicates);
Chris Lattnerd934c702004-04-02 20:23:17 +00007164 }
7165 }
Chris Lattnerdff679f2011-01-09 22:39:48 +00007166 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007167 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007168
Chris Lattnerdff679f2011-01-09 22:39:48 +00007169 // Otherwise we can only handle this if it is affine.
7170 if (!AddRec->isAffine())
7171 return getCouldNotCompute();
7172
7173 // If this is an affine expression, the execution count of this branch is
7174 // the minimum unsigned root of the following equation:
7175 //
7176 // Start + Step*N = 0 (mod 2^BW)
7177 //
7178 // equivalent to:
7179 //
7180 // Step*N = -Start (mod 2^BW)
7181 //
7182 // where BW is the common bit width of Start and Step.
7183
7184 // Get the initial value for the loop.
7185 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7186 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7187
7188 // For now we handle only constant steps.
Andrew Trick8b55b732011-03-14 16:50:06 +00007189 //
7190 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7191 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7192 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7193 // We have not yet seen any such cases.
Chris Lattnerdff679f2011-01-09 22:39:48 +00007194 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
Craig Topper9f008862014-04-15 04:59:12 +00007195 if (!StepC || StepC->getValue()->equalsInt(0))
Chris Lattnerdff679f2011-01-09 22:39:48 +00007196 return getCouldNotCompute();
7197
Andrew Trick8b55b732011-03-14 16:50:06 +00007198 // For positive steps (counting up until unsigned overflow):
7199 // N = -Start/Step (as unsigned)
7200 // For negative steps (counting down to zero):
7201 // N = Start/-Step
7202 // First compute the unsigned distance from zero in the direction of Step.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007203 bool CountDown = StepC->getAPInt().isNegative();
Andrew Trickf1781db2011-03-14 17:28:02 +00007204 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick8b55b732011-03-14 16:50:06 +00007205
7206 // Handle unitary steps, which cannot wraparound.
Andrew Trickf1781db2011-03-14 17:28:02 +00007207 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7208 // N = Distance (as unsigned)
Nick Lewycky31555522011-10-03 07:10:45 +00007209 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
7210 ConstantRange CR = getUnsignedRange(Start);
7211 const SCEV *MaxBECount;
7212 if (!CountDown && CR.getUnsignedMin().isMinValue())
7213 // When counting up, the worst starting value is 1, not 0.
7214 MaxBECount = CR.getUnsignedMax().isMinValue()
7215 ? getConstant(APInt::getMinValue(CR.getBitWidth()))
7216 : getConstant(APInt::getMaxValue(CR.getBitWidth()));
7217 else
7218 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
7219 : -CR.getUnsignedMin());
John Brawn84b21832016-10-21 11:08:48 +00007220 return ExitLimit(Distance, MaxBECount, false, Predicates);
Nick Lewycky31555522011-10-03 07:10:45 +00007221 }
Andrew Trick2a3b7162011-03-09 17:23:39 +00007222
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007223 // As a special case, handle the instance where Step is a positive power of
7224 // two. In this case, determining whether Step divides Distance evenly can be
7225 // done by counting and comparing the number of trailing zeros of Step and
7226 // Distance.
7227 if (!CountDown) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007228 const APInt &StepV = StepC->getAPInt();
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007229 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It
7230 // also returns true if StepV is maximally negative (eg, INT_MIN), but that
7231 // case is not handled as this code is guarded by !CountDown.
7232 if (StepV.isPowerOf2() &&
Sanjoy Dasf3132d32015-09-10 05:27:38 +00007233 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) {
7234 // Here we've constrained the equation to be of the form
7235 //
7236 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0)
7237 //
7238 // where we're operating on a W bit wide integer domain and k is
7239 // non-negative. The smallest unsigned solution for X is the trip count.
7240 //
7241 // (0) is equivalent to:
7242 //
7243 // 2^(N + k) * Distance' - 2^N * X = L * 2^W
7244 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N
7245 // <=> 2^k * Distance' - X = L * 2^(W - N)
7246 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1)
7247 //
7248 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS
7249 // by 2^(W - N).
7250 //
7251 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2)
7252 //
7253 // E.g. say we're solving
7254 //
7255 // 2 * Val = 2 * X (in i8) ... (3)
7256 //
7257 // then from (2), we get X = Val URem i8 128 (k = 0 in this case).
7258 //
7259 // Note: It is tempting to solve (3) by setting X = Val, but Val is not
7260 // necessarily the smallest unsigned value of X that satisfies (3).
7261 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3)
7262 // is i8 1, not i8 -127
7263
7264 const auto *ModuloResult = getUDivExactExpr(Distance, Step);
7265
7266 // Since SCEV does not have a URem node, we construct one using a truncate
7267 // and a zero extend.
7268
7269 unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros();
7270 auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth);
7271 auto *WideTy = Distance->getType();
7272
Silviu Baranga6f444df2016-04-08 14:29:09 +00007273 const SCEV *Limit =
7274 getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy);
John Brawn84b21832016-10-21 11:08:48 +00007275 return ExitLimit(Limit, Limit, false, Predicates);
Sanjoy Dasf3132d32015-09-10 05:27:38 +00007276 }
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007277 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007278
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007279 // If the condition controls loop exit (the loop exits only if the expression
7280 // is true) and the addition is no-wrap we can use unsigned divide to
7281 // compute the backedge count. In this case, the step may not divide the
7282 // distance, but we don't care because if the condition is "missed" the loop
7283 // will have undefined behavior due to wrapping.
Sanjoy Dasc7f69b92016-06-09 01:13:59 +00007284 if (ControlsExit && AddRec->hasNoSelfWrap() &&
7285 loopHasNoAbnormalExits(AddRec->getLoop())) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007286 const SCEV *Exact =
7287 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
John Brawn84b21832016-10-21 11:08:48 +00007288 return ExitLimit(Exact, Exact, false, Predicates);
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007289 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007290
Chris Lattnerdff679f2011-01-09 22:39:48 +00007291 // Then, try to solve the above equation provided that Start is constant.
Silviu Baranga6f444df2016-04-08 14:29:09 +00007292 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
7293 const SCEV *E = SolveLinEquationWithOverflow(
7294 StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this);
John Brawn84b21832016-10-21 11:08:48 +00007295 return ExitLimit(E, E, false, Predicates);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007296 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007297 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007298}
7299
Andrew Trick3ca3f982011-07-26 17:19:55 +00007300ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00007301ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007302 // Loops that look like: while (X == 0) are very strange indeed. We don't
7303 // handle them yet except for the trivial case. This could be expanded in the
7304 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00007305
Chris Lattnerd934c702004-04-02 20:23:17 +00007306 // If the value is a constant, check to see if it is known to be non-zero
7307 // already. If so, the backedge will execute zero times.
Dan Gohmana30370b2009-05-04 22:02:23 +00007308 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky5a3db142008-02-21 09:14:53 +00007309 if (!C->getValue()->isNullValue())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00007310 return getZero(C->getType());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007311 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007312 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007313
Chris Lattnerd934c702004-04-02 20:23:17 +00007314 // We could implement others, but I really doubt anyone writes loops like
7315 // this, and if they did, they would already be constant folded.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007316 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007317}
7318
Dan Gohman4e3c1132010-04-15 16:19:08 +00007319std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanc8e23622009-04-21 23:15:49 +00007320ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohmanfa066ef2009-04-30 20:48:53 +00007321 // If the block has a unique predecessor, then there is no path from the
7322 // predecessor to the block that does not go through the direct edge
7323 // from the predecessor to the block.
Dan Gohmanf9081a22008-09-15 22:18:04 +00007324 if (BasicBlock *Pred = BB->getSinglePredecessor())
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007325 return {Pred, BB};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007326
7327 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman8c77f1a2009-05-18 15:36:09 +00007328 // If the header has a unique predecessor outside the loop, it must be
7329 // a block that has exactly one successor that can reach the loop.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007330 if (Loop *L = LI.getLoopFor(BB))
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007331 return {L->getLoopPredecessor(), L->getHeader()};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007332
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007333 return {nullptr, nullptr};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007334}
7335
Sanjoy Dasf8570812016-05-29 00:38:22 +00007336/// SCEV structural equivalence is usually sufficient for testing whether two
7337/// expressions are equal, however for the purposes of looking for a condition
7338/// guarding a loop, it can be useful to be a little more general, since a
7339/// front-end may have replicated the controlling expression.
Dan Gohman450f4e02009-06-20 00:35:32 +00007340///
Dan Gohmanaf752342009-07-07 17:06:11 +00007341static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman450f4e02009-06-20 00:35:32 +00007342 // Quick check to see if they are the same SCEV.
7343 if (A == B) return true;
7344
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007345 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7346 // Not all instructions that are "identical" compute the same value. For
7347 // instance, two distinct alloca instructions allocating the same type are
7348 // identical and do not read memory; but compute distinct values.
7349 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7350 };
7351
Dan Gohman450f4e02009-06-20 00:35:32 +00007352 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7353 // two different instructions with the same value. Check for this case.
7354 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7355 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7356 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7357 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007358 if (ComputesEqualValues(AI, BI))
Dan Gohman450f4e02009-06-20 00:35:32 +00007359 return true;
7360
7361 // Otherwise assume they may have a different value.
7362 return false;
7363}
7364
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007365bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007366 const SCEV *&LHS, const SCEV *&RHS,
7367 unsigned Depth) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007368 bool Changed = false;
7369
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007370 // If we hit the max recursion limit bail out.
7371 if (Depth >= 3)
7372 return false;
7373
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007374 // Canonicalize a constant to the right side.
7375 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7376 // Check for both operands constant.
7377 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7378 if (ConstantExpr::getICmp(Pred,
7379 LHSC->getValue(),
7380 RHSC->getValue())->isNullValue())
7381 goto trivially_false;
7382 else
7383 goto trivially_true;
7384 }
7385 // Otherwise swap the operands to put the constant on the right.
7386 std::swap(LHS, RHS);
7387 Pred = ICmpInst::getSwappedPredicate(Pred);
7388 Changed = true;
7389 }
7390
7391 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohmandf564ca2010-05-03 17:00:11 +00007392 // addrec's loop, put the addrec on the left. Also make a dominance check,
7393 // as both operands could be addrecs loop-invariant in each other's loop.
7394 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7395 const Loop *L = AR->getLoop();
Dan Gohman20d9ce22010-11-17 21:41:58 +00007396 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007397 std::swap(LHS, RHS);
7398 Pred = ICmpInst::getSwappedPredicate(Pred);
7399 Changed = true;
7400 }
Dan Gohmandf564ca2010-05-03 17:00:11 +00007401 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007402
7403 // If there's a constant operand, canonicalize comparisons with boundary
7404 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7405 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007406 const APInt &RA = RC->getAPInt();
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007407
7408 bool SimplifiedByConstantRange = false;
7409
7410 if (!ICmpInst::isEquality(Pred)) {
7411 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
7412 if (ExactCR.isFullSet())
7413 goto trivially_true;
7414 else if (ExactCR.isEmptySet())
7415 goto trivially_false;
7416
7417 APInt NewRHS;
7418 CmpInst::Predicate NewPred;
7419 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
7420 ICmpInst::isEquality(NewPred)) {
7421 // We were able to convert an inequality to an equality.
7422 Pred = NewPred;
7423 RHS = getConstant(NewRHS);
7424 Changed = SimplifiedByConstantRange = true;
7425 }
7426 }
7427
7428 if (!SimplifiedByConstantRange) {
7429 switch (Pred) {
7430 default:
7431 break;
7432 case ICmpInst::ICMP_EQ:
7433 case ICmpInst::ICMP_NE:
7434 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7435 if (!RA)
7436 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7437 if (const SCEVMulExpr *ME =
7438 dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
7439 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7440 ME->getOperand(0)->isAllOnesValue()) {
7441 RHS = AE->getOperand(1);
7442 LHS = ME->getOperand(1);
7443 Changed = true;
7444 }
7445 break;
7446
7447
7448 // The "Should have been caught earlier!" messages refer to the fact
7449 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
7450 // should have fired on the corresponding cases, and canonicalized the
7451 // check to trivially_true or trivially_false.
7452
7453 case ICmpInst::ICMP_UGE:
7454 assert(!RA.isMinValue() && "Should have been caught earlier!");
7455 Pred = ICmpInst::ICMP_UGT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007456 RHS = getConstant(RA - 1);
7457 Changed = true;
7458 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007459 case ICmpInst::ICMP_ULE:
7460 assert(!RA.isMaxValue() && "Should have been caught earlier!");
7461 Pred = ICmpInst::ICMP_ULT;
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007462 RHS = getConstant(RA + 1);
7463 Changed = true;
7464 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007465 case ICmpInst::ICMP_SGE:
7466 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
7467 Pred = ICmpInst::ICMP_SGT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007468 RHS = getConstant(RA - 1);
7469 Changed = true;
7470 break;
Sanjoy Das4aeb0f22016-10-02 20:59:10 +00007471 case ICmpInst::ICMP_SLE:
7472 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
7473 Pred = ICmpInst::ICMP_SLT;
Sanjoy Dasf230b0a2016-10-02 02:40:27 +00007474 RHS = getConstant(RA + 1);
7475 Changed = true;
7476 break;
7477 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007478 }
7479 }
7480
7481 // Check for obvious equality.
7482 if (HasSameValue(LHS, RHS)) {
7483 if (ICmpInst::isTrueWhenEqual(Pred))
7484 goto trivially_true;
7485 if (ICmpInst::isFalseWhenEqual(Pred))
7486 goto trivially_false;
7487 }
7488
Dan Gohman81585c12010-05-03 16:35:17 +00007489 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7490 // adding or subtracting 1 from one of the operands.
7491 switch (Pred) {
7492 case ICmpInst::ICMP_SLE:
7493 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7494 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007495 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007496 Pred = ICmpInst::ICMP_SLT;
7497 Changed = true;
7498 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007499 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007500 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007501 Pred = ICmpInst::ICMP_SLT;
7502 Changed = true;
7503 }
7504 break;
7505 case ICmpInst::ICMP_SGE:
7506 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007507 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007508 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007509 Pred = ICmpInst::ICMP_SGT;
7510 Changed = true;
7511 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7512 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007513 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007514 Pred = ICmpInst::ICMP_SGT;
7515 Changed = true;
7516 }
7517 break;
7518 case ICmpInst::ICMP_ULE:
7519 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007520 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007521 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007522 Pred = ICmpInst::ICMP_ULT;
7523 Changed = true;
7524 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007525 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007526 Pred = ICmpInst::ICMP_ULT;
7527 Changed = true;
7528 }
7529 break;
7530 case ICmpInst::ICMP_UGE:
7531 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007532 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007533 Pred = ICmpInst::ICMP_UGT;
7534 Changed = true;
7535 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007536 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007537 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007538 Pred = ICmpInst::ICMP_UGT;
7539 Changed = true;
7540 }
7541 break;
7542 default:
7543 break;
7544 }
7545
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007546 // TODO: More simplifications are possible here.
7547
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007548 // Recursively simplify until we either hit a recursion limit or nothing
7549 // changes.
7550 if (Changed)
7551 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7552
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007553 return Changed;
7554
7555trivially_true:
7556 // Return 0 == 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007557 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007558 Pred = ICmpInst::ICMP_EQ;
7559 return true;
7560
7561trivially_false:
7562 // Return 0 != 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007563 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007564 Pred = ICmpInst::ICMP_NE;
7565 return true;
7566}
7567
Dan Gohmane65c9172009-07-13 21:35:55 +00007568bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7569 return getSignedRange(S).getSignedMax().isNegative();
7570}
7571
7572bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7573 return getSignedRange(S).getSignedMin().isStrictlyPositive();
7574}
7575
7576bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7577 return !getSignedRange(S).getSignedMin().isNegative();
7578}
7579
7580bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7581 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7582}
7583
7584bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7585 return isKnownNegative(S) || isKnownPositive(S);
7586}
7587
7588bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7589 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman36cce7e2010-04-24 01:38:36 +00007590 // Canonicalize the inputs first.
7591 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7592
Dan Gohman07591692010-04-11 22:16:48 +00007593 // If LHS or RHS is an addrec, check to see if the condition is true in
7594 // every iteration of the loop.
Justin Bognercbb84382014-05-23 00:06:56 +00007595 // If LHS and RHS are both addrec, both conditions must be true in
7596 // every iteration of the loop.
7597 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7598 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7599 bool LeftGuarded = false;
7600 bool RightGuarded = false;
7601 if (LAR) {
7602 const Loop *L = LAR->getLoop();
7603 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7604 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7605 if (!RAR) return true;
7606 LeftGuarded = true;
7607 }
7608 }
7609 if (RAR) {
7610 const Loop *L = RAR->getLoop();
7611 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7612 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7613 if (!LAR) return true;
7614 RightGuarded = true;
7615 }
7616 }
7617 if (LeftGuarded && RightGuarded)
7618 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007619
Sanjoy Das7d910f22015-10-02 18:50:30 +00007620 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7621 return true;
7622
Dan Gohman07591692010-04-11 22:16:48 +00007623 // Otherwise see what can be done with known constant ranges.
Sanjoy Das401e6312016-02-01 20:48:10 +00007624 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
Dan Gohman07591692010-04-11 22:16:48 +00007625}
7626
Sanjoy Das5dab2052015-07-27 21:42:49 +00007627bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7628 ICmpInst::Predicate Pred,
7629 bool &Increasing) {
7630 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7631
7632#ifndef NDEBUG
7633 // Verify an invariant: inverting the predicate should turn a monotonically
7634 // increasing change to a monotonically decreasing one, and vice versa.
7635 bool IncreasingSwapped;
7636 bool ResultSwapped = isMonotonicPredicateImpl(
7637 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7638
7639 assert(Result == ResultSwapped && "should be able to analyze both!");
7640 if (ResultSwapped)
7641 assert(Increasing == !IncreasingSwapped &&
7642 "monotonicity should flip as we flip the predicate");
7643#endif
7644
7645 return Result;
7646}
7647
7648bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7649 ICmpInst::Predicate Pred,
7650 bool &Increasing) {
Sanjoy Das5dab2052015-07-27 21:42:49 +00007651
7652 // A zero step value for LHS means the induction variable is essentially a
7653 // loop invariant value. We don't really depend on the predicate actually
7654 // flipping from false to true (for increasing predicates, and the other way
7655 // around for decreasing predicates), all we care about is that *if* the
7656 // predicate changes then it only changes from false to true.
7657 //
7658 // A zero step value in itself is not very useful, but there may be places
7659 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7660 // as general as possible.
7661
Sanjoy Das366acc12015-08-06 20:43:41 +00007662 switch (Pred) {
7663 default:
7664 return false; // Conservative answer
7665
7666 case ICmpInst::ICMP_UGT:
7667 case ICmpInst::ICMP_UGE:
7668 case ICmpInst::ICMP_ULT:
7669 case ICmpInst::ICMP_ULE:
Sanjoy Das76c48e02016-02-04 18:21:54 +00007670 if (!LHS->hasNoUnsignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007671 return false;
7672
7673 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007674 return true;
Sanjoy Das366acc12015-08-06 20:43:41 +00007675
7676 case ICmpInst::ICMP_SGT:
7677 case ICmpInst::ICMP_SGE:
7678 case ICmpInst::ICMP_SLT:
7679 case ICmpInst::ICMP_SLE: {
Sanjoy Das76c48e02016-02-04 18:21:54 +00007680 if (!LHS->hasNoSignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007681 return false;
7682
7683 const SCEV *Step = LHS->getStepRecurrence(*this);
7684
7685 if (isKnownNonNegative(Step)) {
7686 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7687 return true;
7688 }
7689
7690 if (isKnownNonPositive(Step)) {
7691 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7692 return true;
7693 }
7694
7695 return false;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007696 }
7697
Sanjoy Das5dab2052015-07-27 21:42:49 +00007698 }
7699
Sanjoy Das366acc12015-08-06 20:43:41 +00007700 llvm_unreachable("switch has default clause!");
Sanjoy Das5dab2052015-07-27 21:42:49 +00007701}
7702
7703bool ScalarEvolution::isLoopInvariantPredicate(
7704 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7705 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7706 const SCEV *&InvariantRHS) {
7707
7708 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7709 if (!isLoopInvariant(RHS, L)) {
7710 if (!isLoopInvariant(LHS, L))
7711 return false;
7712
7713 std::swap(LHS, RHS);
7714 Pred = ICmpInst::getSwappedPredicate(Pred);
7715 }
7716
7717 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7718 if (!ArLHS || ArLHS->getLoop() != L)
7719 return false;
7720
7721 bool Increasing;
7722 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7723 return false;
7724
7725 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7726 // true as the loop iterates, and the backedge is control dependent on
7727 // "ArLHS `Pred` RHS" == true then we can reason as follows:
7728 //
7729 // * if the predicate was false in the first iteration then the predicate
7730 // is never evaluated again, since the loop exits without taking the
7731 // backedge.
7732 // * if the predicate was true in the first iteration then it will
7733 // continue to be true for all future iterations since it is
7734 // monotonically increasing.
7735 //
7736 // For both the above possibilities, we can replace the loop varying
7737 // predicate with its value on the first iteration of the loop (which is
7738 // loop invariant).
7739 //
7740 // A similar reasoning applies for a monotonically decreasing predicate, by
7741 // replacing true with false and false with true in the above two bullets.
7742
7743 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7744
7745 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7746 return false;
7747
7748 InvariantPred = Pred;
7749 InvariantLHS = ArLHS->getStart();
7750 InvariantRHS = RHS;
7751 return true;
7752}
7753
Sanjoy Das401e6312016-02-01 20:48:10 +00007754bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7755 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00007756 if (HasSameValue(LHS, RHS))
7757 return ICmpInst::isTrueWhenEqual(Pred);
7758
Dan Gohman07591692010-04-11 22:16:48 +00007759 // This code is split out from isKnownPredicate because it is called from
7760 // within isLoopEntryGuardedByCond.
Dan Gohmane65c9172009-07-13 21:35:55 +00007761
Sanjoy Das4c7b6d72016-02-01 20:48:14 +00007762 auto CheckRanges =
7763 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7764 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7765 .contains(RangeLHS);
7766 };
7767
7768 // The check at the top of the function catches the case where the values are
7769 // known to be equal.
7770 if (Pred == CmpInst::ICMP_EQ)
7771 return false;
7772
7773 if (Pred == CmpInst::ICMP_NE)
7774 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7775 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7776 isKnownNonZero(getMinusSCEV(LHS, RHS));
7777
7778 if (CmpInst::isSigned(Pred))
7779 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7780
7781 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
Dan Gohmane65c9172009-07-13 21:35:55 +00007782}
7783
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007784bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7785 const SCEV *LHS,
7786 const SCEV *RHS) {
7787
7788 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7789 // Return Y via OutY.
7790 auto MatchBinaryAddToConst =
7791 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7792 SCEV::NoWrapFlags ExpectedFlags) {
7793 const SCEV *NonConstOp, *ConstOp;
7794 SCEV::NoWrapFlags FlagsPresent;
7795
7796 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7797 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7798 return false;
7799
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007800 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007801 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7802 };
7803
7804 APInt C;
7805
7806 switch (Pred) {
7807 default:
7808 break;
7809
7810 case ICmpInst::ICMP_SGE:
7811 std::swap(LHS, RHS);
7812 case ICmpInst::ICMP_SLE:
7813 // X s<= (X + C)<nsw> if C >= 0
7814 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7815 return true;
7816
7817 // (X + C)<nsw> s<= X if C <= 0
7818 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7819 !C.isStrictlyPositive())
7820 return true;
7821 break;
7822
7823 case ICmpInst::ICMP_SGT:
7824 std::swap(LHS, RHS);
7825 case ICmpInst::ICMP_SLT:
7826 // X s< (X + C)<nsw> if C > 0
7827 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7828 C.isStrictlyPositive())
7829 return true;
7830
7831 // (X + C)<nsw> s< X if C < 0
7832 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7833 return true;
7834 break;
7835 }
7836
7837 return false;
7838}
7839
Sanjoy Das7d910f22015-10-02 18:50:30 +00007840bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7841 const SCEV *LHS,
7842 const SCEV *RHS) {
Sanjoy Das10dffcb2015-10-08 03:46:00 +00007843 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
Sanjoy Das7d910f22015-10-02 18:50:30 +00007844 return false;
7845
7846 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7847 // the stack can result in exponential time complexity.
7848 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7849
7850 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7851 //
7852 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7853 // isKnownPredicate. isKnownPredicate is more powerful, but also more
7854 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7855 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
7856 // use isKnownPredicate later if needed.
Alexander Kornienko484e48e32015-11-05 21:07:12 +00007857 return isKnownNonNegative(RHS) &&
7858 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7859 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
Sanjoy Das7d910f22015-10-02 18:50:30 +00007860}
7861
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007862bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
7863 ICmpInst::Predicate Pred,
7864 const SCEV *LHS, const SCEV *RHS) {
7865 // No need to even try if we know the module has no guards.
7866 if (!HasGuards)
7867 return false;
7868
7869 return any_of(*BB, [&](Instruction &I) {
7870 using namespace llvm::PatternMatch;
7871
7872 Value *Condition;
7873 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
7874 m_Value(Condition))) &&
7875 isImpliedCond(Pred, LHS, RHS, Condition, false);
7876 });
7877}
7878
Dan Gohmane65c9172009-07-13 21:35:55 +00007879/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7880/// protected by a conditional between LHS and RHS. This is used to
7881/// to eliminate casts.
7882bool
7883ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7884 ICmpInst::Predicate Pred,
7885 const SCEV *LHS, const SCEV *RHS) {
7886 // Interpret a null as meaning no loop, where there is obviously no guard
7887 // (interprocedural conditions notwithstanding).
7888 if (!L) return true;
7889
Sanjoy Das401e6312016-02-01 20:48:10 +00007890 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7891 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00007892
Dan Gohmane65c9172009-07-13 21:35:55 +00007893 BasicBlock *Latch = L->getLoopLatch();
7894 if (!Latch)
7895 return false;
7896
7897 BranchInst *LoopContinuePredicate =
7898 dyn_cast<BranchInst>(Latch->getTerminator());
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007899 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7900 isImpliedCond(Pred, LHS, RHS,
7901 LoopContinuePredicate->getCondition(),
7902 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7903 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007904
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007905 // We don't want more than one activation of the following loops on the stack
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007906 // -- that can lead to O(n!) time complexity.
7907 if (WalkingBEDominatingConds)
7908 return false;
7909
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +00007910 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007911
Sanjoy Dasb174f9a2015-09-25 23:53:50 +00007912 // See if we can exploit a trip count to prove the predicate.
7913 const auto &BETakenInfo = getBackedgeTakenInfo(L);
7914 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
7915 if (LatchBECount != getCouldNotCompute()) {
7916 // We know that Latch branches back to the loop header exactly
7917 // LatchBECount times. This means the backdege condition at Latch is
7918 // equivalent to "{0,+,1} u< LatchBECount".
7919 Type *Ty = LatchBECount->getType();
7920 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
7921 const SCEV *LoopCounter =
7922 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
7923 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
7924 LatchBECount))
7925 return true;
7926 }
7927
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007928 // Check conditions due to any @llvm.assume intrinsics.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00007929 for (auto &AssumeVH : AC.assumptions()) {
7930 if (!AssumeVH)
7931 continue;
7932 auto *CI = cast<CallInst>(AssumeVH);
7933 if (!DT.dominates(CI, Latch->getTerminator()))
7934 continue;
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007935
Daniel Jasperaec2fa32016-12-19 08:22:17 +00007936 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7937 return true;
7938 }
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007939
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007940 // If the loop is not reachable from the entry block, we risk running into an
7941 // infinite loop as we walk up into the dom tree. These loops do not matter
7942 // anyway, so we just return a conservative answer when we see them.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007943 if (!DT.isReachableFromEntry(L->getHeader()))
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007944 return false;
7945
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007946 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
7947 return true;
7948
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007949 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
7950 DTN != HeaderDTN; DTN = DTN->getIDom()) {
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007951
7952 assert(DTN && "should reach the loop header before reaching the root!");
7953
7954 BasicBlock *BB = DTN->getBlock();
Sanjoy Das2512d0c2016-05-10 00:31:49 +00007955 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
7956 return true;
7957
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007958 BasicBlock *PBB = BB->getSinglePredecessor();
7959 if (!PBB)
7960 continue;
7961
7962 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
7963 if (!ContinuePredicate || !ContinuePredicate->isConditional())
7964 continue;
7965
7966 Value *Condition = ContinuePredicate->getCondition();
7967
7968 // If we have an edge `E` within the loop body that dominates the only
7969 // latch, the condition guarding `E` also guards the backedge. This
7970 // reasoning works only for loops with a single latch.
7971
7972 BasicBlockEdge DominatingEdge(PBB, BB);
7973 if (DominatingEdge.isSingleEdge()) {
7974 // We're constructively (and conservatively) enumerating edges within the
7975 // loop body that dominate the latch. The dominator tree better agree
7976 // with us on this:
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007977 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007978
7979 if (isImpliedCond(Pred, LHS, RHS, Condition,
7980 BB != ContinuePredicate->getSuccessor(0)))
7981 return true;
7982 }
7983 }
7984
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007985 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00007986}
7987
Dan Gohmane65c9172009-07-13 21:35:55 +00007988bool
Dan Gohmanb50349a2010-04-11 19:27:13 +00007989ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
7990 ICmpInst::Predicate Pred,
7991 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman9cf09f82009-05-18 16:03:58 +00007992 // Interpret a null as meaning no loop, where there is obviously no guard
7993 // (interprocedural conditions notwithstanding).
7994 if (!L) return false;
7995
Sanjoy Das401e6312016-02-01 20:48:10 +00007996 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7997 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00007998
Dan Gohman8c77f1a2009-05-18 15:36:09 +00007999 // Starting at the loop predecessor, climb up the predecessor chain, as long
8000 // as there are predecessors that can be found that have unique successors
Dan Gohmanf9081a22008-09-15 22:18:04 +00008001 // leading to the original header.
Dan Gohman4e3c1132010-04-15 16:19:08 +00008002 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman75c6b0b2010-06-22 23:43:28 +00008003 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman4e3c1132010-04-15 16:19:08 +00008004 Pair.first;
8005 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman2a62fd92008-08-12 20:17:31 +00008006
Sanjoy Das2512d0c2016-05-10 00:31:49 +00008007 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8008 return true;
8009
Dan Gohman2a62fd92008-08-12 20:17:31 +00008010 BranchInst *LoopEntryPredicate =
Dan Gohman4e3c1132010-04-15 16:19:08 +00008011 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman2a62fd92008-08-12 20:17:31 +00008012 if (!LoopEntryPredicate ||
8013 LoopEntryPredicate->isUnconditional())
8014 continue;
8015
Dan Gohmane18c2d62010-08-10 23:46:30 +00008016 if (isImpliedCond(Pred, LHS, RHS,
8017 LoopEntryPredicate->getCondition(),
Dan Gohman4e3c1132010-04-15 16:19:08 +00008018 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman2a62fd92008-08-12 20:17:31 +00008019 return true;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008020 }
8021
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008022 // Check conditions due to any @llvm.assume intrinsics.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00008023 for (auto &AssumeVH : AC.assumptions()) {
8024 if (!AssumeVH)
8025 continue;
8026 auto *CI = cast<CallInst>(AssumeVH);
8027 if (!DT.dominates(CI, L->getHeader()))
8028 continue;
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008029
Daniel Jasperaec2fa32016-12-19 08:22:17 +00008030 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8031 return true;
8032 }
Hal Finkelcebf0cc2014-09-07 21:37:59 +00008033
Dan Gohman2a62fd92008-08-12 20:17:31 +00008034 return false;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00008035}
8036
Dan Gohmane18c2d62010-08-10 23:46:30 +00008037bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008038 const SCEV *LHS, const SCEV *RHS,
Dan Gohmane18c2d62010-08-10 23:46:30 +00008039 Value *FoundCondValue,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008040 bool Inverse) {
Sanjoy Dasc46bceb2016-09-27 18:01:42 +00008041 if (!PendingLoopPredicates.insert(FoundCondValue).second)
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008042 return false;
8043
Sanjoy Dasc46bceb2016-09-27 18:01:42 +00008044 auto ClearOnExit =
8045 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8046
Dan Gohman8b0a4192010-03-01 17:49:51 +00008047 // Recursively handle And and Or conditions.
Dan Gohmane18c2d62010-08-10 23:46:30 +00008048 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008049 if (BO->getOpcode() == Instruction::And) {
8050 if (!Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008051 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8052 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008053 } else if (BO->getOpcode() == Instruction::Or) {
8054 if (Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008055 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8056 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008057 }
8058 }
8059
Dan Gohmane18c2d62010-08-10 23:46:30 +00008060 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008061 if (!ICI) return false;
8062
Andrew Trickfa594032012-11-29 18:35:13 +00008063 // Now that we found a conditional branch that dominates the loop or controls
8064 // the loop latch. Check to see if it is the comparison we are looking for.
Dan Gohman430f0cc2009-07-21 23:03:19 +00008065 ICmpInst::Predicate FoundPred;
8066 if (Inverse)
8067 FoundPred = ICI->getInversePredicate();
8068 else
8069 FoundPred = ICI->getPredicate();
8070
8071 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8072 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohmane65c9172009-07-13 21:35:55 +00008073
Sanjoy Dasdf1635d2015-09-25 19:59:52 +00008074 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8075}
8076
8077bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8078 const SCEV *RHS,
8079 ICmpInst::Predicate FoundPred,
8080 const SCEV *FoundLHS,
8081 const SCEV *FoundRHS) {
Sanjoy Das14598832015-03-26 17:28:26 +00008082 // Balance the types.
8083 if (getTypeSizeInBits(LHS->getType()) <
8084 getTypeSizeInBits(FoundLHS->getType())) {
8085 if (CmpInst::isSigned(Pred)) {
8086 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8087 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8088 } else {
8089 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8090 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8091 }
8092 } else if (getTypeSizeInBits(LHS->getType()) >
Dan Gohmane65c9172009-07-13 21:35:55 +00008093 getTypeSizeInBits(FoundLHS->getType())) {
Stepan Dyatkovskiy431993b2014-01-09 12:26:12 +00008094 if (CmpInst::isSigned(FoundPred)) {
Dan Gohmane65c9172009-07-13 21:35:55 +00008095 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8096 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8097 } else {
8098 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8099 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8100 }
8101 }
8102
Dan Gohman430f0cc2009-07-21 23:03:19 +00008103 // Canonicalize the query to match the way instcombine will have
8104 // canonicalized the comparison.
Dan Gohman3673aa12010-04-24 01:34:53 +00008105 if (SimplifyICmpOperands(Pred, LHS, RHS))
8106 if (LHS == RHS)
Dan Gohmanb5025c72010-05-03 18:00:24 +00008107 return CmpInst::isTrueWhenEqual(Pred);
Benjamin Kramerba11a982012-11-29 19:07:57 +00008108 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8109 if (FoundLHS == FoundRHS)
8110 return CmpInst::isFalseWhenEqual(FoundPred);
Dan Gohman430f0cc2009-07-21 23:03:19 +00008111
8112 // Check to see if we can make the LHS or RHS match.
8113 if (LHS == FoundRHS || RHS == FoundLHS) {
8114 if (isa<SCEVConstant>(RHS)) {
8115 std::swap(FoundLHS, FoundRHS);
8116 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8117 } else {
8118 std::swap(LHS, RHS);
8119 Pred = ICmpInst::getSwappedPredicate(Pred);
8120 }
8121 }
8122
8123 // Check whether the found predicate is the same as the desired predicate.
8124 if (FoundPred == Pred)
8125 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8126
8127 // Check whether swapping the found predicate makes it the same as the
8128 // desired predicate.
8129 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8130 if (isa<SCEVConstant>(RHS))
8131 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8132 else
8133 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8134 RHS, LHS, FoundLHS, FoundRHS);
8135 }
8136
Sanjoy Das6e78b172015-10-22 19:57:34 +00008137 // Unsigned comparison is the same as signed comparison when both the operands
8138 // are non-negative.
8139 if (CmpInst::isUnsigned(FoundPred) &&
8140 CmpInst::getSignedPredicate(FoundPred) == Pred &&
8141 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8142 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8143
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008144 // Check if we can make progress by sharpening ranges.
8145 if (FoundPred == ICmpInst::ICMP_NE &&
8146 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8147
8148 const SCEVConstant *C = nullptr;
8149 const SCEV *V = nullptr;
8150
8151 if (isa<SCEVConstant>(FoundLHS)) {
8152 C = cast<SCEVConstant>(FoundLHS);
8153 V = FoundRHS;
8154 } else {
8155 C = cast<SCEVConstant>(FoundRHS);
8156 V = FoundLHS;
8157 }
8158
8159 // The guarding predicate tells us that C != V. If the known range
8160 // of V is [C, t), we can sharpen the range to [C + 1, t). The
8161 // range we consider has to correspond to same signedness as the
8162 // predicate we're interested in folding.
8163
8164 APInt Min = ICmpInst::isSigned(Pred) ?
8165 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8166
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008167 if (Min == C->getAPInt()) {
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008168 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8169 // This is true even if (Min + 1) wraps around -- in case of
8170 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8171
8172 APInt SharperMin = Min + 1;
8173
8174 switch (Pred) {
8175 case ICmpInst::ICMP_SGE:
8176 case ICmpInst::ICMP_UGE:
8177 // We know V `Pred` SharperMin. If this implies LHS `Pred`
8178 // RHS, we're done.
8179 if (isImpliedCondOperands(Pred, LHS, RHS, V,
8180 getConstant(SharperMin)))
8181 return true;
8182
8183 case ICmpInst::ICMP_SGT:
8184 case ICmpInst::ICMP_UGT:
8185 // We know from the range information that (V `Pred` Min ||
8186 // V == Min). We know from the guarding condition that !(V
8187 // == Min). This gives us
8188 //
8189 // V `Pred` Min || V == Min && !(V == Min)
8190 // => V `Pred` Min
8191 //
8192 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8193
8194 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8195 return true;
8196
8197 default:
8198 // No change
8199 break;
8200 }
8201 }
8202 }
8203
Dan Gohman430f0cc2009-07-21 23:03:19 +00008204 // Check whether the actual condition is beyond sufficient.
8205 if (FoundPred == ICmpInst::ICMP_EQ)
8206 if (ICmpInst::isTrueWhenEqual(Pred))
8207 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8208 return true;
8209 if (Pred == ICmpInst::ICMP_NE)
8210 if (!ICmpInst::isTrueWhenEqual(FoundPred))
8211 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8212 return true;
8213
8214 // Otherwise assume the worst.
8215 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008216}
8217
Sanjoy Das1ed69102015-10-13 02:53:27 +00008218bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8219 const SCEV *&L, const SCEV *&R,
8220 SCEV::NoWrapFlags &Flags) {
8221 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8222 if (!AE || AE->getNumOperands() != 2)
8223 return false;
8224
8225 L = AE->getOperand(0);
8226 R = AE->getOperand(1);
8227 Flags = AE->getNoWrapFlags();
8228 return true;
8229}
8230
Sanjoy Das0b1af852016-07-23 00:28:56 +00008231Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8232 const SCEV *Less) {
Sanjoy Das96709c42015-09-25 23:53:45 +00008233 // We avoid subtracting expressions here because this function is usually
8234 // fairly deep in the call stack (i.e. is called many times).
8235
Sanjoy Das96709c42015-09-25 23:53:45 +00008236 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8237 const auto *LAR = cast<SCEVAddRecExpr>(Less);
8238 const auto *MAR = cast<SCEVAddRecExpr>(More);
8239
8240 if (LAR->getLoop() != MAR->getLoop())
Sanjoy Das0b1af852016-07-23 00:28:56 +00008241 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008242
8243 // We look at affine expressions only; not for correctness but to keep
8244 // getStepRecurrence cheap.
8245 if (!LAR->isAffine() || !MAR->isAffine())
Sanjoy Das0b1af852016-07-23 00:28:56 +00008246 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008247
Sanjoy Das1ed69102015-10-13 02:53:27 +00008248 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008249 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008250
8251 Less = LAR->getStart();
8252 More = MAR->getStart();
8253
8254 // fall through
8255 }
8256
8257 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008258 const auto &M = cast<SCEVConstant>(More)->getAPInt();
8259 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
Sanjoy Das0b1af852016-07-23 00:28:56 +00008260 return M - L;
Sanjoy Das96709c42015-09-25 23:53:45 +00008261 }
8262
8263 const SCEV *L, *R;
Sanjoy Das1ed69102015-10-13 02:53:27 +00008264 SCEV::NoWrapFlags Flags;
8265 if (splitBinaryAdd(Less, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008266 if (const auto *LC = dyn_cast<SCEVConstant>(L))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008267 if (R == More)
8268 return -(LC->getAPInt());
Sanjoy Das96709c42015-09-25 23:53:45 +00008269
Sanjoy Das1ed69102015-10-13 02:53:27 +00008270 if (splitBinaryAdd(More, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008271 if (const auto *LC = dyn_cast<SCEVConstant>(L))
Sanjoy Das0b1af852016-07-23 00:28:56 +00008272 if (R == Less)
8273 return LC->getAPInt();
Sanjoy Das96709c42015-09-25 23:53:45 +00008274
Sanjoy Das0b1af852016-07-23 00:28:56 +00008275 return None;
Sanjoy Das96709c42015-09-25 23:53:45 +00008276}
8277
8278bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8279 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8280 const SCEV *FoundLHS, const SCEV *FoundRHS) {
8281 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8282 return false;
8283
8284 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8285 if (!AddRecLHS)
8286 return false;
8287
8288 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8289 if (!AddRecFoundLHS)
8290 return false;
8291
8292 // We'd like to let SCEV reason about control dependencies, so we constrain
8293 // both the inequalities to be about add recurrences on the same loop. This
8294 // way we can use isLoopEntryGuardedByCond later.
8295
8296 const Loop *L = AddRecFoundLHS->getLoop();
8297 if (L != AddRecLHS->getLoop())
8298 return false;
8299
8300 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
8301 //
8302 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8303 // ... (2)
8304 //
8305 // Informal proof for (2), assuming (1) [*]:
8306 //
8307 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8308 //
8309 // Then
8310 //
8311 // FoundLHS s< FoundRHS s< INT_MIN - C
8312 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
8313 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8314 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
8315 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8316 // <=> FoundLHS + C s< FoundRHS + C
8317 //
8318 // [*]: (1) can be proved by ruling out overflow.
8319 //
8320 // [**]: This can be proved by analyzing all the four possibilities:
8321 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8322 // (A s>= 0, B s>= 0).
8323 //
8324 // Note:
8325 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8326 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
8327 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
8328 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
8329 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8330 // C)".
8331
Sanjoy Das0b1af852016-07-23 00:28:56 +00008332 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8333 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8334 if (!LDiff || !RDiff || *LDiff != *RDiff)
Sanjoy Das96709c42015-09-25 23:53:45 +00008335 return false;
8336
Sanjoy Das0b1af852016-07-23 00:28:56 +00008337 if (LDiff->isMinValue())
Sanjoy Das96709c42015-09-25 23:53:45 +00008338 return true;
8339
Sanjoy Das96709c42015-09-25 23:53:45 +00008340 APInt FoundRHSLimit;
8341
8342 if (Pred == CmpInst::ICMP_ULT) {
Sanjoy Das0b1af852016-07-23 00:28:56 +00008343 FoundRHSLimit = -(*RDiff);
Sanjoy Das96709c42015-09-25 23:53:45 +00008344 } else {
8345 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
Sanjoy Das0b1af852016-07-23 00:28:56 +00008346 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
Sanjoy Das96709c42015-09-25 23:53:45 +00008347 }
8348
8349 // Try to prove (1) or (2), as needed.
8350 return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8351 getConstant(FoundRHSLimit));
8352}
8353
Dan Gohman430f0cc2009-07-21 23:03:19 +00008354bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8355 const SCEV *LHS, const SCEV *RHS,
8356 const SCEV *FoundLHS,
8357 const SCEV *FoundRHS) {
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008358 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8359 return true;
8360
Sanjoy Das96709c42015-09-25 23:53:45 +00008361 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8362 return true;
8363
Dan Gohman430f0cc2009-07-21 23:03:19 +00008364 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8365 FoundLHS, FoundRHS) ||
8366 // ~x < ~y --> x > y
8367 isImpliedCondOperandsHelper(Pred, LHS, RHS,
8368 getNotSCEV(FoundRHS),
8369 getNotSCEV(FoundLHS));
8370}
8371
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008372
8373/// If Expr computes ~A, return A else return nullptr
8374static const SCEV *MatchNotExpr(const SCEV *Expr) {
8375 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008376 if (!Add || Add->getNumOperands() != 2 ||
8377 !Add->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008378 return nullptr;
8379
8380 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008381 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8382 !AddRHS->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008383 return nullptr;
8384
8385 return AddRHS->getOperand(1);
8386}
8387
8388
8389/// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8390template<typename MaxExprType>
8391static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8392 const SCEV *Candidate) {
8393 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8394 if (!MaxExpr) return false;
8395
Sanjoy Das347d2722015-12-01 07:49:27 +00008396 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008397}
8398
8399
8400/// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8401template<typename MaxExprType>
8402static bool IsMinConsistingOf(ScalarEvolution &SE,
8403 const SCEV *MaybeMinExpr,
8404 const SCEV *Candidate) {
8405 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8406 if (!MaybeMaxExpr)
8407 return false;
8408
8409 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8410}
8411
Hal Finkela8d205f2015-08-19 01:51:51 +00008412static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8413 ICmpInst::Predicate Pred,
8414 const SCEV *LHS, const SCEV *RHS) {
8415
8416 // If both sides are affine addrecs for the same loop, with equal
8417 // steps, and we know the recurrences don't wrap, then we only
8418 // need to check the predicate on the starting values.
8419
8420 if (!ICmpInst::isRelational(Pred))
8421 return false;
8422
8423 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8424 if (!LAR)
8425 return false;
8426 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8427 if (!RAR)
8428 return false;
8429 if (LAR->getLoop() != RAR->getLoop())
8430 return false;
8431 if (!LAR->isAffine() || !RAR->isAffine())
8432 return false;
8433
8434 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8435 return false;
8436
Hal Finkelff08a2e2015-08-19 17:26:07 +00008437 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8438 SCEV::FlagNSW : SCEV::FlagNUW;
8439 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
Hal Finkela8d205f2015-08-19 01:51:51 +00008440 return false;
8441
8442 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8443}
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008444
8445/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8446/// expression?
8447static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8448 ICmpInst::Predicate Pred,
8449 const SCEV *LHS, const SCEV *RHS) {
8450 switch (Pred) {
8451 default:
8452 return false;
8453
8454 case ICmpInst::ICMP_SGE:
8455 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008456 LLVM_FALLTHROUGH;
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008457 case ICmpInst::ICMP_SLE:
8458 return
8459 // min(A, ...) <= A
8460 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8461 // A <= max(A, ...)
8462 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8463
8464 case ICmpInst::ICMP_UGE:
8465 std::swap(LHS, RHS);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008466 LLVM_FALLTHROUGH;
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008467 case ICmpInst::ICMP_ULE:
8468 return
8469 // min(A, ...) <= A
8470 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8471 // A <= max(A, ...)
8472 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8473 }
8474
8475 llvm_unreachable("covered switch fell through?!");
8476}
8477
Dan Gohmane65c9172009-07-13 21:35:55 +00008478bool
Dan Gohman430f0cc2009-07-21 23:03:19 +00008479ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8480 const SCEV *LHS, const SCEV *RHS,
8481 const SCEV *FoundLHS,
8482 const SCEV *FoundRHS) {
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008483 auto IsKnownPredicateFull =
8484 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Sanjoy Das401e6312016-02-01 20:48:10 +00008485 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
Sanjoy Das11231482015-10-22 19:57:29 +00008486 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
Sanjoy Dasc1a29772015-11-05 23:45:38 +00008487 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8488 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008489 };
8490
Dan Gohmane65c9172009-07-13 21:35:55 +00008491 switch (Pred) {
Dan Gohman8c129d72009-07-16 17:34:36 +00008492 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8493 case ICmpInst::ICMP_EQ:
8494 case ICmpInst::ICMP_NE:
8495 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8496 return true;
8497 break;
Dan Gohmane65c9172009-07-13 21:35:55 +00008498 case ICmpInst::ICMP_SLT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008499 case ICmpInst::ICMP_SLE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008500 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8501 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008502 return true;
8503 break;
8504 case ICmpInst::ICMP_SGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008505 case ICmpInst::ICMP_SGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008506 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8507 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008508 return true;
8509 break;
8510 case ICmpInst::ICMP_ULT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008511 case ICmpInst::ICMP_ULE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008512 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8513 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008514 return true;
8515 break;
8516 case ICmpInst::ICMP_UGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008517 case ICmpInst::ICMP_UGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008518 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8519 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008520 return true;
8521 break;
8522 }
8523
8524 return false;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008525}
8526
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008527bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8528 const SCEV *LHS,
8529 const SCEV *RHS,
8530 const SCEV *FoundLHS,
8531 const SCEV *FoundRHS) {
8532 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8533 // The restriction on `FoundRHS` be lifted easily -- it exists only to
8534 // reduce the compile time impact of this optimization.
8535 return false;
8536
Sanjoy Dasa7d9ec82016-07-23 00:54:36 +00008537 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
Sanjoy Das095f5b22016-07-22 20:47:55 +00008538 if (!Addend)
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008539 return false;
8540
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008541 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008542
8543 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8544 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8545 ConstantRange FoundLHSRange =
8546 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8547
Sanjoy Das095f5b22016-07-22 20:47:55 +00008548 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
8549 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008550
8551 // We can also compute the range of values for `LHS` that satisfy the
8552 // consequent, "`LHS` `Pred` `RHS`":
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008553 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008554 ConstantRange SatisfyingLHSRange =
8555 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8556
8557 // The antecedent implies the consequent if every value of `LHS` that
8558 // satisfies the antecedent also satisfies the consequent.
8559 return SatisfyingLHSRange.contains(LHSRange);
8560}
8561
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008562bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8563 bool IsSigned, bool NoWrap) {
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008564 assert(isKnownPositive(Stride) && "Positive stride expected!");
8565
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008566 if (NoWrap) return false;
Dan Gohman51aaf022010-01-26 04:40:18 +00008567
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008568 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008569 const SCEV *One = getOne(Stride->getType());
Andrew Trick2afa3252011-03-09 17:29:58 +00008570
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008571 if (IsSigned) {
8572 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8573 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8574 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8575 .getSignedMax();
Andrew Trick2afa3252011-03-09 17:29:58 +00008576
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008577 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8578 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
Dan Gohman36bad002009-09-17 18:05:20 +00008579 }
Dan Gohman01048422009-06-21 23:46:38 +00008580
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008581 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8582 APInt MaxValue = APInt::getMaxValue(BitWidth);
8583 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8584 .getUnsignedMax();
8585
8586 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8587 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8588}
8589
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008590bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8591 bool IsSigned, bool NoWrap) {
8592 if (NoWrap) return false;
8593
8594 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008595 const SCEV *One = getOne(Stride->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008596
8597 if (IsSigned) {
8598 APInt MinRHS = getSignedRange(RHS).getSignedMin();
8599 APInt MinValue = APInt::getSignedMinValue(BitWidth);
8600 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8601 .getSignedMax();
8602
8603 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8604 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8605 }
8606
8607 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8608 APInt MinValue = APInt::getMinValue(BitWidth);
8609 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8610 .getUnsignedMax();
8611
8612 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8613 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8614}
8615
Johannes Doerfert2683e562015-02-09 12:34:23 +00008616const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008617 bool Equality) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008618 const SCEV *One = getOne(Step->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008619 Delta = Equality ? getAddExpr(Delta, Step)
8620 : getAddExpr(Delta, getMinusSCEV(Step, One));
8621 return getUDivExpr(Delta, Step);
Dan Gohman01048422009-06-21 23:46:38 +00008622}
8623
Andrew Trick3ca3f982011-07-26 17:19:55 +00008624ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00008625ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008626 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008627 bool ControlsExit, bool AllowPredicates) {
Sanjoy Dasf0022122016-09-28 17:14:58 +00008628 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008629 // We handle only IV < Invariant
8630 if (!isLoopInvariant(RHS, L))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00008631 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008632
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008633 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008634 bool PredicatedIV = false;
8635
8636 if (!IV && AllowPredicates) {
Silviu Baranga6f444df2016-04-08 14:29:09 +00008637 // Try to make this an AddRec using runtime tests, in the first X
8638 // iterations of this loop, where X is the SCEV expression found by the
8639 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00008640 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008641 PredicatedIV = true;
8642 }
Dan Gohman2b8da352009-04-30 20:47:05 +00008643
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008644 // Avoid weird loops
8645 if (!IV || IV->getLoop() != L || !IV->isAffine())
8646 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008647
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008648 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008649 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008650
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008651 const SCEV *Stride = IV->getStepRecurrence(*this);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008652
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008653 bool PositiveStride = isKnownPositive(Stride);
Dan Gohman2b8da352009-04-30 20:47:05 +00008654
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008655 // Avoid negative or zero stride values.
8656 if (!PositiveStride) {
8657 // We can compute the correct backedge taken count for loops with unknown
8658 // strides if we can prove that the loop is not an infinite loop with side
8659 // effects. Here's the loop structure we are trying to handle -
8660 //
8661 // i = start
8662 // do {
8663 // A[i] = i;
8664 // i += s;
8665 // } while (i < end);
8666 //
8667 // The backedge taken count for such loops is evaluated as -
8668 // (max(end, start + stride) - start - 1) /u stride
8669 //
8670 // The additional preconditions that we need to check to prove correctness
8671 // of the above formula is as follows -
8672 //
8673 // a) IV is either nuw or nsw depending upon signedness (indicated by the
8674 // NoWrap flag).
8675 // b) loop is single exit with no side effects.
8676 //
8677 //
8678 // Precondition a) implies that if the stride is negative, this is a single
8679 // trip loop. The backedge taken count formula reduces to zero in this case.
8680 //
8681 // Precondition b) implies that the unknown stride cannot be zero otherwise
8682 // we have UB.
8683 //
8684 // The positive stride case is the same as isKnownPositive(Stride) returning
8685 // true (original behavior of the function).
8686 //
8687 // We want to make sure that the stride is truly unknown as there are edge
8688 // cases where ScalarEvolution propagates no wrap flags to the
8689 // post-increment/decrement IV even though the increment/decrement operation
8690 // itself is wrapping. The computed backedge taken count may be wrong in
8691 // such cases. This is prevented by checking that the stride is not known to
8692 // be either positive or non-positive. For example, no wrap flags are
8693 // propagated to the post-increment IV of this loop with a trip count of 2 -
8694 //
8695 // unsigned char i;
8696 // for(i=127; i<128; i+=129)
8697 // A[i] = i;
8698 //
8699 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
8700 !loopHasNoSideEffects(L))
8701 return getCouldNotCompute();
8702
8703 } else if (!Stride->isOne() &&
8704 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8705 // Avoid proven overflow cases: this will ensure that the backedge taken
8706 // count will not generate any unsigned overflow. Relaxed no-overflow
8707 // conditions exploit NoWrapFlags, allowing to optimize in presence of
8708 // undefined behaviors like the case of C language.
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008709 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00008710
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008711 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8712 : ICmpInst::ICMP_ULT;
8713 const SCEV *Start = IV->getStart();
8714 const SCEV *End = RHS;
John Brawnecf79302016-10-18 10:10:53 +00008715 // If the backedge is taken at least once, then it will be taken
8716 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
8717 // is the LHS value of the less-than comparison the first time it is evaluated
8718 // and End is the RHS.
8719 const SCEV *BECountIfBackedgeTaken =
8720 computeBECount(getMinusSCEV(End, Start), Stride, false);
8721 // If the loop entry is guarded by the result of the backedge test of the
8722 // first loop iteration, then we know the backedge will be taken at least
8723 // once and so the backedge taken count is as above. If not then we use the
8724 // expression (max(End,Start)-Start)/Stride to describe the backedge count,
8725 // as if the backedge is taken at least once max(End,Start) is End and so the
8726 // result is as above, and if not max(End,Start) is Start so we get a backedge
8727 // count of zero.
8728 const SCEV *BECount;
8729 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
8730 BECount = BECountIfBackedgeTaken;
8731 else {
Sanjoy Dase8fd9562016-06-18 04:38:31 +00008732 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
John Brawnecf79302016-10-18 10:10:53 +00008733 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
8734 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008735
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +00008736 const SCEV *MaxBECount;
John Brawn84b21832016-10-21 11:08:48 +00008737 bool MaxOrZero = false;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008738 if (isa<SCEVConstant>(BECount))
8739 MaxBECount = BECount;
John Brawn84b21832016-10-21 11:08:48 +00008740 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
John Brawnecf79302016-10-18 10:10:53 +00008741 // If we know exactly how many times the backedge will be taken if it's
8742 // taken at least once, then the backedge count will either be that or
8743 // zero.
8744 MaxBECount = BECountIfBackedgeTaken;
John Brawn84b21832016-10-21 11:08:48 +00008745 MaxOrZero = true;
8746 } else {
John Brawnecf79302016-10-18 10:10:53 +00008747 // Calculate the maximum backedge count based on the range of values
8748 // permitted by Start, End, and Stride.
8749 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8750 : getUnsignedRange(Start).getUnsignedMin();
8751
8752 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8753
8754 APInt StrideForMaxBECount;
8755
8756 if (PositiveStride)
8757 StrideForMaxBECount =
8758 IsSigned ? getSignedRange(Stride).getSignedMin()
8759 : getUnsignedRange(Stride).getUnsignedMin();
8760 else
8761 // Using a stride of 1 is safe when computing max backedge taken count for
8762 // a loop with unknown stride.
8763 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
8764
8765 APInt Limit =
8766 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
8767 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
8768
8769 // Although End can be a MAX expression we estimate MaxEnd considering only
8770 // the case End = RHS. This is safe because in the other case (End - Start)
8771 // is zero, leading to a zero maximum backedge taken count.
8772 APInt MaxEnd =
8773 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8774 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8775
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008776 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
David L Kreitzer8bbabee2016-09-16 14:38:13 +00008777 getConstant(StrideForMaxBECount), false);
John Brawnecf79302016-10-18 10:10:53 +00008778 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008779
8780 if (isa<SCEVCouldNotCompute>(MaxBECount))
8781 MaxBECount = BECount;
8782
John Brawn84b21832016-10-21 11:08:48 +00008783 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008784}
8785
8786ScalarEvolution::ExitLimit
Sanjoy Das108fcf22016-05-29 00:38:00 +00008787ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008788 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008789 bool ControlsExit, bool AllowPredicates) {
Sanjoy Dasf0022122016-09-28 17:14:58 +00008790 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008791 // We handle only IV > Invariant
8792 if (!isLoopInvariant(RHS, L))
8793 return getCouldNotCompute();
8794
8795 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Silviu Baranga6f444df2016-04-08 14:29:09 +00008796 if (!IV && AllowPredicates)
8797 // Try to make this an AddRec using runtime tests, in the first X
8798 // iterations of this loop, where X is the SCEV expression found by the
8799 // algorithm below.
Sanjoy Dasf0022122016-09-28 17:14:58 +00008800 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008801
8802 // Avoid weird loops
8803 if (!IV || IV->getLoop() != L || !IV->isAffine())
8804 return getCouldNotCompute();
8805
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008806 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008807 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8808
8809 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8810
8811 // Avoid negative or zero stride values
8812 if (!isKnownPositive(Stride))
8813 return getCouldNotCompute();
8814
8815 // Avoid proven overflow cases: this will ensure that the backedge taken count
8816 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00008817 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008818 // behaviors like the case of C language.
8819 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8820 return getCouldNotCompute();
8821
8822 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8823 : ICmpInst::ICMP_UGT;
8824
8825 const SCEV *Start = IV->getStart();
8826 const SCEV *End = RHS;
Sanjoy Dase8fd9562016-06-18 04:38:31 +00008827 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
8828 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008829
8830 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8831
8832 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8833 : getUnsignedRange(Start).getUnsignedMax();
8834
8835 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8836 : getUnsignedRange(Stride).getUnsignedMin();
8837
8838 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8839 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8840 : APInt::getMinValue(BitWidth) + (MinStride - 1);
8841
8842 // Although End can be a MIN expression we estimate MinEnd considering only
8843 // the case End = RHS. This is safe because in the other case (Start - End)
8844 // is zero, leading to a zero maximum backedge taken count.
8845 APInt MinEnd =
8846 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8847 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8848
8849
8850 const SCEV *MaxBECount = getCouldNotCompute();
8851 if (isa<SCEVConstant>(BECount))
8852 MaxBECount = BECount;
8853 else
Johannes Doerfert2683e562015-02-09 12:34:23 +00008854 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008855 getConstant(MinStride), false);
8856
8857 if (isa<SCEVCouldNotCompute>(MaxBECount))
8858 MaxBECount = BECount;
8859
John Brawn84b21832016-10-21 11:08:48 +00008860 return ExitLimit(BECount, MaxBECount, false, Predicates);
Chris Lattner587a75b2005-08-15 23:33:51 +00008861}
8862
Benjamin Kramerc321e532016-06-08 19:09:22 +00008863const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
Dan Gohmance973df2009-06-24 04:48:43 +00008864 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00008865 if (Range.isFullSet()) // Infinite loop.
Dan Gohman31efa302009-04-18 17:58:19 +00008866 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008867
8868 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmana30370b2009-05-04 22:02:23 +00008869 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencer2e54a152007-03-02 00:28:52 +00008870 if (!SC->getValue()->isZero()) {
Dan Gohmanaf752342009-07-07 17:06:11 +00008871 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008872 Operands[0] = SE.getZero(SC->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00008873 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00008874 getNoWrapFlags(FlagNW));
Sanjoy Das63914592015-10-18 00:29:20 +00008875 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattnerd934c702004-04-02 20:23:17 +00008876 return ShiftedAddRec->getNumIterationsInRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008877 Range.subtract(SC->getAPInt()), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00008878 // This is strange and shouldn't happen.
Dan Gohman31efa302009-04-18 17:58:19 +00008879 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008880 }
8881
8882 // The only time we can solve this is when we have all constant indices.
8883 // Otherwise, we cannot determine the overflow conditions.
Sanjoy Dasff3b8b42015-12-01 07:49:23 +00008884 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00008885 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008886
8887 // Okay at this point we know that all elements of the chrec are constants and
8888 // that the start element is zero.
8889
8890 // First check to see if the range contains zero. If not, the first
8891 // iteration exits.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00008892 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +00008893 if (!Range.contains(APInt(BitWidth, 0)))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008894 return SE.getZero(getType());
Misha Brukman01808ca2005-04-21 21:13:18 +00008895
Chris Lattnerd934c702004-04-02 20:23:17 +00008896 if (isAffine()) {
8897 // If this is an affine expression then we have this situation:
8898 // Solve {0,+,A} in Range === Ax in Range
8899
Nick Lewycky52460262007-07-16 02:08:00 +00008900 // We know that zero is in the range. If A is positive then we know that
8901 // the upper value of the range must be the first possible exit value.
8902 // If A is negative then the lower of the range is the last possible loop
8903 // value. Also note that we already checked for a full range.
Dan Gohman0a40ad92009-04-16 03:18:22 +00008904 APInt One(BitWidth,1);
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008905 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
Nick Lewycky52460262007-07-16 02:08:00 +00008906 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattnerd934c702004-04-02 20:23:17 +00008907
Nick Lewycky52460262007-07-16 02:08:00 +00008908 // The exit value should be (End+A)/A.
Nick Lewycky39349612007-09-27 14:12:54 +00008909 APInt ExitVal = (End + A).udiv(A);
Owen Andersonedb4a702009-07-24 23:12:02 +00008910 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00008911
8912 // Evaluate at the exit value. If we really did fall out of the valid
8913 // range, then we computed our trip count, otherwise wrap around or other
8914 // things must have happened.
Dan Gohmana37eaf22007-10-22 18:31:58 +00008915 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008916 if (Range.contains(Val->getValue()))
Dan Gohman31efa302009-04-18 17:58:19 +00008917 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008918
8919 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00008920 assert(Range.contains(
Dan Gohmance973df2009-06-24 04:48:43 +00008921 EvaluateConstantChrecAtConstant(this,
Owen Andersonedb4a702009-07-24 23:12:02 +00008922 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattnerd934c702004-04-02 20:23:17 +00008923 "Linear scev computation is off in a bad way!");
Dan Gohmana37eaf22007-10-22 18:31:58 +00008924 return SE.getConstant(ExitValue);
Chris Lattnerd934c702004-04-02 20:23:17 +00008925 } else if (isQuadratic()) {
8926 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
8927 // quadratic equation to solve it. To do this, we must frame our problem in
8928 // terms of figuring out when zero is crossed, instead of when
8929 // Range.getUpper() is crossed.
Dan Gohmanaf752342009-07-07 17:06:11 +00008930 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00008931 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Sanjoy Das54e6a212016-10-02 00:09:45 +00008932 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00008933
8934 // Next, solve the constructed addrec
Sanjoy Das0e392d52016-06-15 04:37:50 +00008935 if (auto Roots =
8936 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
Sanjoy Das5a3d8932016-06-15 04:37:47 +00008937 const SCEVConstant *R1 = Roots->first;
8938 const SCEVConstant *R2 = Roots->second;
Chris Lattnerd934c702004-04-02 20:23:17 +00008939 // Pick the smallest positive root value.
Sanjoy Das01947432015-11-22 21:20:13 +00008940 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8941 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00008942 if (!CB->getZExtValue())
Sanjoy Das0e392d52016-06-15 04:37:50 +00008943 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00008944
Chris Lattnerd934c702004-04-02 20:23:17 +00008945 // Make sure the root is not off by one. The returned iteration should
8946 // not be in the range, but the previous one should be. When solving
8947 // for "X*X < 5", for example, we should not return a root of 2.
Sanjoy Das0e392d52016-06-15 04:37:50 +00008948 ConstantInt *R1Val =
8949 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008950 if (Range.contains(R1Val->getValue())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00008951 // The next iteration must be out of the range...
Owen Andersonf1f17432009-07-06 22:37:39 +00008952 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008953 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
Misha Brukman01808ca2005-04-21 21:13:18 +00008954
Dan Gohmana37eaf22007-10-22 18:31:58 +00008955 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008956 if (!Range.contains(R1Val->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00008957 return SE.getConstant(NextVal);
Sanjoy Das0e392d52016-06-15 04:37:50 +00008958 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008959 }
Misha Brukman01808ca2005-04-21 21:13:18 +00008960
Chris Lattnerd934c702004-04-02 20:23:17 +00008961 // If R1 was not in the range, then it is a good return value. Make
8962 // sure that R1-1 WAS in the range though, just in case.
Owen Andersonf1f17432009-07-06 22:37:39 +00008963 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008964 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
Dan Gohmana37eaf22007-10-22 18:31:58 +00008965 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008966 if (Range.contains(R1Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00008967 return R1;
Sanjoy Das0e392d52016-06-15 04:37:50 +00008968 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008969 }
8970 }
8971 }
8972
Dan Gohman31efa302009-04-18 17:58:19 +00008973 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008974}
8975
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008976// Return true when S contains at least an undef value.
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00008977static inline bool containsUndefs(const SCEV *S) {
8978 return SCEVExprContains(S, [](const SCEV *S) {
8979 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
8980 return isa<UndefValue>(SU->getValue());
8981 else if (const auto *SC = dyn_cast<SCEVConstant>(S))
8982 return isa<UndefValue>(SC->getValue());
8983 return false;
8984 });
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008985}
8986
8987namespace {
Sebastian Pop448712b2014-05-07 18:01:20 +00008988// Collect all steps of SCEV expressions.
8989struct SCEVCollectStrides {
8990 ScalarEvolution &SE;
8991 SmallVectorImpl<const SCEV *> &Strides;
8992
8993 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
8994 : SE(SE), Strides(S) {}
8995
8996 bool follow(const SCEV *S) {
8997 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
8998 Strides.push_back(AR->getStepRecurrence(SE));
8999 return true;
9000 }
9001 bool isDone() const { return false; }
9002};
9003
9004// Collect all SCEVUnknown and SCEVMulExpr expressions.
9005struct SCEVCollectTerms {
9006 SmallVectorImpl<const SCEV *> &Terms;
9007
9008 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9009 : Terms(T) {}
9010
9011 bool follow(const SCEV *S) {
Tobias Grosser2bbec0e2016-10-17 11:56:26 +00009012 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
9013 isa<SCEVSignExtendExpr>(S)) {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00009014 if (!containsUndefs(S))
9015 Terms.push_back(S);
Sebastian Pop448712b2014-05-07 18:01:20 +00009016
9017 // Stop recursion: once we collected a term, do not walk its operands.
9018 return false;
9019 }
9020
9021 // Keep looking.
9022 return true;
9023 }
9024 bool isDone() const { return false; }
9025};
Tobias Grosser374bce02015-10-12 08:02:00 +00009026
9027// Check if a SCEV contains an AddRecExpr.
9028struct SCEVHasAddRec {
9029 bool &ContainsAddRec;
9030
9031 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9032 ContainsAddRec = false;
9033 }
9034
9035 bool follow(const SCEV *S) {
9036 if (isa<SCEVAddRecExpr>(S)) {
9037 ContainsAddRec = true;
9038
9039 // Stop recursion: once we collected a term, do not walk its operands.
9040 return false;
9041 }
9042
9043 // Keep looking.
9044 return true;
9045 }
9046 bool isDone() const { return false; }
9047};
9048
9049// Find factors that are multiplied with an expression that (possibly as a
9050// subexpression) contains an AddRecExpr. In the expression:
9051//
9052// 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
9053//
9054// "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9055// that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9056// parameters as they form a product with an induction variable.
9057//
9058// This collector expects all array size parameters to be in the same MulExpr.
9059// It might be necessary to later add support for collecting parameters that are
9060// spread over different nested MulExpr.
9061struct SCEVCollectAddRecMultiplies {
9062 SmallVectorImpl<const SCEV *> &Terms;
9063 ScalarEvolution &SE;
9064
9065 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9066 : Terms(T), SE(SE) {}
9067
9068 bool follow(const SCEV *S) {
9069 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9070 bool HasAddRec = false;
9071 SmallVector<const SCEV *, 0> Operands;
9072 for (auto Op : Mul->operands()) {
9073 if (isa<SCEVUnknown>(Op)) {
9074 Operands.push_back(Op);
9075 } else {
9076 bool ContainsAddRec;
9077 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9078 visitAll(Op, ContiansAddRec);
9079 HasAddRec |= ContainsAddRec;
9080 }
9081 }
9082 if (Operands.size() == 0)
9083 return true;
9084
9085 if (!HasAddRec)
9086 return false;
9087
9088 Terms.push_back(SE.getMulExpr(Operands));
9089 // Stop recursion: once we collected a term, do not walk its operands.
9090 return false;
9091 }
9092
9093 // Keep looking.
9094 return true;
9095 }
9096 bool isDone() const { return false; }
9097};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00009098}
Sebastian Pop448712b2014-05-07 18:01:20 +00009099
Tobias Grosser374bce02015-10-12 08:02:00 +00009100/// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9101/// two places:
9102/// 1) The strides of AddRec expressions.
9103/// 2) Unknowns that are multiplied with AddRec expressions.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009104void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9105 SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009106 SmallVector<const SCEV *, 4> Strides;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009107 SCEVCollectStrides StrideCollector(*this, Strides);
9108 visitAll(Expr, StrideCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009109
9110 DEBUG({
9111 dbgs() << "Strides:\n";
9112 for (const SCEV *S : Strides)
9113 dbgs() << *S << "\n";
9114 });
9115
9116 for (const SCEV *S : Strides) {
9117 SCEVCollectTerms TermCollector(Terms);
9118 visitAll(S, TermCollector);
9119 }
9120
9121 DEBUG({
9122 dbgs() << "Terms:\n";
9123 for (const SCEV *T : Terms)
9124 dbgs() << *T << "\n";
9125 });
Tobias Grosser374bce02015-10-12 08:02:00 +00009126
9127 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9128 visitAll(Expr, MulCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009129}
9130
Sebastian Popb1a548f2014-05-12 19:01:53 +00009131static bool findArrayDimensionsRec(ScalarEvolution &SE,
Sebastian Pop448712b2014-05-07 18:01:20 +00009132 SmallVectorImpl<const SCEV *> &Terms,
Sebastian Pop47fe7de2014-05-09 22:45:07 +00009133 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pope30bd352014-05-27 22:41:56 +00009134 int Last = Terms.size() - 1;
9135 const SCEV *Step = Terms[Last];
Sebastian Popc62c6792013-11-12 22:47:20 +00009136
Sebastian Pop448712b2014-05-07 18:01:20 +00009137 // End of recursion.
Sebastian Pope30bd352014-05-27 22:41:56 +00009138 if (Last == 0) {
9139 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009140 SmallVector<const SCEV *, 2> Qs;
9141 for (const SCEV *Op : M->operands())
9142 if (!isa<SCEVConstant>(Op))
9143 Qs.push_back(Op);
Sebastian Popc62c6792013-11-12 22:47:20 +00009144
Sebastian Pope30bd352014-05-27 22:41:56 +00009145 Step = SE.getMulExpr(Qs);
Sebastian Popc62c6792013-11-12 22:47:20 +00009146 }
9147
Sebastian Pope30bd352014-05-27 22:41:56 +00009148 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009149 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00009150 }
9151
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009152 for (const SCEV *&Term : Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009153 // Normalize the terms before the next call to findArrayDimensionsRec.
9154 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009155 SCEVDivision::divide(SE, Term, Step, &Q, &R);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009156
9157 // Bail out when GCD does not evenly divide one of the terms.
9158 if (!R->isZero())
9159 return false;
9160
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009161 Term = Q;
Sebastian Popc62c6792013-11-12 22:47:20 +00009162 }
9163
Tobias Grosser3080cf12014-05-08 07:55:34 +00009164 // Remove all SCEVConstants.
David Majnemerc7004902016-08-12 04:32:37 +00009165 Terms.erase(
9166 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9167 Terms.end());
Sebastian Popc62c6792013-11-12 22:47:20 +00009168
Sebastian Pop448712b2014-05-07 18:01:20 +00009169 if (Terms.size() > 0)
Sebastian Popb1a548f2014-05-12 19:01:53 +00009170 if (!findArrayDimensionsRec(SE, Terms, Sizes))
9171 return false;
9172
Sebastian Pope30bd352014-05-27 22:41:56 +00009173 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009174 return true;
Sebastian Pop448712b2014-05-07 18:01:20 +00009175}
Sebastian Popc62c6792013-11-12 22:47:20 +00009176
Sebastian Pop448712b2014-05-07 18:01:20 +00009177
9178// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00009179static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009180 for (const SCEV *T : Terms)
Sanjoy Das0ae390a2016-11-10 06:33:54 +00009181 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
Sebastian Pop448712b2014-05-07 18:01:20 +00009182 return true;
9183 return false;
9184}
9185
9186// Return the number of product terms in S.
9187static inline int numberOfTerms(const SCEV *S) {
9188 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9189 return Expr->getNumOperands();
9190 return 1;
9191}
9192
Sebastian Popa6e58602014-05-27 22:41:45 +00009193static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9194 if (isa<SCEVConstant>(T))
9195 return nullptr;
9196
9197 if (isa<SCEVUnknown>(T))
9198 return T;
9199
9200 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9201 SmallVector<const SCEV *, 2> Factors;
9202 for (const SCEV *Op : M->operands())
9203 if (!isa<SCEVConstant>(Op))
9204 Factors.push_back(Op);
9205
9206 return SE.getMulExpr(Factors);
9207 }
9208
9209 return T;
9210}
9211
9212/// Return the size of an element read or written by Inst.
9213const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9214 Type *Ty;
9215 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9216 Ty = Store->getValueOperand()->getType();
9217 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
Tobias Grosser40ac1002014-06-08 19:21:20 +00009218 Ty = Load->getType();
Sebastian Popa6e58602014-05-27 22:41:45 +00009219 else
9220 return nullptr;
9221
9222 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9223 return getSizeOfExpr(ETy, Ty);
9224}
9225
Sebastian Popa6e58602014-05-27 22:41:45 +00009226void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9227 SmallVectorImpl<const SCEV *> &Sizes,
9228 const SCEV *ElementSize) const {
Sebastian Pop53524082014-05-29 19:44:05 +00009229 if (Terms.size() < 1 || !ElementSize)
Sebastian Pop448712b2014-05-07 18:01:20 +00009230 return;
9231
9232 // Early return when Terms do not contain parameters: we do not delinearize
9233 // non parametric SCEVs.
9234 if (!containsParameters(Terms))
9235 return;
9236
9237 DEBUG({
9238 dbgs() << "Terms:\n";
9239 for (const SCEV *T : Terms)
9240 dbgs() << *T << "\n";
9241 });
9242
9243 // Remove duplicates.
9244 std::sort(Terms.begin(), Terms.end());
9245 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9246
9247 // Put larger terms first.
9248 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9249 return numberOfTerms(LHS) > numberOfTerms(RHS);
9250 });
9251
Sebastian Popa6e58602014-05-27 22:41:45 +00009252 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9253
Tobias Grosser374bce02015-10-12 08:02:00 +00009254 // Try to divide all terms by the element size. If term is not divisible by
9255 // element size, proceed with the original term.
Sebastian Popa6e58602014-05-27 22:41:45 +00009256 for (const SCEV *&Term : Terms) {
9257 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009258 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
Tobias Grosser374bce02015-10-12 08:02:00 +00009259 if (!Q->isZero())
9260 Term = Q;
Sebastian Popa6e58602014-05-27 22:41:45 +00009261 }
9262
9263 SmallVector<const SCEV *, 4> NewTerms;
9264
9265 // Remove constant factors.
9266 for (const SCEV *T : Terms)
9267 if (const SCEV *NewT = removeConstantFactors(SE, T))
9268 NewTerms.push_back(NewT);
9269
Sebastian Pop448712b2014-05-07 18:01:20 +00009270 DEBUG({
9271 dbgs() << "Terms after sorting:\n";
Sebastian Popa6e58602014-05-27 22:41:45 +00009272 for (const SCEV *T : NewTerms)
Sebastian Pop448712b2014-05-07 18:01:20 +00009273 dbgs() << *T << "\n";
9274 });
9275
Sebastian Popa6e58602014-05-27 22:41:45 +00009276 if (NewTerms.empty() ||
9277 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
Sebastian Popb1a548f2014-05-12 19:01:53 +00009278 Sizes.clear();
9279 return;
9280 }
Sebastian Pop448712b2014-05-07 18:01:20 +00009281
Sebastian Popa6e58602014-05-27 22:41:45 +00009282 // The last element to be pushed into Sizes is the size of an element.
9283 Sizes.push_back(ElementSize);
9284
Sebastian Pop448712b2014-05-07 18:01:20 +00009285 DEBUG({
9286 dbgs() << "Sizes:\n";
9287 for (const SCEV *S : Sizes)
9288 dbgs() << *S << "\n";
9289 });
9290}
9291
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009292void ScalarEvolution::computeAccessFunctions(
9293 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9294 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009295
Sebastian Popb1a548f2014-05-12 19:01:53 +00009296 // Early exit in case this SCEV is not an affine multivariate function.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009297 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009298 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009299
Sanjoy Das1195dbe2015-10-08 03:45:58 +00009300 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009301 if (!AR->isAffine())
9302 return;
9303
9304 const SCEV *Res = Expr;
Sebastian Pop448712b2014-05-07 18:01:20 +00009305 int Last = Sizes.size() - 1;
9306 for (int i = Last; i >= 0; i--) {
9307 const SCEV *Q, *R;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009308 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
Sebastian Pop448712b2014-05-07 18:01:20 +00009309
9310 DEBUG({
9311 dbgs() << "Res: " << *Res << "\n";
9312 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9313 dbgs() << "Res divided by Sizes[i]:\n";
9314 dbgs() << "Quotient: " << *Q << "\n";
9315 dbgs() << "Remainder: " << *R << "\n";
9316 });
9317
9318 Res = Q;
9319
Sebastian Popa6e58602014-05-27 22:41:45 +00009320 // Do not record the last subscript corresponding to the size of elements in
9321 // the array.
Sebastian Pop448712b2014-05-07 18:01:20 +00009322 if (i == Last) {
Sebastian Popa6e58602014-05-27 22:41:45 +00009323
9324 // Bail out if the remainder is too complex.
Sebastian Pop28e6b972014-05-27 22:41:51 +00009325 if (isa<SCEVAddRecExpr>(R)) {
9326 Subscripts.clear();
9327 Sizes.clear();
9328 return;
9329 }
Sebastian Popa6e58602014-05-27 22:41:45 +00009330
Sebastian Pop448712b2014-05-07 18:01:20 +00009331 continue;
9332 }
9333
9334 // Record the access function for the current subscript.
9335 Subscripts.push_back(R);
9336 }
9337
9338 // Also push in last position the remainder of the last division: it will be
9339 // the access function of the innermost dimension.
9340 Subscripts.push_back(Res);
9341
9342 std::reverse(Subscripts.begin(), Subscripts.end());
9343
9344 DEBUG({
9345 dbgs() << "Subscripts:\n";
9346 for (const SCEV *S : Subscripts)
9347 dbgs() << *S << "\n";
9348 });
Sebastian Pop448712b2014-05-07 18:01:20 +00009349}
9350
Sebastian Popc62c6792013-11-12 22:47:20 +00009351/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9352/// sizes of an array access. Returns the remainder of the delinearization that
Sebastian Pop7ee14722013-11-13 22:37:58 +00009353/// is the offset start of the array. The SCEV->delinearize algorithm computes
9354/// the multiples of SCEV coefficients: that is a pattern matching of sub
9355/// expressions in the stride and base of a SCEV corresponding to the
9356/// computation of a GCD (greatest common divisor) of base and stride. When
9357/// SCEV->delinearize fails, it returns the SCEV unchanged.
9358///
9359/// For example: when analyzing the memory access A[i][j][k] in this loop nest
9360///
9361/// void foo(long n, long m, long o, double A[n][m][o]) {
9362///
9363/// for (long i = 0; i < n; i++)
9364/// for (long j = 0; j < m; j++)
9365/// for (long k = 0; k < o; k++)
9366/// A[i][j][k] = 1.0;
9367/// }
9368///
9369/// the delinearization input is the following AddRec SCEV:
9370///
9371/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9372///
9373/// From this SCEV, we are able to say that the base offset of the access is %A
9374/// because it appears as an offset that does not divide any of the strides in
9375/// the loops:
9376///
9377/// CHECK: Base offset: %A
9378///
9379/// and then SCEV->delinearize determines the size of some of the dimensions of
9380/// the array as these are the multiples by which the strides are happening:
9381///
9382/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9383///
9384/// Note that the outermost dimension remains of UnknownSize because there are
9385/// no strides that would help identifying the size of the last dimension: when
9386/// the array has been statically allocated, one could compute the size of that
9387/// dimension by dividing the overall size of the array by the size of the known
9388/// dimensions: %m * %o * 8.
9389///
9390/// Finally delinearize provides the access functions for the array reference
9391/// that does correspond to A[i][j][k] of the above C testcase:
9392///
9393/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9394///
9395/// The testcases are checking the output of a function pass:
9396/// DelinearizationPass that walks through all loads and stores of a function
9397/// asking for the SCEV of the memory access with respect to all enclosing
9398/// loops, calling SCEV->delinearize on that and printing the results.
9399
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009400void ScalarEvolution::delinearize(const SCEV *Expr,
Sebastian Pop28e6b972014-05-27 22:41:51 +00009401 SmallVectorImpl<const SCEV *> &Subscripts,
9402 SmallVectorImpl<const SCEV *> &Sizes,
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009403 const SCEV *ElementSize) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009404 // First step: collect parametric terms.
9405 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009406 collectParametricTerms(Expr, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00009407
Sebastian Popb1a548f2014-05-12 19:01:53 +00009408 if (Terms.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009409 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009410
Sebastian Pop448712b2014-05-07 18:01:20 +00009411 // Second step: find subscript sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009412 findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop7ee14722013-11-13 22:37:58 +00009413
Sebastian Popb1a548f2014-05-12 19:01:53 +00009414 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009415 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009416
Sebastian Pop448712b2014-05-07 18:01:20 +00009417 // Third step: compute the access functions for each subscript.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009418 computeAccessFunctions(Expr, Subscripts, Sizes);
Sebastian Popc62c6792013-11-12 22:47:20 +00009419
Sebastian Pop28e6b972014-05-27 22:41:51 +00009420 if (Subscripts.empty())
9421 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009422
Sebastian Pop448712b2014-05-07 18:01:20 +00009423 DEBUG({
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009424 dbgs() << "succeeded to delinearize " << *Expr << "\n";
Sebastian Pop448712b2014-05-07 18:01:20 +00009425 dbgs() << "ArrayDecl[UnknownSize]";
9426 for (const SCEV *S : Sizes)
9427 dbgs() << "[" << *S << "]";
Sebastian Popc62c6792013-11-12 22:47:20 +00009428
Sebastian Pop444621a2014-05-09 22:45:02 +00009429 dbgs() << "\nArrayRef";
9430 for (const SCEV *S : Subscripts)
Sebastian Pop448712b2014-05-07 18:01:20 +00009431 dbgs() << "[" << *S << "]";
9432 dbgs() << "\n";
9433 });
Sebastian Popc62c6792013-11-12 22:47:20 +00009434}
Chris Lattnerd934c702004-04-02 20:23:17 +00009435
9436//===----------------------------------------------------------------------===//
Dan Gohman48f82222009-05-04 22:30:44 +00009437// SCEVCallbackVH Class Implementation
9438//===----------------------------------------------------------------------===//
9439
Dan Gohmand33a0902009-05-19 19:22:47 +00009440void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmandd707af2009-07-13 22:20:53 +00009441 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman48f82222009-05-04 22:30:44 +00009442 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9443 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009444 SE->eraseValueFromMap(getValPtr());
Dan Gohman48f82222009-05-04 22:30:44 +00009445 // this now dangles!
9446}
9447
Dan Gohman7a066722010-07-28 01:09:07 +00009448void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmandd707af2009-07-13 22:20:53 +00009449 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christopheref6d5932010-07-29 01:25:38 +00009450
Dan Gohman48f82222009-05-04 22:30:44 +00009451 // Forget all the expressions associated with users of the old value,
9452 // so that future queries will recompute the expressions using the new
9453 // value.
Dan Gohman7cac9572010-08-02 23:49:30 +00009454 Value *Old = getValPtr();
Chandler Carruthcdf47882014-03-09 03:16:01 +00009455 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
Dan Gohmanf34f8632009-07-14 14:34:04 +00009456 SmallPtrSet<User *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00009457 while (!Worklist.empty()) {
9458 User *U = Worklist.pop_back_val();
9459 // Deleting the Old value will cause this to dangle. Postpone
9460 // that until everything else is done.
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009461 if (U == Old)
Dan Gohman48f82222009-05-04 22:30:44 +00009462 continue;
David Blaikie70573dc2014-11-19 07:49:26 +00009463 if (!Visited.insert(U).second)
Dan Gohmanf34f8632009-07-14 14:34:04 +00009464 continue;
Dan Gohman48f82222009-05-04 22:30:44 +00009465 if (PHINode *PN = dyn_cast<PHINode>(U))
9466 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009467 SE->eraseValueFromMap(U);
Chandler Carruthcdf47882014-03-09 03:16:01 +00009468 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
Dan Gohman48f82222009-05-04 22:30:44 +00009469 }
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009470 // Delete the Old value.
9471 if (PHINode *PN = dyn_cast<PHINode>(Old))
9472 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009473 SE->eraseValueFromMap(Old);
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009474 // this now dangles!
Dan Gohman48f82222009-05-04 22:30:44 +00009475}
9476
Dan Gohmand33a0902009-05-19 19:22:47 +00009477ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman48f82222009-05-04 22:30:44 +00009478 : CallbackVH(V), SE(se) {}
9479
9480//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00009481// ScalarEvolution Class Implementation
9482//===----------------------------------------------------------------------===//
9483
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009484ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00009485 AssumptionCache &AC, DominatorTree &DT,
9486 LoopInfo &LI)
9487 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009488 CouldNotCompute(new SCEVCouldNotCompute()),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009489 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9490 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009491 FirstUnknown(nullptr) {
9492
9493 // To use guards for proving predicates, we need to scan every instruction in
9494 // relevant basic blocks, and not just terminators. Doing this is a waste of
9495 // time if the IR does not actually contain any calls to
9496 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9497 //
9498 // This pessimizes the case where a pass that preserves ScalarEvolution wants
9499 // to _add_ guards to the module when there weren't any before, and wants
9500 // ScalarEvolution to optimize based on those guards. For now we prefer to be
9501 // efficient in lieu of being smart in that rather obscure case.
9502
9503 auto *GuardDecl = F.getParent()->getFunction(
9504 Intrinsic::getName(Intrinsic::experimental_guard));
9505 HasGuards = GuardDecl && !GuardDecl->use_empty();
9506}
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009507
9508ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00009509 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
Sanjoy Das2512d0c2016-05-10 00:31:49 +00009510 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009511 ValueExprMap(std::move(Arg.ValueExprMap)),
Sanjoy Dasdb933752016-09-27 18:01:38 +00009512 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009513 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009514 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
Silviu Baranga6f444df2016-04-08 14:29:09 +00009515 PredicatedBackedgeTakenCounts(
9516 std::move(Arg.PredicatedBackedgeTakenCounts)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009517 ConstantEvolutionLoopExitValue(
9518 std::move(Arg.ConstantEvolutionLoopExitValue)),
9519 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9520 LoopDispositions(std::move(Arg.LoopDispositions)),
Sanjoy Das5cb11b62016-09-26 02:44:10 +00009521 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
Chandler Carruth68abda52016-09-26 04:49:58 +00009522 BlockDispositions(std::move(Arg.BlockDispositions)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009523 UnsignedRanges(std::move(Arg.UnsignedRanges)),
9524 SignedRanges(std::move(Arg.SignedRanges)),
9525 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
Silviu Barangae3c05342015-11-02 14:41:02 +00009526 UniquePreds(std::move(Arg.UniquePreds)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009527 SCEVAllocator(std::move(Arg.SCEVAllocator)),
9528 FirstUnknown(Arg.FirstUnknown) {
9529 Arg.FirstUnknown = nullptr;
Dan Gohmanc8e23622009-04-21 23:15:49 +00009530}
9531
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009532ScalarEvolution::~ScalarEvolution() {
Dan Gohman7cac9572010-08-02 23:49:30 +00009533 // Iterate through all the SCEVUnknown instances and call their
9534 // destructors, so that they release their references to their values.
Naomi Musgravef90c1be2015-09-16 23:46:40 +00009535 for (SCEVUnknown *U = FirstUnknown; U;) {
9536 SCEVUnknown *Tmp = U;
9537 U = U->Next;
9538 Tmp->~SCEVUnknown();
9539 }
Craig Topper9f008862014-04-15 04:59:12 +00009540 FirstUnknown = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00009541
Wei Mia49559b2016-02-04 01:27:38 +00009542 ExprValueMap.clear();
Dan Gohman9bad2fb2010-08-27 18:55:03 +00009543 ValueExprMap.clear();
Wei Mia49559b2016-02-04 01:27:38 +00009544 HasRecMap.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009545
9546 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9547 // that a loop had multiple computable exits.
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009548 for (auto &BTCI : BackedgeTakenCounts)
9549 BTCI.second.clear();
Silviu Baranga6f444df2016-04-08 14:29:09 +00009550 for (auto &BTCI : PredicatedBackedgeTakenCounts)
9551 BTCI.second.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009552
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00009553 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00009554 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
Sanjoy Das7d910f22015-10-02 18:50:30 +00009555 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
Dan Gohman0a40ad92009-04-16 03:18:22 +00009556}
9557
Dan Gohmanc8e23622009-04-21 23:15:49 +00009558bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman0bddac12009-02-24 18:55:53 +00009559 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattnerd934c702004-04-02 20:23:17 +00009560}
9561
Dan Gohmanc8e23622009-04-21 23:15:49 +00009562static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +00009563 const Loop *L) {
9564 // Print all inner loops first
Benjamin Krameraa209152016-06-26 17:27:42 +00009565 for (Loop *I : *L)
9566 PrintLoopInfo(OS, SE, I);
Misha Brukman01808ca2005-04-21 21:13:18 +00009567
Dan Gohmanbc694912010-01-09 18:17:45 +00009568 OS << "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009569 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009570 OS << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009571
Dan Gohmancb0efec2009-12-18 01:14:11 +00009572 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009573 L->getExitBlocks(ExitBlocks);
9574 if (ExitBlocks.size() != 1)
Nick Lewyckyd1200b02008-01-02 02:49:20 +00009575 OS << "<multiple exits> ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009576
Dan Gohman0bddac12009-02-24 18:55:53 +00009577 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9578 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattnerd934c702004-04-02 20:23:17 +00009579 } else {
Dan Gohman0bddac12009-02-24 18:55:53 +00009580 OS << "Unpredictable backedge-taken count. ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009581 }
9582
Dan Gohmanbc694912010-01-09 18:17:45 +00009583 OS << "\n"
9584 "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009585 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009586 OS << ": ";
Dan Gohman69942932009-06-24 00:33:16 +00009587
9588 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9589 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
John Brawn84b21832016-10-21 11:08:48 +00009590 if (SE->isBackedgeTakenCountMaxOrZero(L))
9591 OS << ", actual taken count either this or zero.";
Dan Gohman69942932009-06-24 00:33:16 +00009592 } else {
9593 OS << "Unpredictable max backedge-taken count. ";
9594 }
9595
Silviu Baranga6f444df2016-04-08 14:29:09 +00009596 OS << "\n"
9597 "Loop ";
9598 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9599 OS << ": ";
9600
9601 SCEVUnionPredicate Pred;
9602 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
9603 if (!isa<SCEVCouldNotCompute>(PBT)) {
9604 OS << "Predicated backedge-taken count is " << *PBT << "\n";
9605 OS << " Predicates:\n";
9606 Pred.print(OS, 4);
9607 } else {
9608 OS << "Unpredictable predicated backedge-taken count. ";
9609 }
Dan Gohman69942932009-06-24 00:33:16 +00009610 OS << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00009611}
9612
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009613static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
9614 switch (LD) {
9615 case ScalarEvolution::LoopVariant:
9616 return "Variant";
9617 case ScalarEvolution::LoopInvariant:
9618 return "Invariant";
9619 case ScalarEvolution::LoopComputable:
9620 return "Computable";
9621 }
Simon Pilgrim33ae13d2016-05-01 15:52:31 +00009622 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009623}
9624
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009625void ScalarEvolution::print(raw_ostream &OS) const {
Dan Gohman8b0a4192010-03-01 17:49:51 +00009626 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanc8e23622009-04-21 23:15:49 +00009627 // out SCEV values of all instructions that are interesting. Doing
9628 // this potentially causes it to create new SCEV objects though,
9629 // which technically conflicts with the const qualifier. This isn't
Dan Gohman028e6152009-07-10 20:25:29 +00009630 // observable from outside the class though, so casting away the
9631 // const isn't dangerous.
Dan Gohmancb0efec2009-12-18 01:14:11 +00009632 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattnerd934c702004-04-02 20:23:17 +00009633
Dan Gohmanbc694912010-01-09 18:17:45 +00009634 OS << "Classifying expressions for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009635 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009636 OS << "\n";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009637 for (Instruction &I : instructions(F))
9638 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9639 OS << I << '\n';
Dan Gohman81313fd2008-09-14 17:21:12 +00009640 OS << " --> ";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009641 const SCEV *SV = SE.getSCEV(&I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009642 SV->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009643 if (!isa<SCEVCouldNotCompute>(SV)) {
9644 OS << " U: ";
9645 SE.getUnsignedRange(SV).print(OS);
9646 OS << " S: ";
9647 SE.getSignedRange(SV).print(OS);
9648 }
Misha Brukman01808ca2005-04-21 21:13:18 +00009649
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009650 const Loop *L = LI.getLoopFor(I.getParent());
Dan Gohmanb9063a82009-06-19 17:49:54 +00009651
Dan Gohmanaf752342009-07-07 17:06:11 +00009652 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohmanb9063a82009-06-19 17:49:54 +00009653 if (AtUse != SV) {
9654 OS << " --> ";
9655 AtUse->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009656 if (!isa<SCEVCouldNotCompute>(AtUse)) {
9657 OS << " U: ";
9658 SE.getUnsignedRange(AtUse).print(OS);
9659 OS << " S: ";
9660 SE.getSignedRange(AtUse).print(OS);
9661 }
Dan Gohmanb9063a82009-06-19 17:49:54 +00009662 }
9663
9664 if (L) {
Dan Gohman94c468f2009-06-18 00:37:45 +00009665 OS << "\t\t" "Exits: ";
Dan Gohmanaf752342009-07-07 17:06:11 +00009666 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanafd6db92010-11-17 21:23:15 +00009667 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00009668 OS << "<<Unknown>>";
9669 } else {
9670 OS << *ExitValue;
9671 }
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009672
9673 bool First = true;
9674 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
9675 if (First) {
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009676 OS << "\t\t" "LoopDispositions: { ";
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009677 First = false;
9678 } else {
9679 OS << ", ";
9680 }
9681
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009682 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9683 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
Sanjoy Dasf2f00fb12016-05-01 04:51:05 +00009684 }
9685
Sanjoy Das013a4ac2016-05-03 17:49:57 +00009686 for (auto *InnerL : depth_first(L)) {
9687 if (InnerL == L)
9688 continue;
9689 if (First) {
9690 OS << "\t\t" "LoopDispositions: { ";
9691 First = false;
9692 } else {
9693 OS << ", ";
9694 }
9695
9696 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9697 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
9698 }
9699
9700 OS << " }";
Chris Lattnerd934c702004-04-02 20:23:17 +00009701 }
9702
Chris Lattnerd934c702004-04-02 20:23:17 +00009703 OS << "\n";
9704 }
9705
Dan Gohmanbc694912010-01-09 18:17:45 +00009706 OS << "Determining loop execution counts for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009707 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009708 OS << "\n";
Benjamin Krameraa209152016-06-26 17:27:42 +00009709 for (Loop *I : LI)
9710 PrintLoopInfo(OS, &SE, I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009711}
Dan Gohmane20f8242009-04-21 00:47:46 +00009712
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009713ScalarEvolution::LoopDisposition
9714ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009715 auto &Values = LoopDispositions[S];
9716 for (auto &V : Values) {
9717 if (V.getPointer() == L)
9718 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009719 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009720 Values.emplace_back(L, LoopVariant);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009721 LoopDisposition D = computeLoopDisposition(S, L);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009722 auto &Values2 = LoopDispositions[S];
9723 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9724 if (V.getPointer() == L) {
9725 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009726 break;
9727 }
9728 }
9729 return D;
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009730}
9731
9732ScalarEvolution::LoopDisposition
9733ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009734 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009735 case scConstant:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009736 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009737 case scTruncate:
9738 case scZeroExtend:
9739 case scSignExtend:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009740 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohmanafd6db92010-11-17 21:23:15 +00009741 case scAddRecExpr: {
9742 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9743
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009744 // If L is the addrec's loop, it's computable.
9745 if (AR->getLoop() == L)
9746 return LoopComputable;
9747
Dan Gohmanafd6db92010-11-17 21:23:15 +00009748 // Add recurrences are never invariant in the function-body (null loop).
9749 if (!L)
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009750 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009751
9752 // This recurrence is variant w.r.t. L if L contains AR's loop.
9753 if (L->contains(AR->getLoop()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009754 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009755
9756 // This recurrence is invariant w.r.t. L if AR's loop contains L.
9757 if (AR->getLoop()->contains(L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009758 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009759
9760 // This recurrence is variant w.r.t. L if any of its operands
9761 // are variant.
Sanjoy Das01947432015-11-22 21:20:13 +00009762 for (auto *Op : AR->operands())
9763 if (!isLoopInvariant(Op, L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009764 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009765
9766 // Otherwise it's loop-invariant.
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009767 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009768 }
9769 case scAddExpr:
9770 case scMulExpr:
9771 case scUMaxExpr:
9772 case scSMaxExpr: {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009773 bool HasVarying = false;
Sanjoy Das01947432015-11-22 21:20:13 +00009774 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
9775 LoopDisposition D = getLoopDisposition(Op, L);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009776 if (D == LoopVariant)
9777 return LoopVariant;
9778 if (D == LoopComputable)
9779 HasVarying = true;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009780 }
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009781 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009782 }
9783 case scUDivExpr: {
9784 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009785 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9786 if (LD == LoopVariant)
9787 return LoopVariant;
9788 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9789 if (RD == LoopVariant)
9790 return LoopVariant;
9791 return (LD == LoopInvariant && RD == LoopInvariant) ?
9792 LoopInvariant : LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009793 }
9794 case scUnknown:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009795 // All non-instruction values are loop invariant. All instructions are loop
9796 // invariant if they are not contained in the specified loop.
9797 // Instructions are never considered invariant in the function body
9798 // (null loop) because they are defined within the "loop".
Sanjoy Das01947432015-11-22 21:20:13 +00009799 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009800 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9801 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009802 case scCouldNotCompute:
9803 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanafd6db92010-11-17 21:23:15 +00009804 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009805 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009806}
9807
9808bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9809 return getLoopDisposition(S, L) == LoopInvariant;
9810}
9811
9812bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9813 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009814}
Dan Gohman20d9ce22010-11-17 21:41:58 +00009815
Dan Gohman8ea83d82010-11-18 00:34:22 +00009816ScalarEvolution::BlockDisposition
9817ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009818 auto &Values = BlockDispositions[S];
9819 for (auto &V : Values) {
9820 if (V.getPointer() == BB)
9821 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009822 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009823 Values.emplace_back(BB, DoesNotDominateBlock);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009824 BlockDisposition D = computeBlockDisposition(S, BB);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009825 auto &Values2 = BlockDispositions[S];
9826 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9827 if (V.getPointer() == BB) {
9828 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009829 break;
9830 }
9831 }
9832 return D;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009833}
9834
Dan Gohman8ea83d82010-11-18 00:34:22 +00009835ScalarEvolution::BlockDisposition
9836ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009837 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohman20d9ce22010-11-17 21:41:58 +00009838 case scConstant:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009839 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009840 case scTruncate:
9841 case scZeroExtend:
9842 case scSignExtend:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009843 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohman20d9ce22010-11-17 21:41:58 +00009844 case scAddRecExpr: {
9845 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman8ea83d82010-11-18 00:34:22 +00009846 // to test for proper dominance too, because the instruction which
9847 // produces the addrec's value is a PHI, and a PHI effectively properly
9848 // dominates its entire containing block.
Dan Gohman20d9ce22010-11-17 21:41:58 +00009849 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009850 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009851 return DoesNotDominateBlock;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00009852
9853 // Fall through into SCEVNAryExpr handling.
9854 LLVM_FALLTHROUGH;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009855 }
Dan Gohman20d9ce22010-11-17 21:41:58 +00009856 case scAddExpr:
9857 case scMulExpr:
9858 case scUMaxExpr:
9859 case scSMaxExpr: {
9860 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009861 bool Proper = true;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00009862 for (const SCEV *NAryOp : NAry->operands()) {
9863 BlockDisposition D = getBlockDisposition(NAryOp, BB);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009864 if (D == DoesNotDominateBlock)
9865 return DoesNotDominateBlock;
9866 if (D == DominatesBlock)
9867 Proper = false;
9868 }
9869 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009870 }
9871 case scUDivExpr: {
9872 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009873 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
9874 BlockDisposition LD = getBlockDisposition(LHS, BB);
9875 if (LD == DoesNotDominateBlock)
9876 return DoesNotDominateBlock;
9877 BlockDisposition RD = getBlockDisposition(RHS, BB);
9878 if (RD == DoesNotDominateBlock)
9879 return DoesNotDominateBlock;
9880 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
9881 ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009882 }
9883 case scUnknown:
9884 if (Instruction *I =
Dan Gohman8ea83d82010-11-18 00:34:22 +00009885 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
9886 if (I->getParent() == BB)
9887 return DominatesBlock;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009888 if (DT.properlyDominates(I->getParent(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009889 return ProperlyDominatesBlock;
9890 return DoesNotDominateBlock;
9891 }
9892 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009893 case scCouldNotCompute:
9894 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman20d9ce22010-11-17 21:41:58 +00009895 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009896 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman8ea83d82010-11-18 00:34:22 +00009897}
9898
9899bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
9900 return getBlockDisposition(S, BB) >= DominatesBlock;
9901}
9902
9903bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
9904 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009905}
Dan Gohman534749b2010-11-17 22:27:42 +00009906
9907bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
Sanjoy Das6b46a0d2016-11-09 18:22:43 +00009908 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
Dan Gohman534749b2010-11-17 22:27:42 +00009909}
Dan Gohman7e6b3932010-11-17 23:28:48 +00009910
9911void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
9912 ValuesAtScopes.erase(S);
9913 LoopDispositions.erase(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009914 BlockDispositions.erase(S);
Dan Gohman7e6b3932010-11-17 23:28:48 +00009915 UnsignedRanges.erase(S);
9916 SignedRanges.erase(S);
Wei Mia49559b2016-02-04 01:27:38 +00009917 ExprValueMap.erase(S);
9918 HasRecMap.erase(S);
Andrew Trick9093e152013-03-26 03:14:53 +00009919
Silviu Baranga6f444df2016-04-08 14:29:09 +00009920 auto RemoveSCEVFromBackedgeMap =
9921 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
9922 for (auto I = Map.begin(), E = Map.end(); I != E;) {
9923 BackedgeTakenInfo &BEInfo = I->second;
9924 if (BEInfo.hasOperand(S, this)) {
9925 BEInfo.clear();
9926 Map.erase(I++);
9927 } else
9928 ++I;
9929 }
9930 };
9931
9932 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
9933 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohman7e6b3932010-11-17 23:28:48 +00009934}
Benjamin Kramer214935e2012-10-26 17:31:32 +00009935
9936typedef DenseMap<const Loop *, std::string> VerifyMap;
Benjamin Kramer24d270d2012-10-27 10:45:01 +00009937
Alp Tokercb402912014-01-24 17:20:08 +00009938/// replaceSubString - Replaces all occurrences of From in Str with To.
Benjamin Kramer24d270d2012-10-27 10:45:01 +00009939static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
9940 size_t Pos = 0;
9941 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
9942 Str.replace(Pos, From.size(), To.data(), To.size());
9943 Pos += To.size();
9944 }
9945}
9946
Benjamin Kramer214935e2012-10-26 17:31:32 +00009947/// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
9948static void
9949getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
Sanjoy Das2fbfb252015-12-23 17:48:14 +00009950 std::string &S = Map[L];
9951 if (S.empty()) {
9952 raw_string_ostream OS(S);
9953 SE.getBackedgeTakenCount(L)->print(OS);
Benjamin Kramer214935e2012-10-26 17:31:32 +00009954
Sanjoy Das2fbfb252015-12-23 17:48:14 +00009955 // false and 0 are semantically equivalent. This can happen in dead loops.
9956 replaceSubString(OS.str(), "false", "0");
9957 // Remove wrap flags, their use in SCEV is highly fragile.
9958 // FIXME: Remove this when SCEV gets smarter about them.
9959 replaceSubString(OS.str(), "<nw>", "");
9960 replaceSubString(OS.str(), "<nsw>", "");
9961 replaceSubString(OS.str(), "<nuw>", "");
Benjamin Kramer214935e2012-10-26 17:31:32 +00009962 }
Sanjoy Das2fbfb252015-12-23 17:48:14 +00009963
JF Bastien61ad8b32015-12-23 18:18:53 +00009964 for (auto *R : reverse(*L))
9965 getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
Benjamin Kramer214935e2012-10-26 17:31:32 +00009966}
9967
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009968void ScalarEvolution::verify() const {
Benjamin Kramer214935e2012-10-26 17:31:32 +00009969 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9970
9971 // Gather stringified backedge taken counts for all loops using SCEV's caches.
9972 // FIXME: It would be much better to store actual values instead of strings,
9973 // but SCEV pointers will change if we drop the caches.
9974 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009975 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
Benjamin Kramer214935e2012-10-26 17:31:32 +00009976 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
9977
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009978 // Gather stringified backedge taken counts for all loops using a fresh
9979 // ScalarEvolution object.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00009980 ScalarEvolution SE2(F, TLI, AC, DT, LI);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009981 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
9982 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
Benjamin Kramer214935e2012-10-26 17:31:32 +00009983
9984 // Now compare whether they're the same with and without caches. This allows
9985 // verifying that no pass changed the cache.
9986 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
9987 "New loops suddenly appeared!");
9988
9989 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
9990 OldE = BackedgeDumpsOld.end(),
9991 NewI = BackedgeDumpsNew.begin();
9992 OldI != OldE; ++OldI, ++NewI) {
9993 assert(OldI->first == NewI->first && "Loop order changed!");
9994
9995 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
9996 // changes.
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009997 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
Benjamin Kramer214935e2012-10-26 17:31:32 +00009998 // means that a pass is buggy or SCEV has to learn a new pattern but is
9999 // usually not harmful.
10000 if (OldI->second != NewI->second &&
10001 OldI->second.find("undef") == std::string::npos &&
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010002 NewI->second.find("undef") == std::string::npos &&
10003 OldI->second != "***COULDNOTCOMPUTE***" &&
Benjamin Kramer214935e2012-10-26 17:31:32 +000010004 NewI->second != "***COULDNOTCOMPUTE***") {
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010005 dbgs() << "SCEVValidator: SCEV for loop '"
Benjamin Kramer214935e2012-10-26 17:31:32 +000010006 << OldI->first->getHeader()->getName()
Benjamin Kramer5bc077a2012-10-27 11:36:07 +000010007 << "' changed from '" << OldI->second
10008 << "' to '" << NewI->second << "'!\n";
Benjamin Kramer214935e2012-10-26 17:31:32 +000010009 std::abort();
10010 }
10011 }
10012
10013 // TODO: Verify more things.
10014}
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010015
Chandler Carruthdab4eae2016-11-23 17:53:26 +000010016AnalysisKey ScalarEvolutionAnalysis::Key;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +000010017
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010018ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +000010019 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +000010020 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010021 AM.getResult<AssumptionAnalysis>(F),
Chandler Carruthb47f8012016-03-11 11:05:24 +000010022 AM.getResult<DominatorTreeAnalysis>(F),
10023 AM.getResult<LoopAnalysis>(F));
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010024}
10025
10026PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +000010027ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +000010028 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010029 return PreservedAnalyses::all();
10030}
10031
10032INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10033 "Scalar Evolution Analysis", false, true)
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010034INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010035INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10036INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10037INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10038INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10039 "Scalar Evolution Analysis", false, true)
10040char ScalarEvolutionWrapperPass::ID = 0;
10041
10042ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10043 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10044}
10045
10046bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10047 SE.reset(new ScalarEvolution(
10048 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010049 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010050 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10051 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10052 return false;
10053}
10054
10055void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10056
10057void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10058 SE->print(OS);
10059}
10060
10061void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10062 if (!VerifySCEV)
10063 return;
10064
10065 SE->verify();
10066}
10067
10068void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10069 AU.setPreservesAll();
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010070 AU.addRequiredTransitive<AssumptionCacheTracker>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000010071 AU.addRequiredTransitive<LoopInfoWrapperPass>();
10072 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10073 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10074}
Silviu Barangae3c05342015-11-02 14:41:02 +000010075
10076const SCEVPredicate *
10077ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10078 const SCEVConstant *RHS) {
10079 FoldingSetNodeID ID;
10080 // Unique this node based on the arguments
10081 ID.AddInteger(SCEVPredicate::P_Equal);
10082 ID.AddPointer(LHS);
10083 ID.AddPointer(RHS);
10084 void *IP = nullptr;
10085 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10086 return S;
10087 SCEVEqualPredicate *Eq = new (SCEVAllocator)
10088 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10089 UniquePreds.InsertNode(Eq, IP);
10090 return Eq;
10091}
10092
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010093const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10094 const SCEVAddRecExpr *AR,
10095 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10096 FoldingSetNodeID ID;
10097 // Unique this node based on the arguments
10098 ID.AddInteger(SCEVPredicate::P_Wrap);
10099 ID.AddPointer(AR);
10100 ID.AddInteger(AddedFlags);
10101 void *IP = nullptr;
10102 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10103 return S;
10104 auto *OF = new (SCEVAllocator)
10105 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10106 UniquePreds.InsertNode(OF, IP);
10107 return OF;
10108}
10109
Benjamin Kramer83709b12015-11-16 09:01:28 +000010110namespace {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010111
Silviu Barangae3c05342015-11-02 14:41:02 +000010112class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10113public:
Sanjoy Dasf0022122016-09-28 17:14:58 +000010114 /// Rewrites \p S in the context of a loop L and the SCEV predication
10115 /// infrastructure.
10116 ///
10117 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
10118 /// equivalences present in \p Pred.
10119 ///
10120 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
10121 /// \p NewPreds such that the result will be an AddRecExpr.
Sanjoy Das807d33d2016-02-20 01:44:10 +000010122 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
Sanjoy Dasf0022122016-09-28 17:14:58 +000010123 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10124 SCEVUnionPredicate *Pred) {
10125 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
Sanjoy Das807d33d2016-02-20 01:44:10 +000010126 return Rewriter.visit(S);
Silviu Barangae3c05342015-11-02 14:41:02 +000010127 }
10128
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010129 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
Sanjoy Dasf0022122016-09-28 17:14:58 +000010130 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10131 SCEVUnionPredicate *Pred)
10132 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
Silviu Barangae3c05342015-11-02 14:41:02 +000010133
10134 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
Sanjoy Dasf0022122016-09-28 17:14:58 +000010135 if (Pred) {
10136 auto ExprPreds = Pred->getPredicatesForExpr(Expr);
10137 for (auto *Pred : ExprPreds)
10138 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
10139 if (IPred->getLHS() == Expr)
10140 return IPred->getRHS();
10141 }
Silviu Barangae3c05342015-11-02 14:41:02 +000010142
10143 return Expr;
10144 }
10145
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010146 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10147 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010148 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010149 if (AR && AR->getLoop() == L && AR->isAffine()) {
10150 // This couldn't be folded because the operand didn't have the nuw
10151 // flag. Add the nusw flag as an assumption that we could make.
10152 const SCEV *Step = AR->getStepRecurrence(SE);
10153 Type *Ty = Expr->getType();
10154 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10155 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10156 SE.getSignExtendExpr(Step, Ty), L,
10157 AR->getNoWrapFlags());
10158 }
10159 return SE.getZeroExtendExpr(Operand, Expr->getType());
10160 }
10161
10162 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10163 const SCEV *Operand = visit(Expr->getOperand());
Sanjoy Dasb277a422016-06-15 06:53:55 +000010164 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010165 if (AR && AR->getLoop() == L && AR->isAffine()) {
10166 // This couldn't be folded because the operand didn't have the nsw
10167 // flag. Add the nssw flag as an assumption that we could make.
10168 const SCEV *Step = AR->getStepRecurrence(SE);
10169 Type *Ty = Expr->getType();
10170 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10171 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10172 SE.getSignExtendExpr(Step, Ty), L,
10173 AR->getNoWrapFlags());
10174 }
10175 return SE.getSignExtendExpr(Operand, Expr->getType());
10176 }
10177
Silviu Barangae3c05342015-11-02 14:41:02 +000010178private:
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010179 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10180 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10181 auto *A = SE.getWrapPredicate(AR, AddedFlags);
Sanjoy Dasf0022122016-09-28 17:14:58 +000010182 if (!NewPreds) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010183 // Check if we've already made this assumption.
Sanjoy Dasf0022122016-09-28 17:14:58 +000010184 return Pred && Pred->implies(A);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010185 }
Sanjoy Dasf0022122016-09-28 17:14:58 +000010186 NewPreds->insert(A);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010187 return true;
10188 }
10189
Sanjoy Dasf0022122016-09-28 17:14:58 +000010190 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
10191 SCEVUnionPredicate *Pred;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010192 const Loop *L;
Silviu Barangae3c05342015-11-02 14:41:02 +000010193};
Benjamin Kramer83709b12015-11-16 09:01:28 +000010194} // end anonymous namespace
Silviu Barangae3c05342015-11-02 14:41:02 +000010195
Sanjoy Das807d33d2016-02-20 01:44:10 +000010196const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
Silviu Barangae3c05342015-11-02 14:41:02 +000010197 SCEVUnionPredicate &Preds) {
Sanjoy Dasf0022122016-09-28 17:14:58 +000010198 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010199}
10200
Sanjoy Dasf0022122016-09-28 17:14:58 +000010201const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
10202 const SCEV *S, const Loop *L,
10203 SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
10204
10205 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
10206 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
Silviu Barangad68ed852016-03-23 15:29:30 +000010207 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10208
10209 if (!AddRec)
10210 return nullptr;
10211
10212 // Since the transformation was successful, we can now transfer the SCEV
10213 // predicates.
Sanjoy Dasf0022122016-09-28 17:14:58 +000010214 for (auto *P : TransformPreds)
10215 Preds.insert(P);
10216
Silviu Barangad68ed852016-03-23 15:29:30 +000010217 return AddRec;
Silviu Barangae3c05342015-11-02 14:41:02 +000010218}
10219
10220/// SCEV predicates
10221SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10222 SCEVPredicateKind Kind)
10223 : FastID(ID), Kind(Kind) {}
10224
10225SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10226 const SCEVUnknown *LHS,
10227 const SCEVConstant *RHS)
10228 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10229
10230bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010231 const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
Silviu Barangae3c05342015-11-02 14:41:02 +000010232
10233 if (!Op)
10234 return false;
10235
10236 return Op->LHS == LHS && Op->RHS == RHS;
10237}
10238
10239bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10240
10241const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10242
10243void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10244 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10245}
10246
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010247SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10248 const SCEVAddRecExpr *AR,
10249 IncrementWrapFlags Flags)
10250 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10251
10252const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10253
10254bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10255 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10256
10257 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10258}
10259
10260bool SCEVWrapPredicate::isAlwaysTrue() const {
10261 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10262 IncrementWrapFlags IFlags = Flags;
10263
10264 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10265 IFlags = clearFlags(IFlags, IncrementNSSW);
10266
10267 return IFlags == IncrementAnyWrap;
10268}
10269
10270void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10271 OS.indent(Depth) << *getExpr() << " Added Flags: ";
10272 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10273 OS << "<nusw>";
10274 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10275 OS << "<nssw>";
10276 OS << "\n";
10277}
10278
10279SCEVWrapPredicate::IncrementWrapFlags
10280SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10281 ScalarEvolution &SE) {
10282 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10283 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10284
10285 // We can safely transfer the NSW flag as NSSW.
10286 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10287 ImpliedFlags = IncrementNSSW;
10288
10289 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10290 // If the increment is positive, the SCEV NUW flag will also imply the
10291 // WrapPredicate NUSW flag.
10292 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10293 if (Step->getValue()->getValue().isNonNegative())
10294 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10295 }
10296
10297 return ImpliedFlags;
10298}
10299
Silviu Barangae3c05342015-11-02 14:41:02 +000010300/// Union predicates don't get cached so create a dummy set ID for it.
10301SCEVUnionPredicate::SCEVUnionPredicate()
10302 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10303
10304bool SCEVUnionPredicate::isAlwaysTrue() const {
Sanjoy Das3b827c72015-11-29 23:40:53 +000010305 return all_of(Preds,
10306 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010307}
10308
10309ArrayRef<const SCEVPredicate *>
10310SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10311 auto I = SCEVToPreds.find(Expr);
10312 if (I == SCEVToPreds.end())
10313 return ArrayRef<const SCEVPredicate *>();
10314 return I->second;
10315}
10316
10317bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010318 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
Sanjoy Das3b827c72015-11-29 23:40:53 +000010319 return all_of(Set->Preds,
10320 [this](const SCEVPredicate *I) { return this->implies(I); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010321
10322 auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10323 if (ScevPredsIt == SCEVToPreds.end())
10324 return false;
10325 auto &SCEVPreds = ScevPredsIt->second;
10326
Sanjoy Dasff3b8b42015-12-01 07:49:23 +000010327 return any_of(SCEVPreds,
10328 [N](const SCEVPredicate *I) { return I->implies(N); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010329}
10330
10331const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10332
10333void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10334 for (auto Pred : Preds)
10335 Pred->print(OS, Depth);
10336}
10337
10338void SCEVUnionPredicate::add(const SCEVPredicate *N) {
Sanjoy Dasb277a422016-06-15 06:53:55 +000010339 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
Silviu Barangae3c05342015-11-02 14:41:02 +000010340 for (auto Pred : Set->Preds)
10341 add(Pred);
10342 return;
10343 }
10344
10345 if (implies(N))
10346 return;
10347
10348 const SCEV *Key = N->getExpr();
10349 assert(Key && "Only SCEVUnionPredicate doesn't have an "
10350 " associated expression!");
10351
10352 SCEVToPreds[Key].push_back(N);
10353 Preds.push_back(N);
10354}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010355
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010356PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10357 Loop &L)
Silviu Baranga6f444df2016-04-08 14:29:09 +000010358 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010359
10360const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10361 const SCEV *Expr = SE.getSCEV(V);
10362 RewriteEntry &Entry = RewriteMap[Expr];
10363
10364 // If we already have an entry and the version matches, return it.
10365 if (Entry.second && Generation == Entry.first)
10366 return Entry.second;
10367
10368 // We found an entry but it's stale. Rewrite the stale entry
Simon Pilgrimf2fbf432016-11-20 13:47:59 +000010369 // according to the current predicate.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010370 if (Entry.second)
10371 Expr = Entry.second;
10372
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010373 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010374 Entry = {Generation, NewSCEV};
10375
10376 return NewSCEV;
10377}
10378
Silviu Baranga6f444df2016-04-08 14:29:09 +000010379const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10380 if (!BackedgeCount) {
10381 SCEVUnionPredicate BackedgePred;
10382 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10383 addPredicate(BackedgePred);
10384 }
10385 return BackedgeCount;
10386}
10387
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010388void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10389 if (Preds.implies(&Pred))
10390 return;
10391 Preds.add(&Pred);
10392 updateGeneration();
10393}
10394
10395const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10396 return Preds;
10397}
10398
10399void PredicatedScalarEvolution::updateGeneration() {
10400 // If the generation number wrapped recompute everything.
10401 if (++Generation == 0) {
10402 for (auto &II : RewriteMap) {
10403 const SCEV *Rewritten = II.second.second;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010404 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010405 }
10406 }
10407}
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010408
10409void PredicatedScalarEvolution::setNoOverflow(
10410 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10411 const SCEV *Expr = getSCEV(V);
10412 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10413
10414 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10415
10416 // Clear the statically implied flags.
10417 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10418 addPredicate(*SE.getWrapPredicate(AR, Flags));
10419
10420 auto II = FlagsMap.insert({V, Flags});
10421 if (!II.second)
10422 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10423}
10424
10425bool PredicatedScalarEvolution::hasNoOverflow(
10426 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10427 const SCEV *Expr = getSCEV(V);
10428 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10429
10430 Flags = SCEVWrapPredicate::clearFlags(
10431 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10432
10433 auto II = FlagsMap.find(V);
10434
10435 if (II != FlagsMap.end())
10436 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10437
10438 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10439}
10440
Silviu Barangad68ed852016-03-23 15:29:30 +000010441const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010442 const SCEV *Expr = this->getSCEV(V);
Sanjoy Dasf0022122016-09-28 17:14:58 +000010443 SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
10444 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
Silviu Barangad68ed852016-03-23 15:29:30 +000010445
10446 if (!New)
10447 return nullptr;
10448
Sanjoy Dasf0022122016-09-28 17:14:58 +000010449 for (auto *P : NewPreds)
10450 Preds.add(P);
10451
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010452 updateGeneration();
10453 RewriteMap[SE.getSCEV(V)] = {Generation, New};
10454 return New;
10455}
10456
Silviu Baranga6f444df2016-04-08 14:29:09 +000010457PredicatedScalarEvolution::PredicatedScalarEvolution(
10458 const PredicatedScalarEvolution &Init)
10459 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10460 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
Benjamin Krameraa209152016-06-26 17:27:42 +000010461 for (const auto &I : Init.FlagsMap)
10462 FlagsMap.insert(I);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010463}
Silviu Barangab77365b2016-04-14 16:08:45 +000010464
10465void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10466 // For each block.
10467 for (auto *BB : L.getBlocks())
10468 for (auto &I : *BB) {
10469 if (!SE.isSCEVable(I.getType()))
10470 continue;
10471
10472 auto *Expr = SE.getSCEV(&I);
10473 auto II = RewriteMap.find(Expr);
10474
10475 if (II == RewriteMap.end())
10476 continue;
10477
10478 // Don't print things that are not interesting.
10479 if (II->second.second == Expr)
10480 continue;
10481
10482 OS.indent(Depth) << "[PSE]" << I << ":\n";
10483 OS.indent(Depth + 2) << *Expr << "\n";
10484 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
10485 }
10486}