blob: f8edbf4b0ceeba26b66b010b76952cb13dc76a12 [file] [log] [blame]
Nick Lewycky97756402014-09-01 05:17:15 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
Misha Brukman01808ca2005-04-21 21:13:18 +00002//
Chris Lattnerd934c702004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman01808ca2005-04-21 21:13:18 +00007//
Chris Lattnerd934c702004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
Dan Gohmanef2ae2c2009-07-25 16:18:07 +000017// can handle. We only create one SCEV of a particular shape, so
18// pointer-comparisons for equality are legal.
Chris Lattnerd934c702004-04-02 20:23:17 +000019//
20// One important aspect of the SCEV objects is that they are never cyclic, even
21// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
22// the PHI node is one of the idioms that we can represent (e.g., a polynomial
23// recurrence) then we represent it directly as a recurrence node, otherwise we
24// represent it as a SCEVUnknown node.
25//
26// In addition to being able to represent expressions of various types, we also
27// have folders that are used to build the *canonical* representation for a
28// particular expression. These folders are capable of using a variety of
29// rewrite rules to simplify the expressions.
Misha Brukman01808ca2005-04-21 21:13:18 +000030//
Chris Lattnerd934c702004-04-02 20:23:17 +000031// Once the folders are defined, we can implement the more interesting
32// higher-level code, such as the code that recognizes PHI nodes of various
33// types, computes the execution count of a loop, etc.
34//
Chris Lattnerd934c702004-04-02 20:23:17 +000035// TODO: We should use these routines and value representations to implement
36// dependence analysis!
37//
38//===----------------------------------------------------------------------===//
39//
40// There are several good references for the techniques used in this analysis.
41//
42// Chains of recurrences -- a method to expedite the evaluation
43// of closed-form functions
44// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45//
46// On computational properties of chains of recurrences
47// Eugene V. Zima
48//
49// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50// Robert A. van Engelen
51//
52// Efficient Symbolic Analysis for Optimizing Compilers
53// Robert A. van Engelen
54//
55// Using the chains of recurrences algebra for data dependence testing and
56// induction variable substitution
57// MS Thesis, Johnie Birch
58//
59//===----------------------------------------------------------------------===//
60
Chandler Carruthed0881b2012-12-03 16:50:05 +000061#include "llvm/Analysis/ScalarEvolution.h"
Sanjoy Das1f05c512014-10-10 21:22:34 +000062#include "llvm/ADT/Optional.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000063#include "llvm/ADT/STLExtras.h"
64#include "llvm/ADT/SmallPtrSet.h"
65#include "llvm/ADT/Statistic.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000066#include "llvm/Analysis/AssumptionCache.h"
John Criswellfe5f33b2005-10-27 15:54:34 +000067#include "llvm/Analysis/ConstantFolding.h"
Duncan Sandsd06f50e2010-11-17 04:18:45 +000068#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000069#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000070#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000071#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman1ee696d2009-06-16 19:52:01 +000072#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000073#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000074#include "llvm/IR/Constants.h"
75#include "llvm/IR/DataLayout.h"
76#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000077#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000078#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000079#include "llvm/IR/GlobalAlias.h"
80#include "llvm/IR/GlobalVariable.h"
Chandler Carruth83948572014-03-04 10:30:26 +000081#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000082#include "llvm/IR/Instructions.h"
83#include "llvm/IR/LLVMContext.h"
Sanjoy Das1f05c512014-10-10 21:22:34 +000084#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000085#include "llvm/IR/Operator.h"
Sanjoy Dasc88f5d32015-10-28 21:27:14 +000086#include "llvm/IR/PatternMatch.h"
Chris Lattner996795b2006-06-28 23:17:24 +000087#include "llvm/Support/CommandLine.h"
David Greene2330f782009-12-23 22:58:38 +000088#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000089#include "llvm/Support/ErrorHandling.h"
Chris Lattner0a1e9932006-12-19 01:16:02 +000090#include "llvm/Support/MathExtras.h"
Dan Gohmane20f8242009-04-21 00:47:46 +000091#include "llvm/Support/raw_ostream.h"
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +000092#include "llvm/Support/SaveAndRestore.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000093#include <algorithm>
Chris Lattnerd934c702004-04-02 20:23:17 +000094using namespace llvm;
95
Chandler Carruthf1221bd2014-04-22 02:48:03 +000096#define DEBUG_TYPE "scalar-evolution"
97
Chris Lattner57ef9422006-12-19 22:30:33 +000098STATISTIC(NumArrayLenItCounts,
99 "Number of trip counts computed with array length");
100STATISTIC(NumTripCountsComputed,
101 "Number of loops with predictable loop counts");
102STATISTIC(NumTripCountsNotComputed,
103 "Number of loops without predictable loop counts");
104STATISTIC(NumBruteForceTripCountsComputed,
105 "Number of loops with trip counts computed by force");
106
Dan Gohmand78c4002008-05-13 00:00:25 +0000107static cl::opt<unsigned>
Chris Lattner57ef9422006-12-19 22:30:33 +0000108MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
109 cl::desc("Maximum number of iterations SCEV will "
Dan Gohmance973df2009-06-24 04:48:43 +0000110 "symbolically execute a constant "
111 "derived loop"),
Chris Lattner57ef9422006-12-19 22:30:33 +0000112 cl::init(100));
113
Benjamin Kramer214935e2012-10-26 17:31:32 +0000114// FIXME: Enable this with XDEBUG when the test suite is clean.
115static cl::opt<bool>
116VerifySCEV("verify-scev",
117 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
Wei Mia49559b2016-02-04 01:27:38 +0000118static cl::opt<bool>
119 VerifySCEVMap("verify-scev-maps",
120 cl::desc("Verify no dangling value in ScalarEvolution's"
121 "ExprValueMap (slow)"));
Benjamin Kramer214935e2012-10-26 17:31:32 +0000122
Chris Lattnerd934c702004-04-02 20:23:17 +0000123//===----------------------------------------------------------------------===//
124// SCEV class definitions
125//===----------------------------------------------------------------------===//
126
127//===----------------------------------------------------------------------===//
128// Implementation of the SCEV class.
129//
Dan Gohman3423e722009-06-30 20:13:32 +0000130
Davide Italiano2071f4c2015-10-25 19:55:24 +0000131LLVM_DUMP_METHOD
132void SCEV::dump() const {
133 print(dbgs());
134 dbgs() << '\n';
135}
136
Dan Gohman534749b2010-11-17 22:27:42 +0000137void SCEV::print(raw_ostream &OS) const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000138 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000139 case scConstant:
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000140 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000141 return;
142 case scTruncate: {
143 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
144 const SCEV *Op = Trunc->getOperand();
145 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
146 << *Trunc->getType() << ")";
147 return;
148 }
149 case scZeroExtend: {
150 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
151 const SCEV *Op = ZExt->getOperand();
152 OS << "(zext " << *Op->getType() << " " << *Op << " to "
153 << *ZExt->getType() << ")";
154 return;
155 }
156 case scSignExtend: {
157 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
158 const SCEV *Op = SExt->getOperand();
159 OS << "(sext " << *Op->getType() << " " << *Op << " to "
160 << *SExt->getType() << ")";
161 return;
162 }
163 case scAddRecExpr: {
164 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
165 OS << "{" << *AR->getOperand(0);
166 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
167 OS << ",+," << *AR->getOperand(i);
168 OS << "}<";
Andrew Trick8b55b732011-03-14 16:50:06 +0000169 if (AR->getNoWrapFlags(FlagNUW))
Chris Lattnera337f5e2011-01-09 02:16:18 +0000170 OS << "nuw><";
Andrew Trick8b55b732011-03-14 16:50:06 +0000171 if (AR->getNoWrapFlags(FlagNSW))
Chris Lattnera337f5e2011-01-09 02:16:18 +0000172 OS << "nsw><";
Andrew Trick8b55b732011-03-14 16:50:06 +0000173 if (AR->getNoWrapFlags(FlagNW) &&
174 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
175 OS << "nw><";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000176 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman534749b2010-11-17 22:27:42 +0000177 OS << ">";
178 return;
179 }
180 case scAddExpr:
181 case scMulExpr:
182 case scUMaxExpr:
183 case scSMaxExpr: {
184 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
Craig Topper9f008862014-04-15 04:59:12 +0000185 const char *OpStr = nullptr;
Dan Gohman534749b2010-11-17 22:27:42 +0000186 switch (NAry->getSCEVType()) {
187 case scAddExpr: OpStr = " + "; break;
188 case scMulExpr: OpStr = " * "; break;
189 case scUMaxExpr: OpStr = " umax "; break;
190 case scSMaxExpr: OpStr = " smax "; break;
191 }
192 OS << "(";
193 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
194 I != E; ++I) {
195 OS << **I;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000196 if (std::next(I) != E)
Dan Gohman534749b2010-11-17 22:27:42 +0000197 OS << OpStr;
198 }
199 OS << ")";
Andrew Trickd912a5b2011-11-29 02:06:35 +0000200 switch (NAry->getSCEVType()) {
201 case scAddExpr:
202 case scMulExpr:
203 if (NAry->getNoWrapFlags(FlagNUW))
204 OS << "<nuw>";
205 if (NAry->getNoWrapFlags(FlagNSW))
206 OS << "<nsw>";
207 }
Dan Gohman534749b2010-11-17 22:27:42 +0000208 return;
209 }
210 case scUDivExpr: {
211 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
212 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
213 return;
214 }
215 case scUnknown: {
216 const SCEVUnknown *U = cast<SCEVUnknown>(this);
Chris Lattner229907c2011-07-18 04:54:35 +0000217 Type *AllocTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000218 if (U->isSizeOf(AllocTy)) {
219 OS << "sizeof(" << *AllocTy << ")";
220 return;
221 }
222 if (U->isAlignOf(AllocTy)) {
223 OS << "alignof(" << *AllocTy << ")";
224 return;
225 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000226
Chris Lattner229907c2011-07-18 04:54:35 +0000227 Type *CTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000228 Constant *FieldNo;
229 if (U->isOffsetOf(CTy, FieldNo)) {
230 OS << "offsetof(" << *CTy << ", ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000231 FieldNo->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000232 OS << ")";
233 return;
234 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000235
Dan Gohman534749b2010-11-17 22:27:42 +0000236 // Otherwise just print it normally.
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000237 U->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000238 return;
239 }
240 case scCouldNotCompute:
241 OS << "***COULDNOTCOMPUTE***";
242 return;
Dan Gohman534749b2010-11-17 22:27:42 +0000243 }
244 llvm_unreachable("Unknown SCEV kind!");
245}
246
Chris Lattner229907c2011-07-18 04:54:35 +0000247Type *SCEV::getType() const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000248 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000249 case scConstant:
250 return cast<SCEVConstant>(this)->getType();
251 case scTruncate:
252 case scZeroExtend:
253 case scSignExtend:
254 return cast<SCEVCastExpr>(this)->getType();
255 case scAddRecExpr:
256 case scMulExpr:
257 case scUMaxExpr:
258 case scSMaxExpr:
259 return cast<SCEVNAryExpr>(this)->getType();
260 case scAddExpr:
261 return cast<SCEVAddExpr>(this)->getType();
262 case scUDivExpr:
263 return cast<SCEVUDivExpr>(this)->getType();
264 case scUnknown:
265 return cast<SCEVUnknown>(this)->getType();
266 case scCouldNotCompute:
267 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman534749b2010-11-17 22:27:42 +0000268 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000269 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman534749b2010-11-17 22:27:42 +0000270}
271
Dan Gohmanbe928e32008-06-18 16:23:07 +0000272bool SCEV::isZero() const {
273 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
274 return SC->getValue()->isZero();
275 return false;
276}
277
Dan Gohmanba7f6d82009-05-18 15:22:39 +0000278bool SCEV::isOne() const {
279 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
280 return SC->getValue()->isOne();
281 return false;
282}
Chris Lattnerd934c702004-04-02 20:23:17 +0000283
Dan Gohman18a96bb2009-06-24 00:30:26 +0000284bool SCEV::isAllOnesValue() const {
285 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
286 return SC->getValue()->isAllOnesValue();
287 return false;
288}
289
Andrew Trick881a7762012-01-07 00:27:31 +0000290/// isNonConstantNegative - Return true if the specified scev is negated, but
291/// not a constant.
292bool SCEV::isNonConstantNegative() const {
293 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
294 if (!Mul) return false;
295
296 // If there is a constant factor, it will be first.
297 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
298 if (!SC) return false;
299
300 // Return true if the value is negative, this matches things like (-42 * V).
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000301 return SC->getAPInt().isNegative();
Andrew Trick881a7762012-01-07 00:27:31 +0000302}
303
Owen Anderson04052ec2009-06-22 21:57:23 +0000304SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman24ceda82010-06-18 19:54:20 +0000305 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000306
Chris Lattnerd934c702004-04-02 20:23:17 +0000307bool SCEVCouldNotCompute::classof(const SCEV *S) {
308 return S->getSCEVType() == scCouldNotCompute;
309}
310
Dan Gohmanaf752342009-07-07 17:06:11 +0000311const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000312 FoldingSetNodeID ID;
313 ID.AddInteger(scConstant);
314 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +0000315 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000316 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman24ceda82010-06-18 19:54:20 +0000317 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000318 UniqueSCEVs.InsertNode(S, IP);
319 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000320}
Chris Lattnerd934c702004-04-02 20:23:17 +0000321
Nick Lewycky31eaca52014-01-27 10:04:03 +0000322const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000323 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman0a76e7f2007-07-09 15:25:17 +0000324}
325
Dan Gohmanaf752342009-07-07 17:06:11 +0000326const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +0000327ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
328 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Dan Gohmana029cbe2010-04-21 16:04:04 +0000329 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000330}
331
Dan Gohman24ceda82010-06-18 19:54:20 +0000332SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000333 unsigned SCEVTy, const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000334 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000335
Dan Gohman24ceda82010-06-18 19:54:20 +0000336SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000337 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000338 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000339 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
340 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000341 "Cannot truncate non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000342}
Chris Lattnerd934c702004-04-02 20:23:17 +0000343
Dan Gohman24ceda82010-06-18 19:54:20 +0000344SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000345 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000346 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000347 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
348 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000349 "Cannot zero extend non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000350}
351
Dan Gohman24ceda82010-06-18 19:54:20 +0000352SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000353 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000354 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000355 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
356 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000357 "Cannot sign extend non-integer value!");
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000358}
359
Dan Gohman7cac9572010-08-02 23:49:30 +0000360void SCEVUnknown::deleted() {
Dan Gohman761065e2010-11-17 02:44:44 +0000361 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000362 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000363
364 // Remove this SCEVUnknown from the uniquing map.
365 SE->UniqueSCEVs.RemoveNode(this);
366
367 // Release the value.
Craig Topper9f008862014-04-15 04:59:12 +0000368 setValPtr(nullptr);
Dan Gohman7cac9572010-08-02 23:49:30 +0000369}
370
371void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman761065e2010-11-17 02:44:44 +0000372 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000373 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000374
375 // Remove this SCEVUnknown from the uniquing map.
376 SE->UniqueSCEVs.RemoveNode(this);
377
378 // Update this SCEVUnknown to point to the new value. This is needed
379 // because there may still be outstanding SCEVs which still point to
380 // this SCEVUnknown.
381 setValPtr(New);
382}
383
Chris Lattner229907c2011-07-18 04:54:35 +0000384bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000385 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000386 if (VCE->getOpcode() == Instruction::PtrToInt)
387 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000388 if (CE->getOpcode() == Instruction::GetElementPtr &&
389 CE->getOperand(0)->isNullValue() &&
390 CE->getNumOperands() == 2)
391 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
392 if (CI->isOne()) {
393 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
394 ->getElementType();
395 return true;
396 }
Dan Gohmancf913832010-01-28 02:15:55 +0000397
398 return false;
399}
400
Chris Lattner229907c2011-07-18 04:54:35 +0000401bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000402 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000403 if (VCE->getOpcode() == Instruction::PtrToInt)
404 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000405 if (CE->getOpcode() == Instruction::GetElementPtr &&
406 CE->getOperand(0)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000407 Type *Ty =
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000408 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000409 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000410 if (!STy->isPacked() &&
411 CE->getNumOperands() == 3 &&
412 CE->getOperand(1)->isNullValue()) {
413 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
414 if (CI->isOne() &&
415 STy->getNumElements() == 2 &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000416 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000417 AllocTy = STy->getElementType(1);
418 return true;
419 }
420 }
421 }
Dan Gohmancf913832010-01-28 02:15:55 +0000422
423 return false;
424}
425
Chris Lattner229907c2011-07-18 04:54:35 +0000426bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000427 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000428 if (VCE->getOpcode() == Instruction::PtrToInt)
429 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
430 if (CE->getOpcode() == Instruction::GetElementPtr &&
431 CE->getNumOperands() == 3 &&
432 CE->getOperand(0)->isNullValue() &&
433 CE->getOperand(1)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000434 Type *Ty =
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000435 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
436 // Ignore vector types here so that ScalarEvolutionExpander doesn't
437 // emit getelementptrs that index into vectors.
Duncan Sands19d0b472010-02-16 11:11:14 +0000438 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000439 CTy = Ty;
440 FieldNo = CE->getOperand(2);
441 return true;
442 }
443 }
444
445 return false;
446}
447
Chris Lattnereb3e8402004-06-20 06:23:15 +0000448//===----------------------------------------------------------------------===//
449// SCEV Utilities
450//===----------------------------------------------------------------------===//
451
452namespace {
Sanjoy Das7881abd2015-12-08 04:32:51 +0000453/// SCEVComplexityCompare - Return true if the complexity of the LHS is less
454/// than the complexity of the RHS. This comparator is used to canonicalize
455/// expressions.
456class SCEVComplexityCompare {
457 const LoopInfo *const LI;
458public:
459 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman9ba542c2009-05-07 14:39:04 +0000460
Sanjoy Das7881abd2015-12-08 04:32:51 +0000461 // Return true or false if LHS is less than, or at least RHS, respectively.
462 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
463 return compare(LHS, RHS) < 0;
464 }
Dan Gohman27065672010-08-27 15:26:01 +0000465
Sanjoy Das7881abd2015-12-08 04:32:51 +0000466 // Return negative, zero, or positive, if LHS is less than, equal to, or
467 // greater than RHS, respectively. A three-way result allows recursive
468 // comparisons to be more efficient.
469 int compare(const SCEV *LHS, const SCEV *RHS) const {
470 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
471 if (LHS == RHS)
472 return 0;
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000473
Sanjoy Das7881abd2015-12-08 04:32:51 +0000474 // Primarily, sort the SCEVs by their getSCEVType().
475 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
476 if (LType != RType)
477 return (int)LType - (int)RType;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000478
Sanjoy Das7881abd2015-12-08 04:32:51 +0000479 // Aside from the getSCEVType() ordering, the particular ordering
480 // isn't very important except that it's beneficial to be consistent,
481 // so that (a + b) and (b + a) don't end up as different expressions.
482 switch (static_cast<SCEVTypes>(LType)) {
483 case scUnknown: {
484 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
485 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000486
Sanjoy Das7881abd2015-12-08 04:32:51 +0000487 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
488 // not as complete as it could be.
489 const Value *LV = LU->getValue(), *RV = RU->getValue();
Dan Gohman24ceda82010-06-18 19:54:20 +0000490
Sanjoy Das7881abd2015-12-08 04:32:51 +0000491 // Order pointer values after integer values. This helps SCEVExpander
492 // form GEPs.
493 bool LIsPointer = LV->getType()->isPointerTy(),
494 RIsPointer = RV->getType()->isPointerTy();
495 if (LIsPointer != RIsPointer)
496 return (int)LIsPointer - (int)RIsPointer;
Dan Gohman24ceda82010-06-18 19:54:20 +0000497
Sanjoy Das7881abd2015-12-08 04:32:51 +0000498 // Compare getValueID values.
499 unsigned LID = LV->getValueID(),
500 RID = RV->getValueID();
501 if (LID != RID)
502 return (int)LID - (int)RID;
Dan Gohman24ceda82010-06-18 19:54:20 +0000503
Sanjoy Das7881abd2015-12-08 04:32:51 +0000504 // Sort arguments by their position.
505 if (const Argument *LA = dyn_cast<Argument>(LV)) {
506 const Argument *RA = cast<Argument>(RV);
507 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
508 return (int)LArgNo - (int)RArgNo;
Dan Gohman24ceda82010-06-18 19:54:20 +0000509 }
510
Sanjoy Das7881abd2015-12-08 04:32:51 +0000511 // For instructions, compare their loop depth, and their operand
512 // count. This is pretty loose.
513 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
514 const Instruction *RInst = cast<Instruction>(RV);
Dan Gohman27065672010-08-27 15:26:01 +0000515
Sanjoy Das7881abd2015-12-08 04:32:51 +0000516 // Compare loop depths.
517 const BasicBlock *LParent = LInst->getParent(),
518 *RParent = RInst->getParent();
519 if (LParent != RParent) {
520 unsigned LDepth = LI->getLoopDepth(LParent),
521 RDepth = LI->getLoopDepth(RParent);
Dan Gohman0c436ab2010-08-13 21:24:58 +0000522 if (LDepth != RDepth)
Dan Gohman27065672010-08-27 15:26:01 +0000523 return (int)LDepth - (int)RDepth;
Dan Gohman0c436ab2010-08-13 21:24:58 +0000524 }
Dan Gohman27065672010-08-27 15:26:01 +0000525
Sanjoy Das7881abd2015-12-08 04:32:51 +0000526 // Compare the number of operands.
527 unsigned LNumOps = LInst->getNumOperands(),
528 RNumOps = RInst->getNumOperands();
Dan Gohman27065672010-08-27 15:26:01 +0000529 return (int)LNumOps - (int)RNumOps;
Dan Gohman24ceda82010-06-18 19:54:20 +0000530 }
531
Sanjoy Das7881abd2015-12-08 04:32:51 +0000532 return 0;
533 }
Dan Gohman27065672010-08-27 15:26:01 +0000534
Sanjoy Das7881abd2015-12-08 04:32:51 +0000535 case scConstant: {
536 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
537 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
538
539 // Compare constant values.
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000540 const APInt &LA = LC->getAPInt();
541 const APInt &RA = RC->getAPInt();
Sanjoy Das7881abd2015-12-08 04:32:51 +0000542 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
543 if (LBitWidth != RBitWidth)
544 return (int)LBitWidth - (int)RBitWidth;
545 return LA.ult(RA) ? -1 : 1;
546 }
547
548 case scAddRecExpr: {
549 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
550 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
551
552 // Compare addrec loop depths.
553 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
554 if (LLoop != RLoop) {
555 unsigned LDepth = LLoop->getLoopDepth(),
556 RDepth = RLoop->getLoopDepth();
557 if (LDepth != RDepth)
558 return (int)LDepth - (int)RDepth;
559 }
560
561 // Addrec complexity grows with operand count.
562 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
563 if (LNumOps != RNumOps)
564 return (int)LNumOps - (int)RNumOps;
565
566 // Lexicographically compare.
567 for (unsigned i = 0; i != LNumOps; ++i) {
568 long X = compare(LA->getOperand(i), RA->getOperand(i));
Dan Gohman27065672010-08-27 15:26:01 +0000569 if (X != 0)
570 return X;
Dan Gohman24ceda82010-06-18 19:54:20 +0000571 }
572
Sanjoy Das7881abd2015-12-08 04:32:51 +0000573 return 0;
Chris Lattnereb3e8402004-06-20 06:23:15 +0000574 }
Sanjoy Das7881abd2015-12-08 04:32:51 +0000575
576 case scAddExpr:
577 case scMulExpr:
578 case scSMaxExpr:
579 case scUMaxExpr: {
580 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
581 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
582
583 // Lexicographically compare n-ary expressions.
584 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
585 if (LNumOps != RNumOps)
586 return (int)LNumOps - (int)RNumOps;
587
588 for (unsigned i = 0; i != LNumOps; ++i) {
589 if (i >= RNumOps)
590 return 1;
591 long X = compare(LC->getOperand(i), RC->getOperand(i));
592 if (X != 0)
593 return X;
594 }
595 return (int)LNumOps - (int)RNumOps;
596 }
597
598 case scUDivExpr: {
599 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
600 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
601
602 // Lexicographically compare udiv expressions.
603 long X = compare(LC->getLHS(), RC->getLHS());
604 if (X != 0)
605 return X;
606 return compare(LC->getRHS(), RC->getRHS());
607 }
608
609 case scTruncate:
610 case scZeroExtend:
611 case scSignExtend: {
612 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
613 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
614
615 // Compare cast expressions by operand.
616 return compare(LC->getOperand(), RC->getOperand());
617 }
618
619 case scCouldNotCompute:
620 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
621 }
622 llvm_unreachable("Unknown SCEV kind!");
623 }
624};
625} // end anonymous namespace
Chris Lattnereb3e8402004-06-20 06:23:15 +0000626
627/// GroupByComplexity - Given a list of SCEV objects, order them by their
628/// complexity, and group objects of the same complexity together by value.
629/// When this routine is finished, we know that any duplicates in the vector are
630/// consecutive and that complexity is monotonically increasing.
631///
Dan Gohman8b0a4192010-03-01 17:49:51 +0000632/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattnereb3e8402004-06-20 06:23:15 +0000633/// results from this routine. In other words, we don't want the results of
634/// this to depend on where the addresses of various SCEV objects happened to
635/// land in memory.
636///
Dan Gohmanaf752342009-07-07 17:06:11 +0000637static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman9ba542c2009-05-07 14:39:04 +0000638 LoopInfo *LI) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000639 if (Ops.size() < 2) return; // Noop
640 if (Ops.size() == 2) {
641 // This is the common case, which also happens to be trivially simple.
642 // Special case it.
Dan Gohman7712d292010-08-29 15:07:13 +0000643 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
644 if (SCEVComplexityCompare(LI)(RHS, LHS))
645 std::swap(LHS, RHS);
Chris Lattnereb3e8402004-06-20 06:23:15 +0000646 return;
647 }
648
Dan Gohman24ceda82010-06-18 19:54:20 +0000649 // Do the rough sort by complexity.
650 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
651
652 // Now that we are sorted by complexity, group elements of the same
653 // complexity. Note that this is, at worst, N^2, but the vector is likely to
654 // be extremely short in practice. Note that we take this approach because we
655 // do not want to depend on the addresses of the objects we are grouping.
656 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
657 const SCEV *S = Ops[i];
658 unsigned Complexity = S->getSCEVType();
659
660 // If there are any objects of the same complexity and same value as this
661 // one, group them.
662 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
663 if (Ops[j] == S) { // Found a duplicate.
664 // Move it to immediately after i'th element.
665 std::swap(Ops[i+1], Ops[j]);
666 ++i; // no need to rescan it.
667 if (i == e-2) return; // Done!
668 }
669 }
670 }
Chris Lattnereb3e8402004-06-20 06:23:15 +0000671}
672
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000673// Returns the size of the SCEV S.
674static inline int sizeOfSCEV(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +0000675 struct FindSCEVSize {
676 int Size;
677 FindSCEVSize() : Size(0) {}
678
679 bool follow(const SCEV *S) {
680 ++Size;
681 // Keep looking at all operands of S.
682 return true;
683 }
684 bool isDone() const {
685 return false;
686 }
687 };
688
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000689 FindSCEVSize F;
690 SCEVTraversal<FindSCEVSize> ST(F);
691 ST.visitAll(S);
692 return F.Size;
693}
694
695namespace {
696
David Majnemer4e879362014-12-14 09:12:33 +0000697struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000698public:
699 // Computes the Quotient and Remainder of the division of Numerator by
700 // Denominator.
701 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
702 const SCEV *Denominator, const SCEV **Quotient,
703 const SCEV **Remainder) {
704 assert(Numerator && Denominator && "Uninitialized SCEV");
705
David Majnemer4e879362014-12-14 09:12:33 +0000706 SCEVDivision D(SE, Numerator, Denominator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000707
708 // Check for the trivial case here to avoid having to check for it in the
709 // rest of the code.
710 if (Numerator == Denominator) {
711 *Quotient = D.One;
712 *Remainder = D.Zero;
713 return;
714 }
715
716 if (Numerator->isZero()) {
717 *Quotient = D.Zero;
718 *Remainder = D.Zero;
719 return;
720 }
721
Brendon Cahoona57cc8b2015-04-20 16:03:28 +0000722 // A simple case when N/1. The quotient is N.
723 if (Denominator->isOne()) {
724 *Quotient = Numerator;
725 *Remainder = D.Zero;
726 return;
727 }
728
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000729 // Split the Denominator when it is a product.
730 if (const SCEVMulExpr *T = dyn_cast<const SCEVMulExpr>(Denominator)) {
731 const SCEV *Q, *R;
732 *Quotient = Numerator;
733 for (const SCEV *Op : T->operands()) {
734 divide(SE, *Quotient, Op, &Q, &R);
735 *Quotient = Q;
736
737 // Bail out when the Numerator is not divisible by one of the terms of
738 // the Denominator.
739 if (!R->isZero()) {
740 *Quotient = D.Zero;
741 *Remainder = Numerator;
742 return;
743 }
744 }
745 *Remainder = D.Zero;
746 return;
747 }
748
749 D.visit(Numerator);
750 *Quotient = D.Quotient;
751 *Remainder = D.Remainder;
752 }
753
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000754 // Except in the trivial case described above, we do not know how to divide
755 // Expr by Denominator for the following functions with empty implementation.
756 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
757 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
758 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
759 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
760 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
761 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
762 void visitUnknown(const SCEVUnknown *Numerator) {}
763 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
764
David Majnemer4e879362014-12-14 09:12:33 +0000765 void visitConstant(const SCEVConstant *Numerator) {
766 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000767 APInt NumeratorVal = Numerator->getAPInt();
768 APInt DenominatorVal = D->getAPInt();
David Majnemer4e879362014-12-14 09:12:33 +0000769 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
770 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
771
772 if (NumeratorBW > DenominatorBW)
773 DenominatorVal = DenominatorVal.sext(NumeratorBW);
774 else if (NumeratorBW < DenominatorBW)
775 NumeratorVal = NumeratorVal.sext(DenominatorBW);
776
777 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
778 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
779 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
780 Quotient = SE.getConstant(QuotientVal);
781 Remainder = SE.getConstant(RemainderVal);
782 return;
783 }
784 }
785
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000786 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
787 const SCEV *StartQ, *StartR, *StepQ, *StepR;
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000788 if (!Numerator->isAffine())
789 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000790 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
791 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
Brendon Cahoonf9751ad2015-04-22 15:06:40 +0000792 // Bail out if the types do not match.
793 Type *Ty = Denominator->getType();
794 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000795 Ty != StepQ->getType() || Ty != StepR->getType())
796 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000797 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
798 Numerator->getNoWrapFlags());
799 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
800 Numerator->getNoWrapFlags());
801 }
802
803 void visitAddExpr(const SCEVAddExpr *Numerator) {
804 SmallVector<const SCEV *, 2> Qs, Rs;
805 Type *Ty = Denominator->getType();
806
807 for (const SCEV *Op : Numerator->operands()) {
808 const SCEV *Q, *R;
809 divide(SE, Op, Denominator, &Q, &R);
810
811 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000812 if (Ty != Q->getType() || Ty != R->getType())
813 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000814
815 Qs.push_back(Q);
816 Rs.push_back(R);
817 }
818
819 if (Qs.size() == 1) {
820 Quotient = Qs[0];
821 Remainder = Rs[0];
822 return;
823 }
824
825 Quotient = SE.getAddExpr(Qs);
826 Remainder = SE.getAddExpr(Rs);
827 }
828
829 void visitMulExpr(const SCEVMulExpr *Numerator) {
830 SmallVector<const SCEV *, 2> Qs;
831 Type *Ty = Denominator->getType();
832
833 bool FoundDenominatorTerm = false;
834 for (const SCEV *Op : Numerator->operands()) {
835 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000836 if (Ty != Op->getType())
837 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000838
839 if (FoundDenominatorTerm) {
840 Qs.push_back(Op);
841 continue;
842 }
843
844 // Check whether Denominator divides one of the product operands.
845 const SCEV *Q, *R;
846 divide(SE, Op, Denominator, &Q, &R);
847 if (!R->isZero()) {
848 Qs.push_back(Op);
849 continue;
850 }
851
852 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000853 if (Ty != Q->getType())
854 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000855
856 FoundDenominatorTerm = true;
857 Qs.push_back(Q);
858 }
859
860 if (FoundDenominatorTerm) {
861 Remainder = Zero;
862 if (Qs.size() == 1)
863 Quotient = Qs[0];
864 else
865 Quotient = SE.getMulExpr(Qs);
866 return;
867 }
868
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000869 if (!isa<SCEVUnknown>(Denominator))
870 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000871
872 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
873 ValueToValueMap RewriteMap;
874 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
875 cast<SCEVConstant>(Zero)->getValue();
876 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
877
878 if (Remainder->isZero()) {
879 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
880 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
881 cast<SCEVConstant>(One)->getValue();
882 Quotient =
883 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
884 return;
885 }
886
887 // Quotient is (Numerator - Remainder) divided by Denominator.
888 const SCEV *Q, *R;
889 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000890 // This SCEV does not seem to simplify: fail the division here.
891 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
892 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000893 divide(SE, Diff, Denominator, &Q, &R);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000894 if (R != Zero)
895 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000896 Quotient = Q;
897 }
898
899private:
David Majnemer5d2670c2014-11-17 11:27:45 +0000900 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
901 const SCEV *Denominator)
902 : SE(S), Denominator(Denominator) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000903 Zero = SE.getZero(Denominator->getType());
904 One = SE.getOne(Denominator->getType());
David Majnemer5d2670c2014-11-17 11:27:45 +0000905
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000906 // We generally do not know how to divide Expr by Denominator. We
907 // initialize the division to a "cannot divide" state to simplify the rest
908 // of the code.
909 cannotDivide(Numerator);
910 }
911
912 // Convenience function for giving up on the division. We set the quotient to
913 // be equal to zero and the remainder to be equal to the numerator.
914 void cannotDivide(const SCEV *Numerator) {
David Majnemer5d2670c2014-11-17 11:27:45 +0000915 Quotient = Zero;
916 Remainder = Numerator;
917 }
918
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000919 ScalarEvolution &SE;
920 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
David Majnemer32b8ccf2014-11-16 20:35:19 +0000921};
922
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000923}
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000924
Chris Lattnerd934c702004-04-02 20:23:17 +0000925//===----------------------------------------------------------------------===//
926// Simple SCEV method implementations
927//===----------------------------------------------------------------------===//
928
Eli Friedman61f67622008-08-04 23:49:06 +0000929/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman4d5435d2009-05-24 23:45:28 +0000930/// Assume, K > 0.
Dan Gohmanaf752342009-07-07 17:06:11 +0000931static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohman32291b12009-07-21 00:38:55 +0000932 ScalarEvolution &SE,
Nick Lewycky702cf1e2011-09-06 06:39:54 +0000933 Type *ResultTy) {
Eli Friedman61f67622008-08-04 23:49:06 +0000934 // Handle the simplest case efficiently.
935 if (K == 1)
936 return SE.getTruncateOrZeroExtend(It, ResultTy);
937
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000938 // We are using the following formula for BC(It, K):
939 //
940 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
941 //
Eli Friedman61f67622008-08-04 23:49:06 +0000942 // Suppose, W is the bitwidth of the return value. We must be prepared for
943 // overflow. Hence, we must assure that the result of our computation is
944 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
945 // safe in modular arithmetic.
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000946 //
Eli Friedman61f67622008-08-04 23:49:06 +0000947 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohmance973df2009-06-24 04:48:43 +0000948 // is something like the following, where T is the number of factors of 2 in
Eli Friedman61f67622008-08-04 23:49:06 +0000949 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
950 // exponentiation:
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000951 //
Eli Friedman61f67622008-08-04 23:49:06 +0000952 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000953 //
Eli Friedman61f67622008-08-04 23:49:06 +0000954 // This formula is trivially equivalent to the previous formula. However,
955 // this formula can be implemented much more efficiently. The trick is that
956 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
957 // arithmetic. To do exact division in modular arithmetic, all we have
958 // to do is multiply by the inverse. Therefore, this step can be done at
959 // width W.
Dan Gohmance973df2009-06-24 04:48:43 +0000960 //
Eli Friedman61f67622008-08-04 23:49:06 +0000961 // The next issue is how to safely do the division by 2^T. The way this
962 // is done is by doing the multiplication step at a width of at least W + T
963 // bits. This way, the bottom W+T bits of the product are accurate. Then,
964 // when we perform the division by 2^T (which is equivalent to a right shift
965 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
966 // truncated out after the division by 2^T.
967 //
968 // In comparison to just directly using the first formula, this technique
969 // is much more efficient; using the first formula requires W * K bits,
970 // but this formula less than W + K bits. Also, the first formula requires
971 // a division step, whereas this formula only requires multiplies and shifts.
972 //
973 // It doesn't matter whether the subtraction step is done in the calculation
974 // width or the input iteration count's width; if the subtraction overflows,
975 // the result must be zero anyway. We prefer here to do it in the width of
976 // the induction variable because it helps a lot for certain cases; CodeGen
977 // isn't smart enough to ignore the overflow, which leads to much less
978 // efficient code if the width of the subtraction is wider than the native
979 // register width.
980 //
981 // (It's possible to not widen at all by pulling out factors of 2 before
982 // the multiplication; for example, K=2 can be calculated as
983 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
984 // extra arithmetic, so it's not an obvious win, and it gets
985 // much more complicated for K > 3.)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000986
Eli Friedman61f67622008-08-04 23:49:06 +0000987 // Protection from insane SCEVs; this bound is conservative,
988 // but it probably doesn't matter.
989 if (K > 1000)
Dan Gohman31efa302009-04-18 17:58:19 +0000990 return SE.getCouldNotCompute();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000991
Dan Gohmanb397e1a2009-04-21 01:07:12 +0000992 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000993
Eli Friedman61f67622008-08-04 23:49:06 +0000994 // Calculate K! / 2^T and T; we divide out the factors of two before
995 // multiplying for calculating K! / 2^T to avoid overflow.
996 // Other overflow doesn't matter because we only care about the bottom
997 // W bits of the result.
998 APInt OddFactorial(W, 1);
999 unsigned T = 1;
1000 for (unsigned i = 3; i <= K; ++i) {
1001 APInt Mult(W, i);
1002 unsigned TwoFactors = Mult.countTrailingZeros();
1003 T += TwoFactors;
1004 Mult = Mult.lshr(TwoFactors);
1005 OddFactorial *= Mult;
Chris Lattnerd934c702004-04-02 20:23:17 +00001006 }
Nick Lewyckyed169d52008-06-13 04:38:55 +00001007
Eli Friedman61f67622008-08-04 23:49:06 +00001008 // We need at least W + T bits for the multiplication step
Nick Lewycky21add8f2009-01-25 08:16:27 +00001009 unsigned CalculationBits = W + T;
Eli Friedman61f67622008-08-04 23:49:06 +00001010
Dan Gohman8b0a4192010-03-01 17:49:51 +00001011 // Calculate 2^T, at width T+W.
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00001012 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
Eli Friedman61f67622008-08-04 23:49:06 +00001013
1014 // Calculate the multiplicative inverse of K! / 2^T;
1015 // this multiplication factor will perform the exact division by
1016 // K! / 2^T.
1017 APInt Mod = APInt::getSignedMinValue(W+1);
1018 APInt MultiplyFactor = OddFactorial.zext(W+1);
1019 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1020 MultiplyFactor = MultiplyFactor.trunc(W);
1021
1022 // Calculate the product, at width T+W
Chris Lattner229907c2011-07-18 04:54:35 +00001023 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001024 CalculationBits);
Dan Gohmanaf752342009-07-07 17:06:11 +00001025 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman61f67622008-08-04 23:49:06 +00001026 for (unsigned i = 1; i != K; ++i) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00001027 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedman61f67622008-08-04 23:49:06 +00001028 Dividend = SE.getMulExpr(Dividend,
1029 SE.getTruncateOrZeroExtend(S, CalculationTy));
1030 }
1031
1032 // Divide by 2^T
Dan Gohmanaf752342009-07-07 17:06:11 +00001033 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman61f67622008-08-04 23:49:06 +00001034
1035 // Truncate the result, and divide by K! / 2^T.
1036
1037 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1038 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattnerd934c702004-04-02 20:23:17 +00001039}
1040
Chris Lattnerd934c702004-04-02 20:23:17 +00001041/// evaluateAtIteration - Return the value of this chain of recurrences at
1042/// the specified iteration number. We can evaluate this recurrence by
1043/// multiplying each element in the chain by the binomial coefficient
1044/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
1045///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001046/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattnerd934c702004-04-02 20:23:17 +00001047///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001048/// where BC(It, k) stands for binomial coefficient.
Chris Lattnerd934c702004-04-02 20:23:17 +00001049///
Dan Gohmanaf752342009-07-07 17:06:11 +00001050const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman32291b12009-07-21 00:38:55 +00001051 ScalarEvolution &SE) const {
Dan Gohmanaf752342009-07-07 17:06:11 +00001052 const SCEV *Result = getStart();
Chris Lattnerd934c702004-04-02 20:23:17 +00001053 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001054 // The computation is correct in the face of overflow provided that the
1055 // multiplication is performed _after_ the evaluation of the binomial
1056 // coefficient.
Dan Gohmanaf752342009-07-07 17:06:11 +00001057 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewycky707663e2008-10-13 03:58:02 +00001058 if (isa<SCEVCouldNotCompute>(Coeff))
1059 return Coeff;
1060
1061 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattnerd934c702004-04-02 20:23:17 +00001062 }
1063 return Result;
1064}
1065
Chris Lattnerd934c702004-04-02 20:23:17 +00001066//===----------------------------------------------------------------------===//
1067// SCEV Expression folder implementations
1068//===----------------------------------------------------------------------===//
1069
Dan Gohmanaf752342009-07-07 17:06:11 +00001070const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001071 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001072 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001073 "This is not a truncating conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001074 assert(isSCEVable(Ty) &&
1075 "This is not a conversion to a SCEVable type!");
1076 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001077
Dan Gohman3a302cb2009-07-13 20:50:19 +00001078 FoldingSetNodeID ID;
1079 ID.AddInteger(scTruncate);
1080 ID.AddPointer(Op);
1081 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001082 void *IP = nullptr;
Dan Gohman3a302cb2009-07-13 20:50:19 +00001083 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1084
Dan Gohman3423e722009-06-30 20:13:32 +00001085 // Fold if the operand is constant.
Dan Gohmana30370b2009-05-04 22:02:23 +00001086 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman8d7576e2009-06-24 00:38:39 +00001087 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001088 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001089
Dan Gohman79af8542009-04-22 16:20:48 +00001090 // trunc(trunc(x)) --> trunc(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001091 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001092 return getTruncateExpr(ST->getOperand(), Ty);
1093
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001094 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001095 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001096 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1097
1098 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001099 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001100 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1101
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001102 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
Nick Lewycky2ce28322015-03-20 02:52:23 +00001103 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001104 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1105 SmallVector<const SCEV *, 4> Operands;
1106 bool hasTrunc = false;
1107 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1108 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001109 if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1110 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001111 Operands.push_back(S);
1112 }
1113 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001114 return getAddExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001115 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001116 }
1117
Nick Lewycky5c901f32011-01-19 18:56:00 +00001118 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
Nick Lewyckybe8af482015-03-20 02:25:00 +00001119 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001120 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1121 SmallVector<const SCEV *, 4> Operands;
1122 bool hasTrunc = false;
1123 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1124 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001125 if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1126 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5c901f32011-01-19 18:56:00 +00001127 Operands.push_back(S);
1128 }
1129 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001130 return getMulExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001131 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001132 }
1133
Dan Gohman5a728c92009-06-18 16:24:47 +00001134 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmana30370b2009-05-04 22:02:23 +00001135 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001136 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00001137 for (const SCEV *Op : AddRec->operands())
1138 Operands.push_back(getTruncateExpr(Op, Ty));
Andrew Trick8b55b732011-03-14 16:50:06 +00001139 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00001140 }
1141
Dan Gohman89dd42a2010-06-25 18:47:08 +00001142 // The cast wasn't folded; create an explicit cast node. We can reuse
1143 // the existing insert position since if we get here, we won't have
1144 // made any changes which would invalidate it.
Dan Gohman01c65a22010-03-18 18:49:47 +00001145 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1146 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001147 UniqueSCEVs.InsertNode(S, IP);
1148 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001149}
1150
Sanjoy Das4153f472015-02-18 01:47:07 +00001151// Get the limit of a recurrence such that incrementing by Step cannot cause
1152// signed overflow as long as the value of the recurrence within the
1153// loop does not exceed this limit before incrementing.
1154static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1155 ICmpInst::Predicate *Pred,
1156 ScalarEvolution *SE) {
1157 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1158 if (SE->isKnownPositive(Step)) {
1159 *Pred = ICmpInst::ICMP_SLT;
1160 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1161 SE->getSignedRange(Step).getSignedMax());
1162 }
1163 if (SE->isKnownNegative(Step)) {
1164 *Pred = ICmpInst::ICMP_SGT;
1165 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1166 SE->getSignedRange(Step).getSignedMin());
1167 }
1168 return nullptr;
1169}
1170
1171// Get the limit of a recurrence such that incrementing by Step cannot cause
1172// unsigned overflow as long as the value of the recurrence within the loop does
1173// not exceed this limit before incrementing.
1174static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1175 ICmpInst::Predicate *Pred,
1176 ScalarEvolution *SE) {
1177 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1178 *Pred = ICmpInst::ICMP_ULT;
1179
1180 return SE->getConstant(APInt::getMinValue(BitWidth) -
1181 SE->getUnsignedRange(Step).getUnsignedMax());
1182}
1183
1184namespace {
1185
1186struct ExtendOpTraitsBase {
1187 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *);
1188};
1189
1190// Used to make code generic over signed and unsigned overflow.
1191template <typename ExtendOp> struct ExtendOpTraits {
1192 // Members present:
1193 //
1194 // static const SCEV::NoWrapFlags WrapType;
1195 //
1196 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1197 //
1198 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1199 // ICmpInst::Predicate *Pred,
1200 // ScalarEvolution *SE);
1201};
1202
1203template <>
1204struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1205 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1206
1207 static const GetExtendExprTy GetExtendExpr;
1208
1209 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1210 ICmpInst::Predicate *Pred,
1211 ScalarEvolution *SE) {
1212 return getSignedOverflowLimitForStep(Step, Pred, SE);
1213 }
1214};
1215
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001216const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001217 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1218
1219template <>
1220struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1221 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1222
1223 static const GetExtendExprTy GetExtendExpr;
1224
1225 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1226 ICmpInst::Predicate *Pred,
1227 ScalarEvolution *SE) {
1228 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1229 }
1230};
1231
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001232const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001233 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001234}
Sanjoy Das4153f472015-02-18 01:47:07 +00001235
1236// The recurrence AR has been shown to have no signed/unsigned wrap or something
1237// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1238// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1239// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1240// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1241// expression "Step + sext/zext(PreIncAR)" is congruent with
1242// "sext/zext(PostIncAR)"
1243template <typename ExtendOpTy>
1244static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1245 ScalarEvolution *SE) {
1246 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1247 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1248
1249 const Loop *L = AR->getLoop();
1250 const SCEV *Start = AR->getStart();
1251 const SCEV *Step = AR->getStepRecurrence(*SE);
1252
1253 // Check for a simple looking step prior to loop entry.
1254 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1255 if (!SA)
1256 return nullptr;
1257
1258 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1259 // subtraction is expensive. For this purpose, perform a quick and dirty
1260 // difference, by checking for Step in the operand list.
1261 SmallVector<const SCEV *, 4> DiffOps;
1262 for (const SCEV *Op : SA->operands())
1263 if (Op != Step)
1264 DiffOps.push_back(Op);
1265
1266 if (DiffOps.size() == SA->getNumOperands())
1267 return nullptr;
1268
1269 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1270 // `Step`:
1271
1272 // 1. NSW/NUW flags on the step increment.
Sanjoy Das0714e3e2015-10-23 06:33:47 +00001273 auto PreStartFlags =
1274 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1275 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
Sanjoy Das4153f472015-02-18 01:47:07 +00001276 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1277 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1278
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001279 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1280 // "S+X does not sign/unsign-overflow".
Sanjoy Das4153f472015-02-18 01:47:07 +00001281 //
1282
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001283 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1284 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1285 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
Sanjoy Das4153f472015-02-18 01:47:07 +00001286 return PreStart;
1287
1288 // 2. Direct overflow check on the step operation's expression.
1289 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1290 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1291 const SCEV *OperandExtendedStart =
1292 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1293 (SE->*GetExtendExpr)(Step, WideTy));
1294 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1295 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1296 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1297 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1298 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1299 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1300 }
1301 return PreStart;
1302 }
1303
1304 // 3. Loop precondition.
1305 ICmpInst::Predicate Pred;
1306 const SCEV *OverflowLimit =
1307 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1308
1309 if (OverflowLimit &&
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001310 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
Sanjoy Das4153f472015-02-18 01:47:07 +00001311 return PreStart;
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001312
Sanjoy Das4153f472015-02-18 01:47:07 +00001313 return nullptr;
1314}
1315
1316// Get the normalized zero or sign extended expression for this AddRec's Start.
1317template <typename ExtendOpTy>
1318static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1319 ScalarEvolution *SE) {
1320 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1321
1322 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1323 if (!PreStart)
1324 return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1325
1326 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1327 (SE->*GetExtendExpr)(PreStart, Ty));
1328}
1329
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001330// Try to prove away overflow by looking at "nearby" add recurrences. A
1331// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1332// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1333//
1334// Formally:
1335//
1336// {S,+,X} == {S-T,+,X} + T
1337// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1338//
1339// If ({S-T,+,X} + T) does not overflow ... (1)
1340//
1341// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1342//
1343// If {S-T,+,X} does not overflow ... (2)
1344//
1345// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1346// == {Ext(S-T)+Ext(T),+,Ext(X)}
1347//
1348// If (S-T)+T does not overflow ... (3)
1349//
1350// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1351// == {Ext(S),+,Ext(X)} == LHS
1352//
1353// Thus, if (1), (2) and (3) are true for some T, then
1354// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1355//
1356// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1357// does not overflow" restricted to the 0th iteration. Therefore we only need
1358// to check for (1) and (2).
1359//
1360// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1361// is `Delta` (defined below).
1362//
1363template <typename ExtendOpTy>
1364bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1365 const SCEV *Step,
1366 const Loop *L) {
1367 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1368
1369 // We restrict `Start` to a constant to prevent SCEV from spending too much
1370 // time here. It is correct (but more expensive) to continue with a
1371 // non-constant `Start` and do a general SCEV subtraction to compute
1372 // `PreStart` below.
1373 //
1374 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1375 if (!StartC)
1376 return false;
1377
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001378 APInt StartAI = StartC->getAPInt();
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001379
1380 for (unsigned Delta : {-2, -1, 1, 2}) {
1381 const SCEV *PreStart = getConstant(StartAI - Delta);
1382
Sanjoy Das42801102015-10-23 06:57:21 +00001383 FoldingSetNodeID ID;
1384 ID.AddInteger(scAddRecExpr);
1385 ID.AddPointer(PreStart);
1386 ID.AddPointer(Step);
1387 ID.AddPointer(L);
1388 void *IP = nullptr;
1389 const auto *PreAR =
1390 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1391
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001392 // Give up if we don't already have the add recurrence we need because
1393 // actually constructing an add recurrence is relatively expensive.
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001394 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1395 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1396 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1397 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1398 DeltaS, &Pred, this);
1399 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1400 return true;
1401 }
1402 }
1403
1404 return false;
1405}
1406
Dan Gohmanaf752342009-07-07 17:06:11 +00001407const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001408 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001409 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001410 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001411 assert(isSCEVable(Ty) &&
1412 "This is not a conversion to a SCEVable type!");
1413 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001414
Dan Gohman3423e722009-06-30 20:13:32 +00001415 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001416 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1417 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001418 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001419
Dan Gohman79af8542009-04-22 16:20:48 +00001420 // zext(zext(x)) --> zext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001421 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001422 return getZeroExtendExpr(SZ->getOperand(), Ty);
1423
Dan Gohman74a0ba12009-07-13 20:55:53 +00001424 // Before doing any expensive analysis, check to see if we've already
1425 // computed a SCEV for this Op and Ty.
1426 FoldingSetNodeID ID;
1427 ID.AddInteger(scZeroExtend);
1428 ID.AddPointer(Op);
1429 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001430 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001431 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1432
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001433 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1434 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1435 // It's possible the bits taken off by the truncate were all zero bits. If
1436 // so, we should be able to simplify this further.
1437 const SCEV *X = ST->getOperand();
1438 ConstantRange CR = getUnsignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001439 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1440 unsigned NewBits = getTypeSizeInBits(Ty);
1441 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001442 CR.zextOrTrunc(NewBits)))
1443 return getTruncateOrZeroExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001444 }
1445
Dan Gohman76466372009-04-27 20:16:15 +00001446 // If the input value is a chrec scev, and we can prove that the value
Chris Lattnerd934c702004-04-02 20:23:17 +00001447 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001448 // operands (often constants). This allows analysis of something like
Chris Lattnerd934c702004-04-02 20:23:17 +00001449 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001450 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001451 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001452 const SCEV *Start = AR->getStart();
1453 const SCEV *Step = AR->getStepRecurrence(*this);
1454 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1455 const Loop *L = AR->getLoop();
1456
Dan Gohman62ef6a72009-07-25 01:22:26 +00001457 // If we have special knowledge that this addrec won't overflow,
1458 // we don't need to do any further analysis.
Andrew Trick8b55b732011-03-14 16:50:06 +00001459 if (AR->getNoWrapFlags(SCEV::FlagNUW))
Sanjoy Das4153f472015-02-18 01:47:07 +00001460 return getAddRecExpr(
1461 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1462 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman62ef6a72009-07-25 01:22:26 +00001463
Dan Gohman76466372009-04-27 20:16:15 +00001464 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1465 // Note that this serves two purposes: It filters out loops that are
1466 // simply not analyzable, and it covers the case where this code is
1467 // being called from within backedge-taken count analysis, such that
1468 // attempting to ask for the backedge-taken count would likely result
1469 // in infinite recursion. In the later case, the analysis code will
1470 // cope with a conservative value, and it will take care to purge
1471 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001472 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001473 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001474 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001475 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001476
1477 // Check whether the backedge-taken count can be losslessly casted to
1478 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001479 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001480 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001481 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001482 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1483 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001484 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001485 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001486 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001487 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1488 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1489 const SCEV *WideMaxBECount =
1490 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001491 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001492 getAddExpr(WideStart,
1493 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001494 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001495 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001496 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1497 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohman494dac32009-04-29 22:28:28 +00001498 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001499 return getAddRecExpr(
1500 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1501 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001502 }
Dan Gohman76466372009-04-27 20:16:15 +00001503 // Similar to above, only this time treat the step value as signed.
1504 // This covers loops that count down.
Dan Gohman4fc36682009-05-18 15:58:39 +00001505 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001506 getAddExpr(WideStart,
1507 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001508 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001509 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001510 // Cache knowledge of AR NW, which is propagated to this AddRec.
1511 // Negative step causes unsigned wrap, but it still can't self-wrap.
1512 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
Dan Gohman494dac32009-04-29 22:28:28 +00001513 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001514 return getAddRecExpr(
1515 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1516 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001517 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001518 }
1519
1520 // If the backedge is guarded by a comparison with the pre-inc value
1521 // the addrec is safe. Also, if the entry is guarded by a comparison
1522 // with the start value and the backedge is guarded by a comparison
1523 // with the post-inc value, the addrec is safe.
1524 if (isKnownPositive(Step)) {
1525 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1526 getUnsignedRange(Step).getUnsignedMax());
1527 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohmanb50349a2010-04-11 19:27:13 +00001528 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001529 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001530 AR->getPostIncExpr(*this), N))) {
1531 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1532 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohmane65c9172009-07-13 21:35:55 +00001533 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001534 return getAddRecExpr(
1535 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1536 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001537 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001538 } else if (isKnownNegative(Step)) {
1539 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1540 getSignedRange(Step).getSignedMin());
Dan Gohman5f18c542010-05-04 01:11:15 +00001541 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1542 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001543 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001544 AR->getPostIncExpr(*this), N))) {
1545 // Cache knowledge of AR NW, which is propagated to this AddRec.
1546 // Negative step causes unsigned wrap, but it still can't self-wrap.
1547 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1548 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001549 return getAddRecExpr(
1550 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1551 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001552 }
Dan Gohman76466372009-04-27 20:16:15 +00001553 }
1554 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001555
1556 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1557 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1558 return getAddRecExpr(
1559 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1560 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1561 }
Dan Gohman76466372009-04-27 20:16:15 +00001562 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001563
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001564 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1565 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1566 if (SA->getNoWrapFlags(SCEV::FlagNUW)) {
1567 // If the addition does not unsign overflow then we can, by definition,
1568 // commute the zero extension with the addition operation.
1569 SmallVector<const SCEV *, 4> Ops;
1570 for (const auto *Op : SA->operands())
1571 Ops.push_back(getZeroExtendExpr(Op, Ty));
1572 return getAddExpr(Ops, SCEV::FlagNUW);
1573 }
1574 }
1575
Dan Gohman74a0ba12009-07-13 20:55:53 +00001576 // The cast wasn't folded; create an explicit cast node.
1577 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001578 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001579 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1580 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001581 UniqueSCEVs.InsertNode(S, IP);
1582 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001583}
1584
Dan Gohmanaf752342009-07-07 17:06:11 +00001585const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001586 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001587 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001588 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001589 assert(isSCEVable(Ty) &&
1590 "This is not a conversion to a SCEVable type!");
1591 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001592
Dan Gohman3423e722009-06-30 20:13:32 +00001593 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001594 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1595 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001596 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001597
Dan Gohman79af8542009-04-22 16:20:48 +00001598 // sext(sext(x)) --> sext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001599 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001600 return getSignExtendExpr(SS->getOperand(), Ty);
1601
Nick Lewyckye9ea75e2011-01-19 15:56:12 +00001602 // sext(zext(x)) --> zext(x)
1603 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1604 return getZeroExtendExpr(SZ->getOperand(), Ty);
1605
Dan Gohman74a0ba12009-07-13 20:55:53 +00001606 // Before doing any expensive analysis, check to see if we've already
1607 // computed a SCEV for this Op and Ty.
1608 FoldingSetNodeID ID;
1609 ID.AddInteger(scSignExtend);
1610 ID.AddPointer(Op);
1611 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001612 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001613 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1614
Nick Lewyckyb32c8942011-01-22 22:06:21 +00001615 // If the input value is provably positive, build a zext instead.
1616 if (isKnownNonNegative(Op))
1617 return getZeroExtendExpr(Op, Ty);
1618
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001619 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1620 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1621 // It's possible the bits taken off by the truncate were all sign bits. If
1622 // so, we should be able to simplify this further.
1623 const SCEV *X = ST->getOperand();
1624 ConstantRange CR = getSignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001625 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1626 unsigned NewBits = getTypeSizeInBits(Ty);
1627 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001628 CR.sextOrTrunc(NewBits)))
1629 return getTruncateOrSignExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001630 }
1631
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001632 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001633 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001634 if (SA->getNumOperands() == 2) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001635 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1636 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001637 if (SMul && SC1) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001638 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001639 const APInt &C1 = SC1->getAPInt();
1640 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001641 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001642 C2.ugt(C1) && C2.isPowerOf2())
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001643 return getAddExpr(getSignExtendExpr(SC1, Ty),
1644 getSignExtendExpr(SMul, Ty));
1645 }
1646 }
1647 }
Sanjoy Dasa060e602015-10-22 19:57:25 +00001648
1649 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1650 if (SA->getNoWrapFlags(SCEV::FlagNSW)) {
1651 // If the addition does not sign overflow then we can, by definition,
1652 // commute the sign extension with the addition operation.
1653 SmallVector<const SCEV *, 4> Ops;
1654 for (const auto *Op : SA->operands())
1655 Ops.push_back(getSignExtendExpr(Op, Ty));
1656 return getAddExpr(Ops, SCEV::FlagNSW);
1657 }
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001658 }
Dan Gohman76466372009-04-27 20:16:15 +00001659 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001660 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001661 // operands (often constants). This allows analysis of something like
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001662 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001663 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001664 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001665 const SCEV *Start = AR->getStart();
1666 const SCEV *Step = AR->getStepRecurrence(*this);
1667 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1668 const Loop *L = AR->getLoop();
1669
Dan Gohman62ef6a72009-07-25 01:22:26 +00001670 // If we have special knowledge that this addrec won't overflow,
1671 // we don't need to do any further analysis.
Andrew Trick8b55b732011-03-14 16:50:06 +00001672 if (AR->getNoWrapFlags(SCEV::FlagNSW))
Sanjoy Das4153f472015-02-18 01:47:07 +00001673 return getAddRecExpr(
1674 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1675 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
Dan Gohman62ef6a72009-07-25 01:22:26 +00001676
Dan Gohman76466372009-04-27 20:16:15 +00001677 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1678 // Note that this serves two purposes: It filters out loops that are
1679 // simply not analyzable, and it covers the case where this code is
1680 // being called from within backedge-taken count analysis, such that
1681 // attempting to ask for the backedge-taken count would likely result
1682 // in infinite recursion. In the later case, the analysis code will
1683 // cope with a conservative value, and it will take care to purge
1684 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001685 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001686 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001687 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001688 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001689
1690 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman494dac32009-04-29 22:28:28 +00001691 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001692 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001693 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001694 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001695 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1696 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001697 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001698 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001699 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001700 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1701 const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1702 const SCEV *WideMaxBECount =
1703 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001704 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001705 getAddExpr(WideStart,
1706 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001707 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001708 if (SAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001709 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1710 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman494dac32009-04-29 22:28:28 +00001711 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001712 return getAddRecExpr(
1713 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1714 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001715 }
Dan Gohman8c129d72009-07-16 17:34:36 +00001716 // Similar to above, only this time treat the step value as unsigned.
1717 // This covers loops that count up with an unsigned step.
Dan Gohman8c129d72009-07-16 17:34:36 +00001718 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001719 getAddExpr(WideStart,
1720 getMulExpr(WideMaxBECount,
Dan Gohman8c129d72009-07-16 17:34:36 +00001721 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001722 if (SAdd == OperandExtendedAdd) {
Sanjoy Dasbf5d8702015-02-09 18:34:55 +00001723 // If AR wraps around then
1724 //
1725 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1726 // => SAdd != OperandExtendedAdd
1727 //
1728 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1729 // (SAdd == OperandExtendedAdd => AR is NW)
1730
1731 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1732
Dan Gohman8c129d72009-07-16 17:34:36 +00001733 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001734 return getAddRecExpr(
1735 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1736 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001737 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001738 }
1739
1740 // If the backedge is guarded by a comparison with the pre-inc value
1741 // the addrec is safe. Also, if the entry is guarded by a comparison
1742 // with the start value and the backedge is guarded by a comparison
1743 // with the post-inc value, the addrec is safe.
Andrew Trick812276e2011-05-31 21:17:47 +00001744 ICmpInst::Predicate Pred;
Sanjoy Das4153f472015-02-18 01:47:07 +00001745 const SCEV *OverflowLimit =
1746 getSignedOverflowLimitForStep(Step, &Pred, this);
Andrew Trick812276e2011-05-31 21:17:47 +00001747 if (OverflowLimit &&
1748 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1749 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1750 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1751 OverflowLimit)))) {
1752 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1753 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Sanjoy Das4153f472015-02-18 01:47:07 +00001754 return getAddRecExpr(
1755 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1756 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman76466372009-04-27 20:16:15 +00001757 }
1758 }
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001759 // If Start and Step are constants, check if we can apply this
1760 // transformation:
1761 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001762 auto *SC1 = dyn_cast<SCEVConstant>(Start);
1763 auto *SC2 = dyn_cast<SCEVConstant>(Step);
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001764 if (SC1 && SC2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001765 const APInt &C1 = SC1->getAPInt();
1766 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001767 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1768 C2.isPowerOf2()) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001769 Start = getSignExtendExpr(Start, Ty);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001770 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1771 AR->getNoWrapFlags());
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001772 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1773 }
1774 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001775
1776 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1777 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1778 return getAddRecExpr(
1779 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1780 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1781 }
Dan Gohman76466372009-04-27 20:16:15 +00001782 }
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001783
Dan Gohman74a0ba12009-07-13 20:55:53 +00001784 // The cast wasn't folded; create an explicit cast node.
1785 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001786 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001787 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1788 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001789 UniqueSCEVs.InsertNode(S, IP);
1790 return S;
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001791}
1792
Dan Gohman8db2edc2009-06-13 15:56:47 +00001793/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1794/// unspecified bits out to the given type.
1795///
Dan Gohmanaf752342009-07-07 17:06:11 +00001796const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001797 Type *Ty) {
Dan Gohman8db2edc2009-06-13 15:56:47 +00001798 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1799 "This is not an extending conversion!");
1800 assert(isSCEVable(Ty) &&
1801 "This is not a conversion to a SCEVable type!");
1802 Ty = getEffectiveSCEVType(Ty);
1803
1804 // Sign-extend negative constants.
1805 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001806 if (SC->getAPInt().isNegative())
Dan Gohman8db2edc2009-06-13 15:56:47 +00001807 return getSignExtendExpr(Op, Ty);
1808
1809 // Peel off a truncate cast.
1810 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001811 const SCEV *NewOp = T->getOperand();
Dan Gohman8db2edc2009-06-13 15:56:47 +00001812 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1813 return getAnyExtendExpr(NewOp, Ty);
1814 return getTruncateOrNoop(NewOp, Ty);
1815 }
1816
1817 // Next try a zext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001818 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001819 if (!isa<SCEVZeroExtendExpr>(ZExt))
1820 return ZExt;
1821
1822 // Next try a sext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001823 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001824 if (!isa<SCEVSignExtendExpr>(SExt))
1825 return SExt;
1826
Dan Gohman51ad99d2010-01-21 02:09:26 +00001827 // Force the cast to be folded into the operands of an addrec.
1828 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1829 SmallVector<const SCEV *, 4> Ops;
Tobias Grosser924221c2014-05-07 06:07:47 +00001830 for (const SCEV *Op : AR->operands())
1831 Ops.push_back(getAnyExtendExpr(Op, Ty));
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001832 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001833 }
1834
Dan Gohman8db2edc2009-06-13 15:56:47 +00001835 // If the expression is obviously signed, use the sext cast value.
1836 if (isa<SCEVSMaxExpr>(Op))
1837 return SExt;
1838
1839 // Absent any other information, use the zext cast value.
1840 return ZExt;
1841}
1842
Dan Gohman038d02e2009-06-14 22:58:51 +00001843/// CollectAddOperandsWithScales - Process the given Ops list, which is
1844/// a list of operands to be added under the given scale, update the given
1845/// map. This is a helper function for getAddRecExpr. As an example of
1846/// what it does, given a sequence of operands that would form an add
1847/// expression like this:
1848///
Tobias Grosserba49e422014-03-05 10:37:17 +00001849/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
Dan Gohman038d02e2009-06-14 22:58:51 +00001850///
1851/// where A and B are constants, update the map with these values:
1852///
1853/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1854///
1855/// and add 13 + A*B*29 to AccumulatedConstant.
1856/// This will allow getAddRecExpr to produce this:
1857///
1858/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1859///
1860/// This form often exposes folding opportunities that are hidden in
1861/// the original operand list.
1862///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001863/// Return true iff it appears that any interesting folding opportunities
Dan Gohman038d02e2009-06-14 22:58:51 +00001864/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1865/// the common case where no interesting opportunities are present, and
1866/// is also used as a check to avoid infinite recursion.
1867///
1868static bool
Dan Gohmanaf752342009-07-07 17:06:11 +00001869CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
Craig Topper2cd5ff82013-07-11 16:22:38 +00001870 SmallVectorImpl<const SCEV *> &NewOps,
Dan Gohman038d02e2009-06-14 22:58:51 +00001871 APInt &AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001872 const SCEV *const *Ops, size_t NumOperands,
Dan Gohman038d02e2009-06-14 22:58:51 +00001873 const APInt &Scale,
1874 ScalarEvolution &SE) {
1875 bool Interesting = false;
1876
Dan Gohman45073042010-06-18 19:12:32 +00001877 // Iterate over the add operands. They are sorted, with constants first.
1878 unsigned i = 0;
1879 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1880 ++i;
1881 // Pull a buried constant out to the outside.
1882 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1883 Interesting = true;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001884 AccumulatedConstant += Scale * C->getAPInt();
Dan Gohman45073042010-06-18 19:12:32 +00001885 }
1886
1887 // Next comes everything else. We're especially interested in multiplies
1888 // here, but they're in the middle, so just visit the rest with one loop.
1889 for (; i != NumOperands; ++i) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001890 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1891 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1892 APInt NewScale =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001893 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
Dan Gohman038d02e2009-06-14 22:58:51 +00001894 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1895 // A multiplication of a constant with another add; recurse.
Dan Gohman00524492010-03-18 01:17:13 +00001896 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohman038d02e2009-06-14 22:58:51 +00001897 Interesting |=
1898 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001899 Add->op_begin(), Add->getNumOperands(),
Dan Gohman038d02e2009-06-14 22:58:51 +00001900 NewScale, SE);
1901 } else {
1902 // A multiplication of a constant with some other value. Update
1903 // the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00001904 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1905 const SCEV *Key = SE.getMulExpr(MulOps);
Sanjoy Das7a9f8bb2015-09-17 19:04:09 +00001906 auto Pair = M.insert(std::make_pair(Key, NewScale));
Dan Gohman038d02e2009-06-14 22:58:51 +00001907 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001908 NewOps.push_back(Pair.first->first);
1909 } else {
1910 Pair.first->second += NewScale;
1911 // The map already had an entry for this value, which may indicate
1912 // a folding opportunity.
1913 Interesting = true;
1914 }
1915 }
Dan Gohman038d02e2009-06-14 22:58:51 +00001916 } else {
1917 // An ordinary operand. Update the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00001918 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohmane00beaa2009-06-29 18:25:52 +00001919 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohman038d02e2009-06-14 22:58:51 +00001920 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001921 NewOps.push_back(Pair.first->first);
1922 } else {
1923 Pair.first->second += Scale;
1924 // The map already had an entry for this value, which may indicate
1925 // a folding opportunity.
1926 Interesting = true;
1927 }
1928 }
1929 }
1930
1931 return Interesting;
1932}
1933
Sanjoy Das81401d42015-01-10 23:41:24 +00001934// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
1935// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
1936// can't-overflow flags for the operation if possible.
1937static SCEV::NoWrapFlags
1938StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
1939 const SmallVectorImpl<const SCEV *> &Ops,
Sanjoy Das8f274152015-10-22 19:57:19 +00001940 SCEV::NoWrapFlags Flags) {
Sanjoy Das81401d42015-01-10 23:41:24 +00001941 using namespace std::placeholders;
Sanjoy Das8f274152015-10-22 19:57:19 +00001942 typedef OverflowingBinaryOperator OBO;
Sanjoy Das81401d42015-01-10 23:41:24 +00001943
1944 bool CanAnalyze =
1945 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
1946 (void)CanAnalyze;
1947 assert(CanAnalyze && "don't call from other places!");
1948
1949 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1950 SCEV::NoWrapFlags SignOrUnsignWrap =
Sanjoy Das8f274152015-10-22 19:57:19 +00001951 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00001952
1953 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Sanjoy Das9b0015f2015-11-29 23:40:57 +00001954 auto IsKnownNonNegative = [&](const SCEV *S) {
1955 return SE->isKnownNonNegative(S);
1956 };
Sanjoy Das81401d42015-01-10 23:41:24 +00001957
Sanjoy Das3b827c72015-11-29 23:40:53 +00001958 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
Sanjoy Das8f274152015-10-22 19:57:19 +00001959 Flags =
1960 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00001961
Sanjoy Das8f274152015-10-22 19:57:19 +00001962 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
1963
1964 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
1965 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
1966
1967 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
1968 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
1969
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001970 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
Sanjoy Das8f274152015-10-22 19:57:19 +00001971 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
1972 auto NSWRegion =
1973 ConstantRange::makeNoWrapRegion(Instruction::Add, C, OBO::NoSignedWrap);
1974 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
1975 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
1976 }
1977 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
1978 auto NUWRegion =
1979 ConstantRange::makeNoWrapRegion(Instruction::Add, C,
1980 OBO::NoUnsignedWrap);
1981 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
1982 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
1983 }
1984 }
1985
1986 return Flags;
Sanjoy Das81401d42015-01-10 23:41:24 +00001987}
1988
Dan Gohman4d5435d2009-05-24 23:45:28 +00001989/// getAddExpr - Get a canonical add expression, or something simpler if
1990/// possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00001991const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00001992 SCEV::NoWrapFlags Flags) {
1993 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
1994 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00001995 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +00001996 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00001997#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00001998 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00001999 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohman9136d9f2010-06-18 19:09:27 +00002000 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002001 "SCEVAddExpr operand types don't match!");
2002#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002003
2004 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002005 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002006
Sanjoy Das64895612015-10-09 02:44:45 +00002007 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2008
Chris Lattnerd934c702004-04-02 20:23:17 +00002009 // If there are any constants, fold them together.
2010 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002011 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002012 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +00002013 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002014 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002015 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002016 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
Dan Gohman011cf682009-06-14 22:53:57 +00002017 if (Ops.size() == 2) return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002018 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002019 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002020 }
2021
2022 // If we are left with a constant zero being added, strip it off.
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002023 if (LHSC->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002024 Ops.erase(Ops.begin());
2025 --Idx;
2026 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002027
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002028 if (Ops.size() == 1) return Ops[0];
2029 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002030
Dan Gohman15871f22010-08-27 21:39:59 +00002031 // Okay, check to see if the same value occurs in the operand list more than
2032 // once. If so, merge them together into an multiply expression. Since we
2033 // sorted the list, these values are required to be adjacent.
Chris Lattner229907c2011-07-18 04:54:35 +00002034 Type *Ty = Ops[0]->getType();
Dan Gohmane67b2872010-08-12 14:46:54 +00002035 bool FoundMatch = false;
Dan Gohman15871f22010-08-27 21:39:59 +00002036 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattnerd934c702004-04-02 20:23:17 +00002037 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman15871f22010-08-27 21:39:59 +00002038 // Scan ahead to count how many equal operands there are.
2039 unsigned Count = 2;
2040 while (i+Count != e && Ops[i+Count] == Ops[i])
2041 ++Count;
2042 // Merge the values into a multiply.
2043 const SCEV *Scale = getConstant(Ty, Count);
2044 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2045 if (Ops.size() == Count)
Chris Lattnerd934c702004-04-02 20:23:17 +00002046 return Mul;
Dan Gohmane67b2872010-08-12 14:46:54 +00002047 Ops[i] = Mul;
Dan Gohman15871f22010-08-27 21:39:59 +00002048 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohmanfe22f1d2010-08-28 00:39:27 +00002049 --i; e -= Count - 1;
Dan Gohmane67b2872010-08-12 14:46:54 +00002050 FoundMatch = true;
Chris Lattnerd934c702004-04-02 20:23:17 +00002051 }
Dan Gohmane67b2872010-08-12 14:46:54 +00002052 if (FoundMatch)
Andrew Trick8b55b732011-03-14 16:50:06 +00002053 return getAddExpr(Ops, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002054
Dan Gohman2e55cc52009-05-08 21:03:19 +00002055 // Check for truncates. If all the operands are truncated from the same
2056 // type, see if factoring out the truncate would permit the result to be
2057 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2058 // if the contents of the resulting outer trunc fold to something simple.
2059 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2060 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
Chris Lattner229907c2011-07-18 04:54:35 +00002061 Type *DstType = Trunc->getType();
2062 Type *SrcType = Trunc->getOperand()->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00002063 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002064 bool Ok = true;
2065 // Check all the operands to see if they can be represented in the
2066 // source type of the truncate.
2067 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2068 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2069 if (T->getOperand()->getType() != SrcType) {
2070 Ok = false;
2071 break;
2072 }
2073 LargeOps.push_back(T->getOperand());
2074 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002075 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002076 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002077 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002078 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2079 if (const SCEVTruncateExpr *T =
2080 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2081 if (T->getOperand()->getType() != SrcType) {
2082 Ok = false;
2083 break;
2084 }
2085 LargeMulOps.push_back(T->getOperand());
Sanjoy Das63914592015-10-18 00:29:20 +00002086 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002087 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002088 } else {
2089 Ok = false;
2090 break;
2091 }
2092 }
2093 if (Ok)
2094 LargeOps.push_back(getMulExpr(LargeMulOps));
2095 } else {
2096 Ok = false;
2097 break;
2098 }
2099 }
2100 if (Ok) {
2101 // Evaluate the expression in the larger type.
Andrew Trick8b55b732011-03-14 16:50:06 +00002102 const SCEV *Fold = getAddExpr(LargeOps, Flags);
Dan Gohman2e55cc52009-05-08 21:03:19 +00002103 // If it folds to something simple, use it. Otherwise, don't.
2104 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2105 return getTruncateExpr(Fold, DstType);
2106 }
2107 }
2108
2109 // Skip past any other cast SCEVs.
Dan Gohmaneed125f2007-06-18 19:30:09 +00002110 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2111 ++Idx;
2112
2113 // If there are add operands they would be next.
Chris Lattnerd934c702004-04-02 20:23:17 +00002114 if (Idx < Ops.size()) {
2115 bool DeletedAdd = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002116 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002117 // If we have an add, expand the add operands onto the end of the operands
2118 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002119 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002120 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002121 DeletedAdd = true;
2122 }
2123
2124 // If we deleted at least one add, we added operands to the end of the list,
2125 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002126 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002127 if (DeletedAdd)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002128 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002129 }
2130
2131 // Skip over the add expression until we get to a multiply.
2132 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2133 ++Idx;
2134
Dan Gohman038d02e2009-06-14 22:58:51 +00002135 // Check to see if there are any folding opportunities present with
2136 // operands multiplied by constant values.
2137 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2138 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohmanaf752342009-07-07 17:06:11 +00002139 DenseMap<const SCEV *, APInt> M;
2140 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman038d02e2009-06-14 22:58:51 +00002141 APInt AccumulatedConstant(BitWidth, 0);
2142 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002143 Ops.data(), Ops.size(),
2144 APInt(BitWidth, 1), *this)) {
Sanjoy Das7d752672015-12-08 04:32:54 +00002145 struct APIntCompare {
2146 bool operator()(const APInt &LHS, const APInt &RHS) const {
2147 return LHS.ult(RHS);
2148 }
2149 };
2150
Dan Gohman038d02e2009-06-14 22:58:51 +00002151 // Some interesting folding opportunity is present, so its worthwhile to
2152 // re-generate the operands list. Group the operands by constant scale,
2153 // to avoid multiplying by the same constant scale multiple times.
Dan Gohmanaf752342009-07-07 17:06:11 +00002154 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002155 for (const SCEV *NewOp : NewOps)
2156 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
Dan Gohman038d02e2009-06-14 22:58:51 +00002157 // Re-generate the operands list.
2158 Ops.clear();
2159 if (AccumulatedConstant != 0)
2160 Ops.push_back(getConstant(AccumulatedConstant));
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002161 for (auto &MulOp : MulOpLists)
2162 if (MulOp.first != 0)
2163 Ops.push_back(getMulExpr(getConstant(MulOp.first),
2164 getAddExpr(MulOp.second)));
Dan Gohman038d02e2009-06-14 22:58:51 +00002165 if (Ops.empty())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002166 return getZero(Ty);
Dan Gohman038d02e2009-06-14 22:58:51 +00002167 if (Ops.size() == 1)
2168 return Ops[0];
2169 return getAddExpr(Ops);
2170 }
2171 }
2172
Chris Lattnerd934c702004-04-02 20:23:17 +00002173 // If we are adding something to a multiply expression, make sure the
2174 // something is not already an operand of the multiply. If so, merge it into
2175 // the multiply.
2176 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002177 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002178 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman48f82222009-05-04 22:30:44 +00002179 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman157847f2010-08-12 14:52:55 +00002180 if (isa<SCEVConstant>(MulOpSCEV))
2181 continue;
Chris Lattnerd934c702004-04-02 20:23:17 +00002182 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman157847f2010-08-12 14:52:55 +00002183 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002184 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohmanaf752342009-07-07 17:06:11 +00002185 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002186 if (Mul->getNumOperands() != 2) {
2187 // If the multiply has more than two operands, we must get the
2188 // Y*Z term.
Dan Gohman797a1db2010-08-16 16:57:24 +00002189 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2190 Mul->op_begin()+MulOp);
2191 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002192 InnerMul = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002193 }
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002194 const SCEV *One = getOne(Ty);
Dan Gohmancf32f2b2010-08-13 20:17:14 +00002195 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman157847f2010-08-12 14:52:55 +00002196 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattnerd934c702004-04-02 20:23:17 +00002197 if (Ops.size() == 2) return OuterMul;
2198 if (AddOp < Idx) {
2199 Ops.erase(Ops.begin()+AddOp);
2200 Ops.erase(Ops.begin()+Idx-1);
2201 } else {
2202 Ops.erase(Ops.begin()+Idx);
2203 Ops.erase(Ops.begin()+AddOp-1);
2204 }
2205 Ops.push_back(OuterMul);
Dan Gohmana37eaf22007-10-22 18:31:58 +00002206 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002207 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002208
Chris Lattnerd934c702004-04-02 20:23:17 +00002209 // Check this multiply against other multiplies being added together.
2210 for (unsigned OtherMulIdx = Idx+1;
2211 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2212 ++OtherMulIdx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002213 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002214 // If MulOp occurs in OtherMul, we can fold the two multiplies
2215 // together.
2216 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2217 OMulOp != e; ++OMulOp)
2218 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2219 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohmanaf752342009-07-07 17:06:11 +00002220 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002221 if (Mul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002222 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002223 Mul->op_begin()+MulOp);
2224 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002225 InnerMul1 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002226 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002227 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002228 if (OtherMul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002229 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002230 OtherMul->op_begin()+OMulOp);
2231 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002232 InnerMul2 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002233 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002234 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2235 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattnerd934c702004-04-02 20:23:17 +00002236 if (Ops.size() == 2) return OuterMul;
Dan Gohmanaabfc522010-08-31 22:50:31 +00002237 Ops.erase(Ops.begin()+Idx);
2238 Ops.erase(Ops.begin()+OtherMulIdx-1);
2239 Ops.push_back(OuterMul);
2240 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002241 }
2242 }
2243 }
2244 }
2245
2246 // If there are any add recurrences in the operands list, see if any other
2247 // added values are loop invariant. If so, we can fold them into the
2248 // recurrence.
2249 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2250 ++Idx;
2251
2252 // Scan over all recurrences, trying to fold loop invariants into them.
2253 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2254 // Scan all of the other operands to this add and add them to the vector if
2255 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002256 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002257 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002258 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002259 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002260 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002261 LIOps.push_back(Ops[i]);
2262 Ops.erase(Ops.begin()+i);
2263 --i; --e;
2264 }
2265
2266 // If we found some loop invariants, fold them into the recurrence.
2267 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002268 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattnerd934c702004-04-02 20:23:17 +00002269 LIOps.push_back(AddRec->getStart());
2270
Dan Gohmanaf752342009-07-07 17:06:11 +00002271 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman7a2dab82009-12-18 03:57:04 +00002272 AddRec->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002273 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002274
Dan Gohman16206132010-06-30 07:16:37 +00002275 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher23bf3ba2011-01-11 09:02:09 +00002276 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002277 // Always propagate NW.
2278 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick8b55b732011-03-14 16:50:06 +00002279 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman51f13052009-12-18 18:45:31 +00002280
Chris Lattnerd934c702004-04-02 20:23:17 +00002281 // If all of the other operands were loop invariant, we are done.
2282 if (Ops.size() == 1) return NewRec;
2283
Nick Lewyckydb66b822011-09-06 05:08:09 +00002284 // Otherwise, add the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002285 for (unsigned i = 0;; ++i)
2286 if (Ops[i] == AddRec) {
2287 Ops[i] = NewRec;
2288 break;
2289 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002290 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002291 }
2292
2293 // Okay, if there weren't any loop invariants to be folded, check to see if
2294 // there are multiple AddRec's with the same loop induction variable being
2295 // added together. If so, we can fold them.
2296 for (unsigned OtherIdx = Idx+1;
Dan Gohmanc866bf42010-08-27 20:45:56 +00002297 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2298 ++OtherIdx)
2299 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2300 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2301 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2302 AddRec->op_end());
2303 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2304 ++OtherIdx)
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002305 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman028c1812010-08-29 14:53:34 +00002306 if (OtherAddRec->getLoop() == AddRecLoop) {
2307 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2308 i != e; ++i) {
Dan Gohmanc866bf42010-08-27 20:45:56 +00002309 if (i >= AddRecOps.size()) {
Dan Gohman028c1812010-08-29 14:53:34 +00002310 AddRecOps.append(OtherAddRec->op_begin()+i,
2311 OtherAddRec->op_end());
Dan Gohmanc866bf42010-08-27 20:45:56 +00002312 break;
2313 }
Dan Gohman028c1812010-08-29 14:53:34 +00002314 AddRecOps[i] = getAddExpr(AddRecOps[i],
2315 OtherAddRec->getOperand(i));
Dan Gohmanc866bf42010-08-27 20:45:56 +00002316 }
2317 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattnerd934c702004-04-02 20:23:17 +00002318 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002319 // Step size has changed, so we cannot guarantee no self-wraparound.
2320 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Dan Gohmanc866bf42010-08-27 20:45:56 +00002321 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002322 }
2323
2324 // Otherwise couldn't fold anything into this recurrence. Move onto the
2325 // next one.
2326 }
2327
2328 // Okay, it looks like we really DO need an add expr. Check to see if we
2329 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002330 FoldingSetNodeID ID;
2331 ID.AddInteger(scAddExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002332 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2333 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002334 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002335 SCEVAddExpr *S =
2336 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2337 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002338 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2339 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002340 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2341 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002342 UniqueSCEVs.InsertNode(S, IP);
2343 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002344 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002345 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002346}
2347
Nick Lewycky287682e2011-10-04 06:51:26 +00002348static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2349 uint64_t k = i*j;
2350 if (j > 1 && k / j != i) Overflow = true;
2351 return k;
2352}
2353
2354/// Compute the result of "n choose k", the binomial coefficient. If an
2355/// intermediate computation overflows, Overflow will be set and the return will
Benjamin Kramerbde91762012-06-02 10:20:22 +00002356/// be garbage. Overflow is not cleared on absence of overflow.
Nick Lewycky287682e2011-10-04 06:51:26 +00002357static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2358 // We use the multiplicative formula:
2359 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2360 // At each iteration, we take the n-th term of the numeral and divide by the
2361 // (k-n)th term of the denominator. This division will always produce an
2362 // integral result, and helps reduce the chance of overflow in the
2363 // intermediate computations. However, we can still overflow even when the
2364 // final result would fit.
2365
2366 if (n == 0 || n == k) return 1;
2367 if (k > n) return 0;
2368
2369 if (k > n/2)
2370 k = n-k;
2371
2372 uint64_t r = 1;
2373 for (uint64_t i = 1; i <= k; ++i) {
2374 r = umul_ov(r, n-(i-1), Overflow);
2375 r /= i;
2376 }
2377 return r;
2378}
2379
Nick Lewycky05044c22014-12-06 00:45:50 +00002380/// Determine if any of the operands in this SCEV are a constant or if
2381/// any of the add or multiply expressions in this SCEV contain a constant.
2382static bool containsConstantSomewhere(const SCEV *StartExpr) {
2383 SmallVector<const SCEV *, 4> Ops;
2384 Ops.push_back(StartExpr);
2385 while (!Ops.empty()) {
2386 const SCEV *CurrentExpr = Ops.pop_back_val();
2387 if (isa<SCEVConstant>(*CurrentExpr))
2388 return true;
2389
2390 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2391 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002392 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
Nick Lewycky05044c22014-12-06 00:45:50 +00002393 }
2394 }
2395 return false;
2396}
2397
Dan Gohman4d5435d2009-05-24 23:45:28 +00002398/// getMulExpr - Get a canonical multiply expression, or something simpler if
2399/// possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002400const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002401 SCEV::NoWrapFlags Flags) {
2402 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2403 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002404 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohman51ad99d2010-01-21 02:09:26 +00002405 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002406#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002407 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002408 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002409 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002410 "SCEVMulExpr operand types don't match!");
2411#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002412
2413 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002414 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002415
Sanjoy Das64895612015-10-09 02:44:45 +00002416 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2417
Chris Lattnerd934c702004-04-02 20:23:17 +00002418 // If there are any constants, fold them together.
2419 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002420 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002421
2422 // C1*(C2+V) -> C1*C2 + C1*V
2423 if (Ops.size() == 2)
Nick Lewycky05044c22014-12-06 00:45:50 +00002424 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2425 // If any of Add's ops are Adds or Muls with a constant,
2426 // apply this transformation as well.
2427 if (Add->getNumOperands() == 2)
2428 if (containsConstantSomewhere(Add))
2429 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2430 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002431
Chris Lattnerd934c702004-04-02 20:23:17 +00002432 ++Idx;
Dan Gohmana30370b2009-05-04 22:02:23 +00002433 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002434 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002435 ConstantInt *Fold =
2436 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002437 Ops[0] = getConstant(Fold);
2438 Ops.erase(Ops.begin()+1); // Erase the folded element
2439 if (Ops.size() == 1) return Ops[0];
2440 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002441 }
2442
2443 // If we are left with a constant one being multiplied, strip it off.
2444 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2445 Ops.erase(Ops.begin());
2446 --Idx;
Reid Spencer2e54a152007-03-02 00:28:52 +00002447 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002448 // If we have a multiply of zero, it will always be zero.
2449 return Ops[0];
Dan Gohman51ad99d2010-01-21 02:09:26 +00002450 } else if (Ops[0]->isAllOnesValue()) {
2451 // If we have a mul by -1 of an add, try distributing the -1 among the
2452 // add operands.
Andrew Trick8b55b732011-03-14 16:50:06 +00002453 if (Ops.size() == 2) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002454 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2455 SmallVector<const SCEV *, 4> NewOps;
2456 bool AnyFolded = false;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002457 for (const SCEV *AddOp : Add->operands()) {
2458 const SCEV *Mul = getMulExpr(Ops[0], AddOp);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002459 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2460 NewOps.push_back(Mul);
2461 }
2462 if (AnyFolded)
2463 return getAddExpr(NewOps);
Sanjoy Das63914592015-10-18 00:29:20 +00002464 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
Andrew Tricke92dcce2011-03-14 17:38:54 +00002465 // Negation preserves a recurrence's no self-wrap property.
2466 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002467 for (const SCEV *AddRecOp : AddRec->operands())
2468 Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2469
Andrew Tricke92dcce2011-03-14 17:38:54 +00002470 return getAddRecExpr(Operands, AddRec->getLoop(),
2471 AddRec->getNoWrapFlags(SCEV::FlagNW));
2472 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002473 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002474 }
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002475
2476 if (Ops.size() == 1)
2477 return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00002478 }
2479
2480 // Skip over the add expression until we get to a multiply.
2481 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2482 ++Idx;
2483
Chris Lattnerd934c702004-04-02 20:23:17 +00002484 // If there are mul operands inline them all into this expression.
2485 if (Idx < Ops.size()) {
2486 bool DeletedMul = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002487 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002488 // If we have an mul, expand the mul operands onto the end of the operands
2489 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002490 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002491 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002492 DeletedMul = true;
2493 }
2494
2495 // If we deleted at least one mul, we added operands to the end of the list,
2496 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002497 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002498 if (DeletedMul)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002499 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002500 }
2501
2502 // If there are any add recurrences in the operands list, see if any other
2503 // added values are loop invariant. If so, we can fold them into the
2504 // recurrence.
2505 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2506 ++Idx;
2507
2508 // Scan over all recurrences, trying to fold loop invariants into them.
2509 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2510 // Scan all of the other operands to this mul and add them to the vector if
2511 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002512 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002513 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f2de012010-08-29 14:55:19 +00002514 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002515 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002516 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002517 LIOps.push_back(Ops[i]);
2518 Ops.erase(Ops.begin()+i);
2519 --i; --e;
2520 }
2521
2522 // If we found some loop invariants, fold them into the recurrence.
2523 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002524 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanaf752342009-07-07 17:06:11 +00002525 SmallVector<const SCEV *, 4> NewOps;
Chris Lattnerd934c702004-04-02 20:23:17 +00002526 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman8f5954f2010-06-17 23:34:09 +00002527 const SCEV *Scale = getMulExpr(LIOps);
2528 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2529 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002530
Dan Gohman16206132010-06-30 07:16:37 +00002531 // Build the new addrec. Propagate the NUW and NSW flags if both the
2532 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick8b55b732011-03-14 16:50:06 +00002533 //
2534 // No self-wrap cannot be guaranteed after changing the step size, but
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002535 // will be inferred if either NUW or NSW is true.
Andrew Trick8b55b732011-03-14 16:50:06 +00002536 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2537 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002538
2539 // If all of the other operands were loop invariant, we are done.
2540 if (Ops.size() == 1) return NewRec;
2541
Nick Lewyckydb66b822011-09-06 05:08:09 +00002542 // Otherwise, multiply the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002543 for (unsigned i = 0;; ++i)
2544 if (Ops[i] == AddRec) {
2545 Ops[i] = NewRec;
2546 break;
2547 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002548 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002549 }
2550
2551 // Okay, if there weren't any loop invariants to be folded, check to see if
2552 // there are multiple AddRec's with the same loop induction variable being
2553 // multiplied together. If so, we can fold them.
Nick Lewycky97756402014-09-01 05:17:15 +00002554
2555 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2556 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2557 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2558 // ]]],+,...up to x=2n}.
2559 // Note that the arguments to choose() are always integers with values
2560 // known at compile time, never SCEV objects.
2561 //
2562 // The implementation avoids pointless extra computations when the two
2563 // addrec's are of different length (mathematically, it's equivalent to
2564 // an infinite stream of zeros on the right).
2565 bool OpsModified = false;
Chris Lattnerd934c702004-04-02 20:23:17 +00002566 for (unsigned OtherIdx = Idx+1;
Nick Lewycky97756402014-09-01 05:17:15 +00002567 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002568 ++OtherIdx) {
Nick Lewycky97756402014-09-01 05:17:15 +00002569 const SCEVAddRecExpr *OtherAddRec =
2570 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2571 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
Andrew Trick946f76b2012-05-30 03:35:17 +00002572 continue;
2573
Nick Lewycky97756402014-09-01 05:17:15 +00002574 bool Overflow = false;
2575 Type *Ty = AddRec->getType();
2576 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2577 SmallVector<const SCEV*, 7> AddRecOps;
2578 for (int x = 0, xe = AddRec->getNumOperands() +
2579 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002580 const SCEV *Term = getZero(Ty);
Nick Lewycky97756402014-09-01 05:17:15 +00002581 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2582 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2583 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2584 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2585 z < ze && !Overflow; ++z) {
2586 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2587 uint64_t Coeff;
2588 if (LargerThan64Bits)
2589 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2590 else
2591 Coeff = Coeff1*Coeff2;
2592 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2593 const SCEV *Term1 = AddRec->getOperand(y-z);
2594 const SCEV *Term2 = OtherAddRec->getOperand(z);
2595 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
Andrew Trick946f76b2012-05-30 03:35:17 +00002596 }
Andrew Trick946f76b2012-05-30 03:35:17 +00002597 }
Nick Lewycky97756402014-09-01 05:17:15 +00002598 AddRecOps.push_back(Term);
Chris Lattnerd934c702004-04-02 20:23:17 +00002599 }
Nick Lewycky97756402014-09-01 05:17:15 +00002600 if (!Overflow) {
2601 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2602 SCEV::FlagAnyWrap);
2603 if (Ops.size() == 2) return NewAddRec;
2604 Ops[Idx] = NewAddRec;
2605 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2606 OpsModified = true;
2607 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2608 if (!AddRec)
2609 break;
2610 }
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002611 }
Nick Lewycky97756402014-09-01 05:17:15 +00002612 if (OpsModified)
2613 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002614
2615 // Otherwise couldn't fold anything into this recurrence. Move onto the
2616 // next one.
2617 }
2618
2619 // Okay, it looks like we really DO need an mul expr. Check to see if we
2620 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002621 FoldingSetNodeID ID;
2622 ID.AddInteger(scMulExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002623 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2624 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002625 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002626 SCEVMulExpr *S =
2627 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2628 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002629 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2630 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002631 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2632 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002633 UniqueSCEVs.InsertNode(S, IP);
2634 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002635 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002636 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002637}
2638
Andreas Bolka7a5c8db2009-08-07 22:55:26 +00002639/// getUDivExpr - Get a canonical unsigned division expression, or something
2640/// simpler if possible.
Dan Gohmanabd17092009-06-24 14:49:00 +00002641const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2642 const SCEV *RHS) {
Dan Gohmand33f36e2009-05-18 15:44:58 +00002643 assert(getEffectiveSCEVType(LHS->getType()) ==
2644 getEffectiveSCEVType(RHS->getType()) &&
2645 "SCEVUDivExpr operand types don't match!");
2646
Dan Gohmana30370b2009-05-04 22:02:23 +00002647 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002648 if (RHSC->getValue()->equalsInt(1))
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00002649 return LHS; // X udiv 1 --> x
Dan Gohmanacd700a2010-04-22 01:35:11 +00002650 // If the denominator is zero, the result of the udiv is undefined. Don't
2651 // try to analyze it, because the resolution chosen here may differ from
2652 // the resolution chosen in other parts of the compiler.
2653 if (!RHSC->getValue()->isZero()) {
2654 // Determine if the division can be folded into the operands of
2655 // its operands.
2656 // TODO: Generalize this to non-constants by using known-bits information.
Chris Lattner229907c2011-07-18 04:54:35 +00002657 Type *Ty = LHS->getType();
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002658 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
Dan Gohmandb764c62010-08-04 19:52:50 +00002659 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanacd700a2010-04-22 01:35:11 +00002660 // For non-power-of-two values, effectively round the value up to the
2661 // nearest power of two.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002662 if (!RHSC->getAPInt().isPowerOf2())
Dan Gohmanacd700a2010-04-22 01:35:11 +00002663 ++MaxShiftAmt;
Chris Lattner229907c2011-07-18 04:54:35 +00002664 IntegerType *ExtTy =
Dan Gohmanacd700a2010-04-22 01:35:11 +00002665 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohmanacd700a2010-04-22 01:35:11 +00002666 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2667 if (const SCEVConstant *Step =
Andrew Trick6d45a012011-08-06 07:00:37 +00002668 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2669 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002670 const APInt &StepInt = Step->getAPInt();
2671 const APInt &DivInt = RHSC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002672 if (!StepInt.urem(DivInt) &&
Dan Gohmanacd700a2010-04-22 01:35:11 +00002673 getZeroExtendExpr(AR, ExtTy) ==
2674 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2675 getZeroExtendExpr(Step, ExtTy),
Andrew Trick8b55b732011-03-14 16:50:06 +00002676 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002677 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002678 for (const SCEV *Op : AR->operands())
2679 Operands.push_back(getUDivExpr(Op, RHS));
2680 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002681 }
Andrew Trick6d45a012011-08-06 07:00:37 +00002682 /// Get a canonical UDivExpr for a recurrence.
2683 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2684 // We can currently only fold X%N if X is constant.
2685 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2686 if (StartC && !DivInt.urem(StepInt) &&
2687 getZeroExtendExpr(AR, ExtTy) ==
2688 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2689 getZeroExtendExpr(Step, ExtTy),
2690 AR->getLoop(), SCEV::FlagAnyWrap)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002691 const APInt &StartInt = StartC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002692 const APInt &StartRem = StartInt.urem(StepInt);
2693 if (StartRem != 0)
2694 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2695 AR->getLoop(), SCEV::FlagNW);
2696 }
2697 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002698 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2699 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2700 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002701 for (const SCEV *Op : M->operands())
2702 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002703 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2704 // Find an operand that's safely divisible.
2705 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2706 const SCEV *Op = M->getOperand(i);
2707 const SCEV *Div = getUDivExpr(Op, RHSC);
2708 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2709 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2710 M->op_end());
2711 Operands[i] = Div;
2712 return getMulExpr(Operands);
2713 }
2714 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002715 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002716 // (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 +00002717 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002718 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002719 for (const SCEV *Op : A->operands())
2720 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002721 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2722 Operands.clear();
2723 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2724 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2725 if (isa<SCEVUDivExpr>(Op) ||
2726 getMulExpr(Op, RHS) != A->getOperand(i))
2727 break;
2728 Operands.push_back(Op);
2729 }
2730 if (Operands.size() == A->getNumOperands())
2731 return getAddExpr(Operands);
2732 }
2733 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002734
Dan Gohmanacd700a2010-04-22 01:35:11 +00002735 // Fold if both operands are constant.
2736 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2737 Constant *LHSCV = LHSC->getValue();
2738 Constant *RHSCV = RHSC->getValue();
2739 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2740 RHSCV)));
2741 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002742 }
2743 }
2744
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002745 FoldingSetNodeID ID;
2746 ID.AddInteger(scUDivExpr);
2747 ID.AddPointer(LHS);
2748 ID.AddPointer(RHS);
Craig Topper9f008862014-04-15 04:59:12 +00002749 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002750 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00002751 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2752 LHS, RHS);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002753 UniqueSCEVs.InsertNode(S, IP);
2754 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002755}
2756
Nick Lewycky31eaca52014-01-27 10:04:03 +00002757static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002758 APInt A = C1->getAPInt().abs();
2759 APInt B = C2->getAPInt().abs();
Nick Lewycky31eaca52014-01-27 10:04:03 +00002760 uint32_t ABW = A.getBitWidth();
2761 uint32_t BBW = B.getBitWidth();
2762
2763 if (ABW > BBW)
2764 B = B.zext(ABW);
2765 else if (ABW < BBW)
2766 A = A.zext(BBW);
2767
2768 return APIntOps::GreatestCommonDivisor(A, B);
2769}
2770
2771/// getUDivExactExpr - Get a canonical unsigned division expression, or
2772/// something simpler if possible. There is no representation for an exact udiv
2773/// in SCEV IR, but we can attempt to remove factors from the LHS and RHS.
2774/// We can't do this when it's not exact because the udiv may be clearing bits.
2775const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2776 const SCEV *RHS) {
2777 // TODO: we could try to find factors in all sorts of things, but for now we
2778 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2779 // end of this file for inspiration.
2780
2781 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2782 if (!Mul)
2783 return getUDivExpr(LHS, RHS);
2784
2785 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2786 // If the mulexpr multiplies by a constant, then that constant must be the
2787 // first element of the mulexpr.
Sanjoy Das63914592015-10-18 00:29:20 +00002788 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
Nick Lewycky31eaca52014-01-27 10:04:03 +00002789 if (LHSCst == RHSCst) {
2790 SmallVector<const SCEV *, 2> Operands;
2791 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2792 return getMulExpr(Operands);
2793 }
2794
2795 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2796 // that there's a factor provided by one of the other terms. We need to
2797 // check.
2798 APInt Factor = gcd(LHSCst, RHSCst);
2799 if (!Factor.isIntN(1)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002800 LHSCst =
2801 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
2802 RHSCst =
2803 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
Nick Lewycky31eaca52014-01-27 10:04:03 +00002804 SmallVector<const SCEV *, 2> Operands;
2805 Operands.push_back(LHSCst);
2806 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2807 LHS = getMulExpr(Operands);
2808 RHS = RHSCst;
Nick Lewycky629199c2014-01-27 10:47:44 +00002809 Mul = dyn_cast<SCEVMulExpr>(LHS);
2810 if (!Mul)
2811 return getUDivExactExpr(LHS, RHS);
Nick Lewycky31eaca52014-01-27 10:04:03 +00002812 }
2813 }
2814 }
2815
2816 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2817 if (Mul->getOperand(i) == RHS) {
2818 SmallVector<const SCEV *, 2> Operands;
2819 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2820 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2821 return getMulExpr(Operands);
2822 }
2823 }
2824
2825 return getUDivExpr(LHS, RHS);
2826}
Chris Lattnerd934c702004-04-02 20:23:17 +00002827
Dan Gohman4d5435d2009-05-24 23:45:28 +00002828/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2829/// Simplify the expression as much as possible.
Andrew Trick8b55b732011-03-14 16:50:06 +00002830const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2831 const Loop *L,
2832 SCEV::NoWrapFlags Flags) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002833 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00002834 Operands.push_back(Start);
Dan Gohmana30370b2009-05-04 22:02:23 +00002835 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattnerd934c702004-04-02 20:23:17 +00002836 if (StepChrec->getLoop() == L) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00002837 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002838 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattnerd934c702004-04-02 20:23:17 +00002839 }
2840
2841 Operands.push_back(Step);
Andrew Trick8b55b732011-03-14 16:50:06 +00002842 return getAddRecExpr(Operands, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002843}
2844
Dan Gohman4d5435d2009-05-24 23:45:28 +00002845/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2846/// Simplify the expression as much as possible.
Dan Gohmance973df2009-06-24 04:48:43 +00002847const SCEV *
Dan Gohmanaf752342009-07-07 17:06:11 +00002848ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick8b55b732011-03-14 16:50:06 +00002849 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002850 if (Operands.size() == 1) return Operands[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002851#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002852 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002853 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002854 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002855 "SCEVAddRecExpr operand types don't match!");
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002856 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002857 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002858 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmand33f36e2009-05-18 15:44:58 +00002859#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002860
Dan Gohmanbe928e32008-06-18 16:23:07 +00002861 if (Operands.back()->isZero()) {
2862 Operands.pop_back();
Andrew Trick8b55b732011-03-14 16:50:06 +00002863 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmanbe928e32008-06-18 16:23:07 +00002864 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002865
Dan Gohmancf9c64e2010-02-19 18:49:22 +00002866 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2867 // use that information to infer NUW and NSW flags. However, computing a
2868 // BE count requires calling getAddRecExpr, so we may not yet have a
2869 // meaningful BE count at this point (and if we don't, we'd be stuck
2870 // with a SCEVCouldNotCompute as the cached BE count).
2871
Sanjoy Das81401d42015-01-10 23:41:24 +00002872 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002873
Dan Gohman223a5d22008-08-08 18:33:12 +00002874 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmana30370b2009-05-04 22:02:23 +00002875 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00002876 const Loop *NestedLoop = NestedAR->getLoop();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002877 if (L->contains(NestedLoop)
2878 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
2879 : (!NestedLoop->contains(L) &&
2880 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002881 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmancb0efec2009-12-18 01:14:11 +00002882 NestedAR->op_end());
Dan Gohman223a5d22008-08-08 18:33:12 +00002883 Operands[0] = NestedAR->getStart();
Dan Gohmancc030b72009-06-26 22:36:20 +00002884 // AddRecs require their operands be loop-invariant with respect to their
2885 // loops. Don't perform this transformation if it would break this
2886 // requirement.
Sanjoy Das3b827c72015-11-29 23:40:53 +00002887 bool AllInvariant = all_of(
2888 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00002889
Dan Gohmancc030b72009-06-26 22:36:20 +00002890 if (AllInvariant) {
Andrew Trick8b55b732011-03-14 16:50:06 +00002891 // Create a recurrence for the outer loop with the same step size.
2892 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002893 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2894 // inner recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002895 SCEV::NoWrapFlags OuterFlags =
2896 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick8b55b732011-03-14 16:50:06 +00002897
2898 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Sanjoy Das3b827c72015-11-29 23:40:53 +00002899 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
2900 return isLoopInvariant(Op, NestedLoop);
2901 });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00002902
Andrew Trick8b55b732011-03-14 16:50:06 +00002903 if (AllInvariant) {
Dan Gohmancc030b72009-06-26 22:36:20 +00002904 // Ok, both add recurrences are valid after the transformation.
Andrew Trick8b55b732011-03-14 16:50:06 +00002905 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002906 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2907 // the outer recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002908 SCEV::NoWrapFlags InnerFlags =
2909 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick8b55b732011-03-14 16:50:06 +00002910 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2911 }
Dan Gohmancc030b72009-06-26 22:36:20 +00002912 }
2913 // Reset Operands to its original state.
2914 Operands[0] = NestedAR;
Dan Gohman223a5d22008-08-08 18:33:12 +00002915 }
2916 }
2917
Dan Gohman8d67d2f2010-01-19 22:27:22 +00002918 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2919 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002920 FoldingSetNodeID ID;
2921 ID.AddInteger(scAddRecExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002922 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2923 ID.AddPointer(Operands[i]);
2924 ID.AddPointer(L);
Craig Topper9f008862014-04-15 04:59:12 +00002925 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002926 SCEVAddRecExpr *S =
2927 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2928 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002929 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2930 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002931 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2932 O, Operands.size(), L);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002933 UniqueSCEVs.InsertNode(S, IP);
2934 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002935 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002936 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002937}
2938
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002939const SCEV *
2940ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr,
2941 const SmallVectorImpl<const SCEV *> &IndexExprs,
2942 bool InBounds) {
2943 // getSCEV(Base)->getType() has the same address space as Base->getType()
2944 // because SCEV::getType() preserves the address space.
2945 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
2946 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
2947 // instruction to its SCEV, because the Instruction may be guarded by control
2948 // flow and the no-overflow bits may not be valid for the expression in any
Jingyue Wu42f1d672015-07-28 18:22:40 +00002949 // context. This can be fixed similarly to how these flags are handled for
2950 // adds.
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002951 SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
2952
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002953 const SCEV *TotalOffset = getZero(IntPtrTy);
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002954 // The address space is unimportant. The first thing we do on CurTy is getting
2955 // its element type.
2956 Type *CurTy = PointerType::getUnqual(PointeeType);
2957 for (const SCEV *IndexExpr : IndexExprs) {
2958 // Compute the (potentially symbolic) offset in bytes for this index.
2959 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2960 // For a struct, add the member offset.
2961 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
2962 unsigned FieldNo = Index->getZExtValue();
2963 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
2964
2965 // Add the field offset to the running total offset.
2966 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
2967
2968 // Update CurTy to the type of the field at Index.
2969 CurTy = STy->getTypeAtIndex(Index);
2970 } else {
2971 // Update CurTy to its element type.
2972 CurTy = cast<SequentialType>(CurTy)->getElementType();
2973 // For an array, add the element offset, explicitly scaled.
2974 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
2975 // Getelementptr indices are signed.
2976 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
2977
2978 // Multiply the index by the element size to compute the element offset.
2979 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
2980
2981 // Add the element offset to the running total offset.
2982 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2983 }
2984 }
2985
2986 // Add the total offset from all the GEP indices to the base.
2987 return getAddExpr(BaseExpr, TotalOffset, Wrap);
2988}
2989
Dan Gohmanabd17092009-06-24 14:49:00 +00002990const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2991 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002992 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002993 Ops.push_back(LHS);
2994 Ops.push_back(RHS);
2995 return getSMaxExpr(Ops);
2996}
2997
Dan Gohmanaf752342009-07-07 17:06:11 +00002998const SCEV *
2999ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003000 assert(!Ops.empty() && "Cannot get empty smax!");
3001 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003002#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003003 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003004 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003005 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003006 "SCEVSMaxExpr operand types don't match!");
3007#endif
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003008
3009 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003010 GroupByComplexity(Ops, &LI);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003011
3012 // If there are any constants, fold them together.
3013 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003014 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003015 ++Idx;
3016 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003017 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003018 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003019 ConstantInt *Fold = ConstantInt::get(
3020 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003021 Ops[0] = getConstant(Fold);
3022 Ops.erase(Ops.begin()+1); // Erase the folded element
3023 if (Ops.size() == 1) return Ops[0];
3024 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003025 }
3026
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003027 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003028 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3029 Ops.erase(Ops.begin());
3030 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003031 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3032 // If we have an smax with a constant maximum-int, it will always be
3033 // maximum-int.
3034 return Ops[0];
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003035 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003036
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003037 if (Ops.size() == 1) return Ops[0];
3038 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003039
3040 // Find the first SMax
3041 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3042 ++Idx;
3043
3044 // Check to see if one of the operands is an SMax. If so, expand its operands
3045 // onto our operand list, and recurse to simplify.
3046 if (Idx < Ops.size()) {
3047 bool DeletedSMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003048 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003049 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003050 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003051 DeletedSMax = true;
3052 }
3053
3054 if (DeletedSMax)
3055 return getSMaxExpr(Ops);
3056 }
3057
3058 // Okay, check to see if the same value occurs in the operand list twice. If
3059 // so, delete one. Since we sorted the list, these values are required to
3060 // be adjacent.
3061 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003062 // X smax Y smax Y --> X smax Y
3063 // X smax Y --> X, if X is always greater than Y
3064 if (Ops[i] == Ops[i+1] ||
3065 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3066 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3067 --i; --e;
3068 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003069 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3070 --i; --e;
3071 }
3072
3073 if (Ops.size() == 1) return Ops[0];
3074
3075 assert(!Ops.empty() && "Reduced smax down to nothing!");
3076
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003077 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003078 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003079 FoldingSetNodeID ID;
3080 ID.AddInteger(scSMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003081 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3082 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003083 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003084 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003085 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3086 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003087 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3088 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003089 UniqueSCEVs.InsertNode(S, IP);
3090 return S;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003091}
3092
Dan Gohmanabd17092009-06-24 14:49:00 +00003093const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3094 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003095 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003096 Ops.push_back(LHS);
3097 Ops.push_back(RHS);
3098 return getUMaxExpr(Ops);
3099}
3100
Dan Gohmanaf752342009-07-07 17:06:11 +00003101const SCEV *
3102ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003103 assert(!Ops.empty() && "Cannot get empty umax!");
3104 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003105#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003106 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003107 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003108 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003109 "SCEVUMaxExpr operand types don't match!");
3110#endif
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003111
3112 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003113 GroupByComplexity(Ops, &LI);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003114
3115 // If there are any constants, fold them together.
3116 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003117 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003118 ++Idx;
3119 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003120 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003121 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003122 ConstantInt *Fold = ConstantInt::get(
3123 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003124 Ops[0] = getConstant(Fold);
3125 Ops.erase(Ops.begin()+1); // Erase the folded element
3126 if (Ops.size() == 1) return Ops[0];
3127 LHSC = cast<SCEVConstant>(Ops[0]);
3128 }
3129
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003130 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003131 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3132 Ops.erase(Ops.begin());
3133 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003134 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3135 // If we have an umax with a constant maximum-int, it will always be
3136 // maximum-int.
3137 return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003138 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003139
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003140 if (Ops.size() == 1) return Ops[0];
3141 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003142
3143 // Find the first UMax
3144 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3145 ++Idx;
3146
3147 // Check to see if one of the operands is a UMax. If so, expand its operands
3148 // onto our operand list, and recurse to simplify.
3149 if (Idx < Ops.size()) {
3150 bool DeletedUMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003151 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003152 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003153 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003154 DeletedUMax = true;
3155 }
3156
3157 if (DeletedUMax)
3158 return getUMaxExpr(Ops);
3159 }
3160
3161 // Okay, check to see if the same value occurs in the operand list twice. If
3162 // so, delete one. Since we sorted the list, these values are required to
3163 // be adjacent.
3164 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003165 // X umax Y umax Y --> X umax Y
3166 // X umax Y --> X, if X is always greater than Y
3167 if (Ops[i] == Ops[i+1] ||
3168 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3169 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3170 --i; --e;
3171 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003172 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3173 --i; --e;
3174 }
3175
3176 if (Ops.size() == 1) return Ops[0];
3177
3178 assert(!Ops.empty() && "Reduced umax down to nothing!");
3179
3180 // Okay, it looks like we really DO need a umax expr. Check to see if we
3181 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003182 FoldingSetNodeID ID;
3183 ID.AddInteger(scUMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003184 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3185 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003186 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003187 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003188 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3189 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003190 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3191 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003192 UniqueSCEVs.InsertNode(S, IP);
3193 return S;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003194}
3195
Dan Gohmanabd17092009-06-24 14:49:00 +00003196const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3197 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003198 // ~smax(~x, ~y) == smin(x, y).
3199 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3200}
3201
Dan Gohmanabd17092009-06-24 14:49:00 +00003202const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3203 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003204 // ~umax(~x, ~y) == umin(x, y)
3205 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3206}
3207
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003208const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003209 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003210 // constant expression and then folding it back into a ConstantInt.
3211 // This is just a compile-time optimization.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003212 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003213}
3214
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003215const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3216 StructType *STy,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003217 unsigned FieldNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003218 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003219 // constant expression and then folding it back into a ConstantInt.
3220 // This is just a compile-time optimization.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003221 return getConstant(
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003222 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003223}
3224
Dan Gohmanaf752342009-07-07 17:06:11 +00003225const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf436bac2009-06-24 00:54:57 +00003226 // Don't attempt to do anything other than create a SCEVUnknown object
3227 // here. createSCEV only calls getUnknown after checking for all other
3228 // interesting possibilities, and any other code that calls getUnknown
3229 // is doing so in order to hide a value from SCEV canonicalization.
3230
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003231 FoldingSetNodeID ID;
3232 ID.AddInteger(scUnknown);
3233 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +00003234 void *IP = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00003235 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3236 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3237 "Stale SCEVUnknown in uniquing map!");
3238 return S;
3239 }
3240 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3241 FirstUnknown);
3242 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003243 UniqueSCEVs.InsertNode(S, IP);
3244 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +00003245}
3246
Chris Lattnerd934c702004-04-02 20:23:17 +00003247//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00003248// Basic SCEV Analysis and PHI Idiom Recognition Code
3249//
3250
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003251/// isSCEVable - Test if values of the given type are analyzable within
3252/// the SCEV framework. This primarily includes integer types, and it
3253/// can optionally include pointer types if the ScalarEvolution class
3254/// has access to target-specific information.
Chris Lattner229907c2011-07-18 04:54:35 +00003255bool ScalarEvolution::isSCEVable(Type *Ty) const {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003256 // Integers and pointers are always SCEVable.
Duncan Sands19d0b472010-02-16 11:11:14 +00003257 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003258}
3259
3260/// getTypeSizeInBits - Return the size in bits of the specified type,
3261/// for which isSCEVable must return true.
Chris Lattner229907c2011-07-18 04:54:35 +00003262uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003263 assert(isSCEVable(Ty) && "Type is not SCEVable!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003264 return getDataLayout().getTypeSizeInBits(Ty);
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003265}
3266
3267/// getEffectiveSCEVType - Return a type with the same bitwidth as
3268/// the given type and which represents how SCEV will treat the given
3269/// type, for which isSCEVable must return true. For pointer types,
3270/// this is the pointer-sized integer type.
Chris Lattner229907c2011-07-18 04:54:35 +00003271Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003272 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3273
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003274 if (Ty->isIntegerTy())
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003275 return Ty;
3276
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003277 // The only other support type is pointer.
Duncan Sands19d0b472010-02-16 11:11:14 +00003278 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003279 return getDataLayout().getIntPtrType(Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003280}
Chris Lattnerd934c702004-04-02 20:23:17 +00003281
Dan Gohmanaf752342009-07-07 17:06:11 +00003282const SCEV *ScalarEvolution::getCouldNotCompute() {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003283 return CouldNotCompute.get();
Dan Gohman31efa302009-04-18 17:58:19 +00003284}
3285
Sanjoy Das7d752672015-12-08 04:32:54 +00003286
3287bool ScalarEvolution::checkValidity(const SCEV *S) const {
Shuxin Yangefc4c012013-07-08 17:33:13 +00003288 // Helper class working with SCEVTraversal to figure out if a SCEV contains
3289 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
3290 // is set iff if find such SCEVUnknown.
3291 //
3292 struct FindInvalidSCEVUnknown {
3293 bool FindOne;
3294 FindInvalidSCEVUnknown() { FindOne = false; }
3295 bool follow(const SCEV *S) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00003296 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Shuxin Yangefc4c012013-07-08 17:33:13 +00003297 case scConstant:
3298 return false;
3299 case scUnknown:
Shuxin Yang23773b32013-07-12 07:25:38 +00003300 if (!cast<SCEVUnknown>(S)->getValue())
Shuxin Yangefc4c012013-07-08 17:33:13 +00003301 FindOne = true;
3302 return false;
3303 default:
3304 return true;
3305 }
3306 }
3307 bool isDone() const { return FindOne; }
3308 };
Shuxin Yangefc4c012013-07-08 17:33:13 +00003309
Shuxin Yangefc4c012013-07-08 17:33:13 +00003310 FindInvalidSCEVUnknown F;
3311 SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
3312 ST.visitAll(S);
3313
3314 return !F.FindOne;
3315}
3316
Wei Mia49559b2016-02-04 01:27:38 +00003317namespace {
3318// Helper class working with SCEVTraversal to figure out if a SCEV contains
3319// a sub SCEV of scAddRecExpr type. FindInvalidSCEVUnknown::FoundOne is set
3320// iff if such sub scAddRecExpr type SCEV is found.
3321struct FindAddRecurrence {
3322 bool FoundOne;
3323 FindAddRecurrence() : FoundOne(false) {}
3324
3325 bool follow(const SCEV *S) {
3326 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
3327 case scAddRecExpr:
3328 FoundOne = true;
3329 case scConstant:
3330 case scUnknown:
3331 case scCouldNotCompute:
3332 return false;
3333 default:
3334 return true;
3335 }
3336 }
3337 bool isDone() const { return FoundOne; }
3338};
3339}
3340
3341bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3342 HasRecMapType::iterator I = HasRecMap.find_as(S);
3343 if (I != HasRecMap.end())
3344 return I->second;
3345
3346 FindAddRecurrence F;
3347 SCEVTraversal<FindAddRecurrence> ST(F);
3348 ST.visitAll(S);
3349 HasRecMap.insert(std::make_pair(S, F.FoundOne));
3350 return F.FoundOne;
3351}
3352
3353/// getSCEVValues - Return the Value set from S.
3354SetVector<Value *> *ScalarEvolution::getSCEVValues(const SCEV *S) {
3355 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3356 if (SI == ExprValueMap.end())
3357 return nullptr;
3358#ifndef NDEBUG
3359 if (VerifySCEVMap) {
3360 // Check there is no dangling Value in the set returned.
3361 for (const auto &VE : SI->second)
3362 assert(ValueExprMap.count(VE));
3363 }
3364#endif
3365 return &SI->second;
3366}
3367
3368/// eraseValueFromMap - Erase Value from ValueExprMap and ExprValueMap.
3369/// If ValueExprMap.erase(V) is not used together with forgetMemoizedResults(S),
3370/// eraseValueFromMap should be used instead to ensure whenever V->S is removed
3371/// from ValueExprMap, V is also removed from the set of ExprValueMap[S].
3372void ScalarEvolution::eraseValueFromMap(Value *V) {
3373 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3374 if (I != ValueExprMap.end()) {
3375 const SCEV *S = I->second;
3376 SetVector<Value *> *SV = getSCEVValues(S);
3377 // Remove V from the set of ExprValueMap[S]
3378 if (SV)
3379 SV->remove(V);
3380 ValueExprMap.erase(V);
3381 }
3382}
3383
Chris Lattnerd934c702004-04-02 20:23:17 +00003384/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
3385/// expression and create a new one.
Dan Gohmanaf752342009-07-07 17:06:11 +00003386const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003387 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattnerd934c702004-04-02 20:23:17 +00003388
Jingyue Wu42f1d672015-07-28 18:22:40 +00003389 const SCEV *S = getExistingSCEV(V);
3390 if (S == nullptr) {
3391 S = createSCEV(V);
Wei Mia49559b2016-02-04 01:27:38 +00003392 // During PHI resolution, it is possible to create two SCEVs for the same
3393 // V, so it is needed to double check whether V->S is inserted into
3394 // ValueExprMap before insert S->V into ExprValueMap.
3395 std::pair<ValueExprMapType::iterator, bool> Pair =
3396 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
3397 if (Pair.second)
3398 ExprValueMap[S].insert(V);
Jingyue Wu42f1d672015-07-28 18:22:40 +00003399 }
3400 return S;
3401}
3402
3403const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3404 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3405
Shuxin Yangefc4c012013-07-08 17:33:13 +00003406 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3407 if (I != ValueExprMap.end()) {
3408 const SCEV *S = I->second;
Shuxin Yang23773b32013-07-12 07:25:38 +00003409 if (checkValidity(S))
Shuxin Yangefc4c012013-07-08 17:33:13 +00003410 return S;
Wei Mia49559b2016-02-04 01:27:38 +00003411 forgetMemoizedResults(S);
Jingyue Wu42f1d672015-07-28 18:22:40 +00003412 ValueExprMap.erase(I);
Shuxin Yangefc4c012013-07-08 17:33:13 +00003413 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003414 return nullptr;
Chris Lattnerd934c702004-04-02 20:23:17 +00003415}
3416
Dan Gohman0a40ad92009-04-16 03:18:22 +00003417/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3418///
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003419const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3420 SCEV::NoWrapFlags Flags) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003421 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson53a52212009-07-13 04:09:18 +00003422 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003423 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003424
Chris Lattner229907c2011-07-18 04:54:35 +00003425 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003426 Ty = getEffectiveSCEVType(Ty);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003427 return getMulExpr(
3428 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003429}
3430
3431/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanaf752342009-07-07 17:06:11 +00003432const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003433 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson542619e2009-07-13 20:58:05 +00003434 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003435 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003436
Chris Lattner229907c2011-07-18 04:54:35 +00003437 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003438 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003439 const SCEV *AllOnes =
Owen Anderson5a1acd92009-07-31 20:28:14 +00003440 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003441 return getMinusSCEV(AllOnes, V);
3442}
3443
Andrew Trick8b55b732011-03-14 16:50:06 +00003444/// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
Chris Lattnerfc877522011-01-09 22:26:35 +00003445const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00003446 SCEV::NoWrapFlags Flags) {
Dan Gohman46f00a22010-07-20 16:53:00 +00003447 // Fast path: X - X --> 0.
3448 if (LHS == RHS)
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003449 return getZero(LHS->getType());
Dan Gohman46f00a22010-07-20 16:53:00 +00003450
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003451 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3452 // makes it so that we cannot make much use of NUW.
3453 auto AddFlags = SCEV::FlagAnyWrap;
3454 const bool RHSIsNotMinSigned =
3455 !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3456 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3457 // Let M be the minimum representable signed value. Then (-1)*RHS
3458 // signed-wraps if and only if RHS is M. That can happen even for
3459 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3460 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3461 // (-1)*RHS, we need to prove that RHS != M.
3462 //
3463 // If LHS is non-negative and we know that LHS - RHS does not
3464 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3465 // either by proving that RHS > M or that LHS >= 0.
3466 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3467 AddFlags = SCEV::FlagNSW;
3468 }
3469 }
3470
3471 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3472 // RHS is NSW and LHS >= 0.
3473 //
3474 // The difficulty here is that the NSW flag may have been proven
3475 // relative to a loop that is to be found in a recurrence in LHS and
3476 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3477 // larger scope than intended.
3478 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3479
3480 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003481}
3482
3483/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
3484/// input value to the specified type. If the type must be extended, it is zero
3485/// extended.
Dan Gohmanaf752342009-07-07 17:06:11 +00003486const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003487ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3488 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003489 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3490 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003491 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003492 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003493 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003494 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003495 return getTruncateExpr(V, Ty);
3496 return getZeroExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003497}
3498
3499/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
3500/// input value to the specified type. If the type must be extended, it is sign
3501/// extended.
Dan Gohmanaf752342009-07-07 17:06:11 +00003502const SCEV *
3503ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattner229907c2011-07-18 04:54:35 +00003504 Type *Ty) {
3505 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003506 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3507 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003508 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003509 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003510 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003511 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003512 return getTruncateExpr(V, Ty);
3513 return getSignExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003514}
3515
Dan Gohmane712a2f2009-05-13 03:46:30 +00003516/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
3517/// input value to the specified type. If the type must be extended, it is zero
3518/// extended. The conversion must not be narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003519const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003520ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3521 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003522 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3523 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003524 "Cannot noop or zero extend with non-integer arguments!");
3525 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3526 "getNoopOrZeroExtend cannot truncate!");
3527 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3528 return V; // No conversion
3529 return getZeroExtendExpr(V, Ty);
3530}
3531
3532/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
3533/// input value to the specified type. If the type must be extended, it is sign
3534/// extended. The conversion must not be narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003535const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003536ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3537 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003538 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3539 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003540 "Cannot noop or sign extend with non-integer arguments!");
3541 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3542 "getNoopOrSignExtend cannot truncate!");
3543 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3544 return V; // No conversion
3545 return getSignExtendExpr(V, Ty);
3546}
3547
Dan Gohman8db2edc2009-06-13 15:56:47 +00003548/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
3549/// the input value to the specified type. If the type must be extended,
3550/// it is extended with unspecified bits. The conversion must not be
3551/// narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003552const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003553ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3554 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003555 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3556 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman8db2edc2009-06-13 15:56:47 +00003557 "Cannot noop or any extend with non-integer arguments!");
3558 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3559 "getNoopOrAnyExtend cannot truncate!");
3560 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3561 return V; // No conversion
3562 return getAnyExtendExpr(V, Ty);
3563}
3564
Dan Gohmane712a2f2009-05-13 03:46:30 +00003565/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
3566/// input value to the specified type. The conversion must not be widening.
Dan Gohmanaf752342009-07-07 17:06:11 +00003567const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003568ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3569 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003570 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3571 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003572 "Cannot truncate or noop with non-integer arguments!");
3573 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3574 "getTruncateOrNoop cannot extend!");
3575 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3576 return V; // No conversion
3577 return getTruncateExpr(V, Ty);
3578}
3579
Dan Gohman96212b62009-06-22 00:31:57 +00003580/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
3581/// the types using zero-extension, and then perform a umax operation
3582/// with them.
Dan Gohmanabd17092009-06-24 14:49:00 +00003583const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3584 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003585 const SCEV *PromotedLHS = LHS;
3586 const SCEV *PromotedRHS = RHS;
Dan Gohman96212b62009-06-22 00:31:57 +00003587
3588 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3589 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3590 else
3591 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3592
3593 return getUMaxExpr(PromotedLHS, PromotedRHS);
3594}
3595
Dan Gohman2bc22302009-06-22 15:03:27 +00003596/// getUMinFromMismatchedTypes - Promote the operands to the wider of
3597/// the types using zero-extension, and then perform a umin operation
3598/// with them.
Dan Gohmanabd17092009-06-24 14:49:00 +00003599const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3600 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003601 const SCEV *PromotedLHS = LHS;
3602 const SCEV *PromotedRHS = RHS;
Dan Gohman2bc22302009-06-22 15:03:27 +00003603
3604 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3605 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3606 else
3607 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3608
3609 return getUMinExpr(PromotedLHS, PromotedRHS);
3610}
3611
Andrew Trick87716c92011-03-17 23:51:11 +00003612/// getPointerBase - Transitively follow the chain of pointer-type operands
3613/// until reaching a SCEV that does not have a single pointer operand. This
3614/// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
3615/// but corner cases do exist.
3616const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3617 // A pointer operand may evaluate to a nonpointer expression, such as null.
3618 if (!V->getType()->isPointerTy())
3619 return V;
3620
3621 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3622 return getPointerBase(Cast->getOperand());
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003623 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
Craig Topper9f008862014-04-15 04:59:12 +00003624 const SCEV *PtrOp = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003625 for (const SCEV *NAryOp : NAry->operands()) {
3626 if (NAryOp->getType()->isPointerTy()) {
Andrew Trick87716c92011-03-17 23:51:11 +00003627 // Cannot find the base of an expression with multiple pointer operands.
3628 if (PtrOp)
3629 return V;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003630 PtrOp = NAryOp;
Andrew Trick87716c92011-03-17 23:51:11 +00003631 }
3632 }
3633 if (!PtrOp)
3634 return V;
3635 return getPointerBase(PtrOp);
3636 }
3637 return V;
3638}
3639
Dan Gohman0b89dff2009-07-25 01:13:03 +00003640/// PushDefUseChildren - Push users of the given Instruction
3641/// onto the given Worklist.
3642static void
3643PushDefUseChildren(Instruction *I,
3644 SmallVectorImpl<Instruction *> &Worklist) {
3645 // Push the def-use children onto the Worklist stack.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003646 for (User *U : I->users())
3647 Worklist.push_back(cast<Instruction>(U));
Dan Gohman0b89dff2009-07-25 01:13:03 +00003648}
3649
3650/// ForgetSymbolicValue - This looks up computed SCEV values for all
3651/// instructions that depend on the given instruction and removes them from
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003652/// the ValueExprMapType map if they reference SymName. This is used during PHI
Dan Gohman0b89dff2009-07-25 01:13:03 +00003653/// resolution.
Dan Gohmance973df2009-06-24 04:48:43 +00003654void
Dan Gohmana9c205c2010-02-25 06:57:05 +00003655ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohman0b89dff2009-07-25 01:13:03 +00003656 SmallVector<Instruction *, 16> Worklist;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003657 PushDefUseChildren(PN, Worklist);
Chris Lattnerd934c702004-04-02 20:23:17 +00003658
Dan Gohman0b89dff2009-07-25 01:13:03 +00003659 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003660 Visited.insert(PN);
Dan Gohman0b89dff2009-07-25 01:13:03 +00003661 while (!Worklist.empty()) {
Dan Gohmana9c205c2010-02-25 06:57:05 +00003662 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00003663 if (!Visited.insert(I).second)
3664 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003665
Sanjoy Das63914592015-10-18 00:29:20 +00003666 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003667 if (It != ValueExprMap.end()) {
Dan Gohman761065e2010-11-17 02:44:44 +00003668 const SCEV *Old = It->second;
3669
Dan Gohman0b89dff2009-07-25 01:13:03 +00003670 // Short-circuit the def-use traversal if the symbolic name
3671 // ceases to appear in expressions.
Dan Gohman534749b2010-11-17 22:27:42 +00003672 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohman0b89dff2009-07-25 01:13:03 +00003673 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003674
Dan Gohman0b89dff2009-07-25 01:13:03 +00003675 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohmana9c205c2010-02-25 06:57:05 +00003676 // structure, it's a PHI that's in the progress of being computed
3677 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3678 // additional loop trip count information isn't going to change anything.
3679 // In the second case, createNodeForPHI will perform the necessary
3680 // updates on its own when it gets to that point. In the third, we do
3681 // want to forget the SCEVUnknown.
3682 if (!isa<PHINode>(I) ||
Dan Gohman761065e2010-11-17 02:44:44 +00003683 !isa<SCEVUnknown>(Old) ||
3684 (I != PN && Old == SymName)) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00003685 forgetMemoizedResults(Old);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003686 ValueExprMap.erase(It);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00003687 }
Dan Gohman0b89dff2009-07-25 01:13:03 +00003688 }
3689
3690 PushDefUseChildren(I, Worklist);
3691 }
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003692}
Chris Lattnerd934c702004-04-02 20:23:17 +00003693
Benjamin Kramer83709b12015-11-16 09:01:28 +00003694namespace {
Silviu Barangaf91c8072015-10-30 15:02:28 +00003695class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3696public:
3697 static const SCEV *rewrite(const SCEV *Scev, const Loop *L,
3698 ScalarEvolution &SE) {
3699 SCEVInitRewriter Rewriter(L, SE);
3700 const SCEV *Result = Rewriter.visit(Scev);
3701 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3702 }
3703
3704 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3705 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3706
3707 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3708 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3709 Valid = false;
3710 return Expr;
3711 }
3712
3713 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3714 // Only allow AddRecExprs for this loop.
3715 if (Expr->getLoop() == L)
3716 return Expr->getStart();
3717 Valid = false;
3718 return Expr;
3719 }
3720
3721 bool isValid() { return Valid; }
3722
3723private:
3724 const Loop *L;
3725 bool Valid;
3726};
3727
3728class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3729public:
3730 static const SCEV *rewrite(const SCEV *Scev, const Loop *L,
3731 ScalarEvolution &SE) {
3732 SCEVShiftRewriter Rewriter(L, SE);
3733 const SCEV *Result = Rewriter.visit(Scev);
3734 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3735 }
3736
3737 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3738 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3739
3740 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3741 // Only allow AddRecExprs for this loop.
3742 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3743 Valid = false;
3744 return Expr;
3745 }
3746
3747 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3748 if (Expr->getLoop() == L && Expr->isAffine())
3749 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3750 Valid = false;
3751 return Expr;
3752 }
3753 bool isValid() { return Valid; }
3754
3755private:
3756 const Loop *L;
3757 bool Valid;
3758};
Benjamin Kramer83709b12015-11-16 09:01:28 +00003759} // end anonymous namespace
Silviu Barangaf91c8072015-10-30 15:02:28 +00003760
Sanjoy Das55015d22015-10-02 23:09:44 +00003761const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
3762 const Loop *L = LI.getLoopFor(PN->getParent());
3763 if (!L || L->getHeader() != PN->getParent())
3764 return nullptr;
3765
3766 // The loop may have multiple entrances or multiple exits; we can analyze
3767 // this phi as an addrec if it has a unique entry value and a unique
3768 // backedge value.
3769 Value *BEValueV = nullptr, *StartValueV = nullptr;
3770 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3771 Value *V = PN->getIncomingValue(i);
3772 if (L->contains(PN->getIncomingBlock(i))) {
3773 if (!BEValueV) {
3774 BEValueV = V;
3775 } else if (BEValueV != V) {
3776 BEValueV = nullptr;
3777 break;
3778 }
3779 } else if (!StartValueV) {
3780 StartValueV = V;
3781 } else if (StartValueV != V) {
3782 StartValueV = nullptr;
3783 break;
3784 }
3785 }
3786 if (BEValueV && StartValueV) {
3787 // While we are analyzing this PHI node, handle its value symbolically.
3788 const SCEV *SymbolicName = getUnknown(PN);
3789 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
3790 "PHI node already processed?");
3791 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
3792
3793 // Using this symbolic name for the PHI, analyze the value coming around
3794 // the back-edge.
3795 const SCEV *BEValue = getSCEV(BEValueV);
3796
3797 // NOTE: If BEValue is loop invariant, we know that the PHI node just
3798 // has a special value for the first iteration of the loop.
3799
3800 // If the value coming around the backedge is an add with the symbolic
3801 // value we just inserted, then we found a simple induction variable!
3802 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
3803 // If there is a single occurrence of the symbolic value, replace it
3804 // with a recurrence.
3805 unsigned FoundIndex = Add->getNumOperands();
3806 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3807 if (Add->getOperand(i) == SymbolicName)
3808 if (FoundIndex == e) {
3809 FoundIndex = i;
Dan Gohman6635bb22010-04-12 07:49:36 +00003810 break;
3811 }
Sanjoy Das55015d22015-10-02 23:09:44 +00003812
3813 if (FoundIndex != Add->getNumOperands()) {
3814 // Create an add with everything but the specified operand.
3815 SmallVector<const SCEV *, 8> Ops;
3816 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3817 if (i != FoundIndex)
3818 Ops.push_back(Add->getOperand(i));
3819 const SCEV *Accum = getAddExpr(Ops);
3820
3821 // This is not a valid addrec if the step amount is varying each
3822 // loop iteration, but is not itself an addrec in this loop.
3823 if (isLoopInvariant(Accum, L) ||
3824 (isa<SCEVAddRecExpr>(Accum) &&
3825 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
3826 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
3827
3828 // If the increment doesn't overflow, then neither the addrec nor
3829 // the post-increment will overflow.
3830 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
3831 if (OBO->getOperand(0) == PN) {
3832 if (OBO->hasNoUnsignedWrap())
3833 Flags = setFlags(Flags, SCEV::FlagNUW);
3834 if (OBO->hasNoSignedWrap())
3835 Flags = setFlags(Flags, SCEV::FlagNSW);
3836 }
3837 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
3838 // If the increment is an inbounds GEP, then we know the address
3839 // space cannot be wrapped around. We cannot make any guarantee
3840 // about signed or unsigned overflow because pointers are
3841 // unsigned but we may have a negative index from the base
3842 // pointer. We can guarantee that no unsigned wrap occurs if the
3843 // indices form a positive value.
3844 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
3845 Flags = setFlags(Flags, SCEV::FlagNW);
3846
3847 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
3848 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
3849 Flags = setFlags(Flags, SCEV::FlagNUW);
3850 }
3851
3852 // We cannot transfer nuw and nsw flags from subtraction
3853 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
3854 // for instance.
3855 }
3856
3857 const SCEV *StartVal = getSCEV(StartValueV);
3858 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
3859
3860 // Since the no-wrap flags are on the increment, they apply to the
3861 // post-incremented value as well.
3862 if (isLoopInvariant(Accum, L))
3863 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
3864
3865 // Okay, for the entire analysis of this edge we assumed the PHI
3866 // to be symbolic. We now need to go back and purge all of the
3867 // entries for the scalars that use the symbolic expression.
3868 ForgetSymbolicName(PN, SymbolicName);
3869 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
3870 return PHISCEV;
Dan Gohman6635bb22010-04-12 07:49:36 +00003871 }
3872 }
Silviu Barangaf91c8072015-10-30 15:02:28 +00003873 } else {
Sanjoy Das55015d22015-10-02 23:09:44 +00003874 // Otherwise, this could be a loop like this:
3875 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
3876 // In this case, j = {1,+,1} and BEValue is j.
3877 // Because the other in-value of i (0) fits the evolution of BEValue
3878 // i really is an addrec evolution.
Silviu Barangaf91c8072015-10-30 15:02:28 +00003879 //
3880 // We can generalize this saying that i is the shifted value of BEValue
3881 // by one iteration:
3882 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
3883 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
3884 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
3885 if (Shifted != getCouldNotCompute() &&
3886 Start != getCouldNotCompute()) {
Sanjoy Das55015d22015-10-02 23:09:44 +00003887 const SCEV *StartVal = getSCEV(StartValueV);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003888 if (Start == StartVal) {
Sanjoy Das55015d22015-10-02 23:09:44 +00003889 // Okay, for the entire analysis of this edge we assumed the PHI
3890 // to be symbolic. We now need to go back and purge all of the
3891 // entries for the scalars that use the symbolic expression.
3892 ForgetSymbolicName(PN, SymbolicName);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003893 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
3894 return Shifted;
Chris Lattnerd934c702004-04-02 20:23:17 +00003895 }
Chris Lattnerd934c702004-04-02 20:23:17 +00003896 }
Dan Gohman6635bb22010-04-12 07:49:36 +00003897 }
Sanjoy Das55015d22015-10-02 23:09:44 +00003898 }
3899
3900 return nullptr;
3901}
3902
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003903// Checks if the SCEV S is available at BB. S is considered available at BB
3904// if S can be materialized at BB without introducing a fault.
3905static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
3906 BasicBlock *BB) {
3907 struct CheckAvailable {
3908 bool TraversalDone = false;
3909 bool Available = true;
Sanjoy Das55015d22015-10-02 23:09:44 +00003910
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003911 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
3912 BasicBlock *BB = nullptr;
3913 DominatorTree &DT;
Sanjoy Das55015d22015-10-02 23:09:44 +00003914
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003915 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
3916 : L(L), BB(BB), DT(DT) {}
Sanjoy Das55015d22015-10-02 23:09:44 +00003917
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003918 bool setUnavailable() {
3919 TraversalDone = true;
3920 Available = false;
Sanjoy Das55015d22015-10-02 23:09:44 +00003921 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00003922 }
3923
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003924 bool follow(const SCEV *S) {
3925 switch (S->getSCEVType()) {
3926 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
3927 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
Sanjoy Dasbb5ffc52015-10-24 05:37:28 +00003928 // These expressions are available if their operand(s) is/are.
3929 return true;
Sanjoy Das55015d22015-10-02 23:09:44 +00003930
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003931 case scAddRecExpr: {
3932 // We allow add recurrences that are on the loop BB is in, or some
3933 // outer loop. This guarantees availability because the value of the
3934 // add recurrence at BB is simply the "current" value of the induction
3935 // variable. We can relax this in the future; for instance an add
3936 // recurrence on a sibling dominating loop is also available at BB.
3937 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
3938 if (L && (ARLoop == L || ARLoop->contains(L)))
Sanjoy Das55015d22015-10-02 23:09:44 +00003939 return true;
3940
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003941 return setUnavailable();
Sanjoy Das55015d22015-10-02 23:09:44 +00003942 }
3943
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003944 case scUnknown: {
3945 // For SCEVUnknown, we check for simple dominance.
3946 const auto *SU = cast<SCEVUnknown>(S);
3947 Value *V = SU->getValue();
Sanjoy Das55015d22015-10-02 23:09:44 +00003948
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003949 if (isa<Argument>(V))
3950 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00003951
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003952 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
3953 return false;
3954
3955 return setUnavailable();
3956 }
3957
3958 case scUDivExpr:
3959 case scCouldNotCompute:
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003960 // We do not try to smart about these at all.
3961 return setUnavailable();
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003962 }
3963 llvm_unreachable("switch should be fully covered!");
3964 }
3965
3966 bool isDone() { return TraversalDone; }
Sanjoy Das55015d22015-10-02 23:09:44 +00003967 };
3968
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003969 CheckAvailable CA(L, BB, DT);
3970 SCEVTraversal<CheckAvailable> ST(CA);
3971
3972 ST.visitAll(S);
3973 return CA.Available;
3974}
3975
3976// Try to match a control flow sequence that branches out at BI and merges back
3977// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
3978// match.
3979static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
3980 Value *&C, Value *&LHS, Value *&RHS) {
3981 C = BI->getCondition();
3982
3983 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
3984 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
3985
3986 if (!LeftEdge.isSingleEdge())
3987 return false;
3988
3989 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
3990
3991 Use &LeftUse = Merge->getOperandUse(0);
3992 Use &RightUse = Merge->getOperandUse(1);
3993
3994 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
3995 LHS = LeftUse;
3996 RHS = RightUse;
3997 return true;
3998 }
3999
4000 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4001 LHS = RightUse;
4002 RHS = LeftUse;
4003 return true;
4004 }
4005
4006 return false;
4007}
4008
4009const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004010 if (PN->getNumIncomingValues() == 2) {
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004011 const Loop *L = LI.getLoopFor(PN->getParent());
4012
Sanjoy Das337d4782015-10-31 23:21:40 +00004013 // We don't want to break LCSSA, even in a SCEV expression tree.
4014 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4015 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4016 return nullptr;
4017
Sanjoy Das55015d22015-10-02 23:09:44 +00004018 // Try to match
4019 //
4020 // br %cond, label %left, label %right
4021 // left:
4022 // br label %merge
4023 // right:
4024 // br label %merge
4025 // merge:
4026 // V = phi [ %x, %left ], [ %y, %right ]
4027 //
4028 // as "select %cond, %x, %y"
4029
4030 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4031 assert(IDom && "At least the entry block should dominate PN");
4032
4033 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4034 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4035
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004036 if (BI && BI->isConditional() &&
4037 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4038 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4039 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
Sanjoy Das55015d22015-10-02 23:09:44 +00004040 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4041 }
4042
4043 return nullptr;
4044}
4045
4046const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4047 if (const SCEV *S = createAddRecFromPHI(PN))
4048 return S;
4049
4050 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4051 return S;
Misha Brukman01808ca2005-04-21 21:13:18 +00004052
Dan Gohmana9c205c2010-02-25 06:57:05 +00004053 // If the PHI has a single incoming value, follow that value, unless the
4054 // PHI's incoming blocks are in a different loop, in which case doing so
4055 // risks breaking LCSSA form. Instcombine would normally zap these, but
4056 // it doesn't have DominatorTree information, so it may miss cases.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004057 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004058 if (LI.replacementPreservesLCSSAForm(PN, V))
Dan Gohmana9c205c2010-02-25 06:57:05 +00004059 return getSCEV(V);
Duncan Sands39d771312010-11-17 20:49:12 +00004060
Chris Lattnerd934c702004-04-02 20:23:17 +00004061 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanc8e23622009-04-21 23:15:49 +00004062 return getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00004063}
4064
Sanjoy Das55015d22015-10-02 23:09:44 +00004065const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4066 Value *Cond,
4067 Value *TrueVal,
4068 Value *FalseVal) {
Mehdi Amini044cb342015-10-07 18:14:25 +00004069 // Handle "constant" branch or select. This can occur for instance when a
4070 // loop pass transforms an inner loop and moves on to process the outer loop.
4071 if (auto *CI = dyn_cast<ConstantInt>(Cond))
4072 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4073
Sanjoy Dasd0671342015-10-02 19:39:59 +00004074 // Try to match some simple smax or umax patterns.
4075 auto *ICI = dyn_cast<ICmpInst>(Cond);
4076 if (!ICI)
4077 return getUnknown(I);
4078
4079 Value *LHS = ICI->getOperand(0);
4080 Value *RHS = ICI->getOperand(1);
4081
4082 switch (ICI->getPredicate()) {
4083 case ICmpInst::ICMP_SLT:
4084 case ICmpInst::ICMP_SLE:
4085 std::swap(LHS, RHS);
4086 // fall through
4087 case ICmpInst::ICMP_SGT:
4088 case ICmpInst::ICMP_SGE:
4089 // a >s b ? a+x : b+x -> smax(a, b)+x
4090 // a >s b ? b+x : a+x -> smin(a, b)+x
4091 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4092 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4093 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4094 const SCEV *LA = getSCEV(TrueVal);
4095 const SCEV *RA = getSCEV(FalseVal);
4096 const SCEV *LDiff = getMinusSCEV(LA, LS);
4097 const SCEV *RDiff = getMinusSCEV(RA, RS);
4098 if (LDiff == RDiff)
4099 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4100 LDiff = getMinusSCEV(LA, RS);
4101 RDiff = getMinusSCEV(RA, LS);
4102 if (LDiff == RDiff)
4103 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4104 }
4105 break;
4106 case ICmpInst::ICMP_ULT:
4107 case ICmpInst::ICMP_ULE:
4108 std::swap(LHS, RHS);
4109 // fall through
4110 case ICmpInst::ICMP_UGT:
4111 case ICmpInst::ICMP_UGE:
4112 // a >u b ? a+x : b+x -> umax(a, b)+x
4113 // a >u b ? b+x : a+x -> umin(a, b)+x
4114 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4115 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4116 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4117 const SCEV *LA = getSCEV(TrueVal);
4118 const SCEV *RA = getSCEV(FalseVal);
4119 const SCEV *LDiff = getMinusSCEV(LA, LS);
4120 const SCEV *RDiff = getMinusSCEV(RA, RS);
4121 if (LDiff == RDiff)
4122 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4123 LDiff = getMinusSCEV(LA, RS);
4124 RDiff = getMinusSCEV(RA, LS);
4125 if (LDiff == RDiff)
4126 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4127 }
4128 break;
4129 case ICmpInst::ICMP_NE:
4130 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4131 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4132 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4133 const SCEV *One = getOne(I->getType());
4134 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4135 const SCEV *LA = getSCEV(TrueVal);
4136 const SCEV *RA = getSCEV(FalseVal);
4137 const SCEV *LDiff = getMinusSCEV(LA, LS);
4138 const SCEV *RDiff = getMinusSCEV(RA, One);
4139 if (LDiff == RDiff)
4140 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4141 }
4142 break;
4143 case ICmpInst::ICMP_EQ:
4144 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4145 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4146 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4147 const SCEV *One = getOne(I->getType());
4148 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4149 const SCEV *LA = getSCEV(TrueVal);
4150 const SCEV *RA = getSCEV(FalseVal);
4151 const SCEV *LDiff = getMinusSCEV(LA, One);
4152 const SCEV *RDiff = getMinusSCEV(RA, LS);
4153 if (LDiff == RDiff)
4154 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4155 }
4156 break;
4157 default:
4158 break;
4159 }
4160
4161 return getUnknown(I);
4162}
4163
Dan Gohmanee750d12009-05-08 20:26:55 +00004164/// createNodeForGEP - Expand GEP instructions into add and multiply
4165/// operations. This allows them to be analyzed by regular SCEV code.
4166///
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004167const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman30f24fe2009-05-09 00:14:52 +00004168 // Don't attempt to analyze GEPs over unsized objects.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004169 if (!GEP->getSourceElementType()->isSized())
Dan Gohman30f24fe2009-05-09 00:14:52 +00004170 return getUnknown(GEP);
Matt Arsenault4c265902013-09-27 22:38:23 +00004171
Jingyue Wu2982d4d2015-05-18 17:03:25 +00004172 SmallVector<const SCEV *, 4> IndexExprs;
4173 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4174 IndexExprs.push_back(getSCEV(*Index));
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004175 return getGEPExpr(GEP->getSourceElementType(),
4176 getSCEV(GEP->getPointerOperand()),
4177 IndexExprs, GEP->isInBounds());
Dan Gohmanee750d12009-05-08 20:26:55 +00004178}
4179
Nick Lewycky3783b462007-11-22 07:59:40 +00004180/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
4181/// guaranteed to end in (at every loop iteration). It is, at the same time,
4182/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
4183/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004184uint32_t
Dan Gohmanaf752342009-07-07 17:06:11 +00004185ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmana30370b2009-05-04 22:02:23 +00004186 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004187 return C->getAPInt().countTrailingZeros();
Chris Lattner49b090e2006-12-12 02:26:09 +00004188
Dan Gohmana30370b2009-05-04 22:02:23 +00004189 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanc702fc02009-06-19 23:29:04 +00004190 return std::min(GetMinTrailingZeros(T->getOperand()),
4191 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky3783b462007-11-22 07:59:40 +00004192
Dan Gohmana30370b2009-05-04 22:02:23 +00004193 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004194 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4195 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4196 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004197 }
4198
Dan Gohmana30370b2009-05-04 22:02:23 +00004199 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004200 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4201 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4202 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004203 }
4204
Dan Gohmana30370b2009-05-04 22:02:23 +00004205 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004206 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004207 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004208 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004209 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004210 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004211 }
4212
Dan Gohmana30370b2009-05-04 22:02:23 +00004213 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004214 // The result is the sum of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004215 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4216 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky3783b462007-11-22 07:59:40 +00004217 for (unsigned i = 1, e = M->getNumOperands();
4218 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004219 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky3783b462007-11-22 07:59:40 +00004220 BitWidth);
4221 return SumOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004222 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004223
Dan Gohmana30370b2009-05-04 22:02:23 +00004224 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004225 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004226 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004227 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004228 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004229 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004230 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004231
Dan Gohmana30370b2009-05-04 22:02:23 +00004232 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004233 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004234 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004235 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004236 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004237 return MinOpRes;
4238 }
4239
Dan Gohmana30370b2009-05-04 22:02:23 +00004240 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004241 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004242 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004243 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004244 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004245 return MinOpRes;
4246 }
4247
Dan Gohmanc702fc02009-06-19 23:29:04 +00004248 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4249 // For a SCEVUnknown, ask ValueTracking.
4250 unsigned BitWidth = getTypeSizeInBits(U->getType());
Dan Gohmanc702fc02009-06-19 23:29:04 +00004251 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004252 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
4253 nullptr, &DT);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004254 return Zeros.countTrailingOnes();
4255 }
4256
4257 // SCEVUDivExpr
Nick Lewycky3783b462007-11-22 07:59:40 +00004258 return 0;
Chris Lattner49b090e2006-12-12 02:26:09 +00004259}
Chris Lattnerd934c702004-04-02 20:23:17 +00004260
Sanjoy Das1f05c512014-10-10 21:22:34 +00004261/// GetRangeFromMetadata - Helper method to assign a range to V from
4262/// metadata present in the IR.
4263static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004264 if (Instruction *I = dyn_cast<Instruction>(V))
4265 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4266 return getConstantRangeFromMetadata(*MD);
Sanjoy Das1f05c512014-10-10 21:22:34 +00004267
4268 return None;
4269}
4270
Sanjoy Das91b54772015-03-09 21:43:43 +00004271/// getRange - Determine the range for a particular SCEV. If SignHint is
4272/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4273/// with a "cleaner" unsigned (resp. signed) representation.
Dan Gohmane65c9172009-07-13 21:35:55 +00004274///
4275ConstantRange
Sanjoy Das91b54772015-03-09 21:43:43 +00004276ScalarEvolution::getRange(const SCEV *S,
4277 ScalarEvolution::RangeSignHint SignHint) {
4278 DenseMap<const SCEV *, ConstantRange> &Cache =
4279 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4280 : SignedRanges;
4281
Dan Gohman761065e2010-11-17 02:44:44 +00004282 // See if we've computed this range already.
Sanjoy Das91b54772015-03-09 21:43:43 +00004283 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4284 if (I != Cache.end())
Dan Gohman761065e2010-11-17 02:44:44 +00004285 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00004286
4287 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004288 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
Dan Gohmanc702fc02009-06-19 23:29:04 +00004289
Dan Gohman85be4332010-01-26 19:19:05 +00004290 unsigned BitWidth = getTypeSizeInBits(S->getType());
4291 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4292
Sanjoy Das91b54772015-03-09 21:43:43 +00004293 // If the value has known zeros, the maximum value will have those known zeros
4294 // as well.
Dan Gohman85be4332010-01-26 19:19:05 +00004295 uint32_t TZ = GetMinTrailingZeros(S);
Sanjoy Das91b54772015-03-09 21:43:43 +00004296 if (TZ != 0) {
4297 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4298 ConservativeResult =
4299 ConstantRange(APInt::getMinValue(BitWidth),
4300 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4301 else
4302 ConservativeResult = ConstantRange(
4303 APInt::getSignedMinValue(BitWidth),
4304 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4305 }
Dan Gohman85be4332010-01-26 19:19:05 +00004306
Dan Gohmane65c9172009-07-13 21:35:55 +00004307 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004308 ConstantRange X = getRange(Add->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004309 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004310 X = X.add(getRange(Add->getOperand(i), SignHint));
4311 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004312 }
4313
4314 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004315 ConstantRange X = getRange(Mul->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004316 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004317 X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4318 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004319 }
4320
4321 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004322 ConstantRange X = getRange(SMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004323 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004324 X = X.smax(getRange(SMax->getOperand(i), SignHint));
4325 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004326 }
4327
4328 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004329 ConstantRange X = getRange(UMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004330 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004331 X = X.umax(getRange(UMax->getOperand(i), SignHint));
4332 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004333 }
4334
4335 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004336 ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4337 ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4338 return setRange(UDiv, SignHint,
4339 ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004340 }
4341
4342 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004343 ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4344 return setRange(ZExt, SignHint,
4345 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004346 }
4347
4348 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004349 ConstantRange X = getRange(SExt->getOperand(), SignHint);
4350 return setRange(SExt, SignHint,
4351 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004352 }
4353
4354 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004355 ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4356 return setRange(Trunc, SignHint,
4357 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004358 }
4359
Dan Gohmane65c9172009-07-13 21:35:55 +00004360 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004361 // If there's no unsigned wrap, the value will never be less than its
4362 // initial value.
Andrew Trick8b55b732011-03-14 16:50:06 +00004363 if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
Dan Gohman51ad99d2010-01-21 02:09:26 +00004364 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanebbd05f2010-04-12 23:08:18 +00004365 if (!C->getValue()->isZero())
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004366 ConservativeResult = ConservativeResult.intersectWith(
4367 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004368
Dan Gohman51ad99d2010-01-21 02:09:26 +00004369 // If there's no signed wrap, and all the operands have the same sign or
4370 // zero, the value won't ever change sign.
Andrew Trick8b55b732011-03-14 16:50:06 +00004371 if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004372 bool AllNonNeg = true;
4373 bool AllNonPos = true;
4374 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4375 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4376 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4377 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004378 if (AllNonNeg)
Dan Gohman51aaf022010-01-26 04:40:18 +00004379 ConservativeResult = ConservativeResult.intersectWith(
4380 ConstantRange(APInt(BitWidth, 0),
4381 APInt::getSignedMinValue(BitWidth)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004382 else if (AllNonPos)
Dan Gohman51aaf022010-01-26 04:40:18 +00004383 ConservativeResult = ConservativeResult.intersectWith(
4384 ConstantRange(APInt::getSignedMinValue(BitWidth),
4385 APInt(BitWidth, 1)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004386 }
Dan Gohmane65c9172009-07-13 21:35:55 +00004387
4388 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00004389 if (AddRec->isAffine()) {
Chris Lattner229907c2011-07-18 04:54:35 +00004390 Type *Ty = AddRec->getType();
Dan Gohmane65c9172009-07-13 21:35:55 +00004391 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00004392 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4393 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004394
4395 // Check for overflow. This must be done with ConstantRange arithmetic
4396 // because we could be called from within the ScalarEvolution overflow
4397 // checking code.
4398
Dan Gohmane65c9172009-07-13 21:35:55 +00004399 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
Sanjoy Das91b54772015-03-09 21:43:43 +00004400 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4401 ConstantRange ZExtMaxBECountRange =
4402 MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1);
Dan Gohmane65c9172009-07-13 21:35:55 +00004403
4404 const SCEV *Start = AddRec->getStart();
Dan Gohmanf76210e2010-04-12 07:39:33 +00004405 const SCEV *Step = AddRec->getStepRecurrence(*this);
Sanjoy Das91b54772015-03-09 21:43:43 +00004406 ConstantRange StepSRange = getSignedRange(Step);
4407 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1);
Dan Gohmane65c9172009-07-13 21:35:55 +00004408
Sanjoy Das91b54772015-03-09 21:43:43 +00004409 ConstantRange StartURange = getUnsignedRange(Start);
4410 ConstantRange EndURange =
4411 StartURange.add(MaxBECountRange.multiply(StepSRange));
Dan Gohmanf76210e2010-04-12 07:39:33 +00004412
Sanjoy Das91b54772015-03-09 21:43:43 +00004413 // Check for unsigned overflow.
4414 ConstantRange ZExtStartURange =
4415 StartURange.zextOrTrunc(BitWidth * 2 + 1);
4416 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1);
4417 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4418 ZExtEndURange) {
4419 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(),
4420 EndURange.getUnsignedMin());
4421 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(),
4422 EndURange.getUnsignedMax());
4423 bool IsFullRange = Min.isMinValue() && Max.isMaxValue();
4424 if (!IsFullRange)
4425 ConservativeResult =
4426 ConservativeResult.intersectWith(ConstantRange(Min, Max + 1));
4427 }
Dan Gohmanf76210e2010-04-12 07:39:33 +00004428
Sanjoy Das91b54772015-03-09 21:43:43 +00004429 ConstantRange StartSRange = getSignedRange(Start);
4430 ConstantRange EndSRange =
4431 StartSRange.add(MaxBECountRange.multiply(StepSRange));
4432
4433 // Check for signed overflow. This must be done with ConstantRange
4434 // arithmetic because we could be called from within the ScalarEvolution
4435 // overflow checking code.
4436 ConstantRange SExtStartSRange =
4437 StartSRange.sextOrTrunc(BitWidth * 2 + 1);
4438 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1);
4439 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4440 SExtEndSRange) {
4441 APInt Min = APIntOps::smin(StartSRange.getSignedMin(),
4442 EndSRange.getSignedMin());
4443 APInt Max = APIntOps::smax(StartSRange.getSignedMax(),
4444 EndSRange.getSignedMax());
4445 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue();
4446 if (!IsFullRange)
4447 ConservativeResult =
4448 ConservativeResult.intersectWith(ConstantRange(Min, Max + 1));
4449 }
Dan Gohmand261d272009-06-24 01:05:09 +00004450 }
Dan Gohmand261d272009-06-24 01:05:09 +00004451 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004452
Sanjoy Das91b54772015-03-09 21:43:43 +00004453 return setRange(AddRec, SignHint, ConservativeResult);
Dan Gohmand261d272009-06-24 01:05:09 +00004454 }
4455
Dan Gohmanc702fc02009-06-19 23:29:04 +00004456 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00004457 // Check if the IR explicitly contains !range metadata.
4458 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4459 if (MDRange.hasValue())
4460 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4461
Sanjoy Das91b54772015-03-09 21:43:43 +00004462 // Split here to avoid paying the compile-time cost of calling both
4463 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
4464 // if needed.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004465 const DataLayout &DL = getDataLayout();
Sanjoy Das91b54772015-03-09 21:43:43 +00004466 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4467 // For a SCEVUnknown, ask ValueTracking.
4468 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004469 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
Sanjoy Das91b54772015-03-09 21:43:43 +00004470 if (Ones != ~Zeros + 1)
4471 ConservativeResult =
4472 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4473 } else {
4474 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4475 "generalize as needed!");
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004476 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004477 if (NS > 1)
4478 ConservativeResult = ConservativeResult.intersectWith(
4479 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4480 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
Sanjoy Das91b54772015-03-09 21:43:43 +00004481 }
4482
4483 return setRange(U, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004484 }
4485
Sanjoy Das91b54772015-03-09 21:43:43 +00004486 return setRange(S, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004487}
4488
Jingyue Wu42f1d672015-07-28 18:22:40 +00004489SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004490 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004491 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4492
4493 // Return early if there are no flags to propagate to the SCEV.
4494 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4495 if (BinOp->hasNoUnsignedWrap())
4496 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4497 if (BinOp->hasNoSignedWrap())
4498 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
4499 if (Flags == SCEV::FlagAnyWrap) {
4500 return SCEV::FlagAnyWrap;
4501 }
4502
4503 // Here we check that BinOp is in the header of the innermost loop
4504 // containing BinOp, since we only deal with instructions in the loop
4505 // header. The actual loop we need to check later will come from an add
4506 // recurrence, but getting that requires computing the SCEV of the operands,
4507 // which can be expensive. This check we can do cheaply to rule out some
4508 // cases early.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004509 Loop *innermostContainingLoop = LI.getLoopFor(BinOp->getParent());
Jingyue Wu42f1d672015-07-28 18:22:40 +00004510 if (innermostContainingLoop == nullptr ||
4511 innermostContainingLoop->getHeader() != BinOp->getParent())
4512 return SCEV::FlagAnyWrap;
4513
4514 // Only proceed if we can prove that BinOp does not yield poison.
4515 if (!isKnownNotFullPoison(BinOp)) return SCEV::FlagAnyWrap;
4516
4517 // At this point we know that if V is executed, then it does not wrap
4518 // according to at least one of NSW or NUW. If V is not executed, then we do
4519 // not know if the calculation that V represents would wrap. Multiple
4520 // instructions can map to the same SCEV. If we apply NSW or NUW from V to
4521 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4522 // derived from other instructions that map to the same SCEV. We cannot make
4523 // that guarantee for cases where V is not executed. So we need to find the
4524 // loop that V is considered in relation to and prove that V is executed for
4525 // every iteration of that loop. That implies that the value that V
4526 // calculates does not wrap anywhere in the loop, so then we can apply the
4527 // flags to the SCEV.
4528 //
4529 // We check isLoopInvariant to disambiguate in case we are adding two
4530 // recurrences from different loops, so that we know which loop to prove
4531 // that V is executed in.
4532 for (int OpIndex = 0; OpIndex < 2; ++OpIndex) {
4533 const SCEV *Op = getSCEV(BinOp->getOperand(OpIndex));
4534 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
4535 const int OtherOpIndex = 1 - OpIndex;
4536 const SCEV *OtherOp = getSCEV(BinOp->getOperand(OtherOpIndex));
4537 if (isLoopInvariant(OtherOp, AddRec->getLoop()) &&
4538 isGuaranteedToExecuteForEveryIteration(BinOp, AddRec->getLoop()))
4539 return Flags;
4540 }
4541 }
4542 return SCEV::FlagAnyWrap;
4543}
4544
4545/// createSCEV - We know that there is no SCEV for the specified value. Analyze
4546/// the expression.
Chris Lattnerd934c702004-04-02 20:23:17 +00004547///
Dan Gohmanaf752342009-07-07 17:06:11 +00004548const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00004549 if (!isSCEVable(V->getType()))
Dan Gohmanc8e23622009-04-21 23:15:49 +00004550 return getUnknown(V);
Dan Gohman0a40ad92009-04-16 03:18:22 +00004551
Dan Gohman05e89732008-06-22 19:56:46 +00004552 unsigned Opcode = Instruction::UserOp1;
Dan Gohman69451a02010-03-09 23:46:50 +00004553 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman05e89732008-06-22 19:56:46 +00004554 Opcode = I->getOpcode();
Dan Gohman69451a02010-03-09 23:46:50 +00004555
4556 // Don't attempt to analyze instructions in blocks that aren't
4557 // reachable. Such instructions don't matter, and they aren't required
4558 // to obey basic rules for definitions dominating uses which this
4559 // analysis depends on.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004560 if (!DT.isReachableFromEntry(I->getParent()))
Dan Gohman69451a02010-03-09 23:46:50 +00004561 return getUnknown(V);
4562 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman05e89732008-06-22 19:56:46 +00004563 Opcode = CE->getOpcode();
Dan Gohmanf436bac2009-06-24 00:54:57 +00004564 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
4565 return getConstant(CI);
4566 else if (isa<ConstantPointerNull>(V))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00004567 return getZero(V->getType());
Dan Gohmanf161e06e2009-08-25 17:49:57 +00004568 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
4569 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman05e89732008-06-22 19:56:46 +00004570 else
Dan Gohmanc8e23622009-04-21 23:15:49 +00004571 return getUnknown(V);
Chris Lattnera3e0bb42007-04-02 05:41:38 +00004572
Dan Gohman80ca01c2009-07-17 20:47:02 +00004573 Operator *U = cast<Operator>(V);
Dan Gohman05e89732008-06-22 19:56:46 +00004574 switch (Opcode) {
Dan Gohmane5fb1032010-08-16 16:03:49 +00004575 case Instruction::Add: {
4576 // The simple thing to do would be to just call getSCEV on both operands
4577 // and call getAddExpr with the result. However if we're looking at a
4578 // bunch of things all added together, this can be quite inefficient,
4579 // because it leads to N-1 getAddExpr calls for N ultimate operands.
4580 // Instead, gather up all the operands and make a single getAddExpr call.
4581 // LLVM IR canonical form means we need only traverse the left operands.
4582 SmallVector<const SCEV *, 4> AddOps;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004583 for (Value *Op = U;; Op = U->getOperand(0)) {
4584 U = dyn_cast<Operator>(Op);
4585 unsigned Opcode = U ? U->getOpcode() : 0;
4586 if (!U || (Opcode != Instruction::Add && Opcode != Instruction::Sub)) {
4587 assert(Op != V && "V should be an add");
4588 AddOps.push_back(getSCEV(Op));
Dan Gohman47308d52010-08-31 22:53:17 +00004589 break;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004590 }
4591
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004592 if (auto *OpSCEV = getExistingSCEV(U)) {
Jingyue Wu42f1d672015-07-28 18:22:40 +00004593 AddOps.push_back(OpSCEV);
4594 break;
4595 }
4596
4597 // If a NUW or NSW flag can be applied to the SCEV for this
4598 // addition, then compute the SCEV for this addition by itself
4599 // with a separate call to getAddExpr. We need to do that
4600 // instead of pushing the operands of the addition onto AddOps,
4601 // since the flags are only known to apply to this particular
4602 // addition - they may not apply to other additions that can be
4603 // formed with operands from AddOps.
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004604 const SCEV *RHS = getSCEV(U->getOperand(1));
4605 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(U);
4606 if (Flags != SCEV::FlagAnyWrap) {
4607 const SCEV *LHS = getSCEV(U->getOperand(0));
4608 if (Opcode == Instruction::Sub)
4609 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
4610 else
4611 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
4612 break;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004613 }
4614
Dan Gohman47308d52010-08-31 22:53:17 +00004615 if (Opcode == Instruction::Sub)
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004616 AddOps.push_back(getNegativeSCEV(RHS));
Dan Gohman47308d52010-08-31 22:53:17 +00004617 else
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004618 AddOps.push_back(RHS);
Dan Gohmane5fb1032010-08-16 16:03:49 +00004619 }
Andrew Trickd25089f2011-11-29 02:16:38 +00004620 return getAddExpr(AddOps);
Dan Gohmane5fb1032010-08-16 16:03:49 +00004621 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004622
Dan Gohmane5fb1032010-08-16 16:03:49 +00004623 case Instruction::Mul: {
Dan Gohmane5fb1032010-08-16 16:03:49 +00004624 SmallVector<const SCEV *, 4> MulOps;
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004625 for (Value *Op = U;; Op = U->getOperand(0)) {
4626 U = dyn_cast<Operator>(Op);
4627 if (!U || U->getOpcode() != Instruction::Mul) {
4628 assert(Op != V && "V should be a mul");
4629 MulOps.push_back(getSCEV(Op));
4630 break;
4631 }
4632
4633 if (auto *OpSCEV = getExistingSCEV(U)) {
4634 MulOps.push_back(OpSCEV);
4635 break;
4636 }
4637
4638 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(U);
4639 if (Flags != SCEV::FlagAnyWrap) {
4640 MulOps.push_back(getMulExpr(getSCEV(U->getOperand(0)),
4641 getSCEV(U->getOperand(1)), Flags));
4642 break;
4643 }
4644
Dan Gohmane5fb1032010-08-16 16:03:49 +00004645 MulOps.push_back(getSCEV(U->getOperand(1)));
4646 }
Dan Gohmane5fb1032010-08-16 16:03:49 +00004647 return getMulExpr(MulOps);
4648 }
Dan Gohman05e89732008-06-22 19:56:46 +00004649 case Instruction::UDiv:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004650 return getUDivExpr(getSCEV(U->getOperand(0)),
4651 getSCEV(U->getOperand(1)));
Dan Gohman05e89732008-06-22 19:56:46 +00004652 case Instruction::Sub:
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004653 return getMinusSCEV(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)),
4654 getNoWrapFlagsFromUB(U));
Dan Gohman0ec05372009-04-21 02:26:00 +00004655 case Instruction::And:
4656 // For an expression like x&255 that merely masks off the high bits,
4657 // use zext(trunc(x)) as the SCEV expression.
4658 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmandf199482009-04-25 17:05:40 +00004659 if (CI->isNullValue())
4660 return getSCEV(U->getOperand(1));
Dan Gohman05c1d372009-04-27 01:41:10 +00004661 if (CI->isAllOnesValue())
4662 return getSCEV(U->getOperand(0));
Dan Gohman0ec05372009-04-21 02:26:00 +00004663 const APInt &A = CI->getValue();
Dan Gohman1ee696d2009-06-16 19:52:01 +00004664
4665 // Instcombine's ShrinkDemandedConstant may strip bits out of
4666 // constants, obscuring what would otherwise be a low-bits mask.
Jay Foada0653a32014-05-14 21:14:37 +00004667 // Use computeKnownBits to compute what ShrinkDemandedConstant
Dan Gohman1ee696d2009-06-16 19:52:01 +00004668 // knew about to reconstruct a low-bits mask value.
4669 unsigned LZ = A.countLeadingZeros();
Nick Lewycky31eaca52014-01-27 10:04:03 +00004670 unsigned TZ = A.countTrailingZeros();
Dan Gohman1ee696d2009-06-16 19:52:01 +00004671 unsigned BitWidth = A.getBitWidth();
Dan Gohman1ee696d2009-06-16 19:52:01 +00004672 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004673 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, getDataLayout(),
4674 0, &AC, nullptr, &DT);
Dan Gohman1ee696d2009-06-16 19:52:01 +00004675
Nick Lewycky31eaca52014-01-27 10:04:03 +00004676 APInt EffectiveMask =
4677 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
4678 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
4679 const SCEV *MulCount = getConstant(
4680 ConstantInt::get(getContext(), APInt::getOneBitSet(BitWidth, TZ)));
4681 return getMulExpr(
4682 getZeroExtendExpr(
4683 getTruncateExpr(
4684 getUDivExactExpr(getSCEV(U->getOperand(0)), MulCount),
4685 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
4686 U->getType()),
4687 MulCount);
4688 }
Dan Gohman0ec05372009-04-21 02:26:00 +00004689 }
4690 break;
Dan Gohman1ee696d2009-06-16 19:52:01 +00004691
Dan Gohman05e89732008-06-22 19:56:46 +00004692 case Instruction::Or:
4693 // If the RHS of the Or is a constant, we may have something like:
4694 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
4695 // optimizations will transparently handle this case.
4696 //
4697 // In order for this transformation to be safe, the LHS must be of the
4698 // form X*(2^n) and the Or constant must be less than 2^n.
4699 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00004700 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman05e89732008-06-22 19:56:46 +00004701 const APInt &CIVal = CI->getValue();
Dan Gohmanc702fc02009-06-19 23:29:04 +00004702 if (GetMinTrailingZeros(LHS) >=
Dan Gohman36bad002009-09-17 18:05:20 +00004703 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
4704 // Build a plain add SCEV.
4705 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
4706 // If the LHS of the add was an addrec and it has no-wrap flags,
4707 // transfer the no-wrap flags, since an or won't introduce a wrap.
4708 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
4709 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
Andrew Trick8b55b732011-03-14 16:50:06 +00004710 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
4711 OldAR->getNoWrapFlags());
Dan Gohman36bad002009-09-17 18:05:20 +00004712 }
4713 return S;
4714 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004715 }
Dan Gohman05e89732008-06-22 19:56:46 +00004716 break;
4717 case Instruction::Xor:
Dan Gohman05e89732008-06-22 19:56:46 +00004718 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004719 // If the RHS of the xor is a signbit, then this is just an add.
4720 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman05e89732008-06-22 19:56:46 +00004721 if (CI->getValue().isSignBit())
Dan Gohmanc8e23622009-04-21 23:15:49 +00004722 return getAddExpr(getSCEV(U->getOperand(0)),
4723 getSCEV(U->getOperand(1)));
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004724
4725 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmand277a1e2009-05-18 16:17:44 +00004726 if (CI->isAllOnesValue())
Dan Gohmanc8e23622009-04-21 23:15:49 +00004727 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman6350296e2009-05-18 16:29:04 +00004728
4729 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
4730 // This is a variant of the check for xor with -1, and it handles
4731 // the case where instcombine has trimmed non-demanded bits out
4732 // of an xor with -1.
4733 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
4734 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
4735 if (BO->getOpcode() == Instruction::And &&
4736 LCI->getValue() == CI->getValue())
4737 if (const SCEVZeroExtendExpr *Z =
Dan Gohmanb50f5a42009-06-17 01:22:39 +00004738 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Chris Lattner229907c2011-07-18 04:54:35 +00004739 Type *UTy = U->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00004740 const SCEV *Z0 = Z->getOperand();
Chris Lattner229907c2011-07-18 04:54:35 +00004741 Type *Z0Ty = Z0->getType();
Dan Gohmaneddf7712009-06-18 00:00:20 +00004742 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
4743
Dan Gohman8b0a4192010-03-01 17:49:51 +00004744 // If C is a low-bits mask, the zero extend is serving to
Dan Gohmaneddf7712009-06-18 00:00:20 +00004745 // mask off the high bits. Complement the operand and
4746 // re-apply the zext.
4747 if (APIntOps::isMask(Z0TySize, CI->getValue()))
4748 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
4749
4750 // If C is a single bit, it may be in the sign-bit position
4751 // before the zero-extend. In this case, represent the xor
4752 // using an add, which is equivalent, and re-apply the zext.
Jay Foad583abbc2010-12-07 08:25:19 +00004753 APInt Trunc = CI->getValue().trunc(Z0TySize);
4754 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
Dan Gohmaneddf7712009-06-18 00:00:20 +00004755 Trunc.isSignBit())
4756 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
4757 UTy);
Dan Gohmanb50f5a42009-06-17 01:22:39 +00004758 }
Dan Gohman05e89732008-06-22 19:56:46 +00004759 }
4760 break;
4761
4762 case Instruction::Shl:
4763 // Turn shift left of a constant amount into a multiply.
4764 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00004765 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00004766
4767 // If the shift count is not less than the bitwidth, the result of
4768 // the shift is undefined. Don't try to analyze it, because the
4769 // resolution chosen here may differ from the resolution chosen in
4770 // other parts of the compiler.
4771 if (SA->getValue().uge(BitWidth))
4772 break;
4773
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004774 // It is currently not resolved how to interpret NSW for left
4775 // shift by BitWidth - 1, so we avoid applying flags in that
4776 // case. Remove this check (or this comment) once the situation
4777 // is resolved. See
4778 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
4779 // and http://reviews.llvm.org/D8890 .
4780 auto Flags = SCEV::FlagAnyWrap;
4781 if (SA->getValue().ult(BitWidth - 1)) Flags = getNoWrapFlagsFromUB(U);
4782
Owen Andersonedb4a702009-07-24 23:12:02 +00004783 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00004784 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004785 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X), Flags);
Dan Gohman05e89732008-06-22 19:56:46 +00004786 }
4787 break;
4788
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004789 case Instruction::LShr:
Nick Lewycky52348302009-01-13 09:18:58 +00004790 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004791 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00004792 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00004793
4794 // If the shift count is not less than the bitwidth, the result of
4795 // the shift is undefined. Don't try to analyze it, because the
4796 // resolution chosen here may differ from the resolution chosen in
4797 // other parts of the compiler.
4798 if (SA->getValue().uge(BitWidth))
4799 break;
4800
Owen Andersonedb4a702009-07-24 23:12:02 +00004801 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00004802 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Dan Gohmanc8e23622009-04-21 23:15:49 +00004803 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004804 }
4805 break;
4806
Dan Gohman0ec05372009-04-21 02:26:00 +00004807 case Instruction::AShr:
4808 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
4809 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanacd700a2010-04-22 01:35:11 +00004810 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman0ec05372009-04-21 02:26:00 +00004811 if (L->getOpcode() == Instruction::Shl &&
4812 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00004813 uint64_t BitWidth = getTypeSizeInBits(U->getType());
4814
4815 // If the shift count is not less than the bitwidth, the result of
4816 // the shift is undefined. Don't try to analyze it, because the
4817 // resolution chosen here may differ from the resolution chosen in
4818 // other parts of the compiler.
4819 if (CI->getValue().uge(BitWidth))
4820 break;
4821
Dan Gohmandf199482009-04-25 17:05:40 +00004822 uint64_t Amt = BitWidth - CI->getZExtValue();
4823 if (Amt == BitWidth)
4824 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman0ec05372009-04-21 02:26:00 +00004825 return
Dan Gohmanc8e23622009-04-21 23:15:49 +00004826 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanacd700a2010-04-22 01:35:11 +00004827 IntegerType::get(getContext(),
4828 Amt)),
4829 U->getType());
Dan Gohman0ec05372009-04-21 02:26:00 +00004830 }
4831 break;
4832
Dan Gohman05e89732008-06-22 19:56:46 +00004833 case Instruction::Trunc:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004834 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00004835
4836 case Instruction::ZExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004837 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00004838
4839 case Instruction::SExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004840 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00004841
4842 case Instruction::BitCast:
4843 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00004844 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman05e89732008-06-22 19:56:46 +00004845 return getSCEV(U->getOperand(0));
4846 break;
4847
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00004848 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
4849 // lead to pointer expressions which cannot safely be expanded to GEPs,
4850 // because ScalarEvolution doesn't respect the GEP aliasing rules when
4851 // simplifying integer expressions.
Dan Gohman0a40ad92009-04-16 03:18:22 +00004852
Dan Gohmanee750d12009-05-08 20:26:55 +00004853 case Instruction::GetElementPtr:
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004854 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman0a40ad92009-04-16 03:18:22 +00004855
Dan Gohman05e89732008-06-22 19:56:46 +00004856 case Instruction::PHI:
4857 return createNodeForPHI(cast<PHINode>(U));
4858
4859 case Instruction::Select:
Sanjoy Dasd0671342015-10-02 19:39:59 +00004860 // U can also be a select constant expr, which let fall through. Since
4861 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
4862 // constant expressions cannot have instructions as operands, we'd have
4863 // returned getUnknown for a select constant expressions anyway.
4864 if (isa<Instruction>(U))
Sanjoy Das55015d22015-10-02 23:09:44 +00004865 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
4866 U->getOperand(1), U->getOperand(2));
Dan Gohman05e89732008-06-22 19:56:46 +00004867
4868 default: // We cannot analyze this expression.
4869 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00004870 }
4871
Dan Gohmanc8e23622009-04-21 23:15:49 +00004872 return getUnknown(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00004873}
4874
4875
4876
4877//===----------------------------------------------------------------------===//
4878// Iteration Count Computation Code
4879//
4880
Chandler Carruth6666c272014-10-11 00:12:11 +00004881unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
4882 if (BasicBlock *ExitingBB = L->getExitingBlock())
4883 return getSmallConstantTripCount(L, ExitingBB);
4884
4885 // No trip count information for multiple exits.
4886 return 0;
4887}
4888
Andrew Trick2b6860f2011-08-11 23:36:16 +00004889/// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
Andrew Tricke81211f2012-01-11 06:52:55 +00004890/// normal unsigned value. Returns 0 if the trip count is unknown or not
4891/// constant. Will also return 0 if the maximum trip count is very large (>=
4892/// 2^32).
4893///
4894/// This "trip count" assumes that control exits via ExitingBlock. More
4895/// precisely, it is the number of times that control may reach ExitingBlock
4896/// before taking the branch. For loops with multiple exits, it may not be the
4897/// number times that the loop header executes because the loop may exit
4898/// prematurely via another branch.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004899unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
4900 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00004901 assert(ExitingBlock && "Must pass a non-null exiting block!");
4902 assert(L->isLoopExiting(ExitingBlock) &&
4903 "Exiting block must actually branch out of the loop!");
Andrew Trick2b6860f2011-08-11 23:36:16 +00004904 const SCEVConstant *ExitCount =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004905 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
Andrew Trick2b6860f2011-08-11 23:36:16 +00004906 if (!ExitCount)
4907 return 0;
4908
4909 ConstantInt *ExitConst = ExitCount->getValue();
4910
4911 // Guard against huge trip counts.
4912 if (ExitConst->getValue().getActiveBits() > 32)
4913 return 0;
4914
4915 // In case of integer overflow, this returns 0, which is correct.
4916 return ((unsigned)ExitConst->getZExtValue()) + 1;
4917}
4918
Chandler Carruth6666c272014-10-11 00:12:11 +00004919unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
4920 if (BasicBlock *ExitingBB = L->getExitingBlock())
4921 return getSmallConstantTripMultiple(L, ExitingBB);
4922
4923 // No trip multiple information for multiple exits.
4924 return 0;
4925}
4926
Andrew Trick2b6860f2011-08-11 23:36:16 +00004927/// getSmallConstantTripMultiple - Returns the largest constant divisor of the
4928/// trip count of this loop as a normal unsigned value, if possible. This
4929/// means that the actual trip count is always a multiple of the returned
4930/// value (don't forget the trip count could very well be zero as well!).
4931///
4932/// Returns 1 if the trip count is unknown or not guaranteed to be the
4933/// multiple of a constant (which is also the case if the trip count is simply
4934/// constant, use getSmallConstantTripCount for that case), Will also return 1
4935/// if the trip count is very large (>= 2^32).
Andrew Tricke81211f2012-01-11 06:52:55 +00004936///
4937/// As explained in the comments for getSmallConstantTripCount, this assumes
4938/// that control exits the loop via ExitingBlock.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004939unsigned
4940ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
4941 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00004942 assert(ExitingBlock && "Must pass a non-null exiting block!");
4943 assert(L->isLoopExiting(ExitingBlock) &&
4944 "Exiting block must actually branch out of the loop!");
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004945 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +00004946 if (ExitCount == getCouldNotCompute())
4947 return 1;
4948
4949 // Get the trip count from the BE count by adding 1.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00004950 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType()));
Andrew Trick2b6860f2011-08-11 23:36:16 +00004951 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
4952 // to factor simple cases.
4953 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
4954 TCMul = Mul->getOperand(0);
4955
4956 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
4957 if (!MulC)
4958 return 1;
4959
4960 ConstantInt *Result = MulC->getValue();
4961
Hal Finkel30bd9342012-10-24 19:46:44 +00004962 // Guard against huge trip counts (this requires checking
4963 // for zero to handle the case where the trip count == -1 and the
4964 // addition wraps).
4965 if (!Result || Result->getValue().getActiveBits() > 32 ||
4966 Result->getValue().getActiveBits() == 0)
Andrew Trick2b6860f2011-08-11 23:36:16 +00004967 return 1;
4968
4969 return (unsigned)Result->getZExtValue();
4970}
4971
Andrew Trick3ca3f982011-07-26 17:19:55 +00004972// getExitCount - Get the expression for the number of loop iterations for which
Andrew Trickee9143a2013-05-31 23:34:46 +00004973// this loop is guaranteed not to exit via ExitingBlock. Otherwise return
Andrew Trick3ca3f982011-07-26 17:19:55 +00004974// SCEVCouldNotCompute.
Andrew Trick77c55422011-08-02 04:23:35 +00004975const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
4976 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick3ca3f982011-07-26 17:19:55 +00004977}
4978
Dan Gohman0bddac12009-02-24 18:55:53 +00004979/// getBackedgeTakenCount - If the specified loop has a predictable
4980/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
4981/// object. The backedge-taken count is the number of times the loop header
4982/// will be branched to from within the loop. This is one less than the
4983/// trip count of the loop, since it doesn't count the first iteration,
4984/// when the header is branched to from outside the loop.
4985///
4986/// Note that it is not valid to call this method on a loop without a
4987/// loop-invariant backedge-taken count (see
4988/// hasLoopInvariantBackedgeTakenCount).
4989///
Dan Gohmanaf752342009-07-07 17:06:11 +00004990const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004991 return getBackedgeTakenInfo(L).getExact(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00004992}
4993
4994/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
4995/// return the least SCEV value that is known never to be less than the
4996/// actual backedge taken count.
Dan Gohmanaf752342009-07-07 17:06:11 +00004997const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004998 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00004999}
5000
Dan Gohmandc191042009-07-08 19:23:34 +00005001/// PushLoopPHIs - Push PHI nodes in the header of the given loop
5002/// onto the given Worklist.
5003static void
5004PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5005 BasicBlock *Header = L->getHeader();
5006
5007 // Push all Loop-header PHIs onto the Worklist stack.
5008 for (BasicBlock::iterator I = Header->begin();
5009 PHINode *PN = dyn_cast<PHINode>(I); ++I)
5010 Worklist.push_back(PN);
5011}
5012
Dan Gohman2b8da352009-04-30 20:47:05 +00005013const ScalarEvolution::BackedgeTakenInfo &
5014ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005015 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman8b0a4192010-03-01 17:49:51 +00005016 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman76466372009-04-27 20:16:15 +00005017 // update the value. The temporary CouldNotCompute value tells SCEV
5018 // code elsewhere that it shouldn't attempt to request a new
5019 // backedge-taken count, which could result in infinite recursion.
Dan Gohman0daf6872011-05-09 18:44:09 +00005020 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Andrew Trick3ca3f982011-07-26 17:19:55 +00005021 BackedgeTakenCounts.insert(std::make_pair(L, BackedgeTakenInfo()));
Chris Lattnera337f5e2011-01-09 02:16:18 +00005022 if (!Pair.second)
5023 return Pair.first->second;
Dan Gohman76466372009-04-27 20:16:15 +00005024
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005025 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
Andrew Trick3ca3f982011-07-26 17:19:55 +00005026 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5027 // must be cleared in this scope.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005028 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005029
5030 if (Result.getExact(this) != getCouldNotCompute()) {
5031 assert(isLoopInvariant(Result.getExact(this), L) &&
5032 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnera337f5e2011-01-09 02:16:18 +00005033 "Computed backedge-taken count isn't loop invariant for loop!");
5034 ++NumTripCountsComputed;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005035 }
5036 else if (Result.getMax(this) == getCouldNotCompute() &&
5037 isa<PHINode>(L->getHeader()->begin())) {
5038 // Only count loops that have phi nodes as not being computable.
5039 ++NumTripCountsNotComputed;
Chris Lattnera337f5e2011-01-09 02:16:18 +00005040 }
Dan Gohman2b8da352009-04-30 20:47:05 +00005041
Chris Lattnera337f5e2011-01-09 02:16:18 +00005042 // Now that we know more about the trip count for this loop, forget any
5043 // existing SCEV values for PHI nodes in this loop since they are only
5044 // conservative estimates made without the benefit of trip count
5045 // information. This is similar to the code in forgetLoop, except that
5046 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005047 if (Result.hasAnyInfo()) {
Chris Lattnera337f5e2011-01-09 02:16:18 +00005048 SmallVector<Instruction *, 16> Worklist;
5049 PushLoopPHIs(L, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005050
Chris Lattnera337f5e2011-01-09 02:16:18 +00005051 SmallPtrSet<Instruction *, 8> Visited;
5052 while (!Worklist.empty()) {
5053 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005054 if (!Visited.insert(I).second)
5055 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005056
Chris Lattnera337f5e2011-01-09 02:16:18 +00005057 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005058 ValueExprMap.find_as(static_cast<Value *>(I));
Chris Lattnera337f5e2011-01-09 02:16:18 +00005059 if (It != ValueExprMap.end()) {
5060 const SCEV *Old = It->second;
Dan Gohman761065e2010-11-17 02:44:44 +00005061
Chris Lattnera337f5e2011-01-09 02:16:18 +00005062 // SCEVUnknown for a PHI either means that it has an unrecognized
5063 // structure, or it's a PHI that's in the progress of being computed
5064 // by createNodeForPHI. In the former case, additional loop trip
5065 // count information isn't going to change anything. In the later
5066 // case, createNodeForPHI will perform the necessary updates on its
5067 // own when it gets to that point.
5068 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
5069 forgetMemoizedResults(Old);
5070 ValueExprMap.erase(It);
Dan Gohmandc191042009-07-08 19:23:34 +00005071 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005072 if (PHINode *PN = dyn_cast<PHINode>(I))
5073 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmandc191042009-07-08 19:23:34 +00005074 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005075
5076 PushDefUseChildren(I, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005077 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005078 }
Dan Gohman6acd95b2011-04-25 22:48:29 +00005079
5080 // Re-lookup the insert position, since the call to
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005081 // computeBackedgeTakenCount above could result in a
Dan Gohman6acd95b2011-04-25 22:48:29 +00005082 // recusive call to getBackedgeTakenInfo (on a different
5083 // loop), which would invalidate the iterator computed
5084 // earlier.
5085 return BackedgeTakenCounts.find(L)->second = Result;
Chris Lattnerd934c702004-04-02 20:23:17 +00005086}
5087
Dan Gohman880c92a2009-10-31 15:04:55 +00005088/// forgetLoop - This method should be called by the client when it has
5089/// changed a loop in a way that may effect ScalarEvolution's ability to
5090/// compute a trip count, or if the loop is deleted.
5091void ScalarEvolution::forgetLoop(const Loop *L) {
5092 // Drop any stored trip count value.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005093 DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos =
5094 BackedgeTakenCounts.find(L);
5095 if (BTCPos != BackedgeTakenCounts.end()) {
5096 BTCPos->second.clear();
5097 BackedgeTakenCounts.erase(BTCPos);
5098 }
Dan Gohmanf1505722009-05-02 17:43:35 +00005099
Dan Gohman880c92a2009-10-31 15:04:55 +00005100 // Drop information about expressions based on loop-header PHIs.
Dan Gohman48f82222009-05-04 22:30:44 +00005101 SmallVector<Instruction *, 16> Worklist;
Dan Gohmandc191042009-07-08 19:23:34 +00005102 PushLoopPHIs(L, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005103
Dan Gohmandc191042009-07-08 19:23:34 +00005104 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00005105 while (!Worklist.empty()) {
5106 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005107 if (!Visited.insert(I).second)
5108 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005109
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005110 ValueExprMapType::iterator It =
5111 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005112 if (It != ValueExprMap.end()) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00005113 forgetMemoizedResults(It->second);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005114 ValueExprMap.erase(It);
Dan Gohmandc191042009-07-08 19:23:34 +00005115 if (PHINode *PN = dyn_cast<PHINode>(I))
5116 ConstantEvolutionLoopExitValue.erase(PN);
5117 }
5118
5119 PushDefUseChildren(I, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005120 }
Dan Gohmandcb354b2010-10-29 20:16:10 +00005121
5122 // Forget all contained loops too, to avoid dangling entries in the
5123 // ValuesAtScopes map.
5124 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5125 forgetLoop(*I);
Dan Gohman43300342009-02-17 20:49:49 +00005126}
5127
Eric Christopheref6d5932010-07-29 01:25:38 +00005128/// forgetValue - This method should be called by the client when it has
5129/// changed a value in a way that may effect its value, or which may
5130/// disconnect it from a def-use chain linking it to a loop.
5131void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005132 Instruction *I = dyn_cast<Instruction>(V);
5133 if (!I) return;
5134
5135 // Drop information about expressions based on loop-header PHIs.
5136 SmallVector<Instruction *, 16> Worklist;
5137 Worklist.push_back(I);
5138
5139 SmallPtrSet<Instruction *, 8> Visited;
5140 while (!Worklist.empty()) {
5141 I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005142 if (!Visited.insert(I).second)
5143 continue;
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005144
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005145 ValueExprMapType::iterator It =
5146 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005147 if (It != ValueExprMap.end()) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00005148 forgetMemoizedResults(It->second);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005149 ValueExprMap.erase(It);
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005150 if (PHINode *PN = dyn_cast<PHINode>(I))
5151 ConstantEvolutionLoopExitValue.erase(PN);
5152 }
5153
5154 PushDefUseChildren(I, Worklist);
5155 }
5156}
5157
Andrew Trick3ca3f982011-07-26 17:19:55 +00005158/// getExact - Get the exact loop backedge taken count considering all loop
Sanjoy Das135e5b92015-07-21 20:59:22 +00005159/// exits. A computable result can only be returned for loops with a single
5160/// exit. Returning the minimum taken count among all exits is incorrect
5161/// because one of the loop's exit limit's may have been skipped. HowFarToZero
5162/// assumes that the limit of each loop test is never skipped. This is a valid
5163/// assumption as long as the loop exits via that test. For precise results, it
5164/// is the caller's responsibility to specify the relevant loop exit using
Andrew Trick90c7a102011-11-16 00:52:40 +00005165/// getExact(ExitingBlock, SE).
Andrew Trick3ca3f982011-07-26 17:19:55 +00005166const SCEV *
5167ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const {
5168 // If any exits were not computable, the loop is not computable.
5169 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
5170
Andrew Trick90c7a102011-11-16 00:52:40 +00005171 // We need exactly one computable exit.
Andrew Trick77c55422011-08-02 04:23:35 +00005172 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005173 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
5174
Craig Topper9f008862014-04-15 04:59:12 +00005175 const SCEV *BECount = nullptr;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005176 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
Craig Topper9f008862014-04-15 04:59:12 +00005177 ENT != nullptr; ENT = ENT->getNextExit()) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005178
5179 assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
5180
5181 if (!BECount)
5182 BECount = ENT->ExactNotTaken;
Andrew Trick90c7a102011-11-16 00:52:40 +00005183 else if (BECount != ENT->ExactNotTaken)
5184 return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005185 }
Andrew Trickbbb226a2011-09-02 21:20:46 +00005186 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005187 return BECount;
5188}
5189
5190/// getExact - Get the exact not taken count for this loop exit.
5191const SCEV *
Andrew Trick77c55422011-08-02 04:23:35 +00005192ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005193 ScalarEvolution *SE) const {
5194 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
Craig Topper9f008862014-04-15 04:59:12 +00005195 ENT != nullptr; ENT = ENT->getNextExit()) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005196
Andrew Trick77c55422011-08-02 04:23:35 +00005197 if (ENT->ExitingBlock == ExitingBlock)
Andrew Trick3ca3f982011-07-26 17:19:55 +00005198 return ENT->ExactNotTaken;
5199 }
5200 return SE->getCouldNotCompute();
5201}
5202
5203/// getMax - Get the max backedge taken count for the loop.
5204const SCEV *
5205ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
5206 return Max ? Max : SE->getCouldNotCompute();
5207}
5208
Andrew Trick9093e152013-03-26 03:14:53 +00005209bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5210 ScalarEvolution *SE) const {
5211 if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S))
5212 return true;
5213
5214 if (!ExitNotTaken.ExitingBlock)
5215 return false;
5216
5217 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
Craig Topper9f008862014-04-15 04:59:12 +00005218 ENT != nullptr; ENT = ENT->getNextExit()) {
Andrew Trick9093e152013-03-26 03:14:53 +00005219
5220 if (ENT->ExactNotTaken != SE->getCouldNotCompute()
5221 && SE->hasOperand(ENT->ExactNotTaken, S)) {
5222 return true;
5223 }
5224 }
5225 return false;
5226}
5227
Andrew Trick3ca3f982011-07-26 17:19:55 +00005228/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5229/// computable exit into a persistent ExitNotTakenInfo array.
5230ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
5231 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
5232 bool Complete, const SCEV *MaxCount) : Max(MaxCount) {
5233
5234 if (!Complete)
5235 ExitNotTaken.setIncomplete();
5236
5237 unsigned NumExits = ExitCounts.size();
5238 if (NumExits == 0) return;
5239
Andrew Trick77c55422011-08-02 04:23:35 +00005240 ExitNotTaken.ExitingBlock = ExitCounts[0].first;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005241 ExitNotTaken.ExactNotTaken = ExitCounts[0].second;
5242 if (NumExits == 1) return;
5243
5244 // Handle the rare case of multiple computable exits.
5245 ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1];
5246
5247 ExitNotTakenInfo *PrevENT = &ExitNotTaken;
5248 for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) {
5249 PrevENT->setNextExit(ENT);
Andrew Trick77c55422011-08-02 04:23:35 +00005250 ENT->ExitingBlock = ExitCounts[i].first;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005251 ENT->ExactNotTaken = ExitCounts[i].second;
5252 }
5253}
5254
5255/// clear - Invalidate this result and free the ExitNotTakenInfo array.
5256void ScalarEvolution::BackedgeTakenInfo::clear() {
Craig Topper9f008862014-04-15 04:59:12 +00005257 ExitNotTaken.ExitingBlock = nullptr;
5258 ExitNotTaken.ExactNotTaken = nullptr;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005259 delete[] ExitNotTaken.getNextExit();
5260}
5261
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005262/// computeBackedgeTakenCount - Compute the number of times the backedge
Dan Gohman0bddac12009-02-24 18:55:53 +00005263/// of the specified loop will execute.
Dan Gohman2b8da352009-04-30 20:47:05 +00005264ScalarEvolution::BackedgeTakenInfo
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005265ScalarEvolution::computeBackedgeTakenCount(const Loop *L) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00005266 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohman96212b62009-06-22 00:31:57 +00005267 L->getExitingBlocks(ExitingBlocks);
Chris Lattnerd934c702004-04-02 20:23:17 +00005268
Andrew Trick839e30b2014-05-23 19:47:13 +00005269 SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005270 bool CouldComputeBECount = true;
Andrew Trickee5aa7f2014-01-15 06:42:11 +00005271 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
Andrew Trick839e30b2014-05-23 19:47:13 +00005272 const SCEV *MustExitMaxBECount = nullptr;
5273 const SCEV *MayExitMaxBECount = nullptr;
5274
5275 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5276 // and compute maxBECount.
Dan Gohman96212b62009-06-22 00:31:57 +00005277 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005278 BasicBlock *ExitBB = ExitingBlocks[i];
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005279 ExitLimit EL = computeExitLimit(L, ExitBB);
Andrew Trick839e30b2014-05-23 19:47:13 +00005280
5281 // 1. For each exit that can be computed, add an entry to ExitCounts.
5282 // CouldComputeBECount is true only if all exits can be computed.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005283 if (EL.Exact == getCouldNotCompute())
Dan Gohman96212b62009-06-22 00:31:57 +00005284 // We couldn't compute an exact value for this exit, so
Dan Gohman8885b372009-06-22 21:10:22 +00005285 // we won't be able to compute an exact value for the loop.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005286 CouldComputeBECount = false;
5287 else
Andrew Trick839e30b2014-05-23 19:47:13 +00005288 ExitCounts.push_back(std::make_pair(ExitBB, EL.Exact));
Andrew Trick3ca3f982011-07-26 17:19:55 +00005289
Andrew Trick839e30b2014-05-23 19:47:13 +00005290 // 2. Derive the loop's MaxBECount from each exit's max number of
5291 // non-exiting iterations. Partition the loop exits into two kinds:
5292 // LoopMustExits and LoopMayExits.
5293 //
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005294 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5295 // is a LoopMayExit. If any computable LoopMustExit is found, then
5296 // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise,
5297 // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is
5298 // considered greater than any computable EL.Max.
5299 if (EL.Max != getCouldNotCompute() && Latch &&
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005300 DT.dominates(ExitBB, Latch)) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005301 if (!MustExitMaxBECount)
5302 MustExitMaxBECount = EL.Max;
5303 else {
5304 MustExitMaxBECount =
5305 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max);
Andrew Tricke2553592014-05-22 00:37:03 +00005306 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005307 } else if (MayExitMaxBECount != getCouldNotCompute()) {
5308 if (!MayExitMaxBECount || EL.Max == getCouldNotCompute())
5309 MayExitMaxBECount = EL.Max;
5310 else {
5311 MayExitMaxBECount =
5312 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max);
5313 }
Andrew Trick90c7a102011-11-16 00:52:40 +00005314 }
Dan Gohman96212b62009-06-22 00:31:57 +00005315 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005316 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5317 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
Andrew Trick3ca3f982011-07-26 17:19:55 +00005318 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00005319}
5320
Andrew Trick3ca3f982011-07-26 17:19:55 +00005321ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005322ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock) {
Dan Gohman96212b62009-06-22 00:31:57 +00005323
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005324 // Okay, we've chosen an exiting block. See what condition causes us to exit
5325 // at this block and remember the exit block and whether all other targets
Benjamin Kramer5a188542014-02-11 15:44:32 +00005326 // lead to the loop header.
5327 bool MustExecuteLoopHeader = true;
Craig Topper9f008862014-04-15 04:59:12 +00005328 BasicBlock *Exit = nullptr;
Sanjoy Das0ff07872016-01-19 20:53:46 +00005329 for (auto *SBB : successors(ExitingBlock))
5330 if (!L->contains(SBB)) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005331 if (Exit) // Multiple exit successors.
5332 return getCouldNotCompute();
Sanjoy Das0ff07872016-01-19 20:53:46 +00005333 Exit = SBB;
5334 } else if (SBB != L->getHeader()) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005335 MustExecuteLoopHeader = false;
5336 }
Dan Gohmance973df2009-06-24 04:48:43 +00005337
Chris Lattner18954852007-01-07 02:24:26 +00005338 // At this point, we know we have a conditional branch that determines whether
5339 // the loop is exited. However, we don't know if the branch is executed each
5340 // time through the loop. If not, then the execution count of the branch will
5341 // not be equal to the trip count of the loop.
5342 //
5343 // Currently we check for this by checking to see if the Exit branch goes to
5344 // the loop header. If so, we know it will always execute the same number of
Chris Lattner5a554762007-01-14 01:24:47 +00005345 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman96212b62009-06-22 00:31:57 +00005346 // loop header. This is common for un-rotated loops.
5347 //
5348 // If both of those tests fail, walk up the unique predecessor chain to the
5349 // header, stopping if there is an edge that doesn't exit the loop. If the
5350 // header is reached, the execution count of the branch will be equal to the
5351 // trip count of the loop.
5352 //
5353 // More extensive analysis could be done to handle more cases here.
5354 //
Benjamin Kramer5a188542014-02-11 15:44:32 +00005355 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005356 // The simple checks failed, try climbing the unique predecessor chain
5357 // up to the header.
5358 bool Ok = false;
Benjamin Kramer5a188542014-02-11 15:44:32 +00005359 for (BasicBlock *BB = ExitingBlock; BB; ) {
Dan Gohman96212b62009-06-22 00:31:57 +00005360 BasicBlock *Pred = BB->getUniquePredecessor();
5361 if (!Pred)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005362 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005363 TerminatorInst *PredTerm = Pred->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +00005364 for (const BasicBlock *PredSucc : PredTerm->successors()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005365 if (PredSucc == BB)
5366 continue;
5367 // If the predecessor has a successor that isn't BB and isn't
5368 // outside the loop, assume the worst.
5369 if (L->contains(PredSucc))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005370 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005371 }
5372 if (Pred == L->getHeader()) {
5373 Ok = true;
5374 break;
5375 }
5376 BB = Pred;
5377 }
5378 if (!Ok)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005379 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005380 }
5381
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005382 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005383 TerminatorInst *Term = ExitingBlock->getTerminator();
5384 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
5385 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
5386 // Proceed to the next level to examine the exit condition expression.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005387 return computeExitLimitFromCond(L, BI->getCondition(), BI->getSuccessor(0),
Benjamin Kramer5a188542014-02-11 15:44:32 +00005388 BI->getSuccessor(1),
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005389 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005390 }
5391
5392 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005393 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005394 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005395
5396 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005397}
5398
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005399/// computeExitLimitFromCond - Compute the number of times the
Dan Gohman96212b62009-06-22 00:31:57 +00005400/// backedge of the specified loop will execute if its exit condition
5401/// were a conditional branch of ExitCond, TBB, and FBB.
Andrew Trick5b245a12013-05-31 06:43:25 +00005402///
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005403/// @param ControlsExit is true if ExitCond directly controls the exit
5404/// branch. In this case, we can assume that the loop exits only if the
5405/// condition is true and can infer that failing to meet the condition prior to
5406/// integer wraparound results in undefined behavior.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005407ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005408ScalarEvolution::computeExitLimitFromCond(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005409 Value *ExitCond,
5410 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005411 BasicBlock *FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005412 bool ControlsExit) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00005413 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman96212b62009-06-22 00:31:57 +00005414 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
5415 if (BO->getOpcode() == Instruction::And) {
5416 // Recurse on the operands of the and.
Andrew Trick5b245a12013-05-31 06:43:25 +00005417 bool EitherMayExit = L->contains(TBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005418 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005419 ControlsExit && !EitherMayExit);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005420 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005421 ControlsExit && !EitherMayExit);
Dan Gohmanaf752342009-07-07 17:06:11 +00005422 const SCEV *BECount = getCouldNotCompute();
5423 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005424 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005425 // Both conditions must be true for the loop to continue executing.
5426 // Choose the less conservative count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005427 if (EL0.Exact == getCouldNotCompute() ||
5428 EL1.Exact == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005429 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005430 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005431 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5432 if (EL0.Max == getCouldNotCompute())
5433 MaxBECount = EL1.Max;
5434 else if (EL1.Max == getCouldNotCompute())
5435 MaxBECount = EL0.Max;
Dan Gohmaned627382009-06-22 15:09:28 +00005436 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005437 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohman96212b62009-06-22 00:31:57 +00005438 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005439 // Both conditions must be true at the same time for the loop to exit.
5440 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005441 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005442 if (EL0.Max == EL1.Max)
5443 MaxBECount = EL0.Max;
5444 if (EL0.Exact == EL1.Exact)
5445 BECount = EL0.Exact;
Dan Gohman96212b62009-06-22 00:31:57 +00005446 }
5447
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00005448 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
5449 // to be more aggressive when computing BECount than when computing
5450 // MaxBECount. In these cases it is possible for EL0.Exact and EL1.Exact
5451 // to match, but for EL0.Max and EL1.Max to not.
5452 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
5453 !isa<SCEVCouldNotCompute>(BECount))
5454 MaxBECount = BECount;
5455
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005456 return ExitLimit(BECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00005457 }
5458 if (BO->getOpcode() == Instruction::Or) {
5459 // Recurse on the operands of the or.
Andrew Trick5b245a12013-05-31 06:43:25 +00005460 bool EitherMayExit = L->contains(FBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005461 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005462 ControlsExit && !EitherMayExit);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005463 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005464 ControlsExit && !EitherMayExit);
Dan Gohmanaf752342009-07-07 17:06:11 +00005465 const SCEV *BECount = getCouldNotCompute();
5466 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005467 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005468 // Both conditions must be false for the loop to continue executing.
5469 // Choose the less conservative count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005470 if (EL0.Exact == getCouldNotCompute() ||
5471 EL1.Exact == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005472 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005473 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005474 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5475 if (EL0.Max == getCouldNotCompute())
5476 MaxBECount = EL1.Max;
5477 else if (EL1.Max == getCouldNotCompute())
5478 MaxBECount = EL0.Max;
Dan Gohmaned627382009-06-22 15:09:28 +00005479 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005480 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohman96212b62009-06-22 00:31:57 +00005481 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005482 // Both conditions must be false at the same time for the loop to exit.
5483 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005484 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005485 if (EL0.Max == EL1.Max)
5486 MaxBECount = EL0.Max;
5487 if (EL0.Exact == EL1.Exact)
5488 BECount = EL0.Exact;
Dan Gohman96212b62009-06-22 00:31:57 +00005489 }
5490
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005491 return ExitLimit(BECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00005492 }
5493 }
5494
5495 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman8b0a4192010-03-01 17:49:51 +00005496 // Proceed to the next level to examine the icmp.
Dan Gohman96212b62009-06-22 00:31:57 +00005497 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005498 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
Reid Spencer266e42b2006-12-23 06:05:41 +00005499
Dan Gohman6b1e2a82010-02-19 18:12:07 +00005500 // Check for a constant condition. These are normally stripped out by
5501 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
5502 // preserve the CFG and is temporarily leaving constant conditions
5503 // in place.
5504 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
5505 if (L->contains(FBB) == !CI->getZExtValue())
5506 // The backedge is always taken.
5507 return getCouldNotCompute();
5508 else
5509 // The backedge is never taken.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005510 return getZero(CI->getType());
Dan Gohman6b1e2a82010-02-19 18:12:07 +00005511 }
5512
Eli Friedmanebf98b02009-05-09 12:32:42 +00005513 // If it's not an integer or pointer comparison then compute it the hard way.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005514 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohman96212b62009-06-22 00:31:57 +00005515}
5516
Andrew Trick3ca3f982011-07-26 17:19:55 +00005517ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005518ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005519 ICmpInst *ExitCond,
5520 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005521 BasicBlock *FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005522 bool ControlsExit) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005523
Reid Spencer266e42b2006-12-23 06:05:41 +00005524 // If the condition was exit on true, convert the condition to exit on false
5525 ICmpInst::Predicate Cond;
Dan Gohman96212b62009-06-22 00:31:57 +00005526 if (!L->contains(FBB))
Reid Spencer266e42b2006-12-23 06:05:41 +00005527 Cond = ExitCond->getPredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005528 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005529 Cond = ExitCond->getInversePredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005530
5531 // Handle common loops like: for (X = "string"; *X; ++X)
5532 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
5533 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005534 ExitLimit ItCnt =
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005535 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanba820342010-02-24 17:31:30 +00005536 if (ItCnt.hasAnyInfo())
5537 return ItCnt;
Chris Lattnerec901cc2004-10-12 01:49:27 +00005538 }
5539
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00005540 ExitLimit ShiftEL = computeShiftCompareExitLimit(
5541 ExitCond->getOperand(0), ExitCond->getOperand(1), L, Cond);
5542 if (ShiftEL.hasAnyInfo())
5543 return ShiftEL;
5544
Dan Gohmanaf752342009-07-07 17:06:11 +00005545 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
5546 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattnerd934c702004-04-02 20:23:17 +00005547
5548 // Try to evaluate any dependencies out of the loop.
Dan Gohman8ca08852009-05-24 23:25:42 +00005549 LHS = getSCEVAtScope(LHS, L);
5550 RHS = getSCEVAtScope(RHS, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00005551
Dan Gohmance973df2009-06-24 04:48:43 +00005552 // At this point, we would like to compute how many iterations of the
Reid Spencer266e42b2006-12-23 06:05:41 +00005553 // loop the predicate will return true for these inputs.
Dan Gohmanafd6db92010-11-17 21:23:15 +00005554 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohmandc5f5cb2008-09-16 18:52:57 +00005555 // If there is a loop-invariant, force it into the RHS.
Chris Lattnerd934c702004-04-02 20:23:17 +00005556 std::swap(LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00005557 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattnerd934c702004-04-02 20:23:17 +00005558 }
5559
Dan Gohman81585c12010-05-03 16:35:17 +00005560 // Simplify the operands before analyzing them.
5561 (void)SimplifyICmpOperands(Cond, LHS, RHS);
5562
Chris Lattnerd934c702004-04-02 20:23:17 +00005563 // If we have a comparison of a chrec against a constant, try to use value
5564 // ranges to answer this query.
Dan Gohmana30370b2009-05-04 22:02:23 +00005565 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
5566 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattnerd934c702004-04-02 20:23:17 +00005567 if (AddRec->getLoop() == L) {
Eli Friedmanebf98b02009-05-09 12:32:42 +00005568 // Form the constant range.
5569 ConstantRange CompRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00005570 ICmpInst::makeConstantRange(Cond, RHSC->getAPInt()));
Misha Brukman01808ca2005-04-21 21:13:18 +00005571
Dan Gohmanaf752342009-07-07 17:06:11 +00005572 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedmanebf98b02009-05-09 12:32:42 +00005573 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattnerd934c702004-04-02 20:23:17 +00005574 }
Misha Brukman01808ca2005-04-21 21:13:18 +00005575
Chris Lattnerd934c702004-04-02 20:23:17 +00005576 switch (Cond) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005577 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattnerd934c702004-04-02 20:23:17 +00005578 // Convert to: while (X-Y != 0)
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005579 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005580 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00005581 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005582 }
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00005583 case ICmpInst::ICMP_EQ: { // while (X == Y)
5584 // Convert to: while (X-Y == 0)
Andrew Trick3ca3f982011-07-26 17:19:55 +00005585 ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
5586 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00005587 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005588 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00005589 case ICmpInst::ICMP_SLT:
5590 case ICmpInst::ICMP_ULT: { // while (X < Y)
5591 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005592 ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, ControlsExit);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005593 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00005594 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005595 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00005596 case ICmpInst::ICMP_SGT:
5597 case ICmpInst::ICMP_UGT: { // while (X > Y)
5598 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005599 ExitLimit EL = HowManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005600 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00005601 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005602 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005603 default:
Chris Lattner0defaa12004-04-03 00:43:03 +00005604 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00005605 }
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005606 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner4021d1a2004-04-17 18:36:24 +00005607}
5608
Benjamin Kramer5a188542014-02-11 15:44:32 +00005609ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005610ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
Benjamin Kramer5a188542014-02-11 15:44:32 +00005611 SwitchInst *Switch,
5612 BasicBlock *ExitingBlock,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005613 bool ControlsExit) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005614 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
5615
5616 // Give up if the exit is the default dest of a switch.
5617 if (Switch->getDefaultDest() == ExitingBlock)
5618 return getCouldNotCompute();
5619
5620 assert(L->contains(Switch->getDefaultDest()) &&
5621 "Default case must not exit the loop!");
5622 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
5623 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
5624
5625 // while (X != Y) --> while (X-Y != 0)
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005626 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005627 if (EL.hasAnyInfo())
5628 return EL;
5629
5630 return getCouldNotCompute();
5631}
5632
Chris Lattnerec901cc2004-10-12 01:49:27 +00005633static ConstantInt *
Dan Gohmana37eaf22007-10-22 18:31:58 +00005634EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
5635 ScalarEvolution &SE) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005636 const SCEV *InVal = SE.getConstant(C);
5637 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005638 assert(isa<SCEVConstant>(Val) &&
5639 "Evaluation of SCEV at constant didn't fold correctly?");
5640 return cast<SCEVConstant>(Val)->getValue();
5641}
5642
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005643/// computeLoadConstantCompareExitLimit - Given an exit condition of
Dan Gohman0bddac12009-02-24 18:55:53 +00005644/// 'icmp op load X, cst', try to see if we can compute the backedge
5645/// execution count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005646ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005647ScalarEvolution::computeLoadConstantCompareExitLimit(
Andrew Trick3ca3f982011-07-26 17:19:55 +00005648 LoadInst *LI,
5649 Constant *RHS,
5650 const Loop *L,
5651 ICmpInst::Predicate predicate) {
5652
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005653 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005654
5655 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanba820342010-02-24 17:31:30 +00005656 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattnerec901cc2004-10-12 01:49:27 +00005657 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005658 if (!GEP) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005659
5660 // Make sure that it is really a constant global we are gepping, with an
5661 // initializer, and make sure the first IDX is really 0.
5662 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00005663 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00005664 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
5665 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005666 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005667
5668 // Okay, we allow one non-constant index into the GEP instruction.
Craig Topper9f008862014-04-15 04:59:12 +00005669 Value *VarIdx = nullptr;
Chris Lattnere166a852012-01-24 05:49:24 +00005670 std::vector<Constant*> Indexes;
Chris Lattnerec901cc2004-10-12 01:49:27 +00005671 unsigned VarIdxNum = 0;
5672 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
5673 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5674 Indexes.push_back(CI);
5675 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005676 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattnerec901cc2004-10-12 01:49:27 +00005677 VarIdx = GEP->getOperand(i);
5678 VarIdxNum = i-2;
Craig Topper9f008862014-04-15 04:59:12 +00005679 Indexes.push_back(nullptr);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005680 }
5681
Andrew Trick7004e4b2012-03-26 22:33:59 +00005682 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
5683 if (!VarIdx)
5684 return getCouldNotCompute();
5685
Chris Lattnerec901cc2004-10-12 01:49:27 +00005686 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
5687 // Check to see if X is a loop variant variable value now.
Dan Gohmanaf752342009-07-07 17:06:11 +00005688 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohman8ca08852009-05-24 23:25:42 +00005689 Idx = getSCEVAtScope(Idx, L);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005690
5691 // We can only recognize very limited forms of loop index expressions, in
5692 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman48f82222009-05-04 22:30:44 +00005693 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanafd6db92010-11-17 21:23:15 +00005694 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00005695 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
5696 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005697 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005698
5699 unsigned MaxSteps = MaxBruteForceIterations;
5700 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersonedb4a702009-07-24 23:12:02 +00005701 ConstantInt *ItCst = ConstantInt::get(
Owen Andersonb6b25302009-07-14 23:09:55 +00005702 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanc8e23622009-04-21 23:15:49 +00005703 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005704
5705 // Form the GEP offset.
5706 Indexes[VarIdxNum] = Val;
5707
Chris Lattnere166a852012-01-24 05:49:24 +00005708 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
5709 Indexes);
Craig Topper9f008862014-04-15 04:59:12 +00005710 if (!Result) break; // Cannot compute!
Chris Lattnerec901cc2004-10-12 01:49:27 +00005711
5712 // Evaluate the condition for this iteration.
Reid Spencer266e42b2006-12-23 06:05:41 +00005713 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00005714 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer983e3b32007-03-01 07:25:48 +00005715 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00005716 ++NumArrayLenItCounts;
Dan Gohmanc8e23622009-04-21 23:15:49 +00005717 return getConstant(ItCst); // Found terminating iteration!
Chris Lattnerec901cc2004-10-12 01:49:27 +00005718 }
5719 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005720 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005721}
5722
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00005723ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
5724 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
5725 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
5726 if (!RHS)
5727 return getCouldNotCompute();
5728
5729 const BasicBlock *Latch = L->getLoopLatch();
5730 if (!Latch)
5731 return getCouldNotCompute();
5732
5733 const BasicBlock *Predecessor = L->getLoopPredecessor();
5734 if (!Predecessor)
5735 return getCouldNotCompute();
5736
5737 // Return true if V is of the form "LHS `shift_op` <positive constant>".
5738 // Return LHS in OutLHS and shift_opt in OutOpCode.
5739 auto MatchPositiveShift =
5740 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
5741
5742 using namespace PatternMatch;
5743
5744 ConstantInt *ShiftAmt;
5745 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
5746 OutOpCode = Instruction::LShr;
5747 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
5748 OutOpCode = Instruction::AShr;
5749 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
5750 OutOpCode = Instruction::Shl;
5751 else
5752 return false;
5753
5754 return ShiftAmt->getValue().isStrictlyPositive();
5755 };
5756
5757 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
5758 //
5759 // loop:
5760 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
5761 // %iv.shifted = lshr i32 %iv, <positive constant>
5762 //
5763 // Return true on a succesful match. Return the corresponding PHI node (%iv
5764 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
5765 auto MatchShiftRecurrence =
5766 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
5767 Optional<Instruction::BinaryOps> PostShiftOpCode;
5768
5769 {
5770 Instruction::BinaryOps OpC;
5771 Value *V;
5772
5773 // If we encounter a shift instruction, "peel off" the shift operation,
5774 // and remember that we did so. Later when we inspect %iv's backedge
5775 // value, we will make sure that the backedge value uses the same
5776 // operation.
5777 //
5778 // Note: the peeled shift operation does not have to be the same
5779 // instruction as the one feeding into the PHI's backedge value. We only
5780 // really care about it being the same *kind* of shift instruction --
5781 // that's all that is required for our later inferences to hold.
5782 if (MatchPositiveShift(LHS, V, OpC)) {
5783 PostShiftOpCode = OpC;
5784 LHS = V;
5785 }
5786 }
5787
5788 PNOut = dyn_cast<PHINode>(LHS);
5789 if (!PNOut || PNOut->getParent() != L->getHeader())
5790 return false;
5791
5792 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
5793 Value *OpLHS;
5794
5795 return
5796 // The backedge value for the PHI node must be a shift by a positive
5797 // amount
5798 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
5799
5800 // of the PHI node itself
5801 OpLHS == PNOut &&
5802
5803 // and the kind of shift should be match the kind of shift we peeled
5804 // off, if any.
5805 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
5806 };
5807
5808 PHINode *PN;
5809 Instruction::BinaryOps OpCode;
5810 if (!MatchShiftRecurrence(LHS, PN, OpCode))
5811 return getCouldNotCompute();
5812
5813 const DataLayout &DL = getDataLayout();
5814
5815 // The key rationale for this optimization is that for some kinds of shift
5816 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
5817 // within a finite number of iterations. If the condition guarding the
5818 // backedge (in the sense that the backedge is taken if the condition is true)
5819 // is false for the value the shift recurrence stabilizes to, then we know
5820 // that the backedge is taken only a finite number of times.
5821
5822 ConstantInt *StableValue = nullptr;
5823 switch (OpCode) {
5824 default:
5825 llvm_unreachable("Impossible case!");
5826
5827 case Instruction::AShr: {
5828 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
5829 // bitwidth(K) iterations.
5830 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
5831 bool KnownZero, KnownOne;
5832 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
5833 Predecessor->getTerminator(), &DT);
5834 auto *Ty = cast<IntegerType>(RHS->getType());
5835 if (KnownZero)
5836 StableValue = ConstantInt::get(Ty, 0);
5837 else if (KnownOne)
5838 StableValue = ConstantInt::get(Ty, -1, true);
5839 else
5840 return getCouldNotCompute();
5841
5842 break;
5843 }
5844 case Instruction::LShr:
5845 case Instruction::Shl:
5846 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
5847 // stabilize to 0 in at most bitwidth(K) iterations.
5848 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
5849 break;
5850 }
5851
5852 auto *Result =
5853 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
5854 assert(Result->getType()->isIntegerTy(1) &&
5855 "Otherwise cannot be an operand to a branch instruction");
5856
5857 if (Result->isZeroValue()) {
5858 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
5859 const SCEV *UpperBound =
5860 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
5861 return ExitLimit(getCouldNotCompute(), UpperBound);
5862 }
5863
5864 return getCouldNotCompute();
5865}
Chris Lattnerec901cc2004-10-12 01:49:27 +00005866
Chris Lattnerdd730472004-04-17 22:58:41 +00005867/// CanConstantFold - Return true if we can constant fold an instruction of the
5868/// specified type, assuming that all operands were constants.
5869static bool CanConstantFold(const Instruction *I) {
Reid Spencer2341c222007-02-02 02:16:23 +00005870 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Nick Lewyckya6674c72011-10-22 19:58:20 +00005871 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
5872 isa<LoadInst>(I))
Chris Lattnerdd730472004-04-17 22:58:41 +00005873 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00005874
Chris Lattnerdd730472004-04-17 22:58:41 +00005875 if (const CallInst *CI = dyn_cast<CallInst>(I))
5876 if (const Function *F = CI->getCalledFunction())
Dan Gohmana65951f2008-01-31 01:05:10 +00005877 return canConstantFoldCallTo(F);
Chris Lattnerdd730472004-04-17 22:58:41 +00005878 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00005879}
5880
Andrew Trick3a86ba72011-10-05 03:25:31 +00005881/// Determine whether this instruction can constant evolve within this loop
5882/// assuming its operands can all constant evolve.
5883static bool canConstantEvolve(Instruction *I, const Loop *L) {
5884 // An instruction outside of the loop can't be derived from a loop PHI.
5885 if (!L->contains(I)) return false;
5886
5887 if (isa<PHINode>(I)) {
David Blaikie19ef0d32015-03-24 16:33:19 +00005888 // We don't currently keep track of the control flow needed to evaluate
5889 // PHIs, so we cannot handle PHIs inside of loops.
5890 return L->getHeader() == I->getParent();
Andrew Trick3a86ba72011-10-05 03:25:31 +00005891 }
5892
5893 // If we won't be able to constant fold this expression even if the operands
5894 // are constants, bail early.
5895 return CanConstantFold(I);
5896}
5897
5898/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
5899/// recursing through each instruction operand until reaching a loop header phi.
5900static PHINode *
5901getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
Andrew Tricke9162f12011-10-05 05:58:49 +00005902 DenseMap<Instruction *, PHINode *> &PHIMap) {
Andrew Trick3a86ba72011-10-05 03:25:31 +00005903
5904 // Otherwise, we can evaluate this instruction if all of its operands are
5905 // constant or derived from a PHI node themselves.
Craig Topper9f008862014-04-15 04:59:12 +00005906 PHINode *PHI = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00005907 for (Value *Op : UseInst->operands()) {
5908 if (isa<Constant>(Op)) continue;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005909
Sanjoy Dasd87e4352015-12-08 22:53:36 +00005910 Instruction *OpInst = dyn_cast<Instruction>(Op);
Craig Topper9f008862014-04-15 04:59:12 +00005911 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005912
5913 PHINode *P = dyn_cast<PHINode>(OpInst);
Andrew Trick3e8a5762011-10-05 22:06:53 +00005914 if (!P)
5915 // If this operand is already visited, reuse the prior result.
5916 // We may have P != PHI if this is the deepest point at which the
5917 // inconsistent paths meet.
5918 P = PHIMap.lookup(OpInst);
5919 if (!P) {
5920 // Recurse and memoize the results, whether a phi is found or not.
5921 // This recursive call invalidates pointers into PHIMap.
5922 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
5923 PHIMap[OpInst] = P;
Andrew Tricke9162f12011-10-05 05:58:49 +00005924 }
Craig Topper9f008862014-04-15 04:59:12 +00005925 if (!P)
5926 return nullptr; // Not evolving from PHI
5927 if (PHI && PHI != P)
5928 return nullptr; // Evolving from multiple different PHIs.
Andrew Tricke9162f12011-10-05 05:58:49 +00005929 PHI = P;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005930 }
5931 // This is a expression evolving from a constant PHI!
5932 return PHI;
5933}
5934
Chris Lattnerdd730472004-04-17 22:58:41 +00005935/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
5936/// in the loop that V is derived from. We allow arbitrary operations along the
5937/// way, but the operands of an operation must either be constants or a value
5938/// derived from a constant PHI. If this expression does not fit with these
5939/// constraints, return null.
5940static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00005941 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00005942 if (!I || !canConstantEvolve(I, L)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00005943
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00005944 if (PHINode *PN = dyn_cast<PHINode>(I))
Andrew Trick3a86ba72011-10-05 03:25:31 +00005945 return PN;
Chris Lattnerdd730472004-04-17 22:58:41 +00005946
Andrew Trick3a86ba72011-10-05 03:25:31 +00005947 // Record non-constant instructions contained by the loop.
Andrew Tricke9162f12011-10-05 05:58:49 +00005948 DenseMap<Instruction *, PHINode *> PHIMap;
5949 return getConstantEvolvingPHIOperands(I, L, PHIMap);
Chris Lattnerdd730472004-04-17 22:58:41 +00005950}
5951
5952/// EvaluateExpression - Given an expression that passes the
5953/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
5954/// in the loop has the value PHIVal. If we can't fold this expression for some
5955/// reason, return null.
Andrew Trick3a86ba72011-10-05 03:25:31 +00005956static Constant *EvaluateExpression(Value *V, const Loop *L,
5957 DenseMap<Instruction *, Constant *> &Vals,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005958 const DataLayout &DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00005959 const TargetLibraryInfo *TLI) {
Andrew Tricke9162f12011-10-05 05:58:49 +00005960 // Convenient constant check, but redundant for recursive calls.
Reid Spencer30d69a52004-07-18 00:18:30 +00005961 if (Constant *C = dyn_cast<Constant>(V)) return C;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005962 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00005963 if (!I) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005964
Andrew Trick3a86ba72011-10-05 03:25:31 +00005965 if (Constant *C = Vals.lookup(I)) return C;
5966
Nick Lewyckya6674c72011-10-22 19:58:20 +00005967 // An instruction inside the loop depends on a value outside the loop that we
5968 // weren't given a mapping for, or a value such as a call inside the loop.
Craig Topper9f008862014-04-15 04:59:12 +00005969 if (!canConstantEvolve(I, L)) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005970
5971 // An unmapped PHI can be due to a branch or another loop inside this loop,
5972 // or due to this not being the initial iteration through a loop where we
5973 // couldn't compute the evolution of this particular PHI last time.
Craig Topper9f008862014-04-15 04:59:12 +00005974 if (isa<PHINode>(I)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00005975
Dan Gohmanf820bd32010-06-22 13:15:46 +00005976 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattnerdd730472004-04-17 22:58:41 +00005977
5978 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Andrew Tricke9162f12011-10-05 05:58:49 +00005979 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
5980 if (!Operand) {
Nick Lewyckya447e0f32011-10-14 09:38:46 +00005981 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00005982 if (!Operands[i]) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00005983 continue;
5984 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005985 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Andrew Tricke9162f12011-10-05 05:58:49 +00005986 Vals[Operand] = C;
Craig Topper9f008862014-04-15 04:59:12 +00005987 if (!C) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00005988 Operands[i] = C;
Chris Lattnerdd730472004-04-17 22:58:41 +00005989 }
5990
Nick Lewyckya6674c72011-10-22 19:58:20 +00005991 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00005992 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005993 Operands[1], DL, TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005994 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5995 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00005996 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005997 }
Manuel Jacobe9024592016-01-21 06:33:22 +00005998 return ConstantFoldInstOperands(I, Operands, DL, TLI);
Chris Lattnerdd730472004-04-17 22:58:41 +00005999}
6000
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006001
6002// If every incoming value to PN except the one for BB is a specific Constant,
6003// return that, else return nullptr.
6004static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6005 Constant *IncomingVal = nullptr;
6006
6007 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6008 if (PN->getIncomingBlock(i) == BB)
6009 continue;
6010
6011 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6012 if (!CurrentVal)
6013 return nullptr;
6014
6015 if (IncomingVal != CurrentVal) {
6016 if (IncomingVal)
6017 return nullptr;
6018 IncomingVal = CurrentVal;
6019 }
6020 }
6021
6022 return IncomingVal;
6023}
6024
Chris Lattnerdd730472004-04-17 22:58:41 +00006025/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6026/// in the header of its containing loop, we know the loop executes a
6027/// constant number of times, and the PHI node is just a recurrence
6028/// involving constants, fold it.
Dan Gohmance973df2009-06-24 04:48:43 +00006029Constant *
6030ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohmancb0efec2009-12-18 01:14:11 +00006031 const APInt &BEs,
Dan Gohmance973df2009-06-24 04:48:43 +00006032 const Loop *L) {
Sanjoy Das4493b402015-10-07 17:38:25 +00006033 auto I = ConstantEvolutionLoopExitValue.find(PN);
Chris Lattnerdd730472004-04-17 22:58:41 +00006034 if (I != ConstantEvolutionLoopExitValue.end())
6035 return I->second;
6036
Dan Gohman4ce1fb12010-04-08 23:03:40 +00006037 if (BEs.ugt(MaxBruteForceIterations))
Craig Topper9f008862014-04-15 04:59:12 +00006038 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
Chris Lattnerdd730472004-04-17 22:58:41 +00006039
6040 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6041
Andrew Trick3a86ba72011-10-05 03:25:31 +00006042 DenseMap<Instruction *, Constant *> CurrentIterVals;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006043 BasicBlock *Header = L->getHeader();
6044 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
Andrew Trick3a86ba72011-10-05 03:25:31 +00006045
Sanjoy Dasdd709962015-10-08 18:28:36 +00006046 BasicBlock *Latch = L->getLoopLatch();
6047 if (!Latch)
6048 return nullptr;
6049
Sanjoy Das4493b402015-10-07 17:38:25 +00006050 for (auto &I : *Header) {
6051 PHINode *PHI = dyn_cast<PHINode>(&I);
6052 if (!PHI) break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006053 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006054 if (!StartCST) continue;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006055 CurrentIterVals[PHI] = StartCST;
6056 }
6057 if (!CurrentIterVals.count(PN))
Craig Topper9f008862014-04-15 04:59:12 +00006058 return RetVal = nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006059
Sanjoy Dasdd709962015-10-08 18:28:36 +00006060 Value *BEValue = PN->getIncomingValueForBlock(Latch);
Chris Lattnerdd730472004-04-17 22:58:41 +00006061
6062 // Execute the loop symbolically to determine the exit value.
Dan Gohman0bddac12009-02-24 18:55:53 +00006063 if (BEs.getActiveBits() >= 32)
Craig Topper9f008862014-04-15 04:59:12 +00006064 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
Chris Lattnerdd730472004-04-17 22:58:41 +00006065
Dan Gohman0bddac12009-02-24 18:55:53 +00006066 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencer983e3b32007-03-01 07:25:48 +00006067 unsigned IterationNum = 0;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006068 const DataLayout &DL = getDataLayout();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006069 for (; ; ++IterationNum) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006070 if (IterationNum == NumIterations)
Andrew Trick3a86ba72011-10-05 03:25:31 +00006071 return RetVal = CurrentIterVals[PN]; // Got exit value!
Chris Lattnerdd730472004-04-17 22:58:41 +00006072
Nick Lewyckya6674c72011-10-22 19:58:20 +00006073 // Compute the value of the PHIs for the next iteration.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006074 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006075 DenseMap<Instruction *, Constant *> NextIterVals;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006076 Constant *NextPHI =
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006077 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Craig Topper9f008862014-04-15 04:59:12 +00006078 if (!NextPHI)
6079 return nullptr; // Couldn't evaluate!
Andrew Trick3a86ba72011-10-05 03:25:31 +00006080 NextIterVals[PN] = NextPHI;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006081
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006082 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6083
Nick Lewyckya6674c72011-10-22 19:58:20 +00006084 // Also evaluate the other PHI nodes. However, we don't get to stop if we
6085 // cease to be able to evaluate one of them or if they stop evolving,
6086 // because that doesn't necessarily prevent us from computing PN.
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006087 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006088 for (const auto &I : CurrentIterVals) {
6089 PHINode *PHI = dyn_cast<PHINode>(I.first);
Nick Lewycky8e904de2011-10-24 05:51:01 +00006090 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
Sanjoy Das4493b402015-10-07 17:38:25 +00006091 PHIsToCompute.emplace_back(PHI, I.second);
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006092 }
6093 // We use two distinct loops because EvaluateExpression may invalidate any
6094 // iterators into CurrentIterVals.
Sanjoy Das4493b402015-10-07 17:38:25 +00006095 for (const auto &I : PHIsToCompute) {
6096 PHINode *PHI = I.first;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006097 Constant *&NextPHI = NextIterVals[PHI];
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006098 if (!NextPHI) { // Not already computed.
Sanjoy Dasdd709962015-10-08 18:28:36 +00006099 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006100 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006101 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006102 if (NextPHI != I.second)
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006103 StoppedEvolving = false;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006104 }
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006105
6106 // If all entries in CurrentIterVals == NextIterVals then we can stop
6107 // iterating, the loop can't continue to change.
6108 if (StoppedEvolving)
6109 return RetVal = CurrentIterVals[PN];
6110
Andrew Trick3a86ba72011-10-05 03:25:31 +00006111 CurrentIterVals.swap(NextIterVals);
Chris Lattnerdd730472004-04-17 22:58:41 +00006112 }
6113}
6114
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006115const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
Nick Lewyckya6674c72011-10-22 19:58:20 +00006116 Value *Cond,
6117 bool ExitWhen) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006118 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Craig Topper9f008862014-04-15 04:59:12 +00006119 if (!PN) return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006120
Dan Gohman866971e2010-06-19 14:17:24 +00006121 // If the loop is canonicalized, the PHI will have exactly two entries.
6122 // That's the only form we support here.
6123 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6124
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006125 DenseMap<Instruction *, Constant *> CurrentIterVals;
6126 BasicBlock *Header = L->getHeader();
6127 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6128
Sanjoy Dasdd709962015-10-08 18:28:36 +00006129 BasicBlock *Latch = L->getLoopLatch();
6130 assert(Latch && "Should follow from NumIncomingValues == 2!");
6131
Sanjoy Das4493b402015-10-07 17:38:25 +00006132 for (auto &I : *Header) {
6133 PHINode *PHI = dyn_cast<PHINode>(&I);
6134 if (!PHI)
6135 break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006136 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006137 if (!StartCST) continue;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006138 CurrentIterVals[PHI] = StartCST;
6139 }
6140 if (!CurrentIterVals.count(PN))
6141 return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006142
6143 // Okay, we find a PHI node that defines the trip count of this loop. Execute
6144 // the loop symbolically to determine when the condition gets a value of
6145 // "ExitWhen".
Andrew Trick90c7a102011-11-16 00:52:40 +00006146 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006147 const DataLayout &DL = getDataLayout();
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006148 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
Sanjoy Das4493b402015-10-07 17:38:25 +00006149 auto *CondVal = dyn_cast_or_null<ConstantInt>(
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006150 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
Chris Lattnerdd730472004-04-17 22:58:41 +00006151
Zhou Sheng75b871f2007-01-11 12:24:14 +00006152 // Couldn't symbolically evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006153 if (!CondVal) return getCouldNotCompute();
Zhou Sheng75b871f2007-01-11 12:24:14 +00006154
Reid Spencer983e3b32007-03-01 07:25:48 +00006155 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006156 ++NumBruteForceTripCountsComputed;
Owen Anderson55f1c092009-08-13 21:58:54 +00006157 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006158 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006159
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006160 // Update all the PHI nodes for the next iteration.
6161 DenseMap<Instruction *, Constant *> NextIterVals;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006162
6163 // Create a list of which PHIs we need to compute. We want to do this before
6164 // calling EvaluateExpression on them because that may invalidate iterators
6165 // into CurrentIterVals.
6166 SmallVector<PHINode *, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006167 for (const auto &I : CurrentIterVals) {
6168 PHINode *PHI = dyn_cast<PHINode>(I.first);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006169 if (!PHI || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006170 PHIsToCompute.push_back(PHI);
6171 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006172 for (PHINode *PHI : PHIsToCompute) {
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006173 Constant *&NextPHI = NextIterVals[PHI];
6174 if (NextPHI) continue; // Already computed!
6175
Sanjoy Dasdd709962015-10-08 18:28:36 +00006176 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006177 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006178 }
6179 CurrentIterVals.swap(NextIterVals);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006180 }
6181
6182 // Too many iterations were needed to evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006183 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006184}
6185
Dan Gohman237d9e52009-09-03 15:00:26 +00006186/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohmanb81f47d2009-05-08 20:38:54 +00006187/// at the specified scope in the program. The L value specifies a loop
6188/// nest to evaluate the expression at, where null is the top-level or a
6189/// specified loop is immediately inside of the loop.
6190///
6191/// This method can be used to compute the exit value for a variable defined
6192/// in a loop by querying what the value will hold in the parent loop.
6193///
Dan Gohman8ca08852009-05-24 23:25:42 +00006194/// In the case that a relevant loop exit value cannot be computed, the
6195/// original value V is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00006196const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Sanjoy Das01947432015-11-22 21:20:13 +00006197 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6198 ValuesAtScopes[V];
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006199 // Check to see if we've folded this expression at this loop before.
Sanjoy Das01947432015-11-22 21:20:13 +00006200 for (auto &LS : Values)
6201 if (LS.first == L)
6202 return LS.second ? LS.second : V;
6203
6204 Values.emplace_back(L, nullptr);
6205
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006206 // Otherwise compute it.
6207 const SCEV *C = computeSCEVAtScope(V, L);
Sanjoy Das01947432015-11-22 21:20:13 +00006208 for (auto &LS : reverse(ValuesAtScopes[V]))
6209 if (LS.first == L) {
6210 LS.second = C;
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00006211 break;
6212 }
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006213 return C;
6214}
6215
Nick Lewyckya6674c72011-10-22 19:58:20 +00006216/// This builds up a Constant using the ConstantExpr interface. That way, we
6217/// will return Constants for objects which aren't represented by a
6218/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6219/// Returns NULL if the SCEV isn't representable as a Constant.
6220static Constant *BuildConstantFromSCEV(const SCEV *V) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00006221 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
Nick Lewyckya6674c72011-10-22 19:58:20 +00006222 case scCouldNotCompute:
6223 case scAddRecExpr:
6224 break;
6225 case scConstant:
6226 return cast<SCEVConstant>(V)->getValue();
6227 case scUnknown:
6228 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6229 case scSignExtend: {
6230 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6231 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6232 return ConstantExpr::getSExt(CastOp, SS->getType());
6233 break;
6234 }
6235 case scZeroExtend: {
6236 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6237 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6238 return ConstantExpr::getZExt(CastOp, SZ->getType());
6239 break;
6240 }
6241 case scTruncate: {
6242 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6243 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6244 return ConstantExpr::getTrunc(CastOp, ST->getType());
6245 break;
6246 }
6247 case scAddExpr: {
6248 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6249 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006250 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6251 unsigned AS = PTy->getAddressSpace();
6252 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6253 C = ConstantExpr::getBitCast(C, DestPtrTy);
6254 }
Nick Lewyckya6674c72011-10-22 19:58:20 +00006255 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6256 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006257 if (!C2) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006258
6259 // First pointer!
6260 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006261 unsigned AS = C2->getType()->getPointerAddressSpace();
Nick Lewyckya6674c72011-10-22 19:58:20 +00006262 std::swap(C, C2);
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006263 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006264 // The offsets have been converted to bytes. We can add bytes to an
6265 // i8* by GEP with the byte count in the first index.
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006266 C = ConstantExpr::getBitCast(C, DestPtrTy);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006267 }
6268
6269 // Don't bother trying to sum two pointers. We probably can't
6270 // statically compute a load that results from it anyway.
6271 if (C2->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +00006272 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006273
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006274 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6275 if (PTy->getElementType()->isStructTy())
Nick Lewyckya6674c72011-10-22 19:58:20 +00006276 C2 = ConstantExpr::getIntegerCast(
6277 C2, Type::getInt32Ty(C->getContext()), true);
David Blaikie4a2e73b2015-04-02 18:55:32 +00006278 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006279 } else
6280 C = ConstantExpr::getAdd(C, C2);
6281 }
6282 return C;
6283 }
6284 break;
6285 }
6286 case scMulExpr: {
6287 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6288 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6289 // Don't bother with pointers at all.
Craig Topper9f008862014-04-15 04:59:12 +00006290 if (C->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006291 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6292 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006293 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006294 C = ConstantExpr::getMul(C, C2);
6295 }
6296 return C;
6297 }
6298 break;
6299 }
6300 case scUDivExpr: {
6301 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6302 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6303 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6304 if (LHS->getType() == RHS->getType())
6305 return ConstantExpr::getUDiv(LHS, RHS);
6306 break;
6307 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00006308 case scSMaxExpr:
6309 case scUMaxExpr:
6310 break; // TODO: smax, umax.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006311 }
Craig Topper9f008862014-04-15 04:59:12 +00006312 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006313}
6314
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006315const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006316 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00006317
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006318 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattnerdd730472004-04-17 22:58:41 +00006319 // exit value from the loop without using SCEVs.
Dan Gohmana30370b2009-05-04 22:02:23 +00006320 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006321 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006322 const Loop *LI = this->LI[I->getParent()];
Chris Lattnerdd730472004-04-17 22:58:41 +00006323 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
6324 if (PHINode *PN = dyn_cast<PHINode>(I))
6325 if (PN->getParent() == LI->getHeader()) {
6326 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman0bddac12009-02-24 18:55:53 +00006327 // to see if the loop that contains it has a known backedge-taken
6328 // count. If so, we may be able to force computation of the exit
6329 // value.
Dan Gohmanaf752342009-07-07 17:06:11 +00006330 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmana30370b2009-05-04 22:02:23 +00006331 if (const SCEVConstant *BTCC =
Dan Gohman0bddac12009-02-24 18:55:53 +00006332 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006333 // Okay, we know how many times the containing loop executes. If
6334 // this is a constant evolving PHI node, get the final value at
6335 // the specified iteration number.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006336 Constant *RV =
6337 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
Dan Gohman9d203c62009-06-29 21:31:18 +00006338 if (RV) return getSCEV(RV);
Chris Lattnerdd730472004-04-17 22:58:41 +00006339 }
6340 }
6341
Reid Spencere6328ca2006-12-04 21:33:23 +00006342 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattnerdd730472004-04-17 22:58:41 +00006343 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencere6328ca2006-12-04 21:33:23 +00006344 // the arguments into constants, and if so, try to constant propagate the
Chris Lattnerdd730472004-04-17 22:58:41 +00006345 // result. This is particularly useful for computing loop exit values.
6346 if (CanConstantFold(I)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006347 SmallVector<Constant *, 4> Operands;
6348 bool MadeImprovement = false;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00006349 for (Value *Op : I->operands()) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006350 if (Constant *C = dyn_cast<Constant>(Op)) {
6351 Operands.push_back(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006352 continue;
Chris Lattnerdd730472004-04-17 22:58:41 +00006353 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006354
6355 // If any of the operands is non-constant and if they are
6356 // non-integer and non-pointer, don't even try to analyze them
6357 // with scev techniques.
6358 if (!isSCEVable(Op->getType()))
6359 return V;
6360
6361 const SCEV *OrigV = getSCEV(Op);
6362 const SCEV *OpV = getSCEVAtScope(OrigV, L);
6363 MadeImprovement |= OrigV != OpV;
6364
Nick Lewyckya6674c72011-10-22 19:58:20 +00006365 Constant *C = BuildConstantFromSCEV(OpV);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006366 if (!C) return V;
6367 if (C->getType() != Op->getType())
6368 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
6369 Op->getType(),
6370 false),
6371 C, Op->getType());
6372 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00006373 }
Dan Gohmance973df2009-06-24 04:48:43 +00006374
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006375 // Check to see if getSCEVAtScope actually made an improvement.
6376 if (MadeImprovement) {
Craig Topper9f008862014-04-15 04:59:12 +00006377 Constant *C = nullptr;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006378 const DataLayout &DL = getDataLayout();
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006379 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006380 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006381 Operands[1], DL, &TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006382 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
6383 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006384 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006385 } else
Manuel Jacobe9024592016-01-21 06:33:22 +00006386 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006387 if (!C) return V;
Dan Gohman4aad7502010-02-24 19:31:47 +00006388 return getSCEV(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006389 }
Chris Lattnerdd730472004-04-17 22:58:41 +00006390 }
6391 }
6392
6393 // This is some other type of SCEVUnknown, just return it.
6394 return V;
6395 }
6396
Dan Gohmana30370b2009-05-04 22:02:23 +00006397 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006398 // Avoid performing the look-up in the common case where the specified
6399 // expression has no loop-variant portions.
6400 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006401 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006402 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006403 // Okay, at least one of these operands is loop variant but might be
6404 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmance973df2009-06-24 04:48:43 +00006405 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
6406 Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00006407 NewOps.push_back(OpAtScope);
6408
6409 for (++i; i != e; ++i) {
6410 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006411 NewOps.push_back(OpAtScope);
6412 }
6413 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006414 return getAddExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006415 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006416 return getMulExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006417 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006418 return getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006419 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006420 return getUMaxExpr(NewOps);
Torok Edwinfbcc6632009-07-14 16:55:14 +00006421 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00006422 }
6423 }
6424 // If we got here, all operands are loop invariant.
6425 return Comm;
6426 }
6427
Dan Gohmana30370b2009-05-04 22:02:23 +00006428 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006429 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
6430 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky52348302009-01-13 09:18:58 +00006431 if (LHS == Div->getLHS() && RHS == Div->getRHS())
6432 return Div; // must be loop invariant
Dan Gohmanc8e23622009-04-21 23:15:49 +00006433 return getUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00006434 }
6435
6436 // If this is a loop recurrence for a loop that does not contain L, then we
6437 // are dealing with the final value computed by the loop.
Dan Gohmana30370b2009-05-04 22:02:23 +00006438 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006439 // First, attempt to evaluate each operand.
6440 // Avoid performing the look-up in the common case where the specified
6441 // expression has no loop-variant portions.
6442 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
6443 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
6444 if (OpAtScope == AddRec->getOperand(i))
6445 continue;
6446
6447 // Okay, at least one of these operands is loop variant but might be
6448 // foldable. Build a new instance of the folded commutative expression.
6449 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
6450 AddRec->op_begin()+i);
6451 NewOps.push_back(OpAtScope);
6452 for (++i; i != e; ++i)
6453 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
6454
Andrew Trick759ba082011-04-27 01:21:25 +00006455 const SCEV *FoldedRec =
Andrew Trick8b55b732011-03-14 16:50:06 +00006456 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick759ba082011-04-27 01:21:25 +00006457 AddRec->getNoWrapFlags(SCEV::FlagNW));
6458 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick01eff822011-04-27 05:42:17 +00006459 // The addrec may be folded to a nonrecurrence, for example, if the
6460 // induction variable is multiplied by zero after constant folding. Go
6461 // ahead and return the folded value.
Andrew Trick759ba082011-04-27 01:21:25 +00006462 if (!AddRec)
6463 return FoldedRec;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006464 break;
6465 }
6466
6467 // If the scope is outside the addrec's loop, evaluate it by using the
6468 // loop exit value of the addrec.
6469 if (!AddRec->getLoop()->contains(L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006470 // To evaluate this recurrence, we need to know how many times the AddRec
6471 // loop iterates. Compute this now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006472 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006473 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman01808ca2005-04-21 21:13:18 +00006474
Eli Friedman61f67622008-08-04 23:49:06 +00006475 // Then, evaluate the AddRec.
Dan Gohmanc8e23622009-04-21 23:15:49 +00006476 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattnerd934c702004-04-02 20:23:17 +00006477 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006478
Dan Gohman8ca08852009-05-24 23:25:42 +00006479 return AddRec;
Chris Lattnerd934c702004-04-02 20:23:17 +00006480 }
6481
Dan Gohmana30370b2009-05-04 22:02:23 +00006482 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006483 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006484 if (Op == Cast->getOperand())
6485 return Cast; // must be loop invariant
6486 return getZeroExtendExpr(Op, Cast->getType());
6487 }
6488
Dan Gohmana30370b2009-05-04 22:02:23 +00006489 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006490 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006491 if (Op == Cast->getOperand())
6492 return Cast; // must be loop invariant
6493 return getSignExtendExpr(Op, Cast->getType());
6494 }
6495
Dan Gohmana30370b2009-05-04 22:02:23 +00006496 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006497 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006498 if (Op == Cast->getOperand())
6499 return Cast; // must be loop invariant
6500 return getTruncateExpr(Op, Cast->getType());
6501 }
6502
Torok Edwinfbcc6632009-07-14 16:55:14 +00006503 llvm_unreachable("Unknown SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00006504}
6505
Dan Gohmanb81f47d2009-05-08 20:38:54 +00006506/// getSCEVAtScope - This is a convenience function which does
6507/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanaf752342009-07-07 17:06:11 +00006508const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00006509 return getSCEVAtScope(getSCEV(V), L);
6510}
6511
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006512/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
6513/// following equation:
6514///
6515/// A * X = B (mod N)
6516///
6517/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
6518/// A and B isn't important.
6519///
6520/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00006521static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006522 ScalarEvolution &SE) {
6523 uint32_t BW = A.getBitWidth();
6524 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
6525 assert(A != 0 && "A must be non-zero.");
6526
6527 // 1. D = gcd(A, N)
6528 //
6529 // The gcd of A and N may have only one prime factor: 2. The number of
6530 // trailing zeros in A is its multiplicity
6531 uint32_t Mult2 = A.countTrailingZeros();
6532 // D = 2^Mult2
6533
6534 // 2. Check if B is divisible by D.
6535 //
6536 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
6537 // is not less than multiplicity of this prime factor for D.
6538 if (B.countTrailingZeros() < Mult2)
Dan Gohman31efa302009-04-18 17:58:19 +00006539 return SE.getCouldNotCompute();
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006540
6541 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
6542 // modulo (N / D).
6543 //
6544 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
6545 // bit width during computations.
6546 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
6547 APInt Mod(BW + 1, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00006548 Mod.setBit(BW - Mult2); // Mod = N / D
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006549 APInt I = AD.multiplicativeInverse(Mod);
6550
6551 // 4. Compute the minimum unsigned root of the equation:
6552 // I * (B / D) mod (N / D)
6553 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
6554
6555 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
6556 // bits.
6557 return SE.getConstant(Result.trunc(BW));
6558}
Chris Lattnerd934c702004-04-02 20:23:17 +00006559
6560/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
6561/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
6562/// might be the same) or two SCEVCouldNotCompute objects.
6563///
Dan Gohmanaf752342009-07-07 17:06:11 +00006564static std::pair<const SCEV *,const SCEV *>
Dan Gohmana37eaf22007-10-22 18:31:58 +00006565SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006566 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman48f82222009-05-04 22:30:44 +00006567 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
6568 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
6569 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00006570
Chris Lattnerd934c702004-04-02 20:23:17 +00006571 // We currently can only solve this if the coefficients are constants.
Reid Spencer983e3b32007-03-01 07:25:48 +00006572 if (!LC || !MC || !NC) {
Dan Gohman48f82222009-05-04 22:30:44 +00006573 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006574 return std::make_pair(CNC, CNC);
6575 }
6576
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006577 uint32_t BitWidth = LC->getAPInt().getBitWidth();
6578 const APInt &L = LC->getAPInt();
6579 const APInt &M = MC->getAPInt();
6580 const APInt &N = NC->getAPInt();
Reid Spencer983e3b32007-03-01 07:25:48 +00006581 APInt Two(BitWidth, 2);
6582 APInt Four(BitWidth, 4);
Misha Brukman01808ca2005-04-21 21:13:18 +00006583
Dan Gohmance973df2009-06-24 04:48:43 +00006584 {
Reid Spencer983e3b32007-03-01 07:25:48 +00006585 using namespace APIntOps;
Zhou Sheng2852d992007-04-07 17:48:27 +00006586 const APInt& C = L;
Reid Spencer983e3b32007-03-01 07:25:48 +00006587 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
6588 // The B coefficient is M-N/2
6589 APInt B(M);
6590 B -= sdiv(N,Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00006591
Reid Spencer983e3b32007-03-01 07:25:48 +00006592 // The A coefficient is N/2
Zhou Sheng2852d992007-04-07 17:48:27 +00006593 APInt A(N.sdiv(Two));
Chris Lattnerd934c702004-04-02 20:23:17 +00006594
Reid Spencer983e3b32007-03-01 07:25:48 +00006595 // Compute the B^2-4ac term.
6596 APInt SqrtTerm(B);
6597 SqrtTerm *= B;
6598 SqrtTerm -= Four * (A * C);
Chris Lattnerd934c702004-04-02 20:23:17 +00006599
Nick Lewyckyfb780832012-08-01 09:14:36 +00006600 if (SqrtTerm.isNegative()) {
6601 // The loop is provably infinite.
6602 const SCEV *CNC = SE.getCouldNotCompute();
6603 return std::make_pair(CNC, CNC);
6604 }
6605
Reid Spencer983e3b32007-03-01 07:25:48 +00006606 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
6607 // integer value or else APInt::sqrt() will assert.
6608 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman01808ca2005-04-21 21:13:18 +00006609
Dan Gohmance973df2009-06-24 04:48:43 +00006610 // Compute the two solutions for the quadratic formula.
Reid Spencer983e3b32007-03-01 07:25:48 +00006611 // The divisions must be performed as signed divisions.
6612 APInt NegB(-B);
Nick Lewycky31555522011-10-03 07:10:45 +00006613 APInt TwoA(A << 1);
Nick Lewycky7b14e202008-11-03 02:43:49 +00006614 if (TwoA.isMinValue()) {
Dan Gohman48f82222009-05-04 22:30:44 +00006615 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky7b14e202008-11-03 02:43:49 +00006616 return std::make_pair(CNC, CNC);
6617 }
6618
Owen Anderson47db9412009-07-22 00:24:57 +00006619 LLVMContext &Context = SE.getContext();
Owen Andersonf1f17432009-07-06 22:37:39 +00006620
6621 ConstantInt *Solution1 =
Owen Andersonedb4a702009-07-24 23:12:02 +00006622 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Andersonf1f17432009-07-06 22:37:39 +00006623 ConstantInt *Solution2 =
Owen Andersonedb4a702009-07-24 23:12:02 +00006624 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman01808ca2005-04-21 21:13:18 +00006625
Dan Gohmance973df2009-06-24 04:48:43 +00006626 return std::make_pair(SE.getConstant(Solution1),
Dan Gohmana37eaf22007-10-22 18:31:58 +00006627 SE.getConstant(Solution2));
Nick Lewycky31555522011-10-03 07:10:45 +00006628 } // end APIntOps namespace
Chris Lattnerd934c702004-04-02 20:23:17 +00006629}
6630
6631/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman4c720c02009-06-06 14:37:11 +00006632/// value to zero will execute. If not computable, return CouldNotCompute.
Andrew Trick8b55b732011-03-14 16:50:06 +00006633///
6634/// This is only used for loops with a "x != y" exit test. The exit condition is
6635/// now expressed as a single expression, V = x-y. So the exit test is
6636/// effectively V != 0. We know and take advantage of the fact that this
6637/// expression only being used in a comparison by zero context.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006638ScalarEvolution::ExitLimit
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006639ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool ControlsExit) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006640 // If the value is a constant
Dan Gohmana30370b2009-05-04 22:02:23 +00006641 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006642 // If the value is already zero, the branch will execute zero times.
Reid Spencer2e54a152007-03-02 00:28:52 +00006643 if (C->getValue()->isZero()) return C;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006644 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00006645 }
6646
Dan Gohman48f82222009-05-04 22:30:44 +00006647 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00006648 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006649 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006650
Chris Lattnerdff679f2011-01-09 22:39:48 +00006651 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
6652 // the quadratic equation to solve it.
6653 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
6654 std::pair<const SCEV *,const SCEV *> Roots =
6655 SolveQuadraticEquation(AddRec, *this);
Dan Gohman48f82222009-05-04 22:30:44 +00006656 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
6657 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattnerdff679f2011-01-09 22:39:48 +00006658 if (R1 && R2) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006659 // Pick the smallest positive root value.
Zhou Sheng75b871f2007-01-11 12:24:14 +00006660 if (ConstantInt *CB =
Chris Lattner28f140a2011-01-09 22:58:47 +00006661 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
6662 R1->getValue(),
6663 R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00006664 if (!CB->getZExtValue())
Chris Lattnerd934c702004-04-02 20:23:17 +00006665 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick2a3b7162011-03-09 17:23:39 +00006666
Chris Lattnerd934c702004-04-02 20:23:17 +00006667 // We can only use this value if the chrec ends up with an exact zero
6668 // value at this index. When solving for "X*X != 5", for example, we
6669 // should not accept a root of 2.
Dan Gohmanaf752342009-07-07 17:06:11 +00006670 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmanbe928e32008-06-18 16:23:07 +00006671 if (Val->isZero())
6672 return R1; // We found a quadratic root!
Chris Lattnerd934c702004-04-02 20:23:17 +00006673 }
6674 }
Chris Lattnerdff679f2011-01-09 22:39:48 +00006675 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006676 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006677
Chris Lattnerdff679f2011-01-09 22:39:48 +00006678 // Otherwise we can only handle this if it is affine.
6679 if (!AddRec->isAffine())
6680 return getCouldNotCompute();
6681
6682 // If this is an affine expression, the execution count of this branch is
6683 // the minimum unsigned root of the following equation:
6684 //
6685 // Start + Step*N = 0 (mod 2^BW)
6686 //
6687 // equivalent to:
6688 //
6689 // Step*N = -Start (mod 2^BW)
6690 //
6691 // where BW is the common bit width of Start and Step.
6692
6693 // Get the initial value for the loop.
6694 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
6695 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
6696
6697 // For now we handle only constant steps.
Andrew Trick8b55b732011-03-14 16:50:06 +00006698 //
6699 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
6700 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
6701 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
6702 // We have not yet seen any such cases.
Chris Lattnerdff679f2011-01-09 22:39:48 +00006703 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
Craig Topper9f008862014-04-15 04:59:12 +00006704 if (!StepC || StepC->getValue()->equalsInt(0))
Chris Lattnerdff679f2011-01-09 22:39:48 +00006705 return getCouldNotCompute();
6706
Andrew Trick8b55b732011-03-14 16:50:06 +00006707 // For positive steps (counting up until unsigned overflow):
6708 // N = -Start/Step (as unsigned)
6709 // For negative steps (counting down to zero):
6710 // N = Start/-Step
6711 // First compute the unsigned distance from zero in the direction of Step.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006712 bool CountDown = StepC->getAPInt().isNegative();
Andrew Trickf1781db2011-03-14 17:28:02 +00006713 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick8b55b732011-03-14 16:50:06 +00006714
6715 // Handle unitary steps, which cannot wraparound.
Andrew Trickf1781db2011-03-14 17:28:02 +00006716 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
6717 // N = Distance (as unsigned)
Nick Lewycky31555522011-10-03 07:10:45 +00006718 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
6719 ConstantRange CR = getUnsignedRange(Start);
6720 const SCEV *MaxBECount;
6721 if (!CountDown && CR.getUnsignedMin().isMinValue())
6722 // When counting up, the worst starting value is 1, not 0.
6723 MaxBECount = CR.getUnsignedMax().isMinValue()
6724 ? getConstant(APInt::getMinValue(CR.getBitWidth()))
6725 : getConstant(APInt::getMaxValue(CR.getBitWidth()));
6726 else
6727 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
6728 : -CR.getUnsignedMin());
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006729 return ExitLimit(Distance, MaxBECount);
Nick Lewycky31555522011-10-03 07:10:45 +00006730 }
Andrew Trick2a3b7162011-03-09 17:23:39 +00006731
Mark Heffernanacbed5e2014-12-15 21:19:53 +00006732 // As a special case, handle the instance where Step is a positive power of
6733 // two. In this case, determining whether Step divides Distance evenly can be
6734 // done by counting and comparing the number of trailing zeros of Step and
6735 // Distance.
6736 if (!CountDown) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006737 const APInt &StepV = StepC->getAPInt();
Mark Heffernanacbed5e2014-12-15 21:19:53 +00006738 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It
6739 // also returns true if StepV is maximally negative (eg, INT_MIN), but that
6740 // case is not handled as this code is guarded by !CountDown.
6741 if (StepV.isPowerOf2() &&
Sanjoy Dasf3132d32015-09-10 05:27:38 +00006742 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) {
6743 // Here we've constrained the equation to be of the form
6744 //
6745 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0)
6746 //
6747 // where we're operating on a W bit wide integer domain and k is
6748 // non-negative. The smallest unsigned solution for X is the trip count.
6749 //
6750 // (0) is equivalent to:
6751 //
6752 // 2^(N + k) * Distance' - 2^N * X = L * 2^W
6753 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N
6754 // <=> 2^k * Distance' - X = L * 2^(W - N)
6755 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1)
6756 //
6757 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS
6758 // by 2^(W - N).
6759 //
6760 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2)
6761 //
6762 // E.g. say we're solving
6763 //
6764 // 2 * Val = 2 * X (in i8) ... (3)
6765 //
6766 // then from (2), we get X = Val URem i8 128 (k = 0 in this case).
6767 //
6768 // Note: It is tempting to solve (3) by setting X = Val, but Val is not
6769 // necessarily the smallest unsigned value of X that satisfies (3).
6770 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3)
6771 // is i8 1, not i8 -127
6772
6773 const auto *ModuloResult = getUDivExactExpr(Distance, Step);
6774
6775 // Since SCEV does not have a URem node, we construct one using a truncate
6776 // and a zero extend.
6777
6778 unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros();
6779 auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth);
6780 auto *WideTy = Distance->getType();
6781
6782 return getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy);
6783 }
Mark Heffernanacbed5e2014-12-15 21:19:53 +00006784 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00006785
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006786 // If the condition controls loop exit (the loop exits only if the expression
6787 // is true) and the addition is no-wrap we can use unsigned divide to
6788 // compute the backedge count. In this case, the step may not divide the
6789 // distance, but we don't care because if the condition is "missed" the loop
6790 // will have undefined behavior due to wrapping.
6791 if (ControlsExit && AddRec->getNoWrapFlags(SCEV::FlagNW)) {
6792 const SCEV *Exact =
6793 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
6794 return ExitLimit(Exact, Exact);
6795 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00006796
Chris Lattnerdff679f2011-01-09 22:39:48 +00006797 // Then, try to solve the above equation provided that Start is constant.
6798 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006799 return SolveLinEquationWithOverflow(StepC->getAPInt(), -StartC->getAPInt(),
Chris Lattnerdff679f2011-01-09 22:39:48 +00006800 *this);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006801 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006802}
6803
6804/// HowFarToNonZero - Return the number of times a backedge checking the
6805/// specified value for nonzero will execute. If not computable, return
Dan Gohman4c720c02009-06-06 14:37:11 +00006806/// CouldNotCompute
Andrew Trick3ca3f982011-07-26 17:19:55 +00006807ScalarEvolution::ExitLimit
Dan Gohmanba820342010-02-24 17:31:30 +00006808ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006809 // Loops that look like: while (X == 0) are very strange indeed. We don't
6810 // handle them yet except for the trivial case. This could be expanded in the
6811 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00006812
Chris Lattnerd934c702004-04-02 20:23:17 +00006813 // If the value is a constant, check to see if it is known to be non-zero
6814 // already. If so, the backedge will execute zero times.
Dan Gohmana30370b2009-05-04 22:02:23 +00006815 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky5a3db142008-02-21 09:14:53 +00006816 if (!C->getValue()->isNullValue())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00006817 return getZero(C->getType());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006818 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00006819 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006820
Chris Lattnerd934c702004-04-02 20:23:17 +00006821 // We could implement others, but I really doubt anyone writes loops like
6822 // this, and if they did, they would already be constant folded.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006823 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006824}
6825
Dan Gohmanf9081a22008-09-15 22:18:04 +00006826/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
6827/// (which may not be an immediate predecessor) which has exactly one
6828/// successor from which BB is reachable, or null if no such block is
6829/// found.
6830///
Dan Gohman4e3c1132010-04-15 16:19:08 +00006831std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanc8e23622009-04-21 23:15:49 +00006832ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohmanfa066ef2009-04-30 20:48:53 +00006833 // If the block has a unique predecessor, then there is no path from the
6834 // predecessor to the block that does not go through the direct edge
6835 // from the predecessor to the block.
Dan Gohmanf9081a22008-09-15 22:18:04 +00006836 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman4e3c1132010-04-15 16:19:08 +00006837 return std::make_pair(Pred, BB);
Dan Gohmanf9081a22008-09-15 22:18:04 +00006838
6839 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman8c77f1a2009-05-18 15:36:09 +00006840 // If the header has a unique predecessor outside the loop, it must be
6841 // a block that has exactly one successor that can reach the loop.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006842 if (Loop *L = LI.getLoopFor(BB))
Dan Gohman75c6b0b2010-06-22 23:43:28 +00006843 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohmanf9081a22008-09-15 22:18:04 +00006844
Dan Gohman4e3c1132010-04-15 16:19:08 +00006845 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanf9081a22008-09-15 22:18:04 +00006846}
6847
Dan Gohman450f4e02009-06-20 00:35:32 +00006848/// HasSameValue - SCEV structural equivalence is usually sufficient for
6849/// testing whether two expressions are equal, however for the purposes of
6850/// looking for a condition guarding a loop, it can be useful to be a little
6851/// more general, since a front-end may have replicated the controlling
6852/// expression.
6853///
Dan Gohmanaf752342009-07-07 17:06:11 +00006854static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman450f4e02009-06-20 00:35:32 +00006855 // Quick check to see if they are the same SCEV.
6856 if (A == B) return true;
6857
Sanjoy Dasf1090b62015-09-27 21:09:48 +00006858 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
6859 // Not all instructions that are "identical" compute the same value. For
6860 // instance, two distinct alloca instructions allocating the same type are
6861 // identical and do not read memory; but compute distinct values.
6862 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
6863 };
6864
Dan Gohman450f4e02009-06-20 00:35:32 +00006865 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
6866 // two different instructions with the same value. Check for this case.
6867 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
6868 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
6869 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
6870 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Sanjoy Dasf1090b62015-09-27 21:09:48 +00006871 if (ComputesEqualValues(AI, BI))
Dan Gohman450f4e02009-06-20 00:35:32 +00006872 return true;
6873
6874 // Otherwise assume they may have a different value.
6875 return false;
6876}
6877
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006878/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006879/// predicate Pred. Return true iff any changes were made.
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006880///
6881bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006882 const SCEV *&LHS, const SCEV *&RHS,
6883 unsigned Depth) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006884 bool Changed = false;
6885
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006886 // If we hit the max recursion limit bail out.
6887 if (Depth >= 3)
6888 return false;
6889
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006890 // Canonicalize a constant to the right side.
6891 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
6892 // Check for both operands constant.
6893 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
6894 if (ConstantExpr::getICmp(Pred,
6895 LHSC->getValue(),
6896 RHSC->getValue())->isNullValue())
6897 goto trivially_false;
6898 else
6899 goto trivially_true;
6900 }
6901 // Otherwise swap the operands to put the constant on the right.
6902 std::swap(LHS, RHS);
6903 Pred = ICmpInst::getSwappedPredicate(Pred);
6904 Changed = true;
6905 }
6906
6907 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohmandf564ca2010-05-03 17:00:11 +00006908 // addrec's loop, put the addrec on the left. Also make a dominance check,
6909 // as both operands could be addrecs loop-invariant in each other's loop.
6910 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
6911 const Loop *L = AR->getLoop();
Dan Gohman20d9ce22010-11-17 21:41:58 +00006912 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006913 std::swap(LHS, RHS);
6914 Pred = ICmpInst::getSwappedPredicate(Pred);
6915 Changed = true;
6916 }
Dan Gohmandf564ca2010-05-03 17:00:11 +00006917 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006918
6919 // If there's a constant operand, canonicalize comparisons with boundary
6920 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
6921 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006922 const APInt &RA = RC->getAPInt();
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006923 switch (Pred) {
6924 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6925 case ICmpInst::ICMP_EQ:
6926 case ICmpInst::ICMP_NE:
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006927 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
6928 if (!RA)
6929 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
6930 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
Benjamin Kramer406a2db2012-05-30 18:42:43 +00006931 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
6932 ME->getOperand(0)->isAllOnesValue()) {
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006933 RHS = AE->getOperand(1);
6934 LHS = ME->getOperand(1);
6935 Changed = true;
6936 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006937 break;
6938 case ICmpInst::ICMP_UGE:
6939 if ((RA - 1).isMinValue()) {
6940 Pred = ICmpInst::ICMP_NE;
6941 RHS = getConstant(RA - 1);
6942 Changed = true;
6943 break;
6944 }
6945 if (RA.isMaxValue()) {
6946 Pred = ICmpInst::ICMP_EQ;
6947 Changed = true;
6948 break;
6949 }
6950 if (RA.isMinValue()) goto trivially_true;
6951
6952 Pred = ICmpInst::ICMP_UGT;
6953 RHS = getConstant(RA - 1);
6954 Changed = true;
6955 break;
6956 case ICmpInst::ICMP_ULE:
6957 if ((RA + 1).isMaxValue()) {
6958 Pred = ICmpInst::ICMP_NE;
6959 RHS = getConstant(RA + 1);
6960 Changed = true;
6961 break;
6962 }
6963 if (RA.isMinValue()) {
6964 Pred = ICmpInst::ICMP_EQ;
6965 Changed = true;
6966 break;
6967 }
6968 if (RA.isMaxValue()) goto trivially_true;
6969
6970 Pred = ICmpInst::ICMP_ULT;
6971 RHS = getConstant(RA + 1);
6972 Changed = true;
6973 break;
6974 case ICmpInst::ICMP_SGE:
6975 if ((RA - 1).isMinSignedValue()) {
6976 Pred = ICmpInst::ICMP_NE;
6977 RHS = getConstant(RA - 1);
6978 Changed = true;
6979 break;
6980 }
6981 if (RA.isMaxSignedValue()) {
6982 Pred = ICmpInst::ICMP_EQ;
6983 Changed = true;
6984 break;
6985 }
6986 if (RA.isMinSignedValue()) goto trivially_true;
6987
6988 Pred = ICmpInst::ICMP_SGT;
6989 RHS = getConstant(RA - 1);
6990 Changed = true;
6991 break;
6992 case ICmpInst::ICMP_SLE:
6993 if ((RA + 1).isMaxSignedValue()) {
6994 Pred = ICmpInst::ICMP_NE;
6995 RHS = getConstant(RA + 1);
6996 Changed = true;
6997 break;
6998 }
6999 if (RA.isMinSignedValue()) {
7000 Pred = ICmpInst::ICMP_EQ;
7001 Changed = true;
7002 break;
7003 }
7004 if (RA.isMaxSignedValue()) goto trivially_true;
7005
7006 Pred = ICmpInst::ICMP_SLT;
7007 RHS = getConstant(RA + 1);
7008 Changed = true;
7009 break;
7010 case ICmpInst::ICMP_UGT:
7011 if (RA.isMinValue()) {
7012 Pred = ICmpInst::ICMP_NE;
7013 Changed = true;
7014 break;
7015 }
7016 if ((RA + 1).isMaxValue()) {
7017 Pred = ICmpInst::ICMP_EQ;
7018 RHS = getConstant(RA + 1);
7019 Changed = true;
7020 break;
7021 }
7022 if (RA.isMaxValue()) goto trivially_false;
7023 break;
7024 case ICmpInst::ICMP_ULT:
7025 if (RA.isMaxValue()) {
7026 Pred = ICmpInst::ICMP_NE;
7027 Changed = true;
7028 break;
7029 }
7030 if ((RA - 1).isMinValue()) {
7031 Pred = ICmpInst::ICMP_EQ;
7032 RHS = getConstant(RA - 1);
7033 Changed = true;
7034 break;
7035 }
7036 if (RA.isMinValue()) goto trivially_false;
7037 break;
7038 case ICmpInst::ICMP_SGT:
7039 if (RA.isMinSignedValue()) {
7040 Pred = ICmpInst::ICMP_NE;
7041 Changed = true;
7042 break;
7043 }
7044 if ((RA + 1).isMaxSignedValue()) {
7045 Pred = ICmpInst::ICMP_EQ;
7046 RHS = getConstant(RA + 1);
7047 Changed = true;
7048 break;
7049 }
7050 if (RA.isMaxSignedValue()) goto trivially_false;
7051 break;
7052 case ICmpInst::ICMP_SLT:
7053 if (RA.isMaxSignedValue()) {
7054 Pred = ICmpInst::ICMP_NE;
7055 Changed = true;
7056 break;
7057 }
7058 if ((RA - 1).isMinSignedValue()) {
7059 Pred = ICmpInst::ICMP_EQ;
7060 RHS = getConstant(RA - 1);
7061 Changed = true;
7062 break;
7063 }
7064 if (RA.isMinSignedValue()) goto trivially_false;
7065 break;
7066 }
7067 }
7068
7069 // Check for obvious equality.
7070 if (HasSameValue(LHS, RHS)) {
7071 if (ICmpInst::isTrueWhenEqual(Pred))
7072 goto trivially_true;
7073 if (ICmpInst::isFalseWhenEqual(Pred))
7074 goto trivially_false;
7075 }
7076
Dan Gohman81585c12010-05-03 16:35:17 +00007077 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7078 // adding or subtracting 1 from one of the operands.
7079 switch (Pred) {
7080 case ICmpInst::ICMP_SLE:
7081 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7082 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007083 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007084 Pred = ICmpInst::ICMP_SLT;
7085 Changed = true;
7086 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007087 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007088 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007089 Pred = ICmpInst::ICMP_SLT;
7090 Changed = true;
7091 }
7092 break;
7093 case ICmpInst::ICMP_SGE:
7094 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007095 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007096 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007097 Pred = ICmpInst::ICMP_SGT;
7098 Changed = true;
7099 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7100 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007101 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007102 Pred = ICmpInst::ICMP_SGT;
7103 Changed = true;
7104 }
7105 break;
7106 case ICmpInst::ICMP_ULE:
7107 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007108 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007109 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007110 Pred = ICmpInst::ICMP_ULT;
7111 Changed = true;
7112 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007113 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007114 Pred = ICmpInst::ICMP_ULT;
7115 Changed = true;
7116 }
7117 break;
7118 case ICmpInst::ICMP_UGE:
7119 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007120 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007121 Pred = ICmpInst::ICMP_UGT;
7122 Changed = true;
7123 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007124 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007125 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007126 Pred = ICmpInst::ICMP_UGT;
7127 Changed = true;
7128 }
7129 break;
7130 default:
7131 break;
7132 }
7133
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007134 // TODO: More simplifications are possible here.
7135
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007136 // Recursively simplify until we either hit a recursion limit or nothing
7137 // changes.
7138 if (Changed)
7139 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7140
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007141 return Changed;
7142
7143trivially_true:
7144 // Return 0 == 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007145 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007146 Pred = ICmpInst::ICMP_EQ;
7147 return true;
7148
7149trivially_false:
7150 // Return 0 != 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007151 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007152 Pred = ICmpInst::ICMP_NE;
7153 return true;
7154}
7155
Dan Gohmane65c9172009-07-13 21:35:55 +00007156bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7157 return getSignedRange(S).getSignedMax().isNegative();
7158}
7159
7160bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7161 return getSignedRange(S).getSignedMin().isStrictlyPositive();
7162}
7163
7164bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7165 return !getSignedRange(S).getSignedMin().isNegative();
7166}
7167
7168bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7169 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7170}
7171
7172bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7173 return isKnownNegative(S) || isKnownPositive(S);
7174}
7175
7176bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7177 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman36cce7e2010-04-24 01:38:36 +00007178 // Canonicalize the inputs first.
7179 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7180
Dan Gohman07591692010-04-11 22:16:48 +00007181 // If LHS or RHS is an addrec, check to see if the condition is true in
7182 // every iteration of the loop.
Justin Bognercbb84382014-05-23 00:06:56 +00007183 // If LHS and RHS are both addrec, both conditions must be true in
7184 // every iteration of the loop.
7185 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7186 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7187 bool LeftGuarded = false;
7188 bool RightGuarded = false;
7189 if (LAR) {
7190 const Loop *L = LAR->getLoop();
7191 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7192 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7193 if (!RAR) return true;
7194 LeftGuarded = true;
7195 }
7196 }
7197 if (RAR) {
7198 const Loop *L = RAR->getLoop();
7199 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7200 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7201 if (!LAR) return true;
7202 RightGuarded = true;
7203 }
7204 }
7205 if (LeftGuarded && RightGuarded)
7206 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007207
Sanjoy Das7d910f22015-10-02 18:50:30 +00007208 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7209 return true;
7210
Dan Gohman07591692010-04-11 22:16:48 +00007211 // Otherwise see what can be done with known constant ranges.
Sanjoy Das401e6312016-02-01 20:48:10 +00007212 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
Dan Gohman07591692010-04-11 22:16:48 +00007213}
7214
Sanjoy Das5dab2052015-07-27 21:42:49 +00007215bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7216 ICmpInst::Predicate Pred,
7217 bool &Increasing) {
7218 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7219
7220#ifndef NDEBUG
7221 // Verify an invariant: inverting the predicate should turn a monotonically
7222 // increasing change to a monotonically decreasing one, and vice versa.
7223 bool IncreasingSwapped;
7224 bool ResultSwapped = isMonotonicPredicateImpl(
7225 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7226
7227 assert(Result == ResultSwapped && "should be able to analyze both!");
7228 if (ResultSwapped)
7229 assert(Increasing == !IncreasingSwapped &&
7230 "monotonicity should flip as we flip the predicate");
7231#endif
7232
7233 return Result;
7234}
7235
7236bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7237 ICmpInst::Predicate Pred,
7238 bool &Increasing) {
Sanjoy Das5dab2052015-07-27 21:42:49 +00007239
7240 // A zero step value for LHS means the induction variable is essentially a
7241 // loop invariant value. We don't really depend on the predicate actually
7242 // flipping from false to true (for increasing predicates, and the other way
7243 // around for decreasing predicates), all we care about is that *if* the
7244 // predicate changes then it only changes from false to true.
7245 //
7246 // A zero step value in itself is not very useful, but there may be places
7247 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7248 // as general as possible.
7249
Sanjoy Das366acc12015-08-06 20:43:41 +00007250 switch (Pred) {
7251 default:
7252 return false; // Conservative answer
7253
7254 case ICmpInst::ICMP_UGT:
7255 case ICmpInst::ICMP_UGE:
7256 case ICmpInst::ICMP_ULT:
7257 case ICmpInst::ICMP_ULE:
7258 if (!LHS->getNoWrapFlags(SCEV::FlagNUW))
7259 return false;
7260
7261 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007262 return true;
Sanjoy Das366acc12015-08-06 20:43:41 +00007263
7264 case ICmpInst::ICMP_SGT:
7265 case ICmpInst::ICMP_SGE:
7266 case ICmpInst::ICMP_SLT:
7267 case ICmpInst::ICMP_SLE: {
7268 if (!LHS->getNoWrapFlags(SCEV::FlagNSW))
7269 return false;
7270
7271 const SCEV *Step = LHS->getStepRecurrence(*this);
7272
7273 if (isKnownNonNegative(Step)) {
7274 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7275 return true;
7276 }
7277
7278 if (isKnownNonPositive(Step)) {
7279 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7280 return true;
7281 }
7282
7283 return false;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007284 }
7285
Sanjoy Das5dab2052015-07-27 21:42:49 +00007286 }
7287
Sanjoy Das366acc12015-08-06 20:43:41 +00007288 llvm_unreachable("switch has default clause!");
Sanjoy Das5dab2052015-07-27 21:42:49 +00007289}
7290
7291bool ScalarEvolution::isLoopInvariantPredicate(
7292 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7293 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7294 const SCEV *&InvariantRHS) {
7295
7296 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7297 if (!isLoopInvariant(RHS, L)) {
7298 if (!isLoopInvariant(LHS, L))
7299 return false;
7300
7301 std::swap(LHS, RHS);
7302 Pred = ICmpInst::getSwappedPredicate(Pred);
7303 }
7304
7305 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7306 if (!ArLHS || ArLHS->getLoop() != L)
7307 return false;
7308
7309 bool Increasing;
7310 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7311 return false;
7312
7313 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7314 // true as the loop iterates, and the backedge is control dependent on
7315 // "ArLHS `Pred` RHS" == true then we can reason as follows:
7316 //
7317 // * if the predicate was false in the first iteration then the predicate
7318 // is never evaluated again, since the loop exits without taking the
7319 // backedge.
7320 // * if the predicate was true in the first iteration then it will
7321 // continue to be true for all future iterations since it is
7322 // monotonically increasing.
7323 //
7324 // For both the above possibilities, we can replace the loop varying
7325 // predicate with its value on the first iteration of the loop (which is
7326 // loop invariant).
7327 //
7328 // A similar reasoning applies for a monotonically decreasing predicate, by
7329 // replacing true with false and false with true in the above two bullets.
7330
7331 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7332
7333 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7334 return false;
7335
7336 InvariantPred = Pred;
7337 InvariantLHS = ArLHS->getStart();
7338 InvariantRHS = RHS;
7339 return true;
7340}
7341
Sanjoy Das401e6312016-02-01 20:48:10 +00007342bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7343 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00007344 if (HasSameValue(LHS, RHS))
7345 return ICmpInst::isTrueWhenEqual(Pred);
7346
Dan Gohman07591692010-04-11 22:16:48 +00007347 // This code is split out from isKnownPredicate because it is called from
7348 // within isLoopEntryGuardedByCond.
Dan Gohmane65c9172009-07-13 21:35:55 +00007349
Sanjoy Das4c7b6d72016-02-01 20:48:14 +00007350 auto CheckRanges =
7351 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7352 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7353 .contains(RangeLHS);
7354 };
7355
7356 // The check at the top of the function catches the case where the values are
7357 // known to be equal.
7358 if (Pred == CmpInst::ICMP_EQ)
7359 return false;
7360
7361 if (Pred == CmpInst::ICMP_NE)
7362 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7363 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7364 isKnownNonZero(getMinusSCEV(LHS, RHS));
7365
7366 if (CmpInst::isSigned(Pred))
7367 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7368
7369 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
Dan Gohmane65c9172009-07-13 21:35:55 +00007370}
7371
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007372bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7373 const SCEV *LHS,
7374 const SCEV *RHS) {
7375
7376 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7377 // Return Y via OutY.
7378 auto MatchBinaryAddToConst =
7379 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7380 SCEV::NoWrapFlags ExpectedFlags) {
7381 const SCEV *NonConstOp, *ConstOp;
7382 SCEV::NoWrapFlags FlagsPresent;
7383
7384 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7385 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7386 return false;
7387
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007388 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007389 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7390 };
7391
7392 APInt C;
7393
7394 switch (Pred) {
7395 default:
7396 break;
7397
7398 case ICmpInst::ICMP_SGE:
7399 std::swap(LHS, RHS);
7400 case ICmpInst::ICMP_SLE:
7401 // X s<= (X + C)<nsw> if C >= 0
7402 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7403 return true;
7404
7405 // (X + C)<nsw> s<= X if C <= 0
7406 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7407 !C.isStrictlyPositive())
7408 return true;
7409 break;
7410
7411 case ICmpInst::ICMP_SGT:
7412 std::swap(LHS, RHS);
7413 case ICmpInst::ICMP_SLT:
7414 // X s< (X + C)<nsw> if C > 0
7415 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7416 C.isStrictlyPositive())
7417 return true;
7418
7419 // (X + C)<nsw> s< X if C < 0
7420 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7421 return true;
7422 break;
7423 }
7424
7425 return false;
7426}
7427
Sanjoy Das7d910f22015-10-02 18:50:30 +00007428bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7429 const SCEV *LHS,
7430 const SCEV *RHS) {
Sanjoy Das10dffcb2015-10-08 03:46:00 +00007431 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
Sanjoy Das7d910f22015-10-02 18:50:30 +00007432 return false;
7433
7434 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7435 // the stack can result in exponential time complexity.
7436 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7437
7438 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7439 //
7440 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7441 // isKnownPredicate. isKnownPredicate is more powerful, but also more
7442 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7443 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
7444 // use isKnownPredicate later if needed.
Alexander Kornienko484e48e32015-11-05 21:07:12 +00007445 return isKnownNonNegative(RHS) &&
7446 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7447 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
Sanjoy Das7d910f22015-10-02 18:50:30 +00007448}
7449
Dan Gohmane65c9172009-07-13 21:35:55 +00007450/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7451/// protected by a conditional between LHS and RHS. This is used to
7452/// to eliminate casts.
7453bool
7454ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7455 ICmpInst::Predicate Pred,
7456 const SCEV *LHS, const SCEV *RHS) {
7457 // Interpret a null as meaning no loop, where there is obviously no guard
7458 // (interprocedural conditions notwithstanding).
7459 if (!L) return true;
7460
Sanjoy Das401e6312016-02-01 20:48:10 +00007461 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7462 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00007463
Dan Gohmane65c9172009-07-13 21:35:55 +00007464 BasicBlock *Latch = L->getLoopLatch();
7465 if (!Latch)
7466 return false;
7467
7468 BranchInst *LoopContinuePredicate =
7469 dyn_cast<BranchInst>(Latch->getTerminator());
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007470 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7471 isImpliedCond(Pred, LHS, RHS,
7472 LoopContinuePredicate->getCondition(),
7473 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7474 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007475
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007476 // We don't want more than one activation of the following loops on the stack
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007477 // -- that can lead to O(n!) time complexity.
7478 if (WalkingBEDominatingConds)
7479 return false;
7480
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +00007481 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007482
Sanjoy Dasb174f9a2015-09-25 23:53:50 +00007483 // See if we can exploit a trip count to prove the predicate.
7484 const auto &BETakenInfo = getBackedgeTakenInfo(L);
7485 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
7486 if (LatchBECount != getCouldNotCompute()) {
7487 // We know that Latch branches back to the loop header exactly
7488 // LatchBECount times. This means the backdege condition at Latch is
7489 // equivalent to "{0,+,1} u< LatchBECount".
7490 Type *Ty = LatchBECount->getType();
7491 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
7492 const SCEV *LoopCounter =
7493 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
7494 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
7495 LatchBECount))
7496 return true;
7497 }
7498
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007499 // Check conditions due to any @llvm.assume intrinsics.
7500 for (auto &AssumeVH : AC.assumptions()) {
7501 if (!AssumeVH)
7502 continue;
7503 auto *CI = cast<CallInst>(AssumeVH);
7504 if (!DT.dominates(CI, Latch->getTerminator()))
7505 continue;
7506
7507 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7508 return true;
7509 }
7510
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007511 // If the loop is not reachable from the entry block, we risk running into an
7512 // infinite loop as we walk up into the dom tree. These loops do not matter
7513 // anyway, so we just return a conservative answer when we see them.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007514 if (!DT.isReachableFromEntry(L->getHeader()))
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007515 return false;
7516
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007517 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
7518 DTN != HeaderDTN; DTN = DTN->getIDom()) {
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007519
7520 assert(DTN && "should reach the loop header before reaching the root!");
7521
7522 BasicBlock *BB = DTN->getBlock();
7523 BasicBlock *PBB = BB->getSinglePredecessor();
7524 if (!PBB)
7525 continue;
7526
7527 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
7528 if (!ContinuePredicate || !ContinuePredicate->isConditional())
7529 continue;
7530
7531 Value *Condition = ContinuePredicate->getCondition();
7532
7533 // If we have an edge `E` within the loop body that dominates the only
7534 // latch, the condition guarding `E` also guards the backedge. This
7535 // reasoning works only for loops with a single latch.
7536
7537 BasicBlockEdge DominatingEdge(PBB, BB);
7538 if (DominatingEdge.isSingleEdge()) {
7539 // We're constructively (and conservatively) enumerating edges within the
7540 // loop body that dominate the latch. The dominator tree better agree
7541 // with us on this:
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007542 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007543
7544 if (isImpliedCond(Pred, LHS, RHS, Condition,
7545 BB != ContinuePredicate->getSuccessor(0)))
7546 return true;
7547 }
7548 }
7549
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007550 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00007551}
7552
Dan Gohmanb50349a2010-04-11 19:27:13 +00007553/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohmane65c9172009-07-13 21:35:55 +00007554/// by a conditional between LHS and RHS. This is used to help avoid max
7555/// expressions in loop trip counts, and to eliminate casts.
7556bool
Dan Gohmanb50349a2010-04-11 19:27:13 +00007557ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
7558 ICmpInst::Predicate Pred,
7559 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman9cf09f82009-05-18 16:03:58 +00007560 // Interpret a null as meaning no loop, where there is obviously no guard
7561 // (interprocedural conditions notwithstanding).
7562 if (!L) return false;
7563
Sanjoy Das401e6312016-02-01 20:48:10 +00007564 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7565 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00007566
Dan Gohman8c77f1a2009-05-18 15:36:09 +00007567 // Starting at the loop predecessor, climb up the predecessor chain, as long
7568 // as there are predecessors that can be found that have unique successors
Dan Gohmanf9081a22008-09-15 22:18:04 +00007569 // leading to the original header.
Dan Gohman4e3c1132010-04-15 16:19:08 +00007570 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman75c6b0b2010-06-22 23:43:28 +00007571 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman4e3c1132010-04-15 16:19:08 +00007572 Pair.first;
7573 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman2a62fd92008-08-12 20:17:31 +00007574
7575 BranchInst *LoopEntryPredicate =
Dan Gohman4e3c1132010-04-15 16:19:08 +00007576 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman2a62fd92008-08-12 20:17:31 +00007577 if (!LoopEntryPredicate ||
7578 LoopEntryPredicate->isUnconditional())
7579 continue;
7580
Dan Gohmane18c2d62010-08-10 23:46:30 +00007581 if (isImpliedCond(Pred, LHS, RHS,
7582 LoopEntryPredicate->getCondition(),
Dan Gohman4e3c1132010-04-15 16:19:08 +00007583 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman2a62fd92008-08-12 20:17:31 +00007584 return true;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00007585 }
7586
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007587 // Check conditions due to any @llvm.assume intrinsics.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007588 for (auto &AssumeVH : AC.assumptions()) {
Chandler Carruth66b31302015-01-04 12:03:27 +00007589 if (!AssumeVH)
7590 continue;
7591 auto *CI = cast<CallInst>(AssumeVH);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007592 if (!DT.dominates(CI, L->getHeader()))
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007593 continue;
7594
7595 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7596 return true;
7597 }
7598
Dan Gohman2a62fd92008-08-12 20:17:31 +00007599 return false;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00007600}
7601
Benjamin Kramer039b1042015-10-28 13:54:36 +00007602namespace {
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00007603/// RAII wrapper to prevent recursive application of isImpliedCond.
7604/// ScalarEvolution's PendingLoopPredicates set must be empty unless we are
7605/// currently evaluating isImpliedCond.
7606struct MarkPendingLoopPredicate {
7607 Value *Cond;
7608 DenseSet<Value*> &LoopPreds;
7609 bool Pending;
7610
7611 MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP)
7612 : Cond(C), LoopPreds(LP) {
7613 Pending = !LoopPreds.insert(Cond).second;
7614 }
7615 ~MarkPendingLoopPredicate() {
7616 if (!Pending)
7617 LoopPreds.erase(Cond);
7618 }
7619};
Benjamin Kramer039b1042015-10-28 13:54:36 +00007620} // end anonymous namespace
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00007621
Dan Gohman430f0cc2009-07-21 23:03:19 +00007622/// isImpliedCond - Test whether the condition described by Pred, LHS,
7623/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmane18c2d62010-08-10 23:46:30 +00007624bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00007625 const SCEV *LHS, const SCEV *RHS,
Dan Gohmane18c2d62010-08-10 23:46:30 +00007626 Value *FoundCondValue,
Dan Gohman430f0cc2009-07-21 23:03:19 +00007627 bool Inverse) {
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00007628 MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates);
7629 if (Mark.Pending)
7630 return false;
7631
Dan Gohman8b0a4192010-03-01 17:49:51 +00007632 // Recursively handle And and Or conditions.
Dan Gohmane18c2d62010-08-10 23:46:30 +00007633 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00007634 if (BO->getOpcode() == Instruction::And) {
7635 if (!Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00007636 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
7637 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00007638 } else if (BO->getOpcode() == Instruction::Or) {
7639 if (Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00007640 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
7641 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00007642 }
7643 }
7644
Dan Gohmane18c2d62010-08-10 23:46:30 +00007645 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00007646 if (!ICI) return false;
7647
Andrew Trickfa594032012-11-29 18:35:13 +00007648 // Now that we found a conditional branch that dominates the loop or controls
7649 // the loop latch. Check to see if it is the comparison we are looking for.
Dan Gohman430f0cc2009-07-21 23:03:19 +00007650 ICmpInst::Predicate FoundPred;
7651 if (Inverse)
7652 FoundPred = ICI->getInversePredicate();
7653 else
7654 FoundPred = ICI->getPredicate();
7655
7656 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
7657 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohmane65c9172009-07-13 21:35:55 +00007658
Sanjoy Dasdf1635d2015-09-25 19:59:52 +00007659 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
7660}
7661
7662bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
7663 const SCEV *RHS,
7664 ICmpInst::Predicate FoundPred,
7665 const SCEV *FoundLHS,
7666 const SCEV *FoundRHS) {
Sanjoy Das14598832015-03-26 17:28:26 +00007667 // Balance the types.
7668 if (getTypeSizeInBits(LHS->getType()) <
7669 getTypeSizeInBits(FoundLHS->getType())) {
7670 if (CmpInst::isSigned(Pred)) {
7671 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
7672 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
7673 } else {
7674 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
7675 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
7676 }
7677 } else if (getTypeSizeInBits(LHS->getType()) >
Dan Gohmane65c9172009-07-13 21:35:55 +00007678 getTypeSizeInBits(FoundLHS->getType())) {
Stepan Dyatkovskiy431993b2014-01-09 12:26:12 +00007679 if (CmpInst::isSigned(FoundPred)) {
Dan Gohmane65c9172009-07-13 21:35:55 +00007680 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
7681 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
7682 } else {
7683 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
7684 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
7685 }
7686 }
7687
Dan Gohman430f0cc2009-07-21 23:03:19 +00007688 // Canonicalize the query to match the way instcombine will have
7689 // canonicalized the comparison.
Dan Gohman3673aa12010-04-24 01:34:53 +00007690 if (SimplifyICmpOperands(Pred, LHS, RHS))
7691 if (LHS == RHS)
Dan Gohmanb5025c72010-05-03 18:00:24 +00007692 return CmpInst::isTrueWhenEqual(Pred);
Benjamin Kramerba11a982012-11-29 19:07:57 +00007693 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
7694 if (FoundLHS == FoundRHS)
7695 return CmpInst::isFalseWhenEqual(FoundPred);
Dan Gohman430f0cc2009-07-21 23:03:19 +00007696
7697 // Check to see if we can make the LHS or RHS match.
7698 if (LHS == FoundRHS || RHS == FoundLHS) {
7699 if (isa<SCEVConstant>(RHS)) {
7700 std::swap(FoundLHS, FoundRHS);
7701 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
7702 } else {
7703 std::swap(LHS, RHS);
7704 Pred = ICmpInst::getSwappedPredicate(Pred);
7705 }
7706 }
7707
7708 // Check whether the found predicate is the same as the desired predicate.
7709 if (FoundPred == Pred)
7710 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
7711
7712 // Check whether swapping the found predicate makes it the same as the
7713 // desired predicate.
7714 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
7715 if (isa<SCEVConstant>(RHS))
7716 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
7717 else
7718 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
7719 RHS, LHS, FoundLHS, FoundRHS);
7720 }
7721
Sanjoy Das6e78b172015-10-22 19:57:34 +00007722 // Unsigned comparison is the same as signed comparison when both the operands
7723 // are non-negative.
7724 if (CmpInst::isUnsigned(FoundPred) &&
7725 CmpInst::getSignedPredicate(FoundPred) == Pred &&
7726 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
7727 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
7728
Sanjoy Dasc5676df2014-11-13 00:00:58 +00007729 // Check if we can make progress by sharpening ranges.
7730 if (FoundPred == ICmpInst::ICMP_NE &&
7731 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
7732
7733 const SCEVConstant *C = nullptr;
7734 const SCEV *V = nullptr;
7735
7736 if (isa<SCEVConstant>(FoundLHS)) {
7737 C = cast<SCEVConstant>(FoundLHS);
7738 V = FoundRHS;
7739 } else {
7740 C = cast<SCEVConstant>(FoundRHS);
7741 V = FoundLHS;
7742 }
7743
7744 // The guarding predicate tells us that C != V. If the known range
7745 // of V is [C, t), we can sharpen the range to [C + 1, t). The
7746 // range we consider has to correspond to same signedness as the
7747 // predicate we're interested in folding.
7748
7749 APInt Min = ICmpInst::isSigned(Pred) ?
7750 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
7751
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007752 if (Min == C->getAPInt()) {
Sanjoy Dasc5676df2014-11-13 00:00:58 +00007753 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
7754 // This is true even if (Min + 1) wraps around -- in case of
7755 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
7756
7757 APInt SharperMin = Min + 1;
7758
7759 switch (Pred) {
7760 case ICmpInst::ICMP_SGE:
7761 case ICmpInst::ICMP_UGE:
7762 // We know V `Pred` SharperMin. If this implies LHS `Pred`
7763 // RHS, we're done.
7764 if (isImpliedCondOperands(Pred, LHS, RHS, V,
7765 getConstant(SharperMin)))
7766 return true;
7767
7768 case ICmpInst::ICMP_SGT:
7769 case ICmpInst::ICMP_UGT:
7770 // We know from the range information that (V `Pred` Min ||
7771 // V == Min). We know from the guarding condition that !(V
7772 // == Min). This gives us
7773 //
7774 // V `Pred` Min || V == Min && !(V == Min)
7775 // => V `Pred` Min
7776 //
7777 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
7778
7779 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
7780 return true;
7781
7782 default:
7783 // No change
7784 break;
7785 }
7786 }
7787 }
7788
Dan Gohman430f0cc2009-07-21 23:03:19 +00007789 // Check whether the actual condition is beyond sufficient.
7790 if (FoundPred == ICmpInst::ICMP_EQ)
7791 if (ICmpInst::isTrueWhenEqual(Pred))
7792 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
7793 return true;
7794 if (Pred == ICmpInst::ICMP_NE)
7795 if (!ICmpInst::isTrueWhenEqual(FoundPred))
7796 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
7797 return true;
7798
7799 // Otherwise assume the worst.
7800 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00007801}
7802
Sanjoy Das1ed69102015-10-13 02:53:27 +00007803bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
7804 const SCEV *&L, const SCEV *&R,
7805 SCEV::NoWrapFlags &Flags) {
7806 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
7807 if (!AE || AE->getNumOperands() != 2)
7808 return false;
7809
7810 L = AE->getOperand(0);
7811 R = AE->getOperand(1);
7812 Flags = AE->getNoWrapFlags();
7813 return true;
7814}
7815
7816bool ScalarEvolution::computeConstantDifference(const SCEV *Less,
7817 const SCEV *More,
7818 APInt &C) {
Sanjoy Das96709c42015-09-25 23:53:45 +00007819 // We avoid subtracting expressions here because this function is usually
7820 // fairly deep in the call stack (i.e. is called many times).
7821
Sanjoy Das96709c42015-09-25 23:53:45 +00007822 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
7823 const auto *LAR = cast<SCEVAddRecExpr>(Less);
7824 const auto *MAR = cast<SCEVAddRecExpr>(More);
7825
7826 if (LAR->getLoop() != MAR->getLoop())
7827 return false;
7828
7829 // We look at affine expressions only; not for correctness but to keep
7830 // getStepRecurrence cheap.
7831 if (!LAR->isAffine() || !MAR->isAffine())
7832 return false;
7833
Sanjoy Das1ed69102015-10-13 02:53:27 +00007834 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
Sanjoy Das96709c42015-09-25 23:53:45 +00007835 return false;
7836
7837 Less = LAR->getStart();
7838 More = MAR->getStart();
7839
7840 // fall through
7841 }
7842
7843 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007844 const auto &M = cast<SCEVConstant>(More)->getAPInt();
7845 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
Sanjoy Das96709c42015-09-25 23:53:45 +00007846 C = M - L;
7847 return true;
7848 }
7849
7850 const SCEV *L, *R;
Sanjoy Das1ed69102015-10-13 02:53:27 +00007851 SCEV::NoWrapFlags Flags;
7852 if (splitBinaryAdd(Less, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00007853 if (const auto *LC = dyn_cast<SCEVConstant>(L))
7854 if (R == More) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007855 C = -(LC->getAPInt());
Sanjoy Das96709c42015-09-25 23:53:45 +00007856 return true;
7857 }
7858
Sanjoy Das1ed69102015-10-13 02:53:27 +00007859 if (splitBinaryAdd(More, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00007860 if (const auto *LC = dyn_cast<SCEVConstant>(L))
7861 if (R == Less) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007862 C = LC->getAPInt();
Sanjoy Das96709c42015-09-25 23:53:45 +00007863 return true;
7864 }
7865
7866 return false;
7867}
7868
7869bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
7870 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
7871 const SCEV *FoundLHS, const SCEV *FoundRHS) {
7872 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
7873 return false;
7874
7875 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7876 if (!AddRecLHS)
7877 return false;
7878
7879 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
7880 if (!AddRecFoundLHS)
7881 return false;
7882
7883 // We'd like to let SCEV reason about control dependencies, so we constrain
7884 // both the inequalities to be about add recurrences on the same loop. This
7885 // way we can use isLoopEntryGuardedByCond later.
7886
7887 const Loop *L = AddRecFoundLHS->getLoop();
7888 if (L != AddRecLHS->getLoop())
7889 return false;
7890
7891 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
7892 //
7893 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
7894 // ... (2)
7895 //
7896 // Informal proof for (2), assuming (1) [*]:
7897 //
7898 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
7899 //
7900 // Then
7901 //
7902 // FoundLHS s< FoundRHS s< INT_MIN - C
7903 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
7904 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
7905 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
7906 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
7907 // <=> FoundLHS + C s< FoundRHS + C
7908 //
7909 // [*]: (1) can be proved by ruling out overflow.
7910 //
7911 // [**]: This can be proved by analyzing all the four possibilities:
7912 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
7913 // (A s>= 0, B s>= 0).
7914 //
7915 // Note:
7916 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
7917 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
7918 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
7919 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
7920 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
7921 // C)".
7922
7923 APInt LDiff, RDiff;
Sanjoy Das1ed69102015-10-13 02:53:27 +00007924 if (!computeConstantDifference(FoundLHS, LHS, LDiff) ||
7925 !computeConstantDifference(FoundRHS, RHS, RDiff) ||
Sanjoy Das96709c42015-09-25 23:53:45 +00007926 LDiff != RDiff)
7927 return false;
7928
7929 if (LDiff == 0)
7930 return true;
7931
Sanjoy Das96709c42015-09-25 23:53:45 +00007932 APInt FoundRHSLimit;
7933
7934 if (Pred == CmpInst::ICMP_ULT) {
7935 FoundRHSLimit = -RDiff;
7936 } else {
7937 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
Sanjoy Das4f1c4592015-09-28 21:14:32 +00007938 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - RDiff;
Sanjoy Das96709c42015-09-25 23:53:45 +00007939 }
7940
7941 // Try to prove (1) or (2), as needed.
7942 return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
7943 getConstant(FoundRHSLimit));
7944}
7945
Dan Gohman430f0cc2009-07-21 23:03:19 +00007946/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman8b0a4192010-03-01 17:49:51 +00007947/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman430f0cc2009-07-21 23:03:19 +00007948/// and FoundRHS is true.
7949bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
7950 const SCEV *LHS, const SCEV *RHS,
7951 const SCEV *FoundLHS,
7952 const SCEV *FoundRHS) {
Sanjoy Dascb8bca12015-03-18 00:41:29 +00007953 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
7954 return true;
7955
Sanjoy Das96709c42015-09-25 23:53:45 +00007956 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
7957 return true;
7958
Dan Gohman430f0cc2009-07-21 23:03:19 +00007959 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
7960 FoundLHS, FoundRHS) ||
7961 // ~x < ~y --> x > y
7962 isImpliedCondOperandsHelper(Pred, LHS, RHS,
7963 getNotSCEV(FoundRHS),
7964 getNotSCEV(FoundLHS));
7965}
7966
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007967
7968/// If Expr computes ~A, return A else return nullptr
7969static const SCEV *MatchNotExpr(const SCEV *Expr) {
7970 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
Sanjoy Das16e7ff12015-10-13 23:28:31 +00007971 if (!Add || Add->getNumOperands() != 2 ||
7972 !Add->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007973 return nullptr;
7974
7975 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
Sanjoy Das16e7ff12015-10-13 23:28:31 +00007976 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
7977 !AddRHS->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007978 return nullptr;
7979
7980 return AddRHS->getOperand(1);
7981}
7982
7983
7984/// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
7985template<typename MaxExprType>
7986static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
7987 const SCEV *Candidate) {
7988 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
7989 if (!MaxExpr) return false;
7990
Sanjoy Das347d2722015-12-01 07:49:27 +00007991 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007992}
7993
7994
7995/// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
7996template<typename MaxExprType>
7997static bool IsMinConsistingOf(ScalarEvolution &SE,
7998 const SCEV *MaybeMinExpr,
7999 const SCEV *Candidate) {
8000 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8001 if (!MaybeMaxExpr)
8002 return false;
8003
8004 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8005}
8006
Hal Finkela8d205f2015-08-19 01:51:51 +00008007static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8008 ICmpInst::Predicate Pred,
8009 const SCEV *LHS, const SCEV *RHS) {
8010
8011 // If both sides are affine addrecs for the same loop, with equal
8012 // steps, and we know the recurrences don't wrap, then we only
8013 // need to check the predicate on the starting values.
8014
8015 if (!ICmpInst::isRelational(Pred))
8016 return false;
8017
8018 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8019 if (!LAR)
8020 return false;
8021 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8022 if (!RAR)
8023 return false;
8024 if (LAR->getLoop() != RAR->getLoop())
8025 return false;
8026 if (!LAR->isAffine() || !RAR->isAffine())
8027 return false;
8028
8029 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8030 return false;
8031
Hal Finkelff08a2e2015-08-19 17:26:07 +00008032 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8033 SCEV::FlagNSW : SCEV::FlagNUW;
8034 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
Hal Finkela8d205f2015-08-19 01:51:51 +00008035 return false;
8036
8037 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8038}
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008039
8040/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8041/// expression?
8042static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8043 ICmpInst::Predicate Pred,
8044 const SCEV *LHS, const SCEV *RHS) {
8045 switch (Pred) {
8046 default:
8047 return false;
8048
8049 case ICmpInst::ICMP_SGE:
8050 std::swap(LHS, RHS);
8051 // fall through
8052 case ICmpInst::ICMP_SLE:
8053 return
8054 // min(A, ...) <= A
8055 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8056 // A <= max(A, ...)
8057 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8058
8059 case ICmpInst::ICMP_UGE:
8060 std::swap(LHS, RHS);
8061 // fall through
8062 case ICmpInst::ICMP_ULE:
8063 return
8064 // min(A, ...) <= A
8065 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8066 // A <= max(A, ...)
8067 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8068 }
8069
8070 llvm_unreachable("covered switch fell through?!");
8071}
8072
Dan Gohman430f0cc2009-07-21 23:03:19 +00008073/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman8b0a4192010-03-01 17:49:51 +00008074/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008075/// FoundLHS, and FoundRHS is true.
Dan Gohmane65c9172009-07-13 21:35:55 +00008076bool
Dan Gohman430f0cc2009-07-21 23:03:19 +00008077ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8078 const SCEV *LHS, const SCEV *RHS,
8079 const SCEV *FoundLHS,
8080 const SCEV *FoundRHS) {
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008081 auto IsKnownPredicateFull =
8082 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Sanjoy Das401e6312016-02-01 20:48:10 +00008083 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
Sanjoy Das11231482015-10-22 19:57:29 +00008084 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
Sanjoy Dasc1a29772015-11-05 23:45:38 +00008085 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8086 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008087 };
8088
Dan Gohmane65c9172009-07-13 21:35:55 +00008089 switch (Pred) {
Dan Gohman8c129d72009-07-16 17:34:36 +00008090 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8091 case ICmpInst::ICMP_EQ:
8092 case ICmpInst::ICMP_NE:
8093 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8094 return true;
8095 break;
Dan Gohmane65c9172009-07-13 21:35:55 +00008096 case ICmpInst::ICMP_SLT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008097 case ICmpInst::ICMP_SLE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008098 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8099 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008100 return true;
8101 break;
8102 case ICmpInst::ICMP_SGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008103 case ICmpInst::ICMP_SGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008104 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8105 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008106 return true;
8107 break;
8108 case ICmpInst::ICMP_ULT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008109 case ICmpInst::ICMP_ULE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008110 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8111 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008112 return true;
8113 break;
8114 case ICmpInst::ICMP_UGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008115 case ICmpInst::ICMP_UGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008116 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8117 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008118 return true;
8119 break;
8120 }
8121
8122 return false;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008123}
8124
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008125/// isImpliedCondOperandsViaRanges - helper function for isImpliedCondOperands.
8126/// Tries to get cases like "X `sgt` 0 => X - 1 `sgt` -1".
8127bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8128 const SCEV *LHS,
8129 const SCEV *RHS,
8130 const SCEV *FoundLHS,
8131 const SCEV *FoundRHS) {
8132 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8133 // The restriction on `FoundRHS` be lifted easily -- it exists only to
8134 // reduce the compile time impact of this optimization.
8135 return false;
8136
8137 const SCEVAddExpr *AddLHS = dyn_cast<SCEVAddExpr>(LHS);
8138 if (!AddLHS || AddLHS->getOperand(1) != FoundLHS ||
8139 !isa<SCEVConstant>(AddLHS->getOperand(0)))
8140 return false;
8141
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008142 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008143
8144 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8145 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8146 ConstantRange FoundLHSRange =
8147 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8148
8149 // Since `LHS` is `FoundLHS` + `AddLHS->getOperand(0)`, we can compute a range
8150 // for `LHS`:
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008151 APInt Addend = cast<SCEVConstant>(AddLHS->getOperand(0))->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008152 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(Addend));
8153
8154 // We can also compute the range of values for `LHS` that satisfy the
8155 // consequent, "`LHS` `Pred` `RHS`":
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008156 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008157 ConstantRange SatisfyingLHSRange =
8158 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8159
8160 // The antecedent implies the consequent if every value of `LHS` that
8161 // satisfies the antecedent also satisfies the consequent.
8162 return SatisfyingLHSRange.contains(LHSRange);
8163}
8164
Johannes Doerfert2683e562015-02-09 12:34:23 +00008165// Verify if an linear IV with positive stride can overflow when in a
8166// less-than comparison, knowing the invariant term of the comparison, the
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008167// stride and the knowledge of NSW/NUW flags on the recurrence.
8168bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8169 bool IsSigned, bool NoWrap) {
8170 if (NoWrap) return false;
Dan Gohman51aaf022010-01-26 04:40:18 +00008171
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008172 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008173 const SCEV *One = getOne(Stride->getType());
Andrew Trick2afa3252011-03-09 17:29:58 +00008174
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008175 if (IsSigned) {
8176 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8177 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8178 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8179 .getSignedMax();
Andrew Trick2afa3252011-03-09 17:29:58 +00008180
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008181 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8182 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
Dan Gohman36bad002009-09-17 18:05:20 +00008183 }
Dan Gohman01048422009-06-21 23:46:38 +00008184
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008185 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8186 APInt MaxValue = APInt::getMaxValue(BitWidth);
8187 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8188 .getUnsignedMax();
8189
8190 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8191 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8192}
8193
Johannes Doerfert2683e562015-02-09 12:34:23 +00008194// Verify if an linear IV with negative stride can overflow when in a
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008195// greater-than comparison, knowing the invariant term of the comparison,
8196// the stride and the knowledge of NSW/NUW flags on the recurrence.
8197bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8198 bool IsSigned, bool NoWrap) {
8199 if (NoWrap) return false;
8200
8201 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008202 const SCEV *One = getOne(Stride->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008203
8204 if (IsSigned) {
8205 APInt MinRHS = getSignedRange(RHS).getSignedMin();
8206 APInt MinValue = APInt::getSignedMinValue(BitWidth);
8207 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8208 .getSignedMax();
8209
8210 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8211 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8212 }
8213
8214 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8215 APInt MinValue = APInt::getMinValue(BitWidth);
8216 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8217 .getUnsignedMax();
8218
8219 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8220 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8221}
8222
8223// Compute the backedge taken count knowing the interval difference, the
8224// stride and presence of the equality in the comparison.
Johannes Doerfert2683e562015-02-09 12:34:23 +00008225const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008226 bool Equality) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008227 const SCEV *One = getOne(Step->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008228 Delta = Equality ? getAddExpr(Delta, Step)
8229 : getAddExpr(Delta, getMinusSCEV(Step, One));
8230 return getUDivExpr(Delta, Step);
Dan Gohman01048422009-06-21 23:46:38 +00008231}
8232
Chris Lattner587a75b2005-08-15 23:33:51 +00008233/// HowManyLessThans - Return the number of times a backedge containing the
8234/// specified less-than comparison will execute. If not computable, return
Dan Gohman4c720c02009-06-06 14:37:11 +00008235/// CouldNotCompute.
Andrew Trick5b245a12013-05-31 06:43:25 +00008236///
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008237/// @param ControlsExit is true when the LHS < RHS condition directly controls
8238/// the branch (loops exits only if condition is true). In this case, we can use
8239/// NoWrapFlags to skip overflow checks.
Andrew Trick3ca3f982011-07-26 17:19:55 +00008240ScalarEvolution::ExitLimit
Dan Gohmance973df2009-06-24 04:48:43 +00008241ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008242 const Loop *L, bool IsSigned,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008243 bool ControlsExit) {
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008244 // We handle only IV < Invariant
8245 if (!isLoopInvariant(RHS, L))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00008246 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008247
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008248 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohman2b8da352009-04-30 20:47:05 +00008249
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008250 // Avoid weird loops
8251 if (!IV || IV->getLoop() != L || !IV->isAffine())
8252 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008253
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008254 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008255 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008256
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008257 const SCEV *Stride = IV->getStepRecurrence(*this);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008258
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008259 // Avoid negative or zero stride values
8260 if (!isKnownPositive(Stride))
8261 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00008262
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008263 // Avoid proven overflow cases: this will ensure that the backedge taken count
8264 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00008265 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008266 // behaviors like the case of C language.
8267 if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8268 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00008269
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008270 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8271 : ICmpInst::ICMP_ULT;
8272 const SCEV *Start = IV->getStart();
8273 const SCEV *End = RHS;
Bradley Smith9992b162014-10-31 11:40:32 +00008274 if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) {
8275 const SCEV *Diff = getMinusSCEV(RHS, Start);
8276 // If we have NoWrap set, then we can assume that the increment won't
8277 // overflow, in which case if RHS - Start is a constant, we don't need to
8278 // do a max operation since we can just figure it out statically
8279 if (NoWrap && isa<SCEVConstant>(Diff)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008280 APInt D = dyn_cast<const SCEVConstant>(Diff)->getAPInt();
Bradley Smith9992b162014-10-31 11:40:32 +00008281 if (D.isNegative())
8282 End = Start;
8283 } else
8284 End = IsSigned ? getSMaxExpr(RHS, Start)
8285 : getUMaxExpr(RHS, Start);
8286 }
Dan Gohman51aaf022010-01-26 04:40:18 +00008287
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008288 const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
Dan Gohman2b8da352009-04-30 20:47:05 +00008289
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008290 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8291 : getUnsignedRange(Start).getUnsignedMin();
Andrew Trick2afa3252011-03-09 17:29:58 +00008292
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008293 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8294 : getUnsignedRange(Stride).getUnsignedMin();
Dan Gohman2b8da352009-04-30 20:47:05 +00008295
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008296 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8297 APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1)
8298 : APInt::getMaxValue(BitWidth) - (MinStride - 1);
Chris Lattner587a75b2005-08-15 23:33:51 +00008299
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008300 // Although End can be a MAX expression we estimate MaxEnd considering only
8301 // the case End = RHS. This is safe because in the other case (End - Start)
8302 // is zero, leading to a zero maximum backedge taken count.
8303 APInt MaxEnd =
8304 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8305 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8306
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +00008307 const SCEV *MaxBECount;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008308 if (isa<SCEVConstant>(BECount))
8309 MaxBECount = BECount;
8310 else
8311 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
8312 getConstant(MinStride), false);
8313
8314 if (isa<SCEVCouldNotCompute>(MaxBECount))
8315 MaxBECount = BECount;
8316
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008317 return ExitLimit(BECount, MaxBECount);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008318}
8319
8320ScalarEvolution::ExitLimit
8321ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
8322 const Loop *L, bool IsSigned,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008323 bool ControlsExit) {
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008324 // We handle only IV > Invariant
8325 if (!isLoopInvariant(RHS, L))
8326 return getCouldNotCompute();
8327
8328 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8329
8330 // Avoid weird loops
8331 if (!IV || IV->getLoop() != L || !IV->isAffine())
8332 return getCouldNotCompute();
8333
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008334 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008335 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8336
8337 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8338
8339 // Avoid negative or zero stride values
8340 if (!isKnownPositive(Stride))
8341 return getCouldNotCompute();
8342
8343 // Avoid proven overflow cases: this will ensure that the backedge taken count
8344 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00008345 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008346 // behaviors like the case of C language.
8347 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8348 return getCouldNotCompute();
8349
8350 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8351 : ICmpInst::ICMP_UGT;
8352
8353 const SCEV *Start = IV->getStart();
8354 const SCEV *End = RHS;
Bradley Smith9992b162014-10-31 11:40:32 +00008355 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
8356 const SCEV *Diff = getMinusSCEV(RHS, Start);
8357 // If we have NoWrap set, then we can assume that the increment won't
8358 // overflow, in which case if RHS - Start is a constant, we don't need to
8359 // do a max operation since we can just figure it out statically
8360 if (NoWrap && isa<SCEVConstant>(Diff)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008361 APInt D = dyn_cast<const SCEVConstant>(Diff)->getAPInt();
Bradley Smith9992b162014-10-31 11:40:32 +00008362 if (!D.isNegative())
8363 End = Start;
8364 } else
8365 End = IsSigned ? getSMinExpr(RHS, Start)
8366 : getUMinExpr(RHS, Start);
8367 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008368
8369 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8370
8371 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8372 : getUnsignedRange(Start).getUnsignedMax();
8373
8374 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8375 : getUnsignedRange(Stride).getUnsignedMin();
8376
8377 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8378 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8379 : APInt::getMinValue(BitWidth) + (MinStride - 1);
8380
8381 // Although End can be a MIN expression we estimate MinEnd considering only
8382 // the case End = RHS. This is safe because in the other case (Start - End)
8383 // is zero, leading to a zero maximum backedge taken count.
8384 APInt MinEnd =
8385 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8386 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8387
8388
8389 const SCEV *MaxBECount = getCouldNotCompute();
8390 if (isa<SCEVConstant>(BECount))
8391 MaxBECount = BECount;
8392 else
Johannes Doerfert2683e562015-02-09 12:34:23 +00008393 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008394 getConstant(MinStride), false);
8395
8396 if (isa<SCEVCouldNotCompute>(MaxBECount))
8397 MaxBECount = BECount;
8398
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008399 return ExitLimit(BECount, MaxBECount);
Chris Lattner587a75b2005-08-15 23:33:51 +00008400}
8401
Chris Lattnerd934c702004-04-02 20:23:17 +00008402/// getNumIterationsInRange - Return the number of iterations of this loop that
8403/// produce values in the specified constant range. Another way of looking at
8404/// this is that it returns the first iteration number where the value is not in
8405/// the condition, thus computing the exit count. If the iteration count can't
8406/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00008407const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohmance973df2009-06-24 04:48:43 +00008408 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00008409 if (Range.isFullSet()) // Infinite loop.
Dan Gohman31efa302009-04-18 17:58:19 +00008410 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008411
8412 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmana30370b2009-05-04 22:02:23 +00008413 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencer2e54a152007-03-02 00:28:52 +00008414 if (!SC->getValue()->isZero()) {
Dan Gohmanaf752342009-07-07 17:06:11 +00008415 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008416 Operands[0] = SE.getZero(SC->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00008417 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00008418 getNoWrapFlags(FlagNW));
Sanjoy Das63914592015-10-18 00:29:20 +00008419 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattnerd934c702004-04-02 20:23:17 +00008420 return ShiftedAddRec->getNumIterationsInRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008421 Range.subtract(SC->getAPInt()), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00008422 // This is strange and shouldn't happen.
Dan Gohman31efa302009-04-18 17:58:19 +00008423 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008424 }
8425
8426 // The only time we can solve this is when we have all constant indices.
8427 // Otherwise, we cannot determine the overflow conditions.
Sanjoy Dasff3b8b42015-12-01 07:49:23 +00008428 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00008429 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008430
8431 // Okay at this point we know that all elements of the chrec are constants and
8432 // that the start element is zero.
8433
8434 // First check to see if the range contains zero. If not, the first
8435 // iteration exits.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00008436 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +00008437 if (!Range.contains(APInt(BitWidth, 0)))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008438 return SE.getZero(getType());
Misha Brukman01808ca2005-04-21 21:13:18 +00008439
Chris Lattnerd934c702004-04-02 20:23:17 +00008440 if (isAffine()) {
8441 // If this is an affine expression then we have this situation:
8442 // Solve {0,+,A} in Range === Ax in Range
8443
Nick Lewycky52460262007-07-16 02:08:00 +00008444 // We know that zero is in the range. If A is positive then we know that
8445 // the upper value of the range must be the first possible exit value.
8446 // If A is negative then the lower of the range is the last possible loop
8447 // value. Also note that we already checked for a full range.
Dan Gohman0a40ad92009-04-16 03:18:22 +00008448 APInt One(BitWidth,1);
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008449 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
Nick Lewycky52460262007-07-16 02:08:00 +00008450 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattnerd934c702004-04-02 20:23:17 +00008451
Nick Lewycky52460262007-07-16 02:08:00 +00008452 // The exit value should be (End+A)/A.
Nick Lewycky39349612007-09-27 14:12:54 +00008453 APInt ExitVal = (End + A).udiv(A);
Owen Andersonedb4a702009-07-24 23:12:02 +00008454 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00008455
8456 // Evaluate at the exit value. If we really did fall out of the valid
8457 // range, then we computed our trip count, otherwise wrap around or other
8458 // things must have happened.
Dan Gohmana37eaf22007-10-22 18:31:58 +00008459 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008460 if (Range.contains(Val->getValue()))
Dan Gohman31efa302009-04-18 17:58:19 +00008461 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008462
8463 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00008464 assert(Range.contains(
Dan Gohmance973df2009-06-24 04:48:43 +00008465 EvaluateConstantChrecAtConstant(this,
Owen Andersonedb4a702009-07-24 23:12:02 +00008466 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattnerd934c702004-04-02 20:23:17 +00008467 "Linear scev computation is off in a bad way!");
Dan Gohmana37eaf22007-10-22 18:31:58 +00008468 return SE.getConstant(ExitValue);
Chris Lattnerd934c702004-04-02 20:23:17 +00008469 } else if (isQuadratic()) {
8470 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
8471 // quadratic equation to solve it. To do this, we must frame our problem in
8472 // terms of figuring out when zero is crossed, instead of when
8473 // Range.getUpper() is crossed.
Dan Gohmanaf752342009-07-07 17:06:11 +00008474 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00008475 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Andrew Trick8b55b732011-03-14 16:50:06 +00008476 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
8477 // getNoWrapFlags(FlagNW)
8478 FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00008479
8480 // Next, solve the constructed addrec
Sanjoy Das01947432015-11-22 21:20:13 +00008481 auto Roots = SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman48f82222009-05-04 22:30:44 +00008482 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
8483 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattnerd934c702004-04-02 20:23:17 +00008484 if (R1) {
8485 // Pick the smallest positive root value.
Sanjoy Das01947432015-11-22 21:20:13 +00008486 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8487 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00008488 if (!CB->getZExtValue())
Chris Lattnerd934c702004-04-02 20:23:17 +00008489 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00008490
Chris Lattnerd934c702004-04-02 20:23:17 +00008491 // Make sure the root is not off by one. The returned iteration should
8492 // not be in the range, but the previous one should be. When solving
8493 // for "X*X < 5", for example, we should not return a root of 2.
8494 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohmana37eaf22007-10-22 18:31:58 +00008495 R1->getValue(),
8496 SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008497 if (Range.contains(R1Val->getValue())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00008498 // The next iteration must be out of the range...
Owen Andersonf1f17432009-07-06 22:37:39 +00008499 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008500 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
Misha Brukman01808ca2005-04-21 21:13:18 +00008501
Dan Gohmana37eaf22007-10-22 18:31:58 +00008502 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008503 if (!Range.contains(R1Val->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00008504 return SE.getConstant(NextVal);
Dan Gohman31efa302009-04-18 17:58:19 +00008505 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008506 }
Misha Brukman01808ca2005-04-21 21:13:18 +00008507
Chris Lattnerd934c702004-04-02 20:23:17 +00008508 // If R1 was not in the range, then it is a good return value. Make
8509 // sure that R1-1 WAS in the range though, just in case.
Owen Andersonf1f17432009-07-06 22:37:39 +00008510 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008511 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
Dan Gohmana37eaf22007-10-22 18:31:58 +00008512 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008513 if (Range.contains(R1Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00008514 return R1;
Dan Gohman31efa302009-04-18 17:58:19 +00008515 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008516 }
8517 }
8518 }
8519
Dan Gohman31efa302009-04-18 17:58:19 +00008520 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008521}
8522
Sebastian Pop448712b2014-05-07 18:01:20 +00008523namespace {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008524struct FindUndefs {
8525 bool Found;
8526 FindUndefs() : Found(false) {}
8527
8528 bool follow(const SCEV *S) {
8529 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
8530 if (isa<UndefValue>(C->getValue()))
8531 Found = true;
8532 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
8533 if (isa<UndefValue>(C->getValue()))
8534 Found = true;
8535 }
8536
8537 // Keep looking if we haven't found it yet.
8538 return !Found;
8539 }
8540 bool isDone() const {
8541 // Stop recursion if we have found an undef.
8542 return Found;
8543 }
8544};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00008545}
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008546
8547// Return true when S contains at least an undef value.
8548static inline bool
8549containsUndefs(const SCEV *S) {
8550 FindUndefs F;
8551 SCEVTraversal<FindUndefs> ST(F);
8552 ST.visitAll(S);
8553
8554 return F.Found;
8555}
8556
8557namespace {
Sebastian Pop448712b2014-05-07 18:01:20 +00008558// Collect all steps of SCEV expressions.
8559struct SCEVCollectStrides {
8560 ScalarEvolution &SE;
8561 SmallVectorImpl<const SCEV *> &Strides;
8562
8563 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
8564 : SE(SE), Strides(S) {}
8565
8566 bool follow(const SCEV *S) {
8567 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
8568 Strides.push_back(AR->getStepRecurrence(SE));
8569 return true;
8570 }
8571 bool isDone() const { return false; }
8572};
8573
8574// Collect all SCEVUnknown and SCEVMulExpr expressions.
8575struct SCEVCollectTerms {
8576 SmallVectorImpl<const SCEV *> &Terms;
8577
8578 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
8579 : Terms(T) {}
8580
8581 bool follow(const SCEV *S) {
Sebastian Popa6e58602014-05-27 22:41:45 +00008582 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008583 if (!containsUndefs(S))
8584 Terms.push_back(S);
Sebastian Pop448712b2014-05-07 18:01:20 +00008585
8586 // Stop recursion: once we collected a term, do not walk its operands.
8587 return false;
8588 }
8589
8590 // Keep looking.
8591 return true;
8592 }
8593 bool isDone() const { return false; }
8594};
Tobias Grosser374bce02015-10-12 08:02:00 +00008595
8596// Check if a SCEV contains an AddRecExpr.
8597struct SCEVHasAddRec {
8598 bool &ContainsAddRec;
8599
8600 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
8601 ContainsAddRec = false;
8602 }
8603
8604 bool follow(const SCEV *S) {
8605 if (isa<SCEVAddRecExpr>(S)) {
8606 ContainsAddRec = true;
8607
8608 // Stop recursion: once we collected a term, do not walk its operands.
8609 return false;
8610 }
8611
8612 // Keep looking.
8613 return true;
8614 }
8615 bool isDone() const { return false; }
8616};
8617
8618// Find factors that are multiplied with an expression that (possibly as a
8619// subexpression) contains an AddRecExpr. In the expression:
8620//
8621// 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
8622//
8623// "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
8624// that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
8625// parameters as they form a product with an induction variable.
8626//
8627// This collector expects all array size parameters to be in the same MulExpr.
8628// It might be necessary to later add support for collecting parameters that are
8629// spread over different nested MulExpr.
8630struct SCEVCollectAddRecMultiplies {
8631 SmallVectorImpl<const SCEV *> &Terms;
8632 ScalarEvolution &SE;
8633
8634 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
8635 : Terms(T), SE(SE) {}
8636
8637 bool follow(const SCEV *S) {
8638 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
8639 bool HasAddRec = false;
8640 SmallVector<const SCEV *, 0> Operands;
8641 for (auto Op : Mul->operands()) {
8642 if (isa<SCEVUnknown>(Op)) {
8643 Operands.push_back(Op);
8644 } else {
8645 bool ContainsAddRec;
8646 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
8647 visitAll(Op, ContiansAddRec);
8648 HasAddRec |= ContainsAddRec;
8649 }
8650 }
8651 if (Operands.size() == 0)
8652 return true;
8653
8654 if (!HasAddRec)
8655 return false;
8656
8657 Terms.push_back(SE.getMulExpr(Operands));
8658 // Stop recursion: once we collected a term, do not walk its operands.
8659 return false;
8660 }
8661
8662 // Keep looking.
8663 return true;
8664 }
8665 bool isDone() const { return false; }
8666};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00008667}
Sebastian Pop448712b2014-05-07 18:01:20 +00008668
Tobias Grosser374bce02015-10-12 08:02:00 +00008669/// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
8670/// two places:
8671/// 1) The strides of AddRec expressions.
8672/// 2) Unknowns that are multiplied with AddRec expressions.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008673void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
8674 SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00008675 SmallVector<const SCEV *, 4> Strides;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008676 SCEVCollectStrides StrideCollector(*this, Strides);
8677 visitAll(Expr, StrideCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00008678
8679 DEBUG({
8680 dbgs() << "Strides:\n";
8681 for (const SCEV *S : Strides)
8682 dbgs() << *S << "\n";
8683 });
8684
8685 for (const SCEV *S : Strides) {
8686 SCEVCollectTerms TermCollector(Terms);
8687 visitAll(S, TermCollector);
8688 }
8689
8690 DEBUG({
8691 dbgs() << "Terms:\n";
8692 for (const SCEV *T : Terms)
8693 dbgs() << *T << "\n";
8694 });
Tobias Grosser374bce02015-10-12 08:02:00 +00008695
8696 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
8697 visitAll(Expr, MulCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00008698}
8699
Sebastian Popb1a548f2014-05-12 19:01:53 +00008700static bool findArrayDimensionsRec(ScalarEvolution &SE,
Sebastian Pop448712b2014-05-07 18:01:20 +00008701 SmallVectorImpl<const SCEV *> &Terms,
Sebastian Pop47fe7de2014-05-09 22:45:07 +00008702 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pope30bd352014-05-27 22:41:56 +00008703 int Last = Terms.size() - 1;
8704 const SCEV *Step = Terms[Last];
Sebastian Popc62c6792013-11-12 22:47:20 +00008705
Sebastian Pop448712b2014-05-07 18:01:20 +00008706 // End of recursion.
Sebastian Pope30bd352014-05-27 22:41:56 +00008707 if (Last == 0) {
8708 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
Sebastian Pop448712b2014-05-07 18:01:20 +00008709 SmallVector<const SCEV *, 2> Qs;
8710 for (const SCEV *Op : M->operands())
8711 if (!isa<SCEVConstant>(Op))
8712 Qs.push_back(Op);
Sebastian Popc62c6792013-11-12 22:47:20 +00008713
Sebastian Pope30bd352014-05-27 22:41:56 +00008714 Step = SE.getMulExpr(Qs);
Sebastian Popc62c6792013-11-12 22:47:20 +00008715 }
8716
Sebastian Pope30bd352014-05-27 22:41:56 +00008717 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00008718 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00008719 }
8720
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00008721 for (const SCEV *&Term : Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00008722 // Normalize the terms before the next call to findArrayDimensionsRec.
8723 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00008724 SCEVDivision::divide(SE, Term, Step, &Q, &R);
Sebastian Popb1a548f2014-05-12 19:01:53 +00008725
8726 // Bail out when GCD does not evenly divide one of the terms.
8727 if (!R->isZero())
8728 return false;
8729
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00008730 Term = Q;
Sebastian Popc62c6792013-11-12 22:47:20 +00008731 }
8732
Tobias Grosser3080cf12014-05-08 07:55:34 +00008733 // Remove all SCEVConstants.
Tobias Grosser1e9db7e2014-05-08 21:43:19 +00008734 Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) {
8735 return isa<SCEVConstant>(E);
8736 }),
8737 Terms.end());
Sebastian Popc62c6792013-11-12 22:47:20 +00008738
Sebastian Pop448712b2014-05-07 18:01:20 +00008739 if (Terms.size() > 0)
Sebastian Popb1a548f2014-05-12 19:01:53 +00008740 if (!findArrayDimensionsRec(SE, Terms, Sizes))
8741 return false;
8742
Sebastian Pope30bd352014-05-27 22:41:56 +00008743 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00008744 return true;
Sebastian Pop448712b2014-05-07 18:01:20 +00008745}
Sebastian Popc62c6792013-11-12 22:47:20 +00008746
Sebastian Pop448712b2014-05-07 18:01:20 +00008747// Returns true when S contains at least a SCEVUnknown parameter.
8748static inline bool
8749containsParameters(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +00008750 struct FindParameter {
8751 bool FoundParameter;
8752 FindParameter() : FoundParameter(false) {}
8753
8754 bool follow(const SCEV *S) {
8755 if (isa<SCEVUnknown>(S)) {
8756 FoundParameter = true;
8757 // Stop recursion: we found a parameter.
8758 return false;
8759 }
8760 // Keep looking.
8761 return true;
8762 }
8763 bool isDone() const {
8764 // Stop recursion if we have found a parameter.
8765 return FoundParameter;
8766 }
8767 };
8768
Sebastian Pop448712b2014-05-07 18:01:20 +00008769 FindParameter F;
8770 SCEVTraversal<FindParameter> ST(F);
8771 ST.visitAll(S);
8772
8773 return F.FoundParameter;
8774}
8775
8776// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
8777static inline bool
8778containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
8779 for (const SCEV *T : Terms)
8780 if (containsParameters(T))
8781 return true;
8782 return false;
8783}
8784
8785// Return the number of product terms in S.
8786static inline int numberOfTerms(const SCEV *S) {
8787 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
8788 return Expr->getNumOperands();
8789 return 1;
8790}
8791
Sebastian Popa6e58602014-05-27 22:41:45 +00008792static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
8793 if (isa<SCEVConstant>(T))
8794 return nullptr;
8795
8796 if (isa<SCEVUnknown>(T))
8797 return T;
8798
8799 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
8800 SmallVector<const SCEV *, 2> Factors;
8801 for (const SCEV *Op : M->operands())
8802 if (!isa<SCEVConstant>(Op))
8803 Factors.push_back(Op);
8804
8805 return SE.getMulExpr(Factors);
8806 }
8807
8808 return T;
8809}
8810
8811/// Return the size of an element read or written by Inst.
8812const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
8813 Type *Ty;
8814 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
8815 Ty = Store->getValueOperand()->getType();
8816 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
Tobias Grosser40ac1002014-06-08 19:21:20 +00008817 Ty = Load->getType();
Sebastian Popa6e58602014-05-27 22:41:45 +00008818 else
8819 return nullptr;
8820
8821 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
8822 return getSizeOfExpr(ETy, Ty);
8823}
8824
Sebastian Pop448712b2014-05-07 18:01:20 +00008825/// Second step of delinearization: compute the array dimensions Sizes from the
8826/// set of Terms extracted from the memory access function of this SCEVAddRec.
Sebastian Popa6e58602014-05-27 22:41:45 +00008827void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
8828 SmallVectorImpl<const SCEV *> &Sizes,
8829 const SCEV *ElementSize) const {
Sebastian Pop448712b2014-05-07 18:01:20 +00008830
Sebastian Pop53524082014-05-29 19:44:05 +00008831 if (Terms.size() < 1 || !ElementSize)
Sebastian Pop448712b2014-05-07 18:01:20 +00008832 return;
8833
8834 // Early return when Terms do not contain parameters: we do not delinearize
8835 // non parametric SCEVs.
8836 if (!containsParameters(Terms))
8837 return;
8838
8839 DEBUG({
8840 dbgs() << "Terms:\n";
8841 for (const SCEV *T : Terms)
8842 dbgs() << *T << "\n";
8843 });
8844
8845 // Remove duplicates.
8846 std::sort(Terms.begin(), Terms.end());
8847 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
8848
8849 // Put larger terms first.
8850 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
8851 return numberOfTerms(LHS) > numberOfTerms(RHS);
8852 });
8853
Sebastian Popa6e58602014-05-27 22:41:45 +00008854 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
8855
Tobias Grosser374bce02015-10-12 08:02:00 +00008856 // Try to divide all terms by the element size. If term is not divisible by
8857 // element size, proceed with the original term.
Sebastian Popa6e58602014-05-27 22:41:45 +00008858 for (const SCEV *&Term : Terms) {
8859 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00008860 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
Tobias Grosser374bce02015-10-12 08:02:00 +00008861 if (!Q->isZero())
8862 Term = Q;
Sebastian Popa6e58602014-05-27 22:41:45 +00008863 }
8864
8865 SmallVector<const SCEV *, 4> NewTerms;
8866
8867 // Remove constant factors.
8868 for (const SCEV *T : Terms)
8869 if (const SCEV *NewT = removeConstantFactors(SE, T))
8870 NewTerms.push_back(NewT);
8871
Sebastian Pop448712b2014-05-07 18:01:20 +00008872 DEBUG({
8873 dbgs() << "Terms after sorting:\n";
Sebastian Popa6e58602014-05-27 22:41:45 +00008874 for (const SCEV *T : NewTerms)
Sebastian Pop448712b2014-05-07 18:01:20 +00008875 dbgs() << *T << "\n";
8876 });
8877
Sebastian Popa6e58602014-05-27 22:41:45 +00008878 if (NewTerms.empty() ||
8879 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
Sebastian Popb1a548f2014-05-12 19:01:53 +00008880 Sizes.clear();
8881 return;
8882 }
Sebastian Pop448712b2014-05-07 18:01:20 +00008883
Sebastian Popa6e58602014-05-27 22:41:45 +00008884 // The last element to be pushed into Sizes is the size of an element.
8885 Sizes.push_back(ElementSize);
8886
Sebastian Pop448712b2014-05-07 18:01:20 +00008887 DEBUG({
8888 dbgs() << "Sizes:\n";
8889 for (const SCEV *S : Sizes)
8890 dbgs() << *S << "\n";
8891 });
8892}
8893
8894/// Third step of delinearization: compute the access functions for the
8895/// Subscripts based on the dimensions in Sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008896void ScalarEvolution::computeAccessFunctions(
8897 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
8898 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pop448712b2014-05-07 18:01:20 +00008899
Sebastian Popb1a548f2014-05-12 19:01:53 +00008900 // Early exit in case this SCEV is not an affine multivariate function.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008901 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00008902 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00008903
Sanjoy Das1195dbe2015-10-08 03:45:58 +00008904 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008905 if (!AR->isAffine())
8906 return;
8907
8908 const SCEV *Res = Expr;
Sebastian Pop448712b2014-05-07 18:01:20 +00008909 int Last = Sizes.size() - 1;
8910 for (int i = Last; i >= 0; i--) {
8911 const SCEV *Q, *R;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008912 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
Sebastian Pop448712b2014-05-07 18:01:20 +00008913
8914 DEBUG({
8915 dbgs() << "Res: " << *Res << "\n";
8916 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
8917 dbgs() << "Res divided by Sizes[i]:\n";
8918 dbgs() << "Quotient: " << *Q << "\n";
8919 dbgs() << "Remainder: " << *R << "\n";
8920 });
8921
8922 Res = Q;
8923
Sebastian Popa6e58602014-05-27 22:41:45 +00008924 // Do not record the last subscript corresponding to the size of elements in
8925 // the array.
Sebastian Pop448712b2014-05-07 18:01:20 +00008926 if (i == Last) {
Sebastian Popa6e58602014-05-27 22:41:45 +00008927
8928 // Bail out if the remainder is too complex.
Sebastian Pop28e6b972014-05-27 22:41:51 +00008929 if (isa<SCEVAddRecExpr>(R)) {
8930 Subscripts.clear();
8931 Sizes.clear();
8932 return;
8933 }
Sebastian Popa6e58602014-05-27 22:41:45 +00008934
Sebastian Pop448712b2014-05-07 18:01:20 +00008935 continue;
8936 }
8937
8938 // Record the access function for the current subscript.
8939 Subscripts.push_back(R);
8940 }
8941
8942 // Also push in last position the remainder of the last division: it will be
8943 // the access function of the innermost dimension.
8944 Subscripts.push_back(Res);
8945
8946 std::reverse(Subscripts.begin(), Subscripts.end());
8947
8948 DEBUG({
8949 dbgs() << "Subscripts:\n";
8950 for (const SCEV *S : Subscripts)
8951 dbgs() << *S << "\n";
8952 });
Sebastian Pop448712b2014-05-07 18:01:20 +00008953}
8954
Sebastian Popc62c6792013-11-12 22:47:20 +00008955/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
8956/// sizes of an array access. Returns the remainder of the delinearization that
Sebastian Pop7ee14722013-11-13 22:37:58 +00008957/// is the offset start of the array. The SCEV->delinearize algorithm computes
8958/// the multiples of SCEV coefficients: that is a pattern matching of sub
8959/// expressions in the stride and base of a SCEV corresponding to the
8960/// computation of a GCD (greatest common divisor) of base and stride. When
8961/// SCEV->delinearize fails, it returns the SCEV unchanged.
8962///
8963/// For example: when analyzing the memory access A[i][j][k] in this loop nest
8964///
8965/// void foo(long n, long m, long o, double A[n][m][o]) {
8966///
8967/// for (long i = 0; i < n; i++)
8968/// for (long j = 0; j < m; j++)
8969/// for (long k = 0; k < o; k++)
8970/// A[i][j][k] = 1.0;
8971/// }
8972///
8973/// the delinearization input is the following AddRec SCEV:
8974///
8975/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
8976///
8977/// From this SCEV, we are able to say that the base offset of the access is %A
8978/// because it appears as an offset that does not divide any of the strides in
8979/// the loops:
8980///
8981/// CHECK: Base offset: %A
8982///
8983/// and then SCEV->delinearize determines the size of some of the dimensions of
8984/// the array as these are the multiples by which the strides are happening:
8985///
8986/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
8987///
8988/// Note that the outermost dimension remains of UnknownSize because there are
8989/// no strides that would help identifying the size of the last dimension: when
8990/// the array has been statically allocated, one could compute the size of that
8991/// dimension by dividing the overall size of the array by the size of the known
8992/// dimensions: %m * %o * 8.
8993///
8994/// Finally delinearize provides the access functions for the array reference
8995/// that does correspond to A[i][j][k] of the above C testcase:
8996///
8997/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
8998///
8999/// The testcases are checking the output of a function pass:
9000/// DelinearizationPass that walks through all loads and stores of a function
9001/// asking for the SCEV of the memory access with respect to all enclosing
9002/// loops, calling SCEV->delinearize on that and printing the results.
9003
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009004void ScalarEvolution::delinearize(const SCEV *Expr,
Sebastian Pop28e6b972014-05-27 22:41:51 +00009005 SmallVectorImpl<const SCEV *> &Subscripts,
9006 SmallVectorImpl<const SCEV *> &Sizes,
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009007 const SCEV *ElementSize) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009008 // First step: collect parametric terms.
9009 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009010 collectParametricTerms(Expr, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00009011
Sebastian Popb1a548f2014-05-12 19:01:53 +00009012 if (Terms.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009013 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009014
Sebastian Pop448712b2014-05-07 18:01:20 +00009015 // Second step: find subscript sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009016 findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop7ee14722013-11-13 22:37:58 +00009017
Sebastian Popb1a548f2014-05-12 19:01:53 +00009018 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009019 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009020
Sebastian Pop448712b2014-05-07 18:01:20 +00009021 // Third step: compute the access functions for each subscript.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009022 computeAccessFunctions(Expr, Subscripts, Sizes);
Sebastian Popc62c6792013-11-12 22:47:20 +00009023
Sebastian Pop28e6b972014-05-27 22:41:51 +00009024 if (Subscripts.empty())
9025 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009026
Sebastian Pop448712b2014-05-07 18:01:20 +00009027 DEBUG({
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009028 dbgs() << "succeeded to delinearize " << *Expr << "\n";
Sebastian Pop448712b2014-05-07 18:01:20 +00009029 dbgs() << "ArrayDecl[UnknownSize]";
9030 for (const SCEV *S : Sizes)
9031 dbgs() << "[" << *S << "]";
Sebastian Popc62c6792013-11-12 22:47:20 +00009032
Sebastian Pop444621a2014-05-09 22:45:02 +00009033 dbgs() << "\nArrayRef";
9034 for (const SCEV *S : Subscripts)
Sebastian Pop448712b2014-05-07 18:01:20 +00009035 dbgs() << "[" << *S << "]";
9036 dbgs() << "\n";
9037 });
Sebastian Popc62c6792013-11-12 22:47:20 +00009038}
Chris Lattnerd934c702004-04-02 20:23:17 +00009039
9040//===----------------------------------------------------------------------===//
Dan Gohman48f82222009-05-04 22:30:44 +00009041// SCEVCallbackVH Class Implementation
9042//===----------------------------------------------------------------------===//
9043
Dan Gohmand33a0902009-05-19 19:22:47 +00009044void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmandd707af2009-07-13 22:20:53 +00009045 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman48f82222009-05-04 22:30:44 +00009046 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9047 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009048 SE->eraseValueFromMap(getValPtr());
Dan Gohman48f82222009-05-04 22:30:44 +00009049 // this now dangles!
9050}
9051
Dan Gohman7a066722010-07-28 01:09:07 +00009052void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmandd707af2009-07-13 22:20:53 +00009053 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christopheref6d5932010-07-29 01:25:38 +00009054
Dan Gohman48f82222009-05-04 22:30:44 +00009055 // Forget all the expressions associated with users of the old value,
9056 // so that future queries will recompute the expressions using the new
9057 // value.
Dan Gohman7cac9572010-08-02 23:49:30 +00009058 Value *Old = getValPtr();
Chandler Carruthcdf47882014-03-09 03:16:01 +00009059 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
Dan Gohmanf34f8632009-07-14 14:34:04 +00009060 SmallPtrSet<User *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00009061 while (!Worklist.empty()) {
9062 User *U = Worklist.pop_back_val();
9063 // Deleting the Old value will cause this to dangle. Postpone
9064 // that until everything else is done.
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009065 if (U == Old)
Dan Gohman48f82222009-05-04 22:30:44 +00009066 continue;
David Blaikie70573dc2014-11-19 07:49:26 +00009067 if (!Visited.insert(U).second)
Dan Gohmanf34f8632009-07-14 14:34:04 +00009068 continue;
Dan Gohman48f82222009-05-04 22:30:44 +00009069 if (PHINode *PN = dyn_cast<PHINode>(U))
9070 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009071 SE->eraseValueFromMap(U);
Chandler Carruthcdf47882014-03-09 03:16:01 +00009072 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
Dan Gohman48f82222009-05-04 22:30:44 +00009073 }
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009074 // Delete the Old value.
9075 if (PHINode *PN = dyn_cast<PHINode>(Old))
9076 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009077 SE->eraseValueFromMap(Old);
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009078 // this now dangles!
Dan Gohman48f82222009-05-04 22:30:44 +00009079}
9080
Dan Gohmand33a0902009-05-19 19:22:47 +00009081ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman48f82222009-05-04 22:30:44 +00009082 : CallbackVH(V), SE(se) {}
9083
9084//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00009085// ScalarEvolution Class Implementation
9086//===----------------------------------------------------------------------===//
9087
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009088ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
9089 AssumptionCache &AC, DominatorTree &DT,
9090 LoopInfo &LI)
9091 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
9092 CouldNotCompute(new SCEVCouldNotCompute()),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009093 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9094 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
9095 FirstUnknown(nullptr) {}
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009096
9097ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
9098 : F(Arg.F), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI),
9099 CouldNotCompute(std::move(Arg.CouldNotCompute)),
9100 ValueExprMap(std::move(Arg.ValueExprMap)),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009101 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009102 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
9103 ConstantEvolutionLoopExitValue(
9104 std::move(Arg.ConstantEvolutionLoopExitValue)),
9105 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9106 LoopDispositions(std::move(Arg.LoopDispositions)),
9107 BlockDispositions(std::move(Arg.BlockDispositions)),
9108 UnsignedRanges(std::move(Arg.UnsignedRanges)),
9109 SignedRanges(std::move(Arg.SignedRanges)),
9110 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
Silviu Barangae3c05342015-11-02 14:41:02 +00009111 UniquePreds(std::move(Arg.UniquePreds)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009112 SCEVAllocator(std::move(Arg.SCEVAllocator)),
9113 FirstUnknown(Arg.FirstUnknown) {
9114 Arg.FirstUnknown = nullptr;
Dan Gohmanc8e23622009-04-21 23:15:49 +00009115}
9116
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009117ScalarEvolution::~ScalarEvolution() {
Dan Gohman7cac9572010-08-02 23:49:30 +00009118 // Iterate through all the SCEVUnknown instances and call their
9119 // destructors, so that they release their references to their values.
Naomi Musgravef90c1be2015-09-16 23:46:40 +00009120 for (SCEVUnknown *U = FirstUnknown; U;) {
9121 SCEVUnknown *Tmp = U;
9122 U = U->Next;
9123 Tmp->~SCEVUnknown();
9124 }
Craig Topper9f008862014-04-15 04:59:12 +00009125 FirstUnknown = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00009126
Wei Mia49559b2016-02-04 01:27:38 +00009127 ExprValueMap.clear();
Dan Gohman9bad2fb2010-08-27 18:55:03 +00009128 ValueExprMap.clear();
Wei Mia49559b2016-02-04 01:27:38 +00009129 HasRecMap.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009130
9131 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9132 // that a loop had multiple computable exits.
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009133 for (auto &BTCI : BackedgeTakenCounts)
9134 BTCI.second.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009135
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00009136 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00009137 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
Sanjoy Das7d910f22015-10-02 18:50:30 +00009138 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
Dan Gohman0a40ad92009-04-16 03:18:22 +00009139}
9140
Dan Gohmanc8e23622009-04-21 23:15:49 +00009141bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman0bddac12009-02-24 18:55:53 +00009142 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattnerd934c702004-04-02 20:23:17 +00009143}
9144
Dan Gohmanc8e23622009-04-21 23:15:49 +00009145static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +00009146 const Loop *L) {
9147 // Print all inner loops first
9148 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
9149 PrintLoopInfo(OS, SE, *I);
Misha Brukman01808ca2005-04-21 21:13:18 +00009150
Dan Gohmanbc694912010-01-09 18:17:45 +00009151 OS << "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009152 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009153 OS << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009154
Dan Gohmancb0efec2009-12-18 01:14:11 +00009155 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009156 L->getExitBlocks(ExitBlocks);
9157 if (ExitBlocks.size() != 1)
Nick Lewyckyd1200b02008-01-02 02:49:20 +00009158 OS << "<multiple exits> ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009159
Dan Gohman0bddac12009-02-24 18:55:53 +00009160 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9161 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattnerd934c702004-04-02 20:23:17 +00009162 } else {
Dan Gohman0bddac12009-02-24 18:55:53 +00009163 OS << "Unpredictable backedge-taken count. ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009164 }
9165
Dan Gohmanbc694912010-01-09 18:17:45 +00009166 OS << "\n"
9167 "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009168 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009169 OS << ": ";
Dan Gohman69942932009-06-24 00:33:16 +00009170
9171 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9172 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
9173 } else {
9174 OS << "Unpredictable max backedge-taken count. ";
9175 }
9176
9177 OS << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00009178}
9179
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009180void ScalarEvolution::print(raw_ostream &OS) const {
Dan Gohman8b0a4192010-03-01 17:49:51 +00009181 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanc8e23622009-04-21 23:15:49 +00009182 // out SCEV values of all instructions that are interesting. Doing
9183 // this potentially causes it to create new SCEV objects though,
9184 // which technically conflicts with the const qualifier. This isn't
Dan Gohman028e6152009-07-10 20:25:29 +00009185 // observable from outside the class though, so casting away the
9186 // const isn't dangerous.
Dan Gohmancb0efec2009-12-18 01:14:11 +00009187 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattnerd934c702004-04-02 20:23:17 +00009188
Dan Gohmanbc694912010-01-09 18:17:45 +00009189 OS << "Classifying expressions for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009190 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009191 OS << "\n";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009192 for (Instruction &I : instructions(F))
9193 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9194 OS << I << '\n';
Dan Gohman81313fd2008-09-14 17:21:12 +00009195 OS << " --> ";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009196 const SCEV *SV = SE.getSCEV(&I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009197 SV->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009198 if (!isa<SCEVCouldNotCompute>(SV)) {
9199 OS << " U: ";
9200 SE.getUnsignedRange(SV).print(OS);
9201 OS << " S: ";
9202 SE.getSignedRange(SV).print(OS);
9203 }
Misha Brukman01808ca2005-04-21 21:13:18 +00009204
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009205 const Loop *L = LI.getLoopFor(I.getParent());
Dan Gohmanb9063a82009-06-19 17:49:54 +00009206
Dan Gohmanaf752342009-07-07 17:06:11 +00009207 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohmanb9063a82009-06-19 17:49:54 +00009208 if (AtUse != SV) {
9209 OS << " --> ";
9210 AtUse->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009211 if (!isa<SCEVCouldNotCompute>(AtUse)) {
9212 OS << " U: ";
9213 SE.getUnsignedRange(AtUse).print(OS);
9214 OS << " S: ";
9215 SE.getSignedRange(AtUse).print(OS);
9216 }
Dan Gohmanb9063a82009-06-19 17:49:54 +00009217 }
9218
9219 if (L) {
Dan Gohman94c468f2009-06-18 00:37:45 +00009220 OS << "\t\t" "Exits: ";
Dan Gohmanaf752342009-07-07 17:06:11 +00009221 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanafd6db92010-11-17 21:23:15 +00009222 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00009223 OS << "<<Unknown>>";
9224 } else {
9225 OS << *ExitValue;
9226 }
9227 }
9228
Chris Lattnerd934c702004-04-02 20:23:17 +00009229 OS << "\n";
9230 }
9231
Dan Gohmanbc694912010-01-09 18:17:45 +00009232 OS << "Determining loop execution counts for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009233 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009234 OS << "\n";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009235 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
Dan Gohmanc8e23622009-04-21 23:15:49 +00009236 PrintLoopInfo(OS, &SE, *I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009237}
Dan Gohmane20f8242009-04-21 00:47:46 +00009238
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009239ScalarEvolution::LoopDisposition
9240ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009241 auto &Values = LoopDispositions[S];
9242 for (auto &V : Values) {
9243 if (V.getPointer() == L)
9244 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009245 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009246 Values.emplace_back(L, LoopVariant);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009247 LoopDisposition D = computeLoopDisposition(S, L);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009248 auto &Values2 = LoopDispositions[S];
9249 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9250 if (V.getPointer() == L) {
9251 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009252 break;
9253 }
9254 }
9255 return D;
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009256}
9257
9258ScalarEvolution::LoopDisposition
9259ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009260 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009261 case scConstant:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009262 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009263 case scTruncate:
9264 case scZeroExtend:
9265 case scSignExtend:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009266 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohmanafd6db92010-11-17 21:23:15 +00009267 case scAddRecExpr: {
9268 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9269
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009270 // If L is the addrec's loop, it's computable.
9271 if (AR->getLoop() == L)
9272 return LoopComputable;
9273
Dan Gohmanafd6db92010-11-17 21:23:15 +00009274 // Add recurrences are never invariant in the function-body (null loop).
9275 if (!L)
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009276 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009277
9278 // This recurrence is variant w.r.t. L if L contains AR's loop.
9279 if (L->contains(AR->getLoop()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009280 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009281
9282 // This recurrence is invariant w.r.t. L if AR's loop contains L.
9283 if (AR->getLoop()->contains(L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009284 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009285
9286 // This recurrence is variant w.r.t. L if any of its operands
9287 // are variant.
Sanjoy Das01947432015-11-22 21:20:13 +00009288 for (auto *Op : AR->operands())
9289 if (!isLoopInvariant(Op, L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009290 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009291
9292 // Otherwise it's loop-invariant.
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009293 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009294 }
9295 case scAddExpr:
9296 case scMulExpr:
9297 case scUMaxExpr:
9298 case scSMaxExpr: {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009299 bool HasVarying = false;
Sanjoy Das01947432015-11-22 21:20:13 +00009300 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
9301 LoopDisposition D = getLoopDisposition(Op, L);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009302 if (D == LoopVariant)
9303 return LoopVariant;
9304 if (D == LoopComputable)
9305 HasVarying = true;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009306 }
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009307 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009308 }
9309 case scUDivExpr: {
9310 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009311 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9312 if (LD == LoopVariant)
9313 return LoopVariant;
9314 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9315 if (RD == LoopVariant)
9316 return LoopVariant;
9317 return (LD == LoopInvariant && RD == LoopInvariant) ?
9318 LoopInvariant : LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009319 }
9320 case scUnknown:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009321 // All non-instruction values are loop invariant. All instructions are loop
9322 // invariant if they are not contained in the specified loop.
9323 // Instructions are never considered invariant in the function body
9324 // (null loop) because they are defined within the "loop".
Sanjoy Das01947432015-11-22 21:20:13 +00009325 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009326 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9327 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009328 case scCouldNotCompute:
9329 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanafd6db92010-11-17 21:23:15 +00009330 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009331 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009332}
9333
9334bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9335 return getLoopDisposition(S, L) == LoopInvariant;
9336}
9337
9338bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9339 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009340}
Dan Gohman20d9ce22010-11-17 21:41:58 +00009341
Dan Gohman8ea83d82010-11-18 00:34:22 +00009342ScalarEvolution::BlockDisposition
9343ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009344 auto &Values = BlockDispositions[S];
9345 for (auto &V : Values) {
9346 if (V.getPointer() == BB)
9347 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009348 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009349 Values.emplace_back(BB, DoesNotDominateBlock);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009350 BlockDisposition D = computeBlockDisposition(S, BB);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009351 auto &Values2 = BlockDispositions[S];
9352 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9353 if (V.getPointer() == BB) {
9354 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009355 break;
9356 }
9357 }
9358 return D;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009359}
9360
Dan Gohman8ea83d82010-11-18 00:34:22 +00009361ScalarEvolution::BlockDisposition
9362ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009363 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohman20d9ce22010-11-17 21:41:58 +00009364 case scConstant:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009365 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009366 case scTruncate:
9367 case scZeroExtend:
9368 case scSignExtend:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009369 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohman20d9ce22010-11-17 21:41:58 +00009370 case scAddRecExpr: {
9371 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman8ea83d82010-11-18 00:34:22 +00009372 // to test for proper dominance too, because the instruction which
9373 // produces the addrec's value is a PHI, and a PHI effectively properly
9374 // dominates its entire containing block.
Dan Gohman20d9ce22010-11-17 21:41:58 +00009375 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009376 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009377 return DoesNotDominateBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009378 }
9379 // FALL THROUGH into SCEVNAryExpr handling.
9380 case scAddExpr:
9381 case scMulExpr:
9382 case scUMaxExpr:
9383 case scSMaxExpr: {
9384 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009385 bool Proper = true;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00009386 for (const SCEV *NAryOp : NAry->operands()) {
9387 BlockDisposition D = getBlockDisposition(NAryOp, BB);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009388 if (D == DoesNotDominateBlock)
9389 return DoesNotDominateBlock;
9390 if (D == DominatesBlock)
9391 Proper = false;
9392 }
9393 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009394 }
9395 case scUDivExpr: {
9396 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009397 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
9398 BlockDisposition LD = getBlockDisposition(LHS, BB);
9399 if (LD == DoesNotDominateBlock)
9400 return DoesNotDominateBlock;
9401 BlockDisposition RD = getBlockDisposition(RHS, BB);
9402 if (RD == DoesNotDominateBlock)
9403 return DoesNotDominateBlock;
9404 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
9405 ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009406 }
9407 case scUnknown:
9408 if (Instruction *I =
Dan Gohman8ea83d82010-11-18 00:34:22 +00009409 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
9410 if (I->getParent() == BB)
9411 return DominatesBlock;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009412 if (DT.properlyDominates(I->getParent(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009413 return ProperlyDominatesBlock;
9414 return DoesNotDominateBlock;
9415 }
9416 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009417 case scCouldNotCompute:
9418 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman20d9ce22010-11-17 21:41:58 +00009419 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009420 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman8ea83d82010-11-18 00:34:22 +00009421}
9422
9423bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
9424 return getBlockDisposition(S, BB) >= DominatesBlock;
9425}
9426
9427bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
9428 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009429}
Dan Gohman534749b2010-11-17 22:27:42 +00009430
9431bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
Sanjoy Das7d752672015-12-08 04:32:54 +00009432 // Search for a SCEV expression node within an expression tree.
9433 // Implements SCEVTraversal::Visitor.
9434 struct SCEVSearch {
9435 const SCEV *Node;
9436 bool IsFound;
9437
9438 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
9439
9440 bool follow(const SCEV *S) {
9441 IsFound |= (S == Node);
9442 return !IsFound;
9443 }
9444 bool isDone() const { return IsFound; }
9445 };
9446
Andrew Trick365e31c2012-07-13 23:33:03 +00009447 SCEVSearch Search(Op);
9448 visitAll(S, Search);
9449 return Search.IsFound;
Dan Gohman534749b2010-11-17 22:27:42 +00009450}
Dan Gohman7e6b3932010-11-17 23:28:48 +00009451
9452void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
9453 ValuesAtScopes.erase(S);
9454 LoopDispositions.erase(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009455 BlockDispositions.erase(S);
Dan Gohman7e6b3932010-11-17 23:28:48 +00009456 UnsignedRanges.erase(S);
9457 SignedRanges.erase(S);
Wei Mia49559b2016-02-04 01:27:38 +00009458 ExprValueMap.erase(S);
9459 HasRecMap.erase(S);
Andrew Trick9093e152013-03-26 03:14:53 +00009460
9461 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
9462 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); I != E; ) {
9463 BackedgeTakenInfo &BEInfo = I->second;
9464 if (BEInfo.hasOperand(S, this)) {
9465 BEInfo.clear();
9466 BackedgeTakenCounts.erase(I++);
9467 }
9468 else
9469 ++I;
9470 }
Dan Gohman7e6b3932010-11-17 23:28:48 +00009471}
Benjamin Kramer214935e2012-10-26 17:31:32 +00009472
9473typedef DenseMap<const Loop *, std::string> VerifyMap;
Benjamin Kramer24d270d2012-10-27 10:45:01 +00009474
Alp Tokercb402912014-01-24 17:20:08 +00009475/// replaceSubString - Replaces all occurrences of From in Str with To.
Benjamin Kramer24d270d2012-10-27 10:45:01 +00009476static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
9477 size_t Pos = 0;
9478 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
9479 Str.replace(Pos, From.size(), To.data(), To.size());
9480 Pos += To.size();
9481 }
9482}
9483
Benjamin Kramer214935e2012-10-26 17:31:32 +00009484/// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
9485static void
9486getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
Sanjoy Das2fbfb252015-12-23 17:48:14 +00009487 std::string &S = Map[L];
9488 if (S.empty()) {
9489 raw_string_ostream OS(S);
9490 SE.getBackedgeTakenCount(L)->print(OS);
Benjamin Kramer214935e2012-10-26 17:31:32 +00009491
Sanjoy Das2fbfb252015-12-23 17:48:14 +00009492 // false and 0 are semantically equivalent. This can happen in dead loops.
9493 replaceSubString(OS.str(), "false", "0");
9494 // Remove wrap flags, their use in SCEV is highly fragile.
9495 // FIXME: Remove this when SCEV gets smarter about them.
9496 replaceSubString(OS.str(), "<nw>", "");
9497 replaceSubString(OS.str(), "<nsw>", "");
9498 replaceSubString(OS.str(), "<nuw>", "");
Benjamin Kramer214935e2012-10-26 17:31:32 +00009499 }
Sanjoy Das2fbfb252015-12-23 17:48:14 +00009500
JF Bastien61ad8b32015-12-23 18:18:53 +00009501 for (auto *R : reverse(*L))
9502 getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
Benjamin Kramer214935e2012-10-26 17:31:32 +00009503}
9504
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009505void ScalarEvolution::verify() const {
Benjamin Kramer214935e2012-10-26 17:31:32 +00009506 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9507
9508 // Gather stringified backedge taken counts for all loops using SCEV's caches.
9509 // FIXME: It would be much better to store actual values instead of strings,
9510 // but SCEV pointers will change if we drop the caches.
9511 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009512 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
Benjamin Kramer214935e2012-10-26 17:31:32 +00009513 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
9514
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009515 // Gather stringified backedge taken counts for all loops using a fresh
9516 // ScalarEvolution object.
9517 ScalarEvolution SE2(F, TLI, AC, DT, LI);
9518 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
9519 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
Benjamin Kramer214935e2012-10-26 17:31:32 +00009520
9521 // Now compare whether they're the same with and without caches. This allows
9522 // verifying that no pass changed the cache.
9523 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
9524 "New loops suddenly appeared!");
9525
9526 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
9527 OldE = BackedgeDumpsOld.end(),
9528 NewI = BackedgeDumpsNew.begin();
9529 OldI != OldE; ++OldI, ++NewI) {
9530 assert(OldI->first == NewI->first && "Loop order changed!");
9531
9532 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
9533 // changes.
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009534 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
Benjamin Kramer214935e2012-10-26 17:31:32 +00009535 // means that a pass is buggy or SCEV has to learn a new pattern but is
9536 // usually not harmful.
9537 if (OldI->second != NewI->second &&
9538 OldI->second.find("undef") == std::string::npos &&
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009539 NewI->second.find("undef") == std::string::npos &&
9540 OldI->second != "***COULDNOTCOMPUTE***" &&
Benjamin Kramer214935e2012-10-26 17:31:32 +00009541 NewI->second != "***COULDNOTCOMPUTE***") {
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009542 dbgs() << "SCEVValidator: SCEV for loop '"
Benjamin Kramer214935e2012-10-26 17:31:32 +00009543 << OldI->first->getHeader()->getName()
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009544 << "' changed from '" << OldI->second
9545 << "' to '" << NewI->second << "'!\n";
Benjamin Kramer214935e2012-10-26 17:31:32 +00009546 std::abort();
9547 }
9548 }
9549
9550 // TODO: Verify more things.
9551}
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009552
9553char ScalarEvolutionAnalysis::PassID;
9554
9555ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
9556 AnalysisManager<Function> *AM) {
9557 return ScalarEvolution(F, AM->getResult<TargetLibraryAnalysis>(F),
9558 AM->getResult<AssumptionAnalysis>(F),
9559 AM->getResult<DominatorTreeAnalysis>(F),
9560 AM->getResult<LoopAnalysis>(F));
9561}
9562
9563PreservedAnalyses
9564ScalarEvolutionPrinterPass::run(Function &F, AnalysisManager<Function> *AM) {
9565 AM->getResult<ScalarEvolutionAnalysis>(F).print(OS);
9566 return PreservedAnalyses::all();
9567}
9568
9569INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
9570 "Scalar Evolution Analysis", false, true)
9571INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
9572INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
9573INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
9574INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
9575INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
9576 "Scalar Evolution Analysis", false, true)
9577char ScalarEvolutionWrapperPass::ID = 0;
9578
9579ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
9580 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
9581}
9582
9583bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
9584 SE.reset(new ScalarEvolution(
9585 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
9586 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
9587 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
9588 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
9589 return false;
9590}
9591
9592void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
9593
9594void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
9595 SE->print(OS);
9596}
9597
9598void ScalarEvolutionWrapperPass::verifyAnalysis() const {
9599 if (!VerifySCEV)
9600 return;
9601
9602 SE->verify();
9603}
9604
9605void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
9606 AU.setPreservesAll();
9607 AU.addRequiredTransitive<AssumptionCacheTracker>();
9608 AU.addRequiredTransitive<LoopInfoWrapperPass>();
9609 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
9610 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
9611}
Silviu Barangae3c05342015-11-02 14:41:02 +00009612
9613const SCEVPredicate *
9614ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
9615 const SCEVConstant *RHS) {
9616 FoldingSetNodeID ID;
9617 // Unique this node based on the arguments
9618 ID.AddInteger(SCEVPredicate::P_Equal);
9619 ID.AddPointer(LHS);
9620 ID.AddPointer(RHS);
9621 void *IP = nullptr;
9622 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
9623 return S;
9624 SCEVEqualPredicate *Eq = new (SCEVAllocator)
9625 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
9626 UniquePreds.InsertNode(Eq, IP);
9627 return Eq;
9628}
9629
Benjamin Kramer83709b12015-11-16 09:01:28 +00009630namespace {
Silviu Barangae3c05342015-11-02 14:41:02 +00009631class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
9632public:
9633 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
9634 SCEVUnionPredicate &A) {
9635 SCEVPredicateRewriter Rewriter(SE, A);
9636 return Rewriter.visit(Scev);
9637 }
9638
9639 SCEVPredicateRewriter(ScalarEvolution &SE, SCEVUnionPredicate &P)
9640 : SCEVRewriteVisitor(SE), P(P) {}
9641
9642 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
9643 auto ExprPreds = P.getPredicatesForExpr(Expr);
9644 for (auto *Pred : ExprPreds)
9645 if (const auto *IPred = dyn_cast<const SCEVEqualPredicate>(Pred))
9646 if (IPred->getLHS() == Expr)
9647 return IPred->getRHS();
9648
9649 return Expr;
9650 }
9651
9652private:
9653 SCEVUnionPredicate &P;
9654};
Benjamin Kramer83709b12015-11-16 09:01:28 +00009655} // end anonymous namespace
Silviu Barangae3c05342015-11-02 14:41:02 +00009656
9657const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *Scev,
9658 SCEVUnionPredicate &Preds) {
9659 return SCEVPredicateRewriter::rewrite(Scev, *this, Preds);
9660}
9661
9662/// SCEV predicates
9663SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
9664 SCEVPredicateKind Kind)
9665 : FastID(ID), Kind(Kind) {}
9666
9667SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
9668 const SCEVUnknown *LHS,
9669 const SCEVConstant *RHS)
9670 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
9671
9672bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
9673 const auto *Op = dyn_cast<const SCEVEqualPredicate>(N);
9674
9675 if (!Op)
9676 return false;
9677
9678 return Op->LHS == LHS && Op->RHS == RHS;
9679}
9680
9681bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
9682
9683const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
9684
9685void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
9686 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
9687}
9688
9689/// Union predicates don't get cached so create a dummy set ID for it.
9690SCEVUnionPredicate::SCEVUnionPredicate()
9691 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
9692
9693bool SCEVUnionPredicate::isAlwaysTrue() const {
Sanjoy Das3b827c72015-11-29 23:40:53 +00009694 return all_of(Preds,
9695 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
Silviu Barangae3c05342015-11-02 14:41:02 +00009696}
9697
9698ArrayRef<const SCEVPredicate *>
9699SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
9700 auto I = SCEVToPreds.find(Expr);
9701 if (I == SCEVToPreds.end())
9702 return ArrayRef<const SCEVPredicate *>();
9703 return I->second;
9704}
9705
9706bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
9707 if (const auto *Set = dyn_cast<const SCEVUnionPredicate>(N))
Sanjoy Das3b827c72015-11-29 23:40:53 +00009708 return all_of(Set->Preds,
9709 [this](const SCEVPredicate *I) { return this->implies(I); });
Silviu Barangae3c05342015-11-02 14:41:02 +00009710
9711 auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
9712 if (ScevPredsIt == SCEVToPreds.end())
9713 return false;
9714 auto &SCEVPreds = ScevPredsIt->second;
9715
Sanjoy Dasff3b8b42015-12-01 07:49:23 +00009716 return any_of(SCEVPreds,
9717 [N](const SCEVPredicate *I) { return I->implies(N); });
Silviu Barangae3c05342015-11-02 14:41:02 +00009718}
9719
9720const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
9721
9722void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
9723 for (auto Pred : Preds)
9724 Pred->print(OS, Depth);
9725}
9726
9727void SCEVUnionPredicate::add(const SCEVPredicate *N) {
9728 if (const auto *Set = dyn_cast<const SCEVUnionPredicate>(N)) {
9729 for (auto Pred : Set->Preds)
9730 add(Pred);
9731 return;
9732 }
9733
9734 if (implies(N))
9735 return;
9736
9737 const SCEV *Key = N->getExpr();
9738 assert(Key && "Only SCEVUnionPredicate doesn't have an "
9739 " associated expression!");
9740
9741 SCEVToPreds[Key].push_back(N);
9742 Preds.push_back(N);
9743}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00009744
9745PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE)
9746 : SE(SE), Generation(0) {}
9747
9748const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
9749 const SCEV *Expr = SE.getSCEV(V);
9750 RewriteEntry &Entry = RewriteMap[Expr];
9751
9752 // If we already have an entry and the version matches, return it.
9753 if (Entry.second && Generation == Entry.first)
9754 return Entry.second;
9755
9756 // We found an entry but it's stale. Rewrite the stale entry
9757 // acording to the current predicate.
9758 if (Entry.second)
9759 Expr = Entry.second;
9760
9761 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, Preds);
9762 Entry = {Generation, NewSCEV};
9763
9764 return NewSCEV;
9765}
9766
9767void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
9768 if (Preds.implies(&Pred))
9769 return;
9770 Preds.add(&Pred);
9771 updateGeneration();
9772}
9773
9774const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
9775 return Preds;
9776}
9777
9778void PredicatedScalarEvolution::updateGeneration() {
9779 // If the generation number wrapped recompute everything.
9780 if (++Generation == 0) {
9781 for (auto &II : RewriteMap) {
9782 const SCEV *Rewritten = II.second.second;
9783 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, Preds)};
9784 }
9785 }
9786}