blob: 108e510b6f327f152b0f7a480f5037b2b72a6dd0 [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"
Chris Lattner996795b2006-06-28 23:17:24 +000086#include "llvm/Support/CommandLine.h"
David Greene2330f782009-12-23 22:58:38 +000087#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000088#include "llvm/Support/ErrorHandling.h"
Chris Lattner0a1e9932006-12-19 01:16:02 +000089#include "llvm/Support/MathExtras.h"
Dan Gohmane20f8242009-04-21 00:47:46 +000090#include "llvm/Support/raw_ostream.h"
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +000091#include "llvm/Support/SaveAndRestore.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000092#include <algorithm>
Chris Lattnerd934c702004-04-02 20:23:17 +000093using namespace llvm;
94
Chandler Carruthf1221bd2014-04-22 02:48:03 +000095#define DEBUG_TYPE "scalar-evolution"
96
Chris Lattner57ef9422006-12-19 22:30:33 +000097STATISTIC(NumArrayLenItCounts,
98 "Number of trip counts computed with array length");
99STATISTIC(NumTripCountsComputed,
100 "Number of loops with predictable loop counts");
101STATISTIC(NumTripCountsNotComputed,
102 "Number of loops without predictable loop counts");
103STATISTIC(NumBruteForceTripCountsComputed,
104 "Number of loops with trip counts computed by force");
105
Dan Gohmand78c4002008-05-13 00:00:25 +0000106static cl::opt<unsigned>
Chris Lattner57ef9422006-12-19 22:30:33 +0000107MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
108 cl::desc("Maximum number of iterations SCEV will "
Dan Gohmance973df2009-06-24 04:48:43 +0000109 "symbolically execute a constant "
110 "derived loop"),
Chris Lattner57ef9422006-12-19 22:30:33 +0000111 cl::init(100));
112
Benjamin Kramer214935e2012-10-26 17:31:32 +0000113// FIXME: Enable this with XDEBUG when the test suite is clean.
114static cl::opt<bool>
115VerifySCEV("verify-scev",
116 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
117
Chris Lattnerd934c702004-04-02 20:23:17 +0000118//===----------------------------------------------------------------------===//
119// SCEV class definitions
120//===----------------------------------------------------------------------===//
121
122//===----------------------------------------------------------------------===//
123// Implementation of the SCEV class.
124//
Dan Gohman3423e722009-06-30 20:13:32 +0000125
Manman Ren49d684e2012-09-12 05:06:18 +0000126#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chris Lattnerd934c702004-04-02 20:23:17 +0000127void SCEV::dump() const {
David Greenedf1c4972009-12-23 22:18:14 +0000128 print(dbgs());
129 dbgs() << '\n';
Dan Gohmane20f8242009-04-21 00:47:46 +0000130}
Manman Renc3366cc2012-09-06 19:55:56 +0000131#endif
Dan Gohmane20f8242009-04-21 00:47:46 +0000132
Dan Gohman534749b2010-11-17 22:27:42 +0000133void SCEV::print(raw_ostream &OS) const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000134 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000135 case scConstant:
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000136 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000137 return;
138 case scTruncate: {
139 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
140 const SCEV *Op = Trunc->getOperand();
141 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
142 << *Trunc->getType() << ")";
143 return;
144 }
145 case scZeroExtend: {
146 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
147 const SCEV *Op = ZExt->getOperand();
148 OS << "(zext " << *Op->getType() << " " << *Op << " to "
149 << *ZExt->getType() << ")";
150 return;
151 }
152 case scSignExtend: {
153 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
154 const SCEV *Op = SExt->getOperand();
155 OS << "(sext " << *Op->getType() << " " << *Op << " to "
156 << *SExt->getType() << ")";
157 return;
158 }
159 case scAddRecExpr: {
160 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
161 OS << "{" << *AR->getOperand(0);
162 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
163 OS << ",+," << *AR->getOperand(i);
164 OS << "}<";
Andrew Trick8b55b732011-03-14 16:50:06 +0000165 if (AR->getNoWrapFlags(FlagNUW))
Chris Lattnera337f5e2011-01-09 02:16:18 +0000166 OS << "nuw><";
Andrew Trick8b55b732011-03-14 16:50:06 +0000167 if (AR->getNoWrapFlags(FlagNSW))
Chris Lattnera337f5e2011-01-09 02:16:18 +0000168 OS << "nsw><";
Andrew Trick8b55b732011-03-14 16:50:06 +0000169 if (AR->getNoWrapFlags(FlagNW) &&
170 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
171 OS << "nw><";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000172 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman534749b2010-11-17 22:27:42 +0000173 OS << ">";
174 return;
175 }
176 case scAddExpr:
177 case scMulExpr:
178 case scUMaxExpr:
179 case scSMaxExpr: {
180 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
Craig Topper9f008862014-04-15 04:59:12 +0000181 const char *OpStr = nullptr;
Dan Gohman534749b2010-11-17 22:27:42 +0000182 switch (NAry->getSCEVType()) {
183 case scAddExpr: OpStr = " + "; break;
184 case scMulExpr: OpStr = " * "; break;
185 case scUMaxExpr: OpStr = " umax "; break;
186 case scSMaxExpr: OpStr = " smax "; break;
187 }
188 OS << "(";
189 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
190 I != E; ++I) {
191 OS << **I;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000192 if (std::next(I) != E)
Dan Gohman534749b2010-11-17 22:27:42 +0000193 OS << OpStr;
194 }
195 OS << ")";
Andrew Trickd912a5b2011-11-29 02:06:35 +0000196 switch (NAry->getSCEVType()) {
197 case scAddExpr:
198 case scMulExpr:
199 if (NAry->getNoWrapFlags(FlagNUW))
200 OS << "<nuw>";
201 if (NAry->getNoWrapFlags(FlagNSW))
202 OS << "<nsw>";
203 }
Dan Gohman534749b2010-11-17 22:27:42 +0000204 return;
205 }
206 case scUDivExpr: {
207 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
208 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
209 return;
210 }
211 case scUnknown: {
212 const SCEVUnknown *U = cast<SCEVUnknown>(this);
Chris Lattner229907c2011-07-18 04:54:35 +0000213 Type *AllocTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000214 if (U->isSizeOf(AllocTy)) {
215 OS << "sizeof(" << *AllocTy << ")";
216 return;
217 }
218 if (U->isAlignOf(AllocTy)) {
219 OS << "alignof(" << *AllocTy << ")";
220 return;
221 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000222
Chris Lattner229907c2011-07-18 04:54:35 +0000223 Type *CTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000224 Constant *FieldNo;
225 if (U->isOffsetOf(CTy, FieldNo)) {
226 OS << "offsetof(" << *CTy << ", ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000227 FieldNo->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000228 OS << ")";
229 return;
230 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000231
Dan Gohman534749b2010-11-17 22:27:42 +0000232 // Otherwise just print it normally.
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000233 U->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000234 return;
235 }
236 case scCouldNotCompute:
237 OS << "***COULDNOTCOMPUTE***";
238 return;
Dan Gohman534749b2010-11-17 22:27:42 +0000239 }
240 llvm_unreachable("Unknown SCEV kind!");
241}
242
Chris Lattner229907c2011-07-18 04:54:35 +0000243Type *SCEV::getType() const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000244 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000245 case scConstant:
246 return cast<SCEVConstant>(this)->getType();
247 case scTruncate:
248 case scZeroExtend:
249 case scSignExtend:
250 return cast<SCEVCastExpr>(this)->getType();
251 case scAddRecExpr:
252 case scMulExpr:
253 case scUMaxExpr:
254 case scSMaxExpr:
255 return cast<SCEVNAryExpr>(this)->getType();
256 case scAddExpr:
257 return cast<SCEVAddExpr>(this)->getType();
258 case scUDivExpr:
259 return cast<SCEVUDivExpr>(this)->getType();
260 case scUnknown:
261 return cast<SCEVUnknown>(this)->getType();
262 case scCouldNotCompute:
263 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman534749b2010-11-17 22:27:42 +0000264 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000265 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman534749b2010-11-17 22:27:42 +0000266}
267
Dan Gohmanbe928e32008-06-18 16:23:07 +0000268bool SCEV::isZero() const {
269 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
270 return SC->getValue()->isZero();
271 return false;
272}
273
Dan Gohmanba7f6d82009-05-18 15:22:39 +0000274bool SCEV::isOne() const {
275 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
276 return SC->getValue()->isOne();
277 return false;
278}
Chris Lattnerd934c702004-04-02 20:23:17 +0000279
Dan Gohman18a96bb2009-06-24 00:30:26 +0000280bool SCEV::isAllOnesValue() const {
281 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
282 return SC->getValue()->isAllOnesValue();
283 return false;
284}
285
Andrew Trick881a7762012-01-07 00:27:31 +0000286/// isNonConstantNegative - Return true if the specified scev is negated, but
287/// not a constant.
288bool SCEV::isNonConstantNegative() const {
289 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
290 if (!Mul) return false;
291
292 // If there is a constant factor, it will be first.
293 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
294 if (!SC) return false;
295
296 // Return true if the value is negative, this matches things like (-42 * V).
297 return SC->getValue()->getValue().isNegative();
298}
299
Owen Anderson04052ec2009-06-22 21:57:23 +0000300SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman24ceda82010-06-18 19:54:20 +0000301 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000302
Chris Lattnerd934c702004-04-02 20:23:17 +0000303bool SCEVCouldNotCompute::classof(const SCEV *S) {
304 return S->getSCEVType() == scCouldNotCompute;
305}
306
Dan Gohmanaf752342009-07-07 17:06:11 +0000307const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000308 FoldingSetNodeID ID;
309 ID.AddInteger(scConstant);
310 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +0000311 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000312 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman24ceda82010-06-18 19:54:20 +0000313 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000314 UniqueSCEVs.InsertNode(S, IP);
315 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000316}
Chris Lattnerd934c702004-04-02 20:23:17 +0000317
Nick Lewycky31eaca52014-01-27 10:04:03 +0000318const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000319 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman0a76e7f2007-07-09 15:25:17 +0000320}
321
Dan Gohmanaf752342009-07-07 17:06:11 +0000322const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +0000323ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
324 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Dan Gohmana029cbe2010-04-21 16:04:04 +0000325 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000326}
327
Dan Gohman24ceda82010-06-18 19:54:20 +0000328SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000329 unsigned SCEVTy, const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000330 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000331
Dan Gohman24ceda82010-06-18 19:54:20 +0000332SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000333 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000334 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000335 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
336 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000337 "Cannot truncate non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000338}
Chris Lattnerd934c702004-04-02 20:23:17 +0000339
Dan Gohman24ceda82010-06-18 19:54:20 +0000340SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000341 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000342 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000343 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
344 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000345 "Cannot zero extend non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000346}
347
Dan Gohman24ceda82010-06-18 19:54:20 +0000348SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000349 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000350 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000351 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
352 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000353 "Cannot sign extend non-integer value!");
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000354}
355
Dan Gohman7cac9572010-08-02 23:49:30 +0000356void SCEVUnknown::deleted() {
Dan Gohman761065e2010-11-17 02:44:44 +0000357 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000358 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000359
360 // Remove this SCEVUnknown from the uniquing map.
361 SE->UniqueSCEVs.RemoveNode(this);
362
363 // Release the value.
Craig Topper9f008862014-04-15 04:59:12 +0000364 setValPtr(nullptr);
Dan Gohman7cac9572010-08-02 23:49:30 +0000365}
366
367void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman761065e2010-11-17 02:44:44 +0000368 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000369 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000370
371 // Remove this SCEVUnknown from the uniquing map.
372 SE->UniqueSCEVs.RemoveNode(this);
373
374 // Update this SCEVUnknown to point to the new value. This is needed
375 // because there may still be outstanding SCEVs which still point to
376 // this SCEVUnknown.
377 setValPtr(New);
378}
379
Chris Lattner229907c2011-07-18 04:54:35 +0000380bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000381 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000382 if (VCE->getOpcode() == Instruction::PtrToInt)
383 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000384 if (CE->getOpcode() == Instruction::GetElementPtr &&
385 CE->getOperand(0)->isNullValue() &&
386 CE->getNumOperands() == 2)
387 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
388 if (CI->isOne()) {
389 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
390 ->getElementType();
391 return true;
392 }
Dan Gohmancf913832010-01-28 02:15:55 +0000393
394 return false;
395}
396
Chris Lattner229907c2011-07-18 04:54:35 +0000397bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000398 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000399 if (VCE->getOpcode() == Instruction::PtrToInt)
400 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000401 if (CE->getOpcode() == Instruction::GetElementPtr &&
402 CE->getOperand(0)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000403 Type *Ty =
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000404 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000405 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000406 if (!STy->isPacked() &&
407 CE->getNumOperands() == 3 &&
408 CE->getOperand(1)->isNullValue()) {
409 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
410 if (CI->isOne() &&
411 STy->getNumElements() == 2 &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000412 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000413 AllocTy = STy->getElementType(1);
414 return true;
415 }
416 }
417 }
Dan Gohmancf913832010-01-28 02:15:55 +0000418
419 return false;
420}
421
Chris Lattner229907c2011-07-18 04:54:35 +0000422bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000423 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000424 if (VCE->getOpcode() == Instruction::PtrToInt)
425 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
426 if (CE->getOpcode() == Instruction::GetElementPtr &&
427 CE->getNumOperands() == 3 &&
428 CE->getOperand(0)->isNullValue() &&
429 CE->getOperand(1)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000430 Type *Ty =
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000431 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
432 // Ignore vector types here so that ScalarEvolutionExpander doesn't
433 // emit getelementptrs that index into vectors.
Duncan Sands19d0b472010-02-16 11:11:14 +0000434 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000435 CTy = Ty;
436 FieldNo = CE->getOperand(2);
437 return true;
438 }
439 }
440
441 return false;
442}
443
Chris Lattnereb3e8402004-06-20 06:23:15 +0000444//===----------------------------------------------------------------------===//
445// SCEV Utilities
446//===----------------------------------------------------------------------===//
447
448namespace {
449 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
450 /// than the complexity of the RHS. This comparator is used to canonicalize
451 /// expressions.
Nick Lewycky02d5f772009-10-25 06:33:48 +0000452 class SCEVComplexityCompare {
Dan Gohman3324b9e2010-08-13 20:17:27 +0000453 const LoopInfo *const LI;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000454 public:
Dan Gohman992db002010-07-23 21:18:55 +0000455 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman9ba542c2009-05-07 14:39:04 +0000456
Dan Gohman27065672010-08-27 15:26:01 +0000457 // Return true or false if LHS is less than, or at least RHS, respectively.
Dan Gohman5e6ce7b2008-04-14 18:23:56 +0000458 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman27065672010-08-27 15:26:01 +0000459 return compare(LHS, RHS) < 0;
460 }
461
462 // Return negative, zero, or positive, if LHS is less than, equal to, or
463 // greater than RHS, respectively. A three-way result allows recursive
464 // comparisons to be more efficient.
465 int compare(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000466 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
467 if (LHS == RHS)
Dan Gohman27065672010-08-27 15:26:01 +0000468 return 0;
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000469
Dan Gohman9ba542c2009-05-07 14:39:04 +0000470 // Primarily, sort the SCEVs by their getSCEVType().
Dan Gohman5ae31022010-07-23 21:20:52 +0000471 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
472 if (LType != RType)
Dan Gohman27065672010-08-27 15:26:01 +0000473 return (int)LType - (int)RType;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000474
Dan Gohman24ceda82010-06-18 19:54:20 +0000475 // Aside from the getSCEVType() ordering, the particular ordering
476 // isn't very important except that it's beneficial to be consistent,
477 // so that (a + b) and (b + a) don't end up as different expressions.
Benjamin Kramer987b8502014-02-11 19:02:55 +0000478 switch (static_cast<SCEVTypes>(LType)) {
Dan Gohman27065672010-08-27 15:26:01 +0000479 case scUnknown: {
480 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000481 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000482
483 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
484 // not as complete as it could be.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000485 const Value *LV = LU->getValue(), *RV = RU->getValue();
Dan Gohman24ceda82010-06-18 19:54:20 +0000486
487 // Order pointer values after integer values. This helps SCEVExpander
488 // form GEPs.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000489 bool LIsPointer = LV->getType()->isPointerTy(),
490 RIsPointer = RV->getType()->isPointerTy();
Dan Gohman5ae31022010-07-23 21:20:52 +0000491 if (LIsPointer != RIsPointer)
Dan Gohman27065672010-08-27 15:26:01 +0000492 return (int)LIsPointer - (int)RIsPointer;
Dan Gohman24ceda82010-06-18 19:54:20 +0000493
494 // Compare getValueID values.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000495 unsigned LID = LV->getValueID(),
496 RID = RV->getValueID();
Dan Gohman5ae31022010-07-23 21:20:52 +0000497 if (LID != RID)
Dan Gohman27065672010-08-27 15:26:01 +0000498 return (int)LID - (int)RID;
Dan Gohman24ceda82010-06-18 19:54:20 +0000499
500 // Sort arguments by their position.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000501 if (const Argument *LA = dyn_cast<Argument>(LV)) {
502 const Argument *RA = cast<Argument>(RV);
Dan Gohman27065672010-08-27 15:26:01 +0000503 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
504 return (int)LArgNo - (int)RArgNo;
Dan Gohman24ceda82010-06-18 19:54:20 +0000505 }
506
Dan Gohman27065672010-08-27 15:26:01 +0000507 // For instructions, compare their loop depth, and their operand
508 // count. This is pretty loose.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000509 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
510 const Instruction *RInst = cast<Instruction>(RV);
Dan Gohman24ceda82010-06-18 19:54:20 +0000511
512 // Compare loop depths.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000513 const BasicBlock *LParent = LInst->getParent(),
514 *RParent = RInst->getParent();
515 if (LParent != RParent) {
516 unsigned LDepth = LI->getLoopDepth(LParent),
517 RDepth = LI->getLoopDepth(RParent);
518 if (LDepth != RDepth)
Dan Gohman27065672010-08-27 15:26:01 +0000519 return (int)LDepth - (int)RDepth;
Dan Gohman0c436ab2010-08-13 21:24:58 +0000520 }
Dan Gohman24ceda82010-06-18 19:54:20 +0000521
522 // Compare the number of operands.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000523 unsigned LNumOps = LInst->getNumOperands(),
524 RNumOps = RInst->getNumOperands();
Dan Gohman27065672010-08-27 15:26:01 +0000525 return (int)LNumOps - (int)RNumOps;
Dan Gohman24ceda82010-06-18 19:54:20 +0000526 }
527
Dan Gohman27065672010-08-27 15:26:01 +0000528 return 0;
Dan Gohman24ceda82010-06-18 19:54:20 +0000529 }
530
Dan Gohman27065672010-08-27 15:26:01 +0000531 case scConstant: {
532 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000533 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000534
535 // Compare constant values.
Dan Gohmanf2961822010-08-16 16:25:35 +0000536 const APInt &LA = LC->getValue()->getValue();
537 const APInt &RA = RC->getValue()->getValue();
538 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
Dan Gohman5ae31022010-07-23 21:20:52 +0000539 if (LBitWidth != RBitWidth)
Dan Gohman27065672010-08-27 15:26:01 +0000540 return (int)LBitWidth - (int)RBitWidth;
541 return LA.ult(RA) ? -1 : 1;
Dan Gohman24ceda82010-06-18 19:54:20 +0000542 }
543
Dan Gohman27065672010-08-27 15:26:01 +0000544 case scAddRecExpr: {
545 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000546 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000547
548 // Compare addrec loop depths.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000549 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
550 if (LLoop != RLoop) {
551 unsigned LDepth = LLoop->getLoopDepth(),
552 RDepth = RLoop->getLoopDepth();
553 if (LDepth != RDepth)
Dan Gohman27065672010-08-27 15:26:01 +0000554 return (int)LDepth - (int)RDepth;
Dan Gohman0c436ab2010-08-13 21:24:58 +0000555 }
Dan Gohman27065672010-08-27 15:26:01 +0000556
557 // Addrec complexity grows with operand count.
558 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
559 if (LNumOps != RNumOps)
560 return (int)LNumOps - (int)RNumOps;
561
562 // Lexicographically compare.
563 for (unsigned i = 0; i != LNumOps; ++i) {
564 long X = compare(LA->getOperand(i), RA->getOperand(i));
565 if (X != 0)
566 return X;
567 }
568
569 return 0;
Dan Gohman24ceda82010-06-18 19:54:20 +0000570 }
571
Dan Gohman27065672010-08-27 15:26:01 +0000572 case scAddExpr:
573 case scMulExpr:
574 case scSMaxExpr:
575 case scUMaxExpr: {
576 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000577 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000578
579 // Lexicographically compare n-ary expressions.
Dan Gohman5ae31022010-07-23 21:20:52 +0000580 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
Andrew Trickc3bc8b82013-07-31 02:43:40 +0000581 if (LNumOps != RNumOps)
582 return (int)LNumOps - (int)RNumOps;
583
Dan Gohman5ae31022010-07-23 21:20:52 +0000584 for (unsigned i = 0; i != LNumOps; ++i) {
585 if (i >= RNumOps)
Dan Gohman27065672010-08-27 15:26:01 +0000586 return 1;
587 long X = compare(LC->getOperand(i), RC->getOperand(i));
588 if (X != 0)
589 return X;
Dan Gohman24ceda82010-06-18 19:54:20 +0000590 }
Dan Gohman27065672010-08-27 15:26:01 +0000591 return (int)LNumOps - (int)RNumOps;
Dan Gohman24ceda82010-06-18 19:54:20 +0000592 }
593
Dan Gohman27065672010-08-27 15:26:01 +0000594 case scUDivExpr: {
595 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000596 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000597
598 // Lexicographically compare udiv expressions.
599 long X = compare(LC->getLHS(), RC->getLHS());
600 if (X != 0)
601 return X;
602 return compare(LC->getRHS(), RC->getRHS());
Dan Gohman24ceda82010-06-18 19:54:20 +0000603 }
604
Dan Gohman27065672010-08-27 15:26:01 +0000605 case scTruncate:
606 case scZeroExtend:
607 case scSignExtend: {
608 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000609 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000610
611 // Compare cast expressions by operand.
612 return compare(LC->getOperand(), RC->getOperand());
613 }
614
Benjamin Kramer987b8502014-02-11 19:02:55 +0000615 case scCouldNotCompute:
616 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman24ceda82010-06-18 19:54:20 +0000617 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000618 llvm_unreachable("Unknown SCEV kind!");
Chris Lattnereb3e8402004-06-20 06:23:15 +0000619 }
620 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000621}
Chris Lattnereb3e8402004-06-20 06:23:15 +0000622
623/// GroupByComplexity - Given a list of SCEV objects, order them by their
624/// complexity, and group objects of the same complexity together by value.
625/// When this routine is finished, we know that any duplicates in the vector are
626/// consecutive and that complexity is monotonically increasing.
627///
Dan Gohman8b0a4192010-03-01 17:49:51 +0000628/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattnereb3e8402004-06-20 06:23:15 +0000629/// results from this routine. In other words, we don't want the results of
630/// this to depend on where the addresses of various SCEV objects happened to
631/// land in memory.
632///
Dan Gohmanaf752342009-07-07 17:06:11 +0000633static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman9ba542c2009-05-07 14:39:04 +0000634 LoopInfo *LI) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000635 if (Ops.size() < 2) return; // Noop
636 if (Ops.size() == 2) {
637 // This is the common case, which also happens to be trivially simple.
638 // Special case it.
Dan Gohman7712d292010-08-29 15:07:13 +0000639 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
640 if (SCEVComplexityCompare(LI)(RHS, LHS))
641 std::swap(LHS, RHS);
Chris Lattnereb3e8402004-06-20 06:23:15 +0000642 return;
643 }
644
Dan Gohman24ceda82010-06-18 19:54:20 +0000645 // Do the rough sort by complexity.
646 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
647
648 // Now that we are sorted by complexity, group elements of the same
649 // complexity. Note that this is, at worst, N^2, but the vector is likely to
650 // be extremely short in practice. Note that we take this approach because we
651 // do not want to depend on the addresses of the objects we are grouping.
652 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
653 const SCEV *S = Ops[i];
654 unsigned Complexity = S->getSCEVType();
655
656 // If there are any objects of the same complexity and same value as this
657 // one, group them.
658 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
659 if (Ops[j] == S) { // Found a duplicate.
660 // Move it to immediately after i'th element.
661 std::swap(Ops[i+1], Ops[j]);
662 ++i; // no need to rescan it.
663 if (i == e-2) return; // Done!
664 }
665 }
666 }
Chris Lattnereb3e8402004-06-20 06:23:15 +0000667}
668
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000669namespace {
670struct FindSCEVSize {
671 int Size;
672 FindSCEVSize() : Size(0) {}
673
674 bool follow(const SCEV *S) {
675 ++Size;
676 // Keep looking at all operands of S.
677 return true;
678 }
679 bool isDone() const {
680 return false;
681 }
682};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000683}
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000684
685// Returns the size of the SCEV S.
686static inline int sizeOfSCEV(const SCEV *S) {
687 FindSCEVSize F;
688 SCEVTraversal<FindSCEVSize> ST(F);
689 ST.visitAll(S);
690 return F.Size;
691}
692
693namespace {
694
David Majnemer4e879362014-12-14 09:12:33 +0000695struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000696public:
697 // Computes the Quotient and Remainder of the division of Numerator by
698 // Denominator.
699 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
700 const SCEV *Denominator, const SCEV **Quotient,
701 const SCEV **Remainder) {
702 assert(Numerator && Denominator && "Uninitialized SCEV");
703
David Majnemer4e879362014-12-14 09:12:33 +0000704 SCEVDivision D(SE, Numerator, Denominator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000705
706 // Check for the trivial case here to avoid having to check for it in the
707 // rest of the code.
708 if (Numerator == Denominator) {
709 *Quotient = D.One;
710 *Remainder = D.Zero;
711 return;
712 }
713
714 if (Numerator->isZero()) {
715 *Quotient = D.Zero;
716 *Remainder = D.Zero;
717 return;
718 }
719
Brendon Cahoona57cc8b2015-04-20 16:03:28 +0000720 // A simple case when N/1. The quotient is N.
721 if (Denominator->isOne()) {
722 *Quotient = Numerator;
723 *Remainder = D.Zero;
724 return;
725 }
726
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000727 // Split the Denominator when it is a product.
728 if (const SCEVMulExpr *T = dyn_cast<const SCEVMulExpr>(Denominator)) {
729 const SCEV *Q, *R;
730 *Quotient = Numerator;
731 for (const SCEV *Op : T->operands()) {
732 divide(SE, *Quotient, Op, &Q, &R);
733 *Quotient = Q;
734
735 // Bail out when the Numerator is not divisible by one of the terms of
736 // the Denominator.
737 if (!R->isZero()) {
738 *Quotient = D.Zero;
739 *Remainder = Numerator;
740 return;
741 }
742 }
743 *Remainder = D.Zero;
744 return;
745 }
746
747 D.visit(Numerator);
748 *Quotient = D.Quotient;
749 *Remainder = D.Remainder;
750 }
751
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000752 // Except in the trivial case described above, we do not know how to divide
753 // Expr by Denominator for the following functions with empty implementation.
754 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
755 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
756 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
757 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
758 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
759 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
760 void visitUnknown(const SCEVUnknown *Numerator) {}
761 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
762
David Majnemer4e879362014-12-14 09:12:33 +0000763 void visitConstant(const SCEVConstant *Numerator) {
764 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
765 APInt NumeratorVal = Numerator->getValue()->getValue();
766 APInt DenominatorVal = D->getValue()->getValue();
767 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
768 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
769
770 if (NumeratorBW > DenominatorBW)
771 DenominatorVal = DenominatorVal.sext(NumeratorBW);
772 else if (NumeratorBW < DenominatorBW)
773 NumeratorVal = NumeratorVal.sext(DenominatorBW);
774
775 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
776 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
777 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
778 Quotient = SE.getConstant(QuotientVal);
779 Remainder = SE.getConstant(RemainderVal);
780 return;
781 }
782 }
783
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000784 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
785 const SCEV *StartQ, *StartR, *StepQ, *StepR;
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000786 if (!Numerator->isAffine())
787 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000788 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
789 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
Brendon Cahoonf9751ad2015-04-22 15:06:40 +0000790 // Bail out if the types do not match.
791 Type *Ty = Denominator->getType();
792 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000793 Ty != StepQ->getType() || Ty != StepR->getType())
794 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000795 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
796 Numerator->getNoWrapFlags());
797 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
798 Numerator->getNoWrapFlags());
799 }
800
801 void visitAddExpr(const SCEVAddExpr *Numerator) {
802 SmallVector<const SCEV *, 2> Qs, Rs;
803 Type *Ty = Denominator->getType();
804
805 for (const SCEV *Op : Numerator->operands()) {
806 const SCEV *Q, *R;
807 divide(SE, Op, Denominator, &Q, &R);
808
809 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000810 if (Ty != Q->getType() || Ty != R->getType())
811 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000812
813 Qs.push_back(Q);
814 Rs.push_back(R);
815 }
816
817 if (Qs.size() == 1) {
818 Quotient = Qs[0];
819 Remainder = Rs[0];
820 return;
821 }
822
823 Quotient = SE.getAddExpr(Qs);
824 Remainder = SE.getAddExpr(Rs);
825 }
826
827 void visitMulExpr(const SCEVMulExpr *Numerator) {
828 SmallVector<const SCEV *, 2> Qs;
829 Type *Ty = Denominator->getType();
830
831 bool FoundDenominatorTerm = false;
832 for (const SCEV *Op : Numerator->operands()) {
833 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000834 if (Ty != Op->getType())
835 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000836
837 if (FoundDenominatorTerm) {
838 Qs.push_back(Op);
839 continue;
840 }
841
842 // Check whether Denominator divides one of the product operands.
843 const SCEV *Q, *R;
844 divide(SE, Op, Denominator, &Q, &R);
845 if (!R->isZero()) {
846 Qs.push_back(Op);
847 continue;
848 }
849
850 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000851 if (Ty != Q->getType())
852 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000853
854 FoundDenominatorTerm = true;
855 Qs.push_back(Q);
856 }
857
858 if (FoundDenominatorTerm) {
859 Remainder = Zero;
860 if (Qs.size() == 1)
861 Quotient = Qs[0];
862 else
863 Quotient = SE.getMulExpr(Qs);
864 return;
865 }
866
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000867 if (!isa<SCEVUnknown>(Denominator))
868 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000869
870 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
871 ValueToValueMap RewriteMap;
872 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
873 cast<SCEVConstant>(Zero)->getValue();
874 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
875
876 if (Remainder->isZero()) {
877 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
878 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
879 cast<SCEVConstant>(One)->getValue();
880 Quotient =
881 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
882 return;
883 }
884
885 // Quotient is (Numerator - Remainder) divided by Denominator.
886 const SCEV *Q, *R;
887 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000888 // This SCEV does not seem to simplify: fail the division here.
889 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
890 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000891 divide(SE, Diff, Denominator, &Q, &R);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000892 if (R != Zero)
893 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000894 Quotient = Q;
895 }
896
897private:
David Majnemer5d2670c2014-11-17 11:27:45 +0000898 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
899 const SCEV *Denominator)
900 : SE(S), Denominator(Denominator) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000901 Zero = SE.getZero(Denominator->getType());
902 One = SE.getOne(Denominator->getType());
David Majnemer5d2670c2014-11-17 11:27:45 +0000903
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000904 // We generally do not know how to divide Expr by Denominator. We
905 // initialize the division to a "cannot divide" state to simplify the rest
906 // of the code.
907 cannotDivide(Numerator);
908 }
909
910 // Convenience function for giving up on the division. We set the quotient to
911 // be equal to zero and the remainder to be equal to the numerator.
912 void cannotDivide(const SCEV *Numerator) {
David Majnemer5d2670c2014-11-17 11:27:45 +0000913 Quotient = Zero;
914 Remainder = Numerator;
915 }
916
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000917 ScalarEvolution &SE;
918 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
David Majnemer32b8ccf2014-11-16 20:35:19 +0000919};
920
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000921}
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000922
Chris Lattnerd934c702004-04-02 20:23:17 +0000923//===----------------------------------------------------------------------===//
924// Simple SCEV method implementations
925//===----------------------------------------------------------------------===//
926
Eli Friedman61f67622008-08-04 23:49:06 +0000927/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman4d5435d2009-05-24 23:45:28 +0000928/// Assume, K > 0.
Dan Gohmanaf752342009-07-07 17:06:11 +0000929static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohman32291b12009-07-21 00:38:55 +0000930 ScalarEvolution &SE,
Nick Lewycky702cf1e2011-09-06 06:39:54 +0000931 Type *ResultTy) {
Eli Friedman61f67622008-08-04 23:49:06 +0000932 // Handle the simplest case efficiently.
933 if (K == 1)
934 return SE.getTruncateOrZeroExtend(It, ResultTy);
935
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000936 // We are using the following formula for BC(It, K):
937 //
938 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
939 //
Eli Friedman61f67622008-08-04 23:49:06 +0000940 // Suppose, W is the bitwidth of the return value. We must be prepared for
941 // overflow. Hence, we must assure that the result of our computation is
942 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
943 // safe in modular arithmetic.
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000944 //
Eli Friedman61f67622008-08-04 23:49:06 +0000945 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohmance973df2009-06-24 04:48:43 +0000946 // is something like the following, where T is the number of factors of 2 in
Eli Friedman61f67622008-08-04 23:49:06 +0000947 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
948 // exponentiation:
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000949 //
Eli Friedman61f67622008-08-04 23:49:06 +0000950 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000951 //
Eli Friedman61f67622008-08-04 23:49:06 +0000952 // This formula is trivially equivalent to the previous formula. However,
953 // this formula can be implemented much more efficiently. The trick is that
954 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
955 // arithmetic. To do exact division in modular arithmetic, all we have
956 // to do is multiply by the inverse. Therefore, this step can be done at
957 // width W.
Dan Gohmance973df2009-06-24 04:48:43 +0000958 //
Eli Friedman61f67622008-08-04 23:49:06 +0000959 // The next issue is how to safely do the division by 2^T. The way this
960 // is done is by doing the multiplication step at a width of at least W + T
961 // bits. This way, the bottom W+T bits of the product are accurate. Then,
962 // when we perform the division by 2^T (which is equivalent to a right shift
963 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
964 // truncated out after the division by 2^T.
965 //
966 // In comparison to just directly using the first formula, this technique
967 // is much more efficient; using the first formula requires W * K bits,
968 // but this formula less than W + K bits. Also, the first formula requires
969 // a division step, whereas this formula only requires multiplies and shifts.
970 //
971 // It doesn't matter whether the subtraction step is done in the calculation
972 // width or the input iteration count's width; if the subtraction overflows,
973 // the result must be zero anyway. We prefer here to do it in the width of
974 // the induction variable because it helps a lot for certain cases; CodeGen
975 // isn't smart enough to ignore the overflow, which leads to much less
976 // efficient code if the width of the subtraction is wider than the native
977 // register width.
978 //
979 // (It's possible to not widen at all by pulling out factors of 2 before
980 // the multiplication; for example, K=2 can be calculated as
981 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
982 // extra arithmetic, so it's not an obvious win, and it gets
983 // much more complicated for K > 3.)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000984
Eli Friedman61f67622008-08-04 23:49:06 +0000985 // Protection from insane SCEVs; this bound is conservative,
986 // but it probably doesn't matter.
987 if (K > 1000)
Dan Gohman31efa302009-04-18 17:58:19 +0000988 return SE.getCouldNotCompute();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000989
Dan Gohmanb397e1a2009-04-21 01:07:12 +0000990 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000991
Eli Friedman61f67622008-08-04 23:49:06 +0000992 // Calculate K! / 2^T and T; we divide out the factors of two before
993 // multiplying for calculating K! / 2^T to avoid overflow.
994 // Other overflow doesn't matter because we only care about the bottom
995 // W bits of the result.
996 APInt OddFactorial(W, 1);
997 unsigned T = 1;
998 for (unsigned i = 3; i <= K; ++i) {
999 APInt Mult(W, i);
1000 unsigned TwoFactors = Mult.countTrailingZeros();
1001 T += TwoFactors;
1002 Mult = Mult.lshr(TwoFactors);
1003 OddFactorial *= Mult;
Chris Lattnerd934c702004-04-02 20:23:17 +00001004 }
Nick Lewyckyed169d52008-06-13 04:38:55 +00001005
Eli Friedman61f67622008-08-04 23:49:06 +00001006 // We need at least W + T bits for the multiplication step
Nick Lewycky21add8f2009-01-25 08:16:27 +00001007 unsigned CalculationBits = W + T;
Eli Friedman61f67622008-08-04 23:49:06 +00001008
Dan Gohman8b0a4192010-03-01 17:49:51 +00001009 // Calculate 2^T, at width T+W.
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00001010 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
Eli Friedman61f67622008-08-04 23:49:06 +00001011
1012 // Calculate the multiplicative inverse of K! / 2^T;
1013 // this multiplication factor will perform the exact division by
1014 // K! / 2^T.
1015 APInt Mod = APInt::getSignedMinValue(W+1);
1016 APInt MultiplyFactor = OddFactorial.zext(W+1);
1017 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1018 MultiplyFactor = MultiplyFactor.trunc(W);
1019
1020 // Calculate the product, at width T+W
Chris Lattner229907c2011-07-18 04:54:35 +00001021 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001022 CalculationBits);
Dan Gohmanaf752342009-07-07 17:06:11 +00001023 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman61f67622008-08-04 23:49:06 +00001024 for (unsigned i = 1; i != K; ++i) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00001025 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedman61f67622008-08-04 23:49:06 +00001026 Dividend = SE.getMulExpr(Dividend,
1027 SE.getTruncateOrZeroExtend(S, CalculationTy));
1028 }
1029
1030 // Divide by 2^T
Dan Gohmanaf752342009-07-07 17:06:11 +00001031 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman61f67622008-08-04 23:49:06 +00001032
1033 // Truncate the result, and divide by K! / 2^T.
1034
1035 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1036 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattnerd934c702004-04-02 20:23:17 +00001037}
1038
Chris Lattnerd934c702004-04-02 20:23:17 +00001039/// evaluateAtIteration - Return the value of this chain of recurrences at
1040/// the specified iteration number. We can evaluate this recurrence by
1041/// multiplying each element in the chain by the binomial coefficient
1042/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
1043///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001044/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattnerd934c702004-04-02 20:23:17 +00001045///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001046/// where BC(It, k) stands for binomial coefficient.
Chris Lattnerd934c702004-04-02 20:23:17 +00001047///
Dan Gohmanaf752342009-07-07 17:06:11 +00001048const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman32291b12009-07-21 00:38:55 +00001049 ScalarEvolution &SE) const {
Dan Gohmanaf752342009-07-07 17:06:11 +00001050 const SCEV *Result = getStart();
Chris Lattnerd934c702004-04-02 20:23:17 +00001051 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001052 // The computation is correct in the face of overflow provided that the
1053 // multiplication is performed _after_ the evaluation of the binomial
1054 // coefficient.
Dan Gohmanaf752342009-07-07 17:06:11 +00001055 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewycky707663e2008-10-13 03:58:02 +00001056 if (isa<SCEVCouldNotCompute>(Coeff))
1057 return Coeff;
1058
1059 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattnerd934c702004-04-02 20:23:17 +00001060 }
1061 return Result;
1062}
1063
Chris Lattnerd934c702004-04-02 20:23:17 +00001064//===----------------------------------------------------------------------===//
1065// SCEV Expression folder implementations
1066//===----------------------------------------------------------------------===//
1067
Dan Gohmanaf752342009-07-07 17:06:11 +00001068const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001069 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001070 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001071 "This is not a truncating conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001072 assert(isSCEVable(Ty) &&
1073 "This is not a conversion to a SCEVable type!");
1074 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001075
Dan Gohman3a302cb2009-07-13 20:50:19 +00001076 FoldingSetNodeID ID;
1077 ID.AddInteger(scTruncate);
1078 ID.AddPointer(Op);
1079 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001080 void *IP = nullptr;
Dan Gohman3a302cb2009-07-13 20:50:19 +00001081 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1082
Dan Gohman3423e722009-06-30 20:13:32 +00001083 // Fold if the operand is constant.
Dan Gohmana30370b2009-05-04 22:02:23 +00001084 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman8d7576e2009-06-24 00:38:39 +00001085 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001086 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001087
Dan Gohman79af8542009-04-22 16:20:48 +00001088 // trunc(trunc(x)) --> trunc(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001089 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001090 return getTruncateExpr(ST->getOperand(), Ty);
1091
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001092 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001093 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001094 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1095
1096 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001097 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001098 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1099
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001100 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
Nick Lewycky2ce28322015-03-20 02:52:23 +00001101 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001102 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1103 SmallVector<const SCEV *, 4> Operands;
1104 bool hasTrunc = false;
1105 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1106 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001107 if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1108 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001109 Operands.push_back(S);
1110 }
1111 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001112 return getAddExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001113 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001114 }
1115
Nick Lewycky5c901f32011-01-19 18:56:00 +00001116 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
Nick Lewyckybe8af482015-03-20 02:25:00 +00001117 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001118 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1119 SmallVector<const SCEV *, 4> Operands;
1120 bool hasTrunc = false;
1121 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1122 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001123 if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1124 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5c901f32011-01-19 18:56:00 +00001125 Operands.push_back(S);
1126 }
1127 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001128 return getMulExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001129 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001130 }
1131
Dan Gohman5a728c92009-06-18 16:24:47 +00001132 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmana30370b2009-05-04 22:02:23 +00001133 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001134 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00001135 for (const SCEV *Op : AddRec->operands())
1136 Operands.push_back(getTruncateExpr(Op, Ty));
Andrew Trick8b55b732011-03-14 16:50:06 +00001137 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00001138 }
1139
Dan Gohman89dd42a2010-06-25 18:47:08 +00001140 // The cast wasn't folded; create an explicit cast node. We can reuse
1141 // the existing insert position since if we get here, we won't have
1142 // made any changes which would invalidate it.
Dan Gohman01c65a22010-03-18 18:49:47 +00001143 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1144 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001145 UniqueSCEVs.InsertNode(S, IP);
1146 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001147}
1148
Sanjoy Das4153f472015-02-18 01:47:07 +00001149// Get the limit of a recurrence such that incrementing by Step cannot cause
1150// signed overflow as long as the value of the recurrence within the
1151// loop does not exceed this limit before incrementing.
1152static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1153 ICmpInst::Predicate *Pred,
1154 ScalarEvolution *SE) {
1155 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1156 if (SE->isKnownPositive(Step)) {
1157 *Pred = ICmpInst::ICMP_SLT;
1158 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1159 SE->getSignedRange(Step).getSignedMax());
1160 }
1161 if (SE->isKnownNegative(Step)) {
1162 *Pred = ICmpInst::ICMP_SGT;
1163 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1164 SE->getSignedRange(Step).getSignedMin());
1165 }
1166 return nullptr;
1167}
1168
1169// Get the limit of a recurrence such that incrementing by Step cannot cause
1170// unsigned overflow as long as the value of the recurrence within the loop does
1171// not exceed this limit before incrementing.
1172static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1173 ICmpInst::Predicate *Pred,
1174 ScalarEvolution *SE) {
1175 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1176 *Pred = ICmpInst::ICMP_ULT;
1177
1178 return SE->getConstant(APInt::getMinValue(BitWidth) -
1179 SE->getUnsignedRange(Step).getUnsignedMax());
1180}
1181
1182namespace {
1183
1184struct ExtendOpTraitsBase {
1185 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *);
1186};
1187
1188// Used to make code generic over signed and unsigned overflow.
1189template <typename ExtendOp> struct ExtendOpTraits {
1190 // Members present:
1191 //
1192 // static const SCEV::NoWrapFlags WrapType;
1193 //
1194 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1195 //
1196 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1197 // ICmpInst::Predicate *Pred,
1198 // ScalarEvolution *SE);
1199};
1200
1201template <>
1202struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1203 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1204
1205 static const GetExtendExprTy GetExtendExpr;
1206
1207 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1208 ICmpInst::Predicate *Pred,
1209 ScalarEvolution *SE) {
1210 return getSignedOverflowLimitForStep(Step, Pred, SE);
1211 }
1212};
1213
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001214const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001215 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1216
1217template <>
1218struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1219 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1220
1221 static const GetExtendExprTy GetExtendExpr;
1222
1223 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1224 ICmpInst::Predicate *Pred,
1225 ScalarEvolution *SE) {
1226 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1227 }
1228};
1229
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001230const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001231 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001232}
Sanjoy Das4153f472015-02-18 01:47:07 +00001233
1234// The recurrence AR has been shown to have no signed/unsigned wrap or something
1235// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1236// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1237// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1238// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1239// expression "Step + sext/zext(PreIncAR)" is congruent with
1240// "sext/zext(PostIncAR)"
1241template <typename ExtendOpTy>
1242static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1243 ScalarEvolution *SE) {
1244 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1245 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1246
1247 const Loop *L = AR->getLoop();
1248 const SCEV *Start = AR->getStart();
1249 const SCEV *Step = AR->getStepRecurrence(*SE);
1250
1251 // Check for a simple looking step prior to loop entry.
1252 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1253 if (!SA)
1254 return nullptr;
1255
1256 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1257 // subtraction is expensive. For this purpose, perform a quick and dirty
1258 // difference, by checking for Step in the operand list.
1259 SmallVector<const SCEV *, 4> DiffOps;
1260 for (const SCEV *Op : SA->operands())
1261 if (Op != Step)
1262 DiffOps.push_back(Op);
1263
1264 if (DiffOps.size() == SA->getNumOperands())
1265 return nullptr;
1266
1267 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1268 // `Step`:
1269
1270 // 1. NSW/NUW flags on the step increment.
Sanjoy Das0714e3e2015-10-23 06:33:47 +00001271 auto PreStartFlags =
1272 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1273 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
Sanjoy Das4153f472015-02-18 01:47:07 +00001274 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1275 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1276
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001277 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1278 // "S+X does not sign/unsign-overflow".
Sanjoy Das4153f472015-02-18 01:47:07 +00001279 //
1280
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001281 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1282 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1283 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
Sanjoy Das4153f472015-02-18 01:47:07 +00001284 return PreStart;
1285
1286 // 2. Direct overflow check on the step operation's expression.
1287 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1288 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1289 const SCEV *OperandExtendedStart =
1290 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1291 (SE->*GetExtendExpr)(Step, WideTy));
1292 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1293 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1294 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1295 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1296 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1297 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1298 }
1299 return PreStart;
1300 }
1301
1302 // 3. Loop precondition.
1303 ICmpInst::Predicate Pred;
1304 const SCEV *OverflowLimit =
1305 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1306
1307 if (OverflowLimit &&
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001308 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
Sanjoy Das4153f472015-02-18 01:47:07 +00001309 return PreStart;
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001310
Sanjoy Das4153f472015-02-18 01:47:07 +00001311 return nullptr;
1312}
1313
1314// Get the normalized zero or sign extended expression for this AddRec's Start.
1315template <typename ExtendOpTy>
1316static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1317 ScalarEvolution *SE) {
1318 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1319
1320 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1321 if (!PreStart)
1322 return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1323
1324 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1325 (SE->*GetExtendExpr)(PreStart, Ty));
1326}
1327
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001328// Try to prove away overflow by looking at "nearby" add recurrences. A
1329// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1330// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1331//
1332// Formally:
1333//
1334// {S,+,X} == {S-T,+,X} + T
1335// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1336//
1337// If ({S-T,+,X} + T) does not overflow ... (1)
1338//
1339// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1340//
1341// If {S-T,+,X} does not overflow ... (2)
1342//
1343// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1344// == {Ext(S-T)+Ext(T),+,Ext(X)}
1345//
1346// If (S-T)+T does not overflow ... (3)
1347//
1348// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1349// == {Ext(S),+,Ext(X)} == LHS
1350//
1351// Thus, if (1), (2) and (3) are true for some T, then
1352// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1353//
1354// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1355// does not overflow" restricted to the 0th iteration. Therefore we only need
1356// to check for (1) and (2).
1357//
1358// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1359// is `Delta` (defined below).
1360//
1361template <typename ExtendOpTy>
1362bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1363 const SCEV *Step,
1364 const Loop *L) {
1365 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1366
1367 // We restrict `Start` to a constant to prevent SCEV from spending too much
1368 // time here. It is correct (but more expensive) to continue with a
1369 // non-constant `Start` and do a general SCEV subtraction to compute
1370 // `PreStart` below.
1371 //
1372 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1373 if (!StartC)
1374 return false;
1375
1376 APInt StartAI = StartC->getValue()->getValue();
1377
1378 for (unsigned Delta : {-2, -1, 1, 2}) {
1379 const SCEV *PreStart = getConstant(StartAI - Delta);
1380
1381 // Give up if we don't already have the add recurrence we need because
1382 // actually constructing an add recurrence is relatively expensive.
1383 const SCEVAddRecExpr *PreAR = [&]() {
1384 FoldingSetNodeID ID;
1385 ID.AddInteger(scAddRecExpr);
1386 ID.AddPointer(PreStart);
1387 ID.AddPointer(Step);
1388 ID.AddPointer(L);
1389 void *IP = nullptr;
1390 return static_cast<SCEVAddRecExpr *>(
NAKAMURA Takumi8f49dd32015-03-05 01:02:45 +00001391 this->UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001392 }();
1393
1394 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))) {
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001639 const APInt &C1 = SC1->getValue()->getValue();
1640 const APInt &C2 = SC2->getValue()->getValue();
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) {
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001765 const APInt &C1 = SC1->getValue()->getValue();
1766 const APInt &C2 = SC2->getValue()->getValue();
1767 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))
1806 if (SC->getValue()->getValue().isNegative())
1807 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;
1884 AccumulatedConstant += Scale * C->getValue()->getValue();
1885 }
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 =
1893 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1894 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
1934namespace {
1935 struct APIntCompare {
1936 bool operator()(const APInt &LHS, const APInt &RHS) const {
1937 return LHS.ult(RHS);
1938 }
1939 };
1940}
1941
Sanjoy Das81401d42015-01-10 23:41:24 +00001942// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
1943// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
1944// can't-overflow flags for the operation if possible.
1945static SCEV::NoWrapFlags
1946StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
1947 const SmallVectorImpl<const SCEV *> &Ops,
Sanjoy Das8f274152015-10-22 19:57:19 +00001948 SCEV::NoWrapFlags Flags) {
Sanjoy Das81401d42015-01-10 23:41:24 +00001949 using namespace std::placeholders;
Sanjoy Das8f274152015-10-22 19:57:19 +00001950 typedef OverflowingBinaryOperator OBO;
Sanjoy Das81401d42015-01-10 23:41:24 +00001951
1952 bool CanAnalyze =
1953 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
1954 (void)CanAnalyze;
1955 assert(CanAnalyze && "don't call from other places!");
1956
1957 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1958 SCEV::NoWrapFlags SignOrUnsignWrap =
Sanjoy Das8f274152015-10-22 19:57:19 +00001959 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00001960
1961 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1962 auto IsKnownNonNegative =
1963 std::bind(std::mem_fn(&ScalarEvolution::isKnownNonNegative), SE, _1);
1964
1965 if (SignOrUnsignWrap == SCEV::FlagNSW &&
1966 std::all_of(Ops.begin(), Ops.end(), IsKnownNonNegative))
Sanjoy Das8f274152015-10-22 19:57:19 +00001967 Flags =
1968 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00001969
Sanjoy Das8f274152015-10-22 19:57:19 +00001970 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
1971
1972 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
1973 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
1974
1975 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
1976 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
1977
1978 const APInt &C = cast<SCEVConstant>(Ops[0])->getValue()->getValue();
1979 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
1980 auto NSWRegion =
1981 ConstantRange::makeNoWrapRegion(Instruction::Add, C, OBO::NoSignedWrap);
1982 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
1983 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
1984 }
1985 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
1986 auto NUWRegion =
1987 ConstantRange::makeNoWrapRegion(Instruction::Add, C,
1988 OBO::NoUnsignedWrap);
1989 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
1990 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
1991 }
1992 }
1993
1994 return Flags;
Sanjoy Das81401d42015-01-10 23:41:24 +00001995}
1996
Dan Gohman4d5435d2009-05-24 23:45:28 +00001997/// getAddExpr - Get a canonical add expression, or something simpler if
1998/// possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00001999const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002000 SCEV::NoWrapFlags Flags) {
2001 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2002 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002003 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +00002004 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002005#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002006 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002007 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohman9136d9f2010-06-18 19:09:27 +00002008 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002009 "SCEVAddExpr operand types don't match!");
2010#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002011
2012 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002013 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002014
Sanjoy Das64895612015-10-09 02:44:45 +00002015 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2016
Chris Lattnerd934c702004-04-02 20:23:17 +00002017 // If there are any constants, fold them together.
2018 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002019 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002020 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +00002021 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002022 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002023 // We found two constants, fold them together!
Dan Gohman0652fd52009-06-14 22:47:23 +00002024 Ops[0] = getConstant(LHSC->getValue()->getValue() +
2025 RHSC->getValue()->getValue());
Dan Gohman011cf682009-06-14 22:53:57 +00002026 if (Ops.size() == 2) return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002027 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002028 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002029 }
2030
2031 // If we are left with a constant zero being added, strip it off.
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002032 if (LHSC->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002033 Ops.erase(Ops.begin());
2034 --Idx;
2035 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002036
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002037 if (Ops.size() == 1) return Ops[0];
2038 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002039
Dan Gohman15871f22010-08-27 21:39:59 +00002040 // Okay, check to see if the same value occurs in the operand list more than
2041 // once. If so, merge them together into an multiply expression. Since we
2042 // sorted the list, these values are required to be adjacent.
Chris Lattner229907c2011-07-18 04:54:35 +00002043 Type *Ty = Ops[0]->getType();
Dan Gohmane67b2872010-08-12 14:46:54 +00002044 bool FoundMatch = false;
Dan Gohman15871f22010-08-27 21:39:59 +00002045 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattnerd934c702004-04-02 20:23:17 +00002046 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman15871f22010-08-27 21:39:59 +00002047 // Scan ahead to count how many equal operands there are.
2048 unsigned Count = 2;
2049 while (i+Count != e && Ops[i+Count] == Ops[i])
2050 ++Count;
2051 // Merge the values into a multiply.
2052 const SCEV *Scale = getConstant(Ty, Count);
2053 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2054 if (Ops.size() == Count)
Chris Lattnerd934c702004-04-02 20:23:17 +00002055 return Mul;
Dan Gohmane67b2872010-08-12 14:46:54 +00002056 Ops[i] = Mul;
Dan Gohman15871f22010-08-27 21:39:59 +00002057 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohmanfe22f1d2010-08-28 00:39:27 +00002058 --i; e -= Count - 1;
Dan Gohmane67b2872010-08-12 14:46:54 +00002059 FoundMatch = true;
Chris Lattnerd934c702004-04-02 20:23:17 +00002060 }
Dan Gohmane67b2872010-08-12 14:46:54 +00002061 if (FoundMatch)
Andrew Trick8b55b732011-03-14 16:50:06 +00002062 return getAddExpr(Ops, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002063
Dan Gohman2e55cc52009-05-08 21:03:19 +00002064 // Check for truncates. If all the operands are truncated from the same
2065 // type, see if factoring out the truncate would permit the result to be
2066 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2067 // if the contents of the resulting outer trunc fold to something simple.
2068 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2069 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
Chris Lattner229907c2011-07-18 04:54:35 +00002070 Type *DstType = Trunc->getType();
2071 Type *SrcType = Trunc->getOperand()->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00002072 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002073 bool Ok = true;
2074 // Check all the operands to see if they can be represented in the
2075 // source type of the truncate.
2076 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2077 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2078 if (T->getOperand()->getType() != SrcType) {
2079 Ok = false;
2080 break;
2081 }
2082 LargeOps.push_back(T->getOperand());
2083 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002084 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002085 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002086 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002087 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2088 if (const SCEVTruncateExpr *T =
2089 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2090 if (T->getOperand()->getType() != SrcType) {
2091 Ok = false;
2092 break;
2093 }
2094 LargeMulOps.push_back(T->getOperand());
Sanjoy Das63914592015-10-18 00:29:20 +00002095 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002096 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002097 } else {
2098 Ok = false;
2099 break;
2100 }
2101 }
2102 if (Ok)
2103 LargeOps.push_back(getMulExpr(LargeMulOps));
2104 } else {
2105 Ok = false;
2106 break;
2107 }
2108 }
2109 if (Ok) {
2110 // Evaluate the expression in the larger type.
Andrew Trick8b55b732011-03-14 16:50:06 +00002111 const SCEV *Fold = getAddExpr(LargeOps, Flags);
Dan Gohman2e55cc52009-05-08 21:03:19 +00002112 // If it folds to something simple, use it. Otherwise, don't.
2113 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2114 return getTruncateExpr(Fold, DstType);
2115 }
2116 }
2117
2118 // Skip past any other cast SCEVs.
Dan Gohmaneed125f2007-06-18 19:30:09 +00002119 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2120 ++Idx;
2121
2122 // If there are add operands they would be next.
Chris Lattnerd934c702004-04-02 20:23:17 +00002123 if (Idx < Ops.size()) {
2124 bool DeletedAdd = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002125 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002126 // If we have an add, expand the add operands onto the end of the operands
2127 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002128 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002129 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002130 DeletedAdd = true;
2131 }
2132
2133 // If we deleted at least one add, we added operands to the end of the list,
2134 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002135 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002136 if (DeletedAdd)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002137 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002138 }
2139
2140 // Skip over the add expression until we get to a multiply.
2141 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2142 ++Idx;
2143
Dan Gohman038d02e2009-06-14 22:58:51 +00002144 // Check to see if there are any folding opportunities present with
2145 // operands multiplied by constant values.
2146 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2147 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohmanaf752342009-07-07 17:06:11 +00002148 DenseMap<const SCEV *, APInt> M;
2149 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman038d02e2009-06-14 22:58:51 +00002150 APInt AccumulatedConstant(BitWidth, 0);
2151 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002152 Ops.data(), Ops.size(),
2153 APInt(BitWidth, 1), *this)) {
Dan Gohman038d02e2009-06-14 22:58:51 +00002154 // Some interesting folding opportunity is present, so its worthwhile to
2155 // re-generate the operands list. Group the operands by constant scale,
2156 // to avoid multiplying by the same constant scale multiple times.
Dan Gohmanaf752342009-07-07 17:06:11 +00002157 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Craig Topper31ee5862013-07-03 15:07:05 +00002158 for (SmallVectorImpl<const SCEV *>::const_iterator I = NewOps.begin(),
Dan Gohman038d02e2009-06-14 22:58:51 +00002159 E = NewOps.end(); I != E; ++I)
2160 MulOpLists[M.find(*I)->second].push_back(*I);
2161 // Re-generate the operands list.
2162 Ops.clear();
2163 if (AccumulatedConstant != 0)
2164 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohmance973df2009-06-24 04:48:43 +00002165 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
2166 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohman038d02e2009-06-14 22:58:51 +00002167 if (I->first != 0)
Dan Gohmance973df2009-06-24 04:48:43 +00002168 Ops.push_back(getMulExpr(getConstant(I->first),
2169 getAddExpr(I->second)));
Dan Gohman038d02e2009-06-14 22:58:51 +00002170 if (Ops.empty())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002171 return getZero(Ty);
Dan Gohman038d02e2009-06-14 22:58:51 +00002172 if (Ops.size() == 1)
2173 return Ops[0];
2174 return getAddExpr(Ops);
2175 }
2176 }
2177
Chris Lattnerd934c702004-04-02 20:23:17 +00002178 // If we are adding something to a multiply expression, make sure the
2179 // something is not already an operand of the multiply. If so, merge it into
2180 // the multiply.
2181 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002182 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002183 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman48f82222009-05-04 22:30:44 +00002184 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman157847f2010-08-12 14:52:55 +00002185 if (isa<SCEVConstant>(MulOpSCEV))
2186 continue;
Chris Lattnerd934c702004-04-02 20:23:17 +00002187 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman157847f2010-08-12 14:52:55 +00002188 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002189 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohmanaf752342009-07-07 17:06:11 +00002190 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002191 if (Mul->getNumOperands() != 2) {
2192 // If the multiply has more than two operands, we must get the
2193 // Y*Z term.
Dan Gohman797a1db2010-08-16 16:57:24 +00002194 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2195 Mul->op_begin()+MulOp);
2196 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002197 InnerMul = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002198 }
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002199 const SCEV *One = getOne(Ty);
Dan Gohmancf32f2b2010-08-13 20:17:14 +00002200 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman157847f2010-08-12 14:52:55 +00002201 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattnerd934c702004-04-02 20:23:17 +00002202 if (Ops.size() == 2) return OuterMul;
2203 if (AddOp < Idx) {
2204 Ops.erase(Ops.begin()+AddOp);
2205 Ops.erase(Ops.begin()+Idx-1);
2206 } else {
2207 Ops.erase(Ops.begin()+Idx);
2208 Ops.erase(Ops.begin()+AddOp-1);
2209 }
2210 Ops.push_back(OuterMul);
Dan Gohmana37eaf22007-10-22 18:31:58 +00002211 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002212 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002213
Chris Lattnerd934c702004-04-02 20:23:17 +00002214 // Check this multiply against other multiplies being added together.
2215 for (unsigned OtherMulIdx = Idx+1;
2216 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2217 ++OtherMulIdx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002218 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002219 // If MulOp occurs in OtherMul, we can fold the two multiplies
2220 // together.
2221 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2222 OMulOp != e; ++OMulOp)
2223 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2224 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohmanaf752342009-07-07 17:06:11 +00002225 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002226 if (Mul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002227 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002228 Mul->op_begin()+MulOp);
2229 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002230 InnerMul1 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002231 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002232 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002233 if (OtherMul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002234 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002235 OtherMul->op_begin()+OMulOp);
2236 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002237 InnerMul2 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002238 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002239 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2240 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattnerd934c702004-04-02 20:23:17 +00002241 if (Ops.size() == 2) return OuterMul;
Dan Gohmanaabfc522010-08-31 22:50:31 +00002242 Ops.erase(Ops.begin()+Idx);
2243 Ops.erase(Ops.begin()+OtherMulIdx-1);
2244 Ops.push_back(OuterMul);
2245 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002246 }
2247 }
2248 }
2249 }
2250
2251 // If there are any add recurrences in the operands list, see if any other
2252 // added values are loop invariant. If so, we can fold them into the
2253 // recurrence.
2254 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2255 ++Idx;
2256
2257 // Scan over all recurrences, trying to fold loop invariants into them.
2258 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2259 // Scan all of the other operands to this add and add them to the vector if
2260 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002261 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002262 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002263 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002264 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002265 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002266 LIOps.push_back(Ops[i]);
2267 Ops.erase(Ops.begin()+i);
2268 --i; --e;
2269 }
2270
2271 // If we found some loop invariants, fold them into the recurrence.
2272 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002273 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattnerd934c702004-04-02 20:23:17 +00002274 LIOps.push_back(AddRec->getStart());
2275
Dan Gohmanaf752342009-07-07 17:06:11 +00002276 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman7a2dab82009-12-18 03:57:04 +00002277 AddRec->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002278 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002279
Dan Gohman16206132010-06-30 07:16:37 +00002280 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher23bf3ba2011-01-11 09:02:09 +00002281 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002282 // Always propagate NW.
2283 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick8b55b732011-03-14 16:50:06 +00002284 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman51f13052009-12-18 18:45:31 +00002285
Chris Lattnerd934c702004-04-02 20:23:17 +00002286 // If all of the other operands were loop invariant, we are done.
2287 if (Ops.size() == 1) return NewRec;
2288
Nick Lewyckydb66b822011-09-06 05:08:09 +00002289 // Otherwise, add the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002290 for (unsigned i = 0;; ++i)
2291 if (Ops[i] == AddRec) {
2292 Ops[i] = NewRec;
2293 break;
2294 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002295 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002296 }
2297
2298 // Okay, if there weren't any loop invariants to be folded, check to see if
2299 // there are multiple AddRec's with the same loop induction variable being
2300 // added together. If so, we can fold them.
2301 for (unsigned OtherIdx = Idx+1;
Dan Gohmanc866bf42010-08-27 20:45:56 +00002302 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2303 ++OtherIdx)
2304 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2305 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2306 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2307 AddRec->op_end());
2308 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2309 ++OtherIdx)
Dan Gohman028c1812010-08-29 14:53:34 +00002310 if (const SCEVAddRecExpr *OtherAddRec =
Dan Gohmanc866bf42010-08-27 20:45:56 +00002311 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman028c1812010-08-29 14:53:34 +00002312 if (OtherAddRec->getLoop() == AddRecLoop) {
2313 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2314 i != e; ++i) {
Dan Gohmanc866bf42010-08-27 20:45:56 +00002315 if (i >= AddRecOps.size()) {
Dan Gohman028c1812010-08-29 14:53:34 +00002316 AddRecOps.append(OtherAddRec->op_begin()+i,
2317 OtherAddRec->op_end());
Dan Gohmanc866bf42010-08-27 20:45:56 +00002318 break;
2319 }
Dan Gohman028c1812010-08-29 14:53:34 +00002320 AddRecOps[i] = getAddExpr(AddRecOps[i],
2321 OtherAddRec->getOperand(i));
Dan Gohmanc866bf42010-08-27 20:45:56 +00002322 }
2323 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattnerd934c702004-04-02 20:23:17 +00002324 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002325 // Step size has changed, so we cannot guarantee no self-wraparound.
2326 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Dan Gohmanc866bf42010-08-27 20:45:56 +00002327 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002328 }
2329
2330 // Otherwise couldn't fold anything into this recurrence. Move onto the
2331 // next one.
2332 }
2333
2334 // Okay, it looks like we really DO need an add expr. Check to see if we
2335 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002336 FoldingSetNodeID ID;
2337 ID.AddInteger(scAddExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002338 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2339 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002340 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002341 SCEVAddExpr *S =
2342 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2343 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002344 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2345 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002346 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2347 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002348 UniqueSCEVs.InsertNode(S, IP);
2349 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002350 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002351 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002352}
2353
Nick Lewycky287682e2011-10-04 06:51:26 +00002354static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2355 uint64_t k = i*j;
2356 if (j > 1 && k / j != i) Overflow = true;
2357 return k;
2358}
2359
2360/// Compute the result of "n choose k", the binomial coefficient. If an
2361/// intermediate computation overflows, Overflow will be set and the return will
Benjamin Kramerbde91762012-06-02 10:20:22 +00002362/// be garbage. Overflow is not cleared on absence of overflow.
Nick Lewycky287682e2011-10-04 06:51:26 +00002363static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2364 // We use the multiplicative formula:
2365 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2366 // At each iteration, we take the n-th term of the numeral and divide by the
2367 // (k-n)th term of the denominator. This division will always produce an
2368 // integral result, and helps reduce the chance of overflow in the
2369 // intermediate computations. However, we can still overflow even when the
2370 // final result would fit.
2371
2372 if (n == 0 || n == k) return 1;
2373 if (k > n) return 0;
2374
2375 if (k > n/2)
2376 k = n-k;
2377
2378 uint64_t r = 1;
2379 for (uint64_t i = 1; i <= k; ++i) {
2380 r = umul_ov(r, n-(i-1), Overflow);
2381 r /= i;
2382 }
2383 return r;
2384}
2385
Nick Lewycky05044c22014-12-06 00:45:50 +00002386/// Determine if any of the operands in this SCEV are a constant or if
2387/// any of the add or multiply expressions in this SCEV contain a constant.
2388static bool containsConstantSomewhere(const SCEV *StartExpr) {
2389 SmallVector<const SCEV *, 4> Ops;
2390 Ops.push_back(StartExpr);
2391 while (!Ops.empty()) {
2392 const SCEV *CurrentExpr = Ops.pop_back_val();
2393 if (isa<SCEVConstant>(*CurrentExpr))
2394 return true;
2395
2396 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2397 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002398 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
Nick Lewycky05044c22014-12-06 00:45:50 +00002399 }
2400 }
2401 return false;
2402}
2403
Dan Gohman4d5435d2009-05-24 23:45:28 +00002404/// getMulExpr - Get a canonical multiply expression, or something simpler if
2405/// possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002406const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002407 SCEV::NoWrapFlags Flags) {
2408 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2409 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002410 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohman51ad99d2010-01-21 02:09:26 +00002411 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002412#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002413 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002414 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002415 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002416 "SCEVMulExpr operand types don't match!");
2417#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002418
2419 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002420 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002421
Sanjoy Das64895612015-10-09 02:44:45 +00002422 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2423
Chris Lattnerd934c702004-04-02 20:23:17 +00002424 // If there are any constants, fold them together.
2425 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002426 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002427
2428 // C1*(C2+V) -> C1*C2 + C1*V
2429 if (Ops.size() == 2)
Nick Lewycky05044c22014-12-06 00:45:50 +00002430 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2431 // If any of Add's ops are Adds or Muls with a constant,
2432 // apply this transformation as well.
2433 if (Add->getNumOperands() == 2)
2434 if (containsConstantSomewhere(Add))
2435 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2436 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002437
Chris Lattnerd934c702004-04-02 20:23:17 +00002438 ++Idx;
Dan Gohmana30370b2009-05-04 22:02:23 +00002439 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002440 // We found two constants, fold them together!
Owen Andersonedb4a702009-07-24 23:12:02 +00002441 ConstantInt *Fold = ConstantInt::get(getContext(),
2442 LHSC->getValue()->getValue() *
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002443 RHSC->getValue()->getValue());
2444 Ops[0] = getConstant(Fold);
2445 Ops.erase(Ops.begin()+1); // Erase the folded element
2446 if (Ops.size() == 1) return Ops[0];
2447 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002448 }
2449
2450 // If we are left with a constant one being multiplied, strip it off.
2451 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2452 Ops.erase(Ops.begin());
2453 --Idx;
Reid Spencer2e54a152007-03-02 00:28:52 +00002454 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002455 // If we have a multiply of zero, it will always be zero.
2456 return Ops[0];
Dan Gohman51ad99d2010-01-21 02:09:26 +00002457 } else if (Ops[0]->isAllOnesValue()) {
2458 // If we have a mul by -1 of an add, try distributing the -1 among the
2459 // add operands.
Andrew Trick8b55b732011-03-14 16:50:06 +00002460 if (Ops.size() == 2) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002461 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2462 SmallVector<const SCEV *, 4> NewOps;
2463 bool AnyFolded = false;
Andrew Trick8b55b732011-03-14 16:50:06 +00002464 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(),
2465 E = Add->op_end(); I != E; ++I) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002466 const SCEV *Mul = getMulExpr(Ops[0], *I);
2467 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2468 NewOps.push_back(Mul);
2469 }
2470 if (AnyFolded)
2471 return getAddExpr(NewOps);
Sanjoy Das63914592015-10-18 00:29:20 +00002472 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
Andrew Tricke92dcce2011-03-14 17:38:54 +00002473 // Negation preserves a recurrence's no self-wrap property.
2474 SmallVector<const SCEV *, 4> Operands;
2475 for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(),
2476 E = AddRec->op_end(); I != E; ++I) {
2477 Operands.push_back(getMulExpr(Ops[0], *I));
2478 }
2479 return getAddRecExpr(Operands, AddRec->getLoop(),
2480 AddRec->getNoWrapFlags(SCEV::FlagNW));
2481 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002482 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002483 }
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002484
2485 if (Ops.size() == 1)
2486 return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00002487 }
2488
2489 // Skip over the add expression until we get to a multiply.
2490 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2491 ++Idx;
2492
Chris Lattnerd934c702004-04-02 20:23:17 +00002493 // If there are mul operands inline them all into this expression.
2494 if (Idx < Ops.size()) {
2495 bool DeletedMul = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002496 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002497 // If we have an mul, expand the mul operands onto the end of the operands
2498 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002499 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002500 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002501 DeletedMul = true;
2502 }
2503
2504 // If we deleted at least one mul, we added operands to the end of the list,
2505 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002506 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002507 if (DeletedMul)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002508 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002509 }
2510
2511 // If there are any add recurrences in the operands list, see if any other
2512 // added values are loop invariant. If so, we can fold them into the
2513 // recurrence.
2514 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2515 ++Idx;
2516
2517 // Scan over all recurrences, trying to fold loop invariants into them.
2518 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2519 // Scan all of the other operands to this mul and add them to the vector if
2520 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002521 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002522 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f2de012010-08-29 14:55:19 +00002523 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002524 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002525 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002526 LIOps.push_back(Ops[i]);
2527 Ops.erase(Ops.begin()+i);
2528 --i; --e;
2529 }
2530
2531 // If we found some loop invariants, fold them into the recurrence.
2532 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002533 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanaf752342009-07-07 17:06:11 +00002534 SmallVector<const SCEV *, 4> NewOps;
Chris Lattnerd934c702004-04-02 20:23:17 +00002535 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman8f5954f2010-06-17 23:34:09 +00002536 const SCEV *Scale = getMulExpr(LIOps);
2537 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2538 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002539
Dan Gohman16206132010-06-30 07:16:37 +00002540 // Build the new addrec. Propagate the NUW and NSW flags if both the
2541 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick8b55b732011-03-14 16:50:06 +00002542 //
2543 // No self-wrap cannot be guaranteed after changing the step size, but
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002544 // will be inferred if either NUW or NSW is true.
Andrew Trick8b55b732011-03-14 16:50:06 +00002545 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2546 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002547
2548 // If all of the other operands were loop invariant, we are done.
2549 if (Ops.size() == 1) return NewRec;
2550
Nick Lewyckydb66b822011-09-06 05:08:09 +00002551 // Otherwise, multiply the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002552 for (unsigned i = 0;; ++i)
2553 if (Ops[i] == AddRec) {
2554 Ops[i] = NewRec;
2555 break;
2556 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002557 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002558 }
2559
2560 // Okay, if there weren't any loop invariants to be folded, check to see if
2561 // there are multiple AddRec's with the same loop induction variable being
2562 // multiplied together. If so, we can fold them.
Nick Lewycky97756402014-09-01 05:17:15 +00002563
2564 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2565 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2566 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2567 // ]]],+,...up to x=2n}.
2568 // Note that the arguments to choose() are always integers with values
2569 // known at compile time, never SCEV objects.
2570 //
2571 // The implementation avoids pointless extra computations when the two
2572 // addrec's are of different length (mathematically, it's equivalent to
2573 // an infinite stream of zeros on the right).
2574 bool OpsModified = false;
Chris Lattnerd934c702004-04-02 20:23:17 +00002575 for (unsigned OtherIdx = Idx+1;
Nick Lewycky97756402014-09-01 05:17:15 +00002576 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002577 ++OtherIdx) {
Nick Lewycky97756402014-09-01 05:17:15 +00002578 const SCEVAddRecExpr *OtherAddRec =
2579 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2580 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
Andrew Trick946f76b2012-05-30 03:35:17 +00002581 continue;
2582
Nick Lewycky97756402014-09-01 05:17:15 +00002583 bool Overflow = false;
2584 Type *Ty = AddRec->getType();
2585 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2586 SmallVector<const SCEV*, 7> AddRecOps;
2587 for (int x = 0, xe = AddRec->getNumOperands() +
2588 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002589 const SCEV *Term = getZero(Ty);
Nick Lewycky97756402014-09-01 05:17:15 +00002590 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2591 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2592 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2593 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2594 z < ze && !Overflow; ++z) {
2595 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2596 uint64_t Coeff;
2597 if (LargerThan64Bits)
2598 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2599 else
2600 Coeff = Coeff1*Coeff2;
2601 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2602 const SCEV *Term1 = AddRec->getOperand(y-z);
2603 const SCEV *Term2 = OtherAddRec->getOperand(z);
2604 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
Andrew Trick946f76b2012-05-30 03:35:17 +00002605 }
Andrew Trick946f76b2012-05-30 03:35:17 +00002606 }
Nick Lewycky97756402014-09-01 05:17:15 +00002607 AddRecOps.push_back(Term);
Chris Lattnerd934c702004-04-02 20:23:17 +00002608 }
Nick Lewycky97756402014-09-01 05:17:15 +00002609 if (!Overflow) {
2610 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2611 SCEV::FlagAnyWrap);
2612 if (Ops.size() == 2) return NewAddRec;
2613 Ops[Idx] = NewAddRec;
2614 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2615 OpsModified = true;
2616 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2617 if (!AddRec)
2618 break;
2619 }
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002620 }
Nick Lewycky97756402014-09-01 05:17:15 +00002621 if (OpsModified)
2622 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002623
2624 // Otherwise couldn't fold anything into this recurrence. Move onto the
2625 // next one.
2626 }
2627
2628 // Okay, it looks like we really DO need an mul expr. Check to see if we
2629 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002630 FoldingSetNodeID ID;
2631 ID.AddInteger(scMulExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002632 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2633 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002634 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002635 SCEVMulExpr *S =
2636 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2637 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002638 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2639 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002640 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2641 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002642 UniqueSCEVs.InsertNode(S, IP);
2643 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002644 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002645 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002646}
2647
Andreas Bolka7a5c8db2009-08-07 22:55:26 +00002648/// getUDivExpr - Get a canonical unsigned division expression, or something
2649/// simpler if possible.
Dan Gohmanabd17092009-06-24 14:49:00 +00002650const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2651 const SCEV *RHS) {
Dan Gohmand33f36e2009-05-18 15:44:58 +00002652 assert(getEffectiveSCEVType(LHS->getType()) ==
2653 getEffectiveSCEVType(RHS->getType()) &&
2654 "SCEVUDivExpr operand types don't match!");
2655
Dan Gohmana30370b2009-05-04 22:02:23 +00002656 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002657 if (RHSC->getValue()->equalsInt(1))
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00002658 return LHS; // X udiv 1 --> x
Dan Gohmanacd700a2010-04-22 01:35:11 +00002659 // If the denominator is zero, the result of the udiv is undefined. Don't
2660 // try to analyze it, because the resolution chosen here may differ from
2661 // the resolution chosen in other parts of the compiler.
2662 if (!RHSC->getValue()->isZero()) {
2663 // Determine if the division can be folded into the operands of
2664 // its operands.
2665 // TODO: Generalize this to non-constants by using known-bits information.
Chris Lattner229907c2011-07-18 04:54:35 +00002666 Type *Ty = LHS->getType();
Dan Gohmanacd700a2010-04-22 01:35:11 +00002667 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
Dan Gohmandb764c62010-08-04 19:52:50 +00002668 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanacd700a2010-04-22 01:35:11 +00002669 // For non-power-of-two values, effectively round the value up to the
2670 // nearest power of two.
2671 if (!RHSC->getValue()->getValue().isPowerOf2())
2672 ++MaxShiftAmt;
Chris Lattner229907c2011-07-18 04:54:35 +00002673 IntegerType *ExtTy =
Dan Gohmanacd700a2010-04-22 01:35:11 +00002674 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohmanacd700a2010-04-22 01:35:11 +00002675 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2676 if (const SCEVConstant *Step =
Andrew Trick6d45a012011-08-06 07:00:37 +00002677 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2678 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2679 const APInt &StepInt = Step->getValue()->getValue();
2680 const APInt &DivInt = RHSC->getValue()->getValue();
2681 if (!StepInt.urem(DivInt) &&
Dan Gohmanacd700a2010-04-22 01:35:11 +00002682 getZeroExtendExpr(AR, ExtTy) ==
2683 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2684 getZeroExtendExpr(Step, ExtTy),
Andrew Trick8b55b732011-03-14 16:50:06 +00002685 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002686 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002687 for (const SCEV *Op : AR->operands())
2688 Operands.push_back(getUDivExpr(Op, RHS));
2689 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002690 }
Andrew Trick6d45a012011-08-06 07:00:37 +00002691 /// Get a canonical UDivExpr for a recurrence.
2692 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2693 // We can currently only fold X%N if X is constant.
2694 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2695 if (StartC && !DivInt.urem(StepInt) &&
2696 getZeroExtendExpr(AR, ExtTy) ==
2697 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2698 getZeroExtendExpr(Step, ExtTy),
2699 AR->getLoop(), SCEV::FlagAnyWrap)) {
2700 const APInt &StartInt = StartC->getValue()->getValue();
2701 const APInt &StartRem = StartInt.urem(StepInt);
2702 if (StartRem != 0)
2703 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2704 AR->getLoop(), SCEV::FlagNW);
2705 }
2706 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002707 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2708 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2709 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002710 for (const SCEV *Op : M->operands())
2711 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002712 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2713 // Find an operand that's safely divisible.
2714 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2715 const SCEV *Op = M->getOperand(i);
2716 const SCEV *Div = getUDivExpr(Op, RHSC);
2717 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2718 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2719 M->op_end());
2720 Operands[i] = Div;
2721 return getMulExpr(Operands);
2722 }
2723 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002724 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002725 // (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 +00002726 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002727 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002728 for (const SCEV *Op : A->operands())
2729 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002730 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2731 Operands.clear();
2732 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2733 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2734 if (isa<SCEVUDivExpr>(Op) ||
2735 getMulExpr(Op, RHS) != A->getOperand(i))
2736 break;
2737 Operands.push_back(Op);
2738 }
2739 if (Operands.size() == A->getNumOperands())
2740 return getAddExpr(Operands);
2741 }
2742 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002743
Dan Gohmanacd700a2010-04-22 01:35:11 +00002744 // Fold if both operands are constant.
2745 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2746 Constant *LHSCV = LHSC->getValue();
2747 Constant *RHSCV = RHSC->getValue();
2748 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2749 RHSCV)));
2750 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002751 }
2752 }
2753
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002754 FoldingSetNodeID ID;
2755 ID.AddInteger(scUDivExpr);
2756 ID.AddPointer(LHS);
2757 ID.AddPointer(RHS);
Craig Topper9f008862014-04-15 04:59:12 +00002758 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002759 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00002760 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2761 LHS, RHS);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002762 UniqueSCEVs.InsertNode(S, IP);
2763 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002764}
2765
Nick Lewycky31eaca52014-01-27 10:04:03 +00002766static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2767 APInt A = C1->getValue()->getValue().abs();
2768 APInt B = C2->getValue()->getValue().abs();
2769 uint32_t ABW = A.getBitWidth();
2770 uint32_t BBW = B.getBitWidth();
2771
2772 if (ABW > BBW)
2773 B = B.zext(ABW);
2774 else if (ABW < BBW)
2775 A = A.zext(BBW);
2776
2777 return APIntOps::GreatestCommonDivisor(A, B);
2778}
2779
2780/// getUDivExactExpr - Get a canonical unsigned division expression, or
2781/// something simpler if possible. There is no representation for an exact udiv
2782/// in SCEV IR, but we can attempt to remove factors from the LHS and RHS.
2783/// We can't do this when it's not exact because the udiv may be clearing bits.
2784const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2785 const SCEV *RHS) {
2786 // TODO: we could try to find factors in all sorts of things, but for now we
2787 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2788 // end of this file for inspiration.
2789
2790 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2791 if (!Mul)
2792 return getUDivExpr(LHS, RHS);
2793
2794 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2795 // If the mulexpr multiplies by a constant, then that constant must be the
2796 // first element of the mulexpr.
Sanjoy Das63914592015-10-18 00:29:20 +00002797 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
Nick Lewycky31eaca52014-01-27 10:04:03 +00002798 if (LHSCst == RHSCst) {
2799 SmallVector<const SCEV *, 2> Operands;
2800 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2801 return getMulExpr(Operands);
2802 }
2803
2804 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2805 // that there's a factor provided by one of the other terms. We need to
2806 // check.
2807 APInt Factor = gcd(LHSCst, RHSCst);
2808 if (!Factor.isIntN(1)) {
2809 LHSCst = cast<SCEVConstant>(
2810 getConstant(LHSCst->getValue()->getValue().udiv(Factor)));
2811 RHSCst = cast<SCEVConstant>(
2812 getConstant(RHSCst->getValue()->getValue().udiv(Factor)));
2813 SmallVector<const SCEV *, 2> Operands;
2814 Operands.push_back(LHSCst);
2815 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2816 LHS = getMulExpr(Operands);
2817 RHS = RHSCst;
Nick Lewycky629199c2014-01-27 10:47:44 +00002818 Mul = dyn_cast<SCEVMulExpr>(LHS);
2819 if (!Mul)
2820 return getUDivExactExpr(LHS, RHS);
Nick Lewycky31eaca52014-01-27 10:04:03 +00002821 }
2822 }
2823 }
2824
2825 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2826 if (Mul->getOperand(i) == RHS) {
2827 SmallVector<const SCEV *, 2> Operands;
2828 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2829 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2830 return getMulExpr(Operands);
2831 }
2832 }
2833
2834 return getUDivExpr(LHS, RHS);
2835}
Chris Lattnerd934c702004-04-02 20:23:17 +00002836
Dan Gohman4d5435d2009-05-24 23:45:28 +00002837/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2838/// Simplify the expression as much as possible.
Andrew Trick8b55b732011-03-14 16:50:06 +00002839const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2840 const Loop *L,
2841 SCEV::NoWrapFlags Flags) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002842 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00002843 Operands.push_back(Start);
Dan Gohmana30370b2009-05-04 22:02:23 +00002844 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattnerd934c702004-04-02 20:23:17 +00002845 if (StepChrec->getLoop() == L) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00002846 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002847 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattnerd934c702004-04-02 20:23:17 +00002848 }
2849
2850 Operands.push_back(Step);
Andrew Trick8b55b732011-03-14 16:50:06 +00002851 return getAddRecExpr(Operands, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002852}
2853
Dan Gohman4d5435d2009-05-24 23:45:28 +00002854/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2855/// Simplify the expression as much as possible.
Dan Gohmance973df2009-06-24 04:48:43 +00002856const SCEV *
Dan Gohmanaf752342009-07-07 17:06:11 +00002857ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick8b55b732011-03-14 16:50:06 +00002858 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002859 if (Operands.size() == 1) return Operands[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002860#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002861 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002862 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002863 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002864 "SCEVAddRecExpr operand types don't match!");
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002865 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002866 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002867 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmand33f36e2009-05-18 15:44:58 +00002868#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002869
Dan Gohmanbe928e32008-06-18 16:23:07 +00002870 if (Operands.back()->isZero()) {
2871 Operands.pop_back();
Andrew Trick8b55b732011-03-14 16:50:06 +00002872 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmanbe928e32008-06-18 16:23:07 +00002873 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002874
Dan Gohmancf9c64e2010-02-19 18:49:22 +00002875 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2876 // use that information to infer NUW and NSW flags. However, computing a
2877 // BE count requires calling getAddRecExpr, so we may not yet have a
2878 // meaningful BE count at this point (and if we don't, we'd be stuck
2879 // with a SCEVCouldNotCompute as the cached BE count).
2880
Sanjoy Das81401d42015-01-10 23:41:24 +00002881 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002882
Dan Gohman223a5d22008-08-08 18:33:12 +00002883 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmana30370b2009-05-04 22:02:23 +00002884 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00002885 const Loop *NestedLoop = NestedAR->getLoop();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002886 if (L->contains(NestedLoop)
2887 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
2888 : (!NestedLoop->contains(L) &&
2889 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002890 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmancb0efec2009-12-18 01:14:11 +00002891 NestedAR->op_end());
Dan Gohman223a5d22008-08-08 18:33:12 +00002892 Operands[0] = NestedAR->getStart();
Dan Gohmancc030b72009-06-26 22:36:20 +00002893 // AddRecs require their operands be loop-invariant with respect to their
2894 // loops. Don't perform this transformation if it would break this
2895 // requirement.
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00002896 bool AllInvariant =
2897 std::all_of(Operands.begin(), Operands.end(),
2898 [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
2899
Dan Gohmancc030b72009-06-26 22:36:20 +00002900 if (AllInvariant) {
Andrew Trick8b55b732011-03-14 16:50:06 +00002901 // Create a recurrence for the outer loop with the same step size.
2902 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002903 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2904 // inner recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002905 SCEV::NoWrapFlags OuterFlags =
2906 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick8b55b732011-03-14 16:50:06 +00002907
2908 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00002909 AllInvariant = std::all_of(
2910 NestedOperands.begin(), NestedOperands.end(),
2911 [&](const SCEV *Op) { return isLoopInvariant(Op, NestedLoop); });
2912
Andrew Trick8b55b732011-03-14 16:50:06 +00002913 if (AllInvariant) {
Dan Gohmancc030b72009-06-26 22:36:20 +00002914 // Ok, both add recurrences are valid after the transformation.
Andrew Trick8b55b732011-03-14 16:50:06 +00002915 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002916 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2917 // the outer recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002918 SCEV::NoWrapFlags InnerFlags =
2919 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick8b55b732011-03-14 16:50:06 +00002920 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2921 }
Dan Gohmancc030b72009-06-26 22:36:20 +00002922 }
2923 // Reset Operands to its original state.
2924 Operands[0] = NestedAR;
Dan Gohman223a5d22008-08-08 18:33:12 +00002925 }
2926 }
2927
Dan Gohman8d67d2f2010-01-19 22:27:22 +00002928 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2929 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002930 FoldingSetNodeID ID;
2931 ID.AddInteger(scAddRecExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002932 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2933 ID.AddPointer(Operands[i]);
2934 ID.AddPointer(L);
Craig Topper9f008862014-04-15 04:59:12 +00002935 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002936 SCEVAddRecExpr *S =
2937 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2938 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002939 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2940 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002941 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2942 O, Operands.size(), L);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002943 UniqueSCEVs.InsertNode(S, IP);
2944 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002945 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002946 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002947}
2948
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002949const SCEV *
2950ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr,
2951 const SmallVectorImpl<const SCEV *> &IndexExprs,
2952 bool InBounds) {
2953 // getSCEV(Base)->getType() has the same address space as Base->getType()
2954 // because SCEV::getType() preserves the address space.
2955 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
2956 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
2957 // instruction to its SCEV, because the Instruction may be guarded by control
2958 // flow and the no-overflow bits may not be valid for the expression in any
Jingyue Wu42f1d672015-07-28 18:22:40 +00002959 // context. This can be fixed similarly to how these flags are handled for
2960 // adds.
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002961 SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
2962
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002963 const SCEV *TotalOffset = getZero(IntPtrTy);
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002964 // The address space is unimportant. The first thing we do on CurTy is getting
2965 // its element type.
2966 Type *CurTy = PointerType::getUnqual(PointeeType);
2967 for (const SCEV *IndexExpr : IndexExprs) {
2968 // Compute the (potentially symbolic) offset in bytes for this index.
2969 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2970 // For a struct, add the member offset.
2971 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
2972 unsigned FieldNo = Index->getZExtValue();
2973 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
2974
2975 // Add the field offset to the running total offset.
2976 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
2977
2978 // Update CurTy to the type of the field at Index.
2979 CurTy = STy->getTypeAtIndex(Index);
2980 } else {
2981 // Update CurTy to its element type.
2982 CurTy = cast<SequentialType>(CurTy)->getElementType();
2983 // For an array, add the element offset, explicitly scaled.
2984 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
2985 // Getelementptr indices are signed.
2986 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
2987
2988 // Multiply the index by the element size to compute the element offset.
2989 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
2990
2991 // Add the element offset to the running total offset.
2992 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2993 }
2994 }
2995
2996 // Add the total offset from all the GEP indices to the base.
2997 return getAddExpr(BaseExpr, TotalOffset, Wrap);
2998}
2999
Dan Gohmanabd17092009-06-24 14:49:00 +00003000const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3001 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003002 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003003 Ops.push_back(LHS);
3004 Ops.push_back(RHS);
3005 return getSMaxExpr(Ops);
3006}
3007
Dan Gohmanaf752342009-07-07 17:06:11 +00003008const SCEV *
3009ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003010 assert(!Ops.empty() && "Cannot get empty smax!");
3011 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003012#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003013 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003014 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003015 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003016 "SCEVSMaxExpr operand types don't match!");
3017#endif
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003018
3019 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003020 GroupByComplexity(Ops, &LI);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003021
3022 // If there are any constants, fold them together.
3023 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003024 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003025 ++Idx;
3026 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003027 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003028 // We found two constants, fold them together!
Owen Andersonedb4a702009-07-24 23:12:02 +00003029 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003030 APIntOps::smax(LHSC->getValue()->getValue(),
3031 RHSC->getValue()->getValue()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003032 Ops[0] = getConstant(Fold);
3033 Ops.erase(Ops.begin()+1); // Erase the folded element
3034 if (Ops.size() == 1) return Ops[0];
3035 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003036 }
3037
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003038 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003039 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3040 Ops.erase(Ops.begin());
3041 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003042 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3043 // If we have an smax with a constant maximum-int, it will always be
3044 // maximum-int.
3045 return Ops[0];
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003046 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003047
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003048 if (Ops.size() == 1) return Ops[0];
3049 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003050
3051 // Find the first SMax
3052 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3053 ++Idx;
3054
3055 // Check to see if one of the operands is an SMax. If so, expand its operands
3056 // onto our operand list, and recurse to simplify.
3057 if (Idx < Ops.size()) {
3058 bool DeletedSMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003059 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003060 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003061 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003062 DeletedSMax = true;
3063 }
3064
3065 if (DeletedSMax)
3066 return getSMaxExpr(Ops);
3067 }
3068
3069 // Okay, check to see if the same value occurs in the operand list twice. If
3070 // so, delete one. Since we sorted the list, these values are required to
3071 // be adjacent.
3072 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003073 // X smax Y smax Y --> X smax Y
3074 // X smax Y --> X, if X is always greater than Y
3075 if (Ops[i] == Ops[i+1] ||
3076 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3077 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3078 --i; --e;
3079 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003080 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3081 --i; --e;
3082 }
3083
3084 if (Ops.size() == 1) return Ops[0];
3085
3086 assert(!Ops.empty() && "Reduced smax down to nothing!");
3087
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003088 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003089 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003090 FoldingSetNodeID ID;
3091 ID.AddInteger(scSMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003092 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3093 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003094 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003095 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003096 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3097 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003098 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3099 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003100 UniqueSCEVs.InsertNode(S, IP);
3101 return S;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003102}
3103
Dan Gohmanabd17092009-06-24 14:49:00 +00003104const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3105 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003106 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003107 Ops.push_back(LHS);
3108 Ops.push_back(RHS);
3109 return getUMaxExpr(Ops);
3110}
3111
Dan Gohmanaf752342009-07-07 17:06:11 +00003112const SCEV *
3113ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003114 assert(!Ops.empty() && "Cannot get empty umax!");
3115 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003116#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003117 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003118 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003119 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003120 "SCEVUMaxExpr operand types don't match!");
3121#endif
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003122
3123 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003124 GroupByComplexity(Ops, &LI);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003125
3126 // If there are any constants, fold them together.
3127 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003128 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003129 ++Idx;
3130 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003131 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003132 // We found two constants, fold them together!
Owen Andersonedb4a702009-07-24 23:12:02 +00003133 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003134 APIntOps::umax(LHSC->getValue()->getValue(),
3135 RHSC->getValue()->getValue()));
3136 Ops[0] = getConstant(Fold);
3137 Ops.erase(Ops.begin()+1); // Erase the folded element
3138 if (Ops.size() == 1) return Ops[0];
3139 LHSC = cast<SCEVConstant>(Ops[0]);
3140 }
3141
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003142 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003143 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3144 Ops.erase(Ops.begin());
3145 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003146 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3147 // If we have an umax with a constant maximum-int, it will always be
3148 // maximum-int.
3149 return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003150 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003151
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003152 if (Ops.size() == 1) return Ops[0];
3153 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003154
3155 // Find the first UMax
3156 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3157 ++Idx;
3158
3159 // Check to see if one of the operands is a UMax. If so, expand its operands
3160 // onto our operand list, and recurse to simplify.
3161 if (Idx < Ops.size()) {
3162 bool DeletedUMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003163 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003164 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003165 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003166 DeletedUMax = true;
3167 }
3168
3169 if (DeletedUMax)
3170 return getUMaxExpr(Ops);
3171 }
3172
3173 // Okay, check to see if the same value occurs in the operand list twice. If
3174 // so, delete one. Since we sorted the list, these values are required to
3175 // be adjacent.
3176 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003177 // X umax Y umax Y --> X umax Y
3178 // X umax Y --> X, if X is always greater than Y
3179 if (Ops[i] == Ops[i+1] ||
3180 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3181 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3182 --i; --e;
3183 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003184 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3185 --i; --e;
3186 }
3187
3188 if (Ops.size() == 1) return Ops[0];
3189
3190 assert(!Ops.empty() && "Reduced umax down to nothing!");
3191
3192 // Okay, it looks like we really DO need a umax expr. Check to see if we
3193 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003194 FoldingSetNodeID ID;
3195 ID.AddInteger(scUMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003196 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3197 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003198 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003199 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003200 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3201 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003202 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3203 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003204 UniqueSCEVs.InsertNode(S, IP);
3205 return S;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003206}
3207
Dan Gohmanabd17092009-06-24 14:49:00 +00003208const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3209 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003210 // ~smax(~x, ~y) == smin(x, y).
3211 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3212}
3213
Dan Gohmanabd17092009-06-24 14:49:00 +00003214const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3215 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003216 // ~umax(~x, ~y) == umin(x, y)
3217 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3218}
3219
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003220const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003221 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003222 // constant expression and then folding it back into a ConstantInt.
3223 // This is just a compile-time optimization.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003224 return getConstant(IntTy,
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003225 F.getParent()->getDataLayout().getTypeAllocSize(AllocTy));
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003226}
3227
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003228const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3229 StructType *STy,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003230 unsigned FieldNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003231 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003232 // constant expression and then folding it back into a ConstantInt.
3233 // This is just a compile-time optimization.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003234 return getConstant(
3235 IntTy,
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003236 F.getParent()->getDataLayout().getStructLayout(STy)->getElementOffset(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003237 FieldNo));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003238}
3239
Dan Gohmanaf752342009-07-07 17:06:11 +00003240const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf436bac2009-06-24 00:54:57 +00003241 // Don't attempt to do anything other than create a SCEVUnknown object
3242 // here. createSCEV only calls getUnknown after checking for all other
3243 // interesting possibilities, and any other code that calls getUnknown
3244 // is doing so in order to hide a value from SCEV canonicalization.
3245
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003246 FoldingSetNodeID ID;
3247 ID.AddInteger(scUnknown);
3248 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +00003249 void *IP = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00003250 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3251 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3252 "Stale SCEVUnknown in uniquing map!");
3253 return S;
3254 }
3255 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3256 FirstUnknown);
3257 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003258 UniqueSCEVs.InsertNode(S, IP);
3259 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +00003260}
3261
Chris Lattnerd934c702004-04-02 20:23:17 +00003262//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00003263// Basic SCEV Analysis and PHI Idiom Recognition Code
3264//
3265
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003266/// isSCEVable - Test if values of the given type are analyzable within
3267/// the SCEV framework. This primarily includes integer types, and it
3268/// can optionally include pointer types if the ScalarEvolution class
3269/// has access to target-specific information.
Chris Lattner229907c2011-07-18 04:54:35 +00003270bool ScalarEvolution::isSCEVable(Type *Ty) const {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003271 // Integers and pointers are always SCEVable.
Duncan Sands19d0b472010-02-16 11:11:14 +00003272 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003273}
3274
3275/// getTypeSizeInBits - Return the size in bits of the specified type,
3276/// for which isSCEVable must return true.
Chris Lattner229907c2011-07-18 04:54:35 +00003277uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003278 assert(isSCEVable(Ty) && "Type is not SCEVable!");
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003279 return F.getParent()->getDataLayout().getTypeSizeInBits(Ty);
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003280}
3281
3282/// getEffectiveSCEVType - Return a type with the same bitwidth as
3283/// the given type and which represents how SCEV will treat the given
3284/// type, for which isSCEVable must return true. For pointer types,
3285/// this is the pointer-sized integer type.
Chris Lattner229907c2011-07-18 04:54:35 +00003286Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003287 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3288
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003289 if (Ty->isIntegerTy())
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003290 return Ty;
3291
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003292 // The only other support type is pointer.
Duncan Sands19d0b472010-02-16 11:11:14 +00003293 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003294 return F.getParent()->getDataLayout().getIntPtrType(Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003295}
Chris Lattnerd934c702004-04-02 20:23:17 +00003296
Dan Gohmanaf752342009-07-07 17:06:11 +00003297const SCEV *ScalarEvolution::getCouldNotCompute() {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003298 return CouldNotCompute.get();
Dan Gohman31efa302009-04-18 17:58:19 +00003299}
3300
Shuxin Yangefc4c012013-07-08 17:33:13 +00003301namespace {
3302 // Helper class working with SCEVTraversal to figure out if a SCEV contains
3303 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
3304 // is set iff if find such SCEVUnknown.
3305 //
3306 struct FindInvalidSCEVUnknown {
3307 bool FindOne;
3308 FindInvalidSCEVUnknown() { FindOne = false; }
3309 bool follow(const SCEV *S) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00003310 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Shuxin Yangefc4c012013-07-08 17:33:13 +00003311 case scConstant:
3312 return false;
3313 case scUnknown:
Shuxin Yang23773b32013-07-12 07:25:38 +00003314 if (!cast<SCEVUnknown>(S)->getValue())
Shuxin Yangefc4c012013-07-08 17:33:13 +00003315 FindOne = true;
3316 return false;
3317 default:
3318 return true;
3319 }
3320 }
3321 bool isDone() const { return FindOne; }
3322 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +00003323}
Shuxin Yangefc4c012013-07-08 17:33:13 +00003324
3325bool ScalarEvolution::checkValidity(const SCEV *S) const {
3326 FindInvalidSCEVUnknown F;
3327 SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
3328 ST.visitAll(S);
3329
3330 return !F.FindOne;
3331}
3332
Chris Lattnerd934c702004-04-02 20:23:17 +00003333/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
3334/// expression and create a new one.
Dan Gohmanaf752342009-07-07 17:06:11 +00003335const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003336 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattnerd934c702004-04-02 20:23:17 +00003337
Jingyue Wu42f1d672015-07-28 18:22:40 +00003338 const SCEV *S = getExistingSCEV(V);
3339 if (S == nullptr) {
3340 S = createSCEV(V);
3341 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
3342 }
3343 return S;
3344}
3345
3346const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3347 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3348
Shuxin Yangefc4c012013-07-08 17:33:13 +00003349 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3350 if (I != ValueExprMap.end()) {
3351 const SCEV *S = I->second;
Shuxin Yang23773b32013-07-12 07:25:38 +00003352 if (checkValidity(S))
Shuxin Yangefc4c012013-07-08 17:33:13 +00003353 return S;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003354 ValueExprMap.erase(I);
Shuxin Yangefc4c012013-07-08 17:33:13 +00003355 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003356 return nullptr;
Chris Lattnerd934c702004-04-02 20:23:17 +00003357}
3358
Dan Gohman0a40ad92009-04-16 03:18:22 +00003359/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3360///
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003361const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3362 SCEV::NoWrapFlags Flags) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003363 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson53a52212009-07-13 04:09:18 +00003364 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003365 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003366
Chris Lattner229907c2011-07-18 04:54:35 +00003367 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003368 Ty = getEffectiveSCEVType(Ty);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003369 return getMulExpr(
3370 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003371}
3372
3373/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanaf752342009-07-07 17:06:11 +00003374const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003375 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson542619e2009-07-13 20:58:05 +00003376 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003377 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003378
Chris Lattner229907c2011-07-18 04:54:35 +00003379 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003380 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003381 const SCEV *AllOnes =
Owen Anderson5a1acd92009-07-31 20:28:14 +00003382 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003383 return getMinusSCEV(AllOnes, V);
3384}
3385
Andrew Trick8b55b732011-03-14 16:50:06 +00003386/// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
Chris Lattnerfc877522011-01-09 22:26:35 +00003387const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00003388 SCEV::NoWrapFlags Flags) {
Dan Gohman46f00a22010-07-20 16:53:00 +00003389 // Fast path: X - X --> 0.
3390 if (LHS == RHS)
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003391 return getZero(LHS->getType());
Dan Gohman46f00a22010-07-20 16:53:00 +00003392
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003393 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3394 // makes it so that we cannot make much use of NUW.
3395 auto AddFlags = SCEV::FlagAnyWrap;
3396 const bool RHSIsNotMinSigned =
3397 !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3398 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3399 // Let M be the minimum representable signed value. Then (-1)*RHS
3400 // signed-wraps if and only if RHS is M. That can happen even for
3401 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3402 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3403 // (-1)*RHS, we need to prove that RHS != M.
3404 //
3405 // If LHS is non-negative and we know that LHS - RHS does not
3406 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3407 // either by proving that RHS > M or that LHS >= 0.
3408 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3409 AddFlags = SCEV::FlagNSW;
3410 }
3411 }
3412
3413 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3414 // RHS is NSW and LHS >= 0.
3415 //
3416 // The difficulty here is that the NSW flag may have been proven
3417 // relative to a loop that is to be found in a recurrence in LHS and
3418 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3419 // larger scope than intended.
3420 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3421
3422 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003423}
3424
3425/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
3426/// input value to the specified type. If the type must be extended, it is zero
3427/// extended.
Dan Gohmanaf752342009-07-07 17:06:11 +00003428const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003429ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3430 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003431 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3432 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003433 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003434 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003435 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003436 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003437 return getTruncateExpr(V, Ty);
3438 return getZeroExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003439}
3440
3441/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
3442/// input value to the specified type. If the type must be extended, it is sign
3443/// extended.
Dan Gohmanaf752342009-07-07 17:06:11 +00003444const SCEV *
3445ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattner229907c2011-07-18 04:54:35 +00003446 Type *Ty) {
3447 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003448 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3449 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003450 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003451 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003452 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003453 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003454 return getTruncateExpr(V, Ty);
3455 return getSignExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003456}
3457
Dan Gohmane712a2f2009-05-13 03:46:30 +00003458/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
3459/// input value to the specified type. If the type must be extended, it is zero
3460/// extended. The conversion must not be narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003461const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003462ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3463 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003464 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3465 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003466 "Cannot noop or zero extend with non-integer arguments!");
3467 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3468 "getNoopOrZeroExtend cannot truncate!");
3469 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3470 return V; // No conversion
3471 return getZeroExtendExpr(V, Ty);
3472}
3473
3474/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
3475/// input value to the specified type. If the type must be extended, it is sign
3476/// extended. The conversion must not be narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003477const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003478ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3479 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003480 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3481 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003482 "Cannot noop or sign extend with non-integer arguments!");
3483 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3484 "getNoopOrSignExtend cannot truncate!");
3485 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3486 return V; // No conversion
3487 return getSignExtendExpr(V, Ty);
3488}
3489
Dan Gohman8db2edc2009-06-13 15:56:47 +00003490/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
3491/// the input value to the specified type. If the type must be extended,
3492/// it is extended with unspecified bits. The conversion must not be
3493/// narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003494const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003495ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3496 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003497 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3498 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman8db2edc2009-06-13 15:56:47 +00003499 "Cannot noop or any extend with non-integer arguments!");
3500 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3501 "getNoopOrAnyExtend cannot truncate!");
3502 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3503 return V; // No conversion
3504 return getAnyExtendExpr(V, Ty);
3505}
3506
Dan Gohmane712a2f2009-05-13 03:46:30 +00003507/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
3508/// input value to the specified type. The conversion must not be widening.
Dan Gohmanaf752342009-07-07 17:06:11 +00003509const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003510ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3511 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003512 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3513 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003514 "Cannot truncate or noop with non-integer arguments!");
3515 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3516 "getTruncateOrNoop cannot extend!");
3517 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3518 return V; // No conversion
3519 return getTruncateExpr(V, Ty);
3520}
3521
Dan Gohman96212b62009-06-22 00:31:57 +00003522/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
3523/// the types using zero-extension, and then perform a umax operation
3524/// with them.
Dan Gohmanabd17092009-06-24 14:49:00 +00003525const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3526 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003527 const SCEV *PromotedLHS = LHS;
3528 const SCEV *PromotedRHS = RHS;
Dan Gohman96212b62009-06-22 00:31:57 +00003529
3530 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3531 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3532 else
3533 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3534
3535 return getUMaxExpr(PromotedLHS, PromotedRHS);
3536}
3537
Dan Gohman2bc22302009-06-22 15:03:27 +00003538/// getUMinFromMismatchedTypes - Promote the operands to the wider of
3539/// the types using zero-extension, and then perform a umin operation
3540/// with them.
Dan Gohmanabd17092009-06-24 14:49:00 +00003541const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3542 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003543 const SCEV *PromotedLHS = LHS;
3544 const SCEV *PromotedRHS = RHS;
Dan Gohman2bc22302009-06-22 15:03:27 +00003545
3546 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3547 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3548 else
3549 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3550
3551 return getUMinExpr(PromotedLHS, PromotedRHS);
3552}
3553
Andrew Trick87716c92011-03-17 23:51:11 +00003554/// getPointerBase - Transitively follow the chain of pointer-type operands
3555/// until reaching a SCEV that does not have a single pointer operand. This
3556/// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
3557/// but corner cases do exist.
3558const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3559 // A pointer operand may evaluate to a nonpointer expression, such as null.
3560 if (!V->getType()->isPointerTy())
3561 return V;
3562
3563 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3564 return getPointerBase(Cast->getOperand());
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003565 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
Craig Topper9f008862014-04-15 04:59:12 +00003566 const SCEV *PtrOp = nullptr;
Andrew Trick87716c92011-03-17 23:51:11 +00003567 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
3568 I != E; ++I) {
3569 if ((*I)->getType()->isPointerTy()) {
3570 // Cannot find the base of an expression with multiple pointer operands.
3571 if (PtrOp)
3572 return V;
3573 PtrOp = *I;
3574 }
3575 }
3576 if (!PtrOp)
3577 return V;
3578 return getPointerBase(PtrOp);
3579 }
3580 return V;
3581}
3582
Dan Gohman0b89dff2009-07-25 01:13:03 +00003583/// PushDefUseChildren - Push users of the given Instruction
3584/// onto the given Worklist.
3585static void
3586PushDefUseChildren(Instruction *I,
3587 SmallVectorImpl<Instruction *> &Worklist) {
3588 // Push the def-use children onto the Worklist stack.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003589 for (User *U : I->users())
3590 Worklist.push_back(cast<Instruction>(U));
Dan Gohman0b89dff2009-07-25 01:13:03 +00003591}
3592
3593/// ForgetSymbolicValue - This looks up computed SCEV values for all
3594/// instructions that depend on the given instruction and removes them from
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003595/// the ValueExprMapType map if they reference SymName. This is used during PHI
Dan Gohman0b89dff2009-07-25 01:13:03 +00003596/// resolution.
Dan Gohmance973df2009-06-24 04:48:43 +00003597void
Dan Gohmana9c205c2010-02-25 06:57:05 +00003598ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohman0b89dff2009-07-25 01:13:03 +00003599 SmallVector<Instruction *, 16> Worklist;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003600 PushDefUseChildren(PN, Worklist);
Chris Lattnerd934c702004-04-02 20:23:17 +00003601
Dan Gohman0b89dff2009-07-25 01:13:03 +00003602 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003603 Visited.insert(PN);
Dan Gohman0b89dff2009-07-25 01:13:03 +00003604 while (!Worklist.empty()) {
Dan Gohmana9c205c2010-02-25 06:57:05 +00003605 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00003606 if (!Visited.insert(I).second)
3607 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003608
Sanjoy Das63914592015-10-18 00:29:20 +00003609 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003610 if (It != ValueExprMap.end()) {
Dan Gohman761065e2010-11-17 02:44:44 +00003611 const SCEV *Old = It->second;
3612
Dan Gohman0b89dff2009-07-25 01:13:03 +00003613 // Short-circuit the def-use traversal if the symbolic name
3614 // ceases to appear in expressions.
Dan Gohman534749b2010-11-17 22:27:42 +00003615 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohman0b89dff2009-07-25 01:13:03 +00003616 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003617
Dan Gohman0b89dff2009-07-25 01:13:03 +00003618 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohmana9c205c2010-02-25 06:57:05 +00003619 // structure, it's a PHI that's in the progress of being computed
3620 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3621 // additional loop trip count information isn't going to change anything.
3622 // In the second case, createNodeForPHI will perform the necessary
3623 // updates on its own when it gets to that point. In the third, we do
3624 // want to forget the SCEVUnknown.
3625 if (!isa<PHINode>(I) ||
Dan Gohman761065e2010-11-17 02:44:44 +00003626 !isa<SCEVUnknown>(Old) ||
3627 (I != PN && Old == SymName)) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00003628 forgetMemoizedResults(Old);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003629 ValueExprMap.erase(It);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00003630 }
Dan Gohman0b89dff2009-07-25 01:13:03 +00003631 }
3632
3633 PushDefUseChildren(I, Worklist);
3634 }
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003635}
Chris Lattnerd934c702004-04-02 20:23:17 +00003636
Sanjoy Das55015d22015-10-02 23:09:44 +00003637const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
3638 const Loop *L = LI.getLoopFor(PN->getParent());
3639 if (!L || L->getHeader() != PN->getParent())
3640 return nullptr;
3641
3642 // The loop may have multiple entrances or multiple exits; we can analyze
3643 // this phi as an addrec if it has a unique entry value and a unique
3644 // backedge value.
3645 Value *BEValueV = nullptr, *StartValueV = nullptr;
3646 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3647 Value *V = PN->getIncomingValue(i);
3648 if (L->contains(PN->getIncomingBlock(i))) {
3649 if (!BEValueV) {
3650 BEValueV = V;
3651 } else if (BEValueV != V) {
3652 BEValueV = nullptr;
3653 break;
3654 }
3655 } else if (!StartValueV) {
3656 StartValueV = V;
3657 } else if (StartValueV != V) {
3658 StartValueV = nullptr;
3659 break;
3660 }
3661 }
3662 if (BEValueV && StartValueV) {
3663 // While we are analyzing this PHI node, handle its value symbolically.
3664 const SCEV *SymbolicName = getUnknown(PN);
3665 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
3666 "PHI node already processed?");
3667 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
3668
3669 // Using this symbolic name for the PHI, analyze the value coming around
3670 // the back-edge.
3671 const SCEV *BEValue = getSCEV(BEValueV);
3672
3673 // NOTE: If BEValue is loop invariant, we know that the PHI node just
3674 // has a special value for the first iteration of the loop.
3675
3676 // If the value coming around the backedge is an add with the symbolic
3677 // value we just inserted, then we found a simple induction variable!
3678 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
3679 // If there is a single occurrence of the symbolic value, replace it
3680 // with a recurrence.
3681 unsigned FoundIndex = Add->getNumOperands();
3682 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3683 if (Add->getOperand(i) == SymbolicName)
3684 if (FoundIndex == e) {
3685 FoundIndex = i;
Dan Gohman6635bb22010-04-12 07:49:36 +00003686 break;
3687 }
Sanjoy Das55015d22015-10-02 23:09:44 +00003688
3689 if (FoundIndex != Add->getNumOperands()) {
3690 // Create an add with everything but the specified operand.
3691 SmallVector<const SCEV *, 8> Ops;
3692 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3693 if (i != FoundIndex)
3694 Ops.push_back(Add->getOperand(i));
3695 const SCEV *Accum = getAddExpr(Ops);
3696
3697 // This is not a valid addrec if the step amount is varying each
3698 // loop iteration, but is not itself an addrec in this loop.
3699 if (isLoopInvariant(Accum, L) ||
3700 (isa<SCEVAddRecExpr>(Accum) &&
3701 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
3702 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
3703
3704 // If the increment doesn't overflow, then neither the addrec nor
3705 // the post-increment will overflow.
3706 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
3707 if (OBO->getOperand(0) == PN) {
3708 if (OBO->hasNoUnsignedWrap())
3709 Flags = setFlags(Flags, SCEV::FlagNUW);
3710 if (OBO->hasNoSignedWrap())
3711 Flags = setFlags(Flags, SCEV::FlagNSW);
3712 }
3713 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
3714 // If the increment is an inbounds GEP, then we know the address
3715 // space cannot be wrapped around. We cannot make any guarantee
3716 // about signed or unsigned overflow because pointers are
3717 // unsigned but we may have a negative index from the base
3718 // pointer. We can guarantee that no unsigned wrap occurs if the
3719 // indices form a positive value.
3720 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
3721 Flags = setFlags(Flags, SCEV::FlagNW);
3722
3723 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
3724 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
3725 Flags = setFlags(Flags, SCEV::FlagNUW);
3726 }
3727
3728 // We cannot transfer nuw and nsw flags from subtraction
3729 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
3730 // for instance.
3731 }
3732
3733 const SCEV *StartVal = getSCEV(StartValueV);
3734 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
3735
3736 // Since the no-wrap flags are on the increment, they apply to the
3737 // post-incremented value as well.
3738 if (isLoopInvariant(Accum, L))
3739 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
3740
3741 // Okay, for the entire analysis of this edge we assumed the PHI
3742 // to be symbolic. We now need to go back and purge all of the
3743 // entries for the scalars that use the symbolic expression.
3744 ForgetSymbolicName(PN, SymbolicName);
3745 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
3746 return PHISCEV;
Dan Gohman6635bb22010-04-12 07:49:36 +00003747 }
3748 }
Sanjoy Das63914592015-10-18 00:29:20 +00003749 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
Sanjoy Das55015d22015-10-02 23:09:44 +00003750 // Otherwise, this could be a loop like this:
3751 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
3752 // In this case, j = {1,+,1} and BEValue is j.
3753 // Because the other in-value of i (0) fits the evolution of BEValue
3754 // i really is an addrec evolution.
3755 if (AddRec->getLoop() == L && AddRec->isAffine()) {
3756 const SCEV *StartVal = getSCEV(StartValueV);
Chris Lattnerd934c702004-04-02 20:23:17 +00003757
Sanjoy Das55015d22015-10-02 23:09:44 +00003758 // If StartVal = j.start - j.stride, we can use StartVal as the
3759 // initial step of the addrec evolution.
3760 if (StartVal ==
3761 getMinusSCEV(AddRec->getOperand(0), AddRec->getOperand(1))) {
3762 // FIXME: For constant StartVal, we should be able to infer
3763 // no-wrap flags.
3764 const SCEV *PHISCEV = getAddRecExpr(StartVal, AddRec->getOperand(1),
3765 L, SCEV::FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00003766
Sanjoy Das55015d22015-10-02 23:09:44 +00003767 // Okay, for the entire analysis of this edge we assumed the PHI
3768 // to be symbolic. We now need to go back and purge all of the
3769 // entries for the scalars that use the symbolic expression.
3770 ForgetSymbolicName(PN, SymbolicName);
3771 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
3772 return PHISCEV;
Chris Lattnerd934c702004-04-02 20:23:17 +00003773 }
Chris Lattnerd934c702004-04-02 20:23:17 +00003774 }
Dan Gohman6635bb22010-04-12 07:49:36 +00003775 }
Sanjoy Das55015d22015-10-02 23:09:44 +00003776 }
3777
3778 return nullptr;
3779}
3780
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003781// Checks if the SCEV S is available at BB. S is considered available at BB
3782// if S can be materialized at BB without introducing a fault.
3783static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
3784 BasicBlock *BB) {
3785 struct CheckAvailable {
3786 bool TraversalDone = false;
3787 bool Available = true;
Sanjoy Das55015d22015-10-02 23:09:44 +00003788
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003789 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
3790 BasicBlock *BB = nullptr;
3791 DominatorTree &DT;
Sanjoy Das55015d22015-10-02 23:09:44 +00003792
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003793 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
3794 : L(L), BB(BB), DT(DT) {}
Sanjoy Das55015d22015-10-02 23:09:44 +00003795
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003796 bool setUnavailable() {
3797 TraversalDone = true;
3798 Available = false;
Sanjoy Das55015d22015-10-02 23:09:44 +00003799 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00003800 }
3801
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003802 bool follow(const SCEV *S) {
3803 switch (S->getSCEVType()) {
3804 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
3805 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
3806 // These expressions are available if their operand(s) is/are.
Sanjoy Das55015d22015-10-02 23:09:44 +00003807 return true;
Sanjoy Das55015d22015-10-02 23:09:44 +00003808
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003809 case scAddRecExpr: {
3810 // We allow add recurrences that are on the loop BB is in, or some
3811 // outer loop. This guarantees availability because the value of the
3812 // add recurrence at BB is simply the "current" value of the induction
3813 // variable. We can relax this in the future; for instance an add
3814 // recurrence on a sibling dominating loop is also available at BB.
3815 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
3816 if (L && (ARLoop == L || ARLoop->contains(L)))
Sanjoy Das55015d22015-10-02 23:09:44 +00003817 return true;
3818
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003819 return setUnavailable();
Sanjoy Das55015d22015-10-02 23:09:44 +00003820 }
3821
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003822 case scUnknown: {
3823 // For SCEVUnknown, we check for simple dominance.
3824 const auto *SU = cast<SCEVUnknown>(S);
3825 Value *V = SU->getValue();
Sanjoy Das55015d22015-10-02 23:09:44 +00003826
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003827 if (isa<Argument>(V))
3828 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00003829
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003830 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
3831 return false;
3832
3833 return setUnavailable();
3834 }
3835
3836 case scUDivExpr:
3837 case scCouldNotCompute:
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003838 // We do not try to smart about these at all.
3839 return setUnavailable();
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003840 }
3841 llvm_unreachable("switch should be fully covered!");
3842 }
3843
3844 bool isDone() { return TraversalDone; }
Sanjoy Das55015d22015-10-02 23:09:44 +00003845 };
3846
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003847 CheckAvailable CA(L, BB, DT);
3848 SCEVTraversal<CheckAvailable> ST(CA);
3849
3850 ST.visitAll(S);
3851 return CA.Available;
3852}
3853
3854// Try to match a control flow sequence that branches out at BI and merges back
3855// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
3856// match.
3857static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
3858 Value *&C, Value *&LHS, Value *&RHS) {
3859 C = BI->getCondition();
3860
3861 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
3862 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
3863
3864 if (!LeftEdge.isSingleEdge())
3865 return false;
3866
3867 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
3868
3869 Use &LeftUse = Merge->getOperandUse(0);
3870 Use &RightUse = Merge->getOperandUse(1);
3871
3872 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
3873 LHS = LeftUse;
3874 RHS = RightUse;
3875 return true;
3876 }
3877
3878 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
3879 LHS = RightUse;
3880 RHS = LeftUse;
3881 return true;
3882 }
3883
3884 return false;
3885}
3886
3887const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
Sanjoy Das55015d22015-10-02 23:09:44 +00003888 if (PN->getNumIncomingValues() == 2) {
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003889 const Loop *L = LI.getLoopFor(PN->getParent());
3890
Sanjoy Das55015d22015-10-02 23:09:44 +00003891 // Try to match
3892 //
3893 // br %cond, label %left, label %right
3894 // left:
3895 // br label %merge
3896 // right:
3897 // br label %merge
3898 // merge:
3899 // V = phi [ %x, %left ], [ %y, %right ]
3900 //
3901 // as "select %cond, %x, %y"
3902
3903 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
3904 assert(IDom && "At least the entry block should dominate PN");
3905
3906 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
3907 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
3908
Sanjoy Das1cd930b2015-10-03 00:34:19 +00003909 if (BI && BI->isConditional() &&
3910 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
3911 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
3912 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
Sanjoy Das55015d22015-10-02 23:09:44 +00003913 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
3914 }
3915
3916 return nullptr;
3917}
3918
3919const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
3920 if (const SCEV *S = createAddRecFromPHI(PN))
3921 return S;
3922
3923 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
3924 return S;
Misha Brukman01808ca2005-04-21 21:13:18 +00003925
Dan Gohmana9c205c2010-02-25 06:57:05 +00003926 // If the PHI has a single incoming value, follow that value, unless the
3927 // PHI's incoming blocks are in a different loop, in which case doing so
3928 // risks breaking LCSSA form. Instcombine would normally zap these, but
3929 // it doesn't have DominatorTree information, so it may miss cases.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003930 if (Value *V = SimplifyInstruction(PN, F.getParent()->getDataLayout(), &TLI,
3931 &DT, &AC))
3932 if (LI.replacementPreservesLCSSAForm(PN, V))
Dan Gohmana9c205c2010-02-25 06:57:05 +00003933 return getSCEV(V);
Duncan Sands39d771312010-11-17 20:49:12 +00003934
Chris Lattnerd934c702004-04-02 20:23:17 +00003935 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanc8e23622009-04-21 23:15:49 +00003936 return getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00003937}
3938
Sanjoy Das55015d22015-10-02 23:09:44 +00003939const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
3940 Value *Cond,
3941 Value *TrueVal,
3942 Value *FalseVal) {
Mehdi Amini044cb342015-10-07 18:14:25 +00003943 // Handle "constant" branch or select. This can occur for instance when a
3944 // loop pass transforms an inner loop and moves on to process the outer loop.
3945 if (auto *CI = dyn_cast<ConstantInt>(Cond))
3946 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
3947
Sanjoy Dasd0671342015-10-02 19:39:59 +00003948 // Try to match some simple smax or umax patterns.
3949 auto *ICI = dyn_cast<ICmpInst>(Cond);
3950 if (!ICI)
3951 return getUnknown(I);
3952
3953 Value *LHS = ICI->getOperand(0);
3954 Value *RHS = ICI->getOperand(1);
3955
3956 switch (ICI->getPredicate()) {
3957 case ICmpInst::ICMP_SLT:
3958 case ICmpInst::ICMP_SLE:
3959 std::swap(LHS, RHS);
3960 // fall through
3961 case ICmpInst::ICMP_SGT:
3962 case ICmpInst::ICMP_SGE:
3963 // a >s b ? a+x : b+x -> smax(a, b)+x
3964 // a >s b ? b+x : a+x -> smin(a, b)+x
3965 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
3966 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
3967 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
3968 const SCEV *LA = getSCEV(TrueVal);
3969 const SCEV *RA = getSCEV(FalseVal);
3970 const SCEV *LDiff = getMinusSCEV(LA, LS);
3971 const SCEV *RDiff = getMinusSCEV(RA, RS);
3972 if (LDiff == RDiff)
3973 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3974 LDiff = getMinusSCEV(LA, RS);
3975 RDiff = getMinusSCEV(RA, LS);
3976 if (LDiff == RDiff)
3977 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3978 }
3979 break;
3980 case ICmpInst::ICMP_ULT:
3981 case ICmpInst::ICMP_ULE:
3982 std::swap(LHS, RHS);
3983 // fall through
3984 case ICmpInst::ICMP_UGT:
3985 case ICmpInst::ICMP_UGE:
3986 // a >u b ? a+x : b+x -> umax(a, b)+x
3987 // a >u b ? b+x : a+x -> umin(a, b)+x
3988 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
3989 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
3990 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
3991 const SCEV *LA = getSCEV(TrueVal);
3992 const SCEV *RA = getSCEV(FalseVal);
3993 const SCEV *LDiff = getMinusSCEV(LA, LS);
3994 const SCEV *RDiff = getMinusSCEV(RA, RS);
3995 if (LDiff == RDiff)
3996 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3997 LDiff = getMinusSCEV(LA, RS);
3998 RDiff = getMinusSCEV(RA, LS);
3999 if (LDiff == RDiff)
4000 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4001 }
4002 break;
4003 case ICmpInst::ICMP_NE:
4004 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4005 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4006 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4007 const SCEV *One = getOne(I->getType());
4008 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4009 const SCEV *LA = getSCEV(TrueVal);
4010 const SCEV *RA = getSCEV(FalseVal);
4011 const SCEV *LDiff = getMinusSCEV(LA, LS);
4012 const SCEV *RDiff = getMinusSCEV(RA, One);
4013 if (LDiff == RDiff)
4014 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4015 }
4016 break;
4017 case ICmpInst::ICMP_EQ:
4018 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4019 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4020 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4021 const SCEV *One = getOne(I->getType());
4022 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4023 const SCEV *LA = getSCEV(TrueVal);
4024 const SCEV *RA = getSCEV(FalseVal);
4025 const SCEV *LDiff = getMinusSCEV(LA, One);
4026 const SCEV *RDiff = getMinusSCEV(RA, LS);
4027 if (LDiff == RDiff)
4028 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4029 }
4030 break;
4031 default:
4032 break;
4033 }
4034
4035 return getUnknown(I);
4036}
4037
Dan Gohmanee750d12009-05-08 20:26:55 +00004038/// createNodeForGEP - Expand GEP instructions into add and multiply
4039/// operations. This allows them to be analyzed by regular SCEV code.
4040///
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004041const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman2173bd32009-05-08 20:36:47 +00004042 Value *Base = GEP->getOperand(0);
Dan Gohman30f24fe2009-05-09 00:14:52 +00004043 // Don't attempt to analyze GEPs over unsized objects.
Matt Arsenault404c60a2013-10-21 19:43:56 +00004044 if (!Base->getType()->getPointerElementType()->isSized())
Dan Gohman30f24fe2009-05-09 00:14:52 +00004045 return getUnknown(GEP);
Matt Arsenault4c265902013-09-27 22:38:23 +00004046
Jingyue Wu2982d4d2015-05-18 17:03:25 +00004047 SmallVector<const SCEV *, 4> IndexExprs;
4048 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4049 IndexExprs.push_back(getSCEV(*Index));
4050 return getGEPExpr(GEP->getSourceElementType(), getSCEV(Base), IndexExprs,
4051 GEP->isInBounds());
Dan Gohmanee750d12009-05-08 20:26:55 +00004052}
4053
Nick Lewycky3783b462007-11-22 07:59:40 +00004054/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
4055/// guaranteed to end in (at every loop iteration). It is, at the same time,
4056/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
4057/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004058uint32_t
Dan Gohmanaf752342009-07-07 17:06:11 +00004059ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmana30370b2009-05-04 22:02:23 +00004060 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner69ec1ec2007-11-23 22:36:49 +00004061 return C->getValue()->getValue().countTrailingZeros();
Chris Lattner49b090e2006-12-12 02:26:09 +00004062
Dan Gohmana30370b2009-05-04 22:02:23 +00004063 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanc702fc02009-06-19 23:29:04 +00004064 return std::min(GetMinTrailingZeros(T->getOperand()),
4065 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky3783b462007-11-22 07:59:40 +00004066
Dan Gohmana30370b2009-05-04 22:02:23 +00004067 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004068 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4069 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4070 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004071 }
4072
Dan Gohmana30370b2009-05-04 22:02:23 +00004073 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004074 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4075 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4076 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004077 }
4078
Dan Gohmana30370b2009-05-04 22:02:23 +00004079 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004080 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004081 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004082 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004083 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004084 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004085 }
4086
Dan Gohmana30370b2009-05-04 22:02:23 +00004087 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004088 // The result is the sum of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004089 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4090 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky3783b462007-11-22 07:59:40 +00004091 for (unsigned i = 1, e = M->getNumOperands();
4092 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004093 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky3783b462007-11-22 07:59:40 +00004094 BitWidth);
4095 return SumOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004096 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004097
Dan Gohmana30370b2009-05-04 22:02:23 +00004098 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004099 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004100 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004101 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004102 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004103 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004104 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004105
Dan Gohmana30370b2009-05-04 22:02:23 +00004106 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004107 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004108 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004109 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004110 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004111 return MinOpRes;
4112 }
4113
Dan Gohmana30370b2009-05-04 22:02:23 +00004114 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004115 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004116 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004117 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004118 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004119 return MinOpRes;
4120 }
4121
Dan Gohmanc702fc02009-06-19 23:29:04 +00004122 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4123 // For a SCEVUnknown, ask ValueTracking.
4124 unsigned BitWidth = getTypeSizeInBits(U->getType());
Dan Gohmanc702fc02009-06-19 23:29:04 +00004125 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004126 computeKnownBits(U->getValue(), Zeros, Ones, F.getParent()->getDataLayout(),
4127 0, &AC, nullptr, &DT);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004128 return Zeros.countTrailingOnes();
4129 }
4130
4131 // SCEVUDivExpr
Nick Lewycky3783b462007-11-22 07:59:40 +00004132 return 0;
Chris Lattner49b090e2006-12-12 02:26:09 +00004133}
Chris Lattnerd934c702004-04-02 20:23:17 +00004134
Sanjoy Das1f05c512014-10-10 21:22:34 +00004135/// GetRangeFromMetadata - Helper method to assign a range to V from
4136/// metadata present in the IR.
4137static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
4138 if (Instruction *I = dyn_cast<Instruction>(V)) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00004139 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00004140 ConstantRange TotalRange(
4141 cast<IntegerType>(I->getType())->getBitWidth(), false);
4142
4143 unsigned NumRanges = MD->getNumOperands() / 2;
4144 assert(NumRanges >= 1);
4145
4146 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004147 ConstantInt *Lower =
4148 mdconst::extract<ConstantInt>(MD->getOperand(2 * i + 0));
4149 ConstantInt *Upper =
4150 mdconst::extract<ConstantInt>(MD->getOperand(2 * i + 1));
Sanjoy Das1f05c512014-10-10 21:22:34 +00004151 ConstantRange Range(Lower->getValue(), Upper->getValue());
4152 TotalRange = TotalRange.unionWith(Range);
4153 }
4154
4155 return TotalRange;
4156 }
4157 }
4158
4159 return None;
4160}
4161
Sanjoy Das91b54772015-03-09 21:43:43 +00004162/// getRange - Determine the range for a particular SCEV. If SignHint is
4163/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4164/// with a "cleaner" unsigned (resp. signed) representation.
Dan Gohmane65c9172009-07-13 21:35:55 +00004165///
4166ConstantRange
Sanjoy Das91b54772015-03-09 21:43:43 +00004167ScalarEvolution::getRange(const SCEV *S,
4168 ScalarEvolution::RangeSignHint SignHint) {
4169 DenseMap<const SCEV *, ConstantRange> &Cache =
4170 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4171 : SignedRanges;
4172
Dan Gohman761065e2010-11-17 02:44:44 +00004173 // See if we've computed this range already.
Sanjoy Das91b54772015-03-09 21:43:43 +00004174 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4175 if (I != Cache.end())
Dan Gohman761065e2010-11-17 02:44:44 +00004176 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00004177
4178 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das91b54772015-03-09 21:43:43 +00004179 return setRange(C, SignHint, ConstantRange(C->getValue()->getValue()));
Dan Gohmanc702fc02009-06-19 23:29:04 +00004180
Dan Gohman85be4332010-01-26 19:19:05 +00004181 unsigned BitWidth = getTypeSizeInBits(S->getType());
4182 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4183
Sanjoy Das91b54772015-03-09 21:43:43 +00004184 // If the value has known zeros, the maximum value will have those known zeros
4185 // as well.
Dan Gohman85be4332010-01-26 19:19:05 +00004186 uint32_t TZ = GetMinTrailingZeros(S);
Sanjoy Das91b54772015-03-09 21:43:43 +00004187 if (TZ != 0) {
4188 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4189 ConservativeResult =
4190 ConstantRange(APInt::getMinValue(BitWidth),
4191 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4192 else
4193 ConservativeResult = ConstantRange(
4194 APInt::getSignedMinValue(BitWidth),
4195 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4196 }
Dan Gohman85be4332010-01-26 19:19:05 +00004197
Dan Gohmane65c9172009-07-13 21:35:55 +00004198 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004199 ConstantRange X = getRange(Add->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004200 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004201 X = X.add(getRange(Add->getOperand(i), SignHint));
4202 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004203 }
4204
4205 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004206 ConstantRange X = getRange(Mul->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004207 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004208 X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4209 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004210 }
4211
4212 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004213 ConstantRange X = getRange(SMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004214 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004215 X = X.smax(getRange(SMax->getOperand(i), SignHint));
4216 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004217 }
4218
4219 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004220 ConstantRange X = getRange(UMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004221 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004222 X = X.umax(getRange(UMax->getOperand(i), SignHint));
4223 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004224 }
4225
4226 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004227 ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4228 ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4229 return setRange(UDiv, SignHint,
4230 ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004231 }
4232
4233 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004234 ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4235 return setRange(ZExt, SignHint,
4236 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004237 }
4238
4239 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004240 ConstantRange X = getRange(SExt->getOperand(), SignHint);
4241 return setRange(SExt, SignHint,
4242 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004243 }
4244
4245 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004246 ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4247 return setRange(Trunc, SignHint,
4248 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004249 }
4250
Dan Gohmane65c9172009-07-13 21:35:55 +00004251 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004252 // If there's no unsigned wrap, the value will never be less than its
4253 // initial value.
Andrew Trick8b55b732011-03-14 16:50:06 +00004254 if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
Dan Gohman51ad99d2010-01-21 02:09:26 +00004255 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanebbd05f2010-04-12 23:08:18 +00004256 if (!C->getValue()->isZero())
Dan Gohmanae4a4142010-04-11 22:12:18 +00004257 ConservativeResult =
Dan Gohman9396b422010-06-30 06:58:35 +00004258 ConservativeResult.intersectWith(
4259 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004260
Dan Gohman51ad99d2010-01-21 02:09:26 +00004261 // If there's no signed wrap, and all the operands have the same sign or
4262 // zero, the value won't ever change sign.
Andrew Trick8b55b732011-03-14 16:50:06 +00004263 if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004264 bool AllNonNeg = true;
4265 bool AllNonPos = true;
4266 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4267 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4268 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4269 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004270 if (AllNonNeg)
Dan Gohman51aaf022010-01-26 04:40:18 +00004271 ConservativeResult = ConservativeResult.intersectWith(
4272 ConstantRange(APInt(BitWidth, 0),
4273 APInt::getSignedMinValue(BitWidth)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004274 else if (AllNonPos)
Dan Gohman51aaf022010-01-26 04:40:18 +00004275 ConservativeResult = ConservativeResult.intersectWith(
4276 ConstantRange(APInt::getSignedMinValue(BitWidth),
4277 APInt(BitWidth, 1)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004278 }
Dan Gohmane65c9172009-07-13 21:35:55 +00004279
4280 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00004281 if (AddRec->isAffine()) {
Chris Lattner229907c2011-07-18 04:54:35 +00004282 Type *Ty = AddRec->getType();
Dan Gohmane65c9172009-07-13 21:35:55 +00004283 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00004284 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4285 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004286
4287 // Check for overflow. This must be done with ConstantRange arithmetic
4288 // because we could be called from within the ScalarEvolution overflow
4289 // checking code.
4290
Dan Gohmane65c9172009-07-13 21:35:55 +00004291 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
Sanjoy Das91b54772015-03-09 21:43:43 +00004292 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4293 ConstantRange ZExtMaxBECountRange =
4294 MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1);
Dan Gohmane65c9172009-07-13 21:35:55 +00004295
4296 const SCEV *Start = AddRec->getStart();
Dan Gohmanf76210e2010-04-12 07:39:33 +00004297 const SCEV *Step = AddRec->getStepRecurrence(*this);
Sanjoy Das91b54772015-03-09 21:43:43 +00004298 ConstantRange StepSRange = getSignedRange(Step);
4299 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1);
Dan Gohmane65c9172009-07-13 21:35:55 +00004300
Sanjoy Das91b54772015-03-09 21:43:43 +00004301 ConstantRange StartURange = getUnsignedRange(Start);
4302 ConstantRange EndURange =
4303 StartURange.add(MaxBECountRange.multiply(StepSRange));
Dan Gohmanf76210e2010-04-12 07:39:33 +00004304
Sanjoy Das91b54772015-03-09 21:43:43 +00004305 // Check for unsigned overflow.
4306 ConstantRange ZExtStartURange =
4307 StartURange.zextOrTrunc(BitWidth * 2 + 1);
4308 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1);
4309 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4310 ZExtEndURange) {
4311 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(),
4312 EndURange.getUnsignedMin());
4313 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(),
4314 EndURange.getUnsignedMax());
4315 bool IsFullRange = Min.isMinValue() && Max.isMaxValue();
4316 if (!IsFullRange)
4317 ConservativeResult =
4318 ConservativeResult.intersectWith(ConstantRange(Min, Max + 1));
4319 }
Dan Gohmanf76210e2010-04-12 07:39:33 +00004320
Sanjoy Das91b54772015-03-09 21:43:43 +00004321 ConstantRange StartSRange = getSignedRange(Start);
4322 ConstantRange EndSRange =
4323 StartSRange.add(MaxBECountRange.multiply(StepSRange));
4324
4325 // Check for signed overflow. This must be done with ConstantRange
4326 // arithmetic because we could be called from within the ScalarEvolution
4327 // overflow checking code.
4328 ConstantRange SExtStartSRange =
4329 StartSRange.sextOrTrunc(BitWidth * 2 + 1);
4330 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1);
4331 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4332 SExtEndSRange) {
4333 APInt Min = APIntOps::smin(StartSRange.getSignedMin(),
4334 EndSRange.getSignedMin());
4335 APInt Max = APIntOps::smax(StartSRange.getSignedMax(),
4336 EndSRange.getSignedMax());
4337 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue();
4338 if (!IsFullRange)
4339 ConservativeResult =
4340 ConservativeResult.intersectWith(ConstantRange(Min, Max + 1));
4341 }
Dan Gohmand261d272009-06-24 01:05:09 +00004342 }
Dan Gohmand261d272009-06-24 01:05:09 +00004343 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004344
Sanjoy Das91b54772015-03-09 21:43:43 +00004345 return setRange(AddRec, SignHint, ConservativeResult);
Dan Gohmand261d272009-06-24 01:05:09 +00004346 }
4347
Dan Gohmanc702fc02009-06-19 23:29:04 +00004348 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00004349 // Check if the IR explicitly contains !range metadata.
4350 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4351 if (MDRange.hasValue())
4352 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4353
Sanjoy Das91b54772015-03-09 21:43:43 +00004354 // Split here to avoid paying the compile-time cost of calling both
4355 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
4356 // if needed.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004357 const DataLayout &DL = F.getParent()->getDataLayout();
Sanjoy Das91b54772015-03-09 21:43:43 +00004358 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4359 // For a SCEVUnknown, ask ValueTracking.
4360 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004361 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
Sanjoy Das91b54772015-03-09 21:43:43 +00004362 if (Ones != ~Zeros + 1)
4363 ConservativeResult =
4364 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4365 } else {
4366 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4367 "generalize as needed!");
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004368 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004369 if (NS > 1)
4370 ConservativeResult = ConservativeResult.intersectWith(
4371 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4372 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
Sanjoy Das91b54772015-03-09 21:43:43 +00004373 }
4374
4375 return setRange(U, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004376 }
4377
Sanjoy Das91b54772015-03-09 21:43:43 +00004378 return setRange(S, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004379}
4380
Jingyue Wu42f1d672015-07-28 18:22:40 +00004381SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004382 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004383 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4384
4385 // Return early if there are no flags to propagate to the SCEV.
4386 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4387 if (BinOp->hasNoUnsignedWrap())
4388 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4389 if (BinOp->hasNoSignedWrap())
4390 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
4391 if (Flags == SCEV::FlagAnyWrap) {
4392 return SCEV::FlagAnyWrap;
4393 }
4394
4395 // Here we check that BinOp is in the header of the innermost loop
4396 // containing BinOp, since we only deal with instructions in the loop
4397 // header. The actual loop we need to check later will come from an add
4398 // recurrence, but getting that requires computing the SCEV of the operands,
4399 // which can be expensive. This check we can do cheaply to rule out some
4400 // cases early.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004401 Loop *innermostContainingLoop = LI.getLoopFor(BinOp->getParent());
Jingyue Wu42f1d672015-07-28 18:22:40 +00004402 if (innermostContainingLoop == nullptr ||
4403 innermostContainingLoop->getHeader() != BinOp->getParent())
4404 return SCEV::FlagAnyWrap;
4405
4406 // Only proceed if we can prove that BinOp does not yield poison.
4407 if (!isKnownNotFullPoison(BinOp)) return SCEV::FlagAnyWrap;
4408
4409 // At this point we know that if V is executed, then it does not wrap
4410 // according to at least one of NSW or NUW. If V is not executed, then we do
4411 // not know if the calculation that V represents would wrap. Multiple
4412 // instructions can map to the same SCEV. If we apply NSW or NUW from V to
4413 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4414 // derived from other instructions that map to the same SCEV. We cannot make
4415 // that guarantee for cases where V is not executed. So we need to find the
4416 // loop that V is considered in relation to and prove that V is executed for
4417 // every iteration of that loop. That implies that the value that V
4418 // calculates does not wrap anywhere in the loop, so then we can apply the
4419 // flags to the SCEV.
4420 //
4421 // We check isLoopInvariant to disambiguate in case we are adding two
4422 // recurrences from different loops, so that we know which loop to prove
4423 // that V is executed in.
4424 for (int OpIndex = 0; OpIndex < 2; ++OpIndex) {
4425 const SCEV *Op = getSCEV(BinOp->getOperand(OpIndex));
4426 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
4427 const int OtherOpIndex = 1 - OpIndex;
4428 const SCEV *OtherOp = getSCEV(BinOp->getOperand(OtherOpIndex));
4429 if (isLoopInvariant(OtherOp, AddRec->getLoop()) &&
4430 isGuaranteedToExecuteForEveryIteration(BinOp, AddRec->getLoop()))
4431 return Flags;
4432 }
4433 }
4434 return SCEV::FlagAnyWrap;
4435}
4436
4437/// createSCEV - We know that there is no SCEV for the specified value. Analyze
4438/// the expression.
Chris Lattnerd934c702004-04-02 20:23:17 +00004439///
Dan Gohmanaf752342009-07-07 17:06:11 +00004440const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00004441 if (!isSCEVable(V->getType()))
Dan Gohmanc8e23622009-04-21 23:15:49 +00004442 return getUnknown(V);
Dan Gohman0a40ad92009-04-16 03:18:22 +00004443
Dan Gohman05e89732008-06-22 19:56:46 +00004444 unsigned Opcode = Instruction::UserOp1;
Dan Gohman69451a02010-03-09 23:46:50 +00004445 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman05e89732008-06-22 19:56:46 +00004446 Opcode = I->getOpcode();
Dan Gohman69451a02010-03-09 23:46:50 +00004447
4448 // Don't attempt to analyze instructions in blocks that aren't
4449 // reachable. Such instructions don't matter, and they aren't required
4450 // to obey basic rules for definitions dominating uses which this
4451 // analysis depends on.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004452 if (!DT.isReachableFromEntry(I->getParent()))
Dan Gohman69451a02010-03-09 23:46:50 +00004453 return getUnknown(V);
4454 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman05e89732008-06-22 19:56:46 +00004455 Opcode = CE->getOpcode();
Dan Gohmanf436bac2009-06-24 00:54:57 +00004456 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
4457 return getConstant(CI);
4458 else if (isa<ConstantPointerNull>(V))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00004459 return getZero(V->getType());
Dan Gohmanf161e06e2009-08-25 17:49:57 +00004460 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
4461 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman05e89732008-06-22 19:56:46 +00004462 else
Dan Gohmanc8e23622009-04-21 23:15:49 +00004463 return getUnknown(V);
Chris Lattnera3e0bb42007-04-02 05:41:38 +00004464
Dan Gohman80ca01c2009-07-17 20:47:02 +00004465 Operator *U = cast<Operator>(V);
Dan Gohman05e89732008-06-22 19:56:46 +00004466 switch (Opcode) {
Dan Gohmane5fb1032010-08-16 16:03:49 +00004467 case Instruction::Add: {
4468 // The simple thing to do would be to just call getSCEV on both operands
4469 // and call getAddExpr with the result. However if we're looking at a
4470 // bunch of things all added together, this can be quite inefficient,
4471 // because it leads to N-1 getAddExpr calls for N ultimate operands.
4472 // Instead, gather up all the operands and make a single getAddExpr call.
4473 // LLVM IR canonical form means we need only traverse the left operands.
4474 SmallVector<const SCEV *, 4> AddOps;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004475 for (Value *Op = U;; Op = U->getOperand(0)) {
4476 U = dyn_cast<Operator>(Op);
4477 unsigned Opcode = U ? U->getOpcode() : 0;
4478 if (!U || (Opcode != Instruction::Add && Opcode != Instruction::Sub)) {
4479 assert(Op != V && "V should be an add");
4480 AddOps.push_back(getSCEV(Op));
Dan Gohman47308d52010-08-31 22:53:17 +00004481 break;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004482 }
4483
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004484 if (auto *OpSCEV = getExistingSCEV(U)) {
Jingyue Wu42f1d672015-07-28 18:22:40 +00004485 AddOps.push_back(OpSCEV);
4486 break;
4487 }
4488
4489 // If a NUW or NSW flag can be applied to the SCEV for this
4490 // addition, then compute the SCEV for this addition by itself
4491 // with a separate call to getAddExpr. We need to do that
4492 // instead of pushing the operands of the addition onto AddOps,
4493 // since the flags are only known to apply to this particular
4494 // addition - they may not apply to other additions that can be
4495 // formed with operands from AddOps.
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004496 const SCEV *RHS = getSCEV(U->getOperand(1));
4497 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(U);
4498 if (Flags != SCEV::FlagAnyWrap) {
4499 const SCEV *LHS = getSCEV(U->getOperand(0));
4500 if (Opcode == Instruction::Sub)
4501 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
4502 else
4503 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
4504 break;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004505 }
4506
Dan Gohman47308d52010-08-31 22:53:17 +00004507 if (Opcode == Instruction::Sub)
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004508 AddOps.push_back(getNegativeSCEV(RHS));
Dan Gohman47308d52010-08-31 22:53:17 +00004509 else
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004510 AddOps.push_back(RHS);
Dan Gohmane5fb1032010-08-16 16:03:49 +00004511 }
Andrew Trickd25089f2011-11-29 02:16:38 +00004512 return getAddExpr(AddOps);
Dan Gohmane5fb1032010-08-16 16:03:49 +00004513 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004514
Dan Gohmane5fb1032010-08-16 16:03:49 +00004515 case Instruction::Mul: {
Dan Gohmane5fb1032010-08-16 16:03:49 +00004516 SmallVector<const SCEV *, 4> MulOps;
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004517 for (Value *Op = U;; Op = U->getOperand(0)) {
4518 U = dyn_cast<Operator>(Op);
4519 if (!U || U->getOpcode() != Instruction::Mul) {
4520 assert(Op != V && "V should be a mul");
4521 MulOps.push_back(getSCEV(Op));
4522 break;
4523 }
4524
4525 if (auto *OpSCEV = getExistingSCEV(U)) {
4526 MulOps.push_back(OpSCEV);
4527 break;
4528 }
4529
4530 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(U);
4531 if (Flags != SCEV::FlagAnyWrap) {
4532 MulOps.push_back(getMulExpr(getSCEV(U->getOperand(0)),
4533 getSCEV(U->getOperand(1)), Flags));
4534 break;
4535 }
4536
Dan Gohmane5fb1032010-08-16 16:03:49 +00004537 MulOps.push_back(getSCEV(U->getOperand(1)));
4538 }
Dan Gohmane5fb1032010-08-16 16:03:49 +00004539 return getMulExpr(MulOps);
4540 }
Dan Gohman05e89732008-06-22 19:56:46 +00004541 case Instruction::UDiv:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004542 return getUDivExpr(getSCEV(U->getOperand(0)),
4543 getSCEV(U->getOperand(1)));
Dan Gohman05e89732008-06-22 19:56:46 +00004544 case Instruction::Sub:
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004545 return getMinusSCEV(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)),
4546 getNoWrapFlagsFromUB(U));
Dan Gohman0ec05372009-04-21 02:26:00 +00004547 case Instruction::And:
4548 // For an expression like x&255 that merely masks off the high bits,
4549 // use zext(trunc(x)) as the SCEV expression.
4550 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmandf199482009-04-25 17:05:40 +00004551 if (CI->isNullValue())
4552 return getSCEV(U->getOperand(1));
Dan Gohman05c1d372009-04-27 01:41:10 +00004553 if (CI->isAllOnesValue())
4554 return getSCEV(U->getOperand(0));
Dan Gohman0ec05372009-04-21 02:26:00 +00004555 const APInt &A = CI->getValue();
Dan Gohman1ee696d2009-06-16 19:52:01 +00004556
4557 // Instcombine's ShrinkDemandedConstant may strip bits out of
4558 // constants, obscuring what would otherwise be a low-bits mask.
Jay Foada0653a32014-05-14 21:14:37 +00004559 // Use computeKnownBits to compute what ShrinkDemandedConstant
Dan Gohman1ee696d2009-06-16 19:52:01 +00004560 // knew about to reconstruct a low-bits mask value.
4561 unsigned LZ = A.countLeadingZeros();
Nick Lewycky31eaca52014-01-27 10:04:03 +00004562 unsigned TZ = A.countTrailingZeros();
Dan Gohman1ee696d2009-06-16 19:52:01 +00004563 unsigned BitWidth = A.getBitWidth();
Dan Gohman1ee696d2009-06-16 19:52:01 +00004564 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004565 computeKnownBits(U->getOperand(0), KnownZero, KnownOne,
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004566 F.getParent()->getDataLayout(), 0, &AC, nullptr, &DT);
Dan Gohman1ee696d2009-06-16 19:52:01 +00004567
Nick Lewycky31eaca52014-01-27 10:04:03 +00004568 APInt EffectiveMask =
4569 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
4570 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
4571 const SCEV *MulCount = getConstant(
4572 ConstantInt::get(getContext(), APInt::getOneBitSet(BitWidth, TZ)));
4573 return getMulExpr(
4574 getZeroExtendExpr(
4575 getTruncateExpr(
4576 getUDivExactExpr(getSCEV(U->getOperand(0)), MulCount),
4577 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
4578 U->getType()),
4579 MulCount);
4580 }
Dan Gohman0ec05372009-04-21 02:26:00 +00004581 }
4582 break;
Dan Gohman1ee696d2009-06-16 19:52:01 +00004583
Dan Gohman05e89732008-06-22 19:56:46 +00004584 case Instruction::Or:
4585 // If the RHS of the Or is a constant, we may have something like:
4586 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
4587 // optimizations will transparently handle this case.
4588 //
4589 // In order for this transformation to be safe, the LHS must be of the
4590 // form X*(2^n) and the Or constant must be less than 2^n.
4591 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00004592 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman05e89732008-06-22 19:56:46 +00004593 const APInt &CIVal = CI->getValue();
Dan Gohmanc702fc02009-06-19 23:29:04 +00004594 if (GetMinTrailingZeros(LHS) >=
Dan Gohman36bad002009-09-17 18:05:20 +00004595 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
4596 // Build a plain add SCEV.
4597 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
4598 // If the LHS of the add was an addrec and it has no-wrap flags,
4599 // transfer the no-wrap flags, since an or won't introduce a wrap.
4600 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
4601 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
Andrew Trick8b55b732011-03-14 16:50:06 +00004602 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
4603 OldAR->getNoWrapFlags());
Dan Gohman36bad002009-09-17 18:05:20 +00004604 }
4605 return S;
4606 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004607 }
Dan Gohman05e89732008-06-22 19:56:46 +00004608 break;
4609 case Instruction::Xor:
Dan Gohman05e89732008-06-22 19:56:46 +00004610 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004611 // If the RHS of the xor is a signbit, then this is just an add.
4612 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman05e89732008-06-22 19:56:46 +00004613 if (CI->getValue().isSignBit())
Dan Gohmanc8e23622009-04-21 23:15:49 +00004614 return getAddExpr(getSCEV(U->getOperand(0)),
4615 getSCEV(U->getOperand(1)));
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004616
4617 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmand277a1e2009-05-18 16:17:44 +00004618 if (CI->isAllOnesValue())
Dan Gohmanc8e23622009-04-21 23:15:49 +00004619 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman6350296e2009-05-18 16:29:04 +00004620
4621 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
4622 // This is a variant of the check for xor with -1, and it handles
4623 // the case where instcombine has trimmed non-demanded bits out
4624 // of an xor with -1.
4625 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
4626 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
4627 if (BO->getOpcode() == Instruction::And &&
4628 LCI->getValue() == CI->getValue())
4629 if (const SCEVZeroExtendExpr *Z =
Dan Gohmanb50f5a42009-06-17 01:22:39 +00004630 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Chris Lattner229907c2011-07-18 04:54:35 +00004631 Type *UTy = U->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00004632 const SCEV *Z0 = Z->getOperand();
Chris Lattner229907c2011-07-18 04:54:35 +00004633 Type *Z0Ty = Z0->getType();
Dan Gohmaneddf7712009-06-18 00:00:20 +00004634 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
4635
Dan Gohman8b0a4192010-03-01 17:49:51 +00004636 // If C is a low-bits mask, the zero extend is serving to
Dan Gohmaneddf7712009-06-18 00:00:20 +00004637 // mask off the high bits. Complement the operand and
4638 // re-apply the zext.
4639 if (APIntOps::isMask(Z0TySize, CI->getValue()))
4640 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
4641
4642 // If C is a single bit, it may be in the sign-bit position
4643 // before the zero-extend. In this case, represent the xor
4644 // using an add, which is equivalent, and re-apply the zext.
Jay Foad583abbc2010-12-07 08:25:19 +00004645 APInt Trunc = CI->getValue().trunc(Z0TySize);
4646 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
Dan Gohmaneddf7712009-06-18 00:00:20 +00004647 Trunc.isSignBit())
4648 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
4649 UTy);
Dan Gohmanb50f5a42009-06-17 01:22:39 +00004650 }
Dan Gohman05e89732008-06-22 19:56:46 +00004651 }
4652 break;
4653
4654 case Instruction::Shl:
4655 // Turn shift left of a constant amount into a multiply.
4656 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00004657 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00004658
4659 // If the shift count is not less than the bitwidth, the result of
4660 // the shift is undefined. Don't try to analyze it, because the
4661 // resolution chosen here may differ from the resolution chosen in
4662 // other parts of the compiler.
4663 if (SA->getValue().uge(BitWidth))
4664 break;
4665
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004666 // It is currently not resolved how to interpret NSW for left
4667 // shift by BitWidth - 1, so we avoid applying flags in that
4668 // case. Remove this check (or this comment) once the situation
4669 // is resolved. See
4670 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
4671 // and http://reviews.llvm.org/D8890 .
4672 auto Flags = SCEV::FlagAnyWrap;
4673 if (SA->getValue().ult(BitWidth - 1)) Flags = getNoWrapFlagsFromUB(U);
4674
Owen Andersonedb4a702009-07-24 23:12:02 +00004675 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00004676 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004677 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X), Flags);
Dan Gohman05e89732008-06-22 19:56:46 +00004678 }
4679 break;
4680
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004681 case Instruction::LShr:
Nick Lewycky52348302009-01-13 09:18:58 +00004682 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004683 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00004684 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00004685
4686 // If the shift count is not less than the bitwidth, the result of
4687 // the shift is undefined. Don't try to analyze it, because the
4688 // resolution chosen here may differ from the resolution chosen in
4689 // other parts of the compiler.
4690 if (SA->getValue().uge(BitWidth))
4691 break;
4692
Owen Andersonedb4a702009-07-24 23:12:02 +00004693 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00004694 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Dan Gohmanc8e23622009-04-21 23:15:49 +00004695 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004696 }
4697 break;
4698
Dan Gohman0ec05372009-04-21 02:26:00 +00004699 case Instruction::AShr:
4700 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
4701 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanacd700a2010-04-22 01:35:11 +00004702 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman0ec05372009-04-21 02:26:00 +00004703 if (L->getOpcode() == Instruction::Shl &&
4704 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00004705 uint64_t BitWidth = getTypeSizeInBits(U->getType());
4706
4707 // If the shift count is not less than the bitwidth, the result of
4708 // the shift is undefined. Don't try to analyze it, because the
4709 // resolution chosen here may differ from the resolution chosen in
4710 // other parts of the compiler.
4711 if (CI->getValue().uge(BitWidth))
4712 break;
4713
Dan Gohmandf199482009-04-25 17:05:40 +00004714 uint64_t Amt = BitWidth - CI->getZExtValue();
4715 if (Amt == BitWidth)
4716 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman0ec05372009-04-21 02:26:00 +00004717 return
Dan Gohmanc8e23622009-04-21 23:15:49 +00004718 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanacd700a2010-04-22 01:35:11 +00004719 IntegerType::get(getContext(),
4720 Amt)),
4721 U->getType());
Dan Gohman0ec05372009-04-21 02:26:00 +00004722 }
4723 break;
4724
Dan Gohman05e89732008-06-22 19:56:46 +00004725 case Instruction::Trunc:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004726 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00004727
4728 case Instruction::ZExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004729 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00004730
4731 case Instruction::SExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004732 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00004733
4734 case Instruction::BitCast:
4735 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00004736 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman05e89732008-06-22 19:56:46 +00004737 return getSCEV(U->getOperand(0));
4738 break;
4739
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00004740 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
4741 // lead to pointer expressions which cannot safely be expanded to GEPs,
4742 // because ScalarEvolution doesn't respect the GEP aliasing rules when
4743 // simplifying integer expressions.
Dan Gohman0a40ad92009-04-16 03:18:22 +00004744
Dan Gohmanee750d12009-05-08 20:26:55 +00004745 case Instruction::GetElementPtr:
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004746 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman0a40ad92009-04-16 03:18:22 +00004747
Dan Gohman05e89732008-06-22 19:56:46 +00004748 case Instruction::PHI:
4749 return createNodeForPHI(cast<PHINode>(U));
4750
4751 case Instruction::Select:
Sanjoy Dasd0671342015-10-02 19:39:59 +00004752 // U can also be a select constant expr, which let fall through. Since
4753 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
4754 // constant expressions cannot have instructions as operands, we'd have
4755 // returned getUnknown for a select constant expressions anyway.
4756 if (isa<Instruction>(U))
Sanjoy Das55015d22015-10-02 23:09:44 +00004757 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
4758 U->getOperand(1), U->getOperand(2));
Dan Gohman05e89732008-06-22 19:56:46 +00004759
4760 default: // We cannot analyze this expression.
4761 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00004762 }
4763
Dan Gohmanc8e23622009-04-21 23:15:49 +00004764 return getUnknown(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00004765}
4766
4767
4768
4769//===----------------------------------------------------------------------===//
4770// Iteration Count Computation Code
4771//
4772
Chandler Carruth6666c272014-10-11 00:12:11 +00004773unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
4774 if (BasicBlock *ExitingBB = L->getExitingBlock())
4775 return getSmallConstantTripCount(L, ExitingBB);
4776
4777 // No trip count information for multiple exits.
4778 return 0;
4779}
4780
Andrew Trick2b6860f2011-08-11 23:36:16 +00004781/// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
Andrew Tricke81211f2012-01-11 06:52:55 +00004782/// normal unsigned value. Returns 0 if the trip count is unknown or not
4783/// constant. Will also return 0 if the maximum trip count is very large (>=
4784/// 2^32).
4785///
4786/// This "trip count" assumes that control exits via ExitingBlock. More
4787/// precisely, it is the number of times that control may reach ExitingBlock
4788/// before taking the branch. For loops with multiple exits, it may not be the
4789/// number times that the loop header executes because the loop may exit
4790/// prematurely via another branch.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004791unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
4792 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00004793 assert(ExitingBlock && "Must pass a non-null exiting block!");
4794 assert(L->isLoopExiting(ExitingBlock) &&
4795 "Exiting block must actually branch out of the loop!");
Andrew Trick2b6860f2011-08-11 23:36:16 +00004796 const SCEVConstant *ExitCount =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004797 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
Andrew Trick2b6860f2011-08-11 23:36:16 +00004798 if (!ExitCount)
4799 return 0;
4800
4801 ConstantInt *ExitConst = ExitCount->getValue();
4802
4803 // Guard against huge trip counts.
4804 if (ExitConst->getValue().getActiveBits() > 32)
4805 return 0;
4806
4807 // In case of integer overflow, this returns 0, which is correct.
4808 return ((unsigned)ExitConst->getZExtValue()) + 1;
4809}
4810
Chandler Carruth6666c272014-10-11 00:12:11 +00004811unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
4812 if (BasicBlock *ExitingBB = L->getExitingBlock())
4813 return getSmallConstantTripMultiple(L, ExitingBB);
4814
4815 // No trip multiple information for multiple exits.
4816 return 0;
4817}
4818
Andrew Trick2b6860f2011-08-11 23:36:16 +00004819/// getSmallConstantTripMultiple - Returns the largest constant divisor of the
4820/// trip count of this loop as a normal unsigned value, if possible. This
4821/// means that the actual trip count is always a multiple of the returned
4822/// value (don't forget the trip count could very well be zero as well!).
4823///
4824/// Returns 1 if the trip count is unknown or not guaranteed to be the
4825/// multiple of a constant (which is also the case if the trip count is simply
4826/// constant, use getSmallConstantTripCount for that case), Will also return 1
4827/// if the trip count is very large (>= 2^32).
Andrew Tricke81211f2012-01-11 06:52:55 +00004828///
4829/// As explained in the comments for getSmallConstantTripCount, this assumes
4830/// that control exits the loop via ExitingBlock.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004831unsigned
4832ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
4833 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00004834 assert(ExitingBlock && "Must pass a non-null exiting block!");
4835 assert(L->isLoopExiting(ExitingBlock) &&
4836 "Exiting block must actually branch out of the loop!");
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004837 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +00004838 if (ExitCount == getCouldNotCompute())
4839 return 1;
4840
4841 // Get the trip count from the BE count by adding 1.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00004842 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType()));
Andrew Trick2b6860f2011-08-11 23:36:16 +00004843 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
4844 // to factor simple cases.
4845 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
4846 TCMul = Mul->getOperand(0);
4847
4848 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
4849 if (!MulC)
4850 return 1;
4851
4852 ConstantInt *Result = MulC->getValue();
4853
Hal Finkel30bd9342012-10-24 19:46:44 +00004854 // Guard against huge trip counts (this requires checking
4855 // for zero to handle the case where the trip count == -1 and the
4856 // addition wraps).
4857 if (!Result || Result->getValue().getActiveBits() > 32 ||
4858 Result->getValue().getActiveBits() == 0)
Andrew Trick2b6860f2011-08-11 23:36:16 +00004859 return 1;
4860
4861 return (unsigned)Result->getZExtValue();
4862}
4863
Andrew Trick3ca3f982011-07-26 17:19:55 +00004864// getExitCount - Get the expression for the number of loop iterations for which
Andrew Trickee9143a2013-05-31 23:34:46 +00004865// this loop is guaranteed not to exit via ExitingBlock. Otherwise return
Andrew Trick3ca3f982011-07-26 17:19:55 +00004866// SCEVCouldNotCompute.
Andrew Trick77c55422011-08-02 04:23:35 +00004867const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
4868 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick3ca3f982011-07-26 17:19:55 +00004869}
4870
Dan Gohman0bddac12009-02-24 18:55:53 +00004871/// getBackedgeTakenCount - If the specified loop has a predictable
4872/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
4873/// object. The backedge-taken count is the number of times the loop header
4874/// will be branched to from within the loop. This is one less than the
4875/// trip count of the loop, since it doesn't count the first iteration,
4876/// when the header is branched to from outside the loop.
4877///
4878/// Note that it is not valid to call this method on a loop without a
4879/// loop-invariant backedge-taken count (see
4880/// hasLoopInvariantBackedgeTakenCount).
4881///
Dan Gohmanaf752342009-07-07 17:06:11 +00004882const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004883 return getBackedgeTakenInfo(L).getExact(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00004884}
4885
4886/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
4887/// return the least SCEV value that is known never to be less than the
4888/// actual backedge taken count.
Dan Gohmanaf752342009-07-07 17:06:11 +00004889const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004890 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00004891}
4892
Dan Gohmandc191042009-07-08 19:23:34 +00004893/// PushLoopPHIs - Push PHI nodes in the header of the given loop
4894/// onto the given Worklist.
4895static void
4896PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
4897 BasicBlock *Header = L->getHeader();
4898
4899 // Push all Loop-header PHIs onto the Worklist stack.
4900 for (BasicBlock::iterator I = Header->begin();
4901 PHINode *PN = dyn_cast<PHINode>(I); ++I)
4902 Worklist.push_back(PN);
4903}
4904
Dan Gohman2b8da352009-04-30 20:47:05 +00004905const ScalarEvolution::BackedgeTakenInfo &
4906ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004907 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman8b0a4192010-03-01 17:49:51 +00004908 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman76466372009-04-27 20:16:15 +00004909 // update the value. The temporary CouldNotCompute value tells SCEV
4910 // code elsewhere that it shouldn't attempt to request a new
4911 // backedge-taken count, which could result in infinite recursion.
Dan Gohman0daf6872011-05-09 18:44:09 +00004912 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Andrew Trick3ca3f982011-07-26 17:19:55 +00004913 BackedgeTakenCounts.insert(std::make_pair(L, BackedgeTakenInfo()));
Chris Lattnera337f5e2011-01-09 02:16:18 +00004914 if (!Pair.second)
4915 return Pair.first->second;
Dan Gohman76466372009-04-27 20:16:15 +00004916
Sanjoy Das413dbbb2015-10-08 18:46:59 +00004917 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
Andrew Trick3ca3f982011-07-26 17:19:55 +00004918 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
4919 // must be cleared in this scope.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00004920 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00004921
4922 if (Result.getExact(this) != getCouldNotCompute()) {
4923 assert(isLoopInvariant(Result.getExact(this), L) &&
4924 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnera337f5e2011-01-09 02:16:18 +00004925 "Computed backedge-taken count isn't loop invariant for loop!");
4926 ++NumTripCountsComputed;
Andrew Trick3ca3f982011-07-26 17:19:55 +00004927 }
4928 else if (Result.getMax(this) == getCouldNotCompute() &&
4929 isa<PHINode>(L->getHeader()->begin())) {
4930 // Only count loops that have phi nodes as not being computable.
4931 ++NumTripCountsNotComputed;
Chris Lattnera337f5e2011-01-09 02:16:18 +00004932 }
Dan Gohman2b8da352009-04-30 20:47:05 +00004933
Chris Lattnera337f5e2011-01-09 02:16:18 +00004934 // Now that we know more about the trip count for this loop, forget any
4935 // existing SCEV values for PHI nodes in this loop since they are only
4936 // conservative estimates made without the benefit of trip count
4937 // information. This is similar to the code in forgetLoop, except that
4938 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004939 if (Result.hasAnyInfo()) {
Chris Lattnera337f5e2011-01-09 02:16:18 +00004940 SmallVector<Instruction *, 16> Worklist;
4941 PushLoopPHIs(L, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00004942
Chris Lattnera337f5e2011-01-09 02:16:18 +00004943 SmallPtrSet<Instruction *, 8> Visited;
4944 while (!Worklist.empty()) {
4945 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00004946 if (!Visited.insert(I).second)
4947 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00004948
Chris Lattnera337f5e2011-01-09 02:16:18 +00004949 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00004950 ValueExprMap.find_as(static_cast<Value *>(I));
Chris Lattnera337f5e2011-01-09 02:16:18 +00004951 if (It != ValueExprMap.end()) {
4952 const SCEV *Old = It->second;
Dan Gohman761065e2010-11-17 02:44:44 +00004953
Chris Lattnera337f5e2011-01-09 02:16:18 +00004954 // SCEVUnknown for a PHI either means that it has an unrecognized
4955 // structure, or it's a PHI that's in the progress of being computed
4956 // by createNodeForPHI. In the former case, additional loop trip
4957 // count information isn't going to change anything. In the later
4958 // case, createNodeForPHI will perform the necessary updates on its
4959 // own when it gets to that point.
4960 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
4961 forgetMemoizedResults(Old);
4962 ValueExprMap.erase(It);
Dan Gohmandc191042009-07-08 19:23:34 +00004963 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00004964 if (PHINode *PN = dyn_cast<PHINode>(I))
4965 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmandc191042009-07-08 19:23:34 +00004966 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00004967
4968 PushDefUseChildren(I, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00004969 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004970 }
Dan Gohman6acd95b2011-04-25 22:48:29 +00004971
4972 // Re-lookup the insert position, since the call to
Sanjoy Das413dbbb2015-10-08 18:46:59 +00004973 // computeBackedgeTakenCount above could result in a
Dan Gohman6acd95b2011-04-25 22:48:29 +00004974 // recusive call to getBackedgeTakenInfo (on a different
4975 // loop), which would invalidate the iterator computed
4976 // earlier.
4977 return BackedgeTakenCounts.find(L)->second = Result;
Chris Lattnerd934c702004-04-02 20:23:17 +00004978}
4979
Dan Gohman880c92a2009-10-31 15:04:55 +00004980/// forgetLoop - This method should be called by the client when it has
4981/// changed a loop in a way that may effect ScalarEvolution's ability to
4982/// compute a trip count, or if the loop is deleted.
4983void ScalarEvolution::forgetLoop(const Loop *L) {
4984 // Drop any stored trip count value.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004985 DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos =
4986 BackedgeTakenCounts.find(L);
4987 if (BTCPos != BackedgeTakenCounts.end()) {
4988 BTCPos->second.clear();
4989 BackedgeTakenCounts.erase(BTCPos);
4990 }
Dan Gohmanf1505722009-05-02 17:43:35 +00004991
Dan Gohman880c92a2009-10-31 15:04:55 +00004992 // Drop information about expressions based on loop-header PHIs.
Dan Gohman48f82222009-05-04 22:30:44 +00004993 SmallVector<Instruction *, 16> Worklist;
Dan Gohmandc191042009-07-08 19:23:34 +00004994 PushLoopPHIs(L, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00004995
Dan Gohmandc191042009-07-08 19:23:34 +00004996 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00004997 while (!Worklist.empty()) {
4998 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00004999 if (!Visited.insert(I).second)
5000 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005001
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005002 ValueExprMapType::iterator It =
5003 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005004 if (It != ValueExprMap.end()) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00005005 forgetMemoizedResults(It->second);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005006 ValueExprMap.erase(It);
Dan Gohmandc191042009-07-08 19:23:34 +00005007 if (PHINode *PN = dyn_cast<PHINode>(I))
5008 ConstantEvolutionLoopExitValue.erase(PN);
5009 }
5010
5011 PushDefUseChildren(I, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005012 }
Dan Gohmandcb354b2010-10-29 20:16:10 +00005013
5014 // Forget all contained loops too, to avoid dangling entries in the
5015 // ValuesAtScopes map.
5016 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5017 forgetLoop(*I);
Dan Gohman43300342009-02-17 20:49:49 +00005018}
5019
Eric Christopheref6d5932010-07-29 01:25:38 +00005020/// forgetValue - This method should be called by the client when it has
5021/// changed a value in a way that may effect its value, or which may
5022/// disconnect it from a def-use chain linking it to a loop.
5023void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005024 Instruction *I = dyn_cast<Instruction>(V);
5025 if (!I) return;
5026
5027 // Drop information about expressions based on loop-header PHIs.
5028 SmallVector<Instruction *, 16> Worklist;
5029 Worklist.push_back(I);
5030
5031 SmallPtrSet<Instruction *, 8> Visited;
5032 while (!Worklist.empty()) {
5033 I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005034 if (!Visited.insert(I).second)
5035 continue;
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005036
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005037 ValueExprMapType::iterator It =
5038 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005039 if (It != ValueExprMap.end()) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00005040 forgetMemoizedResults(It->second);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005041 ValueExprMap.erase(It);
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005042 if (PHINode *PN = dyn_cast<PHINode>(I))
5043 ConstantEvolutionLoopExitValue.erase(PN);
5044 }
5045
5046 PushDefUseChildren(I, Worklist);
5047 }
5048}
5049
Andrew Trick3ca3f982011-07-26 17:19:55 +00005050/// getExact - Get the exact loop backedge taken count considering all loop
Sanjoy Das135e5b92015-07-21 20:59:22 +00005051/// exits. A computable result can only be returned for loops with a single
5052/// exit. Returning the minimum taken count among all exits is incorrect
5053/// because one of the loop's exit limit's may have been skipped. HowFarToZero
5054/// assumes that the limit of each loop test is never skipped. This is a valid
5055/// assumption as long as the loop exits via that test. For precise results, it
5056/// is the caller's responsibility to specify the relevant loop exit using
Andrew Trick90c7a102011-11-16 00:52:40 +00005057/// getExact(ExitingBlock, SE).
Andrew Trick3ca3f982011-07-26 17:19:55 +00005058const SCEV *
5059ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const {
5060 // If any exits were not computable, the loop is not computable.
5061 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
5062
Andrew Trick90c7a102011-11-16 00:52:40 +00005063 // We need exactly one computable exit.
Andrew Trick77c55422011-08-02 04:23:35 +00005064 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005065 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
5066
Craig Topper9f008862014-04-15 04:59:12 +00005067 const SCEV *BECount = nullptr;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005068 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
Craig Topper9f008862014-04-15 04:59:12 +00005069 ENT != nullptr; ENT = ENT->getNextExit()) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005070
5071 assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
5072
5073 if (!BECount)
5074 BECount = ENT->ExactNotTaken;
Andrew Trick90c7a102011-11-16 00:52:40 +00005075 else if (BECount != ENT->ExactNotTaken)
5076 return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005077 }
Andrew Trickbbb226a2011-09-02 21:20:46 +00005078 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005079 return BECount;
5080}
5081
5082/// getExact - Get the exact not taken count for this loop exit.
5083const SCEV *
Andrew Trick77c55422011-08-02 04:23:35 +00005084ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005085 ScalarEvolution *SE) const {
5086 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
Craig Topper9f008862014-04-15 04:59:12 +00005087 ENT != nullptr; ENT = ENT->getNextExit()) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005088
Andrew Trick77c55422011-08-02 04:23:35 +00005089 if (ENT->ExitingBlock == ExitingBlock)
Andrew Trick3ca3f982011-07-26 17:19:55 +00005090 return ENT->ExactNotTaken;
5091 }
5092 return SE->getCouldNotCompute();
5093}
5094
5095/// getMax - Get the max backedge taken count for the loop.
5096const SCEV *
5097ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
5098 return Max ? Max : SE->getCouldNotCompute();
5099}
5100
Andrew Trick9093e152013-03-26 03:14:53 +00005101bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5102 ScalarEvolution *SE) const {
5103 if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S))
5104 return true;
5105
5106 if (!ExitNotTaken.ExitingBlock)
5107 return false;
5108
5109 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
Craig Topper9f008862014-04-15 04:59:12 +00005110 ENT != nullptr; ENT = ENT->getNextExit()) {
Andrew Trick9093e152013-03-26 03:14:53 +00005111
5112 if (ENT->ExactNotTaken != SE->getCouldNotCompute()
5113 && SE->hasOperand(ENT->ExactNotTaken, S)) {
5114 return true;
5115 }
5116 }
5117 return false;
5118}
5119
Andrew Trick3ca3f982011-07-26 17:19:55 +00005120/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5121/// computable exit into a persistent ExitNotTakenInfo array.
5122ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
5123 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
5124 bool Complete, const SCEV *MaxCount) : Max(MaxCount) {
5125
5126 if (!Complete)
5127 ExitNotTaken.setIncomplete();
5128
5129 unsigned NumExits = ExitCounts.size();
5130 if (NumExits == 0) return;
5131
Andrew Trick77c55422011-08-02 04:23:35 +00005132 ExitNotTaken.ExitingBlock = ExitCounts[0].first;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005133 ExitNotTaken.ExactNotTaken = ExitCounts[0].second;
5134 if (NumExits == 1) return;
5135
5136 // Handle the rare case of multiple computable exits.
5137 ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1];
5138
5139 ExitNotTakenInfo *PrevENT = &ExitNotTaken;
5140 for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) {
5141 PrevENT->setNextExit(ENT);
Andrew Trick77c55422011-08-02 04:23:35 +00005142 ENT->ExitingBlock = ExitCounts[i].first;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005143 ENT->ExactNotTaken = ExitCounts[i].second;
5144 }
5145}
5146
5147/// clear - Invalidate this result and free the ExitNotTakenInfo array.
5148void ScalarEvolution::BackedgeTakenInfo::clear() {
Craig Topper9f008862014-04-15 04:59:12 +00005149 ExitNotTaken.ExitingBlock = nullptr;
5150 ExitNotTaken.ExactNotTaken = nullptr;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005151 delete[] ExitNotTaken.getNextExit();
5152}
5153
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005154/// computeBackedgeTakenCount - Compute the number of times the backedge
Dan Gohman0bddac12009-02-24 18:55:53 +00005155/// of the specified loop will execute.
Dan Gohman2b8da352009-04-30 20:47:05 +00005156ScalarEvolution::BackedgeTakenInfo
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005157ScalarEvolution::computeBackedgeTakenCount(const Loop *L) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00005158 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohman96212b62009-06-22 00:31:57 +00005159 L->getExitingBlocks(ExitingBlocks);
Chris Lattnerd934c702004-04-02 20:23:17 +00005160
Andrew Trick839e30b2014-05-23 19:47:13 +00005161 SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005162 bool CouldComputeBECount = true;
Andrew Trickee5aa7f2014-01-15 06:42:11 +00005163 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
Andrew Trick839e30b2014-05-23 19:47:13 +00005164 const SCEV *MustExitMaxBECount = nullptr;
5165 const SCEV *MayExitMaxBECount = nullptr;
5166
5167 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5168 // and compute maxBECount.
Dan Gohman96212b62009-06-22 00:31:57 +00005169 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005170 BasicBlock *ExitBB = ExitingBlocks[i];
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005171 ExitLimit EL = computeExitLimit(L, ExitBB);
Andrew Trick839e30b2014-05-23 19:47:13 +00005172
5173 // 1. For each exit that can be computed, add an entry to ExitCounts.
5174 // CouldComputeBECount is true only if all exits can be computed.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005175 if (EL.Exact == getCouldNotCompute())
Dan Gohman96212b62009-06-22 00:31:57 +00005176 // We couldn't compute an exact value for this exit, so
Dan Gohman8885b372009-06-22 21:10:22 +00005177 // we won't be able to compute an exact value for the loop.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005178 CouldComputeBECount = false;
5179 else
Andrew Trick839e30b2014-05-23 19:47:13 +00005180 ExitCounts.push_back(std::make_pair(ExitBB, EL.Exact));
Andrew Trick3ca3f982011-07-26 17:19:55 +00005181
Andrew Trick839e30b2014-05-23 19:47:13 +00005182 // 2. Derive the loop's MaxBECount from each exit's max number of
5183 // non-exiting iterations. Partition the loop exits into two kinds:
5184 // LoopMustExits and LoopMayExits.
5185 //
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005186 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5187 // is a LoopMayExit. If any computable LoopMustExit is found, then
5188 // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise,
5189 // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is
5190 // considered greater than any computable EL.Max.
5191 if (EL.Max != getCouldNotCompute() && Latch &&
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005192 DT.dominates(ExitBB, Latch)) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005193 if (!MustExitMaxBECount)
5194 MustExitMaxBECount = EL.Max;
5195 else {
5196 MustExitMaxBECount =
5197 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max);
Andrew Tricke2553592014-05-22 00:37:03 +00005198 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005199 } else if (MayExitMaxBECount != getCouldNotCompute()) {
5200 if (!MayExitMaxBECount || EL.Max == getCouldNotCompute())
5201 MayExitMaxBECount = EL.Max;
5202 else {
5203 MayExitMaxBECount =
5204 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max);
5205 }
Andrew Trick90c7a102011-11-16 00:52:40 +00005206 }
Dan Gohman96212b62009-06-22 00:31:57 +00005207 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005208 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5209 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
Andrew Trick3ca3f982011-07-26 17:19:55 +00005210 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00005211}
5212
Andrew Trick3ca3f982011-07-26 17:19:55 +00005213ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005214ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock) {
Dan Gohman96212b62009-06-22 00:31:57 +00005215
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005216 // Okay, we've chosen an exiting block. See what condition causes us to exit
5217 // at this block and remember the exit block and whether all other targets
Benjamin Kramer5a188542014-02-11 15:44:32 +00005218 // lead to the loop header.
5219 bool MustExecuteLoopHeader = true;
Craig Topper9f008862014-04-15 04:59:12 +00005220 BasicBlock *Exit = nullptr;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00005221 for (succ_iterator SI = succ_begin(ExitingBlock), SE = succ_end(ExitingBlock);
5222 SI != SE; ++SI)
5223 if (!L->contains(*SI)) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005224 if (Exit) // Multiple exit successors.
5225 return getCouldNotCompute();
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00005226 Exit = *SI;
5227 } else if (*SI != L->getHeader()) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005228 MustExecuteLoopHeader = false;
5229 }
Dan Gohmance973df2009-06-24 04:48:43 +00005230
Chris Lattner18954852007-01-07 02:24:26 +00005231 // At this point, we know we have a conditional branch that determines whether
5232 // the loop is exited. However, we don't know if the branch is executed each
5233 // time through the loop. If not, then the execution count of the branch will
5234 // not be equal to the trip count of the loop.
5235 //
5236 // Currently we check for this by checking to see if the Exit branch goes to
5237 // the loop header. If so, we know it will always execute the same number of
Chris Lattner5a554762007-01-14 01:24:47 +00005238 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman96212b62009-06-22 00:31:57 +00005239 // loop header. This is common for un-rotated loops.
5240 //
5241 // If both of those tests fail, walk up the unique predecessor chain to the
5242 // header, stopping if there is an edge that doesn't exit the loop. If the
5243 // header is reached, the execution count of the branch will be equal to the
5244 // trip count of the loop.
5245 //
5246 // More extensive analysis could be done to handle more cases here.
5247 //
Benjamin Kramer5a188542014-02-11 15:44:32 +00005248 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005249 // The simple checks failed, try climbing the unique predecessor chain
5250 // up to the header.
5251 bool Ok = false;
Benjamin Kramer5a188542014-02-11 15:44:32 +00005252 for (BasicBlock *BB = ExitingBlock; BB; ) {
Dan Gohman96212b62009-06-22 00:31:57 +00005253 BasicBlock *Pred = BB->getUniquePredecessor();
5254 if (!Pred)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005255 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005256 TerminatorInst *PredTerm = Pred->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +00005257 for (const BasicBlock *PredSucc : PredTerm->successors()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005258 if (PredSucc == BB)
5259 continue;
5260 // If the predecessor has a successor that isn't BB and isn't
5261 // outside the loop, assume the worst.
5262 if (L->contains(PredSucc))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005263 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005264 }
5265 if (Pred == L->getHeader()) {
5266 Ok = true;
5267 break;
5268 }
5269 BB = Pred;
5270 }
5271 if (!Ok)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005272 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005273 }
5274
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005275 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005276 TerminatorInst *Term = ExitingBlock->getTerminator();
5277 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
5278 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
5279 // Proceed to the next level to examine the exit condition expression.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005280 return computeExitLimitFromCond(L, BI->getCondition(), BI->getSuccessor(0),
Benjamin Kramer5a188542014-02-11 15:44:32 +00005281 BI->getSuccessor(1),
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005282 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005283 }
5284
5285 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005286 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005287 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005288
5289 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005290}
5291
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005292/// computeExitLimitFromCond - Compute the number of times the
Dan Gohman96212b62009-06-22 00:31:57 +00005293/// backedge of the specified loop will execute if its exit condition
5294/// were a conditional branch of ExitCond, TBB, and FBB.
Andrew Trick5b245a12013-05-31 06:43:25 +00005295///
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005296/// @param ControlsExit is true if ExitCond directly controls the exit
5297/// branch. In this case, we can assume that the loop exits only if the
5298/// condition is true and can infer that failing to meet the condition prior to
5299/// integer wraparound results in undefined behavior.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005300ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005301ScalarEvolution::computeExitLimitFromCond(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005302 Value *ExitCond,
5303 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005304 BasicBlock *FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005305 bool ControlsExit) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00005306 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman96212b62009-06-22 00:31:57 +00005307 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
5308 if (BO->getOpcode() == Instruction::And) {
5309 // Recurse on the operands of the and.
Andrew Trick5b245a12013-05-31 06:43:25 +00005310 bool EitherMayExit = L->contains(TBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005311 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005312 ControlsExit && !EitherMayExit);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005313 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005314 ControlsExit && !EitherMayExit);
Dan Gohmanaf752342009-07-07 17:06:11 +00005315 const SCEV *BECount = getCouldNotCompute();
5316 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005317 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005318 // Both conditions must be true for the loop to continue executing.
5319 // Choose the less conservative count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005320 if (EL0.Exact == getCouldNotCompute() ||
5321 EL1.Exact == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005322 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005323 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005324 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5325 if (EL0.Max == getCouldNotCompute())
5326 MaxBECount = EL1.Max;
5327 else if (EL1.Max == getCouldNotCompute())
5328 MaxBECount = EL0.Max;
Dan Gohmaned627382009-06-22 15:09:28 +00005329 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005330 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohman96212b62009-06-22 00:31:57 +00005331 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005332 // Both conditions must be true at the same time for the loop to exit.
5333 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005334 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005335 if (EL0.Max == EL1.Max)
5336 MaxBECount = EL0.Max;
5337 if (EL0.Exact == EL1.Exact)
5338 BECount = EL0.Exact;
Dan Gohman96212b62009-06-22 00:31:57 +00005339 }
5340
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005341 return ExitLimit(BECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00005342 }
5343 if (BO->getOpcode() == Instruction::Or) {
5344 // Recurse on the operands of the or.
Andrew Trick5b245a12013-05-31 06:43:25 +00005345 bool EitherMayExit = L->contains(FBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005346 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005347 ControlsExit && !EitherMayExit);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005348 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005349 ControlsExit && !EitherMayExit);
Dan Gohmanaf752342009-07-07 17:06:11 +00005350 const SCEV *BECount = getCouldNotCompute();
5351 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005352 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005353 // Both conditions must be false for the loop to continue executing.
5354 // Choose the less conservative count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005355 if (EL0.Exact == getCouldNotCompute() ||
5356 EL1.Exact == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005357 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005358 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005359 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5360 if (EL0.Max == getCouldNotCompute())
5361 MaxBECount = EL1.Max;
5362 else if (EL1.Max == getCouldNotCompute())
5363 MaxBECount = EL0.Max;
Dan Gohmaned627382009-06-22 15:09:28 +00005364 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005365 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohman96212b62009-06-22 00:31:57 +00005366 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005367 // Both conditions must be false at the same time for the loop to exit.
5368 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005369 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005370 if (EL0.Max == EL1.Max)
5371 MaxBECount = EL0.Max;
5372 if (EL0.Exact == EL1.Exact)
5373 BECount = EL0.Exact;
Dan Gohman96212b62009-06-22 00:31:57 +00005374 }
5375
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005376 return ExitLimit(BECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00005377 }
5378 }
5379
5380 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman8b0a4192010-03-01 17:49:51 +00005381 // Proceed to the next level to examine the icmp.
Dan Gohman96212b62009-06-22 00:31:57 +00005382 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005383 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
Reid Spencer266e42b2006-12-23 06:05:41 +00005384
Dan Gohman6b1e2a82010-02-19 18:12:07 +00005385 // Check for a constant condition. These are normally stripped out by
5386 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
5387 // preserve the CFG and is temporarily leaving constant conditions
5388 // in place.
5389 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
5390 if (L->contains(FBB) == !CI->getZExtValue())
5391 // The backedge is always taken.
5392 return getCouldNotCompute();
5393 else
5394 // The backedge is never taken.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005395 return getZero(CI->getType());
Dan Gohman6b1e2a82010-02-19 18:12:07 +00005396 }
5397
Eli Friedmanebf98b02009-05-09 12:32:42 +00005398 // If it's not an integer or pointer comparison then compute it the hard way.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005399 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohman96212b62009-06-22 00:31:57 +00005400}
5401
Andrew Trick3ca3f982011-07-26 17:19:55 +00005402ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005403ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005404 ICmpInst *ExitCond,
5405 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005406 BasicBlock *FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005407 bool ControlsExit) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005408
Reid Spencer266e42b2006-12-23 06:05:41 +00005409 // If the condition was exit on true, convert the condition to exit on false
5410 ICmpInst::Predicate Cond;
Dan Gohman96212b62009-06-22 00:31:57 +00005411 if (!L->contains(FBB))
Reid Spencer266e42b2006-12-23 06:05:41 +00005412 Cond = ExitCond->getPredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005413 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005414 Cond = ExitCond->getInversePredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005415
5416 // Handle common loops like: for (X = "string"; *X; ++X)
5417 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
5418 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005419 ExitLimit ItCnt =
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005420 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanba820342010-02-24 17:31:30 +00005421 if (ItCnt.hasAnyInfo())
5422 return ItCnt;
Chris Lattnerec901cc2004-10-12 01:49:27 +00005423 }
5424
Dan Gohmanaf752342009-07-07 17:06:11 +00005425 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
5426 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattnerd934c702004-04-02 20:23:17 +00005427
5428 // Try to evaluate any dependencies out of the loop.
Dan Gohman8ca08852009-05-24 23:25:42 +00005429 LHS = getSCEVAtScope(LHS, L);
5430 RHS = getSCEVAtScope(RHS, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00005431
Dan Gohmance973df2009-06-24 04:48:43 +00005432 // At this point, we would like to compute how many iterations of the
Reid Spencer266e42b2006-12-23 06:05:41 +00005433 // loop the predicate will return true for these inputs.
Dan Gohmanafd6db92010-11-17 21:23:15 +00005434 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohmandc5f5cb2008-09-16 18:52:57 +00005435 // If there is a loop-invariant, force it into the RHS.
Chris Lattnerd934c702004-04-02 20:23:17 +00005436 std::swap(LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00005437 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattnerd934c702004-04-02 20:23:17 +00005438 }
5439
Dan Gohman81585c12010-05-03 16:35:17 +00005440 // Simplify the operands before analyzing them.
5441 (void)SimplifyICmpOperands(Cond, LHS, RHS);
5442
Chris Lattnerd934c702004-04-02 20:23:17 +00005443 // If we have a comparison of a chrec against a constant, try to use value
5444 // ranges to answer this query.
Dan Gohmana30370b2009-05-04 22:02:23 +00005445 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
5446 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattnerd934c702004-04-02 20:23:17 +00005447 if (AddRec->getLoop() == L) {
Eli Friedmanebf98b02009-05-09 12:32:42 +00005448 // Form the constant range.
5449 ConstantRange CompRange(
5450 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman01808ca2005-04-21 21:13:18 +00005451
Dan Gohmanaf752342009-07-07 17:06:11 +00005452 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedmanebf98b02009-05-09 12:32:42 +00005453 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattnerd934c702004-04-02 20:23:17 +00005454 }
Misha Brukman01808ca2005-04-21 21:13:18 +00005455
Chris Lattnerd934c702004-04-02 20:23:17 +00005456 switch (Cond) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005457 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattnerd934c702004-04-02 20:23:17 +00005458 // Convert to: while (X-Y != 0)
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005459 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005460 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00005461 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005462 }
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00005463 case ICmpInst::ICMP_EQ: { // while (X == Y)
5464 // Convert to: while (X-Y == 0)
Andrew Trick3ca3f982011-07-26 17:19:55 +00005465 ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
5466 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00005467 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005468 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00005469 case ICmpInst::ICMP_SLT:
5470 case ICmpInst::ICMP_ULT: { // while (X < Y)
5471 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005472 ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, ControlsExit);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005473 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00005474 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005475 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00005476 case ICmpInst::ICMP_SGT:
5477 case ICmpInst::ICMP_UGT: { // while (X > Y)
5478 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005479 ExitLimit EL = HowManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005480 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00005481 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005482 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005483 default:
Chris Lattner09169212004-04-02 20:26:46 +00005484#if 0
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005485 dbgs() << "computeBackedgeTakenCount ";
Chris Lattnerd934c702004-04-02 20:23:17 +00005486 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greenedf1c4972009-12-23 22:18:14 +00005487 dbgs() << "[unsigned] ";
5488 dbgs() << *LHS << " "
Dan Gohmance973df2009-06-24 04:48:43 +00005489 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencer266e42b2006-12-23 06:05:41 +00005490 << " " << *RHS << "\n";
Chris Lattner09169212004-04-02 20:26:46 +00005491#endif
Chris Lattner0defaa12004-04-03 00:43:03 +00005492 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00005493 }
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005494 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner4021d1a2004-04-17 18:36:24 +00005495}
5496
Benjamin Kramer5a188542014-02-11 15:44:32 +00005497ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005498ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
Benjamin Kramer5a188542014-02-11 15:44:32 +00005499 SwitchInst *Switch,
5500 BasicBlock *ExitingBlock,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005501 bool ControlsExit) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005502 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
5503
5504 // Give up if the exit is the default dest of a switch.
5505 if (Switch->getDefaultDest() == ExitingBlock)
5506 return getCouldNotCompute();
5507
5508 assert(L->contains(Switch->getDefaultDest()) &&
5509 "Default case must not exit the loop!");
5510 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
5511 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
5512
5513 // while (X != Y) --> while (X-Y != 0)
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005514 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005515 if (EL.hasAnyInfo())
5516 return EL;
5517
5518 return getCouldNotCompute();
5519}
5520
Chris Lattnerec901cc2004-10-12 01:49:27 +00005521static ConstantInt *
Dan Gohmana37eaf22007-10-22 18:31:58 +00005522EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
5523 ScalarEvolution &SE) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005524 const SCEV *InVal = SE.getConstant(C);
5525 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005526 assert(isa<SCEVConstant>(Val) &&
5527 "Evaluation of SCEV at constant didn't fold correctly?");
5528 return cast<SCEVConstant>(Val)->getValue();
5529}
5530
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005531/// computeLoadConstantCompareExitLimit - Given an exit condition of
Dan Gohman0bddac12009-02-24 18:55:53 +00005532/// 'icmp op load X, cst', try to see if we can compute the backedge
5533/// execution count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005534ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005535ScalarEvolution::computeLoadConstantCompareExitLimit(
Andrew Trick3ca3f982011-07-26 17:19:55 +00005536 LoadInst *LI,
5537 Constant *RHS,
5538 const Loop *L,
5539 ICmpInst::Predicate predicate) {
5540
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005541 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005542
5543 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanba820342010-02-24 17:31:30 +00005544 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattnerec901cc2004-10-12 01:49:27 +00005545 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005546 if (!GEP) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005547
5548 // Make sure that it is really a constant global we are gepping, with an
5549 // initializer, and make sure the first IDX is really 0.
5550 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00005551 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00005552 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
5553 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005554 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005555
5556 // Okay, we allow one non-constant index into the GEP instruction.
Craig Topper9f008862014-04-15 04:59:12 +00005557 Value *VarIdx = nullptr;
Chris Lattnere166a852012-01-24 05:49:24 +00005558 std::vector<Constant*> Indexes;
Chris Lattnerec901cc2004-10-12 01:49:27 +00005559 unsigned VarIdxNum = 0;
5560 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
5561 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5562 Indexes.push_back(CI);
5563 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005564 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattnerec901cc2004-10-12 01:49:27 +00005565 VarIdx = GEP->getOperand(i);
5566 VarIdxNum = i-2;
Craig Topper9f008862014-04-15 04:59:12 +00005567 Indexes.push_back(nullptr);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005568 }
5569
Andrew Trick7004e4b2012-03-26 22:33:59 +00005570 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
5571 if (!VarIdx)
5572 return getCouldNotCompute();
5573
Chris Lattnerec901cc2004-10-12 01:49:27 +00005574 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
5575 // Check to see if X is a loop variant variable value now.
Dan Gohmanaf752342009-07-07 17:06:11 +00005576 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohman8ca08852009-05-24 23:25:42 +00005577 Idx = getSCEVAtScope(Idx, L);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005578
5579 // We can only recognize very limited forms of loop index expressions, in
5580 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman48f82222009-05-04 22:30:44 +00005581 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanafd6db92010-11-17 21:23:15 +00005582 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00005583 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
5584 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005585 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005586
5587 unsigned MaxSteps = MaxBruteForceIterations;
5588 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersonedb4a702009-07-24 23:12:02 +00005589 ConstantInt *ItCst = ConstantInt::get(
Owen Andersonb6b25302009-07-14 23:09:55 +00005590 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanc8e23622009-04-21 23:15:49 +00005591 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005592
5593 // Form the GEP offset.
5594 Indexes[VarIdxNum] = Val;
5595
Chris Lattnere166a852012-01-24 05:49:24 +00005596 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
5597 Indexes);
Craig Topper9f008862014-04-15 04:59:12 +00005598 if (!Result) break; // Cannot compute!
Chris Lattnerec901cc2004-10-12 01:49:27 +00005599
5600 // Evaluate the condition for this iteration.
Reid Spencer266e42b2006-12-23 06:05:41 +00005601 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00005602 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer983e3b32007-03-01 07:25:48 +00005603 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00005604#if 0
David Greenedf1c4972009-12-23 22:18:14 +00005605 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmane20f8242009-04-21 00:47:46 +00005606 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
5607 << "***\n";
Chris Lattnerec901cc2004-10-12 01:49:27 +00005608#endif
5609 ++NumArrayLenItCounts;
Dan Gohmanc8e23622009-04-21 23:15:49 +00005610 return getConstant(ItCst); // Found terminating iteration!
Chris Lattnerec901cc2004-10-12 01:49:27 +00005611 }
5612 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005613 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005614}
5615
5616
Chris Lattnerdd730472004-04-17 22:58:41 +00005617/// CanConstantFold - Return true if we can constant fold an instruction of the
5618/// specified type, assuming that all operands were constants.
5619static bool CanConstantFold(const Instruction *I) {
Reid Spencer2341c222007-02-02 02:16:23 +00005620 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Nick Lewyckya6674c72011-10-22 19:58:20 +00005621 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
5622 isa<LoadInst>(I))
Chris Lattnerdd730472004-04-17 22:58:41 +00005623 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00005624
Chris Lattnerdd730472004-04-17 22:58:41 +00005625 if (const CallInst *CI = dyn_cast<CallInst>(I))
5626 if (const Function *F = CI->getCalledFunction())
Dan Gohmana65951f2008-01-31 01:05:10 +00005627 return canConstantFoldCallTo(F);
Chris Lattnerdd730472004-04-17 22:58:41 +00005628 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00005629}
5630
Andrew Trick3a86ba72011-10-05 03:25:31 +00005631/// Determine whether this instruction can constant evolve within this loop
5632/// assuming its operands can all constant evolve.
5633static bool canConstantEvolve(Instruction *I, const Loop *L) {
5634 // An instruction outside of the loop can't be derived from a loop PHI.
5635 if (!L->contains(I)) return false;
5636
5637 if (isa<PHINode>(I)) {
David Blaikie19ef0d32015-03-24 16:33:19 +00005638 // We don't currently keep track of the control flow needed to evaluate
5639 // PHIs, so we cannot handle PHIs inside of loops.
5640 return L->getHeader() == I->getParent();
Andrew Trick3a86ba72011-10-05 03:25:31 +00005641 }
5642
5643 // If we won't be able to constant fold this expression even if the operands
5644 // are constants, bail early.
5645 return CanConstantFold(I);
5646}
5647
5648/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
5649/// recursing through each instruction operand until reaching a loop header phi.
5650static PHINode *
5651getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
Andrew Tricke9162f12011-10-05 05:58:49 +00005652 DenseMap<Instruction *, PHINode *> &PHIMap) {
Andrew Trick3a86ba72011-10-05 03:25:31 +00005653
5654 // Otherwise, we can evaluate this instruction if all of its operands are
5655 // constant or derived from a PHI node themselves.
Craig Topper9f008862014-04-15 04:59:12 +00005656 PHINode *PHI = nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005657 for (Instruction::op_iterator OpI = UseInst->op_begin(),
5658 OpE = UseInst->op_end(); OpI != OpE; ++OpI) {
5659
5660 if (isa<Constant>(*OpI)) continue;
5661
5662 Instruction *OpInst = dyn_cast<Instruction>(*OpI);
Craig Topper9f008862014-04-15 04:59:12 +00005663 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005664
5665 PHINode *P = dyn_cast<PHINode>(OpInst);
Andrew Trick3e8a5762011-10-05 22:06:53 +00005666 if (!P)
5667 // If this operand is already visited, reuse the prior result.
5668 // We may have P != PHI if this is the deepest point at which the
5669 // inconsistent paths meet.
5670 P = PHIMap.lookup(OpInst);
5671 if (!P) {
5672 // Recurse and memoize the results, whether a phi is found or not.
5673 // This recursive call invalidates pointers into PHIMap.
5674 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
5675 PHIMap[OpInst] = P;
Andrew Tricke9162f12011-10-05 05:58:49 +00005676 }
Craig Topper9f008862014-04-15 04:59:12 +00005677 if (!P)
5678 return nullptr; // Not evolving from PHI
5679 if (PHI && PHI != P)
5680 return nullptr; // Evolving from multiple different PHIs.
Andrew Tricke9162f12011-10-05 05:58:49 +00005681 PHI = P;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005682 }
5683 // This is a expression evolving from a constant PHI!
5684 return PHI;
5685}
5686
Chris Lattnerdd730472004-04-17 22:58:41 +00005687/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
5688/// in the loop that V is derived from. We allow arbitrary operations along the
5689/// way, but the operands of an operation must either be constants or a value
5690/// derived from a constant PHI. If this expression does not fit with these
5691/// constraints, return null.
5692static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00005693 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00005694 if (!I || !canConstantEvolve(I, L)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00005695
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00005696 if (PHINode *PN = dyn_cast<PHINode>(I))
Andrew Trick3a86ba72011-10-05 03:25:31 +00005697 return PN;
Chris Lattnerdd730472004-04-17 22:58:41 +00005698
Andrew Trick3a86ba72011-10-05 03:25:31 +00005699 // Record non-constant instructions contained by the loop.
Andrew Tricke9162f12011-10-05 05:58:49 +00005700 DenseMap<Instruction *, PHINode *> PHIMap;
5701 return getConstantEvolvingPHIOperands(I, L, PHIMap);
Chris Lattnerdd730472004-04-17 22:58:41 +00005702}
5703
5704/// EvaluateExpression - Given an expression that passes the
5705/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
5706/// in the loop has the value PHIVal. If we can't fold this expression for some
5707/// reason, return null.
Andrew Trick3a86ba72011-10-05 03:25:31 +00005708static Constant *EvaluateExpression(Value *V, const Loop *L,
5709 DenseMap<Instruction *, Constant *> &Vals,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005710 const DataLayout &DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00005711 const TargetLibraryInfo *TLI) {
Andrew Tricke9162f12011-10-05 05:58:49 +00005712 // Convenient constant check, but redundant for recursive calls.
Reid Spencer30d69a52004-07-18 00:18:30 +00005713 if (Constant *C = dyn_cast<Constant>(V)) return C;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005714 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00005715 if (!I) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005716
Andrew Trick3a86ba72011-10-05 03:25:31 +00005717 if (Constant *C = Vals.lookup(I)) return C;
5718
Nick Lewyckya6674c72011-10-22 19:58:20 +00005719 // An instruction inside the loop depends on a value outside the loop that we
5720 // weren't given a mapping for, or a value such as a call inside the loop.
Craig Topper9f008862014-04-15 04:59:12 +00005721 if (!canConstantEvolve(I, L)) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005722
5723 // An unmapped PHI can be due to a branch or another loop inside this loop,
5724 // or due to this not being the initial iteration through a loop where we
5725 // couldn't compute the evolution of this particular PHI last time.
Craig Topper9f008862014-04-15 04:59:12 +00005726 if (isa<PHINode>(I)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00005727
Dan Gohmanf820bd32010-06-22 13:15:46 +00005728 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattnerdd730472004-04-17 22:58:41 +00005729
5730 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Andrew Tricke9162f12011-10-05 05:58:49 +00005731 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
5732 if (!Operand) {
Nick Lewyckya447e0f32011-10-14 09:38:46 +00005733 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00005734 if (!Operands[i]) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00005735 continue;
5736 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005737 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Andrew Tricke9162f12011-10-05 05:58:49 +00005738 Vals[Operand] = C;
Craig Topper9f008862014-04-15 04:59:12 +00005739 if (!C) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00005740 Operands[i] = C;
Chris Lattnerdd730472004-04-17 22:58:41 +00005741 }
5742
Nick Lewyckya6674c72011-10-22 19:58:20 +00005743 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00005744 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005745 Operands[1], DL, TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005746 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5747 if (!LI->isVolatile())
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005748 return ConstantFoldLoadFromConstPtr(Operands[0], DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005749 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005750 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00005751 TLI);
Chris Lattnerdd730472004-04-17 22:58:41 +00005752}
5753
5754/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
5755/// in the header of its containing loop, we know the loop executes a
5756/// constant number of times, and the PHI node is just a recurrence
5757/// involving constants, fold it.
Dan Gohmance973df2009-06-24 04:48:43 +00005758Constant *
5759ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohmancb0efec2009-12-18 01:14:11 +00005760 const APInt &BEs,
Dan Gohmance973df2009-06-24 04:48:43 +00005761 const Loop *L) {
Sanjoy Das4493b402015-10-07 17:38:25 +00005762 auto I = ConstantEvolutionLoopExitValue.find(PN);
Chris Lattnerdd730472004-04-17 22:58:41 +00005763 if (I != ConstantEvolutionLoopExitValue.end())
5764 return I->second;
5765
Dan Gohman4ce1fb12010-04-08 23:03:40 +00005766 if (BEs.ugt(MaxBruteForceIterations))
Craig Topper9f008862014-04-15 04:59:12 +00005767 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
Chris Lattnerdd730472004-04-17 22:58:41 +00005768
5769 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
5770
Andrew Trick3a86ba72011-10-05 03:25:31 +00005771 DenseMap<Instruction *, Constant *> CurrentIterVals;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005772 BasicBlock *Header = L->getHeader();
5773 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
Andrew Trick3a86ba72011-10-05 03:25:31 +00005774
Sanjoy Dasdd709962015-10-08 18:28:36 +00005775 BasicBlock *Latch = L->getLoopLatch();
5776 if (!Latch)
5777 return nullptr;
5778
5779 // Since the loop has one latch, the PHI node must have two entries. One
Chris Lattnerdd730472004-04-17 22:58:41 +00005780 // entry must be a constant (coming in from outside of the loop), and the
5781 // second must be derived from the same PHI.
Sanjoy Dasdd709962015-10-08 18:28:36 +00005782
5783 BasicBlock *NonLatch = Latch == PN->getIncomingBlock(0)
5784 ? PN->getIncomingBlock(1)
5785 : PN->getIncomingBlock(0);
5786
5787 assert(PN->getNumIncomingValues() == 2 && "Follows from having one latch!");
5788
5789 // Note: not all PHI nodes in the same block have to have their incoming
5790 // values in the same order, so we use the basic block to look up the incoming
5791 // value, not an index.
5792
Sanjoy Das4493b402015-10-07 17:38:25 +00005793 for (auto &I : *Header) {
5794 PHINode *PHI = dyn_cast<PHINode>(&I);
5795 if (!PHI) break;
5796 auto *StartCST =
Sanjoy Dasdd709962015-10-08 18:28:36 +00005797 dyn_cast<Constant>(PHI->getIncomingValueForBlock(NonLatch));
Craig Topper9f008862014-04-15 04:59:12 +00005798 if (!StartCST) continue;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005799 CurrentIterVals[PHI] = StartCST;
5800 }
5801 if (!CurrentIterVals.count(PN))
Craig Topper9f008862014-04-15 04:59:12 +00005802 return RetVal = nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00005803
Sanjoy Dasdd709962015-10-08 18:28:36 +00005804 Value *BEValue = PN->getIncomingValueForBlock(Latch);
Chris Lattnerdd730472004-04-17 22:58:41 +00005805
5806 // Execute the loop symbolically to determine the exit value.
Dan Gohman0bddac12009-02-24 18:55:53 +00005807 if (BEs.getActiveBits() >= 32)
Craig Topper9f008862014-04-15 04:59:12 +00005808 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
Chris Lattnerdd730472004-04-17 22:58:41 +00005809
Dan Gohman0bddac12009-02-24 18:55:53 +00005810 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencer983e3b32007-03-01 07:25:48 +00005811 unsigned IterationNum = 0;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005812 const DataLayout &DL = F.getParent()->getDataLayout();
Andrew Trick3a86ba72011-10-05 03:25:31 +00005813 for (; ; ++IterationNum) {
Chris Lattnerdd730472004-04-17 22:58:41 +00005814 if (IterationNum == NumIterations)
Andrew Trick3a86ba72011-10-05 03:25:31 +00005815 return RetVal = CurrentIterVals[PN]; // Got exit value!
Chris Lattnerdd730472004-04-17 22:58:41 +00005816
Nick Lewyckya6674c72011-10-22 19:58:20 +00005817 // Compute the value of the PHIs for the next iteration.
Andrew Trick3a86ba72011-10-05 03:25:31 +00005818 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
Nick Lewyckya6674c72011-10-22 19:58:20 +00005819 DenseMap<Instruction *, Constant *> NextIterVals;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005820 Constant *NextPHI =
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005821 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Craig Topper9f008862014-04-15 04:59:12 +00005822 if (!NextPHI)
5823 return nullptr; // Couldn't evaluate!
Andrew Trick3a86ba72011-10-05 03:25:31 +00005824 NextIterVals[PN] = NextPHI;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005825
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005826 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
5827
Nick Lewyckya6674c72011-10-22 19:58:20 +00005828 // Also evaluate the other PHI nodes. However, we don't get to stop if we
5829 // cease to be able to evaluate one of them or if they stop evolving,
5830 // because that doesn't necessarily prevent us from computing PN.
Nick Lewyckyd48ab842011-11-12 03:09:12 +00005831 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00005832 for (const auto &I : CurrentIterVals) {
5833 PHINode *PHI = dyn_cast<PHINode>(I.first);
Nick Lewycky8e904de2011-10-24 05:51:01 +00005834 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
Sanjoy Das4493b402015-10-07 17:38:25 +00005835 PHIsToCompute.emplace_back(PHI, I.second);
Nick Lewyckyd48ab842011-11-12 03:09:12 +00005836 }
5837 // We use two distinct loops because EvaluateExpression may invalidate any
5838 // iterators into CurrentIterVals.
Sanjoy Das4493b402015-10-07 17:38:25 +00005839 for (const auto &I : PHIsToCompute) {
5840 PHINode *PHI = I.first;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005841 Constant *&NextPHI = NextIterVals[PHI];
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005842 if (!NextPHI) { // Not already computed.
Sanjoy Dasdd709962015-10-08 18:28:36 +00005843 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005844 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005845 }
Sanjoy Das4493b402015-10-07 17:38:25 +00005846 if (NextPHI != I.second)
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005847 StoppedEvolving = false;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005848 }
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005849
5850 // If all entries in CurrentIterVals == NextIterVals then we can stop
5851 // iterating, the loop can't continue to change.
5852 if (StoppedEvolving)
5853 return RetVal = CurrentIterVals[PN];
5854
Andrew Trick3a86ba72011-10-05 03:25:31 +00005855 CurrentIterVals.swap(NextIterVals);
Chris Lattnerdd730472004-04-17 22:58:41 +00005856 }
5857}
5858
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005859const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
Nick Lewyckya6674c72011-10-22 19:58:20 +00005860 Value *Cond,
5861 bool ExitWhen) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00005862 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Craig Topper9f008862014-04-15 04:59:12 +00005863 if (!PN) return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00005864
Dan Gohman866971e2010-06-19 14:17:24 +00005865 // If the loop is canonicalized, the PHI will have exactly two entries.
5866 // That's the only form we support here.
5867 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
5868
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005869 DenseMap<Instruction *, Constant *> CurrentIterVals;
5870 BasicBlock *Header = L->getHeader();
5871 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
5872
Sanjoy Dasdd709962015-10-08 18:28:36 +00005873 BasicBlock *Latch = L->getLoopLatch();
5874 assert(Latch && "Should follow from NumIncomingValues == 2!");
5875
5876 // NonLatch is the preheader, or something equivalent.
5877 BasicBlock *NonLatch = Latch == PN->getIncomingBlock(0)
5878 ? PN->getIncomingBlock(1)
5879 : PN->getIncomingBlock(0);
5880
5881 // Note: not all PHI nodes in the same block have to have their incoming
5882 // values in the same order, so we use the basic block to look up the incoming
5883 // value, not an index.
5884
Sanjoy Das4493b402015-10-07 17:38:25 +00005885 for (auto &I : *Header) {
5886 PHINode *PHI = dyn_cast<PHINode>(&I);
5887 if (!PHI)
5888 break;
5889 auto *StartCST =
Sanjoy Dasdd709962015-10-08 18:28:36 +00005890 dyn_cast<Constant>(PHI->getIncomingValueForBlock(NonLatch));
Craig Topper9f008862014-04-15 04:59:12 +00005891 if (!StartCST) continue;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005892 CurrentIterVals[PHI] = StartCST;
5893 }
5894 if (!CurrentIterVals.count(PN))
5895 return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00005896
5897 // Okay, we find a PHI node that defines the trip count of this loop. Execute
5898 // the loop symbolically to determine when the condition gets a value of
5899 // "ExitWhen".
Andrew Trick90c7a102011-11-16 00:52:40 +00005900 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005901 const DataLayout &DL = F.getParent()->getDataLayout();
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005902 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
Sanjoy Das4493b402015-10-07 17:38:25 +00005903 auto *CondVal = dyn_cast_or_null<ConstantInt>(
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005904 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
Chris Lattnerdd730472004-04-17 22:58:41 +00005905
Zhou Sheng75b871f2007-01-11 12:24:14 +00005906 // Couldn't symbolically evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005907 if (!CondVal) return getCouldNotCompute();
Zhou Sheng75b871f2007-01-11 12:24:14 +00005908
Reid Spencer983e3b32007-03-01 07:25:48 +00005909 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00005910 ++NumBruteForceTripCountsComputed;
Owen Anderson55f1c092009-08-13 21:58:54 +00005911 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner4021d1a2004-04-17 18:36:24 +00005912 }
Misha Brukman01808ca2005-04-21 21:13:18 +00005913
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005914 // Update all the PHI nodes for the next iteration.
5915 DenseMap<Instruction *, Constant *> NextIterVals;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00005916
5917 // Create a list of which PHIs we need to compute. We want to do this before
5918 // calling EvaluateExpression on them because that may invalidate iterators
5919 // into CurrentIterVals.
5920 SmallVector<PHINode *, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00005921 for (const auto &I : CurrentIterVals) {
5922 PHINode *PHI = dyn_cast<PHINode>(I.first);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005923 if (!PHI || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00005924 PHIsToCompute.push_back(PHI);
5925 }
Sanjoy Das4493b402015-10-07 17:38:25 +00005926 for (PHINode *PHI : PHIsToCompute) {
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005927 Constant *&NextPHI = NextIterVals[PHI];
5928 if (NextPHI) continue; // Already computed!
5929
Sanjoy Dasdd709962015-10-08 18:28:36 +00005930 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005931 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005932 }
5933 CurrentIterVals.swap(NextIterVals);
Chris Lattner4021d1a2004-04-17 18:36:24 +00005934 }
5935
5936 // Too many iterations were needed to evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005937 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00005938}
5939
Dan Gohman237d9e52009-09-03 15:00:26 +00005940/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohmanb81f47d2009-05-08 20:38:54 +00005941/// at the specified scope in the program. The L value specifies a loop
5942/// nest to evaluate the expression at, where null is the top-level or a
5943/// specified loop is immediately inside of the loop.
5944///
5945/// This method can be used to compute the exit value for a variable defined
5946/// in a loop by querying what the value will hold in the parent loop.
5947///
Dan Gohman8ca08852009-05-24 23:25:42 +00005948/// In the case that a relevant loop exit value cannot be computed, the
5949/// original value V is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00005950const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00005951 // Check to see if we've folded this expression at this loop before.
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00005952 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = ValuesAtScopes[V];
5953 for (unsigned u = 0; u < Values.size(); u++) {
5954 if (Values[u].first == L)
5955 return Values[u].second ? Values[u].second : V;
5956 }
Craig Topper9f008862014-04-15 04:59:12 +00005957 Values.push_back(std::make_pair(L, static_cast<const SCEV *>(nullptr)));
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00005958 // Otherwise compute it.
5959 const SCEV *C = computeSCEVAtScope(V, L);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00005960 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values2 = ValuesAtScopes[V];
5961 for (unsigned u = Values2.size(); u > 0; u--) {
5962 if (Values2[u - 1].first == L) {
5963 Values2[u - 1].second = C;
5964 break;
5965 }
5966 }
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00005967 return C;
5968}
5969
Nick Lewyckya6674c72011-10-22 19:58:20 +00005970/// This builds up a Constant using the ConstantExpr interface. That way, we
5971/// will return Constants for objects which aren't represented by a
5972/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
5973/// Returns NULL if the SCEV isn't representable as a Constant.
5974static Constant *BuildConstantFromSCEV(const SCEV *V) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00005975 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
Nick Lewyckya6674c72011-10-22 19:58:20 +00005976 case scCouldNotCompute:
5977 case scAddRecExpr:
5978 break;
5979 case scConstant:
5980 return cast<SCEVConstant>(V)->getValue();
5981 case scUnknown:
5982 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
5983 case scSignExtend: {
5984 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
5985 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
5986 return ConstantExpr::getSExt(CastOp, SS->getType());
5987 break;
5988 }
5989 case scZeroExtend: {
5990 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
5991 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
5992 return ConstantExpr::getZExt(CastOp, SZ->getType());
5993 break;
5994 }
5995 case scTruncate: {
5996 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
5997 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
5998 return ConstantExpr::getTrunc(CastOp, ST->getType());
5999 break;
6000 }
6001 case scAddExpr: {
6002 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6003 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006004 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6005 unsigned AS = PTy->getAddressSpace();
6006 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6007 C = ConstantExpr::getBitCast(C, DestPtrTy);
6008 }
Nick Lewyckya6674c72011-10-22 19:58:20 +00006009 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6010 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006011 if (!C2) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006012
6013 // First pointer!
6014 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006015 unsigned AS = C2->getType()->getPointerAddressSpace();
Nick Lewyckya6674c72011-10-22 19:58:20 +00006016 std::swap(C, C2);
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006017 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006018 // The offsets have been converted to bytes. We can add bytes to an
6019 // i8* by GEP with the byte count in the first index.
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006020 C = ConstantExpr::getBitCast(C, DestPtrTy);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006021 }
6022
6023 // Don't bother trying to sum two pointers. We probably can't
6024 // statically compute a load that results from it anyway.
6025 if (C2->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +00006026 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006027
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006028 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6029 if (PTy->getElementType()->isStructTy())
Nick Lewyckya6674c72011-10-22 19:58:20 +00006030 C2 = ConstantExpr::getIntegerCast(
6031 C2, Type::getInt32Ty(C->getContext()), true);
David Blaikie4a2e73b2015-04-02 18:55:32 +00006032 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006033 } else
6034 C = ConstantExpr::getAdd(C, C2);
6035 }
6036 return C;
6037 }
6038 break;
6039 }
6040 case scMulExpr: {
6041 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6042 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6043 // Don't bother with pointers at all.
Craig Topper9f008862014-04-15 04:59:12 +00006044 if (C->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006045 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6046 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006047 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006048 C = ConstantExpr::getMul(C, C2);
6049 }
6050 return C;
6051 }
6052 break;
6053 }
6054 case scUDivExpr: {
6055 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6056 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6057 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6058 if (LHS->getType() == RHS->getType())
6059 return ConstantExpr::getUDiv(LHS, RHS);
6060 break;
6061 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00006062 case scSMaxExpr:
6063 case scUMaxExpr:
6064 break; // TODO: smax, umax.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006065 }
Craig Topper9f008862014-04-15 04:59:12 +00006066 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006067}
6068
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006069const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006070 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00006071
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006072 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattnerdd730472004-04-17 22:58:41 +00006073 // exit value from the loop without using SCEVs.
Dan Gohmana30370b2009-05-04 22:02:23 +00006074 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006075 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006076 const Loop *LI = this->LI[I->getParent()];
Chris Lattnerdd730472004-04-17 22:58:41 +00006077 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
6078 if (PHINode *PN = dyn_cast<PHINode>(I))
6079 if (PN->getParent() == LI->getHeader()) {
6080 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman0bddac12009-02-24 18:55:53 +00006081 // to see if the loop that contains it has a known backedge-taken
6082 // count. If so, we may be able to force computation of the exit
6083 // value.
Dan Gohmanaf752342009-07-07 17:06:11 +00006084 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmana30370b2009-05-04 22:02:23 +00006085 if (const SCEVConstant *BTCC =
Dan Gohman0bddac12009-02-24 18:55:53 +00006086 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006087 // Okay, we know how many times the containing loop executes. If
6088 // this is a constant evolving PHI node, get the final value at
6089 // the specified iteration number.
6090 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman0bddac12009-02-24 18:55:53 +00006091 BTCC->getValue()->getValue(),
Chris Lattnerdd730472004-04-17 22:58:41 +00006092 LI);
Dan Gohman9d203c62009-06-29 21:31:18 +00006093 if (RV) return getSCEV(RV);
Chris Lattnerdd730472004-04-17 22:58:41 +00006094 }
6095 }
6096
Reid Spencere6328ca2006-12-04 21:33:23 +00006097 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattnerdd730472004-04-17 22:58:41 +00006098 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencere6328ca2006-12-04 21:33:23 +00006099 // the arguments into constants, and if so, try to constant propagate the
Chris Lattnerdd730472004-04-17 22:58:41 +00006100 // result. This is particularly useful for computing loop exit values.
6101 if (CanConstantFold(I)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006102 SmallVector<Constant *, 4> Operands;
6103 bool MadeImprovement = false;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00006104 for (Value *Op : I->operands()) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006105 if (Constant *C = dyn_cast<Constant>(Op)) {
6106 Operands.push_back(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006107 continue;
Chris Lattnerdd730472004-04-17 22:58:41 +00006108 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006109
6110 // If any of the operands is non-constant and if they are
6111 // non-integer and non-pointer, don't even try to analyze them
6112 // with scev techniques.
6113 if (!isSCEVable(Op->getType()))
6114 return V;
6115
6116 const SCEV *OrigV = getSCEV(Op);
6117 const SCEV *OpV = getSCEVAtScope(OrigV, L);
6118 MadeImprovement |= OrigV != OpV;
6119
Nick Lewyckya6674c72011-10-22 19:58:20 +00006120 Constant *C = BuildConstantFromSCEV(OpV);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006121 if (!C) return V;
6122 if (C->getType() != Op->getType())
6123 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
6124 Op->getType(),
6125 false),
6126 C, Op->getType());
6127 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00006128 }
Dan Gohmance973df2009-06-24 04:48:43 +00006129
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006130 // Check to see if getSCEVAtScope actually made an improvement.
6131 if (MadeImprovement) {
Craig Topper9f008862014-04-15 04:59:12 +00006132 Constant *C = nullptr;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006133 const DataLayout &DL = F.getParent()->getDataLayout();
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006134 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006135 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006136 Operands[1], DL, &TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006137 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
6138 if (!LI->isVolatile())
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006139 C = ConstantFoldLoadFromConstPtr(Operands[0], DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006140 } else
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006141 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands,
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006142 DL, &TLI);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006143 if (!C) return V;
Dan Gohman4aad7502010-02-24 19:31:47 +00006144 return getSCEV(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006145 }
Chris Lattnerdd730472004-04-17 22:58:41 +00006146 }
6147 }
6148
6149 // This is some other type of SCEVUnknown, just return it.
6150 return V;
6151 }
6152
Dan Gohmana30370b2009-05-04 22:02:23 +00006153 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006154 // Avoid performing the look-up in the common case where the specified
6155 // expression has no loop-variant portions.
6156 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006157 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006158 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006159 // Okay, at least one of these operands is loop variant but might be
6160 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmance973df2009-06-24 04:48:43 +00006161 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
6162 Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00006163 NewOps.push_back(OpAtScope);
6164
6165 for (++i; i != e; ++i) {
6166 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006167 NewOps.push_back(OpAtScope);
6168 }
6169 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006170 return getAddExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006171 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006172 return getMulExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006173 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006174 return getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006175 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006176 return getUMaxExpr(NewOps);
Torok Edwinfbcc6632009-07-14 16:55:14 +00006177 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00006178 }
6179 }
6180 // If we got here, all operands are loop invariant.
6181 return Comm;
6182 }
6183
Dan Gohmana30370b2009-05-04 22:02:23 +00006184 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006185 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
6186 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky52348302009-01-13 09:18:58 +00006187 if (LHS == Div->getLHS() && RHS == Div->getRHS())
6188 return Div; // must be loop invariant
Dan Gohmanc8e23622009-04-21 23:15:49 +00006189 return getUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00006190 }
6191
6192 // If this is a loop recurrence for a loop that does not contain L, then we
6193 // are dealing with the final value computed by the loop.
Dan Gohmana30370b2009-05-04 22:02:23 +00006194 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006195 // First, attempt to evaluate each operand.
6196 // Avoid performing the look-up in the common case where the specified
6197 // expression has no loop-variant portions.
6198 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
6199 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
6200 if (OpAtScope == AddRec->getOperand(i))
6201 continue;
6202
6203 // Okay, at least one of these operands is loop variant but might be
6204 // foldable. Build a new instance of the folded commutative expression.
6205 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
6206 AddRec->op_begin()+i);
6207 NewOps.push_back(OpAtScope);
6208 for (++i; i != e; ++i)
6209 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
6210
Andrew Trick759ba082011-04-27 01:21:25 +00006211 const SCEV *FoldedRec =
Andrew Trick8b55b732011-03-14 16:50:06 +00006212 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick759ba082011-04-27 01:21:25 +00006213 AddRec->getNoWrapFlags(SCEV::FlagNW));
6214 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick01eff822011-04-27 05:42:17 +00006215 // The addrec may be folded to a nonrecurrence, for example, if the
6216 // induction variable is multiplied by zero after constant folding. Go
6217 // ahead and return the folded value.
Andrew Trick759ba082011-04-27 01:21:25 +00006218 if (!AddRec)
6219 return FoldedRec;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006220 break;
6221 }
6222
6223 // If the scope is outside the addrec's loop, evaluate it by using the
6224 // loop exit value of the addrec.
6225 if (!AddRec->getLoop()->contains(L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006226 // To evaluate this recurrence, we need to know how many times the AddRec
6227 // loop iterates. Compute this now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006228 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006229 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman01808ca2005-04-21 21:13:18 +00006230
Eli Friedman61f67622008-08-04 23:49:06 +00006231 // Then, evaluate the AddRec.
Dan Gohmanc8e23622009-04-21 23:15:49 +00006232 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattnerd934c702004-04-02 20:23:17 +00006233 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006234
Dan Gohman8ca08852009-05-24 23:25:42 +00006235 return AddRec;
Chris Lattnerd934c702004-04-02 20:23:17 +00006236 }
6237
Dan Gohmana30370b2009-05-04 22:02:23 +00006238 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006239 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006240 if (Op == Cast->getOperand())
6241 return Cast; // must be loop invariant
6242 return getZeroExtendExpr(Op, Cast->getType());
6243 }
6244
Dan Gohmana30370b2009-05-04 22:02:23 +00006245 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006246 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006247 if (Op == Cast->getOperand())
6248 return Cast; // must be loop invariant
6249 return getSignExtendExpr(Op, Cast->getType());
6250 }
6251
Dan Gohmana30370b2009-05-04 22:02:23 +00006252 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006253 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006254 if (Op == Cast->getOperand())
6255 return Cast; // must be loop invariant
6256 return getTruncateExpr(Op, Cast->getType());
6257 }
6258
Torok Edwinfbcc6632009-07-14 16:55:14 +00006259 llvm_unreachable("Unknown SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00006260}
6261
Dan Gohmanb81f47d2009-05-08 20:38:54 +00006262/// getSCEVAtScope - This is a convenience function which does
6263/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanaf752342009-07-07 17:06:11 +00006264const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00006265 return getSCEVAtScope(getSCEV(V), L);
6266}
6267
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006268/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
6269/// following equation:
6270///
6271/// A * X = B (mod N)
6272///
6273/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
6274/// A and B isn't important.
6275///
6276/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00006277static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006278 ScalarEvolution &SE) {
6279 uint32_t BW = A.getBitWidth();
6280 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
6281 assert(A != 0 && "A must be non-zero.");
6282
6283 // 1. D = gcd(A, N)
6284 //
6285 // The gcd of A and N may have only one prime factor: 2. The number of
6286 // trailing zeros in A is its multiplicity
6287 uint32_t Mult2 = A.countTrailingZeros();
6288 // D = 2^Mult2
6289
6290 // 2. Check if B is divisible by D.
6291 //
6292 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
6293 // is not less than multiplicity of this prime factor for D.
6294 if (B.countTrailingZeros() < Mult2)
Dan Gohman31efa302009-04-18 17:58:19 +00006295 return SE.getCouldNotCompute();
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006296
6297 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
6298 // modulo (N / D).
6299 //
6300 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
6301 // bit width during computations.
6302 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
6303 APInt Mod(BW + 1, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00006304 Mod.setBit(BW - Mult2); // Mod = N / D
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006305 APInt I = AD.multiplicativeInverse(Mod);
6306
6307 // 4. Compute the minimum unsigned root of the equation:
6308 // I * (B / D) mod (N / D)
6309 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
6310
6311 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
6312 // bits.
6313 return SE.getConstant(Result.trunc(BW));
6314}
Chris Lattnerd934c702004-04-02 20:23:17 +00006315
6316/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
6317/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
6318/// might be the same) or two SCEVCouldNotCompute objects.
6319///
Dan Gohmanaf752342009-07-07 17:06:11 +00006320static std::pair<const SCEV *,const SCEV *>
Dan Gohmana37eaf22007-10-22 18:31:58 +00006321SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006322 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman48f82222009-05-04 22:30:44 +00006323 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
6324 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
6325 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00006326
Chris Lattnerd934c702004-04-02 20:23:17 +00006327 // We currently can only solve this if the coefficients are constants.
Reid Spencer983e3b32007-03-01 07:25:48 +00006328 if (!LC || !MC || !NC) {
Dan Gohman48f82222009-05-04 22:30:44 +00006329 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006330 return std::make_pair(CNC, CNC);
6331 }
6332
Reid Spencer983e3b32007-03-01 07:25:48 +00006333 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnercad61e82007-04-15 19:52:49 +00006334 const APInt &L = LC->getValue()->getValue();
6335 const APInt &M = MC->getValue()->getValue();
6336 const APInt &N = NC->getValue()->getValue();
Reid Spencer983e3b32007-03-01 07:25:48 +00006337 APInt Two(BitWidth, 2);
6338 APInt Four(BitWidth, 4);
Misha Brukman01808ca2005-04-21 21:13:18 +00006339
Dan Gohmance973df2009-06-24 04:48:43 +00006340 {
Reid Spencer983e3b32007-03-01 07:25:48 +00006341 using namespace APIntOps;
Zhou Sheng2852d992007-04-07 17:48:27 +00006342 const APInt& C = L;
Reid Spencer983e3b32007-03-01 07:25:48 +00006343 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
6344 // The B coefficient is M-N/2
6345 APInt B(M);
6346 B -= sdiv(N,Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00006347
Reid Spencer983e3b32007-03-01 07:25:48 +00006348 // The A coefficient is N/2
Zhou Sheng2852d992007-04-07 17:48:27 +00006349 APInt A(N.sdiv(Two));
Chris Lattnerd934c702004-04-02 20:23:17 +00006350
Reid Spencer983e3b32007-03-01 07:25:48 +00006351 // Compute the B^2-4ac term.
6352 APInt SqrtTerm(B);
6353 SqrtTerm *= B;
6354 SqrtTerm -= Four * (A * C);
Chris Lattnerd934c702004-04-02 20:23:17 +00006355
Nick Lewyckyfb780832012-08-01 09:14:36 +00006356 if (SqrtTerm.isNegative()) {
6357 // The loop is provably infinite.
6358 const SCEV *CNC = SE.getCouldNotCompute();
6359 return std::make_pair(CNC, CNC);
6360 }
6361
Reid Spencer983e3b32007-03-01 07:25:48 +00006362 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
6363 // integer value or else APInt::sqrt() will assert.
6364 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman01808ca2005-04-21 21:13:18 +00006365
Dan Gohmance973df2009-06-24 04:48:43 +00006366 // Compute the two solutions for the quadratic formula.
Reid Spencer983e3b32007-03-01 07:25:48 +00006367 // The divisions must be performed as signed divisions.
6368 APInt NegB(-B);
Nick Lewycky31555522011-10-03 07:10:45 +00006369 APInt TwoA(A << 1);
Nick Lewycky7b14e202008-11-03 02:43:49 +00006370 if (TwoA.isMinValue()) {
Dan Gohman48f82222009-05-04 22:30:44 +00006371 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky7b14e202008-11-03 02:43:49 +00006372 return std::make_pair(CNC, CNC);
6373 }
6374
Owen Anderson47db9412009-07-22 00:24:57 +00006375 LLVMContext &Context = SE.getContext();
Owen Andersonf1f17432009-07-06 22:37:39 +00006376
6377 ConstantInt *Solution1 =
Owen Andersonedb4a702009-07-24 23:12:02 +00006378 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Andersonf1f17432009-07-06 22:37:39 +00006379 ConstantInt *Solution2 =
Owen Andersonedb4a702009-07-24 23:12:02 +00006380 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman01808ca2005-04-21 21:13:18 +00006381
Dan Gohmance973df2009-06-24 04:48:43 +00006382 return std::make_pair(SE.getConstant(Solution1),
Dan Gohmana37eaf22007-10-22 18:31:58 +00006383 SE.getConstant(Solution2));
Nick Lewycky31555522011-10-03 07:10:45 +00006384 } // end APIntOps namespace
Chris Lattnerd934c702004-04-02 20:23:17 +00006385}
6386
6387/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman4c720c02009-06-06 14:37:11 +00006388/// value to zero will execute. If not computable, return CouldNotCompute.
Andrew Trick8b55b732011-03-14 16:50:06 +00006389///
6390/// This is only used for loops with a "x != y" exit test. The exit condition is
6391/// now expressed as a single expression, V = x-y. So the exit test is
6392/// effectively V != 0. We know and take advantage of the fact that this
6393/// expression only being used in a comparison by zero context.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006394ScalarEvolution::ExitLimit
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006395ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool ControlsExit) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006396 // If the value is a constant
Dan Gohmana30370b2009-05-04 22:02:23 +00006397 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006398 // If the value is already zero, the branch will execute zero times.
Reid Spencer2e54a152007-03-02 00:28:52 +00006399 if (C->getValue()->isZero()) return C;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006400 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00006401 }
6402
Dan Gohman48f82222009-05-04 22:30:44 +00006403 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00006404 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006405 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006406
Chris Lattnerdff679f2011-01-09 22:39:48 +00006407 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
6408 // the quadratic equation to solve it.
6409 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
6410 std::pair<const SCEV *,const SCEV *> Roots =
6411 SolveQuadraticEquation(AddRec, *this);
Dan Gohman48f82222009-05-04 22:30:44 +00006412 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
6413 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattnerdff679f2011-01-09 22:39:48 +00006414 if (R1 && R2) {
Chris Lattner09169212004-04-02 20:26:46 +00006415#if 0
David Greenedf1c4972009-12-23 22:18:14 +00006416 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmane20f8242009-04-21 00:47:46 +00006417 << " sol#2: " << *R2 << "\n";
Chris Lattner09169212004-04-02 20:26:46 +00006418#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00006419 // Pick the smallest positive root value.
Zhou Sheng75b871f2007-01-11 12:24:14 +00006420 if (ConstantInt *CB =
Chris Lattner28f140a2011-01-09 22:58:47 +00006421 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
6422 R1->getValue(),
6423 R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00006424 if (!CB->getZExtValue())
Chris Lattnerd934c702004-04-02 20:23:17 +00006425 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick2a3b7162011-03-09 17:23:39 +00006426
Chris Lattnerd934c702004-04-02 20:23:17 +00006427 // We can only use this value if the chrec ends up with an exact zero
6428 // value at this index. When solving for "X*X != 5", for example, we
6429 // should not accept a root of 2.
Dan Gohmanaf752342009-07-07 17:06:11 +00006430 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmanbe928e32008-06-18 16:23:07 +00006431 if (Val->isZero())
6432 return R1; // We found a quadratic root!
Chris Lattnerd934c702004-04-02 20:23:17 +00006433 }
6434 }
Chris Lattnerdff679f2011-01-09 22:39:48 +00006435 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006436 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006437
Chris Lattnerdff679f2011-01-09 22:39:48 +00006438 // Otherwise we can only handle this if it is affine.
6439 if (!AddRec->isAffine())
6440 return getCouldNotCompute();
6441
6442 // If this is an affine expression, the execution count of this branch is
6443 // the minimum unsigned root of the following equation:
6444 //
6445 // Start + Step*N = 0 (mod 2^BW)
6446 //
6447 // equivalent to:
6448 //
6449 // Step*N = -Start (mod 2^BW)
6450 //
6451 // where BW is the common bit width of Start and Step.
6452
6453 // Get the initial value for the loop.
6454 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
6455 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
6456
6457 // For now we handle only constant steps.
Andrew Trick8b55b732011-03-14 16:50:06 +00006458 //
6459 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
6460 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
6461 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
6462 // We have not yet seen any such cases.
Chris Lattnerdff679f2011-01-09 22:39:48 +00006463 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
Craig Topper9f008862014-04-15 04:59:12 +00006464 if (!StepC || StepC->getValue()->equalsInt(0))
Chris Lattnerdff679f2011-01-09 22:39:48 +00006465 return getCouldNotCompute();
6466
Andrew Trick8b55b732011-03-14 16:50:06 +00006467 // For positive steps (counting up until unsigned overflow):
6468 // N = -Start/Step (as unsigned)
6469 // For negative steps (counting down to zero):
6470 // N = Start/-Step
6471 // First compute the unsigned distance from zero in the direction of Step.
Andrew Trickf1781db2011-03-14 17:28:02 +00006472 bool CountDown = StepC->getValue()->getValue().isNegative();
6473 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick8b55b732011-03-14 16:50:06 +00006474
6475 // Handle unitary steps, which cannot wraparound.
Andrew Trickf1781db2011-03-14 17:28:02 +00006476 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
6477 // N = Distance (as unsigned)
Nick Lewycky31555522011-10-03 07:10:45 +00006478 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
6479 ConstantRange CR = getUnsignedRange(Start);
6480 const SCEV *MaxBECount;
6481 if (!CountDown && CR.getUnsignedMin().isMinValue())
6482 // When counting up, the worst starting value is 1, not 0.
6483 MaxBECount = CR.getUnsignedMax().isMinValue()
6484 ? getConstant(APInt::getMinValue(CR.getBitWidth()))
6485 : getConstant(APInt::getMaxValue(CR.getBitWidth()));
6486 else
6487 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
6488 : -CR.getUnsignedMin());
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006489 return ExitLimit(Distance, MaxBECount);
Nick Lewycky31555522011-10-03 07:10:45 +00006490 }
Andrew Trick2a3b7162011-03-09 17:23:39 +00006491
Mark Heffernanacbed5e2014-12-15 21:19:53 +00006492 // As a special case, handle the instance where Step is a positive power of
6493 // two. In this case, determining whether Step divides Distance evenly can be
6494 // done by counting and comparing the number of trailing zeros of Step and
6495 // Distance.
6496 if (!CountDown) {
6497 const APInt &StepV = StepC->getValue()->getValue();
6498 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It
6499 // also returns true if StepV is maximally negative (eg, INT_MIN), but that
6500 // case is not handled as this code is guarded by !CountDown.
6501 if (StepV.isPowerOf2() &&
Sanjoy Dasf3132d32015-09-10 05:27:38 +00006502 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) {
6503 // Here we've constrained the equation to be of the form
6504 //
6505 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0)
6506 //
6507 // where we're operating on a W bit wide integer domain and k is
6508 // non-negative. The smallest unsigned solution for X is the trip count.
6509 //
6510 // (0) is equivalent to:
6511 //
6512 // 2^(N + k) * Distance' - 2^N * X = L * 2^W
6513 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N
6514 // <=> 2^k * Distance' - X = L * 2^(W - N)
6515 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1)
6516 //
6517 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS
6518 // by 2^(W - N).
6519 //
6520 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2)
6521 //
6522 // E.g. say we're solving
6523 //
6524 // 2 * Val = 2 * X (in i8) ... (3)
6525 //
6526 // then from (2), we get X = Val URem i8 128 (k = 0 in this case).
6527 //
6528 // Note: It is tempting to solve (3) by setting X = Val, but Val is not
6529 // necessarily the smallest unsigned value of X that satisfies (3).
6530 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3)
6531 // is i8 1, not i8 -127
6532
6533 const auto *ModuloResult = getUDivExactExpr(Distance, Step);
6534
6535 // Since SCEV does not have a URem node, we construct one using a truncate
6536 // and a zero extend.
6537
6538 unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros();
6539 auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth);
6540 auto *WideTy = Distance->getType();
6541
6542 return getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy);
6543 }
Mark Heffernanacbed5e2014-12-15 21:19:53 +00006544 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00006545
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006546 // If the condition controls loop exit (the loop exits only if the expression
6547 // is true) and the addition is no-wrap we can use unsigned divide to
6548 // compute the backedge count. In this case, the step may not divide the
6549 // distance, but we don't care because if the condition is "missed" the loop
6550 // will have undefined behavior due to wrapping.
6551 if (ControlsExit && AddRec->getNoWrapFlags(SCEV::FlagNW)) {
6552 const SCEV *Exact =
6553 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
6554 return ExitLimit(Exact, Exact);
6555 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00006556
Chris Lattnerdff679f2011-01-09 22:39:48 +00006557 // Then, try to solve the above equation provided that Start is constant.
6558 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
6559 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
6560 -StartC->getValue()->getValue(),
6561 *this);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006562 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006563}
6564
6565/// HowFarToNonZero - Return the number of times a backedge checking the
6566/// specified value for nonzero will execute. If not computable, return
Dan Gohman4c720c02009-06-06 14:37:11 +00006567/// CouldNotCompute
Andrew Trick3ca3f982011-07-26 17:19:55 +00006568ScalarEvolution::ExitLimit
Dan Gohmanba820342010-02-24 17:31:30 +00006569ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006570 // Loops that look like: while (X == 0) are very strange indeed. We don't
6571 // handle them yet except for the trivial case. This could be expanded in the
6572 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00006573
Chris Lattnerd934c702004-04-02 20:23:17 +00006574 // If the value is a constant, check to see if it is known to be non-zero
6575 // already. If so, the backedge will execute zero times.
Dan Gohmana30370b2009-05-04 22:02:23 +00006576 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky5a3db142008-02-21 09:14:53 +00006577 if (!C->getValue()->isNullValue())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00006578 return getZero(C->getType());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006579 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00006580 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006581
Chris Lattnerd934c702004-04-02 20:23:17 +00006582 // We could implement others, but I really doubt anyone writes loops like
6583 // this, and if they did, they would already be constant folded.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006584 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006585}
6586
Dan Gohmanf9081a22008-09-15 22:18:04 +00006587/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
6588/// (which may not be an immediate predecessor) which has exactly one
6589/// successor from which BB is reachable, or null if no such block is
6590/// found.
6591///
Dan Gohman4e3c1132010-04-15 16:19:08 +00006592std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanc8e23622009-04-21 23:15:49 +00006593ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohmanfa066ef2009-04-30 20:48:53 +00006594 // If the block has a unique predecessor, then there is no path from the
6595 // predecessor to the block that does not go through the direct edge
6596 // from the predecessor to the block.
Dan Gohmanf9081a22008-09-15 22:18:04 +00006597 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman4e3c1132010-04-15 16:19:08 +00006598 return std::make_pair(Pred, BB);
Dan Gohmanf9081a22008-09-15 22:18:04 +00006599
6600 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman8c77f1a2009-05-18 15:36:09 +00006601 // If the header has a unique predecessor outside the loop, it must be
6602 // a block that has exactly one successor that can reach the loop.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006603 if (Loop *L = LI.getLoopFor(BB))
Dan Gohman75c6b0b2010-06-22 23:43:28 +00006604 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohmanf9081a22008-09-15 22:18:04 +00006605
Dan Gohman4e3c1132010-04-15 16:19:08 +00006606 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanf9081a22008-09-15 22:18:04 +00006607}
6608
Dan Gohman450f4e02009-06-20 00:35:32 +00006609/// HasSameValue - SCEV structural equivalence is usually sufficient for
6610/// testing whether two expressions are equal, however for the purposes of
6611/// looking for a condition guarding a loop, it can be useful to be a little
6612/// more general, since a front-end may have replicated the controlling
6613/// expression.
6614///
Dan Gohmanaf752342009-07-07 17:06:11 +00006615static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman450f4e02009-06-20 00:35:32 +00006616 // Quick check to see if they are the same SCEV.
6617 if (A == B) return true;
6618
Sanjoy Dasf1090b62015-09-27 21:09:48 +00006619 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
6620 // Not all instructions that are "identical" compute the same value. For
6621 // instance, two distinct alloca instructions allocating the same type are
6622 // identical and do not read memory; but compute distinct values.
6623 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
6624 };
6625
Dan Gohman450f4e02009-06-20 00:35:32 +00006626 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
6627 // two different instructions with the same value. Check for this case.
6628 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
6629 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
6630 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
6631 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Sanjoy Dasf1090b62015-09-27 21:09:48 +00006632 if (ComputesEqualValues(AI, BI))
Dan Gohman450f4e02009-06-20 00:35:32 +00006633 return true;
6634
6635 // Otherwise assume they may have a different value.
6636 return false;
6637}
6638
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006639/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006640/// predicate Pred. Return true iff any changes were made.
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006641///
6642bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006643 const SCEV *&LHS, const SCEV *&RHS,
6644 unsigned Depth) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006645 bool Changed = false;
6646
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006647 // If we hit the max recursion limit bail out.
6648 if (Depth >= 3)
6649 return false;
6650
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006651 // Canonicalize a constant to the right side.
6652 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
6653 // Check for both operands constant.
6654 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
6655 if (ConstantExpr::getICmp(Pred,
6656 LHSC->getValue(),
6657 RHSC->getValue())->isNullValue())
6658 goto trivially_false;
6659 else
6660 goto trivially_true;
6661 }
6662 // Otherwise swap the operands to put the constant on the right.
6663 std::swap(LHS, RHS);
6664 Pred = ICmpInst::getSwappedPredicate(Pred);
6665 Changed = true;
6666 }
6667
6668 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohmandf564ca2010-05-03 17:00:11 +00006669 // addrec's loop, put the addrec on the left. Also make a dominance check,
6670 // as both operands could be addrecs loop-invariant in each other's loop.
6671 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
6672 const Loop *L = AR->getLoop();
Dan Gohman20d9ce22010-11-17 21:41:58 +00006673 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006674 std::swap(LHS, RHS);
6675 Pred = ICmpInst::getSwappedPredicate(Pred);
6676 Changed = true;
6677 }
Dan Gohmandf564ca2010-05-03 17:00:11 +00006678 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006679
6680 // If there's a constant operand, canonicalize comparisons with boundary
6681 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
6682 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
6683 const APInt &RA = RC->getValue()->getValue();
6684 switch (Pred) {
6685 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6686 case ICmpInst::ICMP_EQ:
6687 case ICmpInst::ICMP_NE:
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006688 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
6689 if (!RA)
6690 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
6691 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
Benjamin Kramer406a2db2012-05-30 18:42:43 +00006692 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
6693 ME->getOperand(0)->isAllOnesValue()) {
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006694 RHS = AE->getOperand(1);
6695 LHS = ME->getOperand(1);
6696 Changed = true;
6697 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006698 break;
6699 case ICmpInst::ICMP_UGE:
6700 if ((RA - 1).isMinValue()) {
6701 Pred = ICmpInst::ICMP_NE;
6702 RHS = getConstant(RA - 1);
6703 Changed = true;
6704 break;
6705 }
6706 if (RA.isMaxValue()) {
6707 Pred = ICmpInst::ICMP_EQ;
6708 Changed = true;
6709 break;
6710 }
6711 if (RA.isMinValue()) goto trivially_true;
6712
6713 Pred = ICmpInst::ICMP_UGT;
6714 RHS = getConstant(RA - 1);
6715 Changed = true;
6716 break;
6717 case ICmpInst::ICMP_ULE:
6718 if ((RA + 1).isMaxValue()) {
6719 Pred = ICmpInst::ICMP_NE;
6720 RHS = getConstant(RA + 1);
6721 Changed = true;
6722 break;
6723 }
6724 if (RA.isMinValue()) {
6725 Pred = ICmpInst::ICMP_EQ;
6726 Changed = true;
6727 break;
6728 }
6729 if (RA.isMaxValue()) goto trivially_true;
6730
6731 Pred = ICmpInst::ICMP_ULT;
6732 RHS = getConstant(RA + 1);
6733 Changed = true;
6734 break;
6735 case ICmpInst::ICMP_SGE:
6736 if ((RA - 1).isMinSignedValue()) {
6737 Pred = ICmpInst::ICMP_NE;
6738 RHS = getConstant(RA - 1);
6739 Changed = true;
6740 break;
6741 }
6742 if (RA.isMaxSignedValue()) {
6743 Pred = ICmpInst::ICMP_EQ;
6744 Changed = true;
6745 break;
6746 }
6747 if (RA.isMinSignedValue()) goto trivially_true;
6748
6749 Pred = ICmpInst::ICMP_SGT;
6750 RHS = getConstant(RA - 1);
6751 Changed = true;
6752 break;
6753 case ICmpInst::ICMP_SLE:
6754 if ((RA + 1).isMaxSignedValue()) {
6755 Pred = ICmpInst::ICMP_NE;
6756 RHS = getConstant(RA + 1);
6757 Changed = true;
6758 break;
6759 }
6760 if (RA.isMinSignedValue()) {
6761 Pred = ICmpInst::ICMP_EQ;
6762 Changed = true;
6763 break;
6764 }
6765 if (RA.isMaxSignedValue()) goto trivially_true;
6766
6767 Pred = ICmpInst::ICMP_SLT;
6768 RHS = getConstant(RA + 1);
6769 Changed = true;
6770 break;
6771 case ICmpInst::ICMP_UGT:
6772 if (RA.isMinValue()) {
6773 Pred = ICmpInst::ICMP_NE;
6774 Changed = true;
6775 break;
6776 }
6777 if ((RA + 1).isMaxValue()) {
6778 Pred = ICmpInst::ICMP_EQ;
6779 RHS = getConstant(RA + 1);
6780 Changed = true;
6781 break;
6782 }
6783 if (RA.isMaxValue()) goto trivially_false;
6784 break;
6785 case ICmpInst::ICMP_ULT:
6786 if (RA.isMaxValue()) {
6787 Pred = ICmpInst::ICMP_NE;
6788 Changed = true;
6789 break;
6790 }
6791 if ((RA - 1).isMinValue()) {
6792 Pred = ICmpInst::ICMP_EQ;
6793 RHS = getConstant(RA - 1);
6794 Changed = true;
6795 break;
6796 }
6797 if (RA.isMinValue()) goto trivially_false;
6798 break;
6799 case ICmpInst::ICMP_SGT:
6800 if (RA.isMinSignedValue()) {
6801 Pred = ICmpInst::ICMP_NE;
6802 Changed = true;
6803 break;
6804 }
6805 if ((RA + 1).isMaxSignedValue()) {
6806 Pred = ICmpInst::ICMP_EQ;
6807 RHS = getConstant(RA + 1);
6808 Changed = true;
6809 break;
6810 }
6811 if (RA.isMaxSignedValue()) goto trivially_false;
6812 break;
6813 case ICmpInst::ICMP_SLT:
6814 if (RA.isMaxSignedValue()) {
6815 Pred = ICmpInst::ICMP_NE;
6816 Changed = true;
6817 break;
6818 }
6819 if ((RA - 1).isMinSignedValue()) {
6820 Pred = ICmpInst::ICMP_EQ;
6821 RHS = getConstant(RA - 1);
6822 Changed = true;
6823 break;
6824 }
6825 if (RA.isMinSignedValue()) goto trivially_false;
6826 break;
6827 }
6828 }
6829
6830 // Check for obvious equality.
6831 if (HasSameValue(LHS, RHS)) {
6832 if (ICmpInst::isTrueWhenEqual(Pred))
6833 goto trivially_true;
6834 if (ICmpInst::isFalseWhenEqual(Pred))
6835 goto trivially_false;
6836 }
6837
Dan Gohman81585c12010-05-03 16:35:17 +00006838 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
6839 // adding or subtracting 1 from one of the operands.
6840 switch (Pred) {
6841 case ICmpInst::ICMP_SLE:
6842 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
6843 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006844 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00006845 Pred = ICmpInst::ICMP_SLT;
6846 Changed = true;
6847 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006848 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006849 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00006850 Pred = ICmpInst::ICMP_SLT;
6851 Changed = true;
6852 }
6853 break;
6854 case ICmpInst::ICMP_SGE:
6855 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006856 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006857 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00006858 Pred = ICmpInst::ICMP_SGT;
6859 Changed = true;
6860 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
6861 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006862 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00006863 Pred = ICmpInst::ICMP_SGT;
6864 Changed = true;
6865 }
6866 break;
6867 case ICmpInst::ICMP_ULE:
6868 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006869 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006870 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00006871 Pred = ICmpInst::ICMP_ULT;
6872 Changed = true;
6873 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006874 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006875 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00006876 Pred = ICmpInst::ICMP_ULT;
6877 Changed = true;
6878 }
6879 break;
6880 case ICmpInst::ICMP_UGE:
6881 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006882 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006883 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00006884 Pred = ICmpInst::ICMP_UGT;
6885 Changed = true;
6886 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006887 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006888 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00006889 Pred = ICmpInst::ICMP_UGT;
6890 Changed = true;
6891 }
6892 break;
6893 default:
6894 break;
6895 }
6896
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006897 // TODO: More simplifications are possible here.
6898
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006899 // Recursively simplify until we either hit a recursion limit or nothing
6900 // changes.
6901 if (Changed)
6902 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
6903
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006904 return Changed;
6905
6906trivially_true:
6907 // Return 0 == 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00006908 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006909 Pred = ICmpInst::ICMP_EQ;
6910 return true;
6911
6912trivially_false:
6913 // Return 0 != 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00006914 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006915 Pred = ICmpInst::ICMP_NE;
6916 return true;
6917}
6918
Dan Gohmane65c9172009-07-13 21:35:55 +00006919bool ScalarEvolution::isKnownNegative(const SCEV *S) {
6920 return getSignedRange(S).getSignedMax().isNegative();
6921}
6922
6923bool ScalarEvolution::isKnownPositive(const SCEV *S) {
6924 return getSignedRange(S).getSignedMin().isStrictlyPositive();
6925}
6926
6927bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
6928 return !getSignedRange(S).getSignedMin().isNegative();
6929}
6930
6931bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
6932 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
6933}
6934
6935bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
6936 return isKnownNegative(S) || isKnownPositive(S);
6937}
6938
6939bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
6940 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman36cce7e2010-04-24 01:38:36 +00006941 // Canonicalize the inputs first.
6942 (void)SimplifyICmpOperands(Pred, LHS, RHS);
6943
Dan Gohman07591692010-04-11 22:16:48 +00006944 // If LHS or RHS is an addrec, check to see if the condition is true in
6945 // every iteration of the loop.
Justin Bognercbb84382014-05-23 00:06:56 +00006946 // If LHS and RHS are both addrec, both conditions must be true in
6947 // every iteration of the loop.
6948 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
6949 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
6950 bool LeftGuarded = false;
6951 bool RightGuarded = false;
6952 if (LAR) {
6953 const Loop *L = LAR->getLoop();
6954 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
6955 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
6956 if (!RAR) return true;
6957 LeftGuarded = true;
6958 }
6959 }
6960 if (RAR) {
6961 const Loop *L = RAR->getLoop();
6962 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
6963 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
6964 if (!LAR) return true;
6965 RightGuarded = true;
6966 }
6967 }
6968 if (LeftGuarded && RightGuarded)
6969 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00006970
Sanjoy Das7d910f22015-10-02 18:50:30 +00006971 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
6972 return true;
6973
Dan Gohman07591692010-04-11 22:16:48 +00006974 // Otherwise see what can be done with known constant ranges.
6975 return isKnownPredicateWithRanges(Pred, LHS, RHS);
6976}
6977
Sanjoy Das5dab2052015-07-27 21:42:49 +00006978bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
6979 ICmpInst::Predicate Pred,
6980 bool &Increasing) {
6981 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
6982
6983#ifndef NDEBUG
6984 // Verify an invariant: inverting the predicate should turn a monotonically
6985 // increasing change to a monotonically decreasing one, and vice versa.
6986 bool IncreasingSwapped;
6987 bool ResultSwapped = isMonotonicPredicateImpl(
6988 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
6989
6990 assert(Result == ResultSwapped && "should be able to analyze both!");
6991 if (ResultSwapped)
6992 assert(Increasing == !IncreasingSwapped &&
6993 "monotonicity should flip as we flip the predicate");
6994#endif
6995
6996 return Result;
6997}
6998
6999bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7000 ICmpInst::Predicate Pred,
7001 bool &Increasing) {
Sanjoy Das5dab2052015-07-27 21:42:49 +00007002
7003 // A zero step value for LHS means the induction variable is essentially a
7004 // loop invariant value. We don't really depend on the predicate actually
7005 // flipping from false to true (for increasing predicates, and the other way
7006 // around for decreasing predicates), all we care about is that *if* the
7007 // predicate changes then it only changes from false to true.
7008 //
7009 // A zero step value in itself is not very useful, but there may be places
7010 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7011 // as general as possible.
7012
Sanjoy Das366acc12015-08-06 20:43:41 +00007013 switch (Pred) {
7014 default:
7015 return false; // Conservative answer
7016
7017 case ICmpInst::ICMP_UGT:
7018 case ICmpInst::ICMP_UGE:
7019 case ICmpInst::ICMP_ULT:
7020 case ICmpInst::ICMP_ULE:
7021 if (!LHS->getNoWrapFlags(SCEV::FlagNUW))
7022 return false;
7023
7024 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007025 return true;
Sanjoy Das366acc12015-08-06 20:43:41 +00007026
7027 case ICmpInst::ICMP_SGT:
7028 case ICmpInst::ICMP_SGE:
7029 case ICmpInst::ICMP_SLT:
7030 case ICmpInst::ICMP_SLE: {
7031 if (!LHS->getNoWrapFlags(SCEV::FlagNSW))
7032 return false;
7033
7034 const SCEV *Step = LHS->getStepRecurrence(*this);
7035
7036 if (isKnownNonNegative(Step)) {
7037 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7038 return true;
7039 }
7040
7041 if (isKnownNonPositive(Step)) {
7042 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7043 return true;
7044 }
7045
7046 return false;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007047 }
7048
Sanjoy Das5dab2052015-07-27 21:42:49 +00007049 }
7050
Sanjoy Das366acc12015-08-06 20:43:41 +00007051 llvm_unreachable("switch has default clause!");
Sanjoy Das5dab2052015-07-27 21:42:49 +00007052}
7053
7054bool ScalarEvolution::isLoopInvariantPredicate(
7055 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7056 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7057 const SCEV *&InvariantRHS) {
7058
7059 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7060 if (!isLoopInvariant(RHS, L)) {
7061 if (!isLoopInvariant(LHS, L))
7062 return false;
7063
7064 std::swap(LHS, RHS);
7065 Pred = ICmpInst::getSwappedPredicate(Pred);
7066 }
7067
7068 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7069 if (!ArLHS || ArLHS->getLoop() != L)
7070 return false;
7071
7072 bool Increasing;
7073 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7074 return false;
7075
7076 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7077 // true as the loop iterates, and the backedge is control dependent on
7078 // "ArLHS `Pred` RHS" == true then we can reason as follows:
7079 //
7080 // * if the predicate was false in the first iteration then the predicate
7081 // is never evaluated again, since the loop exits without taking the
7082 // backedge.
7083 // * if the predicate was true in the first iteration then it will
7084 // continue to be true for all future iterations since it is
7085 // monotonically increasing.
7086 //
7087 // For both the above possibilities, we can replace the loop varying
7088 // predicate with its value on the first iteration of the loop (which is
7089 // loop invariant).
7090 //
7091 // A similar reasoning applies for a monotonically decreasing predicate, by
7092 // replacing true with false and false with true in the above two bullets.
7093
7094 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7095
7096 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7097 return false;
7098
7099 InvariantPred = Pred;
7100 InvariantLHS = ArLHS->getStart();
7101 InvariantRHS = RHS;
7102 return true;
7103}
7104
Dan Gohman07591692010-04-11 22:16:48 +00007105bool
7106ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
7107 const SCEV *LHS, const SCEV *RHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00007108 if (HasSameValue(LHS, RHS))
7109 return ICmpInst::isTrueWhenEqual(Pred);
7110
Dan Gohman07591692010-04-11 22:16:48 +00007111 // This code is split out from isKnownPredicate because it is called from
7112 // within isLoopEntryGuardedByCond.
Dan Gohmane65c9172009-07-13 21:35:55 +00007113 switch (Pred) {
7114 default:
Dan Gohman8c129d72009-07-16 17:34:36 +00007115 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohmane65c9172009-07-13 21:35:55 +00007116 case ICmpInst::ICMP_SGT:
Dan Gohmane65c9172009-07-13 21:35:55 +00007117 std::swap(LHS, RHS);
7118 case ICmpInst::ICMP_SLT: {
7119 ConstantRange LHSRange = getSignedRange(LHS);
7120 ConstantRange RHSRange = getSignedRange(RHS);
7121 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
7122 return true;
7123 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
7124 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00007125 break;
7126 }
7127 case ICmpInst::ICMP_SGE:
Dan Gohmane65c9172009-07-13 21:35:55 +00007128 std::swap(LHS, RHS);
7129 case ICmpInst::ICMP_SLE: {
7130 ConstantRange LHSRange = getSignedRange(LHS);
7131 ConstantRange RHSRange = getSignedRange(RHS);
7132 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
7133 return true;
7134 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
7135 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00007136 break;
7137 }
7138 case ICmpInst::ICMP_UGT:
Dan Gohmane65c9172009-07-13 21:35:55 +00007139 std::swap(LHS, RHS);
7140 case ICmpInst::ICMP_ULT: {
7141 ConstantRange LHSRange = getUnsignedRange(LHS);
7142 ConstantRange RHSRange = getUnsignedRange(RHS);
7143 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
7144 return true;
7145 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
7146 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00007147 break;
7148 }
7149 case ICmpInst::ICMP_UGE:
Dan Gohmane65c9172009-07-13 21:35:55 +00007150 std::swap(LHS, RHS);
7151 case ICmpInst::ICMP_ULE: {
7152 ConstantRange LHSRange = getUnsignedRange(LHS);
7153 ConstantRange RHSRange = getUnsignedRange(RHS);
7154 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
7155 return true;
7156 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
7157 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00007158 break;
7159 }
7160 case ICmpInst::ICMP_NE: {
7161 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
7162 return true;
7163 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
7164 return true;
7165
7166 const SCEV *Diff = getMinusSCEV(LHS, RHS);
7167 if (isKnownNonZero(Diff))
7168 return true;
7169 break;
7170 }
7171 case ICmpInst::ICMP_EQ:
Dan Gohman34392622009-07-20 23:54:43 +00007172 // The check at the top of the function catches the case where
7173 // the values are known to be equal.
Dan Gohmane65c9172009-07-13 21:35:55 +00007174 break;
7175 }
7176 return false;
7177}
7178
Sanjoy Das11231482015-10-22 19:57:29 +00007179bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7180 const SCEV *LHS,
7181 const SCEV *RHS) {
7182
7183 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7184 // Return Y via OutY.
7185 auto MatchBinaryAddToConst =
7186 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7187 SCEV::NoWrapFlags ExpectedFlags) {
7188 const SCEV *NonConstOp, *ConstOp;
7189 SCEV::NoWrapFlags FlagsPresent;
7190
7191 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7192 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7193 return false;
7194
7195 OutY = cast<SCEVConstant>(ConstOp)->getValue()->getValue();
7196 return (FlagsPresent & ExpectedFlags) != 0;
7197 };
7198
7199 APInt C;
7200
7201 switch (Pred) {
7202 default:
7203 break;
7204
7205 case ICmpInst::ICMP_SGE:
7206 std::swap(LHS, RHS);
7207 case ICmpInst::ICMP_SLE:
7208 // X s<= (X + C)<nsw> if C >= 0
7209 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7210 return true;
7211
7212 // (X + C)<nsw> s<= X if C <= 0
7213 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7214 !C.isStrictlyPositive())
7215 return true;
7216
7217 case ICmpInst::ICMP_SGT:
7218 std::swap(LHS, RHS);
7219 case ICmpInst::ICMP_SLT:
7220 // X s< (X + C)<nsw> if C > 0
7221 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7222 C.isStrictlyPositive())
7223 return true;
7224
7225 // (X + C)<nsw> s< X if C < 0
7226 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7227 return true;
7228 }
7229
7230 return false;
7231}
7232
Sanjoy Das7d910f22015-10-02 18:50:30 +00007233bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7234 const SCEV *LHS,
7235 const SCEV *RHS) {
Sanjoy Das10dffcb2015-10-08 03:46:00 +00007236 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
Sanjoy Das7d910f22015-10-02 18:50:30 +00007237 return false;
7238
7239 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7240 // the stack can result in exponential time complexity.
7241 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7242
7243 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7244 //
7245 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7246 // isKnownPredicate. isKnownPredicate is more powerful, but also more
7247 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7248 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
7249 // use isKnownPredicate later if needed.
Sanjoy Das10dffcb2015-10-08 03:46:00 +00007250 if (isKnownNonNegative(RHS) &&
Sanjoy Das7d910f22015-10-02 18:50:30 +00007251 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7252 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS))
7253 return true;
7254
7255 return false;
7256}
7257
Dan Gohmane65c9172009-07-13 21:35:55 +00007258/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7259/// protected by a conditional between LHS and RHS. This is used to
7260/// to eliminate casts.
7261bool
7262ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7263 ICmpInst::Predicate Pred,
7264 const SCEV *LHS, const SCEV *RHS) {
7265 // Interpret a null as meaning no loop, where there is obviously no guard
7266 // (interprocedural conditions notwithstanding).
7267 if (!L) return true;
7268
Sanjoy Das1f05c512014-10-10 21:22:34 +00007269 if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true;
7270
Dan Gohmane65c9172009-07-13 21:35:55 +00007271 BasicBlock *Latch = L->getLoopLatch();
7272 if (!Latch)
7273 return false;
7274
7275 BranchInst *LoopContinuePredicate =
7276 dyn_cast<BranchInst>(Latch->getTerminator());
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007277 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7278 isImpliedCond(Pred, LHS, RHS,
7279 LoopContinuePredicate->getCondition(),
7280 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7281 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007282
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007283 // We don't want more than one activation of the following loops on the stack
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007284 // -- that can lead to O(n!) time complexity.
7285 if (WalkingBEDominatingConds)
7286 return false;
7287
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +00007288 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007289
Sanjoy Dasb174f9a2015-09-25 23:53:50 +00007290 // See if we can exploit a trip count to prove the predicate.
7291 const auto &BETakenInfo = getBackedgeTakenInfo(L);
7292 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
7293 if (LatchBECount != getCouldNotCompute()) {
7294 // We know that Latch branches back to the loop header exactly
7295 // LatchBECount times. This means the backdege condition at Latch is
7296 // equivalent to "{0,+,1} u< LatchBECount".
7297 Type *Ty = LatchBECount->getType();
7298 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
7299 const SCEV *LoopCounter =
7300 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
7301 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
7302 LatchBECount))
7303 return true;
7304 }
7305
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007306 // Check conditions due to any @llvm.assume intrinsics.
7307 for (auto &AssumeVH : AC.assumptions()) {
7308 if (!AssumeVH)
7309 continue;
7310 auto *CI = cast<CallInst>(AssumeVH);
7311 if (!DT.dominates(CI, Latch->getTerminator()))
7312 continue;
7313
7314 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7315 return true;
7316 }
7317
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007318 // If the loop is not reachable from the entry block, we risk running into an
7319 // infinite loop as we walk up into the dom tree. These loops do not matter
7320 // anyway, so we just return a conservative answer when we see them.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007321 if (!DT.isReachableFromEntry(L->getHeader()))
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007322 return false;
7323
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007324 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
7325 DTN != HeaderDTN; DTN = DTN->getIDom()) {
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007326
7327 assert(DTN && "should reach the loop header before reaching the root!");
7328
7329 BasicBlock *BB = DTN->getBlock();
7330 BasicBlock *PBB = BB->getSinglePredecessor();
7331 if (!PBB)
7332 continue;
7333
7334 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
7335 if (!ContinuePredicate || !ContinuePredicate->isConditional())
7336 continue;
7337
7338 Value *Condition = ContinuePredicate->getCondition();
7339
7340 // If we have an edge `E` within the loop body that dominates the only
7341 // latch, the condition guarding `E` also guards the backedge. This
7342 // reasoning works only for loops with a single latch.
7343
7344 BasicBlockEdge DominatingEdge(PBB, BB);
7345 if (DominatingEdge.isSingleEdge()) {
7346 // We're constructively (and conservatively) enumerating edges within the
7347 // loop body that dominate the latch. The dominator tree better agree
7348 // with us on this:
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007349 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007350
7351 if (isImpliedCond(Pred, LHS, RHS, Condition,
7352 BB != ContinuePredicate->getSuccessor(0)))
7353 return true;
7354 }
7355 }
7356
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007357 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00007358}
7359
Dan Gohmanb50349a2010-04-11 19:27:13 +00007360/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohmane65c9172009-07-13 21:35:55 +00007361/// by a conditional between LHS and RHS. This is used to help avoid max
7362/// expressions in loop trip counts, and to eliminate casts.
7363bool
Dan Gohmanb50349a2010-04-11 19:27:13 +00007364ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
7365 ICmpInst::Predicate Pred,
7366 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman9cf09f82009-05-18 16:03:58 +00007367 // Interpret a null as meaning no loop, where there is obviously no guard
7368 // (interprocedural conditions notwithstanding).
7369 if (!L) return false;
7370
Sanjoy Das1f05c512014-10-10 21:22:34 +00007371 if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true;
7372
Dan Gohman8c77f1a2009-05-18 15:36:09 +00007373 // Starting at the loop predecessor, climb up the predecessor chain, as long
7374 // as there are predecessors that can be found that have unique successors
Dan Gohmanf9081a22008-09-15 22:18:04 +00007375 // leading to the original header.
Dan Gohman4e3c1132010-04-15 16:19:08 +00007376 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman75c6b0b2010-06-22 23:43:28 +00007377 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman4e3c1132010-04-15 16:19:08 +00007378 Pair.first;
7379 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman2a62fd92008-08-12 20:17:31 +00007380
7381 BranchInst *LoopEntryPredicate =
Dan Gohman4e3c1132010-04-15 16:19:08 +00007382 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman2a62fd92008-08-12 20:17:31 +00007383 if (!LoopEntryPredicate ||
7384 LoopEntryPredicate->isUnconditional())
7385 continue;
7386
Dan Gohmane18c2d62010-08-10 23:46:30 +00007387 if (isImpliedCond(Pred, LHS, RHS,
7388 LoopEntryPredicate->getCondition(),
Dan Gohman4e3c1132010-04-15 16:19:08 +00007389 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman2a62fd92008-08-12 20:17:31 +00007390 return true;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00007391 }
7392
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007393 // Check conditions due to any @llvm.assume intrinsics.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007394 for (auto &AssumeVH : AC.assumptions()) {
Chandler Carruth66b31302015-01-04 12:03:27 +00007395 if (!AssumeVH)
7396 continue;
7397 auto *CI = cast<CallInst>(AssumeVH);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007398 if (!DT.dominates(CI, L->getHeader()))
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007399 continue;
7400
7401 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7402 return true;
7403 }
7404
Dan Gohman2a62fd92008-08-12 20:17:31 +00007405 return false;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00007406}
7407
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00007408/// RAII wrapper to prevent recursive application of isImpliedCond.
7409/// ScalarEvolution's PendingLoopPredicates set must be empty unless we are
7410/// currently evaluating isImpliedCond.
7411struct MarkPendingLoopPredicate {
7412 Value *Cond;
7413 DenseSet<Value*> &LoopPreds;
7414 bool Pending;
7415
7416 MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP)
7417 : Cond(C), LoopPreds(LP) {
7418 Pending = !LoopPreds.insert(Cond).second;
7419 }
7420 ~MarkPendingLoopPredicate() {
7421 if (!Pending)
7422 LoopPreds.erase(Cond);
7423 }
7424};
7425
Dan Gohman430f0cc2009-07-21 23:03:19 +00007426/// isImpliedCond - Test whether the condition described by Pred, LHS,
7427/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmane18c2d62010-08-10 23:46:30 +00007428bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00007429 const SCEV *LHS, const SCEV *RHS,
Dan Gohmane18c2d62010-08-10 23:46:30 +00007430 Value *FoundCondValue,
Dan Gohman430f0cc2009-07-21 23:03:19 +00007431 bool Inverse) {
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00007432 MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates);
7433 if (Mark.Pending)
7434 return false;
7435
Dan Gohman8b0a4192010-03-01 17:49:51 +00007436 // Recursively handle And and Or conditions.
Dan Gohmane18c2d62010-08-10 23:46:30 +00007437 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00007438 if (BO->getOpcode() == Instruction::And) {
7439 if (!Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00007440 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
7441 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00007442 } else if (BO->getOpcode() == Instruction::Or) {
7443 if (Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00007444 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
7445 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00007446 }
7447 }
7448
Dan Gohmane18c2d62010-08-10 23:46:30 +00007449 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00007450 if (!ICI) return false;
7451
Andrew Trickfa594032012-11-29 18:35:13 +00007452 // Now that we found a conditional branch that dominates the loop or controls
7453 // the loop latch. Check to see if it is the comparison we are looking for.
Dan Gohman430f0cc2009-07-21 23:03:19 +00007454 ICmpInst::Predicate FoundPred;
7455 if (Inverse)
7456 FoundPred = ICI->getInversePredicate();
7457 else
7458 FoundPred = ICI->getPredicate();
7459
7460 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
7461 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohmane65c9172009-07-13 21:35:55 +00007462
Sanjoy Dasdf1635d2015-09-25 19:59:52 +00007463 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
7464}
7465
7466bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
7467 const SCEV *RHS,
7468 ICmpInst::Predicate FoundPred,
7469 const SCEV *FoundLHS,
7470 const SCEV *FoundRHS) {
Sanjoy Das14598832015-03-26 17:28:26 +00007471 // Balance the types.
7472 if (getTypeSizeInBits(LHS->getType()) <
7473 getTypeSizeInBits(FoundLHS->getType())) {
7474 if (CmpInst::isSigned(Pred)) {
7475 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
7476 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
7477 } else {
7478 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
7479 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
7480 }
7481 } else if (getTypeSizeInBits(LHS->getType()) >
Dan Gohmane65c9172009-07-13 21:35:55 +00007482 getTypeSizeInBits(FoundLHS->getType())) {
Stepan Dyatkovskiy431993b2014-01-09 12:26:12 +00007483 if (CmpInst::isSigned(FoundPred)) {
Dan Gohmane65c9172009-07-13 21:35:55 +00007484 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
7485 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
7486 } else {
7487 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
7488 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
7489 }
7490 }
7491
Dan Gohman430f0cc2009-07-21 23:03:19 +00007492 // Canonicalize the query to match the way instcombine will have
7493 // canonicalized the comparison.
Dan Gohman3673aa12010-04-24 01:34:53 +00007494 if (SimplifyICmpOperands(Pred, LHS, RHS))
7495 if (LHS == RHS)
Dan Gohmanb5025c72010-05-03 18:00:24 +00007496 return CmpInst::isTrueWhenEqual(Pred);
Benjamin Kramerba11a982012-11-29 19:07:57 +00007497 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
7498 if (FoundLHS == FoundRHS)
7499 return CmpInst::isFalseWhenEqual(FoundPred);
Dan Gohman430f0cc2009-07-21 23:03:19 +00007500
7501 // Check to see if we can make the LHS or RHS match.
7502 if (LHS == FoundRHS || RHS == FoundLHS) {
7503 if (isa<SCEVConstant>(RHS)) {
7504 std::swap(FoundLHS, FoundRHS);
7505 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
7506 } else {
7507 std::swap(LHS, RHS);
7508 Pred = ICmpInst::getSwappedPredicate(Pred);
7509 }
7510 }
7511
7512 // Check whether the found predicate is the same as the desired predicate.
7513 if (FoundPred == Pred)
7514 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
7515
7516 // Check whether swapping the found predicate makes it the same as the
7517 // desired predicate.
7518 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
7519 if (isa<SCEVConstant>(RHS))
7520 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
7521 else
7522 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
7523 RHS, LHS, FoundLHS, FoundRHS);
7524 }
7525
Sanjoy Das6e78b172015-10-22 19:57:34 +00007526 // Unsigned comparison is the same as signed comparison when both the operands
7527 // are non-negative.
7528 if (CmpInst::isUnsigned(FoundPred) &&
7529 CmpInst::getSignedPredicate(FoundPred) == Pred &&
7530 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
7531 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
7532
Sanjoy Dasc5676df2014-11-13 00:00:58 +00007533 // Check if we can make progress by sharpening ranges.
7534 if (FoundPred == ICmpInst::ICMP_NE &&
7535 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
7536
7537 const SCEVConstant *C = nullptr;
7538 const SCEV *V = nullptr;
7539
7540 if (isa<SCEVConstant>(FoundLHS)) {
7541 C = cast<SCEVConstant>(FoundLHS);
7542 V = FoundRHS;
7543 } else {
7544 C = cast<SCEVConstant>(FoundRHS);
7545 V = FoundLHS;
7546 }
7547
7548 // The guarding predicate tells us that C != V. If the known range
7549 // of V is [C, t), we can sharpen the range to [C + 1, t). The
7550 // range we consider has to correspond to same signedness as the
7551 // predicate we're interested in folding.
7552
7553 APInt Min = ICmpInst::isSigned(Pred) ?
7554 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
7555
7556 if (Min == C->getValue()->getValue()) {
7557 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
7558 // This is true even if (Min + 1) wraps around -- in case of
7559 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
7560
7561 APInt SharperMin = Min + 1;
7562
7563 switch (Pred) {
7564 case ICmpInst::ICMP_SGE:
7565 case ICmpInst::ICMP_UGE:
7566 // We know V `Pred` SharperMin. If this implies LHS `Pred`
7567 // RHS, we're done.
7568 if (isImpliedCondOperands(Pred, LHS, RHS, V,
7569 getConstant(SharperMin)))
7570 return true;
7571
7572 case ICmpInst::ICMP_SGT:
7573 case ICmpInst::ICMP_UGT:
7574 // We know from the range information that (V `Pred` Min ||
7575 // V == Min). We know from the guarding condition that !(V
7576 // == Min). This gives us
7577 //
7578 // V `Pred` Min || V == Min && !(V == Min)
7579 // => V `Pred` Min
7580 //
7581 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
7582
7583 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
7584 return true;
7585
7586 default:
7587 // No change
7588 break;
7589 }
7590 }
7591 }
7592
Dan Gohman430f0cc2009-07-21 23:03:19 +00007593 // Check whether the actual condition is beyond sufficient.
7594 if (FoundPred == ICmpInst::ICMP_EQ)
7595 if (ICmpInst::isTrueWhenEqual(Pred))
7596 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
7597 return true;
7598 if (Pred == ICmpInst::ICMP_NE)
7599 if (!ICmpInst::isTrueWhenEqual(FoundPred))
7600 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
7601 return true;
7602
7603 // Otherwise assume the worst.
7604 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00007605}
7606
Sanjoy Das1ed69102015-10-13 02:53:27 +00007607bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
7608 const SCEV *&L, const SCEV *&R,
7609 SCEV::NoWrapFlags &Flags) {
7610 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
7611 if (!AE || AE->getNumOperands() != 2)
7612 return false;
7613
7614 L = AE->getOperand(0);
7615 R = AE->getOperand(1);
7616 Flags = AE->getNoWrapFlags();
7617 return true;
7618}
7619
7620bool ScalarEvolution::computeConstantDifference(const SCEV *Less,
7621 const SCEV *More,
7622 APInt &C) {
Sanjoy Das96709c42015-09-25 23:53:45 +00007623 // We avoid subtracting expressions here because this function is usually
7624 // fairly deep in the call stack (i.e. is called many times).
7625
Sanjoy Das96709c42015-09-25 23:53:45 +00007626 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
7627 const auto *LAR = cast<SCEVAddRecExpr>(Less);
7628 const auto *MAR = cast<SCEVAddRecExpr>(More);
7629
7630 if (LAR->getLoop() != MAR->getLoop())
7631 return false;
7632
7633 // We look at affine expressions only; not for correctness but to keep
7634 // getStepRecurrence cheap.
7635 if (!LAR->isAffine() || !MAR->isAffine())
7636 return false;
7637
Sanjoy Das1ed69102015-10-13 02:53:27 +00007638 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
Sanjoy Das96709c42015-09-25 23:53:45 +00007639 return false;
7640
7641 Less = LAR->getStart();
7642 More = MAR->getStart();
7643
7644 // fall through
7645 }
7646
7647 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
7648 const auto &M = cast<SCEVConstant>(More)->getValue()->getValue();
7649 const auto &L = cast<SCEVConstant>(Less)->getValue()->getValue();
7650 C = M - L;
7651 return true;
7652 }
7653
7654 const SCEV *L, *R;
Sanjoy Das1ed69102015-10-13 02:53:27 +00007655 SCEV::NoWrapFlags Flags;
7656 if (splitBinaryAdd(Less, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00007657 if (const auto *LC = dyn_cast<SCEVConstant>(L))
7658 if (R == More) {
7659 C = -(LC->getValue()->getValue());
7660 return true;
7661 }
7662
Sanjoy Das1ed69102015-10-13 02:53:27 +00007663 if (splitBinaryAdd(More, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00007664 if (const auto *LC = dyn_cast<SCEVConstant>(L))
7665 if (R == Less) {
7666 C = LC->getValue()->getValue();
7667 return true;
7668 }
7669
7670 return false;
7671}
7672
7673bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
7674 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
7675 const SCEV *FoundLHS, const SCEV *FoundRHS) {
7676 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
7677 return false;
7678
7679 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7680 if (!AddRecLHS)
7681 return false;
7682
7683 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
7684 if (!AddRecFoundLHS)
7685 return false;
7686
7687 // We'd like to let SCEV reason about control dependencies, so we constrain
7688 // both the inequalities to be about add recurrences on the same loop. This
7689 // way we can use isLoopEntryGuardedByCond later.
7690
7691 const Loop *L = AddRecFoundLHS->getLoop();
7692 if (L != AddRecLHS->getLoop())
7693 return false;
7694
7695 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
7696 //
7697 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
7698 // ... (2)
7699 //
7700 // Informal proof for (2), assuming (1) [*]:
7701 //
7702 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
7703 //
7704 // Then
7705 //
7706 // FoundLHS s< FoundRHS s< INT_MIN - C
7707 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
7708 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
7709 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
7710 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
7711 // <=> FoundLHS + C s< FoundRHS + C
7712 //
7713 // [*]: (1) can be proved by ruling out overflow.
7714 //
7715 // [**]: This can be proved by analyzing all the four possibilities:
7716 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
7717 // (A s>= 0, B s>= 0).
7718 //
7719 // Note:
7720 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
7721 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
7722 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
7723 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
7724 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
7725 // C)".
7726
7727 APInt LDiff, RDiff;
Sanjoy Das1ed69102015-10-13 02:53:27 +00007728 if (!computeConstantDifference(FoundLHS, LHS, LDiff) ||
7729 !computeConstantDifference(FoundRHS, RHS, RDiff) ||
Sanjoy Das96709c42015-09-25 23:53:45 +00007730 LDiff != RDiff)
7731 return false;
7732
7733 if (LDiff == 0)
7734 return true;
7735
Sanjoy Das96709c42015-09-25 23:53:45 +00007736 APInt FoundRHSLimit;
7737
7738 if (Pred == CmpInst::ICMP_ULT) {
7739 FoundRHSLimit = -RDiff;
7740 } else {
7741 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
Sanjoy Das4f1c4592015-09-28 21:14:32 +00007742 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - RDiff;
Sanjoy Das96709c42015-09-25 23:53:45 +00007743 }
7744
7745 // Try to prove (1) or (2), as needed.
7746 return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
7747 getConstant(FoundRHSLimit));
7748}
7749
Dan Gohman430f0cc2009-07-21 23:03:19 +00007750/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman8b0a4192010-03-01 17:49:51 +00007751/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman430f0cc2009-07-21 23:03:19 +00007752/// and FoundRHS is true.
7753bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
7754 const SCEV *LHS, const SCEV *RHS,
7755 const SCEV *FoundLHS,
7756 const SCEV *FoundRHS) {
Sanjoy Dascb8bca12015-03-18 00:41:29 +00007757 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
7758 return true;
7759
Sanjoy Das96709c42015-09-25 23:53:45 +00007760 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
7761 return true;
7762
Dan Gohman430f0cc2009-07-21 23:03:19 +00007763 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
7764 FoundLHS, FoundRHS) ||
7765 // ~x < ~y --> x > y
7766 isImpliedCondOperandsHelper(Pred, LHS, RHS,
7767 getNotSCEV(FoundRHS),
7768 getNotSCEV(FoundLHS));
7769}
7770
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007771
7772/// If Expr computes ~A, return A else return nullptr
7773static const SCEV *MatchNotExpr(const SCEV *Expr) {
7774 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
Sanjoy Das16e7ff12015-10-13 23:28:31 +00007775 if (!Add || Add->getNumOperands() != 2 ||
7776 !Add->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007777 return nullptr;
7778
7779 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
Sanjoy Das16e7ff12015-10-13 23:28:31 +00007780 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
7781 !AddRHS->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007782 return nullptr;
7783
7784 return AddRHS->getOperand(1);
7785}
7786
7787
7788/// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
7789template<typename MaxExprType>
7790static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
7791 const SCEV *Candidate) {
7792 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
7793 if (!MaxExpr) return false;
7794
7795 auto It = std::find(MaxExpr->op_begin(), MaxExpr->op_end(), Candidate);
7796 return It != MaxExpr->op_end();
7797}
7798
7799
7800/// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
7801template<typename MaxExprType>
7802static bool IsMinConsistingOf(ScalarEvolution &SE,
7803 const SCEV *MaybeMinExpr,
7804 const SCEV *Candidate) {
7805 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
7806 if (!MaybeMaxExpr)
7807 return false;
7808
7809 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
7810}
7811
Hal Finkela8d205f2015-08-19 01:51:51 +00007812static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
7813 ICmpInst::Predicate Pred,
7814 const SCEV *LHS, const SCEV *RHS) {
7815
7816 // If both sides are affine addrecs for the same loop, with equal
7817 // steps, and we know the recurrences don't wrap, then we only
7818 // need to check the predicate on the starting values.
7819
7820 if (!ICmpInst::isRelational(Pred))
7821 return false;
7822
7823 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7824 if (!LAR)
7825 return false;
7826 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7827 if (!RAR)
7828 return false;
7829 if (LAR->getLoop() != RAR->getLoop())
7830 return false;
7831 if (!LAR->isAffine() || !RAR->isAffine())
7832 return false;
7833
7834 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
7835 return false;
7836
Hal Finkelff08a2e2015-08-19 17:26:07 +00007837 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
7838 SCEV::FlagNSW : SCEV::FlagNUW;
7839 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
Hal Finkela8d205f2015-08-19 01:51:51 +00007840 return false;
7841
7842 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
7843}
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007844
7845/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
7846/// expression?
7847static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
7848 ICmpInst::Predicate Pred,
7849 const SCEV *LHS, const SCEV *RHS) {
7850 switch (Pred) {
7851 default:
7852 return false;
7853
7854 case ICmpInst::ICMP_SGE:
7855 std::swap(LHS, RHS);
7856 // fall through
7857 case ICmpInst::ICMP_SLE:
7858 return
7859 // min(A, ...) <= A
7860 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
7861 // A <= max(A, ...)
7862 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
7863
7864 case ICmpInst::ICMP_UGE:
7865 std::swap(LHS, RHS);
7866 // fall through
7867 case ICmpInst::ICMP_ULE:
7868 return
7869 // min(A, ...) <= A
7870 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
7871 // A <= max(A, ...)
7872 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
7873 }
7874
7875 llvm_unreachable("covered switch fell through?!");
7876}
7877
Dan Gohman430f0cc2009-07-21 23:03:19 +00007878/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman8b0a4192010-03-01 17:49:51 +00007879/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00007880/// FoundLHS, and FoundRHS is true.
Dan Gohmane65c9172009-07-13 21:35:55 +00007881bool
Dan Gohman430f0cc2009-07-21 23:03:19 +00007882ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
7883 const SCEV *LHS, const SCEV *RHS,
7884 const SCEV *FoundLHS,
7885 const SCEV *FoundRHS) {
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007886 auto IsKnownPredicateFull =
7887 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
7888 return isKnownPredicateWithRanges(Pred, LHS, RHS) ||
Sanjoy Das11231482015-10-22 19:57:29 +00007889 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
7890 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
7891 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007892 };
7893
Dan Gohmane65c9172009-07-13 21:35:55 +00007894 switch (Pred) {
Dan Gohman8c129d72009-07-16 17:34:36 +00007895 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
7896 case ICmpInst::ICMP_EQ:
7897 case ICmpInst::ICMP_NE:
7898 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
7899 return true;
7900 break;
Dan Gohmane65c9172009-07-13 21:35:55 +00007901 case ICmpInst::ICMP_SLT:
Dan Gohman8c129d72009-07-16 17:34:36 +00007902 case ICmpInst::ICMP_SLE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007903 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
7904 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00007905 return true;
7906 break;
7907 case ICmpInst::ICMP_SGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00007908 case ICmpInst::ICMP_SGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007909 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
7910 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00007911 return true;
7912 break;
7913 case ICmpInst::ICMP_ULT:
Dan Gohman8c129d72009-07-16 17:34:36 +00007914 case ICmpInst::ICMP_ULE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007915 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
7916 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00007917 return true;
7918 break;
7919 case ICmpInst::ICMP_UGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00007920 case ICmpInst::ICMP_UGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00007921 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
7922 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00007923 return true;
7924 break;
7925 }
7926
7927 return false;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00007928}
7929
Sanjoy Dascb8bca12015-03-18 00:41:29 +00007930/// isImpliedCondOperandsViaRanges - helper function for isImpliedCondOperands.
7931/// Tries to get cases like "X `sgt` 0 => X - 1 `sgt` -1".
7932bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
7933 const SCEV *LHS,
7934 const SCEV *RHS,
7935 const SCEV *FoundLHS,
7936 const SCEV *FoundRHS) {
7937 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
7938 // The restriction on `FoundRHS` be lifted easily -- it exists only to
7939 // reduce the compile time impact of this optimization.
7940 return false;
7941
7942 const SCEVAddExpr *AddLHS = dyn_cast<SCEVAddExpr>(LHS);
7943 if (!AddLHS || AddLHS->getOperand(1) != FoundLHS ||
7944 !isa<SCEVConstant>(AddLHS->getOperand(0)))
7945 return false;
7946
7947 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getValue()->getValue();
7948
7949 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
7950 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
7951 ConstantRange FoundLHSRange =
7952 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
7953
7954 // Since `LHS` is `FoundLHS` + `AddLHS->getOperand(0)`, we can compute a range
7955 // for `LHS`:
7956 APInt Addend =
7957 cast<SCEVConstant>(AddLHS->getOperand(0))->getValue()->getValue();
7958 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(Addend));
7959
7960 // We can also compute the range of values for `LHS` that satisfy the
7961 // consequent, "`LHS` `Pred` `RHS`":
7962 APInt ConstRHS = cast<SCEVConstant>(RHS)->getValue()->getValue();
7963 ConstantRange SatisfyingLHSRange =
7964 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
7965
7966 // The antecedent implies the consequent if every value of `LHS` that
7967 // satisfies the antecedent also satisfies the consequent.
7968 return SatisfyingLHSRange.contains(LHSRange);
7969}
7970
Johannes Doerfert2683e562015-02-09 12:34:23 +00007971// Verify if an linear IV with positive stride can overflow when in a
7972// less-than comparison, knowing the invariant term of the comparison, the
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007973// stride and the knowledge of NSW/NUW flags on the recurrence.
7974bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
7975 bool IsSigned, bool NoWrap) {
7976 if (NoWrap) return false;
Dan Gohman51aaf022010-01-26 04:40:18 +00007977
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007978 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00007979 const SCEV *One = getOne(Stride->getType());
Andrew Trick2afa3252011-03-09 17:29:58 +00007980
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007981 if (IsSigned) {
7982 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
7983 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
7984 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
7985 .getSignedMax();
Andrew Trick2afa3252011-03-09 17:29:58 +00007986
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007987 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
7988 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
Dan Gohman36bad002009-09-17 18:05:20 +00007989 }
Dan Gohman01048422009-06-21 23:46:38 +00007990
Andrew Trick34e2f0c2013-11-06 02:08:26 +00007991 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
7992 APInt MaxValue = APInt::getMaxValue(BitWidth);
7993 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
7994 .getUnsignedMax();
7995
7996 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
7997 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
7998}
7999
Johannes Doerfert2683e562015-02-09 12:34:23 +00008000// Verify if an linear IV with negative stride can overflow when in a
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008001// greater-than comparison, knowing the invariant term of the comparison,
8002// the stride and the knowledge of NSW/NUW flags on the recurrence.
8003bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8004 bool IsSigned, bool NoWrap) {
8005 if (NoWrap) return false;
8006
8007 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008008 const SCEV *One = getOne(Stride->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008009
8010 if (IsSigned) {
8011 APInt MinRHS = getSignedRange(RHS).getSignedMin();
8012 APInt MinValue = APInt::getSignedMinValue(BitWidth);
8013 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8014 .getSignedMax();
8015
8016 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8017 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8018 }
8019
8020 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8021 APInt MinValue = APInt::getMinValue(BitWidth);
8022 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8023 .getUnsignedMax();
8024
8025 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8026 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8027}
8028
8029// Compute the backedge taken count knowing the interval difference, the
8030// stride and presence of the equality in the comparison.
Johannes Doerfert2683e562015-02-09 12:34:23 +00008031const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008032 bool Equality) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008033 const SCEV *One = getOne(Step->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008034 Delta = Equality ? getAddExpr(Delta, Step)
8035 : getAddExpr(Delta, getMinusSCEV(Step, One));
8036 return getUDivExpr(Delta, Step);
Dan Gohman01048422009-06-21 23:46:38 +00008037}
8038
Chris Lattner587a75b2005-08-15 23:33:51 +00008039/// HowManyLessThans - Return the number of times a backedge containing the
8040/// specified less-than comparison will execute. If not computable, return
Dan Gohman4c720c02009-06-06 14:37:11 +00008041/// CouldNotCompute.
Andrew Trick5b245a12013-05-31 06:43:25 +00008042///
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008043/// @param ControlsExit is true when the LHS < RHS condition directly controls
8044/// the branch (loops exits only if condition is true). In this case, we can use
8045/// NoWrapFlags to skip overflow checks.
Andrew Trick3ca3f982011-07-26 17:19:55 +00008046ScalarEvolution::ExitLimit
Dan Gohmance973df2009-06-24 04:48:43 +00008047ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008048 const Loop *L, bool IsSigned,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008049 bool ControlsExit) {
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008050 // We handle only IV < Invariant
8051 if (!isLoopInvariant(RHS, L))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00008052 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008053
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008054 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohman2b8da352009-04-30 20:47:05 +00008055
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008056 // Avoid weird loops
8057 if (!IV || IV->getLoop() != L || !IV->isAffine())
8058 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008059
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008060 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008061 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008062
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008063 const SCEV *Stride = IV->getStepRecurrence(*this);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008064
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008065 // Avoid negative or zero stride values
8066 if (!isKnownPositive(Stride))
8067 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00008068
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008069 // Avoid proven overflow cases: this will ensure that the backedge taken count
8070 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00008071 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008072 // behaviors like the case of C language.
8073 if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8074 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00008075
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008076 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8077 : ICmpInst::ICMP_ULT;
8078 const SCEV *Start = IV->getStart();
8079 const SCEV *End = RHS;
Bradley Smith9992b162014-10-31 11:40:32 +00008080 if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) {
8081 const SCEV *Diff = getMinusSCEV(RHS, Start);
8082 // If we have NoWrap set, then we can assume that the increment won't
8083 // overflow, in which case if RHS - Start is a constant, we don't need to
8084 // do a max operation since we can just figure it out statically
8085 if (NoWrap && isa<SCEVConstant>(Diff)) {
8086 APInt D = dyn_cast<const SCEVConstant>(Diff)->getValue()->getValue();
8087 if (D.isNegative())
8088 End = Start;
8089 } else
8090 End = IsSigned ? getSMaxExpr(RHS, Start)
8091 : getUMaxExpr(RHS, Start);
8092 }
Dan Gohman51aaf022010-01-26 04:40:18 +00008093
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008094 const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
Dan Gohman2b8da352009-04-30 20:47:05 +00008095
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008096 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8097 : getUnsignedRange(Start).getUnsignedMin();
Andrew Trick2afa3252011-03-09 17:29:58 +00008098
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008099 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8100 : getUnsignedRange(Stride).getUnsignedMin();
Dan Gohman2b8da352009-04-30 20:47:05 +00008101
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008102 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8103 APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1)
8104 : APInt::getMaxValue(BitWidth) - (MinStride - 1);
Chris Lattner587a75b2005-08-15 23:33:51 +00008105
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008106 // Although End can be a MAX expression we estimate MaxEnd considering only
8107 // the case End = RHS. This is safe because in the other case (End - Start)
8108 // is zero, leading to a zero maximum backedge taken count.
8109 APInt MaxEnd =
8110 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8111 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8112
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +00008113 const SCEV *MaxBECount;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008114 if (isa<SCEVConstant>(BECount))
8115 MaxBECount = BECount;
8116 else
8117 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
8118 getConstant(MinStride), false);
8119
8120 if (isa<SCEVCouldNotCompute>(MaxBECount))
8121 MaxBECount = BECount;
8122
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008123 return ExitLimit(BECount, MaxBECount);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008124}
8125
8126ScalarEvolution::ExitLimit
8127ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
8128 const Loop *L, bool IsSigned,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008129 bool ControlsExit) {
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008130 // We handle only IV > Invariant
8131 if (!isLoopInvariant(RHS, L))
8132 return getCouldNotCompute();
8133
8134 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8135
8136 // Avoid weird loops
8137 if (!IV || IV->getLoop() != L || !IV->isAffine())
8138 return getCouldNotCompute();
8139
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008140 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008141 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8142
8143 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8144
8145 // Avoid negative or zero stride values
8146 if (!isKnownPositive(Stride))
8147 return getCouldNotCompute();
8148
8149 // Avoid proven overflow cases: this will ensure that the backedge taken count
8150 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00008151 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008152 // behaviors like the case of C language.
8153 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8154 return getCouldNotCompute();
8155
8156 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8157 : ICmpInst::ICMP_UGT;
8158
8159 const SCEV *Start = IV->getStart();
8160 const SCEV *End = RHS;
Bradley Smith9992b162014-10-31 11:40:32 +00008161 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
8162 const SCEV *Diff = getMinusSCEV(RHS, Start);
8163 // If we have NoWrap set, then we can assume that the increment won't
8164 // overflow, in which case if RHS - Start is a constant, we don't need to
8165 // do a max operation since we can just figure it out statically
8166 if (NoWrap && isa<SCEVConstant>(Diff)) {
8167 APInt D = dyn_cast<const SCEVConstant>(Diff)->getValue()->getValue();
8168 if (!D.isNegative())
8169 End = Start;
8170 } else
8171 End = IsSigned ? getSMinExpr(RHS, Start)
8172 : getUMinExpr(RHS, Start);
8173 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008174
8175 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8176
8177 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8178 : getUnsignedRange(Start).getUnsignedMax();
8179
8180 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8181 : getUnsignedRange(Stride).getUnsignedMin();
8182
8183 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8184 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8185 : APInt::getMinValue(BitWidth) + (MinStride - 1);
8186
8187 // Although End can be a MIN expression we estimate MinEnd considering only
8188 // the case End = RHS. This is safe because in the other case (Start - End)
8189 // is zero, leading to a zero maximum backedge taken count.
8190 APInt MinEnd =
8191 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8192 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8193
8194
8195 const SCEV *MaxBECount = getCouldNotCompute();
8196 if (isa<SCEVConstant>(BECount))
8197 MaxBECount = BECount;
8198 else
Johannes Doerfert2683e562015-02-09 12:34:23 +00008199 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008200 getConstant(MinStride), false);
8201
8202 if (isa<SCEVCouldNotCompute>(MaxBECount))
8203 MaxBECount = BECount;
8204
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008205 return ExitLimit(BECount, MaxBECount);
Chris Lattner587a75b2005-08-15 23:33:51 +00008206}
8207
Chris Lattnerd934c702004-04-02 20:23:17 +00008208/// getNumIterationsInRange - Return the number of iterations of this loop that
8209/// produce values in the specified constant range. Another way of looking at
8210/// this is that it returns the first iteration number where the value is not in
8211/// the condition, thus computing the exit count. If the iteration count can't
8212/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00008213const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohmance973df2009-06-24 04:48:43 +00008214 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00008215 if (Range.isFullSet()) // Infinite loop.
Dan Gohman31efa302009-04-18 17:58:19 +00008216 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008217
8218 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmana30370b2009-05-04 22:02:23 +00008219 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencer2e54a152007-03-02 00:28:52 +00008220 if (!SC->getValue()->isZero()) {
Dan Gohmanaf752342009-07-07 17:06:11 +00008221 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008222 Operands[0] = SE.getZero(SC->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00008223 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00008224 getNoWrapFlags(FlagNW));
Sanjoy Das63914592015-10-18 00:29:20 +00008225 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattnerd934c702004-04-02 20:23:17 +00008226 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohmana37eaf22007-10-22 18:31:58 +00008227 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00008228 // This is strange and shouldn't happen.
Dan Gohman31efa302009-04-18 17:58:19 +00008229 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008230 }
8231
8232 // The only time we can solve this is when we have all constant indices.
8233 // Otherwise, we cannot determine the overflow conditions.
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00008234 if (std::any_of(op_begin(), op_end(),
8235 [](const SCEV *Op) { return !isa<SCEVConstant>(Op);}))
8236 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008237
8238 // Okay at this point we know that all elements of the chrec are constants and
8239 // that the start element is zero.
8240
8241 // First check to see if the range contains zero. If not, the first
8242 // iteration exits.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00008243 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +00008244 if (!Range.contains(APInt(BitWidth, 0)))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008245 return SE.getZero(getType());
Misha Brukman01808ca2005-04-21 21:13:18 +00008246
Chris Lattnerd934c702004-04-02 20:23:17 +00008247 if (isAffine()) {
8248 // If this is an affine expression then we have this situation:
8249 // Solve {0,+,A} in Range === Ax in Range
8250
Nick Lewycky52460262007-07-16 02:08:00 +00008251 // We know that zero is in the range. If A is positive then we know that
8252 // the upper value of the range must be the first possible exit value.
8253 // If A is negative then the lower of the range is the last possible loop
8254 // value. Also note that we already checked for a full range.
Dan Gohman0a40ad92009-04-16 03:18:22 +00008255 APInt One(BitWidth,1);
Nick Lewycky52460262007-07-16 02:08:00 +00008256 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
8257 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattnerd934c702004-04-02 20:23:17 +00008258
Nick Lewycky52460262007-07-16 02:08:00 +00008259 // The exit value should be (End+A)/A.
Nick Lewycky39349612007-09-27 14:12:54 +00008260 APInt ExitVal = (End + A).udiv(A);
Owen Andersonedb4a702009-07-24 23:12:02 +00008261 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00008262
8263 // Evaluate at the exit value. If we really did fall out of the valid
8264 // range, then we computed our trip count, otherwise wrap around or other
8265 // things must have happened.
Dan Gohmana37eaf22007-10-22 18:31:58 +00008266 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008267 if (Range.contains(Val->getValue()))
Dan Gohman31efa302009-04-18 17:58:19 +00008268 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008269
8270 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00008271 assert(Range.contains(
Dan Gohmance973df2009-06-24 04:48:43 +00008272 EvaluateConstantChrecAtConstant(this,
Owen Andersonedb4a702009-07-24 23:12:02 +00008273 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattnerd934c702004-04-02 20:23:17 +00008274 "Linear scev computation is off in a bad way!");
Dan Gohmana37eaf22007-10-22 18:31:58 +00008275 return SE.getConstant(ExitValue);
Chris Lattnerd934c702004-04-02 20:23:17 +00008276 } else if (isQuadratic()) {
8277 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
8278 // quadratic equation to solve it. To do this, we must frame our problem in
8279 // terms of figuring out when zero is crossed, instead of when
8280 // Range.getUpper() is crossed.
Dan Gohmanaf752342009-07-07 17:06:11 +00008281 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00008282 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Andrew Trick8b55b732011-03-14 16:50:06 +00008283 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
8284 // getNoWrapFlags(FlagNW)
8285 FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00008286
8287 // Next, solve the constructed addrec
Dan Gohmanaf752342009-07-07 17:06:11 +00008288 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohmana37eaf22007-10-22 18:31:58 +00008289 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman48f82222009-05-04 22:30:44 +00008290 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
8291 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattnerd934c702004-04-02 20:23:17 +00008292 if (R1) {
8293 // Pick the smallest positive root value.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008294 if (ConstantInt *CB =
Owen Anderson487375e2009-07-29 18:55:55 +00008295 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Andersonf1f17432009-07-06 22:37:39 +00008296 R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00008297 if (!CB->getZExtValue())
Chris Lattnerd934c702004-04-02 20:23:17 +00008298 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00008299
Chris Lattnerd934c702004-04-02 20:23:17 +00008300 // Make sure the root is not off by one. The returned iteration should
8301 // not be in the range, but the previous one should be. When solving
8302 // for "X*X < 5", for example, we should not return a root of 2.
8303 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohmana37eaf22007-10-22 18:31:58 +00008304 R1->getValue(),
8305 SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008306 if (Range.contains(R1Val->getValue())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00008307 // The next iteration must be out of the range...
Owen Andersonf1f17432009-07-06 22:37:39 +00008308 ConstantInt *NextVal =
Owen Andersonedb4a702009-07-24 23:12:02 +00008309 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman01808ca2005-04-21 21:13:18 +00008310
Dan Gohmana37eaf22007-10-22 18:31:58 +00008311 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008312 if (!Range.contains(R1Val->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00008313 return SE.getConstant(NextVal);
Dan Gohman31efa302009-04-18 17:58:19 +00008314 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008315 }
Misha Brukman01808ca2005-04-21 21:13:18 +00008316
Chris Lattnerd934c702004-04-02 20:23:17 +00008317 // If R1 was not in the range, then it is a good return value. Make
8318 // sure that R1-1 WAS in the range though, just in case.
Owen Andersonf1f17432009-07-06 22:37:39 +00008319 ConstantInt *NextVal =
Owen Andersonedb4a702009-07-24 23:12:02 +00008320 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohmana37eaf22007-10-22 18:31:58 +00008321 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008322 if (Range.contains(R1Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00008323 return R1;
Dan Gohman31efa302009-04-18 17:58:19 +00008324 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008325 }
8326 }
8327 }
8328
Dan Gohman31efa302009-04-18 17:58:19 +00008329 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008330}
8331
Sebastian Pop448712b2014-05-07 18:01:20 +00008332namespace {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008333struct FindUndefs {
8334 bool Found;
8335 FindUndefs() : Found(false) {}
8336
8337 bool follow(const SCEV *S) {
8338 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
8339 if (isa<UndefValue>(C->getValue()))
8340 Found = true;
8341 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
8342 if (isa<UndefValue>(C->getValue()))
8343 Found = true;
8344 }
8345
8346 // Keep looking if we haven't found it yet.
8347 return !Found;
8348 }
8349 bool isDone() const {
8350 // Stop recursion if we have found an undef.
8351 return Found;
8352 }
8353};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00008354}
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008355
8356// Return true when S contains at least an undef value.
8357static inline bool
8358containsUndefs(const SCEV *S) {
8359 FindUndefs F;
8360 SCEVTraversal<FindUndefs> ST(F);
8361 ST.visitAll(S);
8362
8363 return F.Found;
8364}
8365
8366namespace {
Sebastian Pop448712b2014-05-07 18:01:20 +00008367// Collect all steps of SCEV expressions.
8368struct SCEVCollectStrides {
8369 ScalarEvolution &SE;
8370 SmallVectorImpl<const SCEV *> &Strides;
8371
8372 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
8373 : SE(SE), Strides(S) {}
8374
8375 bool follow(const SCEV *S) {
8376 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
8377 Strides.push_back(AR->getStepRecurrence(SE));
8378 return true;
8379 }
8380 bool isDone() const { return false; }
8381};
8382
8383// Collect all SCEVUnknown and SCEVMulExpr expressions.
8384struct SCEVCollectTerms {
8385 SmallVectorImpl<const SCEV *> &Terms;
8386
8387 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
8388 : Terms(T) {}
8389
8390 bool follow(const SCEV *S) {
Sebastian Popa6e58602014-05-27 22:41:45 +00008391 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008392 if (!containsUndefs(S))
8393 Terms.push_back(S);
Sebastian Pop448712b2014-05-07 18:01:20 +00008394
8395 // Stop recursion: once we collected a term, do not walk its operands.
8396 return false;
8397 }
8398
8399 // Keep looking.
8400 return true;
8401 }
8402 bool isDone() const { return false; }
8403};
Tobias Grosser374bce02015-10-12 08:02:00 +00008404
8405// Check if a SCEV contains an AddRecExpr.
8406struct SCEVHasAddRec {
8407 bool &ContainsAddRec;
8408
8409 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
8410 ContainsAddRec = false;
8411 }
8412
8413 bool follow(const SCEV *S) {
8414 if (isa<SCEVAddRecExpr>(S)) {
8415 ContainsAddRec = true;
8416
8417 // Stop recursion: once we collected a term, do not walk its operands.
8418 return false;
8419 }
8420
8421 // Keep looking.
8422 return true;
8423 }
8424 bool isDone() const { return false; }
8425};
8426
8427// Find factors that are multiplied with an expression that (possibly as a
8428// subexpression) contains an AddRecExpr. In the expression:
8429//
8430// 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
8431//
8432// "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
8433// that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
8434// parameters as they form a product with an induction variable.
8435//
8436// This collector expects all array size parameters to be in the same MulExpr.
8437// It might be necessary to later add support for collecting parameters that are
8438// spread over different nested MulExpr.
8439struct SCEVCollectAddRecMultiplies {
8440 SmallVectorImpl<const SCEV *> &Terms;
8441 ScalarEvolution &SE;
8442
8443 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
8444 : Terms(T), SE(SE) {}
8445
8446 bool follow(const SCEV *S) {
8447 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
8448 bool HasAddRec = false;
8449 SmallVector<const SCEV *, 0> Operands;
8450 for (auto Op : Mul->operands()) {
8451 if (isa<SCEVUnknown>(Op)) {
8452 Operands.push_back(Op);
8453 } else {
8454 bool ContainsAddRec;
8455 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
8456 visitAll(Op, ContiansAddRec);
8457 HasAddRec |= ContainsAddRec;
8458 }
8459 }
8460 if (Operands.size() == 0)
8461 return true;
8462
8463 if (!HasAddRec)
8464 return false;
8465
8466 Terms.push_back(SE.getMulExpr(Operands));
8467 // Stop recursion: once we collected a term, do not walk its operands.
8468 return false;
8469 }
8470
8471 // Keep looking.
8472 return true;
8473 }
8474 bool isDone() const { return false; }
8475};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00008476}
Sebastian Pop448712b2014-05-07 18:01:20 +00008477
Tobias Grosser374bce02015-10-12 08:02:00 +00008478/// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
8479/// two places:
8480/// 1) The strides of AddRec expressions.
8481/// 2) Unknowns that are multiplied with AddRec expressions.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008482void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
8483 SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00008484 SmallVector<const SCEV *, 4> Strides;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008485 SCEVCollectStrides StrideCollector(*this, Strides);
8486 visitAll(Expr, StrideCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00008487
8488 DEBUG({
8489 dbgs() << "Strides:\n";
8490 for (const SCEV *S : Strides)
8491 dbgs() << *S << "\n";
8492 });
8493
8494 for (const SCEV *S : Strides) {
8495 SCEVCollectTerms TermCollector(Terms);
8496 visitAll(S, TermCollector);
8497 }
8498
8499 DEBUG({
8500 dbgs() << "Terms:\n";
8501 for (const SCEV *T : Terms)
8502 dbgs() << *T << "\n";
8503 });
Tobias Grosser374bce02015-10-12 08:02:00 +00008504
8505 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
8506 visitAll(Expr, MulCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00008507}
8508
Sebastian Popb1a548f2014-05-12 19:01:53 +00008509static bool findArrayDimensionsRec(ScalarEvolution &SE,
Sebastian Pop448712b2014-05-07 18:01:20 +00008510 SmallVectorImpl<const SCEV *> &Terms,
Sebastian Pop47fe7de2014-05-09 22:45:07 +00008511 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pope30bd352014-05-27 22:41:56 +00008512 int Last = Terms.size() - 1;
8513 const SCEV *Step = Terms[Last];
Sebastian Popc62c6792013-11-12 22:47:20 +00008514
Sebastian Pop448712b2014-05-07 18:01:20 +00008515 // End of recursion.
Sebastian Pope30bd352014-05-27 22:41:56 +00008516 if (Last == 0) {
8517 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
Sebastian Pop448712b2014-05-07 18:01:20 +00008518 SmallVector<const SCEV *, 2> Qs;
8519 for (const SCEV *Op : M->operands())
8520 if (!isa<SCEVConstant>(Op))
8521 Qs.push_back(Op);
Sebastian Popc62c6792013-11-12 22:47:20 +00008522
Sebastian Pope30bd352014-05-27 22:41:56 +00008523 Step = SE.getMulExpr(Qs);
Sebastian Popc62c6792013-11-12 22:47:20 +00008524 }
8525
Sebastian Pope30bd352014-05-27 22:41:56 +00008526 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00008527 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00008528 }
8529
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00008530 for (const SCEV *&Term : Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00008531 // Normalize the terms before the next call to findArrayDimensionsRec.
8532 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00008533 SCEVDivision::divide(SE, Term, Step, &Q, &R);
Sebastian Popb1a548f2014-05-12 19:01:53 +00008534
8535 // Bail out when GCD does not evenly divide one of the terms.
8536 if (!R->isZero())
8537 return false;
8538
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00008539 Term = Q;
Sebastian Popc62c6792013-11-12 22:47:20 +00008540 }
8541
Tobias Grosser3080cf12014-05-08 07:55:34 +00008542 // Remove all SCEVConstants.
Tobias Grosser1e9db7e2014-05-08 21:43:19 +00008543 Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) {
8544 return isa<SCEVConstant>(E);
8545 }),
8546 Terms.end());
Sebastian Popc62c6792013-11-12 22:47:20 +00008547
Sebastian Pop448712b2014-05-07 18:01:20 +00008548 if (Terms.size() > 0)
Sebastian Popb1a548f2014-05-12 19:01:53 +00008549 if (!findArrayDimensionsRec(SE, Terms, Sizes))
8550 return false;
8551
Sebastian Pope30bd352014-05-27 22:41:56 +00008552 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00008553 return true;
Sebastian Pop448712b2014-05-07 18:01:20 +00008554}
Sebastian Popc62c6792013-11-12 22:47:20 +00008555
Sebastian Pop448712b2014-05-07 18:01:20 +00008556namespace {
8557struct FindParameter {
8558 bool FoundParameter;
8559 FindParameter() : FoundParameter(false) {}
Sebastian Popc62c6792013-11-12 22:47:20 +00008560
Sebastian Pop448712b2014-05-07 18:01:20 +00008561 bool follow(const SCEV *S) {
8562 if (isa<SCEVUnknown>(S)) {
8563 FoundParameter = true;
8564 // Stop recursion: we found a parameter.
8565 return false;
8566 }
8567 // Keep looking.
8568 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00008569 }
Sebastian Pop448712b2014-05-07 18:01:20 +00008570 bool isDone() const {
8571 // Stop recursion if we have found a parameter.
8572 return FoundParameter;
Sebastian Popc62c6792013-11-12 22:47:20 +00008573 }
Sebastian Popc62c6792013-11-12 22:47:20 +00008574};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00008575}
Sebastian Popc62c6792013-11-12 22:47:20 +00008576
Sebastian Pop448712b2014-05-07 18:01:20 +00008577// Returns true when S contains at least a SCEVUnknown parameter.
8578static inline bool
8579containsParameters(const SCEV *S) {
8580 FindParameter F;
8581 SCEVTraversal<FindParameter> ST(F);
8582 ST.visitAll(S);
8583
8584 return F.FoundParameter;
8585}
8586
8587// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
8588static inline bool
8589containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
8590 for (const SCEV *T : Terms)
8591 if (containsParameters(T))
8592 return true;
8593 return false;
8594}
8595
8596// Return the number of product terms in S.
8597static inline int numberOfTerms(const SCEV *S) {
8598 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
8599 return Expr->getNumOperands();
8600 return 1;
8601}
8602
Sebastian Popa6e58602014-05-27 22:41:45 +00008603static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
8604 if (isa<SCEVConstant>(T))
8605 return nullptr;
8606
8607 if (isa<SCEVUnknown>(T))
8608 return T;
8609
8610 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
8611 SmallVector<const SCEV *, 2> Factors;
8612 for (const SCEV *Op : M->operands())
8613 if (!isa<SCEVConstant>(Op))
8614 Factors.push_back(Op);
8615
8616 return SE.getMulExpr(Factors);
8617 }
8618
8619 return T;
8620}
8621
8622/// Return the size of an element read or written by Inst.
8623const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
8624 Type *Ty;
8625 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
8626 Ty = Store->getValueOperand()->getType();
8627 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
Tobias Grosser40ac1002014-06-08 19:21:20 +00008628 Ty = Load->getType();
Sebastian Popa6e58602014-05-27 22:41:45 +00008629 else
8630 return nullptr;
8631
8632 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
8633 return getSizeOfExpr(ETy, Ty);
8634}
8635
Sebastian Pop448712b2014-05-07 18:01:20 +00008636/// Second step of delinearization: compute the array dimensions Sizes from the
8637/// set of Terms extracted from the memory access function of this SCEVAddRec.
Sebastian Popa6e58602014-05-27 22:41:45 +00008638void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
8639 SmallVectorImpl<const SCEV *> &Sizes,
8640 const SCEV *ElementSize) const {
Sebastian Pop448712b2014-05-07 18:01:20 +00008641
Sebastian Pop53524082014-05-29 19:44:05 +00008642 if (Terms.size() < 1 || !ElementSize)
Sebastian Pop448712b2014-05-07 18:01:20 +00008643 return;
8644
8645 // Early return when Terms do not contain parameters: we do not delinearize
8646 // non parametric SCEVs.
8647 if (!containsParameters(Terms))
8648 return;
8649
8650 DEBUG({
8651 dbgs() << "Terms:\n";
8652 for (const SCEV *T : Terms)
8653 dbgs() << *T << "\n";
8654 });
8655
8656 // Remove duplicates.
8657 std::sort(Terms.begin(), Terms.end());
8658 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
8659
8660 // Put larger terms first.
8661 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
8662 return numberOfTerms(LHS) > numberOfTerms(RHS);
8663 });
8664
Sebastian Popa6e58602014-05-27 22:41:45 +00008665 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
8666
Tobias Grosser374bce02015-10-12 08:02:00 +00008667 // Try to divide all terms by the element size. If term is not divisible by
8668 // element size, proceed with the original term.
Sebastian Popa6e58602014-05-27 22:41:45 +00008669 for (const SCEV *&Term : Terms) {
8670 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00008671 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
Tobias Grosser374bce02015-10-12 08:02:00 +00008672 if (!Q->isZero())
8673 Term = Q;
Sebastian Popa6e58602014-05-27 22:41:45 +00008674 }
8675
8676 SmallVector<const SCEV *, 4> NewTerms;
8677
8678 // Remove constant factors.
8679 for (const SCEV *T : Terms)
8680 if (const SCEV *NewT = removeConstantFactors(SE, T))
8681 NewTerms.push_back(NewT);
8682
Sebastian Pop448712b2014-05-07 18:01:20 +00008683 DEBUG({
8684 dbgs() << "Terms after sorting:\n";
Sebastian Popa6e58602014-05-27 22:41:45 +00008685 for (const SCEV *T : NewTerms)
Sebastian Pop448712b2014-05-07 18:01:20 +00008686 dbgs() << *T << "\n";
8687 });
8688
Sebastian Popa6e58602014-05-27 22:41:45 +00008689 if (NewTerms.empty() ||
8690 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
Sebastian Popb1a548f2014-05-12 19:01:53 +00008691 Sizes.clear();
8692 return;
8693 }
Sebastian Pop448712b2014-05-07 18:01:20 +00008694
Sebastian Popa6e58602014-05-27 22:41:45 +00008695 // The last element to be pushed into Sizes is the size of an element.
8696 Sizes.push_back(ElementSize);
8697
Sebastian Pop448712b2014-05-07 18:01:20 +00008698 DEBUG({
8699 dbgs() << "Sizes:\n";
8700 for (const SCEV *S : Sizes)
8701 dbgs() << *S << "\n";
8702 });
8703}
8704
8705/// Third step of delinearization: compute the access functions for the
8706/// Subscripts based on the dimensions in Sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008707void ScalarEvolution::computeAccessFunctions(
8708 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
8709 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pop448712b2014-05-07 18:01:20 +00008710
Sebastian Popb1a548f2014-05-12 19:01:53 +00008711 // Early exit in case this SCEV is not an affine multivariate function.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008712 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00008713 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00008714
Sanjoy Das1195dbe2015-10-08 03:45:58 +00008715 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008716 if (!AR->isAffine())
8717 return;
8718
8719 const SCEV *Res = Expr;
Sebastian Pop448712b2014-05-07 18:01:20 +00008720 int Last = Sizes.size() - 1;
8721 for (int i = Last; i >= 0; i--) {
8722 const SCEV *Q, *R;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008723 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
Sebastian Pop448712b2014-05-07 18:01:20 +00008724
8725 DEBUG({
8726 dbgs() << "Res: " << *Res << "\n";
8727 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
8728 dbgs() << "Res divided by Sizes[i]:\n";
8729 dbgs() << "Quotient: " << *Q << "\n";
8730 dbgs() << "Remainder: " << *R << "\n";
8731 });
8732
8733 Res = Q;
8734
Sebastian Popa6e58602014-05-27 22:41:45 +00008735 // Do not record the last subscript corresponding to the size of elements in
8736 // the array.
Sebastian Pop448712b2014-05-07 18:01:20 +00008737 if (i == Last) {
Sebastian Popa6e58602014-05-27 22:41:45 +00008738
8739 // Bail out if the remainder is too complex.
Sebastian Pop28e6b972014-05-27 22:41:51 +00008740 if (isa<SCEVAddRecExpr>(R)) {
8741 Subscripts.clear();
8742 Sizes.clear();
8743 return;
8744 }
Sebastian Popa6e58602014-05-27 22:41:45 +00008745
Sebastian Pop448712b2014-05-07 18:01:20 +00008746 continue;
8747 }
8748
8749 // Record the access function for the current subscript.
8750 Subscripts.push_back(R);
8751 }
8752
8753 // Also push in last position the remainder of the last division: it will be
8754 // the access function of the innermost dimension.
8755 Subscripts.push_back(Res);
8756
8757 std::reverse(Subscripts.begin(), Subscripts.end());
8758
8759 DEBUG({
8760 dbgs() << "Subscripts:\n";
8761 for (const SCEV *S : Subscripts)
8762 dbgs() << *S << "\n";
8763 });
Sebastian Pop448712b2014-05-07 18:01:20 +00008764}
8765
Sebastian Popc62c6792013-11-12 22:47:20 +00008766/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
8767/// sizes of an array access. Returns the remainder of the delinearization that
Sebastian Pop7ee14722013-11-13 22:37:58 +00008768/// is the offset start of the array. The SCEV->delinearize algorithm computes
8769/// the multiples of SCEV coefficients: that is a pattern matching of sub
8770/// expressions in the stride and base of a SCEV corresponding to the
8771/// computation of a GCD (greatest common divisor) of base and stride. When
8772/// SCEV->delinearize fails, it returns the SCEV unchanged.
8773///
8774/// For example: when analyzing the memory access A[i][j][k] in this loop nest
8775///
8776/// void foo(long n, long m, long o, double A[n][m][o]) {
8777///
8778/// for (long i = 0; i < n; i++)
8779/// for (long j = 0; j < m; j++)
8780/// for (long k = 0; k < o; k++)
8781/// A[i][j][k] = 1.0;
8782/// }
8783///
8784/// the delinearization input is the following AddRec SCEV:
8785///
8786/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
8787///
8788/// From this SCEV, we are able to say that the base offset of the access is %A
8789/// because it appears as an offset that does not divide any of the strides in
8790/// the loops:
8791///
8792/// CHECK: Base offset: %A
8793///
8794/// and then SCEV->delinearize determines the size of some of the dimensions of
8795/// the array as these are the multiples by which the strides are happening:
8796///
8797/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
8798///
8799/// Note that the outermost dimension remains of UnknownSize because there are
8800/// no strides that would help identifying the size of the last dimension: when
8801/// the array has been statically allocated, one could compute the size of that
8802/// dimension by dividing the overall size of the array by the size of the known
8803/// dimensions: %m * %o * 8.
8804///
8805/// Finally delinearize provides the access functions for the array reference
8806/// that does correspond to A[i][j][k] of the above C testcase:
8807///
8808/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
8809///
8810/// The testcases are checking the output of a function pass:
8811/// DelinearizationPass that walks through all loads and stores of a function
8812/// asking for the SCEV of the memory access with respect to all enclosing
8813/// loops, calling SCEV->delinearize on that and printing the results.
8814
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008815void ScalarEvolution::delinearize(const SCEV *Expr,
Sebastian Pop28e6b972014-05-27 22:41:51 +00008816 SmallVectorImpl<const SCEV *> &Subscripts,
8817 SmallVectorImpl<const SCEV *> &Sizes,
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008818 const SCEV *ElementSize) {
Sebastian Pop448712b2014-05-07 18:01:20 +00008819 // First step: collect parametric terms.
8820 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008821 collectParametricTerms(Expr, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00008822
Sebastian Popb1a548f2014-05-12 19:01:53 +00008823 if (Terms.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00008824 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00008825
Sebastian Pop448712b2014-05-07 18:01:20 +00008826 // Second step: find subscript sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008827 findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop7ee14722013-11-13 22:37:58 +00008828
Sebastian Popb1a548f2014-05-12 19:01:53 +00008829 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00008830 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00008831
Sebastian Pop448712b2014-05-07 18:01:20 +00008832 // Third step: compute the access functions for each subscript.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008833 computeAccessFunctions(Expr, Subscripts, Sizes);
Sebastian Popc62c6792013-11-12 22:47:20 +00008834
Sebastian Pop28e6b972014-05-27 22:41:51 +00008835 if (Subscripts.empty())
8836 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00008837
Sebastian Pop448712b2014-05-07 18:01:20 +00008838 DEBUG({
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00008839 dbgs() << "succeeded to delinearize " << *Expr << "\n";
Sebastian Pop448712b2014-05-07 18:01:20 +00008840 dbgs() << "ArrayDecl[UnknownSize]";
8841 for (const SCEV *S : Sizes)
8842 dbgs() << "[" << *S << "]";
Sebastian Popc62c6792013-11-12 22:47:20 +00008843
Sebastian Pop444621a2014-05-09 22:45:02 +00008844 dbgs() << "\nArrayRef";
8845 for (const SCEV *S : Subscripts)
Sebastian Pop448712b2014-05-07 18:01:20 +00008846 dbgs() << "[" << *S << "]";
8847 dbgs() << "\n";
8848 });
Sebastian Popc62c6792013-11-12 22:47:20 +00008849}
Chris Lattnerd934c702004-04-02 20:23:17 +00008850
8851//===----------------------------------------------------------------------===//
Dan Gohman48f82222009-05-04 22:30:44 +00008852// SCEVCallbackVH Class Implementation
8853//===----------------------------------------------------------------------===//
8854
Dan Gohmand33a0902009-05-19 19:22:47 +00008855void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmandd707af2009-07-13 22:20:53 +00008856 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman48f82222009-05-04 22:30:44 +00008857 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
8858 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00008859 SE->ValueExprMap.erase(getValPtr());
Dan Gohman48f82222009-05-04 22:30:44 +00008860 // this now dangles!
8861}
8862
Dan Gohman7a066722010-07-28 01:09:07 +00008863void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmandd707af2009-07-13 22:20:53 +00008864 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christopheref6d5932010-07-29 01:25:38 +00008865
Dan Gohman48f82222009-05-04 22:30:44 +00008866 // Forget all the expressions associated with users of the old value,
8867 // so that future queries will recompute the expressions using the new
8868 // value.
Dan Gohman7cac9572010-08-02 23:49:30 +00008869 Value *Old = getValPtr();
Chandler Carruthcdf47882014-03-09 03:16:01 +00008870 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
Dan Gohmanf34f8632009-07-14 14:34:04 +00008871 SmallPtrSet<User *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00008872 while (!Worklist.empty()) {
8873 User *U = Worklist.pop_back_val();
8874 // Deleting the Old value will cause this to dangle. Postpone
8875 // that until everything else is done.
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00008876 if (U == Old)
Dan Gohman48f82222009-05-04 22:30:44 +00008877 continue;
David Blaikie70573dc2014-11-19 07:49:26 +00008878 if (!Visited.insert(U).second)
Dan Gohmanf34f8632009-07-14 14:34:04 +00008879 continue;
Dan Gohman48f82222009-05-04 22:30:44 +00008880 if (PHINode *PN = dyn_cast<PHINode>(U))
8881 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00008882 SE->ValueExprMap.erase(U);
Chandler Carruthcdf47882014-03-09 03:16:01 +00008883 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
Dan Gohman48f82222009-05-04 22:30:44 +00008884 }
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00008885 // Delete the Old value.
8886 if (PHINode *PN = dyn_cast<PHINode>(Old))
8887 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00008888 SE->ValueExprMap.erase(Old);
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00008889 // this now dangles!
Dan Gohman48f82222009-05-04 22:30:44 +00008890}
8891
Dan Gohmand33a0902009-05-19 19:22:47 +00008892ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman48f82222009-05-04 22:30:44 +00008893 : CallbackVH(V), SE(se) {}
8894
8895//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00008896// ScalarEvolution Class Implementation
8897//===----------------------------------------------------------------------===//
8898
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008899ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
8900 AssumptionCache &AC, DominatorTree &DT,
8901 LoopInfo &LI)
8902 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
8903 CouldNotCompute(new SCEVCouldNotCompute()),
Sanjoy Das7d910f22015-10-02 18:50:30 +00008904 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
8905 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
8906 FirstUnknown(nullptr) {}
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008907
8908ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
8909 : F(Arg.F), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI),
8910 CouldNotCompute(std::move(Arg.CouldNotCompute)),
8911 ValueExprMap(std::move(Arg.ValueExprMap)),
Sanjoy Das7d910f22015-10-02 18:50:30 +00008912 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008913 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
8914 ConstantEvolutionLoopExitValue(
8915 std::move(Arg.ConstantEvolutionLoopExitValue)),
8916 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
8917 LoopDispositions(std::move(Arg.LoopDispositions)),
8918 BlockDispositions(std::move(Arg.BlockDispositions)),
8919 UnsignedRanges(std::move(Arg.UnsignedRanges)),
8920 SignedRanges(std::move(Arg.SignedRanges)),
8921 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
8922 SCEVAllocator(std::move(Arg.SCEVAllocator)),
8923 FirstUnknown(Arg.FirstUnknown) {
8924 Arg.FirstUnknown = nullptr;
Dan Gohmanc8e23622009-04-21 23:15:49 +00008925}
8926
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008927ScalarEvolution::~ScalarEvolution() {
Dan Gohman7cac9572010-08-02 23:49:30 +00008928 // Iterate through all the SCEVUnknown instances and call their
8929 // destructors, so that they release their references to their values.
Naomi Musgravef90c1be2015-09-16 23:46:40 +00008930 for (SCEVUnknown *U = FirstUnknown; U;) {
8931 SCEVUnknown *Tmp = U;
8932 U = U->Next;
8933 Tmp->~SCEVUnknown();
8934 }
Craig Topper9f008862014-04-15 04:59:12 +00008935 FirstUnknown = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00008936
Dan Gohman9bad2fb2010-08-27 18:55:03 +00008937 ValueExprMap.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00008938
8939 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
8940 // that a loop had multiple computable exits.
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00008941 for (auto &BTCI : BackedgeTakenCounts)
8942 BTCI.second.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00008943
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008944 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00008945 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
Sanjoy Das7d910f22015-10-02 18:50:30 +00008946 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
Dan Gohman0a40ad92009-04-16 03:18:22 +00008947}
8948
Dan Gohmanc8e23622009-04-21 23:15:49 +00008949bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman0bddac12009-02-24 18:55:53 +00008950 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattnerd934c702004-04-02 20:23:17 +00008951}
8952
Dan Gohmanc8e23622009-04-21 23:15:49 +00008953static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +00008954 const Loop *L) {
8955 // Print all inner loops first
8956 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
8957 PrintLoopInfo(OS, SE, *I);
Misha Brukman01808ca2005-04-21 21:13:18 +00008958
Dan Gohmanbc694912010-01-09 18:17:45 +00008959 OS << "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00008960 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00008961 OS << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00008962
Dan Gohmancb0efec2009-12-18 01:14:11 +00008963 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00008964 L->getExitBlocks(ExitBlocks);
8965 if (ExitBlocks.size() != 1)
Nick Lewyckyd1200b02008-01-02 02:49:20 +00008966 OS << "<multiple exits> ";
Chris Lattnerd934c702004-04-02 20:23:17 +00008967
Dan Gohman0bddac12009-02-24 18:55:53 +00008968 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
8969 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattnerd934c702004-04-02 20:23:17 +00008970 } else {
Dan Gohman0bddac12009-02-24 18:55:53 +00008971 OS << "Unpredictable backedge-taken count. ";
Chris Lattnerd934c702004-04-02 20:23:17 +00008972 }
8973
Dan Gohmanbc694912010-01-09 18:17:45 +00008974 OS << "\n"
8975 "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00008976 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00008977 OS << ": ";
Dan Gohman69942932009-06-24 00:33:16 +00008978
8979 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
8980 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
8981 } else {
8982 OS << "Unpredictable max backedge-taken count. ";
8983 }
8984
8985 OS << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00008986}
8987
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008988void ScalarEvolution::print(raw_ostream &OS) const {
Dan Gohman8b0a4192010-03-01 17:49:51 +00008989 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanc8e23622009-04-21 23:15:49 +00008990 // out SCEV values of all instructions that are interesting. Doing
8991 // this potentially causes it to create new SCEV objects though,
8992 // which technically conflicts with the const qualifier. This isn't
Dan Gohman028e6152009-07-10 20:25:29 +00008993 // observable from outside the class though, so casting away the
8994 // const isn't dangerous.
Dan Gohmancb0efec2009-12-18 01:14:11 +00008995 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattnerd934c702004-04-02 20:23:17 +00008996
Dan Gohmanbc694912010-01-09 18:17:45 +00008997 OS << "Classifying expressions for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00008998 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00008999 OS << "\n";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009000 for (Instruction &I : instructions(F))
9001 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9002 OS << I << '\n';
Dan Gohman81313fd2008-09-14 17:21:12 +00009003 OS << " --> ";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009004 const SCEV *SV = SE.getSCEV(&I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009005 SV->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009006 if (!isa<SCEVCouldNotCompute>(SV)) {
9007 OS << " U: ";
9008 SE.getUnsignedRange(SV).print(OS);
9009 OS << " S: ";
9010 SE.getSignedRange(SV).print(OS);
9011 }
Misha Brukman01808ca2005-04-21 21:13:18 +00009012
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009013 const Loop *L = LI.getLoopFor(I.getParent());
Dan Gohmanb9063a82009-06-19 17:49:54 +00009014
Dan Gohmanaf752342009-07-07 17:06:11 +00009015 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohmanb9063a82009-06-19 17:49:54 +00009016 if (AtUse != SV) {
9017 OS << " --> ";
9018 AtUse->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009019 if (!isa<SCEVCouldNotCompute>(AtUse)) {
9020 OS << " U: ";
9021 SE.getUnsignedRange(AtUse).print(OS);
9022 OS << " S: ";
9023 SE.getSignedRange(AtUse).print(OS);
9024 }
Dan Gohmanb9063a82009-06-19 17:49:54 +00009025 }
9026
9027 if (L) {
Dan Gohman94c468f2009-06-18 00:37:45 +00009028 OS << "\t\t" "Exits: ";
Dan Gohmanaf752342009-07-07 17:06:11 +00009029 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanafd6db92010-11-17 21:23:15 +00009030 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00009031 OS << "<<Unknown>>";
9032 } else {
9033 OS << *ExitValue;
9034 }
9035 }
9036
Chris Lattnerd934c702004-04-02 20:23:17 +00009037 OS << "\n";
9038 }
9039
Dan Gohmanbc694912010-01-09 18:17:45 +00009040 OS << "Determining loop execution counts for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009041 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009042 OS << "\n";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009043 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
Dan Gohmanc8e23622009-04-21 23:15:49 +00009044 PrintLoopInfo(OS, &SE, *I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009045}
Dan Gohmane20f8242009-04-21 00:47:46 +00009046
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009047ScalarEvolution::LoopDisposition
9048ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009049 auto &Values = LoopDispositions[S];
9050 for (auto &V : Values) {
9051 if (V.getPointer() == L)
9052 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009053 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009054 Values.emplace_back(L, LoopVariant);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009055 LoopDisposition D = computeLoopDisposition(S, L);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009056 auto &Values2 = LoopDispositions[S];
9057 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9058 if (V.getPointer() == L) {
9059 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009060 break;
9061 }
9062 }
9063 return D;
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009064}
9065
9066ScalarEvolution::LoopDisposition
9067ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009068 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009069 case scConstant:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009070 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009071 case scTruncate:
9072 case scZeroExtend:
9073 case scSignExtend:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009074 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohmanafd6db92010-11-17 21:23:15 +00009075 case scAddRecExpr: {
9076 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9077
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009078 // If L is the addrec's loop, it's computable.
9079 if (AR->getLoop() == L)
9080 return LoopComputable;
9081
Dan Gohmanafd6db92010-11-17 21:23:15 +00009082 // Add recurrences are never invariant in the function-body (null loop).
9083 if (!L)
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009084 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009085
9086 // This recurrence is variant w.r.t. L if L contains AR's loop.
9087 if (L->contains(AR->getLoop()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009088 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009089
9090 // This recurrence is invariant w.r.t. L if AR's loop contains L.
9091 if (AR->getLoop()->contains(L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009092 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009093
9094 // This recurrence is variant w.r.t. L if any of its operands
9095 // are variant.
9096 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
9097 I != E; ++I)
9098 if (!isLoopInvariant(*I, L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009099 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009100
9101 // Otherwise it's loop-invariant.
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009102 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009103 }
9104 case scAddExpr:
9105 case scMulExpr:
9106 case scUMaxExpr:
9107 case scSMaxExpr: {
9108 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohmanafd6db92010-11-17 21:23:15 +00009109 bool HasVarying = false;
9110 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
9111 I != E; ++I) {
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009112 LoopDisposition D = getLoopDisposition(*I, L);
9113 if (D == LoopVariant)
9114 return LoopVariant;
9115 if (D == LoopComputable)
9116 HasVarying = true;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009117 }
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009118 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009119 }
9120 case scUDivExpr: {
9121 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009122 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9123 if (LD == LoopVariant)
9124 return LoopVariant;
9125 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9126 if (RD == LoopVariant)
9127 return LoopVariant;
9128 return (LD == LoopInvariant && RD == LoopInvariant) ?
9129 LoopInvariant : LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009130 }
9131 case scUnknown:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009132 // All non-instruction values are loop invariant. All instructions are loop
9133 // invariant if they are not contained in the specified loop.
9134 // Instructions are never considered invariant in the function body
9135 // (null loop) because they are defined within the "loop".
9136 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
9137 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9138 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009139 case scCouldNotCompute:
9140 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanafd6db92010-11-17 21:23:15 +00009141 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009142 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009143}
9144
9145bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9146 return getLoopDisposition(S, L) == LoopInvariant;
9147}
9148
9149bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9150 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009151}
Dan Gohman20d9ce22010-11-17 21:41:58 +00009152
Dan Gohman8ea83d82010-11-18 00:34:22 +00009153ScalarEvolution::BlockDisposition
9154ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009155 auto &Values = BlockDispositions[S];
9156 for (auto &V : Values) {
9157 if (V.getPointer() == BB)
9158 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009159 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009160 Values.emplace_back(BB, DoesNotDominateBlock);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009161 BlockDisposition D = computeBlockDisposition(S, BB);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009162 auto &Values2 = BlockDispositions[S];
9163 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9164 if (V.getPointer() == BB) {
9165 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009166 break;
9167 }
9168 }
9169 return D;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009170}
9171
Dan Gohman8ea83d82010-11-18 00:34:22 +00009172ScalarEvolution::BlockDisposition
9173ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009174 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohman20d9ce22010-11-17 21:41:58 +00009175 case scConstant:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009176 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009177 case scTruncate:
9178 case scZeroExtend:
9179 case scSignExtend:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009180 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohman20d9ce22010-11-17 21:41:58 +00009181 case scAddRecExpr: {
9182 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman8ea83d82010-11-18 00:34:22 +00009183 // to test for proper dominance too, because the instruction which
9184 // produces the addrec's value is a PHI, and a PHI effectively properly
9185 // dominates its entire containing block.
Dan Gohman20d9ce22010-11-17 21:41:58 +00009186 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009187 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009188 return DoesNotDominateBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009189 }
9190 // FALL THROUGH into SCEVNAryExpr handling.
9191 case scAddExpr:
9192 case scMulExpr:
9193 case scUMaxExpr:
9194 case scSMaxExpr: {
9195 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009196 bool Proper = true;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009197 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
Dan Gohman8ea83d82010-11-18 00:34:22 +00009198 I != E; ++I) {
9199 BlockDisposition D = getBlockDisposition(*I, BB);
9200 if (D == DoesNotDominateBlock)
9201 return DoesNotDominateBlock;
9202 if (D == DominatesBlock)
9203 Proper = false;
9204 }
9205 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009206 }
9207 case scUDivExpr: {
9208 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009209 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
9210 BlockDisposition LD = getBlockDisposition(LHS, BB);
9211 if (LD == DoesNotDominateBlock)
9212 return DoesNotDominateBlock;
9213 BlockDisposition RD = getBlockDisposition(RHS, BB);
9214 if (RD == DoesNotDominateBlock)
9215 return DoesNotDominateBlock;
9216 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
9217 ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009218 }
9219 case scUnknown:
9220 if (Instruction *I =
Dan Gohman8ea83d82010-11-18 00:34:22 +00009221 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
9222 if (I->getParent() == BB)
9223 return DominatesBlock;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009224 if (DT.properlyDominates(I->getParent(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009225 return ProperlyDominatesBlock;
9226 return DoesNotDominateBlock;
9227 }
9228 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009229 case scCouldNotCompute:
9230 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman20d9ce22010-11-17 21:41:58 +00009231 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009232 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman8ea83d82010-11-18 00:34:22 +00009233}
9234
9235bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
9236 return getBlockDisposition(S, BB) >= DominatesBlock;
9237}
9238
9239bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
9240 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009241}
Dan Gohman534749b2010-11-17 22:27:42 +00009242
Andrew Trick365e31c2012-07-13 23:33:03 +00009243namespace {
9244// Search for a SCEV expression node within an expression tree.
9245// Implements SCEVTraversal::Visitor.
9246struct SCEVSearch {
9247 const SCEV *Node;
9248 bool IsFound;
9249
9250 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
9251
9252 bool follow(const SCEV *S) {
9253 IsFound |= (S == Node);
9254 return !IsFound;
9255 }
9256 bool isDone() const { return IsFound; }
9257};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00009258}
Andrew Trick365e31c2012-07-13 23:33:03 +00009259
Dan Gohman534749b2010-11-17 22:27:42 +00009260bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
Andrew Trick365e31c2012-07-13 23:33:03 +00009261 SCEVSearch Search(Op);
9262 visitAll(S, Search);
9263 return Search.IsFound;
Dan Gohman534749b2010-11-17 22:27:42 +00009264}
Dan Gohman7e6b3932010-11-17 23:28:48 +00009265
9266void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
9267 ValuesAtScopes.erase(S);
9268 LoopDispositions.erase(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009269 BlockDispositions.erase(S);
Dan Gohman7e6b3932010-11-17 23:28:48 +00009270 UnsignedRanges.erase(S);
9271 SignedRanges.erase(S);
Andrew Trick9093e152013-03-26 03:14:53 +00009272
9273 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
9274 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); I != E; ) {
9275 BackedgeTakenInfo &BEInfo = I->second;
9276 if (BEInfo.hasOperand(S, this)) {
9277 BEInfo.clear();
9278 BackedgeTakenCounts.erase(I++);
9279 }
9280 else
9281 ++I;
9282 }
Dan Gohman7e6b3932010-11-17 23:28:48 +00009283}
Benjamin Kramer214935e2012-10-26 17:31:32 +00009284
9285typedef DenseMap<const Loop *, std::string> VerifyMap;
Benjamin Kramer24d270d2012-10-27 10:45:01 +00009286
Alp Tokercb402912014-01-24 17:20:08 +00009287/// replaceSubString - Replaces all occurrences of From in Str with To.
Benjamin Kramer24d270d2012-10-27 10:45:01 +00009288static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
9289 size_t Pos = 0;
9290 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
9291 Str.replace(Pos, From.size(), To.data(), To.size());
9292 Pos += To.size();
9293 }
9294}
9295
Benjamin Kramer214935e2012-10-26 17:31:32 +00009296/// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
9297static void
9298getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
9299 for (Loop::reverse_iterator I = L->rbegin(), E = L->rend(); I != E; ++I) {
9300 getLoopBackedgeTakenCounts(*I, Map, SE); // recurse.
9301
9302 std::string &S = Map[L];
9303 if (S.empty()) {
9304 raw_string_ostream OS(S);
9305 SE.getBackedgeTakenCount(L)->print(OS);
Benjamin Kramer24d270d2012-10-27 10:45:01 +00009306
9307 // false and 0 are semantically equivalent. This can happen in dead loops.
9308 replaceSubString(OS.str(), "false", "0");
9309 // Remove wrap flags, their use in SCEV is highly fragile.
9310 // FIXME: Remove this when SCEV gets smarter about them.
9311 replaceSubString(OS.str(), "<nw>", "");
9312 replaceSubString(OS.str(), "<nsw>", "");
9313 replaceSubString(OS.str(), "<nuw>", "");
Benjamin Kramer214935e2012-10-26 17:31:32 +00009314 }
9315 }
9316}
9317
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009318void ScalarEvolution::verify() const {
Benjamin Kramer214935e2012-10-26 17:31:32 +00009319 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9320
9321 // Gather stringified backedge taken counts for all loops using SCEV's caches.
9322 // FIXME: It would be much better to store actual values instead of strings,
9323 // but SCEV pointers will change if we drop the caches.
9324 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009325 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
Benjamin Kramer214935e2012-10-26 17:31:32 +00009326 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
9327
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009328 // Gather stringified backedge taken counts for all loops using a fresh
9329 // ScalarEvolution object.
9330 ScalarEvolution SE2(F, TLI, AC, DT, LI);
9331 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
9332 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
Benjamin Kramer214935e2012-10-26 17:31:32 +00009333
9334 // Now compare whether they're the same with and without caches. This allows
9335 // verifying that no pass changed the cache.
9336 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
9337 "New loops suddenly appeared!");
9338
9339 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
9340 OldE = BackedgeDumpsOld.end(),
9341 NewI = BackedgeDumpsNew.begin();
9342 OldI != OldE; ++OldI, ++NewI) {
9343 assert(OldI->first == NewI->first && "Loop order changed!");
9344
9345 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
9346 // changes.
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009347 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
Benjamin Kramer214935e2012-10-26 17:31:32 +00009348 // means that a pass is buggy or SCEV has to learn a new pattern but is
9349 // usually not harmful.
9350 if (OldI->second != NewI->second &&
9351 OldI->second.find("undef") == std::string::npos &&
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009352 NewI->second.find("undef") == std::string::npos &&
9353 OldI->second != "***COULDNOTCOMPUTE***" &&
Benjamin Kramer214935e2012-10-26 17:31:32 +00009354 NewI->second != "***COULDNOTCOMPUTE***") {
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009355 dbgs() << "SCEVValidator: SCEV for loop '"
Benjamin Kramer214935e2012-10-26 17:31:32 +00009356 << OldI->first->getHeader()->getName()
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009357 << "' changed from '" << OldI->second
9358 << "' to '" << NewI->second << "'!\n";
Benjamin Kramer214935e2012-10-26 17:31:32 +00009359 std::abort();
9360 }
9361 }
9362
9363 // TODO: Verify more things.
9364}
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009365
9366char ScalarEvolutionAnalysis::PassID;
9367
9368ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
9369 AnalysisManager<Function> *AM) {
9370 return ScalarEvolution(F, AM->getResult<TargetLibraryAnalysis>(F),
9371 AM->getResult<AssumptionAnalysis>(F),
9372 AM->getResult<DominatorTreeAnalysis>(F),
9373 AM->getResult<LoopAnalysis>(F));
9374}
9375
9376PreservedAnalyses
9377ScalarEvolutionPrinterPass::run(Function &F, AnalysisManager<Function> *AM) {
9378 AM->getResult<ScalarEvolutionAnalysis>(F).print(OS);
9379 return PreservedAnalyses::all();
9380}
9381
9382INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
9383 "Scalar Evolution Analysis", false, true)
9384INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
9385INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
9386INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
9387INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
9388INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
9389 "Scalar Evolution Analysis", false, true)
9390char ScalarEvolutionWrapperPass::ID = 0;
9391
9392ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
9393 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
9394}
9395
9396bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
9397 SE.reset(new ScalarEvolution(
9398 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
9399 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
9400 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
9401 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
9402 return false;
9403}
9404
9405void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
9406
9407void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
9408 SE->print(OS);
9409}
9410
9411void ScalarEvolutionWrapperPass::verifyAnalysis() const {
9412 if (!VerifySCEV)
9413 return;
9414
9415 SE->verify();
9416}
9417
9418void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
9419 AU.setPreservesAll();
9420 AU.addRequiredTransitive<AssumptionCacheTracker>();
9421 AU.addRequiredTransitive<LoopInfoWrapperPass>();
9422 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
9423 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
9424}