blob: a9619746797ea6de6fd3f263da98346c1b132458 [file] [log] [blame]
Chris Lattner965c7692008-06-02 01:18:21 +00001//===- ValueTracking.cpp - Walk computations to compute properties --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains routines that help analyze properties that chains of
11// computations have.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000016#include "llvm/ADT/APFloat.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/None.h"
James Molloy493e57d2015-10-26 14:10:46 +000020#include "llvm/ADT/Optional.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000021#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000023#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/ADT/iterator_range.h"
27#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000028#include "llvm/Analysis/AssumptionCache.h"
Dan Gohman949ab782010-12-15 20:10:26 +000029#include "llvm/Analysis/InstructionSimplify.h"
Artur Pilipenko31bcca42016-02-24 12:49:04 +000030#include "llvm/Analysis/Loads.h"
Adam Nemete2b885c2015-04-23 20:09:20 +000031#include "llvm/Analysis/LoopInfo.h"
Sanjay Patel54656ca2017-02-06 18:26:06 +000032#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000033#include "llvm/Analysis/TargetLibraryInfo.h"
34#include "llvm/IR/Argument.h"
35#include "llvm/IR/Attributes.h"
36#include "llvm/IR/BasicBlock.h"
Nick Lewyckyec373542014-05-20 05:13:21 +000037#include "llvm/IR/CallSite.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000038#include "llvm/IR/Constant.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000039#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/Constants.h"
41#include "llvm/IR/DataLayout.h"
Matthias Braun50ec0b52017-05-19 22:37:09 +000042#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000043#include "llvm/IR/DiagnosticInfo.h"
Hal Finkel60db0582014-09-07 18:57:58 +000044#include "llvm/IR/Dominators.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000045#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000046#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/GlobalAlias.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000048#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/GlobalVariable.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000050#include "llvm/IR/InstrTypes.h"
51#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000052#include "llvm/IR/Instructions.h"
53#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000054#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/LLVMContext.h"
56#include "llvm/IR/Metadata.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000057#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000059#include "llvm/IR/PatternMatch.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000060#include "llvm/IR/Type.h"
61#include "llvm/IR/User.h"
62#include "llvm/IR/Value.h"
63#include "llvm/Support/Casting.h"
64#include "llvm/Support/CommandLine.h"
65#include "llvm/Support/Compiler.h"
66#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000067#include "llvm/Support/KnownBits.h"
Chris Lattner965c7692008-06-02 01:18:21 +000068#include "llvm/Support/MathExtras.h"
Matthias Braun37e5d792016-01-28 06:29:33 +000069#include <algorithm>
70#include <array>
Eugene Zelenko75075ef2017-09-01 21:37:29 +000071#include <cassert>
72#include <cstdint>
73#include <iterator>
74#include <utility>
75
Chris Lattner965c7692008-06-02 01:18:21 +000076using namespace llvm;
Duncan Sandsd3951082011-01-25 09:38:29 +000077using namespace llvm::PatternMatch;
78
79const unsigned MaxDepth = 6;
80
Philip Reames1c292272015-03-10 22:43:20 +000081// Controls the number of uses of the value searched for possible
82// dominating comparisons.
83static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
Igor Laevskycea9ede2015-09-29 14:57:52 +000084 cl::Hidden, cl::init(20));
Philip Reames1c292272015-03-10 22:43:20 +000085
Chandler Carruth37c7b082017-08-14 07:03:24 +000086// This optimization is known to cause performance regressions is some cases,
87// keep it under a temporary flag for now.
88static cl::opt<bool>
89DontImproveNonNegativePhiBits("dont-improve-non-negative-phi-bits",
90 cl::Hidden, cl::init(true));
91
Craig Topper6b3940a2017-05-03 22:25:19 +000092/// Returns the bitwidth of the given scalar or pointer type. For vector types,
93/// returns the element type's bitwidth.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000094static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
Duncan Sandsd3951082011-01-25 09:38:29 +000095 if (unsigned BitWidth = Ty->getScalarSizeInBits())
96 return BitWidth;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +000097
Mehdi Aminia28d91d2015-03-10 02:37:25 +000098 return DL.getPointerTypeSizeInBits(Ty);
Duncan Sandsd3951082011-01-25 09:38:29 +000099}
Chris Lattner965c7692008-06-02 01:18:21 +0000100
Benjamin Kramercfd8d902014-09-12 08:56:53 +0000101namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000102
Hal Finkel60db0582014-09-07 18:57:58 +0000103// Simplifying using an assume can only be done in a particular control-flow
104// context (the context instruction provides that context). If an assume and
105// the context instruction are not in the same block then the DT helps in
106// figuring out if we can use it.
107struct Query {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000108 const DataLayout &DL;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000109 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +0000110 const Instruction *CxtI;
111 const DominatorTree *DT;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000112
Sanjay Patel54656ca2017-02-06 18:26:06 +0000113 // Unlike the other analyses, this may be a nullptr because not all clients
114 // provide it currently.
115 OptimizationRemarkEmitter *ORE;
Hal Finkel60db0582014-09-07 18:57:58 +0000116
Matthias Braun37e5d792016-01-28 06:29:33 +0000117 /// Set of assumptions that should be excluded from further queries.
118 /// This is because of the potential for mutual recursion to cause
119 /// computeKnownBits to repeatedly visit the same assume intrinsic. The
120 /// classic case of this is assume(x = y), which will attempt to determine
121 /// bits in x from bits in y, which will attempt to determine bits in y from
122 /// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
Craig Topper6e11a052017-05-08 16:22:48 +0000123 /// isKnownNonZero, which calls computeKnownBits and isKnownToBeAPowerOfTwo
124 /// (all of which can call computeKnownBits), and so on.
Li Huang755f75f2016-10-15 19:00:04 +0000125 std::array<const Value *, MaxDepth> Excluded;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000126
127 unsigned NumExcluded = 0;
Matthias Braun37e5d792016-01-28 06:29:33 +0000128
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000129 Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000130 const DominatorTree *DT, OptimizationRemarkEmitter *ORE = nullptr)
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000131 : DL(DL), AC(AC), CxtI(CxtI), DT(DT), ORE(ORE) {}
Hal Finkel60db0582014-09-07 18:57:58 +0000132
133 Query(const Query &Q, const Value *NewExcl)
Sanjay Patel54656ca2017-02-06 18:26:06 +0000134 : DL(Q.DL), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT), ORE(Q.ORE),
135 NumExcluded(Q.NumExcluded) {
Matthias Braun37e5d792016-01-28 06:29:33 +0000136 Excluded = Q.Excluded;
137 Excluded[NumExcluded++] = NewExcl;
138 assert(NumExcluded <= Excluded.size());
139 }
140
141 bool isExcluded(const Value *Value) const {
142 if (NumExcluded == 0)
143 return false;
144 auto End = Excluded.begin() + NumExcluded;
145 return std::find(Excluded.begin(), End, Value) != End;
Hal Finkel60db0582014-09-07 18:57:58 +0000146 }
147};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000148
Benjamin Kramercfd8d902014-09-12 08:56:53 +0000149} // end anonymous namespace
Hal Finkel60db0582014-09-07 18:57:58 +0000150
Sanjay Patel547e9752014-11-04 16:09:50 +0000151// Given the provided Value and, potentially, a context instruction, return
Hal Finkel60db0582014-09-07 18:57:58 +0000152// the preferred context instruction (if any).
153static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
154 // If we've been provided with a context instruction, then use that (provided
155 // it has been inserted).
156 if (CxtI && CxtI->getParent())
157 return CxtI;
158
159 // If the value is really an already-inserted instruction, then use that.
160 CxtI = dyn_cast<Instruction>(V);
161 if (CxtI && CxtI->getParent())
162 return CxtI;
163
164 return nullptr;
165}
166
Craig Topperb45eabc2017-04-26 16:39:58 +0000167static void computeKnownBits(const Value *V, KnownBits &Known,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000168 unsigned Depth, const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000169
Craig Topperb45eabc2017-04-26 16:39:58 +0000170void llvm::computeKnownBits(const Value *V, KnownBits &Known,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000171 const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000172 AssumptionCache *AC, const Instruction *CxtI,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000173 const DominatorTree *DT,
174 OptimizationRemarkEmitter *ORE) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000175 ::computeKnownBits(V, Known, Depth,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000176 Query(DL, AC, safeCxtI(V, CxtI), DT, ORE));
Hal Finkel60db0582014-09-07 18:57:58 +0000177}
178
Craig Topper6e11a052017-05-08 16:22:48 +0000179static KnownBits computeKnownBits(const Value *V, unsigned Depth,
180 const Query &Q);
181
182KnownBits llvm::computeKnownBits(const Value *V, const DataLayout &DL,
183 unsigned Depth, AssumptionCache *AC,
184 const Instruction *CxtI,
Craig Toppera2025ea2017-05-24 16:53:03 +0000185 const DominatorTree *DT,
186 OptimizationRemarkEmitter *ORE) {
187 return ::computeKnownBits(V, Depth,
188 Query(DL, AC, safeCxtI(V, CxtI), DT, ORE));
Craig Topper6e11a052017-05-08 16:22:48 +0000189}
190
Pete Cooper35b00d52016-08-13 01:05:32 +0000191bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
192 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000193 AssumptionCache *AC, const Instruction *CxtI,
Jingyue Wuca321902015-05-14 23:53:19 +0000194 const DominatorTree *DT) {
195 assert(LHS->getType() == RHS->getType() &&
196 "LHS and RHS should have the same type");
197 assert(LHS->getType()->isIntOrIntVectorTy() &&
198 "LHS and RHS should be integers");
199 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
Craig Topperb45eabc2017-04-26 16:39:58 +0000200 KnownBits LHSKnown(IT->getBitWidth());
201 KnownBits RHSKnown(IT->getBitWidth());
202 computeKnownBits(LHS, LHSKnown, DL, 0, AC, CxtI, DT);
203 computeKnownBits(RHS, RHSKnown, DL, 0, AC, CxtI, DT);
204 return (LHSKnown.Zero | RHSKnown.Zero).isAllOnesValue();
Jingyue Wuca321902015-05-14 23:53:19 +0000205}
206
Zaara Syeda3a7578c2017-05-31 17:12:38 +0000207bool llvm::isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI) {
208 for (const User *U : CxtI->users()) {
209 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
210 if (IC->isEquality())
211 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
212 if (C->isNullValue())
213 continue;
214 return false;
215 }
216 return true;
217}
218
Pete Cooper35b00d52016-08-13 01:05:32 +0000219static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000220 const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000221
Pete Cooper35b00d52016-08-13 01:05:32 +0000222bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
223 bool OrZero,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000224 unsigned Depth, AssumptionCache *AC,
225 const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000226 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000227 return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000228 Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000229}
230
Pete Cooper35b00d52016-08-13 01:05:32 +0000231static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000232
Pete Cooper35b00d52016-08-13 01:05:32 +0000233bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000234 AssumptionCache *AC, const Instruction *CxtI,
235 const DominatorTree *DT) {
236 return ::isKnownNonZero(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000237}
238
Pete Cooper35b00d52016-08-13 01:05:32 +0000239bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000240 unsigned Depth,
241 AssumptionCache *AC, const Instruction *CxtI,
Jingyue Wu10fcea52015-08-20 18:27:04 +0000242 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +0000243 KnownBits Known = computeKnownBits(V, DL, Depth, AC, CxtI, DT);
244 return Known.isNonNegative();
Jingyue Wu10fcea52015-08-20 18:27:04 +0000245}
246
Pete Cooper35b00d52016-08-13 01:05:32 +0000247bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000248 AssumptionCache *AC, const Instruction *CxtI,
249 const DominatorTree *DT) {
Philip Reames8f12eba2016-03-09 21:31:47 +0000250 if (auto *CI = dyn_cast<ConstantInt>(V))
251 return CI->getValue().isStrictlyPositive();
Sanjoy Das6082c1a2016-05-07 02:08:15 +0000252
Philip Reames8f12eba2016-03-09 21:31:47 +0000253 // TODO: We'd doing two recursive queries here. We should factor this such
254 // that only a single query is needed.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000255 return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT) &&
256 isKnownNonZero(V, DL, Depth, AC, CxtI, DT);
Philip Reames8f12eba2016-03-09 21:31:47 +0000257}
258
Pete Cooper35b00d52016-08-13 01:05:32 +0000259bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000260 AssumptionCache *AC, const Instruction *CxtI,
261 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +0000262 KnownBits Known = computeKnownBits(V, DL, Depth, AC, CxtI, DT);
263 return Known.isNegative();
Nick Lewycky762f8a82016-04-21 00:53:14 +0000264}
265
Pete Cooper35b00d52016-08-13 01:05:32 +0000266static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q);
James Molloy1d88d6f2015-10-22 13:18:42 +0000267
Pete Cooper35b00d52016-08-13 01:05:32 +0000268bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000269 const DataLayout &DL,
270 AssumptionCache *AC, const Instruction *CxtI,
Pete Cooper35b00d52016-08-13 01:05:32 +0000271 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000272 return ::isKnownNonEqual(V1, V2, Query(DL, AC,
273 safeCxtI(V1, safeCxtI(V2, CxtI)),
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000274 DT));
James Molloy1d88d6f2015-10-22 13:18:42 +0000275}
276
Pete Cooper35b00d52016-08-13 01:05:32 +0000277static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000278 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000279
Pete Cooper35b00d52016-08-13 01:05:32 +0000280bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
281 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000282 unsigned Depth, AssumptionCache *AC,
283 const Instruction *CxtI, const DominatorTree *DT) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000284 return ::MaskedValueIsZero(V, Mask, Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000285 Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000286}
287
Pete Cooper35b00d52016-08-13 01:05:32 +0000288static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
289 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000290
Pete Cooper35b00d52016-08-13 01:05:32 +0000291unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000292 unsigned Depth, AssumptionCache *AC,
293 const Instruction *CxtI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000294 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000295 return ::ComputeNumSignBits(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000296}
297
Craig Topper8fbb74b2017-03-24 22:12:10 +0000298static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
299 bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000300 KnownBits &KnownOut, KnownBits &Known2,
Craig Topper8fbb74b2017-03-24 22:12:10 +0000301 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000302 unsigned BitWidth = KnownOut.getBitWidth();
Craig Topper8fbb74b2017-03-24 22:12:10 +0000303
304 // If an initial sequence of bits in the result is not needed, the
305 // corresponding bits in the operands are not needed.
Craig Topperb45eabc2017-04-26 16:39:58 +0000306 KnownBits LHSKnown(BitWidth);
307 computeKnownBits(Op0, LHSKnown, Depth + 1, Q);
308 computeKnownBits(Op1, Known2, Depth + 1, Q);
Craig Topper8fbb74b2017-03-24 22:12:10 +0000309
Craig Topperb498a232017-08-08 16:29:35 +0000310 KnownOut = KnownBits::computeForAddSub(Add, NSW, LHSKnown, Known2);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000311}
312
Pete Cooper35b00d52016-08-13 01:05:32 +0000313static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000314 KnownBits &Known, KnownBits &Known2,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000315 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000316 unsigned BitWidth = Known.getBitWidth();
317 computeKnownBits(Op1, Known, Depth + 1, Q);
318 computeKnownBits(Op0, Known2, Depth + 1, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000319
320 bool isKnownNegative = false;
321 bool isKnownNonNegative = false;
322 // If the multiplication is known not to overflow, compute the sign bit.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000323 if (NSW) {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000324 if (Op0 == Op1) {
325 // The product of a number with itself is non-negative.
326 isKnownNonNegative = true;
327 } else {
Craig Topperca48af32017-04-29 16:43:11 +0000328 bool isKnownNonNegativeOp1 = Known.isNonNegative();
329 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
330 bool isKnownNegativeOp1 = Known.isNegative();
331 bool isKnownNegativeOp0 = Known2.isNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000332 // The product of two numbers with the same sign is non-negative.
333 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
334 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
335 // The product of a negative number and a non-negative number is either
336 // negative or zero.
337 if (!isKnownNonNegative)
338 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000339 isKnownNonZero(Op0, Depth, Q)) ||
Nick Lewyckyfa306072012-03-18 23:28:48 +0000340 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000341 isKnownNonZero(Op1, Depth, Q));
Nick Lewyckyfa306072012-03-18 23:28:48 +0000342 }
343 }
344
345 // If low bits are zero in either operand, output low known-0 bits.
Sanjay Patel5dd66c32015-09-17 20:51:50 +0000346 // Also compute a conservative estimate for high known-0 bits.
Nick Lewyckyfa306072012-03-18 23:28:48 +0000347 // More trickiness is possible, but this is sufficient for the
348 // interesting case of alignment computation.
Craig Topper8df66c62017-05-12 17:20:30 +0000349 unsigned TrailZ = Known.countMinTrailingZeros() +
350 Known2.countMinTrailingZeros();
351 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
352 Known2.countMinLeadingZeros(),
Nick Lewyckyfa306072012-03-18 23:28:48 +0000353 BitWidth) - BitWidth;
354
355 TrailZ = std::min(TrailZ, BitWidth);
356 LeadZ = std::min(LeadZ, BitWidth);
Craig Topperf0aeee02017-05-05 17:36:09 +0000357 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000358 Known.Zero.setLowBits(TrailZ);
359 Known.Zero.setHighBits(LeadZ);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000360
361 // Only make use of no-wrap flags if we failed to compute the sign bit
362 // directly. This matters if the multiplication always overflows, in
363 // which case we prefer to follow the result of the direct computation,
364 // though as the program is invoking undefined behaviour we can choose
365 // whatever we like here.
Craig Topperca48af32017-04-29 16:43:11 +0000366 if (isKnownNonNegative && !Known.isNegative())
367 Known.makeNonNegative();
368 else if (isKnownNegative && !Known.isNonNegative())
369 Known.makeNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000370}
371
Jingyue Wu37fcb592014-06-19 16:50:16 +0000372void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
Craig Topperf42b23f2017-04-28 06:28:56 +0000373 KnownBits &Known) {
374 unsigned BitWidth = Known.getBitWidth();
Rafael Espindola53190532012-03-30 15:52:11 +0000375 unsigned NumRanges = Ranges.getNumOperands() / 2;
376 assert(NumRanges >= 1);
377
Craig Topperf42b23f2017-04-28 06:28:56 +0000378 Known.Zero.setAllBits();
379 Known.One.setAllBits();
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000380
Rafael Espindola53190532012-03-30 15:52:11 +0000381 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000382 ConstantInt *Lower =
383 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
384 ConstantInt *Upper =
385 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
Rafael Espindola53190532012-03-30 15:52:11 +0000386 ConstantRange Range(Lower->getValue(), Upper->getValue());
Rafael Espindola53190532012-03-30 15:52:11 +0000387
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000388 // The first CommonPrefixBits of all values in Range are equal.
389 unsigned CommonPrefixBits =
390 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
391
392 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
Craig Topperf42b23f2017-04-28 06:28:56 +0000393 Known.One &= Range.getUnsignedMax() & Mask;
394 Known.Zero &= ~Range.getUnsignedMax() & Mask;
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000395 }
Rafael Espindola53190532012-03-30 15:52:11 +0000396}
Jay Foad5a29c362014-05-15 12:12:55 +0000397
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000398static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
Hal Finkel60db0582014-09-07 18:57:58 +0000399 SmallVector<const Value *, 16> WorkSet(1, I);
400 SmallPtrSet<const Value *, 32> Visited;
401 SmallPtrSet<const Value *, 16> EphValues;
402
Hal Finkelf2199b22015-10-23 20:37:08 +0000403 // The instruction defining an assumption's condition itself is always
404 // considered ephemeral to that assumption (even if it has other
405 // non-ephemeral users). See r246696's test case for an example.
David Majnemer0a16c222016-08-11 21:15:00 +0000406 if (is_contained(I->operands(), E))
Hal Finkelf2199b22015-10-23 20:37:08 +0000407 return true;
408
Hal Finkel60db0582014-09-07 18:57:58 +0000409 while (!WorkSet.empty()) {
410 const Value *V = WorkSet.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +0000411 if (!Visited.insert(V).second)
Hal Finkel60db0582014-09-07 18:57:58 +0000412 continue;
413
414 // If all uses of this value are ephemeral, then so is this value.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000415 if (llvm::all_of(V->users(), [&](const User *U) {
416 return EphValues.count(U);
417 })) {
Hal Finkel60db0582014-09-07 18:57:58 +0000418 if (V == E)
419 return true;
420
Hal Finkelb03dd4b2017-08-14 17:11:43 +0000421 if (V == I || isSafeToSpeculativelyExecute(V)) {
422 EphValues.insert(V);
423 if (const User *U = dyn_cast<User>(V))
424 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
425 J != JE; ++J)
426 WorkSet.push_back(*J);
427 }
Hal Finkel60db0582014-09-07 18:57:58 +0000428 }
429 }
430
431 return false;
432}
433
434// Is this an intrinsic that cannot be speculated but also cannot trap?
435static bool isAssumeLikeIntrinsic(const Instruction *I) {
436 if (const CallInst *CI = dyn_cast<CallInst>(I))
437 if (Function *F = CI->getCalledFunction())
438 switch (F->getIntrinsicID()) {
439 default: break;
440 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
441 case Intrinsic::assume:
442 case Intrinsic::dbg_declare:
443 case Intrinsic::dbg_value:
444 case Intrinsic::invariant_start:
445 case Intrinsic::invariant_end:
446 case Intrinsic::lifetime_start:
447 case Intrinsic::lifetime_end:
448 case Intrinsic::objectsize:
449 case Intrinsic::ptr_annotation:
450 case Intrinsic::var_annotation:
451 return true;
452 }
453
454 return false;
455}
456
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000457bool llvm::isValidAssumeForContext(const Instruction *Inv,
458 const Instruction *CxtI,
459 const DominatorTree *DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000460 // There are two restrictions on the use of an assume:
461 // 1. The assume must dominate the context (or the control flow must
462 // reach the assume whenever it reaches the context).
463 // 2. The context must not be in the assume's set of ephemeral values
464 // (otherwise we will use the assume to prove that the condition
465 // feeding the assume is trivially true, thus causing the removal of
466 // the assume).
467
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000468 if (DT) {
Pete Cooper54a02552016-08-12 01:00:15 +0000469 if (DT->dominates(Inv, CxtI))
Hal Finkel60db0582014-09-07 18:57:58 +0000470 return true;
Pete Cooper54a02552016-08-12 01:00:15 +0000471 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
472 // We don't have a DT, but this trivially dominates.
473 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000474 }
475
Pete Cooper54a02552016-08-12 01:00:15 +0000476 // With or without a DT, the only remaining case we will check is if the
477 // instructions are in the same BB. Give up if that is not the case.
478 if (Inv->getParent() != CxtI->getParent())
479 return false;
480
481 // If we have a dom tree, then we now know that the assume doens't dominate
482 // the other instruction. If we don't have a dom tree then we can check if
483 // the assume is first in the BB.
484 if (!DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000485 // Search forward from the assume until we reach the context (or the end
486 // of the block); the common case is that the assume will come first.
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000487 for (auto I = std::next(BasicBlock::const_iterator(Inv)),
Hal Finkel60db0582014-09-07 18:57:58 +0000488 IE = Inv->getParent()->end(); I != IE; ++I)
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000489 if (&*I == CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000490 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000491 }
492
Pete Cooper54a02552016-08-12 01:00:15 +0000493 // The context comes first, but they're both in the same block. Make sure
494 // there is nothing in between that might interrupt the control flow.
495 for (BasicBlock::const_iterator I =
496 std::next(BasicBlock::const_iterator(CxtI)), IE(Inv);
497 I != IE; ++I)
498 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
499 return false;
500
501 return !isEphemeralValueOf(Inv, CxtI);
Hal Finkel60db0582014-09-07 18:57:58 +0000502}
503
Craig Topperb45eabc2017-04-26 16:39:58 +0000504static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
505 unsigned Depth, const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000506 // Use of assumptions is context-sensitive. If we don't have a context, we
507 // cannot use them!
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000508 if (!Q.AC || !Q.CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000509 return;
510
Craig Topperb45eabc2017-04-26 16:39:58 +0000511 unsigned BitWidth = Known.getBitWidth();
Hal Finkel60db0582014-09-07 18:57:58 +0000512
Hal Finkel8a9a7832017-01-11 13:24:24 +0000513 // Note that the patterns below need to be kept in sync with the code
514 // in AssumptionCache::updateAffectedValues.
515
516 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000517 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +0000518 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000519 CallInst *I = cast<CallInst>(AssumeVH);
520 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
521 "Got assumption for the wrong function!");
522 if (Q.isExcluded(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000523 continue;
524
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000525 // Warning: This loop can end up being somewhat performance sensetive.
526 // We're running this loop for once for each value queried resulting in a
527 // runtime of ~O(#assumes * #values).
Philip Reames00d3b272014-11-24 23:44:28 +0000528
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000529 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
530 "must be an assume intrinsic");
531
532 Value *Arg = I->getArgOperand(0);
533
534 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000535 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000536 Known.setAllOnes();
Hal Finkel60db0582014-09-07 18:57:58 +0000537 return;
538 }
Sanjay Patel96669962017-01-17 18:15:49 +0000539 if (match(Arg, m_Not(m_Specific(V))) &&
540 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
541 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000542 Known.setAllZero();
Sanjay Patel96669962017-01-17 18:15:49 +0000543 return;
544 }
Hal Finkel60db0582014-09-07 18:57:58 +0000545
David Majnemer9b609752014-12-12 23:59:29 +0000546 // The remaining tests are all recursive, so bail out if we hit the limit.
547 if (Depth == MaxDepth)
548 continue;
549
Hal Finkel60db0582014-09-07 18:57:58 +0000550 Value *A, *B;
551 auto m_V = m_CombineOr(m_Specific(V),
552 m_CombineOr(m_PtrToInt(m_Specific(V)),
553 m_BitCast(m_Specific(V))));
554
555 CmpInst::Predicate Pred;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000556 ConstantInt *C;
Hal Finkel60db0582014-09-07 18:57:58 +0000557 // assume(v = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000558 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000559 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000560 KnownBits RHSKnown(BitWidth);
561 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
562 Known.Zero |= RHSKnown.Zero;
563 Known.One |= RHSKnown.One;
Hal Finkel60db0582014-09-07 18:57:58 +0000564 // assume(v & b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000565 } else if (match(Arg,
566 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000567 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000568 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000569 KnownBits RHSKnown(BitWidth);
570 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
571 KnownBits MaskKnown(BitWidth);
572 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel60db0582014-09-07 18:57:58 +0000573
574 // For those bits in the mask that are known to be one, we can propagate
575 // known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000576 Known.Zero |= RHSKnown.Zero & MaskKnown.One;
577 Known.One |= RHSKnown.One & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000578 // assume(~(v & b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000579 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
580 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000581 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000582 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000583 KnownBits RHSKnown(BitWidth);
584 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
585 KnownBits MaskKnown(BitWidth);
586 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000587
588 // For those bits in the mask that are known to be one, we can propagate
589 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000590 Known.Zero |= RHSKnown.One & MaskKnown.One;
591 Known.One |= RHSKnown.Zero & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000592 // assume(v | b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000593 } else if (match(Arg,
594 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000595 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000596 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000597 KnownBits RHSKnown(BitWidth);
598 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
599 KnownBits BKnown(BitWidth);
600 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000601
602 // For those bits in B that are known to be zero, we can propagate known
603 // bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000604 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
605 Known.One |= RHSKnown.One & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000606 // assume(~(v | b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000607 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
608 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000609 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000610 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000611 KnownBits RHSKnown(BitWidth);
612 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
613 KnownBits BKnown(BitWidth);
614 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000615
616 // For those bits in B that are known to be zero, we can propagate
617 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000618 Known.Zero |= RHSKnown.One & BKnown.Zero;
619 Known.One |= RHSKnown.Zero & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000620 // assume(v ^ b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000621 } else if (match(Arg,
622 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000623 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000624 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000625 KnownBits RHSKnown(BitWidth);
626 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
627 KnownBits BKnown(BitWidth);
628 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000629
630 // For those bits in B that are known to be zero, we can propagate known
631 // bits from the RHS to V. For those bits in B that are known to be one,
632 // we can propagate inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000633 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
634 Known.One |= RHSKnown.One & BKnown.Zero;
635 Known.Zero |= RHSKnown.One & BKnown.One;
636 Known.One |= RHSKnown.Zero & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000637 // assume(~(v ^ b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000638 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
639 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000640 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000641 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000642 KnownBits RHSKnown(BitWidth);
643 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
644 KnownBits BKnown(BitWidth);
645 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000646
647 // For those bits in B that are known to be zero, we can propagate
648 // inverted known bits from the RHS to V. For those bits in B that are
649 // known to be one, we can propagate known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000650 Known.Zero |= RHSKnown.One & BKnown.Zero;
651 Known.One |= RHSKnown.Zero & BKnown.Zero;
652 Known.Zero |= RHSKnown.Zero & BKnown.One;
653 Known.One |= RHSKnown.One & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000654 // assume(v << c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000655 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
656 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000657 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000658 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000659 KnownBits RHSKnown(BitWidth);
660 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000661 // For those bits in RHS that are known, we can propagate them to known
662 // bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000663 RHSKnown.Zero.lshrInPlace(C->getZExtValue());
664 Known.Zero |= RHSKnown.Zero;
665 RHSKnown.One.lshrInPlace(C->getZExtValue());
666 Known.One |= RHSKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000667 // assume(~(v << c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000668 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
669 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000670 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000671 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000672 KnownBits RHSKnown(BitWidth);
673 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000674 // For those bits in RHS that are known, we can propagate them inverted
675 // to known bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000676 RHSKnown.One.lshrInPlace(C->getZExtValue());
677 Known.Zero |= RHSKnown.One;
678 RHSKnown.Zero.lshrInPlace(C->getZExtValue());
679 Known.One |= RHSKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000680 // assume(v >> c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000681 } else if (match(Arg,
Craig Topper7b66ffe2017-06-24 06:24:04 +0000682 m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000683 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000684 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000685 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000686 KnownBits RHSKnown(BitWidth);
687 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000688 // For those bits in RHS that are known, we can propagate them to known
689 // bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000690 Known.Zero |= RHSKnown.Zero << C->getZExtValue();
691 Known.One |= RHSKnown.One << C->getZExtValue();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000692 // assume(~(v >> c) = a)
Craig Topper7b66ffe2017-06-24 06:24:04 +0000693 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shr(m_V, m_ConstantInt(C))),
Philip Reames00d3b272014-11-24 23:44:28 +0000694 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000695 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000696 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000697 KnownBits RHSKnown(BitWidth);
698 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000699 // For those bits in RHS that are known, we can propagate them inverted
700 // to known bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000701 Known.Zero |= RHSKnown.One << C->getZExtValue();
702 Known.One |= RHSKnown.Zero << C->getZExtValue();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000703 // assume(v >=_s c) where c is non-negative
Philip Reames00d3b272014-11-24 23:44:28 +0000704 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000705 Pred == ICmpInst::ICMP_SGE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000706 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000707 KnownBits RHSKnown(BitWidth);
708 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000709
Craig Topperca48af32017-04-29 16:43:11 +0000710 if (RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000711 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000712 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000713 }
714 // assume(v >_s c) where c is at least -1.
Philip Reames00d3b272014-11-24 23:44:28 +0000715 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000716 Pred == ICmpInst::ICMP_SGT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000717 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000718 KnownBits RHSKnown(BitWidth);
719 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000720
Craig Topperf0aeee02017-05-05 17:36:09 +0000721 if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000722 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000723 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000724 }
725 // assume(v <=_s c) where c is negative
Philip Reames00d3b272014-11-24 23:44:28 +0000726 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000727 Pred == ICmpInst::ICMP_SLE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000728 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000729 KnownBits RHSKnown(BitWidth);
730 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000731
Craig Topperca48af32017-04-29 16:43:11 +0000732 if (RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000733 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000734 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000735 }
736 // assume(v <_s c) where c is non-positive
Philip Reames00d3b272014-11-24 23:44:28 +0000737 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000738 Pred == ICmpInst::ICMP_SLT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000739 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000740 KnownBits RHSKnown(BitWidth);
741 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000742
Craig Topperf0aeee02017-05-05 17:36:09 +0000743 if (RHSKnown.isZero() || RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000744 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000745 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000746 }
747 // assume(v <=_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000748 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000749 Pred == ICmpInst::ICMP_ULE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000750 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000751 KnownBits RHSKnown(BitWidth);
752 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000753
754 // Whatever high bits in c are zero are known to be zero.
Craig Topper8df66c62017-05-12 17:20:30 +0000755 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
756 // assume(v <_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000757 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000758 Pred == ICmpInst::ICMP_ULT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000759 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000760 KnownBits RHSKnown(BitWidth);
761 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000762
763 // Whatever high bits in c are zero are known to be zero (if c is a power
764 // of 2, then one more).
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000765 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
Craig Topper8df66c62017-05-12 17:20:30 +0000766 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000767 else
Craig Topper8df66c62017-05-12 17:20:30 +0000768 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
Hal Finkel60db0582014-09-07 18:57:58 +0000769 }
770 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000771
772 // If assumptions conflict with each other or previous known bits, then we
Sanjay Patel54656ca2017-02-06 18:26:06 +0000773 // have a logical fallacy. It's possible that the assumption is not reachable,
774 // so this isn't a real bug. On the other hand, the program may have undefined
775 // behavior, or we might have a bug in the compiler. We can't assert/crash, so
776 // clear out the known bits, try to warn the user, and hope for the best.
Craig Topperb45eabc2017-04-26 16:39:58 +0000777 if (Known.Zero.intersects(Known.One)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000778 Known.resetAll();
Sanjay Patel54656ca2017-02-06 18:26:06 +0000779
780 if (Q.ORE) {
781 auto *CxtI = const_cast<Instruction *>(Q.CxtI);
782 OptimizationRemarkAnalysis ORA("value-tracking", "BadAssumption", CxtI);
783 Q.ORE->emit(ORA << "Detected conflicting code assumptions. Program may "
784 "have undefined behavior, or compiler may have "
785 "internal error.");
786 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000787 }
Hal Finkel60db0582014-09-07 18:57:58 +0000788}
789
Hal Finkelf2199b22015-10-23 20:37:08 +0000790// Compute known bits from a shift operator, including those with a
Craig Topperb45eabc2017-04-26 16:39:58 +0000791// non-constant shift amount. Known is the outputs of this function. Known2 is a
792// pre-allocated temporary with the/ same bit width as Known. KZF and KOF are
793// operator-specific functors that, given the known-zero or known-one bits
794// respectively, and a shift amount, compute the implied known-zero or known-one
795// bits of the shift operator's result respectively for that shift amount. The
796// results from calling KZF and KOF are conservatively combined for all
797// permitted shift amounts.
David Majnemer54690dc2016-08-23 20:52:00 +0000798static void computeKnownBitsFromShiftOperator(
Craig Topperb45eabc2017-04-26 16:39:58 +0000799 const Operator *I, KnownBits &Known, KnownBits &Known2,
800 unsigned Depth, const Query &Q,
David Majnemer54690dc2016-08-23 20:52:00 +0000801 function_ref<APInt(const APInt &, unsigned)> KZF,
802 function_ref<APInt(const APInt &, unsigned)> KOF) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000803 unsigned BitWidth = Known.getBitWidth();
Hal Finkelf2199b22015-10-23 20:37:08 +0000804
805 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
806 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
807
Craig Topperb45eabc2017-04-26 16:39:58 +0000808 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
809 Known.Zero = KZF(Known.Zero, ShiftAmt);
810 Known.One = KOF(Known.One, ShiftAmt);
811 // If there is conflict between Known.Zero and Known.One, this must be an
812 // overflowing left shift, so the shift result is undefined. Clear Known
813 // bits so that other code could propagate this undef.
Craig Topperf0aeee02017-05-05 17:36:09 +0000814 if ((Known.Zero & Known.One) != 0)
815 Known.resetAll();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +0000816
Hal Finkelf2199b22015-10-23 20:37:08 +0000817 return;
818 }
819
Craig Topperb45eabc2017-04-26 16:39:58 +0000820 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000821
Oliver Stannard06204112017-03-14 10:13:17 +0000822 // If the shift amount could be greater than or equal to the bit-width of the LHS, the
823 // value could be undef, so we don't know anything about it.
Craig Topperb45eabc2017-04-26 16:39:58 +0000824 if ((~Known.Zero).uge(BitWidth)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000825 Known.resetAll();
Oliver Stannard06204112017-03-14 10:13:17 +0000826 return;
827 }
828
Craig Topperb45eabc2017-04-26 16:39:58 +0000829 // Note: We cannot use Known.Zero.getLimitedValue() here, because if
Hal Finkelf2199b22015-10-23 20:37:08 +0000830 // BitWidth > 64 and any upper bits are known, we'll end up returning the
831 // limit value (which implies all bits are known).
Craig Topperb45eabc2017-04-26 16:39:58 +0000832 uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
833 uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
Hal Finkelf2199b22015-10-23 20:37:08 +0000834
835 // It would be more-clearly correct to use the two temporaries for this
836 // calculation. Reusing the APInts here to prevent unnecessary allocations.
Craig Topperf0aeee02017-05-05 17:36:09 +0000837 Known.resetAll();
Hal Finkelf2199b22015-10-23 20:37:08 +0000838
James Molloy493e57d2015-10-26 14:10:46 +0000839 // If we know the shifter operand is nonzero, we can sometimes infer more
840 // known bits. However this is expensive to compute, so be lazy about it and
841 // only compute it when absolutely necessary.
842 Optional<bool> ShifterOperandIsNonZero;
843
Hal Finkelf2199b22015-10-23 20:37:08 +0000844 // Early exit if we can't constrain any well-defined shift amount.
Craig Topperf93b7b12017-06-14 17:04:59 +0000845 if (!(ShiftAmtKZ & (PowerOf2Ceil(BitWidth) - 1)) &&
846 !(ShiftAmtKO & (PowerOf2Ceil(BitWidth) - 1))) {
James Molloy493e57d2015-10-26 14:10:46 +0000847 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000848 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000849 if (!*ShifterOperandIsNonZero)
850 return;
851 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000852
Craig Topperb45eabc2017-04-26 16:39:58 +0000853 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000854
Craig Topperb45eabc2017-04-26 16:39:58 +0000855 Known.Zero.setAllBits();
856 Known.One.setAllBits();
Hal Finkelf2199b22015-10-23 20:37:08 +0000857 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
858 // Combine the shifted known input bits only for those shift amounts
859 // compatible with its known constraints.
860 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
861 continue;
862 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
863 continue;
James Molloy493e57d2015-10-26 14:10:46 +0000864 // If we know the shifter is nonzero, we may be able to infer more known
865 // bits. This check is sunk down as far as possible to avoid the expensive
866 // call to isKnownNonZero if the cheaper checks above fail.
867 if (ShiftAmt == 0) {
868 if (!ShifterOperandIsNonZero.hasValue())
869 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000870 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000871 if (*ShifterOperandIsNonZero)
872 continue;
873 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000874
Craig Topperb45eabc2017-04-26 16:39:58 +0000875 Known.Zero &= KZF(Known2.Zero, ShiftAmt);
876 Known.One &= KOF(Known2.One, ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +0000877 }
878
879 // If there are no compatible shift amounts, then we've proven that the shift
880 // amount must be >= the BitWidth, and the result is undefined. We could
881 // return anything we'd like, but we need to make sure the sets of known bits
882 // stay disjoint (it should be better for some other code to actually
883 // propagate the undef than to pick a value here using known bits).
Craig Topperf0aeee02017-05-05 17:36:09 +0000884 if (Known.Zero.intersects(Known.One))
885 Known.resetAll();
Hal Finkelf2199b22015-10-23 20:37:08 +0000886}
887
Craig Topperb45eabc2017-04-26 16:39:58 +0000888static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known,
889 unsigned Depth, const Query &Q) {
890 unsigned BitWidth = Known.getBitWidth();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000891
Craig Topperb45eabc2017-04-26 16:39:58 +0000892 KnownBits Known2(Known);
Dan Gohman80ca01c2009-07-17 20:47:02 +0000893 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +0000894 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +0000895 case Instruction::Load:
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000896 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +0000897 computeKnownBitsFromRangeMetadata(*MD, Known);
Jay Foad5a29c362014-05-15 12:12:55 +0000898 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000899 case Instruction::And: {
900 // If either the LHS or the RHS are Zero, the result is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +0000901 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
902 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000903
Chris Lattner965c7692008-06-02 01:18:21 +0000904 // Output known-1 bits are only known if set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000905 Known.One &= Known2.One;
Chris Lattner965c7692008-06-02 01:18:21 +0000906 // Output known-0 are known to be clear if zero in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000907 Known.Zero |= Known2.Zero;
Philip Reames2d858742015-11-10 18:46:14 +0000908
909 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
910 // here we handle the more general case of adding any odd number by
911 // matching the form add(x, add(x, y)) where y is odd.
912 // TODO: This could be generalized to clearing any bit set in y where the
913 // following bit is known to be unset in y.
914 Value *Y = nullptr;
Craig Topperb45eabc2017-04-26 16:39:58 +0000915 if (!Known.Zero[0] && !Known.One[0] &&
Craig Toppera80f2042017-04-13 19:04:45 +0000916 (match(I->getOperand(0), m_Add(m_Specific(I->getOperand(1)),
917 m_Value(Y))) ||
918 match(I->getOperand(1), m_Add(m_Specific(I->getOperand(0)),
919 m_Value(Y))))) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000920 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000921 computeKnownBits(Y, Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000922 if (Known2.countMinTrailingOnes() > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +0000923 Known.Zero.setBit(0);
Philip Reames2d858742015-11-10 18:46:14 +0000924 }
Jay Foad5a29c362014-05-15 12:12:55 +0000925 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000926 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000927 case Instruction::Or:
Craig Topperb45eabc2017-04-26 16:39:58 +0000928 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
929 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000930
Chris Lattner965c7692008-06-02 01:18:21 +0000931 // Output known-0 bits are only known if clear in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000932 Known.Zero &= Known2.Zero;
Chris Lattner965c7692008-06-02 01:18:21 +0000933 // Output known-1 are known to be set if set in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000934 Known.One |= Known2.One;
Jay Foad5a29c362014-05-15 12:12:55 +0000935 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000936 case Instruction::Xor: {
Craig Topperb45eabc2017-04-26 16:39:58 +0000937 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
938 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000939
Chris Lattner965c7692008-06-02 01:18:21 +0000940 // Output known-0 bits are known if clear or set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000941 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
Chris Lattner965c7692008-06-02 01:18:21 +0000942 // Output known-1 are known to be set if set in only one of the LHS, RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000943 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
944 Known.Zero = std::move(KnownZeroOut);
Jay Foad5a29c362014-05-15 12:12:55 +0000945 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000946 }
947 case Instruction::Mul: {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000948 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Craig Topperb45eabc2017-04-26 16:39:58 +0000949 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, Known,
950 Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000951 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000952 }
953 case Instruction::UDiv: {
954 // For the purposes of computing leading zeros we can conservatively
955 // treat a udiv as a logical right shift by the power of 2 known to
956 // be less than the denominator.
Craig Topperb45eabc2017-04-26 16:39:58 +0000957 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000958 unsigned LeadZ = Known2.countMinLeadingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +0000959
Craig Topperf0aeee02017-05-05 17:36:09 +0000960 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000961 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000962 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
963 if (RHSMaxLeadingZeros != BitWidth)
964 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
Chris Lattner965c7692008-06-02 01:18:21 +0000965
Craig Topperb45eabc2017-04-26 16:39:58 +0000966 Known.Zero.setHighBits(LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +0000967 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000968 }
David Majnemera19d0f22016-08-06 08:16:00 +0000969 case Instruction::Select: {
Craig Toppere953dec2017-04-13 20:39:37 +0000970 const Value *LHS, *RHS;
David Majnemera19d0f22016-08-06 08:16:00 +0000971 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
972 if (SelectPatternResult::isMinOrMax(SPF)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000973 computeKnownBits(RHS, Known, Depth + 1, Q);
974 computeKnownBits(LHS, Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +0000975 } else {
Craig Topperb45eabc2017-04-26 16:39:58 +0000976 computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
977 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +0000978 }
979
980 unsigned MaxHighOnes = 0;
981 unsigned MaxHighZeros = 0;
982 if (SPF == SPF_SMAX) {
983 // If both sides are negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +0000984 if (Known.isNegative() && Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000985 // We can derive a lower bound on the result by taking the max of the
986 // leading one bits.
Craig Topper8df66c62017-05-12 17:20:30 +0000987 MaxHighOnes =
988 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +0000989 // If either side is non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +0000990 else if (Known.isNonNegative() || Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000991 MaxHighZeros = 1;
992 } else if (SPF == SPF_SMIN) {
993 // If both sides are non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +0000994 if (Known.isNonNegative() && Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000995 // We can derive an upper bound on the result by taking the max of the
996 // leading zero bits.
Craig Topper8df66c62017-05-12 17:20:30 +0000997 MaxHighZeros = std::max(Known.countMinLeadingZeros(),
998 Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +0000999 // If either side is negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +00001000 else if (Known.isNegative() || Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001001 MaxHighOnes = 1;
1002 } else if (SPF == SPF_UMAX) {
1003 // We can derive a lower bound on the result by taking the max of the
1004 // leading one bits.
1005 MaxHighOnes =
Craig Topper8df66c62017-05-12 17:20:30 +00001006 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001007 } else if (SPF == SPF_UMIN) {
1008 // We can derive an upper bound on the result by taking the max of the
1009 // leading zero bits.
1010 MaxHighZeros =
Craig Topper8df66c62017-05-12 17:20:30 +00001011 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +00001012 }
1013
Chris Lattner965c7692008-06-02 01:18:21 +00001014 // Only known if known in both the LHS and RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001015 Known.One &= Known2.One;
1016 Known.Zero &= Known2.Zero;
David Majnemera19d0f22016-08-06 08:16:00 +00001017 if (MaxHighOnes > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001018 Known.One.setHighBits(MaxHighOnes);
David Majnemera19d0f22016-08-06 08:16:00 +00001019 if (MaxHighZeros > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001020 Known.Zero.setHighBits(MaxHighZeros);
Jay Foad5a29c362014-05-15 12:12:55 +00001021 break;
David Majnemera19d0f22016-08-06 08:16:00 +00001022 }
Chris Lattner965c7692008-06-02 01:18:21 +00001023 case Instruction::FPTrunc:
1024 case Instruction::FPExt:
1025 case Instruction::FPToUI:
1026 case Instruction::FPToSI:
1027 case Instruction::SIToFP:
1028 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +00001029 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +00001030 case Instruction::PtrToInt:
1031 case Instruction::IntToPtr:
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001032 // Fall through and handle them the same as zext/trunc.
1033 LLVM_FALLTHROUGH;
Chris Lattner965c7692008-06-02 01:18:21 +00001034 case Instruction::ZExt:
1035 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +00001036 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +00001037
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001038 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +00001039 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1040 // which fall through here.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001041 SrcBitWidth = Q.DL.getTypeSizeInBits(SrcTy->getScalarType());
Nadav Rotem15198e92012-10-26 17:17:05 +00001042
1043 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Craig Topperd938fd12017-05-03 22:07:25 +00001044 Known = Known.zextOrTrunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001045 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Craig Topperd938fd12017-05-03 22:07:25 +00001046 Known = Known.zextOrTrunc(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +00001047 // Any top bits are known to be zero.
1048 if (BitWidth > SrcBitWidth)
Craig Topperb45eabc2017-04-26 16:39:58 +00001049 Known.Zero.setBitsFrom(SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001050 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001051 }
1052 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +00001053 Type *SrcTy = I->getOperand(0)->getType();
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001054 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattneredb84072009-07-02 16:04:08 +00001055 // TODO: For now, not handling conversions like:
1056 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +00001057 !I->getType()->isVectorTy()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001058 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +00001059 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001060 }
1061 break;
1062 }
1063 case Instruction::SExt: {
1064 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001065 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +00001066
Craig Topperd938fd12017-05-03 22:07:25 +00001067 Known = Known.trunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001068 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001069 // If the sign bit of the input is known set or clear, then we know the
1070 // top bits of the result.
Craig Topperd938fd12017-05-03 22:07:25 +00001071 Known = Known.sext(BitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001072 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001073 }
Hal Finkelf2199b22015-10-23 20:37:08 +00001074 case Instruction::Shl: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001075 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001076 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Craig Topperd73c6b42017-03-23 07:06:39 +00001077 auto KZF = [NSW](const APInt &KnownZero, unsigned ShiftAmt) {
1078 APInt KZResult = KnownZero << ShiftAmt;
1079 KZResult.setLowBits(ShiftAmt); // Low bits known 0.
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001080 // If this shift has "nsw" keyword, then the result is either a poison
1081 // value or has the same sign bit as the first operand.
Craig Topperd23004c2017-04-17 16:38:20 +00001082 if (NSW && KnownZero.isSignBitSet())
Craig Topperd73c6b42017-03-23 07:06:39 +00001083 KZResult.setSignBit();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001084 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001085 };
1086
Craig Topperd73c6b42017-03-23 07:06:39 +00001087 auto KOF = [NSW](const APInt &KnownOne, unsigned ShiftAmt) {
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001088 APInt KOResult = KnownOne << ShiftAmt;
Craig Topperd23004c2017-04-17 16:38:20 +00001089 if (NSW && KnownOne.isSignBitSet())
Craig Topperd73c6b42017-03-23 07:06:39 +00001090 KOResult.setSignBit();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001091 return KOResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001092 };
1093
Craig Topperb45eabc2017-04-26 16:39:58 +00001094 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001095 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001096 }
1097 case Instruction::LShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001098 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Craig Topperfc947bc2017-04-18 17:14:21 +00001099 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1100 APInt KZResult = KnownZero.lshr(ShiftAmt);
1101 // High bits known zero.
1102 KZResult.setHighBits(ShiftAmt);
1103 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001104 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001105
Malcolm Parsons17d266b2017-01-13 17:12:16 +00001106 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
Craig Topper885fa122017-03-31 20:01:16 +00001107 return KnownOne.lshr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001108 };
1109
Craig Topperb45eabc2017-04-26 16:39:58 +00001110 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001111 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001112 }
1113 case Instruction::AShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001114 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Malcolm Parsons17d266b2017-01-13 17:12:16 +00001115 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
Craig Topper885fa122017-03-31 20:01:16 +00001116 return KnownZero.ashr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001117 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001118
Malcolm Parsons17d266b2017-01-13 17:12:16 +00001119 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
Craig Topper885fa122017-03-31 20:01:16 +00001120 return KnownOne.ashr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001121 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001122
Craig Topperb45eabc2017-04-26 16:39:58 +00001123 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001124 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001125 }
Chris Lattner965c7692008-06-02 01:18:21 +00001126 case Instruction::Sub: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001127 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001128 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001129 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001130 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001131 }
Chris Lattner965c7692008-06-02 01:18:21 +00001132 case Instruction::Add: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001133 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001134 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001135 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001136 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001137 }
1138 case Instruction::SRem:
1139 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001140 APInt RA = Rem->getValue().abs();
1141 if (RA.isPowerOf2()) {
1142 APInt LowBits = RA - 1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001143 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001144
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001145 // The low bits of the first operand are unchanged by the srem.
Craig Topperb45eabc2017-04-26 16:39:58 +00001146 Known.Zero = Known2.Zero & LowBits;
1147 Known.One = Known2.One & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001148
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001149 // If the first operand is non-negative or has all low bits zero, then
1150 // the upper bits are all zero.
Craig Topperca48af32017-04-29 16:43:11 +00001151 if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
Craig Topperb45eabc2017-04-26 16:39:58 +00001152 Known.Zero |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001153
1154 // If the first operand is negative and not all low bits are zero, then
1155 // the upper bits are all one.
Craig Topperca48af32017-04-29 16:43:11 +00001156 if (Known2.isNegative() && LowBits.intersects(Known2.One))
Craig Topperb45eabc2017-04-26 16:39:58 +00001157 Known.One |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001158
Craig Topperb45eabc2017-04-26 16:39:58 +00001159 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Craig Topperda886c62017-04-16 21:46:12 +00001160 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001161 }
1162 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001163
1164 // The sign bit is the LHS's sign bit, except when the result of the
1165 // remainder is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +00001166 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topperda886c62017-04-16 21:46:12 +00001167 // If it's known zero, our sign bit is also zero.
Craig Topperca48af32017-04-29 16:43:11 +00001168 if (Known2.isNonNegative())
1169 Known.makeNonNegative();
Nick Lewyckye4679792011-03-07 01:50:10 +00001170
Chris Lattner965c7692008-06-02 01:18:21 +00001171 break;
1172 case Instruction::URem: {
1173 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001174 const APInt &RA = Rem->getValue();
Chris Lattner965c7692008-06-02 01:18:21 +00001175 if (RA.isPowerOf2()) {
1176 APInt LowBits = (RA - 1);
Craig Topperb45eabc2017-04-26 16:39:58 +00001177 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1178 Known.Zero |= ~LowBits;
1179 Known.One &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001180 break;
1181 }
1182 }
1183
1184 // Since the result is less than or equal to either operand, any leading
1185 // zero bits in either operand must also exist in the result.
Craig Topperb45eabc2017-04-26 16:39:58 +00001186 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1187 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001188
Craig Topper8df66c62017-05-12 17:20:30 +00001189 unsigned Leaders =
1190 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topperf0aeee02017-05-05 17:36:09 +00001191 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001192 Known.Zero.setHighBits(Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001193 break;
1194 }
1195
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001196 case Instruction::Alloca: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001197 const AllocaInst *AI = cast<AllocaInst>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001198 unsigned Align = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001199 if (Align == 0)
Eduard Burtescu90c44492016-01-18 00:10:01 +00001200 Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001201
Chris Lattner965c7692008-06-02 01:18:21 +00001202 if (Align > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001203 Known.Zero.setLowBits(countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001204 break;
1205 }
1206 case Instruction::GetElementPtr: {
1207 // Analyze all of the subscripts of this getelementptr instruction
1208 // to determine if we can prove known low zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001209 KnownBits LocalKnown(BitWidth);
1210 computeKnownBits(I->getOperand(0), LocalKnown, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001211 unsigned TrailZ = LocalKnown.countMinTrailingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001212
1213 gep_type_iterator GTI = gep_type_begin(I);
1214 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1215 Value *Index = I->getOperand(i);
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001216 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chris Lattner965c7692008-06-02 01:18:21 +00001217 // Handle struct member offset arithmetic.
Matt Arsenault74742a12013-08-19 21:43:16 +00001218
1219 // Handle case when index is vector zeroinitializer
1220 Constant *CIndex = cast<Constant>(Index);
1221 if (CIndex->isZeroValue())
1222 continue;
1223
1224 if (CIndex->getType()->isVectorTy())
1225 Index = CIndex->getSplatValue();
1226
Chris Lattner965c7692008-06-02 01:18:21 +00001227 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001228 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001229 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001230 TrailZ = std::min<unsigned>(TrailZ,
1231 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001232 } else {
1233 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001234 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001235 if (!IndexedTy->isSized()) {
1236 TrailZ = 0;
1237 break;
1238 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001239 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001240 uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
Craig Topperb45eabc2017-04-26 16:39:58 +00001241 LocalKnown.Zero = LocalKnown.One = APInt(GEPOpiBits, 0);
1242 computeKnownBits(Index, LocalKnown, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001243 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001244 unsigned(countTrailingZeros(TypeSize) +
Craig Topper8df66c62017-05-12 17:20:30 +00001245 LocalKnown.countMinTrailingZeros()));
Chris Lattner965c7692008-06-02 01:18:21 +00001246 }
1247 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001248
Craig Topperb45eabc2017-04-26 16:39:58 +00001249 Known.Zero.setLowBits(TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001250 break;
1251 }
1252 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001253 const PHINode *P = cast<PHINode>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001254 // Handle the case of a simple two-predecessor recurrence PHI.
1255 // There's a lot more that could theoretically be done here, but
1256 // this is sufficient to catch some interesting cases.
1257 if (P->getNumIncomingValues() == 2) {
1258 for (unsigned i = 0; i != 2; ++i) {
1259 Value *L = P->getIncomingValue(i);
1260 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001261 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001262 if (!LU)
1263 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001264 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001265 // Check for operations that have the property that if
1266 // both their operands have low zero bits, the result
Artur Pilipenkobc76eca2016-08-22 13:14:07 +00001267 // will have low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001268 if (Opcode == Instruction::Add ||
1269 Opcode == Instruction::Sub ||
1270 Opcode == Instruction::And ||
1271 Opcode == Instruction::Or ||
1272 Opcode == Instruction::Mul) {
1273 Value *LL = LU->getOperand(0);
1274 Value *LR = LU->getOperand(1);
1275 // Find a recurrence.
1276 if (LL == I)
1277 L = LR;
1278 else if (LR == I)
1279 L = LL;
1280 else
1281 break;
1282 // Ok, we have a PHI of the form L op= R. Check for low
1283 // zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001284 computeKnownBits(R, Known2, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001285
1286 // We need to take the minimum number of known bits
Craig Topperb45eabc2017-04-26 16:39:58 +00001287 KnownBits Known3(Known);
1288 computeKnownBits(L, Known3, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001289
Craig Topper8df66c62017-05-12 17:20:30 +00001290 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1291 Known3.countMinTrailingZeros()));
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001292
Chandler Carruth37c7b082017-08-14 07:03:24 +00001293 if (DontImproveNonNegativePhiBits)
1294 break;
1295
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001296 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU);
1297 if (OverflowOp && OverflowOp->hasNoSignedWrap()) {
1298 // If initial value of recurrence is nonnegative, and we are adding
1299 // a nonnegative number with nsw, the result can only be nonnegative
1300 // or poison value regardless of the number of times we execute the
1301 // add in phi recurrence. If initial value is negative and we are
1302 // adding a negative number with nsw, the result can only be
1303 // negative or poison value. Similar arguments apply to sub and mul.
1304 //
1305 // (add non-negative, non-negative) --> non-negative
1306 // (add negative, negative) --> negative
1307 if (Opcode == Instruction::Add) {
Craig Topperca48af32017-04-29 16:43:11 +00001308 if (Known2.isNonNegative() && Known3.isNonNegative())
1309 Known.makeNonNegative();
1310 else if (Known2.isNegative() && Known3.isNegative())
1311 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001312 }
1313
1314 // (sub nsw non-negative, negative) --> non-negative
1315 // (sub nsw negative, non-negative) --> negative
1316 else if (Opcode == Instruction::Sub && LL == I) {
Craig Topperca48af32017-04-29 16:43:11 +00001317 if (Known2.isNonNegative() && Known3.isNegative())
1318 Known.makeNonNegative();
1319 else if (Known2.isNegative() && Known3.isNonNegative())
1320 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001321 }
1322
1323 // (mul nsw non-negative, non-negative) --> non-negative
Craig Topperca48af32017-04-29 16:43:11 +00001324 else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1325 Known3.isNonNegative())
1326 Known.makeNonNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001327 }
1328
Chris Lattner965c7692008-06-02 01:18:21 +00001329 break;
1330 }
1331 }
1332 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001333
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001334 // Unreachable blocks may have zero-operand PHI nodes.
1335 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001336 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001337
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001338 // Otherwise take the unions of the known bit sets of the operands,
1339 // taking conservative care to avoid excessive recursion.
Craig Topperb45eabc2017-04-26 16:39:58 +00001340 if (Depth < MaxDepth - 1 && !Known.Zero && !Known.One) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001341 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001342 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001343 break;
1344
Craig Topperb45eabc2017-04-26 16:39:58 +00001345 Known.Zero.setAllBits();
1346 Known.One.setAllBits();
Pete Cooper833f34d2015-05-12 20:05:31 +00001347 for (Value *IncValue : P->incoming_values()) {
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001348 // Skip direct self references.
Pete Cooper833f34d2015-05-12 20:05:31 +00001349 if (IncValue == P) continue;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001350
Craig Topperb45eabc2017-04-26 16:39:58 +00001351 Known2 = KnownBits(BitWidth);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001352 // Recurse, but cap the recursion to one level, because we don't
1353 // want to waste time spinning around in loops.
Craig Topperb45eabc2017-04-26 16:39:58 +00001354 computeKnownBits(IncValue, Known2, MaxDepth - 1, Q);
1355 Known.Zero &= Known2.Zero;
1356 Known.One &= Known2.One;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001357 // If all bits have been ruled out, there's no need to check
1358 // more operands.
Craig Topperb45eabc2017-04-26 16:39:58 +00001359 if (!Known.Zero && !Known.One)
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001360 break;
1361 }
1362 }
Chris Lattner965c7692008-06-02 01:18:21 +00001363 break;
1364 }
1365 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001366 case Instruction::Invoke:
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001367 // If range metadata is attached to this call, set known bits from that,
1368 // and then intersect with known bits based on other properties of the
1369 // function.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001370 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +00001371 computeKnownBitsFromRangeMetadata(*MD, Known);
Pete Cooper35b00d52016-08-13 01:05:32 +00001372 if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001373 computeKnownBits(RV, Known2, Depth + 1, Q);
1374 Known.Zero |= Known2.Zero;
1375 Known.One |= Known2.One;
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001376 }
Pete Cooper35b00d52016-08-13 01:05:32 +00001377 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001378 switch (II->getIntrinsicID()) {
1379 default: break;
Chad Rosier85204292017-01-17 17:23:51 +00001380 case Intrinsic::bitreverse:
Craig Topperb45eabc2017-04-26 16:39:58 +00001381 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1382 Known.Zero |= Known2.Zero.reverseBits();
1383 Known.One |= Known2.One.reverseBits();
Chad Rosier85204292017-01-17 17:23:51 +00001384 break;
Philip Reames675418e2015-10-06 20:20:45 +00001385 case Intrinsic::bswap:
Craig Topperb45eabc2017-04-26 16:39:58 +00001386 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1387 Known.Zero |= Known2.Zero.byteSwap();
1388 Known.One |= Known2.One.byteSwap();
Philip Reames675418e2015-10-06 20:20:45 +00001389 break;
Craig Topper868813f2017-05-08 17:22:34 +00001390 case Intrinsic::ctlz: {
1391 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1392 // If we have a known 1, its position is our upper bound.
1393 unsigned PossibleLZ = Known2.One.countLeadingZeros();
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001394 // If this call is undefined for 0, the result will be less than 2^n.
1395 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
Craig Topper868813f2017-05-08 17:22:34 +00001396 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1397 unsigned LowBits = Log2_32(PossibleLZ)+1;
1398 Known.Zero.setBitsFrom(LowBits);
1399 break;
1400 }
1401 case Intrinsic::cttz: {
1402 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1403 // If we have a known 1, its position is our upper bound.
1404 unsigned PossibleTZ = Known2.One.countTrailingZeros();
1405 // If this call is undefined for 0, the result will be less than 2^n.
1406 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1407 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1408 unsigned LowBits = Log2_32(PossibleTZ)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001409 Known.Zero.setBitsFrom(LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001410 break;
1411 }
1412 case Intrinsic::ctpop: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001413 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001414 // We can bound the space the count needs. Also, bits known to be zero
1415 // can't contribute to the population.
Craig Topper8df66c62017-05-12 17:20:30 +00001416 unsigned BitsPossiblySet = Known2.countMaxPopulation();
Craig Topper66df10f2017-04-14 06:43:34 +00001417 unsigned LowBits = Log2_32(BitsPossiblySet)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001418 Known.Zero.setBitsFrom(LowBits);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001419 // TODO: we could bound KnownOne using the lower bound on the number
1420 // of bits which might be set provided by popcnt KnownOne2.
Chris Lattner965c7692008-06-02 01:18:21 +00001421 break;
1422 }
Chad Rosierb3628842011-05-26 23:13:19 +00001423 case Intrinsic::x86_sse42_crc32_64_64:
Craig Topperb45eabc2017-04-26 16:39:58 +00001424 Known.Zero.setBitsFrom(32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001425 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001426 }
1427 }
1428 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00001429 case Instruction::ExtractElement:
1430 // Look through extract element. At the moment we keep this simple and skip
1431 // tracking the specific element. But at least we might find information
1432 // valid for all elements of the vector (for example if vector is sign
1433 // extended, shifted, etc).
Craig Topperb45eabc2017-04-26 16:39:58 +00001434 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Bjorn Pettersson39616032016-10-06 09:56:21 +00001435 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001436 case Instruction::ExtractValue:
1437 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001438 const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001439 if (EVI->getNumIndices() != 1) break;
1440 if (EVI->getIndices()[0] == 0) {
1441 switch (II->getIntrinsicID()) {
1442 default: break;
1443 case Intrinsic::uadd_with_overflow:
1444 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001445 computeKnownBitsAddSub(true, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001446 II->getArgOperand(1), false, Known, Known2,
1447 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001448 break;
1449 case Intrinsic::usub_with_overflow:
1450 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001451 computeKnownBitsAddSub(false, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001452 II->getArgOperand(1), false, Known, Known2,
1453 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001454 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001455 case Intrinsic::umul_with_overflow:
1456 case Intrinsic::smul_with_overflow:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001457 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
Craig Topperb45eabc2017-04-26 16:39:58 +00001458 Known, Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001459 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001460 }
1461 }
1462 }
Chris Lattner965c7692008-06-02 01:18:21 +00001463 }
Jingyue Wu12b0c282015-06-15 05:46:29 +00001464}
1465
1466/// Determine which bits of V are known to be either zero or one and return
Craig Topper6e11a052017-05-08 16:22:48 +00001467/// them.
1468KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1469 KnownBits Known(getBitWidth(V->getType(), Q.DL));
1470 computeKnownBits(V, Known, Depth, Q);
1471 return Known;
1472}
1473
1474/// Determine which bits of V are known to be either zero or one and return
Craig Topperb45eabc2017-04-26 16:39:58 +00001475/// them in the Known bit set.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001476///
1477/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1478/// we cannot optimize based on the assumption that it is zero without changing
1479/// it to be an explicit zero. If we don't change it to zero, other code could
1480/// optimized based on the contradictory assumption that it is non-zero.
1481/// Because instcombine aggressively folds operations with undef args anyway,
1482/// this won't lose us code quality.
1483///
1484/// This function is defined on values with integer type, values with pointer
1485/// type, and vectors of integers. In the case
1486/// where V is a vector, known zero, and known one values are the
1487/// same width as the vector element, and the bit is set only if it is true
1488/// for all of the elements in the vector.
Craig Topperb45eabc2017-04-26 16:39:58 +00001489void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
1490 const Query &Q) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001491 assert(V && "No Value?");
1492 assert(Depth <= MaxDepth && "Limit Search Depth");
Craig Topperb45eabc2017-04-26 16:39:58 +00001493 unsigned BitWidth = Known.getBitWidth();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001494
Craig Topperfde47232017-07-09 07:04:03 +00001495 assert((V->getType()->isIntOrIntVectorTy(BitWidth) ||
Craig Topper95d23472017-07-09 07:04:00 +00001496 V->getType()->isPtrOrPtrVectorTy()) &&
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001497 "Not integer or pointer type!");
Craig Topperfde47232017-07-09 07:04:03 +00001498 assert(Q.DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth &&
Craig Topperb45eabc2017-04-26 16:39:58 +00001499 "V and Known should have same BitWidth");
Craig Topperd73c6b42017-03-23 07:06:39 +00001500 (void)BitWidth;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001501
Sanjay Patelc96f6db2016-09-16 21:20:36 +00001502 const APInt *C;
1503 if (match(V, m_APInt(C))) {
1504 // We know all of the bits for a scalar constant or a splat vector constant!
Craig Topperb45eabc2017-04-26 16:39:58 +00001505 Known.One = *C;
1506 Known.Zero = ~Known.One;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001507 return;
1508 }
1509 // Null and aggregate-zero are all-zeros.
Sanjay Patele8dc0902016-05-23 17:57:54 +00001510 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001511 Known.setAllZero();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001512 return;
1513 }
1514 // Handle a constant vector by taking the intersection of the known bits of
David Majnemer3918cdd2016-05-04 06:13:33 +00001515 // each element.
Pete Cooper35b00d52016-08-13 01:05:32 +00001516 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001517 // We know that CDS must be a vector of integers. Take the intersection of
1518 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001519 Known.Zero.setAllBits(); Known.One.setAllBits();
Craig Topper9c932d32017-04-25 16:48:03 +00001520 APInt Elt(BitWidth, 0);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001521 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1522 Elt = CDS->getElementAsInteger(i);
Craig Topperb45eabc2017-04-26 16:39:58 +00001523 Known.Zero &= ~Elt;
1524 Known.One &= Elt;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001525 }
1526 return;
1527 }
1528
Pete Cooper35b00d52016-08-13 01:05:32 +00001529 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
David Majnemer3918cdd2016-05-04 06:13:33 +00001530 // We know that CV must be a vector of integers. Take the intersection of
1531 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001532 Known.Zero.setAllBits(); Known.One.setAllBits();
1533 APInt Elt(BitWidth, 0);
David Majnemer3918cdd2016-05-04 06:13:33 +00001534 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1535 Constant *Element = CV->getAggregateElement(i);
1536 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1537 if (!ElementCI) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001538 Known.resetAll();
David Majnemer3918cdd2016-05-04 06:13:33 +00001539 return;
1540 }
1541 Elt = ElementCI->getValue();
Craig Topperb45eabc2017-04-26 16:39:58 +00001542 Known.Zero &= ~Elt;
1543 Known.One &= Elt;
David Majnemer3918cdd2016-05-04 06:13:33 +00001544 }
1545 return;
1546 }
1547
Jingyue Wu12b0c282015-06-15 05:46:29 +00001548 // Start out not knowing anything.
Craig Topperf0aeee02017-05-05 17:36:09 +00001549 Known.resetAll();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001550
Duncan P. N. Exon Smithb1b208a2016-09-24 20:42:02 +00001551 // We can't imply anything about undefs.
1552 if (isa<UndefValue>(V))
1553 return;
1554
1555 // There's no point in looking through other users of ConstantData for
1556 // assumptions. Confirm that we've handled them all.
1557 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1558
Jingyue Wu12b0c282015-06-15 05:46:29 +00001559 // Limit search depth.
1560 // All recursive calls that increase depth must come after this.
1561 if (Depth == MaxDepth)
1562 return;
1563
1564 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1565 // the bits of its aliasee.
Pete Cooper35b00d52016-08-13 01:05:32 +00001566 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001567 if (!GA->isInterposable())
Craig Topperb45eabc2017-04-26 16:39:58 +00001568 computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001569 return;
1570 }
1571
Pete Cooper35b00d52016-08-13 01:05:32 +00001572 if (const Operator *I = dyn_cast<Operator>(V))
Craig Topperb45eabc2017-04-26 16:39:58 +00001573 computeKnownBitsFromOperator(I, Known, Depth, Q);
Sanjay Patela67559c2015-09-25 20:12:43 +00001574
Craig Topperb45eabc2017-04-26 16:39:58 +00001575 // Aligned pointers have trailing zeros - refine Known.Zero set
Artur Pilipenko029d8532015-09-30 11:55:45 +00001576 if (V->getType()->isPointerTy()) {
Artur Pilipenkoae51afc2016-02-24 12:25:10 +00001577 unsigned Align = V->getPointerAlignment(Q.DL);
Artur Pilipenko029d8532015-09-30 11:55:45 +00001578 if (Align)
Craig Topperb45eabc2017-04-26 16:39:58 +00001579 Known.Zero.setLowBits(countTrailingZeros(Align));
Artur Pilipenko029d8532015-09-30 11:55:45 +00001580 }
1581
Craig Topperb45eabc2017-04-26 16:39:58 +00001582 // computeKnownBitsFromAssume strictly refines Known.
1583 // Therefore, we run them after computeKnownBitsFromOperator.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001584
1585 // Check whether a nearby assume intrinsic can determine some known bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001586 computeKnownBitsFromAssume(V, Known, Depth, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001587
Craig Topperb45eabc2017-04-26 16:39:58 +00001588 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001589}
1590
Sanjay Patelaee84212014-11-04 16:27:42 +00001591/// Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001592/// bit set when defined. For vectors return true if every element is known to
Sanjay Patelaee84212014-11-04 16:27:42 +00001593/// be a power of two when defined. Supports values with integer or pointer
Duncan Sandsd3951082011-01-25 09:38:29 +00001594/// types and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001595bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001596 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00001597 assert(Depth <= MaxDepth && "Limit Search Depth");
1598
Pete Cooper35b00d52016-08-13 01:05:32 +00001599 if (const Constant *C = dyn_cast<Constant>(V)) {
Duncan Sandsba286d72011-10-26 20:55:21 +00001600 if (C->isNullValue())
1601 return OrZero;
Sanjay Patele2e89ef2016-05-22 15:41:53 +00001602
1603 const APInt *ConstIntOrConstSplatInt;
1604 if (match(C, m_APInt(ConstIntOrConstSplatInt)))
1605 return ConstIntOrConstSplatInt->isPowerOf2();
Duncan Sandsba286d72011-10-26 20:55:21 +00001606 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001607
1608 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1609 // it is shifted off the end then the result is undefined.
1610 if (match(V, m_Shl(m_One(), m_Value())))
1611 return true;
1612
Craig Topperbcfd2d12017-04-20 16:56:25 +00001613 // (signmask) >>l X is clearly a power of two if the one is not shifted off
1614 // the bottom. If it is shifted off the bottom then the result is undefined.
1615 if (match(V, m_LShr(m_SignMask(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001616 return true;
1617
1618 // The remaining tests are all recursive, so bail out if we hit the limit.
1619 if (Depth++ == MaxDepth)
1620 return false;
1621
Craig Topper9f008862014-04-15 04:59:12 +00001622 Value *X = nullptr, *Y = nullptr;
Sanjay Patel41160c22015-12-30 22:40:52 +00001623 // A shift left or a logical shift right of a power of two is a power of two
1624 // or zero.
Duncan Sands985ba632011-10-28 18:30:05 +00001625 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
Sanjay Patel41160c22015-12-30 22:40:52 +00001626 match(V, m_LShr(m_Value(X), m_Value()))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001627 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
Duncan Sands985ba632011-10-28 18:30:05 +00001628
Pete Cooper35b00d52016-08-13 01:05:32 +00001629 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001630 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001631
Pete Cooper35b00d52016-08-13 01:05:32 +00001632 if (const SelectInst *SI = dyn_cast<SelectInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001633 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1634 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
Duncan Sandsba286d72011-10-26 20:55:21 +00001635
Duncan Sandsba286d72011-10-26 20:55:21 +00001636 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1637 // A power of two and'd with anything is a power of two or zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001638 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1639 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
Duncan Sandsba286d72011-10-26 20:55:21 +00001640 return true;
1641 // X & (-X) is always a power of two or zero.
1642 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1643 return true;
1644 return false;
1645 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001646
David Majnemerb7d54092013-07-30 21:01:36 +00001647 // Adding a power-of-two or zero to the same power-of-two or zero yields
1648 // either the original power-of-two, a larger power-of-two or zero.
1649 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001650 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
David Majnemerb7d54092013-07-30 21:01:36 +00001651 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1652 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1653 match(X, m_And(m_Value(), m_Specific(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001654 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001655 return true;
1656 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1657 match(Y, m_And(m_Value(), m_Specific(X))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001658 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001659 return true;
1660
1661 unsigned BitWidth = V->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00001662 KnownBits LHSBits(BitWidth);
1663 computeKnownBits(X, LHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001664
Craig Topperb45eabc2017-04-26 16:39:58 +00001665 KnownBits RHSBits(BitWidth);
1666 computeKnownBits(Y, RHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001667 // If i8 V is a power of two or zero:
1668 // ZeroBits: 1 1 1 0 1 1 1 1
1669 // ~ZeroBits: 0 0 0 1 0 0 0 0
Craig Topperb45eabc2017-04-26 16:39:58 +00001670 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
David Majnemerb7d54092013-07-30 21:01:36 +00001671 // If OrZero isn't set, we cannot give back a zero result.
1672 // Make sure either the LHS or RHS has a bit set.
Craig Topperb45eabc2017-04-26 16:39:58 +00001673 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
David Majnemerb7d54092013-07-30 21:01:36 +00001674 return true;
1675 }
1676 }
David Majnemerbeab5672013-05-18 19:30:37 +00001677
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001678 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001679 // is a power of two only if the first operand is a power of two and not
1680 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001681 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1682 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001683 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001684 Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001685 }
1686
Duncan Sandsd3951082011-01-25 09:38:29 +00001687 return false;
1688}
1689
Chandler Carruth80d3e562012-12-07 02:08:58 +00001690/// \brief Test whether a GEP's result is known to be non-null.
1691///
1692/// Uses properties inherent in a GEP to try to determine whether it is known
1693/// to be non-null.
1694///
1695/// Currently this routine does not support vector GEPs.
Pete Cooper35b00d52016-08-13 01:05:32 +00001696static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001697 const Query &Q) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001698 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1699 return false;
1700
1701 // FIXME: Support vector-GEPs.
1702 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1703
1704 // If the base pointer is non-null, we cannot walk to a null address with an
1705 // inbounds GEP in address space zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001706 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001707 return true;
1708
Chandler Carruth80d3e562012-12-07 02:08:58 +00001709 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1710 // If so, then the GEP cannot produce a null pointer, as doing so would
1711 // inherently violate the inbounds contract within address space zero.
1712 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1713 GTI != GTE; ++GTI) {
1714 // Struct types are easy -- they must always be indexed by a constant.
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001715 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001716 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1717 unsigned ElementIdx = OpC->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001718 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chandler Carruth80d3e562012-12-07 02:08:58 +00001719 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1720 if (ElementOffset > 0)
1721 return true;
1722 continue;
1723 }
1724
1725 // If we have a zero-sized type, the index doesn't matter. Keep looping.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001726 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
Chandler Carruth80d3e562012-12-07 02:08:58 +00001727 continue;
1728
1729 // Fast path the constant operand case both for efficiency and so we don't
1730 // increment Depth when just zipping down an all-constant GEP.
1731 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1732 if (!OpC->isZero())
1733 return true;
1734 continue;
1735 }
1736
1737 // We post-increment Depth here because while isKnownNonZero increments it
1738 // as well, when we pop back up that increment won't persist. We don't want
1739 // to recurse 10k times just because we have 10k GEP operands. We don't
1740 // bail completely out because we want to handle constant GEPs regardless
1741 // of depth.
1742 if (Depth++ >= MaxDepth)
1743 continue;
1744
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001745 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001746 return true;
1747 }
1748
1749 return false;
1750}
1751
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001752/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1753/// ensure that the value it's attached to is never Value? 'RangeType' is
1754/// is the type of the value described by the range.
Pete Cooper35b00d52016-08-13 01:05:32 +00001755static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001756 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1757 assert(NumRanges >= 1);
1758 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001759 ConstantInt *Lower =
1760 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1761 ConstantInt *Upper =
1762 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001763 ConstantRange Range(Lower->getValue(), Upper->getValue());
1764 if (Range.contains(Value))
1765 return false;
1766 }
1767 return true;
1768}
1769
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001770/// Return true if the given value is known to be non-zero when defined. For
1771/// vectors, return true if every element is known to be non-zero when
1772/// defined. For pointers, if the context instruction and dominator tree are
1773/// specified, perform context-sensitive analysis and return true if the
1774/// pointer couldn't possibly be null at the specified instruction.
1775/// Supports values with integer or pointer type and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001776bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) {
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001777 if (auto *C = dyn_cast<Constant>(V)) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001778 if (C->isNullValue())
1779 return false;
1780 if (isa<ConstantInt>(C))
1781 // Must be non-zero due to null test above.
1782 return true;
Sanjay Patel23019d12016-05-24 14:18:49 +00001783
1784 // For constant vectors, check that all elements are undefined or known
1785 // non-zero to determine that the whole vector is known non-zero.
1786 if (auto *VecTy = dyn_cast<VectorType>(C->getType())) {
1787 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
1788 Constant *Elt = C->getAggregateElement(i);
1789 if (!Elt || Elt->isNullValue())
1790 return false;
1791 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
1792 return false;
1793 }
1794 return true;
1795 }
1796
Duncan Sandsd3951082011-01-25 09:38:29 +00001797 return false;
1798 }
1799
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001800 if (auto *I = dyn_cast<Instruction>(V)) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001801 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001802 // If the possible ranges don't contain zero, then the value is
1803 // definitely non-zero.
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001804 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001805 const APInt ZeroValue(Ty->getBitWidth(), 0);
1806 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1807 return true;
1808 }
1809 }
1810 }
1811
Duncan Sandsd3951082011-01-25 09:38:29 +00001812 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001813 if (Depth++ >= MaxDepth)
Duncan Sandsd3951082011-01-25 09:38:29 +00001814 return false;
1815
Chandler Carruth80d3e562012-12-07 02:08:58 +00001816 // Check for pointer simplifications.
1817 if (V->getType()->isPointerTy()) {
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001818 if (isKnownNonNullAt(V, Q.CxtI, Q.DT))
Sanjoy Das6082c1a2016-05-07 02:08:15 +00001819 return true;
Pete Cooper35b00d52016-08-13 01:05:32 +00001820 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001821 if (isGEPKnownNonNull(GEP, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001822 return true;
1823 }
1824
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001825 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001826
1827 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00001828 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00001829 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001830 return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001831
1832 // ext X != 0 if X != 0.
1833 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001834 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001835
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001836 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00001837 // if the lowest bit is shifted off the end.
Craig Topper6b3940a2017-05-03 22:25:19 +00001838 if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001839 // shl nuw can't remove any non-zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00001840 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001841 if (BO->hasNoUnsignedWrap())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001842 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001843
Craig Topperb45eabc2017-04-26 16:39:58 +00001844 KnownBits Known(BitWidth);
1845 computeKnownBits(X, Known, Depth, Q);
1846 if (Known.One[0])
Duncan Sandsd3951082011-01-25 09:38:29 +00001847 return true;
1848 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001849 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00001850 // defined if the sign bit is shifted off the end.
1851 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001852 // shr exact can only shift out zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00001853 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001854 if (BO->isExact())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001855 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001856
Craig Topper6e11a052017-05-08 16:22:48 +00001857 KnownBits Known = computeKnownBits(X, Depth, Q);
1858 if (Known.isNegative())
Duncan Sandsd3951082011-01-25 09:38:29 +00001859 return true;
James Molloyb6be1eb2015-09-24 16:06:32 +00001860
1861 // If the shifter operand is a constant, and all of the bits shifted
1862 // out are known to be zero, and X is known non-zero then at least one
1863 // non-zero bit must remain.
1864 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
James Molloyb6be1eb2015-09-24 16:06:32 +00001865 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
1866 // Is there a known one in the portion not shifted out?
Craig Topper8df66c62017-05-12 17:20:30 +00001867 if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
James Molloyb6be1eb2015-09-24 16:06:32 +00001868 return true;
1869 // Are all the bits to be shifted out known zero?
NAKAMURA Takumi76bab1f2017-07-11 02:31:51 +00001870 if (Known.countMinTrailingZeros() >= ShiftVal)
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001871 return isKnownNonZero(X, Depth, Q);
James Molloyb6be1eb2015-09-24 16:06:32 +00001872 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001873 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001874 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001875 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001876 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001877 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001878 // X + Y.
1879 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Craig Topper6e11a052017-05-08 16:22:48 +00001880 KnownBits XKnown = computeKnownBits(X, Depth, Q);
1881 KnownBits YKnown = computeKnownBits(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001882
1883 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001884 // zero unless both X and Y are zero.
Craig Topper6e11a052017-05-08 16:22:48 +00001885 if (XKnown.isNonNegative() && YKnown.isNonNegative())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001886 if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001887 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001888
1889 // If X and Y are both negative (as signed values) then their sum is not
1890 // zero unless both X and Y equal INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00001891 if (XKnown.isNegative() && YKnown.isNegative()) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001892 APInt Mask = APInt::getSignedMaxValue(BitWidth);
1893 // The sign bit of X is set. If some other bit is set then X is not equal
1894 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00001895 if (XKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00001896 return true;
1897 // The sign bit of Y is set. If some other bit is set then Y is not equal
1898 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00001899 if (YKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00001900 return true;
1901 }
1902
1903 // The sum of a non-negative number and a power of two is not zero.
Craig Topper6e11a052017-05-08 16:22:48 +00001904 if (XKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001905 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001906 return true;
Craig Topper6e11a052017-05-08 16:22:48 +00001907 if (YKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001908 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001909 return true;
1910 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00001911 // X * Y.
1912 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001913 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Duncan Sands7cb61e52011-10-27 19:16:21 +00001914 // If X and Y are non-zero then so is X * Y as long as the multiplication
1915 // does not overflow.
1916 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001917 isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00001918 return true;
1919 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001920 // (C ? X : Y) != 0 if X != 0 and Y != 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00001921 else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001922 if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
1923 isKnownNonZero(SI->getFalseValue(), Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001924 return true;
1925 }
James Molloy897048b2015-09-29 14:08:45 +00001926 // PHI
Pete Cooper35b00d52016-08-13 01:05:32 +00001927 else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
James Molloy897048b2015-09-29 14:08:45 +00001928 // Try and detect a recurrence that monotonically increases from a
1929 // starting value, as these are common as induction variables.
1930 if (PN->getNumIncomingValues() == 2) {
1931 Value *Start = PN->getIncomingValue(0);
1932 Value *Induction = PN->getIncomingValue(1);
1933 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
1934 std::swap(Start, Induction);
1935 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
1936 if (!C->isZero() && !C->isNegative()) {
1937 ConstantInt *X;
1938 if ((match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
1939 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
1940 !X->isNegative())
1941 return true;
1942 }
1943 }
1944 }
Jun Bum Limca832662016-02-01 17:03:07 +00001945 // Check if all incoming values are non-zero constant.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001946 bool AllNonZeroConstants = llvm::all_of(PN->operands(), [](Value *V) {
Craig Topper79ab6432017-07-06 18:39:47 +00001947 return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZero();
Jun Bum Limca832662016-02-01 17:03:07 +00001948 });
1949 if (AllNonZeroConstants)
1950 return true;
James Molloy897048b2015-09-29 14:08:45 +00001951 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001952
Craig Topperb45eabc2017-04-26 16:39:58 +00001953 KnownBits Known(BitWidth);
1954 computeKnownBits(V, Known, Depth, Q);
1955 return Known.One != 0;
Duncan Sandsd3951082011-01-25 09:38:29 +00001956}
1957
James Molloy1d88d6f2015-10-22 13:18:42 +00001958/// Return true if V2 == V1 + X, where X is known non-zero.
Pete Cooper35b00d52016-08-13 01:05:32 +00001959static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) {
1960 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
James Molloy1d88d6f2015-10-22 13:18:42 +00001961 if (!BO || BO->getOpcode() != Instruction::Add)
1962 return false;
1963 Value *Op = nullptr;
1964 if (V2 == BO->getOperand(0))
1965 Op = BO->getOperand(1);
1966 else if (V2 == BO->getOperand(1))
1967 Op = BO->getOperand(0);
1968 else
1969 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001970 return isKnownNonZero(Op, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00001971}
1972
1973/// Return true if it is known that V1 != V2.
Pete Cooper35b00d52016-08-13 01:05:32 +00001974static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) {
Craig Topper3002d5b2017-06-06 07:13:15 +00001975 if (V1 == V2)
James Molloy1d88d6f2015-10-22 13:18:42 +00001976 return false;
1977 if (V1->getType() != V2->getType())
1978 // We can't look through casts yet.
1979 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001980 if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
James Molloy1d88d6f2015-10-22 13:18:42 +00001981 return true;
1982
Craig Topper3002d5b2017-06-06 07:13:15 +00001983 if (V1->getType()->isIntOrIntVectorTy()) {
James Molloy1d88d6f2015-10-22 13:18:42 +00001984 // Are any known bits in V1 contradictory to known bits in V2? If V1
1985 // has a known zero where V2 has a known one, they must not be equal.
Craig Topper8e662f72017-06-06 07:13:11 +00001986 KnownBits Known1 = computeKnownBits(V1, 0, Q);
1987 KnownBits Known2 = computeKnownBits(V2, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00001988
Craig Topper8365df82017-06-06 07:13:09 +00001989 if (Known1.Zero.intersects(Known2.One) ||
1990 Known2.Zero.intersects(Known1.One))
James Molloy1d88d6f2015-10-22 13:18:42 +00001991 return true;
1992 }
1993 return false;
1994}
1995
Sanjay Patelaee84212014-11-04 16:27:42 +00001996/// Return true if 'V & Mask' is known to be zero. We use this predicate to
1997/// simplify operations downstream. Mask is known to be zero for bits that V
1998/// cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00001999///
2000/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002001/// type, and vectors of integers. In the case
Chris Lattner4bc28252009-09-08 00:06:16 +00002002/// where V is a vector, the mask, known zero, and known one values are the
2003/// same width as the vector element, and the bit is set only if it is true
2004/// for all of the elements in the vector.
Pete Cooper35b00d52016-08-13 01:05:32 +00002005bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002006 const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002007 KnownBits Known(Mask.getBitWidth());
2008 computeKnownBits(V, Known, Depth, Q);
2009 return Mask.isSubsetOf(Known.Zero);
Chris Lattner965c7692008-06-02 01:18:21 +00002010}
2011
Sanjay Patela06d9892016-06-22 19:20:59 +00002012/// For vector constants, loop over the elements and find the constant with the
2013/// minimum number of sign bits. Return 0 if the value is not a vector constant
2014/// or if any element was not analyzed; otherwise, return the count for the
2015/// element with the minimum number of sign bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002016static unsigned computeNumSignBitsVectorConstant(const Value *V,
2017 unsigned TyBits) {
2018 const auto *CV = dyn_cast<Constant>(V);
Sanjay Patela06d9892016-06-22 19:20:59 +00002019 if (!CV || !CV->getType()->isVectorTy())
2020 return 0;
Chris Lattner965c7692008-06-02 01:18:21 +00002021
Sanjay Patela06d9892016-06-22 19:20:59 +00002022 unsigned MinSignBits = TyBits;
2023 unsigned NumElts = CV->getType()->getVectorNumElements();
2024 for (unsigned i = 0; i != NumElts; ++i) {
2025 // If we find a non-ConstantInt, bail out.
2026 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
2027 if (!Elt)
2028 return 0;
2029
2030 // If the sign bit is 1, flip the bits, so we always count leading zeros.
2031 APInt EltVal = Elt->getValue();
2032 if (EltVal.isNegative())
2033 EltVal = ~EltVal;
2034 MinSignBits = std::min(MinSignBits, EltVal.countLeadingZeros());
2035 }
2036
2037 return MinSignBits;
2038}
Chris Lattner965c7692008-06-02 01:18:21 +00002039
Sanjoy Das39a684d2017-02-25 20:30:45 +00002040static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2041 const Query &Q);
2042
2043static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
2044 const Query &Q) {
2045 unsigned Result = ComputeNumSignBitsImpl(V, Depth, Q);
2046 assert(Result > 0 && "At least one sign bit needs to be present!");
2047 return Result;
2048}
2049
Sanjay Patelaee84212014-11-04 16:27:42 +00002050/// Return the number of times the sign bit of the register is replicated into
2051/// the other bits. We know that at least 1 bit is always equal to the sign bit
2052/// (itself), but other cases can give us information. For example, immediately
2053/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
Sanjay Patela06d9892016-06-22 19:20:59 +00002054/// other, so we return 3. For vectors, return the number of sign bits for the
2055/// vector element with the mininum number of known sign bits.
Sanjoy Das39a684d2017-02-25 20:30:45 +00002056static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2057 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00002058 assert(Depth <= MaxDepth && "Limit Search Depth");
Sanjoy Das39a684d2017-02-25 20:30:45 +00002059
2060 // We return the minimum number of sign bits that are guaranteed to be present
2061 // in V, so for undef we have to conservatively return 1. We don't have the
2062 // same behavior for poison though -- that's a FIXME today.
2063
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002064 unsigned TyBits = Q.DL.getTypeSizeInBits(V->getType()->getScalarType());
Chris Lattner965c7692008-06-02 01:18:21 +00002065 unsigned Tmp, Tmp2;
2066 unsigned FirstAnswer = 1;
2067
Jay Foada0653a32014-05-14 21:14:37 +00002068 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00002069 // below.
2070
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002071 if (Depth == MaxDepth)
Chris Lattner965c7692008-06-02 01:18:21 +00002072 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002073
Pete Cooper35b00d52016-08-13 01:05:32 +00002074 const Operator *U = dyn_cast<Operator>(V);
Dan Gohman80ca01c2009-07-17 20:47:02 +00002075 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00002076 default: break;
2077 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00002078 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002079 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00002080
Nadav Rotemc99a3872015-03-06 00:23:58 +00002081 case Instruction::SDiv: {
Nadav Rotem029c5c72015-03-03 21:39:02 +00002082 const APInt *Denominator;
2083 // sdiv X, C -> adds log(C) sign bits.
2084 if (match(U->getOperand(1), m_APInt(Denominator))) {
2085
2086 // Ignore non-positive denominator.
2087 if (!Denominator->isStrictlyPositive())
2088 break;
2089
2090 // Calculate the incoming numerator bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002091 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotem029c5c72015-03-03 21:39:02 +00002092
2093 // Add floor(log(C)) bits to the numerator bits.
2094 return std::min(TyBits, NumBits + Denominator->logBase2());
2095 }
2096 break;
Nadav Rotemc99a3872015-03-06 00:23:58 +00002097 }
2098
2099 case Instruction::SRem: {
2100 const APInt *Denominator;
Sanjoy Dase561fee2015-03-25 22:33:53 +00002101 // srem X, C -> we know that the result is within [-C+1,C) when C is a
2102 // positive constant. This let us put a lower bound on the number of sign
2103 // bits.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002104 if (match(U->getOperand(1), m_APInt(Denominator))) {
2105
2106 // Ignore non-positive denominator.
2107 if (!Denominator->isStrictlyPositive())
2108 break;
2109
2110 // Calculate the incoming numerator bits. SRem by a positive constant
2111 // can't lower the number of sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002112 unsigned NumrBits =
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002113 ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotemc99a3872015-03-06 00:23:58 +00002114
2115 // Calculate the leading sign bit constraints by examining the
Sanjoy Dase561fee2015-03-25 22:33:53 +00002116 // denominator. Given that the denominator is positive, there are two
2117 // cases:
2118 //
2119 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
2120 // (1 << ceilLogBase2(C)).
2121 //
2122 // 2. the numerator is negative. Then the result range is (-C,0] and
2123 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2124 //
2125 // Thus a lower bound on the number of sign bits is `TyBits -
2126 // ceilLogBase2(C)`.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002127
Sanjoy Dase561fee2015-03-25 22:33:53 +00002128 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
Nadav Rotemc99a3872015-03-06 00:23:58 +00002129 return std::max(NumrBits, ResBits);
2130 }
2131 break;
2132 }
Nadav Rotem029c5c72015-03-03 21:39:02 +00002133
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002134 case Instruction::AShr: {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002135 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002136 // ashr X, C -> adds C sign bits. Vectors too.
2137 const APInt *ShAmt;
2138 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Sanjoy Das39a684d2017-02-25 20:30:45 +00002139 unsigned ShAmtLimited = ShAmt->getZExtValue();
2140 if (ShAmtLimited >= TyBits)
2141 break; // Bad shift.
2142 Tmp += ShAmtLimited;
Chris Lattner965c7692008-06-02 01:18:21 +00002143 if (Tmp > TyBits) Tmp = TyBits;
2144 }
2145 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002146 }
2147 case Instruction::Shl: {
2148 const APInt *ShAmt;
2149 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00002150 // shl destroys sign bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002151 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002152 Tmp2 = ShAmt->getZExtValue();
2153 if (Tmp2 >= TyBits || // Bad shift.
2154 Tmp2 >= Tmp) break; // Shifted all sign bits out.
2155 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00002156 }
2157 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002158 }
Chris Lattner965c7692008-06-02 01:18:21 +00002159 case Instruction::And:
2160 case Instruction::Or:
2161 case Instruction::Xor: // NOT is handled here.
2162 // Logical binary ops preserve the number of sign bits at the worst.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002163 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002164 if (Tmp != 1) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002165 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002166 FirstAnswer = std::min(Tmp, Tmp2);
2167 // We computed what we know about the sign bits as our first
2168 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00002169 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00002170 }
2171 break;
2172
2173 case Instruction::Select:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002174 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002175 if (Tmp == 1) return 1; // Early out.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002176 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002177 return std::min(Tmp, Tmp2);
Craig Topper1bef2c82012-12-22 19:15:35 +00002178
Chris Lattner965c7692008-06-02 01:18:21 +00002179 case Instruction::Add:
2180 // Add can have at most one carry bit. Thus we know that the output
2181 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002182 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002183 if (Tmp == 1) return 1; // Early out.
Craig Topper1bef2c82012-12-22 19:15:35 +00002184
Chris Lattner965c7692008-06-02 01:18:21 +00002185 // Special case decrementing a value (ADD X, -1):
David Majnemera55027f2014-12-26 09:20:17 +00002186 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00002187 if (CRHS->isAllOnesValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002188 KnownBits Known(TyBits);
2189 computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002190
Chris Lattner965c7692008-06-02 01:18:21 +00002191 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2192 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002193 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002194 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002195
Chris Lattner965c7692008-06-02 01:18:21 +00002196 // If we are subtracting one from a positive number, there is no carry
2197 // out of the result.
Craig Topperca48af32017-04-29 16:43:11 +00002198 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002199 return Tmp;
2200 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002201
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002202 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002203 if (Tmp2 == 1) return 1;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002204 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002205
Chris Lattner965c7692008-06-02 01:18:21 +00002206 case Instruction::Sub:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002207 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002208 if (Tmp2 == 1) return 1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002209
Chris Lattner965c7692008-06-02 01:18:21 +00002210 // Handle NEG.
David Majnemera55027f2014-12-26 09:20:17 +00002211 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
Chris Lattner965c7692008-06-02 01:18:21 +00002212 if (CLHS->isNullValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002213 KnownBits Known(TyBits);
2214 computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002215 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2216 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002217 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002218 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002219
Chris Lattner965c7692008-06-02 01:18:21 +00002220 // If the input is known to be positive (the sign bit is known clear),
2221 // the output of the NEG has the same number of sign bits as the input.
Craig Topperca48af32017-04-29 16:43:11 +00002222 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002223 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00002224
Chris Lattner965c7692008-06-02 01:18:21 +00002225 // Otherwise, we treat this like a SUB.
2226 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002227
Chris Lattner965c7692008-06-02 01:18:21 +00002228 // Sub can have at most one carry bit. Thus we know that the output
2229 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002230 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002231 if (Tmp == 1) return 1; // Early out.
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002232 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002233
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002234 case Instruction::Mul: {
2235 // The output of the Mul can be at most twice the valid bits in the inputs.
2236 unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2237 if (SignBitsOp0 == 1) return 1; // Early out.
2238 unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2239 if (SignBitsOp1 == 1) return 1;
2240 unsigned OutValidBits =
2241 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
2242 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
2243 }
2244
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002245 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00002246 const PHINode *PN = cast<PHINode>(U);
David Majnemer6ee8d172015-01-04 07:06:53 +00002247 unsigned NumIncomingValues = PN->getNumIncomingValues();
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002248 // Don't analyze large in-degree PHIs.
David Majnemer6ee8d172015-01-04 07:06:53 +00002249 if (NumIncomingValues > 4) break;
2250 // Unreachable blocks may have zero-operand PHI nodes.
2251 if (NumIncomingValues == 0) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002252
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002253 // Take the minimum of all incoming values. This can't infinitely loop
2254 // because of our depth threshold.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002255 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
David Majnemer6ee8d172015-01-04 07:06:53 +00002256 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002257 if (Tmp == 1) return Tmp;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002258 Tmp = std::min(
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002259 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002260 }
2261 return Tmp;
2262 }
2263
Chris Lattner965c7692008-06-02 01:18:21 +00002264 case Instruction::Trunc:
2265 // FIXME: it's tricky to do anything useful for this, but it is an important
2266 // case for targets like X86.
2267 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00002268
2269 case Instruction::ExtractElement:
2270 // Look through extract element. At the moment we keep this simple and skip
2271 // tracking the specific element. But at least we might find information
2272 // valid for all elements of the vector (for example if vector is sign
2273 // extended, shifted, etc).
2274 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002275 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002276
Chris Lattner965c7692008-06-02 01:18:21 +00002277 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2278 // use this information.
Sanjay Patela06d9892016-06-22 19:20:59 +00002279
2280 // If we can examine all elements of a vector constant successfully, we're
2281 // done (we can't do any better than that). If not, keep trying.
2282 if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits))
2283 return VecSignBits;
2284
Craig Topperb45eabc2017-04-26 16:39:58 +00002285 KnownBits Known(TyBits);
2286 computeKnownBits(V, Known, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002287
Sanjay Patele0536212016-06-23 17:41:59 +00002288 // If we know that the sign bit is either zero or one, determine the number of
2289 // identical bits in the top of the input value.
Craig Topper8df66c62017-05-12 17:20:30 +00002290 return std::max(FirstAnswer, Known.countMinSignBits());
Chris Lattner965c7692008-06-02 01:18:21 +00002291}
Chris Lattnera12a6de2008-06-02 01:29:46 +00002292
Sanjay Patelaee84212014-11-04 16:27:42 +00002293/// This function computes the integer multiple of Base that equals V.
2294/// If successful, it returns true and returns the multiple in
2295/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00002296/// through SExt instructions only if LookThroughSExt is true.
2297bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00002298 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00002299 const unsigned MaxDepth = 6;
2300
Dan Gohman6a976bb2009-11-18 00:58:27 +00002301 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00002302 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002303 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00002304
Chris Lattner229907c2011-07-18 04:54:35 +00002305 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00002306
Dan Gohman6a976bb2009-11-18 00:58:27 +00002307 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00002308
2309 if (Base == 0)
2310 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002311
Victor Hernandez47444882009-11-10 08:28:35 +00002312 if (Base == 1) {
2313 Multiple = V;
2314 return true;
2315 }
2316
2317 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2318 Constant *BaseVal = ConstantInt::get(T, Base);
2319 if (CO && CO == BaseVal) {
2320 // Multiple is 1.
2321 Multiple = ConstantInt::get(T, 1);
2322 return true;
2323 }
2324
2325 if (CI && CI->getZExtValue() % Base == 0) {
2326 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00002327 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00002328 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002329
Victor Hernandez47444882009-11-10 08:28:35 +00002330 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002331
Victor Hernandez47444882009-11-10 08:28:35 +00002332 Operator *I = dyn_cast<Operator>(V);
2333 if (!I) return false;
2334
2335 switch (I->getOpcode()) {
2336 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002337 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00002338 if (!LookThroughSExt) return false;
2339 // otherwise fall through to ZExt
Galina Kistanova244621f2017-05-31 22:16:24 +00002340 LLVM_FALLTHROUGH;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002341 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00002342 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2343 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00002344 case Instruction::Shl:
2345 case Instruction::Mul: {
2346 Value *Op0 = I->getOperand(0);
2347 Value *Op1 = I->getOperand(1);
2348
2349 if (I->getOpcode() == Instruction::Shl) {
2350 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2351 if (!Op1CI) return false;
2352 // Turn Op0 << Op1 into Op0 * 2^Op1
2353 APInt Op1Int = Op1CI->getValue();
2354 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00002355 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002356 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00002357 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00002358 }
2359
Craig Topper9f008862014-04-15 04:59:12 +00002360 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002361 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2362 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2363 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002364 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002365 MulC->getType()->getPrimitiveSizeInBits())
2366 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002367 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002368 MulC->getType()->getPrimitiveSizeInBits())
2369 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002370
Chris Lattner72d283c2010-09-05 17:20:46 +00002371 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2372 Multiple = ConstantExpr::getMul(MulC, Op1C);
2373 return true;
2374 }
Victor Hernandez47444882009-11-10 08:28:35 +00002375
2376 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2377 if (Mul0CI->getValue() == 1) {
2378 // V == Base * Op1, so return Op1
2379 Multiple = Op1;
2380 return true;
2381 }
2382 }
2383
Craig Topper9f008862014-04-15 04:59:12 +00002384 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002385 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2386 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2387 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002388 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002389 MulC->getType()->getPrimitiveSizeInBits())
2390 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002391 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002392 MulC->getType()->getPrimitiveSizeInBits())
2393 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002394
Chris Lattner72d283c2010-09-05 17:20:46 +00002395 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2396 Multiple = ConstantExpr::getMul(MulC, Op0C);
2397 return true;
2398 }
Victor Hernandez47444882009-11-10 08:28:35 +00002399
2400 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2401 if (Mul1CI->getValue() == 1) {
2402 // V == Base * Op0, so return Op0
2403 Multiple = Op0;
2404 return true;
2405 }
2406 }
Victor Hernandez47444882009-11-10 08:28:35 +00002407 }
2408 }
2409
2410 // We could not determine if V is a multiple of Base.
2411 return false;
2412}
2413
David Majnemerb4b27232016-04-19 19:10:21 +00002414Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS,
2415 const TargetLibraryInfo *TLI) {
2416 const Function *F = ICS.getCalledFunction();
2417 if (!F)
2418 return Intrinsic::not_intrinsic;
2419
2420 if (F->isIntrinsic())
2421 return F->getIntrinsicID();
2422
2423 if (!TLI)
2424 return Intrinsic::not_intrinsic;
2425
David L. Jonesd21529f2017-01-23 23:16:46 +00002426 LibFunc Func;
David Majnemerb4b27232016-04-19 19:10:21 +00002427 // We're going to make assumptions on the semantics of the functions, check
2428 // that the target knows that it's available in this environment and it does
2429 // not have local linkage.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002430 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func))
2431 return Intrinsic::not_intrinsic;
2432
2433 if (!ICS.onlyReadsMemory())
David Majnemerb4b27232016-04-19 19:10:21 +00002434 return Intrinsic::not_intrinsic;
2435
2436 // Otherwise check if we have a call to a function that can be turned into a
2437 // vector intrinsic.
2438 switch (Func) {
2439 default:
2440 break;
David L. Jonesd21529f2017-01-23 23:16:46 +00002441 case LibFunc_sin:
2442 case LibFunc_sinf:
2443 case LibFunc_sinl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002444 return Intrinsic::sin;
David L. Jonesd21529f2017-01-23 23:16:46 +00002445 case LibFunc_cos:
2446 case LibFunc_cosf:
2447 case LibFunc_cosl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002448 return Intrinsic::cos;
David L. Jonesd21529f2017-01-23 23:16:46 +00002449 case LibFunc_exp:
2450 case LibFunc_expf:
2451 case LibFunc_expl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002452 return Intrinsic::exp;
David L. Jonesd21529f2017-01-23 23:16:46 +00002453 case LibFunc_exp2:
2454 case LibFunc_exp2f:
2455 case LibFunc_exp2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002456 return Intrinsic::exp2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002457 case LibFunc_log:
2458 case LibFunc_logf:
2459 case LibFunc_logl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002460 return Intrinsic::log;
David L. Jonesd21529f2017-01-23 23:16:46 +00002461 case LibFunc_log10:
2462 case LibFunc_log10f:
2463 case LibFunc_log10l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002464 return Intrinsic::log10;
David L. Jonesd21529f2017-01-23 23:16:46 +00002465 case LibFunc_log2:
2466 case LibFunc_log2f:
2467 case LibFunc_log2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002468 return Intrinsic::log2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002469 case LibFunc_fabs:
2470 case LibFunc_fabsf:
2471 case LibFunc_fabsl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002472 return Intrinsic::fabs;
David L. Jonesd21529f2017-01-23 23:16:46 +00002473 case LibFunc_fmin:
2474 case LibFunc_fminf:
2475 case LibFunc_fminl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002476 return Intrinsic::minnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002477 case LibFunc_fmax:
2478 case LibFunc_fmaxf:
2479 case LibFunc_fmaxl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002480 return Intrinsic::maxnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002481 case LibFunc_copysign:
2482 case LibFunc_copysignf:
2483 case LibFunc_copysignl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002484 return Intrinsic::copysign;
David L. Jonesd21529f2017-01-23 23:16:46 +00002485 case LibFunc_floor:
2486 case LibFunc_floorf:
2487 case LibFunc_floorl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002488 return Intrinsic::floor;
David L. Jonesd21529f2017-01-23 23:16:46 +00002489 case LibFunc_ceil:
2490 case LibFunc_ceilf:
2491 case LibFunc_ceill:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002492 return Intrinsic::ceil;
David L. Jonesd21529f2017-01-23 23:16:46 +00002493 case LibFunc_trunc:
2494 case LibFunc_truncf:
2495 case LibFunc_truncl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002496 return Intrinsic::trunc;
David L. Jonesd21529f2017-01-23 23:16:46 +00002497 case LibFunc_rint:
2498 case LibFunc_rintf:
2499 case LibFunc_rintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002500 return Intrinsic::rint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002501 case LibFunc_nearbyint:
2502 case LibFunc_nearbyintf:
2503 case LibFunc_nearbyintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002504 return Intrinsic::nearbyint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002505 case LibFunc_round:
2506 case LibFunc_roundf:
2507 case LibFunc_roundl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002508 return Intrinsic::round;
David L. Jonesd21529f2017-01-23 23:16:46 +00002509 case LibFunc_pow:
2510 case LibFunc_powf:
2511 case LibFunc_powl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002512 return Intrinsic::pow;
David L. Jonesd21529f2017-01-23 23:16:46 +00002513 case LibFunc_sqrt:
2514 case LibFunc_sqrtf:
2515 case LibFunc_sqrtl:
David Majnemerb4b27232016-04-19 19:10:21 +00002516 if (ICS->hasNoNaNs())
Ahmed Bougachad765a822016-04-27 19:04:35 +00002517 return Intrinsic::sqrt;
David Majnemerb4b27232016-04-19 19:10:21 +00002518 return Intrinsic::not_intrinsic;
2519 }
2520
2521 return Intrinsic::not_intrinsic;
2522}
2523
Sanjay Patelaee84212014-11-04 16:27:42 +00002524/// Return true if we can prove that the specified FP value is never equal to
2525/// -0.0.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002526///
2527/// NOTE: this function will need to be revisited when we support non-default
2528/// rounding modes!
David Majnemer3ee5f342016-04-13 06:55:52 +00002529bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
2530 unsigned Depth) {
Chris Lattnera12a6de2008-06-02 01:29:46 +00002531 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2532 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00002533
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002534 if (Depth == MaxDepth)
Sanjay Patel40eaa8d2015-02-25 18:00:15 +00002535 return false; // Limit search depth.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002536
Dan Gohman80ca01c2009-07-17 20:47:02 +00002537 const Operator *I = dyn_cast<Operator>(V);
Craig Topper9f008862014-04-15 04:59:12 +00002538 if (!I) return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00002539
2540 // Check if the nsz fast-math flag is set
2541 if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
2542 if (FPO->hasNoSignedZeros())
2543 return true;
2544
Chris Lattnera12a6de2008-06-02 01:29:46 +00002545 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Jakub Staszakb7129f22013-03-06 00:16:16 +00002546 if (I->getOpcode() == Instruction::FAdd)
2547 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
2548 if (CFP->isNullValue())
2549 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002550
Chris Lattnera12a6de2008-06-02 01:29:46 +00002551 // sitofp and uitofp turn into +0.0 for zero.
2552 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2553 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002554
David Majnemer3ee5f342016-04-13 06:55:52 +00002555 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
David Majnemerb4b27232016-04-19 19:10:21 +00002556 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002557 switch (IID) {
2558 default:
2559 break;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002560 // sqrt(-0.0) = -0.0, no other negative results are possible.
David Majnemer3ee5f342016-04-13 06:55:52 +00002561 case Intrinsic::sqrt:
2562 return CannotBeNegativeZero(CI->getArgOperand(0), TLI, Depth + 1);
2563 // fabs(x) != -0.0
2564 case Intrinsic::fabs:
2565 return true;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002566 }
David Majnemer3ee5f342016-04-13 06:55:52 +00002567 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002568
Chris Lattnera12a6de2008-06-02 01:29:46 +00002569 return false;
2570}
2571
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002572/// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
2573/// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
2574/// bit despite comparing equal.
2575static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
2576 const TargetLibraryInfo *TLI,
2577 bool SignBitOnly,
2578 unsigned Depth) {
Justin Lebar322c1272017-01-27 00:58:34 +00002579 // TODO: This function does not do the right thing when SignBitOnly is true
2580 // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
2581 // which flips the sign bits of NaNs. See
2582 // https://llvm.org/bugs/show_bug.cgi?id=31702.
2583
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002584 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2585 return !CFP->getValueAPF().isNegative() ||
2586 (!SignBitOnly && CFP->getValueAPF().isZero());
2587 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002588
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002589 if (Depth == MaxDepth)
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002590 return false; // Limit search depth.
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002591
2592 const Operator *I = dyn_cast<Operator>(V);
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002593 if (!I)
2594 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002595
2596 switch (I->getOpcode()) {
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002597 default:
2598 break;
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002599 // Unsigned integers are always nonnegative.
2600 case Instruction::UIToFP:
2601 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002602 case Instruction::FMul:
2603 // x*x is always non-negative or a NaN.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002604 if (I->getOperand(0) == I->getOperand(1) &&
2605 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002606 return true;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002607
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002608 LLVM_FALLTHROUGH;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002609 case Instruction::FAdd:
2610 case Instruction::FDiv:
2611 case Instruction::FRem:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002612 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2613 Depth + 1) &&
2614 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2615 Depth + 1);
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002616 case Instruction::Select:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002617 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2618 Depth + 1) &&
2619 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2620 Depth + 1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002621 case Instruction::FPExt:
2622 case Instruction::FPTrunc:
2623 // Widening/narrowing never change sign.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002624 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2625 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002626 case Instruction::Call:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002627 const auto *CI = cast<CallInst>(I);
2628 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002629 switch (IID) {
2630 default:
2631 break;
2632 case Intrinsic::maxnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002633 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2634 Depth + 1) ||
2635 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2636 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002637 case Intrinsic::minnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002638 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2639 Depth + 1) &&
2640 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2641 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002642 case Intrinsic::exp:
2643 case Intrinsic::exp2:
2644 case Intrinsic::fabs:
David Majnemer3ee5f342016-04-13 06:55:52 +00002645 return true;
Justin Lebar7e3184c2017-01-26 00:10:26 +00002646
2647 case Intrinsic::sqrt:
2648 // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0.
2649 if (!SignBitOnly)
2650 return true;
2651 return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
2652 CannotBeNegativeZero(CI->getOperand(0), TLI));
2653
David Majnemer3ee5f342016-04-13 06:55:52 +00002654 case Intrinsic::powi:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002655 if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
David Majnemer3ee5f342016-04-13 06:55:52 +00002656 // powi(x,n) is non-negative if n is even.
Justin Lebar7e3184c2017-01-26 00:10:26 +00002657 if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
David Majnemer3ee5f342016-04-13 06:55:52 +00002658 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002659 }
Justin Lebar322c1272017-01-27 00:58:34 +00002660 // TODO: This is not correct. Given that exp is an integer, here are the
2661 // ways that pow can return a negative value:
2662 //
2663 // pow(x, exp) --> negative if exp is odd and x is negative.
2664 // pow(-0, exp) --> -inf if exp is negative odd.
2665 // pow(-0, exp) --> -0 if exp is positive odd.
2666 // pow(-inf, exp) --> -0 if exp is negative odd.
2667 // pow(-inf, exp) --> -inf if exp is positive odd.
2668 //
2669 // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
2670 // but we must return false if x == -0. Unfortunately we do not currently
2671 // have a way of expressing this constraint. See details in
2672 // https://llvm.org/bugs/show_bug.cgi?id=31702.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002673 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2674 Depth + 1);
Justin Lebar322c1272017-01-27 00:58:34 +00002675
David Majnemer3ee5f342016-04-13 06:55:52 +00002676 case Intrinsic::fma:
2677 case Intrinsic::fmuladd:
2678 // x*x+y is non-negative if y is non-negative.
2679 return I->getOperand(0) == I->getOperand(1) &&
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002680 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
2681 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2682 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002683 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002684 break;
2685 }
Sanjoy Das6082c1a2016-05-07 02:08:15 +00002686 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002687}
2688
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002689bool llvm::CannotBeOrderedLessThanZero(const Value *V,
2690 const TargetLibraryInfo *TLI) {
2691 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
2692}
2693
2694bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
2695 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
2696}
2697
Sanjay Patelaee84212014-11-04 16:27:42 +00002698/// If the specified value can be set by repeating the same byte in memory,
2699/// return the i8 value that it is represented with. This is
Chris Lattner9cb10352010-12-26 20:15:01 +00002700/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2701/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2702/// byte store (e.g. i16 0x1234), return null.
2703Value *llvm::isBytewiseValue(Value *V) {
2704 // All byte-wide stores are splatable, even of arbitrary variables.
2705 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattneracf6b072011-02-19 19:35:49 +00002706
2707 // Handle 'null' ConstantArrayZero etc.
2708 if (Constant *C = dyn_cast<Constant>(V))
2709 if (C->isNullValue())
2710 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Craig Topper1bef2c82012-12-22 19:15:35 +00002711
Chris Lattner9cb10352010-12-26 20:15:01 +00002712 // Constant float and double values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00002713 // corresponding integer value is "byteable". An important case is 0.0.
Chris Lattner9cb10352010-12-26 20:15:01 +00002714 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2715 if (CFP->getType()->isFloatTy())
2716 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2717 if (CFP->getType()->isDoubleTy())
2718 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2719 // Don't handle long double formats, which have strange constraints.
2720 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002721
Benjamin Kramer17d90152015-02-07 19:29:02 +00002722 // We can handle constant integers that are multiple of 8 bits.
Chris Lattner9cb10352010-12-26 20:15:01 +00002723 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Benjamin Kramer17d90152015-02-07 19:29:02 +00002724 if (CI->getBitWidth() % 8 == 0) {
2725 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
Craig Topper1bef2c82012-12-22 19:15:35 +00002726
Benjamin Kramerb4b51502015-03-25 16:49:59 +00002727 if (!CI->getValue().isSplat(8))
Benjamin Kramer17d90152015-02-07 19:29:02 +00002728 return nullptr;
2729 return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
Chris Lattner9cb10352010-12-26 20:15:01 +00002730 }
2731 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002732
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002733 // A ConstantDataArray/Vector is splatable if all its members are equal and
2734 // also splatable.
2735 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2736 Value *Elt = CA->getElementAsConstant(0);
2737 Value *Val = isBytewiseValue(Elt);
Chris Lattner9cb10352010-12-26 20:15:01 +00002738 if (!Val)
Craig Topper9f008862014-04-15 04:59:12 +00002739 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002740
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002741 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2742 if (CA->getElementAsConstant(I) != Elt)
Craig Topper9f008862014-04-15 04:59:12 +00002743 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002744
Chris Lattner9cb10352010-12-26 20:15:01 +00002745 return Val;
2746 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00002747
Chris Lattner9cb10352010-12-26 20:15:01 +00002748 // Conceptually, we could handle things like:
2749 // %a = zext i8 %X to i16
2750 // %b = shl i16 %a, 8
2751 // %c = or i16 %a, %b
2752 // but until there is an example that actually needs this, it doesn't seem
2753 // worth worrying about.
Craig Topper9f008862014-04-15 04:59:12 +00002754 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00002755}
2756
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002757// This is the recursive version of BuildSubAggregate. It takes a few different
2758// arguments. Idxs is the index within the nested struct From that we are
2759// looking at now (which is of type IndexedType). IdxSkip is the number of
2760// indices from Idxs that should be left out when inserting into the resulting
2761// struct. To is the result struct built so far, new insertvalue instructions
2762// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00002763static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00002764 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002765 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002766 Instruction *InsertBefore) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002767 StructType *STy = dyn_cast<StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002768 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002769 // Save the original To argument so we can modify it
2770 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002771 // General case, the type indexed by Idxs is a struct
2772 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2773 // Process each struct element recursively
2774 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002775 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002776 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002777 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002778 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002779 if (!To) {
2780 // Couldn't find any inserted value for this index? Cleanup
2781 while (PrevTo != OrigTo) {
2782 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2783 PrevTo = Del->getAggregateOperand();
2784 Del->eraseFromParent();
2785 }
2786 // Stop processing elements
2787 break;
2788 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002789 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002790 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002791 if (To)
2792 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002793 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002794 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2795 // the struct's elements had a value that was inserted directly. In the latter
2796 // case, perhaps we can't determine each of the subelements individually, but
2797 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00002798
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002799 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00002800 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002801
2802 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00002803 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002804
2805 // Insert the value in the new (sub) aggregrate
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002806 return InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
2807 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002808}
2809
2810// This helper takes a nested struct and extracts a part of it (which is again a
2811// struct) into a new value. For example, given the struct:
2812// { a, { b, { c, d }, e } }
2813// and the indices "1, 1" this returns
2814// { c, d }.
2815//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002816// It does this by inserting an insertvalue for each element in the resulting
2817// struct, as opposed to just inserting a single struct. This will only work if
2818// each of the elements of the substruct are known (ie, inserted into From by an
2819// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002820//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002821// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00002822static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002823 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00002824 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00002825 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00002826 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00002827 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00002828 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002829 unsigned IdxSkip = Idxs.size();
2830
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002831 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002832}
2833
Sanjay Patelaee84212014-11-04 16:27:42 +00002834/// Given an aggregrate and an sequence of indices, see if
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002835/// the scalar value indexed is already around as a register, for example if it
2836/// were inserted directly into the aggregrate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002837///
2838/// If InsertBefore is not null, this function will duplicate (modified)
2839/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00002840Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2841 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002842 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002843 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00002844 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002845 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002846 // We have indices, so V should have an indexable type.
2847 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2848 "Not looking at a struct or array?");
2849 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2850 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00002851
Chris Lattner67058832012-01-25 06:48:06 +00002852 if (Constant *C = dyn_cast<Constant>(V)) {
2853 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00002854 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00002855 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2856 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002857
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002858 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002859 // Loop the indices for the insertvalue instruction in parallel with the
2860 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002861 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002862 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2863 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00002864 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002865 // We can't handle this without inserting insertvalues
2866 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00002867 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002868
2869 // The requested index identifies a part of a nested aggregate. Handle
2870 // this specially. For example,
2871 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2872 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2873 // %C = extractvalue {i32, { i32, i32 } } %B, 1
2874 // This can be changed into
2875 // %A = insertvalue {i32, i32 } undef, i32 10, 0
2876 // %C = insertvalue {i32, i32 } %A, i32 11, 1
2877 // which allows the unused 0,0 element from the nested struct to be
2878 // removed.
2879 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2880 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00002881 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002882
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002883 // This insert value inserts something else than what we are looking for.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002884 // See if the (aggregate) value inserted into has the value we are
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002885 // looking for, then.
2886 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00002887 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002888 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002889 }
2890 // If we end up here, the indices of the insertvalue match with those
2891 // requested (though possibly only partially). Now we recursively look at
2892 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00002893 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002894 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002895 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002896 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002897
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002898 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002899 // If we're extracting a value from an aggregate that was extracted from
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002900 // something else, we can extract from that something else directly instead.
2901 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00002902
2903 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00002904 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002905 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00002906 SmallVector<unsigned, 5> Idxs;
2907 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002908 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00002909 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00002910
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002911 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002912 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002913
Craig Topper1bef2c82012-12-22 19:15:35 +00002914 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002915 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00002916
Jay Foad57aa6362011-07-13 10:26:04 +00002917 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002918 }
2919 // Otherwise, we don't know (such as, extracting from a function return value
2920 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00002921 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002922}
Evan Chengda3db112008-06-30 07:31:25 +00002923
Sanjay Patelaee84212014-11-04 16:27:42 +00002924/// Analyze the specified pointer to see if it can be expressed as a base
2925/// pointer plus a constant offset. Return the base and offset to the caller.
Chris Lattnere28618d2010-11-30 22:25:26 +00002926Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002927 const DataLayout &DL) {
2928 unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
Nuno Lopes368c4d02012-12-31 20:48:35 +00002929 APInt ByteOffset(BitWidth, 0);
Chandler Carruth76641272016-01-04 07:23:12 +00002930
2931 // We walk up the defs but use a visited set to handle unreachable code. In
2932 // that case, we stop after accumulating the cycle once (not that it
2933 // matters).
2934 SmallPtrSet<Value *, 16> Visited;
2935 while (Visited.insert(Ptr).second) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002936 if (Ptr->getType()->isVectorTy())
2937 break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002938
Nuno Lopes368c4d02012-12-31 20:48:35 +00002939 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Tom Stellard17eb3412016-10-07 14:23:29 +00002940 // If one of the values we have visited is an addrspacecast, then
2941 // the pointer type of this GEP may be different from the type
2942 // of the Ptr parameter which was passed to this function. This
2943 // means when we construct GEPOffset, we need to use the size
2944 // of GEP's pointer type rather than the size of the original
2945 // pointer type.
2946 APInt GEPOffset(DL.getPointerTypeSizeInBits(Ptr->getType()), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002947 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
2948 break;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002949
Tom Stellard17eb3412016-10-07 14:23:29 +00002950 ByteOffset += GEPOffset.getSExtValue();
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002951
Nuno Lopes368c4d02012-12-31 20:48:35 +00002952 Ptr = GEP->getPointerOperand();
Tom Stellard17eb3412016-10-07 14:23:29 +00002953 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2954 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002955 Ptr = cast<Operator>(Ptr)->getOperand(0);
2956 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00002957 if (GA->isInterposable())
Nuno Lopes368c4d02012-12-31 20:48:35 +00002958 break;
2959 Ptr = GA->getAliasee();
Chris Lattnere28618d2010-11-30 22:25:26 +00002960 } else {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002961 break;
Chris Lattnere28618d2010-11-30 22:25:26 +00002962 }
2963 }
Nuno Lopes368c4d02012-12-31 20:48:35 +00002964 Offset = ByteOffset.getSExtValue();
2965 return Ptr;
Chris Lattnere28618d2010-11-30 22:25:26 +00002966}
2967
Matthias Braun50ec0b52017-05-19 22:37:09 +00002968bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP,
2969 unsigned CharSize) {
David L Kreitzer752c1442016-04-13 14:31:06 +00002970 // Make sure the GEP has exactly three arguments.
2971 if (GEP->getNumOperands() != 3)
2972 return false;
2973
Matthias Braun50ec0b52017-05-19 22:37:09 +00002974 // Make sure the index-ee is a pointer to array of \p CharSize integers.
2975 // CharSize.
David L Kreitzer752c1442016-04-13 14:31:06 +00002976 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
Matthias Braun50ec0b52017-05-19 22:37:09 +00002977 if (!AT || !AT->getElementType()->isIntegerTy(CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +00002978 return false;
2979
2980 // Check to make sure that the first operand of the GEP is an integer and
2981 // has value 0 so that we are sure we're indexing into the initializer.
2982 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
2983 if (!FirstIdx || !FirstIdx->isZero())
2984 return false;
2985
2986 return true;
Sanjoy Das6082c1a2016-05-07 02:08:15 +00002987}
Chris Lattnere28618d2010-11-30 22:25:26 +00002988
Matthias Braun50ec0b52017-05-19 22:37:09 +00002989bool llvm::getConstantDataArrayInfo(const Value *V,
2990 ConstantDataArraySlice &Slice,
2991 unsigned ElementSize, uint64_t Offset) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002992 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00002993
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002994 // Look through bitcast instructions and geps.
2995 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00002996
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00002997 // If the value is a GEP instruction or constant expression, treat it as an
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002998 // offset.
2999 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003000 // The GEP operator should be based on a pointer to string constant, and is
3001 // indexing into the string constant.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003002 if (!isGEPBasedOnPointerToString(GEP, ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003003 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003004
Evan Chengda3db112008-06-30 07:31:25 +00003005 // If the second index isn't a ConstantInt, then this is a variable index
3006 // into the array. If this occurs, we can't say anything meaningful about
3007 // the string.
3008 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00003009 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00003010 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003011 else
3012 return false;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003013 return getConstantDataArrayInfo(GEP->getOperand(0), Slice, ElementSize,
3014 StartIdx + Offset);
Evan Chengda3db112008-06-30 07:31:25 +00003015 }
Nick Lewycky46209882011-10-20 00:34:35 +00003016
Evan Chengda3db112008-06-30 07:31:25 +00003017 // The GEP instruction, constant or instruction, must reference a global
3018 // variable that is a constant and is initialized. The referenced constant
3019 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003020 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00003021 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003022 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003023
Matthias Braun50ec0b52017-05-19 22:37:09 +00003024 const ConstantDataArray *Array;
3025 ArrayType *ArrayTy;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003026 if (GV->getInitializer()->isNullValue()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003027 Type *GVTy = GV->getValueType();
3028 if ( (ArrayTy = dyn_cast<ArrayType>(GVTy)) ) {
Sanjay Patel2ad88f82017-06-12 22:34:37 +00003029 // A zeroinitializer for the array; there is no ConstantDataArray.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003030 Array = nullptr;
3031 } else {
3032 const DataLayout &DL = GV->getParent()->getDataLayout();
3033 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy);
3034 uint64_t Length = SizeInBytes / (ElementSize / 8);
3035 if (Length <= Offset)
3036 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003037
Matthias Braun50ec0b52017-05-19 22:37:09 +00003038 Slice.Array = nullptr;
3039 Slice.Offset = 0;
3040 Slice.Length = Length - Offset;
3041 return true;
3042 }
3043 } else {
3044 // This must be a ConstantDataArray.
3045 Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
3046 if (!Array)
3047 return false;
3048 ArrayTy = Array->getType();
3049 }
3050 if (!ArrayTy->getElementType()->isIntegerTy(ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003051 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003052
Matthias Braun50ec0b52017-05-19 22:37:09 +00003053 uint64_t NumElts = ArrayTy->getArrayNumElements();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003054 if (Offset > NumElts)
3055 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003056
Matthias Braun50ec0b52017-05-19 22:37:09 +00003057 Slice.Array = Array;
3058 Slice.Offset = Offset;
3059 Slice.Length = NumElts - Offset;
3060 return true;
3061}
3062
3063/// This function computes the length of a null-terminated C string pointed to
3064/// by V. If successful, it returns true and returns the string in Str.
3065/// If unsuccessful, it returns false.
3066bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
3067 uint64_t Offset, bool TrimAtNul) {
3068 ConstantDataArraySlice Slice;
3069 if (!getConstantDataArrayInfo(V, Slice, 8, Offset))
3070 return false;
3071
3072 if (Slice.Array == nullptr) {
3073 if (TrimAtNul) {
3074 Str = StringRef();
3075 return true;
3076 }
3077 if (Slice.Length == 1) {
3078 Str = StringRef("", 1);
3079 return true;
3080 }
Sanjay Patelfef83e82017-06-09 14:21:18 +00003081 // We cannot instantiate a StringRef as we do not have an appropriate string
Matthias Braun50ec0b52017-05-19 22:37:09 +00003082 // of 0s at hand.
3083 return false;
3084 }
3085
3086 // Start out with the entire array in the StringRef.
3087 Str = Slice.Array->getAsString();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003088 // Skip over 'offset' bytes.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003089 Str = Str.substr(Slice.Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00003090
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003091 if (TrimAtNul) {
3092 // Trim off the \0 and anything after it. If the array is not nul
3093 // terminated, we just return the whole end of string. The client may know
3094 // some other way that the string is length-bound.
3095 Str = Str.substr(0, Str.find('\0'));
3096 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003097 return true;
Evan Chengda3db112008-06-30 07:31:25 +00003098}
Eric Christopher4899cbc2010-03-05 06:58:57 +00003099
3100// These next two are very similar to the above, but also look through PHI
3101// nodes.
3102// TODO: See if we can integrate these two together.
3103
Sanjay Patelaee84212014-11-04 16:27:42 +00003104/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003105/// the specified pointer, return 'len+1'. If we can't, return 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00003106static uint64_t GetStringLengthH(const Value *V,
Matthias Braun50ec0b52017-05-19 22:37:09 +00003107 SmallPtrSetImpl<const PHINode*> &PHIs,
3108 unsigned CharSize) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003109 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003110 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00003111
3112 // If this is a PHI node, there are two cases: either we have already seen it
3113 // or we haven't.
Pete Cooper35b00d52016-08-13 01:05:32 +00003114 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
David Blaikie70573dc2014-11-19 07:49:26 +00003115 if (!PHIs.insert(PN).second)
Eric Christopher4899cbc2010-03-05 06:58:57 +00003116 return ~0ULL; // already in the set.
3117
3118 // If it was new, see if all the input strings are the same length.
3119 uint64_t LenSoFar = ~0ULL;
Pete Cooper833f34d2015-05-12 20:05:31 +00003120 for (Value *IncValue : PN->incoming_values()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003121 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003122 if (Len == 0) return 0; // Unknown length -> unknown.
3123
3124 if (Len == ~0ULL) continue;
3125
3126 if (Len != LenSoFar && LenSoFar != ~0ULL)
3127 return 0; // Disagree -> unknown.
3128 LenSoFar = Len;
3129 }
3130
3131 // Success, all agree.
3132 return LenSoFar;
3133 }
3134
3135 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
Pete Cooper35b00d52016-08-13 01:05:32 +00003136 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003137 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003138 if (Len1 == 0) return 0;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003139 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003140 if (Len2 == 0) return 0;
3141 if (Len1 == ~0ULL) return Len2;
3142 if (Len2 == ~0ULL) return Len1;
3143 if (Len1 != Len2) return 0;
3144 return Len1;
3145 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003146
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003147 // Otherwise, see if we can read the string.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003148 ConstantDataArraySlice Slice;
3149 if (!getConstantDataArrayInfo(V, Slice, CharSize))
Eric Christopher4899cbc2010-03-05 06:58:57 +00003150 return 0;
3151
Matthias Braun50ec0b52017-05-19 22:37:09 +00003152 if (Slice.Array == nullptr)
3153 return 1;
3154
3155 // Search for nul characters
3156 unsigned NullIndex = 0;
3157 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
3158 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
3159 break;
3160 }
3161
3162 return NullIndex + 1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003163}
3164
Sanjay Patelaee84212014-11-04 16:27:42 +00003165/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003166/// the specified pointer, return 'len+1'. If we can't, return 0.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003167uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003168 if (!V->getType()->isPointerTy()) return 0;
3169
Pete Cooper35b00d52016-08-13 01:05:32 +00003170 SmallPtrSet<const PHINode*, 32> PHIs;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003171 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003172 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
3173 // an empty string as a length.
3174 return Len == ~0ULL ? 1 : Len;
3175}
Dan Gohmana4fcd242010-12-15 20:02:24 +00003176
Adam Nemete2b885c2015-04-23 20:09:20 +00003177/// \brief \p PN defines a loop-variant pointer to an object. Check if the
3178/// previous iteration of the loop was referring to the same object as \p PN.
Pete Cooper35b00d52016-08-13 01:05:32 +00003179static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
3180 const LoopInfo *LI) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003181 // Find the loop-defined value.
3182 Loop *L = LI->getLoopFor(PN->getParent());
3183 if (PN->getNumIncomingValues() != 2)
3184 return true;
3185
3186 // Find the value from previous iteration.
3187 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3188 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3189 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3190 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3191 return true;
3192
3193 // If a new pointer is loaded in the loop, the pointer references a different
3194 // object in every iteration. E.g.:
3195 // for (i)
3196 // int *p = a[i];
3197 // ...
3198 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3199 if (!L->isLoopInvariant(Load->getPointerOperand()))
3200 return false;
3201 return true;
3202}
3203
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003204Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3205 unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003206 if (!V->getType()->isPointerTy())
3207 return V;
3208 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3209 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3210 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00003211 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3212 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003213 V = cast<Operator>(V)->getOperand(0);
3214 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003215 if (GA->isInterposable())
Dan Gohmana4fcd242010-12-15 20:02:24 +00003216 return V;
3217 V = GA->getAliasee();
Craig Topper85482412017-04-12 22:29:23 +00003218 } else if (isa<AllocaInst>(V)) {
3219 // An alloca can't be further simplified.
3220 return V;
Dan Gohmana4fcd242010-12-15 20:02:24 +00003221 } else {
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003222 if (auto CS = CallSite(V))
3223 if (Value *RV = CS.getReturnedArgOperand()) {
3224 V = RV;
3225 continue;
3226 }
3227
Dan Gohman05b18f12010-12-15 20:49:55 +00003228 // See if InstructionSimplify knows any relevant tricks.
3229 if (Instruction *I = dyn_cast<Instruction>(V))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003230 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00003231 if (Value *Simplified = SimplifyInstruction(I, {DL, I})) {
Dan Gohman05b18f12010-12-15 20:49:55 +00003232 V = Simplified;
3233 continue;
3234 }
3235
Dan Gohmana4fcd242010-12-15 20:02:24 +00003236 return V;
3237 }
3238 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3239 }
3240 return V;
3241}
Nick Lewycky3e334a42011-06-27 04:20:45 +00003242
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003243void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
Adam Nemete2b885c2015-04-23 20:09:20 +00003244 const DataLayout &DL, LoopInfo *LI,
3245 unsigned MaxLookup) {
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003246 SmallPtrSet<Value *, 4> Visited;
3247 SmallVector<Value *, 4> Worklist;
3248 Worklist.push_back(V);
3249 do {
3250 Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003251 P = GetUnderlyingObject(P, DL, MaxLookup);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003252
David Blaikie70573dc2014-11-19 07:49:26 +00003253 if (!Visited.insert(P).second)
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003254 continue;
3255
3256 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
3257 Worklist.push_back(SI->getTrueValue());
3258 Worklist.push_back(SI->getFalseValue());
3259 continue;
3260 }
3261
3262 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003263 // If this PHI changes the underlying object in every iteration of the
3264 // loop, don't look through it. Consider:
3265 // int **A;
3266 // for (i) {
3267 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
3268 // Curr = A[i];
3269 // *Prev, *Curr;
3270 //
3271 // Prev is tracking Curr one iteration behind so they refer to different
3272 // underlying objects.
3273 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3274 isSameUnderlyingObjectInLoop(PN, LI))
Pete Cooper833f34d2015-05-12 20:05:31 +00003275 for (Value *IncValue : PN->incoming_values())
3276 Worklist.push_back(IncValue);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003277 continue;
3278 }
3279
3280 Objects.push_back(P);
3281 } while (!Worklist.empty());
3282}
3283
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003284/// This is the function that does the work of looking through basic
3285/// ptrtoint+arithmetic+inttoptr sequences.
3286static const Value *getUnderlyingObjectFromInt(const Value *V) {
3287 do {
3288 if (const Operator *U = dyn_cast<Operator>(V)) {
3289 // If we find a ptrtoint, we can transfer control back to the
3290 // regular getUnderlyingObjectFromInt.
3291 if (U->getOpcode() == Instruction::PtrToInt)
3292 return U->getOperand(0);
3293 // If we find an add of a constant, a multiplied value, or a phi, it's
3294 // likely that the other operand will lead us to the base
3295 // object. We don't have to worry about the case where the
3296 // object address is somehow being computed by the multiply,
3297 // because our callers only care when the result is an
3298 // identifiable object.
3299 if (U->getOpcode() != Instruction::Add ||
3300 (!isa<ConstantInt>(U->getOperand(1)) &&
3301 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
3302 !isa<PHINode>(U->getOperand(1))))
3303 return V;
3304 V = U->getOperand(0);
3305 } else {
3306 return V;
3307 }
3308 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
3309 } while (true);
3310}
3311
3312/// This is a wrapper around GetUnderlyingObjects and adds support for basic
3313/// ptrtoint+arithmetic+inttoptr sequences.
3314void llvm::getUnderlyingObjectsForCodeGen(const Value *V,
3315 SmallVectorImpl<Value *> &Objects,
3316 const DataLayout &DL) {
3317 SmallPtrSet<const Value *, 16> Visited;
3318 SmallVector<const Value *, 4> Working(1, V);
3319 do {
3320 V = Working.pop_back_val();
3321
3322 SmallVector<Value *, 4> Objs;
3323 GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
3324
3325 for (Value *V : Objs) {
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003326 if (!Visited.insert(V).second)
3327 continue;
3328 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
3329 const Value *O =
3330 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
3331 if (O->getType()->isPointerTy()) {
3332 Working.push_back(O);
3333 continue;
3334 }
3335 }
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003336 // If GetUnderlyingObjects fails to find an identifiable object,
3337 // getUnderlyingObjectsForCodeGen also fails for safety.
3338 if (!isIdentifiedObject(V)) {
3339 Objects.clear();
3340 return;
3341 }
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003342 Objects.push_back(const_cast<Value *>(V));
3343 }
3344 } while (!Working.empty());
3345}
3346
Sanjay Patelaee84212014-11-04 16:27:42 +00003347/// Return true if the only users of this pointer are lifetime markers.
Nick Lewycky3e334a42011-06-27 04:20:45 +00003348bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003349 for (const User *U : V->users()) {
3350 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00003351 if (!II) return false;
3352
3353 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
3354 II->getIntrinsicID() != Intrinsic::lifetime_end)
3355 return false;
3356 }
3357 return true;
3358}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003359
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003360bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3361 const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003362 const DominatorTree *DT) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00003363 const Operator *Inst = dyn_cast<Operator>(V);
3364 if (!Inst)
3365 return false;
3366
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003367 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3368 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3369 if (C->canTrap())
3370 return false;
3371
3372 switch (Inst->getOpcode()) {
3373 default:
3374 return true;
3375 case Instruction::UDiv:
David Majnemerf20d7c42014-11-04 23:49:08 +00003376 case Instruction::URem: {
3377 // x / y is undefined if y == 0.
3378 const APInt *V;
3379 if (match(Inst->getOperand(1), m_APInt(V)))
3380 return *V != 0;
3381 return false;
3382 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003383 case Instruction::SDiv:
3384 case Instruction::SRem: {
David Majnemerf20d7c42014-11-04 23:49:08 +00003385 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
David Majnemer8a6578a2015-02-01 19:10:19 +00003386 const APInt *Numerator, *Denominator;
3387 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3388 return false;
3389 // We cannot hoist this division if the denominator is 0.
3390 if (*Denominator == 0)
3391 return false;
3392 // It's safe to hoist if the denominator is not 0 or -1.
3393 if (*Denominator != -1)
3394 return true;
3395 // At this point we know that the denominator is -1. It is safe to hoist as
3396 // long we know that the numerator is not INT_MIN.
3397 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3398 return !Numerator->isMinSignedValue();
3399 // The numerator *might* be MinSignedValue.
David Majnemerf20d7c42014-11-04 23:49:08 +00003400 return false;
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003401 }
3402 case Instruction::Load: {
3403 const LoadInst *LI = cast<LoadInst>(Inst);
Kostya Serebryany0b458282013-11-21 07:29:28 +00003404 if (!LI->isUnordered() ||
3405 // Speculative load may create a race that did not exist in the source.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003406 LI->getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
Kostya Serebryany5cb86d52015-10-14 00:21:05 +00003407 // Speculative load may load data from dirty regions.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003408 LI->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003409 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003410 const DataLayout &DL = LI->getModule()->getDataLayout();
Sean Silva45835e72016-07-02 23:47:27 +00003411 return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
3412 LI->getAlignment(), DL, CtxI, DT);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003413 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003414 case Instruction::Call: {
Matt Arsenaultcf5e7fe2017-04-28 21:13:09 +00003415 auto *CI = cast<const CallInst>(Inst);
3416 const Function *Callee = CI->getCalledFunction();
David Majnemer0a92f862015-08-28 21:13:39 +00003417
Matt Arsenault6a288c12017-05-03 02:26:10 +00003418 // The called function could have undefined behavior or side-effects, even
3419 // if marked readnone nounwind.
3420 return Callee && Callee->isSpeculatable();
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003421 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003422 case Instruction::VAArg:
3423 case Instruction::Alloca:
3424 case Instruction::Invoke:
3425 case Instruction::PHI:
3426 case Instruction::Store:
3427 case Instruction::Ret:
3428 case Instruction::Br:
3429 case Instruction::IndirectBr:
3430 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003431 case Instruction::Unreachable:
3432 case Instruction::Fence:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003433 case Instruction::AtomicRMW:
3434 case Instruction::AtomicCmpXchg:
David Majnemer654e1302015-07-31 17:58:14 +00003435 case Instruction::LandingPad:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003436 case Instruction::Resume:
David Majnemer8a1c45d2015-12-12 05:38:55 +00003437 case Instruction::CatchSwitch:
David Majnemer654e1302015-07-31 17:58:14 +00003438 case Instruction::CatchPad:
David Majnemer654e1302015-07-31 17:58:14 +00003439 case Instruction::CatchRet:
3440 case Instruction::CleanupPad:
3441 case Instruction::CleanupRet:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003442 return false; // Misc instructions which have effects
3443 }
3444}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003445
Quentin Colombet6443cce2015-08-06 18:44:34 +00003446bool llvm::mayBeMemoryDependent(const Instruction &I) {
3447 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3448}
3449
Sanjay Patelaee84212014-11-04 16:27:42 +00003450/// Return true if we know that the specified value is never null.
Sean Silva45835e72016-07-02 23:47:27 +00003451bool llvm::isKnownNonNull(const Value *V) {
Chen Li0d043b52015-09-14 18:10:43 +00003452 assert(V->getType()->isPointerTy() && "V must be pointer type");
3453
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003454 // Alloca never returns null, malloc might.
3455 if (isa<AllocaInst>(V)) return true;
3456
Nick Lewyckyd52b1522014-05-20 01:23:40 +00003457 // A byval, inalloca, or nonnull argument is never null.
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003458 if (const Argument *A = dyn_cast<Argument>(V))
Nick Lewyckyd52b1522014-05-20 01:23:40 +00003459 return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003460
Peter Collingbourne235c2752016-12-08 19:01:00 +00003461 // A global variable in address space 0 is non null unless extern weak
3462 // or an absolute symbol reference. Other address spaces may have null as a
3463 // valid address for a global, so we can't assume anything.
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003464 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Peter Collingbourne235c2752016-12-08 19:01:00 +00003465 return !GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
Pete Cooper6b716212015-08-27 03:16:29 +00003466 GV->getType()->getAddressSpace() == 0;
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00003467
Sanjoy Das5056e192016-05-07 02:08:22 +00003468 // A Load tagged with nonnull metadata is never null.
Philip Reamescdb72f32014-10-20 22:40:55 +00003469 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
Philip Reames5a3f5f72014-10-21 00:13:20 +00003470 return LI->getMetadata(LLVMContext::MD_nonnull);
Philip Reamescdb72f32014-10-20 22:40:55 +00003471
Benjamin Kramer3a09ef62015-04-10 14:50:08 +00003472 if (auto CS = ImmutableCallSite(V))
Hal Finkelb0407ba2014-07-18 15:51:28 +00003473 if (CS.isReturnNonNull())
Nick Lewyckyec373542014-05-20 05:13:21 +00003474 return true;
3475
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003476 return false;
3477}
David Majnemer491331a2015-01-02 07:29:43 +00003478
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003479static bool isKnownNonNullFromDominatingCondition(const Value *V,
3480 const Instruction *CtxI,
3481 const DominatorTree *DT) {
Chen Li0d043b52015-09-14 18:10:43 +00003482 assert(V->getType()->isPointerTy() && "V must be pointer type");
Duncan P. N. Exon Smithb4798732016-09-24 19:39:47 +00003483 assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull");
Sanjay Patel7fd779f2016-12-31 17:37:01 +00003484 assert(CtxI && "Context instruction required for analysis");
3485 assert(DT && "Dominator tree required for analysis");
Chen Li0d043b52015-09-14 18:10:43 +00003486
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003487 unsigned NumUsesExplored = 0;
Sanjoy Das987aaa12016-05-07 02:08:24 +00003488 for (auto *U : V->users()) {
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003489 // Avoid massive lists
3490 if (NumUsesExplored >= DomConditionsMaxUses)
3491 break;
3492 NumUsesExplored++;
Sanjay Patel97e4b9872017-02-12 15:35:34 +00003493
3494 // If the value is used as an argument to a call or invoke, then argument
3495 // attributes may provide an answer about null-ness.
3496 if (auto CS = ImmutableCallSite(U))
3497 if (auto *CalledFunc = CS.getCalledFunction())
3498 for (const Argument &Arg : CalledFunc->args())
3499 if (CS.getArgOperand(Arg.getArgNo()) == V &&
3500 Arg.hasNonNullAttr() && DT->dominates(CS.getInstruction(), CtxI))
3501 return true;
3502
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003503 // Consider only compare instructions uniquely controlling a branch
Sanjoy Das987aaa12016-05-07 02:08:24 +00003504 CmpInst::Predicate Pred;
3505 if (!match(const_cast<User *>(U),
3506 m_c_ICmp(Pred, m_Specific(V), m_Zero())) ||
3507 (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE))
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003508 continue;
3509
Sanjoy Das987aaa12016-05-07 02:08:24 +00003510 for (auto *CmpU : U->users()) {
Sanjoy Das12c91dc2016-05-10 02:35:44 +00003511 if (const BranchInst *BI = dyn_cast<BranchInst>(CmpU)) {
3512 assert(BI->isConditional() && "uses a comparison!");
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003513
Sanjoy Das12c91dc2016-05-10 02:35:44 +00003514 BasicBlock *NonNullSuccessor =
3515 BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0);
3516 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3517 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
3518 return true;
3519 } else if (Pred == ICmpInst::ICMP_NE &&
3520 match(CmpU, m_Intrinsic<Intrinsic::experimental_guard>()) &&
3521 DT->dominates(cast<Instruction>(CmpU), CtxI)) {
Sanjoy Das987aaa12016-05-07 02:08:24 +00003522 return true;
Sanjoy Das12c91dc2016-05-10 02:35:44 +00003523 }
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003524 }
3525 }
3526
3527 return false;
3528}
3529
3530bool llvm::isKnownNonNullAt(const Value *V, const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003531 const DominatorTree *DT) {
Duncan P. N. Exon Smithb4798732016-09-24 19:39:47 +00003532 if (isa<ConstantPointerNull>(V) || isa<UndefValue>(V))
3533 return false;
3534
Sean Silva45835e72016-07-02 23:47:27 +00003535 if (isKnownNonNull(V))
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003536 return true;
3537
Sanjay Patel7fd779f2016-12-31 17:37:01 +00003538 if (!CtxI || !DT)
3539 return false;
3540
3541 return ::isKnownNonNullFromDominatingCondition(V, CtxI, DT);
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003542}
3543
Pete Cooper35b00d52016-08-13 01:05:32 +00003544OverflowResult llvm::computeOverflowForUnsignedMul(const Value *LHS,
3545 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003546 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003547 AssumptionCache *AC,
David Majnemer491331a2015-01-02 07:29:43 +00003548 const Instruction *CxtI,
3549 const DominatorTree *DT) {
3550 // Multiplying n * m significant bits yields a result of n + m significant
3551 // bits. If the total number of significant bits does not exceed the
3552 // result bit width (minus 1), there is no overflow.
3553 // This means if we have enough leading zero bits in the operands
3554 // we can guarantee that the result does not overflow.
3555 // Ref: "Hacker's Delight" by Henry Warren
3556 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00003557 KnownBits LHSKnown(BitWidth);
3558 KnownBits RHSKnown(BitWidth);
3559 computeKnownBits(LHS, LHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
3560 computeKnownBits(RHS, RHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
David Majnemer491331a2015-01-02 07:29:43 +00003561 // Note that underestimating the number of zero bits gives a more
3562 // conservative answer.
Craig Topper8df66c62017-05-12 17:20:30 +00003563 unsigned ZeroBits = LHSKnown.countMinLeadingZeros() +
3564 RHSKnown.countMinLeadingZeros();
David Majnemer491331a2015-01-02 07:29:43 +00003565 // First handle the easy case: if we have enough zero bits there's
3566 // definitely no overflow.
3567 if (ZeroBits >= BitWidth)
3568 return OverflowResult::NeverOverflows;
3569
3570 // Get the largest possible values for each operand.
Craig Topperb45eabc2017-04-26 16:39:58 +00003571 APInt LHSMax = ~LHSKnown.Zero;
3572 APInt RHSMax = ~RHSKnown.Zero;
David Majnemer491331a2015-01-02 07:29:43 +00003573
3574 // We know the multiply operation doesn't overflow if the maximum values for
3575 // each operand will not overflow after we multiply them together.
David Majnemerc8a576b2015-01-02 07:29:47 +00003576 bool MaxOverflow;
Craig Topper9b71a402017-04-19 21:09:45 +00003577 (void)LHSMax.umul_ov(RHSMax, MaxOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003578 if (!MaxOverflow)
3579 return OverflowResult::NeverOverflows;
David Majnemer491331a2015-01-02 07:29:43 +00003580
David Majnemerc8a576b2015-01-02 07:29:47 +00003581 // We know it always overflows if multiplying the smallest possible values for
3582 // the operands also results in overflow.
3583 bool MinOverflow;
Craig Topperb45eabc2017-04-26 16:39:58 +00003584 (void)LHSKnown.One.umul_ov(RHSKnown.One, MinOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003585 if (MinOverflow)
3586 return OverflowResult::AlwaysOverflows;
3587
3588 return OverflowResult::MayOverflow;
David Majnemer491331a2015-01-02 07:29:43 +00003589}
David Majnemer5310c1e2015-01-07 00:39:50 +00003590
Pete Cooper35b00d52016-08-13 01:05:32 +00003591OverflowResult llvm::computeOverflowForUnsignedAdd(const Value *LHS,
3592 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003593 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003594 AssumptionCache *AC,
David Majnemer5310c1e2015-01-07 00:39:50 +00003595 const Instruction *CxtI,
3596 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +00003597 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3598 if (LHSKnown.isNonNegative() || LHSKnown.isNegative()) {
3599 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
David Majnemer5310c1e2015-01-07 00:39:50 +00003600
Craig Topper6e11a052017-05-08 16:22:48 +00003601 if (LHSKnown.isNegative() && RHSKnown.isNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00003602 // The sign bit is set in both cases: this MUST overflow.
3603 // Create a simple add instruction, and insert it into the struct.
3604 return OverflowResult::AlwaysOverflows;
3605 }
3606
Craig Topper6e11a052017-05-08 16:22:48 +00003607 if (LHSKnown.isNonNegative() && RHSKnown.isNonNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00003608 // The sign bit is clear in both cases: this CANNOT overflow.
3609 // Create a simple add instruction, and insert it into the struct.
3610 return OverflowResult::NeverOverflows;
3611 }
3612 }
3613
3614 return OverflowResult::MayOverflow;
3615}
James Molloy71b91c22015-05-11 14:42:20 +00003616
Craig Topperbb973722017-05-15 02:44:08 +00003617/// \brief Return true if we can prove that adding the two values of the
3618/// knownbits will not overflow.
3619/// Otherwise return false.
3620static bool checkRippleForSignedAdd(const KnownBits &LHSKnown,
3621 const KnownBits &RHSKnown) {
3622 // Addition of two 2's complement numbers having opposite signs will never
3623 // overflow.
3624 if ((LHSKnown.isNegative() && RHSKnown.isNonNegative()) ||
3625 (LHSKnown.isNonNegative() && RHSKnown.isNegative()))
3626 return true;
3627
3628 // If either of the values is known to be non-negative, adding them can only
3629 // overflow if the second is also non-negative, so we can assume that.
3630 // Two non-negative numbers will only overflow if there is a carry to the
3631 // sign bit, so we can check if even when the values are as big as possible
3632 // there is no overflow to the sign bit.
3633 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative()) {
3634 APInt MaxLHS = ~LHSKnown.Zero;
3635 MaxLHS.clearSignBit();
3636 APInt MaxRHS = ~RHSKnown.Zero;
3637 MaxRHS.clearSignBit();
3638 APInt Result = std::move(MaxLHS) + std::move(MaxRHS);
3639 return Result.isSignBitClear();
3640 }
3641
3642 // If either of the values is known to be negative, adding them can only
3643 // overflow if the second is also negative, so we can assume that.
3644 // Two negative number will only overflow if there is no carry to the sign
3645 // bit, so we can check if even when the values are as small as possible
3646 // there is overflow to the sign bit.
3647 if (LHSKnown.isNegative() || RHSKnown.isNegative()) {
3648 APInt MinLHS = LHSKnown.One;
3649 MinLHS.clearSignBit();
3650 APInt MinRHS = RHSKnown.One;
3651 MinRHS.clearSignBit();
3652 APInt Result = std::move(MinLHS) + std::move(MinRHS);
3653 return Result.isSignBitSet();
3654 }
3655
3656 // If we reached here it means that we know nothing about the sign bits.
3657 // In this case we can't know if there will be an overflow, since by
3658 // changing the sign bits any two values can be made to overflow.
3659 return false;
3660}
3661
Pete Cooper35b00d52016-08-13 01:05:32 +00003662static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
3663 const Value *RHS,
3664 const AddOperator *Add,
3665 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003666 AssumptionCache *AC,
Pete Cooper35b00d52016-08-13 01:05:32 +00003667 const Instruction *CxtI,
3668 const DominatorTree *DT) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003669 if (Add && Add->hasNoSignedWrap()) {
3670 return OverflowResult::NeverOverflows;
3671 }
3672
Craig Topperbb973722017-05-15 02:44:08 +00003673 // If LHS and RHS each have at least two sign bits, the addition will look
3674 // like
3675 //
3676 // XX..... +
3677 // YY.....
3678 //
3679 // If the carry into the most significant position is 0, X and Y can't both
3680 // be 1 and therefore the carry out of the addition is also 0.
3681 //
3682 // If the carry into the most significant position is 1, X and Y can't both
3683 // be 0 and therefore the carry out of the addition is also 1.
3684 //
3685 // Since the carry into the most significant position is always equal to
3686 // the carry out of the addition, there is no signed overflow.
3687 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
3688 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
3689 return OverflowResult::NeverOverflows;
3690
Craig Topper6e11a052017-05-08 16:22:48 +00003691 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3692 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003693
Craig Topperbb973722017-05-15 02:44:08 +00003694 if (checkRippleForSignedAdd(LHSKnown, RHSKnown))
Jingyue Wu10fcea52015-08-20 18:27:04 +00003695 return OverflowResult::NeverOverflows;
Jingyue Wu10fcea52015-08-20 18:27:04 +00003696
3697 // The remaining code needs Add to be available. Early returns if not so.
3698 if (!Add)
3699 return OverflowResult::MayOverflow;
3700
3701 // If the sign of Add is the same as at least one of the operands, this add
3702 // CANNOT overflow. This is particularly useful when the sum is
3703 // @llvm.assume'ed non-negative rather than proved so from analyzing its
3704 // operands.
3705 bool LHSOrRHSKnownNonNegative =
Craig Topper6e11a052017-05-08 16:22:48 +00003706 (LHSKnown.isNonNegative() || RHSKnown.isNonNegative());
Craig Topperbb973722017-05-15 02:44:08 +00003707 bool LHSOrRHSKnownNegative =
3708 (LHSKnown.isNegative() || RHSKnown.isNegative());
Jingyue Wu10fcea52015-08-20 18:27:04 +00003709 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
Craig Topper6e11a052017-05-08 16:22:48 +00003710 KnownBits AddKnown = computeKnownBits(Add, DL, /*Depth=*/0, AC, CxtI, DT);
3711 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
3712 (AddKnown.isNegative() && LHSOrRHSKnownNegative)) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003713 return OverflowResult::NeverOverflows;
3714 }
3715 }
3716
3717 return OverflowResult::MayOverflow;
3718}
3719
Pete Cooper35b00d52016-08-13 01:05:32 +00003720bool llvm::isOverflowIntrinsicNoWrap(const IntrinsicInst *II,
3721 const DominatorTree &DT) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003722#ifndef NDEBUG
3723 auto IID = II->getIntrinsicID();
3724 assert((IID == Intrinsic::sadd_with_overflow ||
3725 IID == Intrinsic::uadd_with_overflow ||
3726 IID == Intrinsic::ssub_with_overflow ||
3727 IID == Intrinsic::usub_with_overflow ||
3728 IID == Intrinsic::smul_with_overflow ||
3729 IID == Intrinsic::umul_with_overflow) &&
3730 "Not an overflow intrinsic!");
3731#endif
3732
Pete Cooper35b00d52016-08-13 01:05:32 +00003733 SmallVector<const BranchInst *, 2> GuardingBranches;
3734 SmallVector<const ExtractValueInst *, 2> Results;
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003735
Pete Cooper35b00d52016-08-13 01:05:32 +00003736 for (const User *U : II->users()) {
3737 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003738 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
3739
3740 if (EVI->getIndices()[0] == 0)
3741 Results.push_back(EVI);
3742 else {
3743 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
3744
Pete Cooper35b00d52016-08-13 01:05:32 +00003745 for (const auto *U : EVI->users())
3746 if (const auto *B = dyn_cast<BranchInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003747 assert(B->isConditional() && "How else is it using an i1?");
3748 GuardingBranches.push_back(B);
3749 }
3750 }
3751 } else {
3752 // We are using the aggregate directly in a way we don't want to analyze
3753 // here (storing it to a global, say).
3754 return false;
3755 }
3756 }
3757
Pete Cooper35b00d52016-08-13 01:05:32 +00003758 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003759 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
3760 if (!NoWrapEdge.isSingleEdge())
3761 return false;
3762
3763 // Check if all users of the add are provably no-wrap.
Pete Cooper35b00d52016-08-13 01:05:32 +00003764 for (const auto *Result : Results) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003765 // If the extractvalue itself is not executed on overflow, the we don't
3766 // need to check each use separately, since domination is transitive.
3767 if (DT.dominates(NoWrapEdge, Result->getParent()))
3768 continue;
3769
3770 for (auto &RU : Result->uses())
3771 if (!DT.dominates(NoWrapEdge, RU))
3772 return false;
3773 }
3774
3775 return true;
3776 };
3777
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003778 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003779}
3780
3781
Pete Cooper35b00d52016-08-13 01:05:32 +00003782OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003783 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003784 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003785 const Instruction *CxtI,
3786 const DominatorTree *DT) {
3787 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003788 Add, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003789}
3790
Pete Cooper35b00d52016-08-13 01:05:32 +00003791OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
3792 const Value *RHS,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003793 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003794 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003795 const Instruction *CxtI,
3796 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003797 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003798}
3799
Jingyue Wu42f1d672015-07-28 18:22:40 +00003800bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003801 // A memory operation returns normally if it isn't volatile. A volatile
3802 // operation is allowed to trap.
3803 //
3804 // An atomic operation isn't guaranteed to return in a reasonable amount of
3805 // time because it's possible for another thread to interfere with it for an
3806 // arbitrary length of time, but programs aren't allowed to rely on that.
3807 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
3808 return !LI->isVolatile();
3809 if (const StoreInst *SI = dyn_cast<StoreInst>(I))
3810 return !SI->isVolatile();
3811 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
3812 return !CXI->isVolatile();
3813 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
3814 return !RMWI->isVolatile();
3815 if (const MemIntrinsic *MII = dyn_cast<MemIntrinsic>(I))
3816 return !MII->isVolatile();
Jingyue Wu42f1d672015-07-28 18:22:40 +00003817
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003818 // If there is no successor, then execution can't transfer to it.
3819 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I))
3820 return !CRI->unwindsToCaller();
3821 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I))
3822 return !CatchSwitch->unwindsToCaller();
3823 if (isa<ResumeInst>(I))
3824 return false;
3825 if (isa<ReturnInst>(I))
3826 return false;
Sebastian Pop4a4d2452017-03-08 01:54:50 +00003827 if (isa<UnreachableInst>(I))
3828 return false;
Sanjoy Das9a65cd22016-06-08 17:48:36 +00003829
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003830 // Calls can throw, or contain an infinite loop, or kill the process.
Sanjoy Das09455302016-12-31 22:12:31 +00003831 if (auto CS = ImmutableCallSite(I)) {
Sanjoy Das3bb2dbd2016-12-31 22:12:34 +00003832 // Call sites that throw have implicit non-local control flow.
3833 if (!CS.doesNotThrow())
3834 return false;
3835
3836 // Non-throwing call sites can loop infinitely, call exit/pthread_exit
3837 // etc. and thus not return. However, LLVM already assumes that
3838 //
3839 // - Thread exiting actions are modeled as writes to memory invisible to
3840 // the program.
3841 //
3842 // - Loops that don't have side effects (side effects are volatile/atomic
3843 // stores and IO) always terminate (see http://llvm.org/PR965).
3844 // Furthermore IO itself is also modeled as writes to memory invisible to
3845 // the program.
3846 //
3847 // We rely on those assumptions here, and use the memory effects of the call
3848 // target as a proxy for checking that it always returns.
3849
3850 // FIXME: This isn't aggressive enough; a call which only writes to a global
3851 // is guaranteed to return.
Sanjoy Dasd7e82062016-06-14 20:23:16 +00003852 return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory() ||
3853 match(I, m_Intrinsic<Intrinsic::assume>());
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003854 }
3855
3856 // Other instructions return normally.
3857 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003858}
3859
3860bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
3861 const Loop *L) {
3862 // The loop header is guaranteed to be executed for every iteration.
3863 //
3864 // FIXME: Relax this constraint to cover all basic blocks that are
3865 // guaranteed to be executed at every iteration.
3866 if (I->getParent() != L->getHeader()) return false;
3867
3868 for (const Instruction &LI : *L->getHeader()) {
3869 if (&LI == I) return true;
3870 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
3871 }
3872 llvm_unreachable("Instruction not contained in its own parent basic block.");
3873}
3874
3875bool llvm::propagatesFullPoison(const Instruction *I) {
3876 switch (I->getOpcode()) {
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003877 case Instruction::Add:
3878 case Instruction::Sub:
3879 case Instruction::Xor:
3880 case Instruction::Trunc:
3881 case Instruction::BitCast:
3882 case Instruction::AddrSpaceCast:
Sanjoy Das5cd6c5ca2017-02-22 06:52:32 +00003883 case Instruction::Mul:
3884 case Instruction::Shl:
3885 case Instruction::GetElementPtr:
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003886 // These operations all propagate poison unconditionally. Note that poison
3887 // is not any particular value, so xor or subtraction of poison with
3888 // itself still yields poison, not zero.
3889 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003890
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003891 case Instruction::AShr:
3892 case Instruction::SExt:
3893 // For these operations, one bit of the input is replicated across
3894 // multiple output bits. A replicated poison bit is still poison.
3895 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003896
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003897 case Instruction::ICmp:
3898 // Comparing poison with any value yields poison. This is why, for
3899 // instance, x s< (x +nsw 1) can be folded to true.
3900 return true;
Sanjoy Das70c2bbd2016-05-29 00:31:18 +00003901
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003902 default:
3903 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003904 }
3905}
3906
3907const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
3908 switch (I->getOpcode()) {
3909 case Instruction::Store:
3910 return cast<StoreInst>(I)->getPointerOperand();
3911
3912 case Instruction::Load:
3913 return cast<LoadInst>(I)->getPointerOperand();
3914
3915 case Instruction::AtomicCmpXchg:
3916 return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
3917
3918 case Instruction::AtomicRMW:
3919 return cast<AtomicRMWInst>(I)->getPointerOperand();
3920
3921 case Instruction::UDiv:
3922 case Instruction::SDiv:
3923 case Instruction::URem:
3924 case Instruction::SRem:
3925 return I->getOperand(1);
3926
3927 default:
3928 return nullptr;
3929 }
3930}
3931
Sanjoy Das08989c72017-04-30 19:41:19 +00003932bool llvm::programUndefinedIfFullPoison(const Instruction *PoisonI) {
Jingyue Wu42f1d672015-07-28 18:22:40 +00003933 // We currently only look for uses of poison values within the same basic
3934 // block, as that makes it easier to guarantee that the uses will be
3935 // executed given that PoisonI is executed.
3936 //
3937 // FIXME: Expand this to consider uses beyond the same basic block. To do
3938 // this, look out for the distinction between post-dominance and strong
3939 // post-dominance.
3940 const BasicBlock *BB = PoisonI->getParent();
3941
3942 // Set of instructions that we have proved will yield poison if PoisonI
3943 // does.
3944 SmallSet<const Value *, 16> YieldsPoison;
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003945 SmallSet<const BasicBlock *, 4> Visited;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003946 YieldsPoison.insert(PoisonI);
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003947 Visited.insert(PoisonI->getParent());
Jingyue Wu42f1d672015-07-28 18:22:40 +00003948
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003949 BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end();
Jingyue Wu42f1d672015-07-28 18:22:40 +00003950
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003951 unsigned Iter = 0;
3952 while (Iter++ < MaxDepth) {
3953 for (auto &I : make_range(Begin, End)) {
3954 if (&I != PoisonI) {
3955 const Value *NotPoison = getGuaranteedNonFullPoisonOp(&I);
3956 if (NotPoison != nullptr && YieldsPoison.count(NotPoison))
3957 return true;
3958 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
3959 return false;
3960 }
3961
3962 // Mark poison that propagates from I through uses of I.
3963 if (YieldsPoison.count(&I)) {
3964 for (const User *User : I.users()) {
3965 const Instruction *UserI = cast<Instruction>(User);
3966 if (propagatesFullPoison(UserI))
3967 YieldsPoison.insert(User);
3968 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003969 }
3970 }
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003971
3972 if (auto *NextBB = BB->getSingleSuccessor()) {
3973 if (Visited.insert(NextBB).second) {
3974 BB = NextBB;
3975 Begin = BB->getFirstNonPHI()->getIterator();
3976 End = BB->end();
3977 continue;
3978 }
3979 }
3980
3981 break;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003982 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003983 return false;
3984}
3985
Pete Cooper35b00d52016-08-13 01:05:32 +00003986static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
James Molloy134bec22015-08-11 09:12:57 +00003987 if (FMF.noNaNs())
3988 return true;
3989
3990 if (auto *C = dyn_cast<ConstantFP>(V))
3991 return !C->isNaN();
3992 return false;
3993}
3994
Pete Cooper35b00d52016-08-13 01:05:32 +00003995static bool isKnownNonZero(const Value *V) {
James Molloy134bec22015-08-11 09:12:57 +00003996 if (auto *C = dyn_cast<ConstantFP>(V))
3997 return !C->isZero();
3998 return false;
3999}
4000
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004001/// Match clamp pattern for float types without care about NaNs or signed zeros.
4002/// Given non-min/max outer cmp/select from the clamp pattern this
4003/// function recognizes if it can be substitued by a "canonical" min/max
4004/// pattern.
4005static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred,
4006 Value *CmpLHS, Value *CmpRHS,
4007 Value *TrueVal, Value *FalseVal,
4008 Value *&LHS, Value *&RHS) {
4009 // Try to match
4010 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
4011 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
4012 // and return description of the outer Max/Min.
4013
4014 // First, check if select has inverse order:
4015 if (CmpRHS == FalseVal) {
4016 std::swap(TrueVal, FalseVal);
4017 Pred = CmpInst::getInversePredicate(Pred);
4018 }
4019
4020 // Assume success now. If there's no match, callers should not use these anyway.
4021 LHS = TrueVal;
4022 RHS = FalseVal;
4023
4024 const APFloat *FC1;
4025 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
4026 return {SPF_UNKNOWN, SPNB_NA, false};
4027
4028 const APFloat *FC2;
4029 switch (Pred) {
4030 case CmpInst::FCMP_OLT:
4031 case CmpInst::FCMP_OLE:
4032 case CmpInst::FCMP_ULT:
4033 case CmpInst::FCMP_ULE:
4034 if (match(FalseVal,
4035 m_CombineOr(m_OrdFMin(m_Specific(CmpLHS), m_APFloat(FC2)),
4036 m_UnordFMin(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4037 FC1->compare(*FC2) == APFloat::cmpResult::cmpLessThan)
4038 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
4039 break;
4040 case CmpInst::FCMP_OGT:
4041 case CmpInst::FCMP_OGE:
4042 case CmpInst::FCMP_UGT:
4043 case CmpInst::FCMP_UGE:
4044 if (match(FalseVal,
4045 m_CombineOr(m_OrdFMax(m_Specific(CmpLHS), m_APFloat(FC2)),
4046 m_UnordFMax(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4047 FC1->compare(*FC2) == APFloat::cmpResult::cmpGreaterThan)
4048 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
4049 break;
4050 default:
4051 break;
4052 }
4053
4054 return {SPF_UNKNOWN, SPNB_NA, false};
4055}
4056
Sanjay Patel819f0962016-11-13 19:30:19 +00004057/// Match non-obvious integer minimum and maximum sequences.
4058static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
4059 Value *CmpLHS, Value *CmpRHS,
4060 Value *TrueVal, Value *FalseVal,
4061 Value *&LHS, Value *&RHS) {
Sanjay Patel24c6f882017-01-21 17:51:25 +00004062 // Assume success. If there's no match, callers should not use these anyway.
4063 LHS = TrueVal;
4064 RHS = FalseVal;
4065
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004066 // Recognize variations of:
4067 // CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
4068 const APInt *C1;
4069 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
4070 const APInt *C2;
4071
4072 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
4073 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004074 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004075 return {SPF_SMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004076
4077 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
4078 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004079 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004080 return {SPF_SMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004081
4082 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
4083 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004084 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004085 return {SPF_UMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004086
4087 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
4088 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004089 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004090 return {SPF_UMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004091 }
4092
Sanjay Patel819f0962016-11-13 19:30:19 +00004093 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
4094 return {SPF_UNKNOWN, SPNB_NA, false};
4095
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004096 // Z = X -nsw Y
4097 // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
4098 // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
4099 if (match(TrueVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004100 match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004101 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004102
4103 // Z = X -nsw Y
4104 // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
4105 // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
4106 if (match(FalseVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004107 match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004108 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004109
Sanjay Patel819f0962016-11-13 19:30:19 +00004110 if (!match(CmpRHS, m_APInt(C1)))
4111 return {SPF_UNKNOWN, SPNB_NA, false};
4112
4113 // An unsigned min/max can be written with a signed compare.
4114 const APInt *C2;
4115 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
4116 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
4117 // Is the sign bit set?
4118 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
4119 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
Sanjay Patel24c6f882017-01-21 17:51:25 +00004120 if (Pred == CmpInst::ICMP_SLT && *C1 == 0 && C2->isMaxSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004121 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004122
4123 // Is the sign bit clear?
4124 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
4125 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
4126 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004127 C2->isMinSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004128 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004129 }
4130
4131 // Look through 'not' ops to find disguised signed min/max.
4132 // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C)
4133 // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C)
4134 if (match(TrueVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004135 match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2)
Sanjay Patel819f0962016-11-13 19:30:19 +00004136 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004137
4138 // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X)
4139 // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X)
4140 if (match(FalseVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004141 match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2)
Sanjay Patel819f0962016-11-13 19:30:19 +00004142 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004143
4144 return {SPF_UNKNOWN, SPNB_NA, false};
4145}
4146
James Molloy134bec22015-08-11 09:12:57 +00004147static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
4148 FastMathFlags FMF,
James Molloy270ef8c2015-05-15 16:04:50 +00004149 Value *CmpLHS, Value *CmpRHS,
4150 Value *TrueVal, Value *FalseVal,
4151 Value *&LHS, Value *&RHS) {
James Molloy71b91c22015-05-11 14:42:20 +00004152 LHS = CmpLHS;
4153 RHS = CmpRHS;
4154
James Molloy134bec22015-08-11 09:12:57 +00004155 // If the predicate is an "or-equal" (FP) predicate, then signed zeroes may
4156 // return inconsistent results between implementations.
4157 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
4158 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
4159 // Therefore we behave conservatively and only proceed if at least one of the
4160 // operands is known to not be zero, or if we don't care about signed zeroes.
4161 switch (Pred) {
4162 default: break;
4163 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
4164 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
4165 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4166 !isKnownNonZero(CmpRHS))
4167 return {SPF_UNKNOWN, SPNB_NA, false};
4168 }
4169
4170 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
4171 bool Ordered = false;
4172
4173 // When given one NaN and one non-NaN input:
4174 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
4175 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
4176 // ordered comparison fails), which could be NaN or non-NaN.
4177 // so here we discover exactly what NaN behavior is required/accepted.
4178 if (CmpInst::isFPPredicate(Pred)) {
4179 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
4180 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
4181
4182 if (LHSSafe && RHSSafe) {
4183 // Both operands are known non-NaN.
4184 NaNBehavior = SPNB_RETURNS_ANY;
4185 } else if (CmpInst::isOrdered(Pred)) {
4186 // An ordered comparison will return false when given a NaN, so it
4187 // returns the RHS.
4188 Ordered = true;
4189 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004190 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004191 NaNBehavior = SPNB_RETURNS_NAN;
4192 else if (RHSSafe)
4193 NaNBehavior = SPNB_RETURNS_OTHER;
4194 else
4195 // Completely unsafe.
4196 return {SPF_UNKNOWN, SPNB_NA, false};
4197 } else {
4198 Ordered = false;
4199 // An unordered comparison will return true when given a NaN, so it
4200 // returns the LHS.
4201 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004202 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004203 NaNBehavior = SPNB_RETURNS_OTHER;
4204 else if (RHSSafe)
4205 NaNBehavior = SPNB_RETURNS_NAN;
4206 else
4207 // Completely unsafe.
4208 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004209 }
4210 }
4211
James Molloy71b91c22015-05-11 14:42:20 +00004212 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
James Molloy134bec22015-08-11 09:12:57 +00004213 std::swap(CmpLHS, CmpRHS);
4214 Pred = CmpInst::getSwappedPredicate(Pred);
4215 if (NaNBehavior == SPNB_RETURNS_NAN)
4216 NaNBehavior = SPNB_RETURNS_OTHER;
4217 else if (NaNBehavior == SPNB_RETURNS_OTHER)
4218 NaNBehavior = SPNB_RETURNS_NAN;
4219 Ordered = !Ordered;
4220 }
4221
4222 // ([if]cmp X, Y) ? X : Y
4223 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
James Molloy71b91c22015-05-11 14:42:20 +00004224 switch (Pred) {
James Molloy134bec22015-08-11 09:12:57 +00004225 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
James Molloy71b91c22015-05-11 14:42:20 +00004226 case ICmpInst::ICMP_UGT:
James Molloy134bec22015-08-11 09:12:57 +00004227 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004228 case ICmpInst::ICMP_SGT:
James Molloy134bec22015-08-11 09:12:57 +00004229 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004230 case ICmpInst::ICMP_ULT:
James Molloy134bec22015-08-11 09:12:57 +00004231 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004232 case ICmpInst::ICMP_SLT:
James Molloy134bec22015-08-11 09:12:57 +00004233 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
4234 case FCmpInst::FCMP_UGT:
4235 case FCmpInst::FCMP_UGE:
4236 case FCmpInst::FCMP_OGT:
4237 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
4238 case FCmpInst::FCMP_ULT:
4239 case FCmpInst::FCMP_ULE:
4240 case FCmpInst::FCMP_OLT:
4241 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
James Molloy71b91c22015-05-11 14:42:20 +00004242 }
4243 }
4244
Sanjay Patele372aec2016-10-27 15:26:10 +00004245 const APInt *C1;
4246 if (match(CmpRHS, m_APInt(C1))) {
James Molloy71b91c22015-05-11 14:42:20 +00004247 if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
4248 (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
4249
4250 // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
4251 // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
Sanjay Patele372aec2016-10-27 15:26:10 +00004252 if (Pred == ICmpInst::ICMP_SGT && (*C1 == 0 || C1->isAllOnesValue())) {
James Molloy134bec22015-08-11 09:12:57 +00004253 return {(CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004254 }
4255
4256 // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
4257 // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
Sanjay Patele372aec2016-10-27 15:26:10 +00004258 if (Pred == ICmpInst::ICMP_SLT && (*C1 == 0 || *C1 == 1)) {
James Molloy134bec22015-08-11 09:12:57 +00004259 return {(CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004260 }
4261 }
James Molloy71b91c22015-05-11 14:42:20 +00004262 }
4263
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004264 if (CmpInst::isIntPredicate(Pred))
4265 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
4266
4267 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
4268 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
4269 // semantics than minNum. Be conservative in such case.
4270 if (NaNBehavior != SPNB_RETURNS_ANY ||
4271 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4272 !isKnownNonZero(CmpRHS)))
4273 return {SPF_UNKNOWN, SPNB_NA, false};
4274
4275 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
James Molloy71b91c22015-05-11 14:42:20 +00004276}
James Molloy270ef8c2015-05-15 16:04:50 +00004277
James Molloy569cea62015-09-02 17:25:25 +00004278static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
4279 Instruction::CastOps *CastOp) {
Sanjay Patel14a4b812017-01-29 16:34:57 +00004280 auto *Cast1 = dyn_cast<CastInst>(V1);
4281 if (!Cast1)
James Molloy270ef8c2015-05-15 16:04:50 +00004282 return nullptr;
James Molloy270ef8c2015-05-15 16:04:50 +00004283
Sanjay Patel14a4b812017-01-29 16:34:57 +00004284 *CastOp = Cast1->getOpcode();
4285 Type *SrcTy = Cast1->getSrcTy();
4286 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
4287 // If V1 and V2 are both the same cast from the same type, look through V1.
4288 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
4289 return Cast2->getOperand(0);
James Molloy569cea62015-09-02 17:25:25 +00004290 return nullptr;
4291 }
4292
Sanjay Patel14a4b812017-01-29 16:34:57 +00004293 auto *C = dyn_cast<Constant>(V2);
4294 if (!C)
4295 return nullptr;
4296
David Majnemerd2a074b2016-04-29 18:40:34 +00004297 Constant *CastedTo = nullptr;
Sanjay Patel14a4b812017-01-29 16:34:57 +00004298 switch (*CastOp) {
4299 case Instruction::ZExt:
4300 if (CmpI->isUnsigned())
4301 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
4302 break;
4303 case Instruction::SExt:
4304 if (CmpI->isSigned())
4305 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
4306 break;
4307 case Instruction::Trunc:
4308 CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
4309 break;
4310 case Instruction::FPTrunc:
4311 CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
4312 break;
4313 case Instruction::FPExt:
4314 CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
4315 break;
4316 case Instruction::FPToUI:
4317 CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
4318 break;
4319 case Instruction::FPToSI:
4320 CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
4321 break;
4322 case Instruction::UIToFP:
4323 CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
4324 break;
4325 case Instruction::SIToFP:
4326 CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
4327 break;
4328 default:
4329 break;
4330 }
David Majnemerd2a074b2016-04-29 18:40:34 +00004331
4332 if (!CastedTo)
4333 return nullptr;
4334
David Majnemerd2a074b2016-04-29 18:40:34 +00004335 // Make sure the cast doesn't lose any information.
Sanjay Patel14a4b812017-01-29 16:34:57 +00004336 Constant *CastedBack =
4337 ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
David Majnemerd2a074b2016-04-29 18:40:34 +00004338 if (CastedBack != C)
4339 return nullptr;
4340
4341 return CastedTo;
James Molloy270ef8c2015-05-15 16:04:50 +00004342}
4343
Sanjay Patele8dc0902016-05-23 17:57:54 +00004344SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004345 Instruction::CastOps *CastOp) {
4346 SelectInst *SI = dyn_cast<SelectInst>(V);
James Molloy134bec22015-08-11 09:12:57 +00004347 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004348
James Molloy134bec22015-08-11 09:12:57 +00004349 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
4350 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004351
James Molloy134bec22015-08-11 09:12:57 +00004352 CmpInst::Predicate Pred = CmpI->getPredicate();
James Molloy270ef8c2015-05-15 16:04:50 +00004353 Value *CmpLHS = CmpI->getOperand(0);
4354 Value *CmpRHS = CmpI->getOperand(1);
4355 Value *TrueVal = SI->getTrueValue();
4356 Value *FalseVal = SI->getFalseValue();
James Molloy134bec22015-08-11 09:12:57 +00004357 FastMathFlags FMF;
4358 if (isa<FPMathOperator>(CmpI))
4359 FMF = CmpI->getFastMathFlags();
James Molloy270ef8c2015-05-15 16:04:50 +00004360
4361 // Bail out early.
4362 if (CmpI->isEquality())
James Molloy134bec22015-08-11 09:12:57 +00004363 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004364
4365 // Deal with type mismatches.
4366 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
James Molloy569cea62015-09-02 17:25:25 +00004367 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp))
James Molloy134bec22015-08-11 09:12:57 +00004368 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004369 cast<CastInst>(TrueVal)->getOperand(0), C,
4370 LHS, RHS);
James Molloy569cea62015-09-02 17:25:25 +00004371 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp))
James Molloy134bec22015-08-11 09:12:57 +00004372 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004373 C, cast<CastInst>(FalseVal)->getOperand(0),
4374 LHS, RHS);
4375 }
James Molloy134bec22015-08-11 09:12:57 +00004376 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
James Molloy270ef8c2015-05-15 16:04:50 +00004377 LHS, RHS);
4378}
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004379
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004380/// Return true if "icmp Pred LHS RHS" is always true.
Chad Rosiere42b44b2017-07-28 14:39:06 +00004381static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
4382 const Value *RHS, const DataLayout &DL,
4383 unsigned Depth) {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004384 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004385 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
4386 return true;
4387
4388 switch (Pred) {
4389 default:
4390 return false;
4391
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004392 case CmpInst::ICMP_SLE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004393 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004394
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004395 // LHS s<= LHS +_{nsw} C if C >= 0
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004396 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004397 return !C->isNegative();
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004398 return false;
4399 }
4400
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004401 case CmpInst::ICMP_ULE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004402 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004403
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004404 // LHS u<= LHS +_{nuw} C for any C
4405 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasc01b4d22015-11-06 19:01:03 +00004406 return true;
Sanjoy Das92568102015-11-10 23:56:20 +00004407
4408 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
Pete Cooper35b00d52016-08-13 01:05:32 +00004409 auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
4410 const Value *&X,
Sanjoy Das92568102015-11-10 23:56:20 +00004411 const APInt *&CA, const APInt *&CB) {
4412 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
4413 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
4414 return true;
4415
4416 // If X & C == 0 then (X | C) == X +_{nuw} C
4417 if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
4418 match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
Craig Topperb45eabc2017-04-26 16:39:58 +00004419 KnownBits Known(CA->getBitWidth());
Chad Rosiere42b44b2017-07-28 14:39:06 +00004420 computeKnownBits(X, Known, DL, Depth + 1, /*AC*/ nullptr,
4421 /*CxtI*/ nullptr, /*DT*/ nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +00004422 if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
Sanjoy Das92568102015-11-10 23:56:20 +00004423 return true;
4424 }
4425
4426 return false;
4427 };
4428
Pete Cooper35b00d52016-08-13 01:05:32 +00004429 const Value *X;
Sanjoy Das92568102015-11-10 23:56:20 +00004430 const APInt *CLHS, *CRHS;
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004431 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
4432 return CLHS->ule(*CRHS);
Sanjoy Das92568102015-11-10 23:56:20 +00004433
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004434 return false;
4435 }
4436 }
4437}
4438
4439/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
Chad Rosier41dd31f2016-04-20 19:15:26 +00004440/// ALHS ARHS" is true. Otherwise, return None.
4441static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004442isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
Chad Rosiere42b44b2017-07-28 14:39:06 +00004443 const Value *ARHS, const Value *BLHS, const Value *BRHS,
4444 const DataLayout &DL, unsigned Depth) {
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004445 switch (Pred) {
4446 default:
Chad Rosier41dd31f2016-04-20 19:15:26 +00004447 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004448
4449 case CmpInst::ICMP_SLT:
4450 case CmpInst::ICMP_SLE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00004451 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth) &&
4452 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004453 return true;
4454 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004455
4456 case CmpInst::ICMP_ULT:
4457 case CmpInst::ICMP_ULE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00004458 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth) &&
4459 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004460 return true;
4461 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004462 }
4463}
4464
Chad Rosier226a7342016-05-05 17:41:19 +00004465/// Return true if the operands of the two compares match. IsSwappedOps is true
4466/// when the operands match, but are swapped.
Pete Cooper35b00d52016-08-13 01:05:32 +00004467static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
4468 const Value *BLHS, const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004469 bool &IsSwappedOps) {
4470
4471 bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
4472 IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
4473 return IsMatchingOps || IsSwappedOps;
4474}
4475
Chad Rosier41dd31f2016-04-20 19:15:26 +00004476/// Return true if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS BRHS" is
4477/// true. Return false if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS
4478/// BRHS" is false. Otherwise, return None if we can't infer anything.
4479static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004480 const Value *ALHS,
4481 const Value *ARHS,
Chad Rosier41dd31f2016-04-20 19:15:26 +00004482 CmpInst::Predicate BPred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004483 const Value *BLHS,
4484 const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004485 bool IsSwappedOps) {
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004486 // Canonicalize the operands so they're matching.
4487 if (IsSwappedOps) {
4488 std::swap(BLHS, BRHS);
4489 BPred = ICmpInst::getSwappedPredicate(BPred);
4490 }
Chad Rosier99bc4802016-04-21 16:18:02 +00004491 if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004492 return true;
Chad Rosier99bc4802016-04-21 16:18:02 +00004493 if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004494 return false;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004495
Chad Rosier41dd31f2016-04-20 19:15:26 +00004496 return None;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004497}
4498
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004499/// Return true if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS C2" is
4500/// true. Return false if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS
4501/// C2" is false. Otherwise, return None if we can't infer anything.
4502static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004503isImpliedCondMatchingImmOperands(CmpInst::Predicate APred, const Value *ALHS,
4504 const ConstantInt *C1,
4505 CmpInst::Predicate BPred,
4506 const Value *BLHS, const ConstantInt *C2) {
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004507 assert(ALHS == BLHS && "LHS operands must match.");
4508 ConstantRange DomCR =
4509 ConstantRange::makeExactICmpRegion(APred, C1->getValue());
4510 ConstantRange CR =
4511 ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
4512 ConstantRange Intersection = DomCR.intersectWith(CR);
4513 ConstantRange Difference = DomCR.difference(CR);
4514 if (Intersection.isEmptySet())
4515 return false;
4516 if (Difference.isEmptySet())
4517 return true;
4518 return None;
4519}
4520
Chad Rosier2f498032017-07-28 18:47:43 +00004521/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
4522/// false. Otherwise, return None if we can't infer anything.
4523static Optional<bool> isImpliedCondICmps(const ICmpInst *LHS,
4524 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00004525 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00004526 unsigned Depth) {
4527 Value *ALHS = LHS->getOperand(0);
4528 Value *ARHS = LHS->getOperand(1);
Chad Rosiera72a9ff2017-07-06 20:00:25 +00004529 // The rest of the logic assumes the LHS condition is true. If that's not the
4530 // case, invert the predicate to make it so.
Chad Rosier2f498032017-07-28 18:47:43 +00004531 ICmpInst::Predicate APred =
Chad Rosierdfd1de62017-08-01 20:18:54 +00004532 LHSIsTrue ? LHS->getPredicate() : LHS->getInversePredicate();
Chad Rosier2f498032017-07-28 18:47:43 +00004533
4534 Value *BLHS = RHS->getOperand(0);
4535 Value *BRHS = RHS->getOperand(1);
4536 ICmpInst::Predicate BPred = RHS->getPredicate();
Chad Rosiere2cbd132016-04-25 17:23:36 +00004537
Chad Rosier226a7342016-05-05 17:41:19 +00004538 // Can we infer anything when the two compares have matching operands?
4539 bool IsSwappedOps;
4540 if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, IsSwappedOps)) {
4541 if (Optional<bool> Implication = isImpliedCondMatchingOperands(
4542 APred, ALHS, ARHS, BPred, BLHS, BRHS, IsSwappedOps))
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004543 return Implication;
Chad Rosier226a7342016-05-05 17:41:19 +00004544 // No amount of additional analysis will infer the second condition, so
4545 // early exit.
4546 return None;
4547 }
4548
4549 // Can we infer anything when the LHS operands match and the RHS operands are
4550 // constants (not necessarily matching)?
4551 if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
4552 if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
4553 APred, ALHS, cast<ConstantInt>(ARHS), BPred, BLHS,
4554 cast<ConstantInt>(BRHS)))
4555 return Implication;
4556 // No amount of additional analysis will infer the second condition, so
4557 // early exit.
4558 return None;
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004559 }
4560
Chad Rosier41dd31f2016-04-20 19:15:26 +00004561 if (APred == BPred)
Chad Rosiere42b44b2017-07-28 14:39:06 +00004562 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth);
Chad Rosier41dd31f2016-04-20 19:15:26 +00004563 return None;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004564}
Chad Rosier2f498032017-07-28 18:47:43 +00004565
Chad Rosierf73a10d2017-08-01 19:22:36 +00004566/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
4567/// false. Otherwise, return None if we can't infer anything. We expect the
4568/// RHS to be an icmp and the LHS to be an 'and' or an 'or' instruction.
4569static Optional<bool> isImpliedCondAndOr(const BinaryOperator *LHS,
4570 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00004571 const DataLayout &DL, bool LHSIsTrue,
Chad Rosierf73a10d2017-08-01 19:22:36 +00004572 unsigned Depth) {
4573 // The LHS must be an 'or' or an 'and' instruction.
4574 assert((LHS->getOpcode() == Instruction::And ||
4575 LHS->getOpcode() == Instruction::Or) &&
4576 "Expected LHS to be 'and' or 'or'.");
4577
Davide Italiano1a943a92017-08-09 16:06:54 +00004578 assert(Depth <= MaxDepth && "Hit recursion limit");
Chad Rosierf73a10d2017-08-01 19:22:36 +00004579
4580 // If the result of an 'or' is false, then we know both legs of the 'or' are
4581 // false. Similarly, if the result of an 'and' is true, then we know both
4582 // legs of the 'and' are true.
4583 Value *ALHS, *ARHS;
Chad Rosierdfd1de62017-08-01 20:18:54 +00004584 if ((!LHSIsTrue && match(LHS, m_Or(m_Value(ALHS), m_Value(ARHS)))) ||
4585 (LHSIsTrue && match(LHS, m_And(m_Value(ALHS), m_Value(ARHS))))) {
Chad Rosierf73a10d2017-08-01 19:22:36 +00004586 // FIXME: Make this non-recursion.
4587 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00004588 isImpliedCondition(ALHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00004589 return Implication;
4590 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00004591 isImpliedCondition(ARHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00004592 return Implication;
4593 return None;
4594 }
4595 return None;
4596}
4597
Chad Rosier2f498032017-07-28 18:47:43 +00004598Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00004599 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00004600 unsigned Depth) {
Davide Italiano30e51942017-08-09 15:13:50 +00004601 // Bail out when we hit the limit.
4602 if (Depth == MaxDepth)
4603 return None;
4604
Chad Rosierf73a10d2017-08-01 19:22:36 +00004605 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
4606 // example.
Chad Rosier2f498032017-07-28 18:47:43 +00004607 if (LHS->getType() != RHS->getType())
4608 return None;
4609
4610 Type *OpTy = LHS->getType();
Chad Rosierf73a10d2017-08-01 19:22:36 +00004611 assert(OpTy->isIntOrIntVectorTy(1) && "Expected integer type only!");
Chad Rosier2f498032017-07-28 18:47:43 +00004612
4613 // LHS ==> RHS by definition
4614 if (LHS == RHS)
Chad Rosierdfd1de62017-08-01 20:18:54 +00004615 return LHSIsTrue;
Chad Rosier2f498032017-07-28 18:47:43 +00004616
Chad Rosierf73a10d2017-08-01 19:22:36 +00004617 // FIXME: Extending the code below to handle vectors.
Chad Rosier2f498032017-07-28 18:47:43 +00004618 if (OpTy->isVectorTy())
Chad Rosier2f498032017-07-28 18:47:43 +00004619 return None;
Chad Rosierf73a10d2017-08-01 19:22:36 +00004620
Chad Rosier2f498032017-07-28 18:47:43 +00004621 assert(OpTy->isIntegerTy(1) && "implied by above");
4622
Chad Rosier2f498032017-07-28 18:47:43 +00004623 // Both LHS and RHS are icmps.
Chad Rosierf73a10d2017-08-01 19:22:36 +00004624 const ICmpInst *LHSCmp = dyn_cast<ICmpInst>(LHS);
4625 const ICmpInst *RHSCmp = dyn_cast<ICmpInst>(RHS);
4626 if (LHSCmp && RHSCmp)
Chad Rosierdfd1de62017-08-01 20:18:54 +00004627 return isImpliedCondICmps(LHSCmp, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00004628
Chad Rosierf73a10d2017-08-01 19:22:36 +00004629 // The LHS should be an 'or' or an 'and' instruction. We expect the RHS to be
4630 // an icmp. FIXME: Add support for and/or on the RHS.
4631 const BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHS);
4632 if (LHSBO && RHSCmp) {
4633 if ((LHSBO->getOpcode() == Instruction::And ||
4634 LHSBO->getOpcode() == Instruction::Or))
Chad Rosierdfd1de62017-08-01 20:18:54 +00004635 return isImpliedCondAndOr(LHSBO, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00004636 }
Chad Rosierf73a10d2017-08-01 19:22:36 +00004637 return None;
Chad Rosier2f498032017-07-28 18:47:43 +00004638}