blob: 3c01d97956018f355879941a4cb9e10e609ad325 [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"
Max Kazantsev3c284bd2018-08-30 03:39:16 +000029#include "llvm/Analysis/GuardUtils.h"
Dan Gohman949ab782010-12-15 20:10:26 +000030#include "llvm/Analysis/InstructionSimplify.h"
Artur Pilipenko31bcca42016-02-24 12:49:04 +000031#include "llvm/Analysis/Loads.h"
Adam Nemete2b885c2015-04-23 20:09:20 +000032#include "llvm/Analysis/LoopInfo.h"
Adam Nemet0965da22017-10-09 23:19:02 +000033#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000034#include "llvm/Analysis/TargetLibraryInfo.h"
35#include "llvm/IR/Argument.h"
36#include "llvm/IR/Attributes.h"
37#include "llvm/IR/BasicBlock.h"
Nick Lewyckyec373542014-05-20 05:13:21 +000038#include "llvm/IR/CallSite.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000039#include "llvm/IR/Constant.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000040#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Constants.h"
42#include "llvm/IR/DataLayout.h"
Matthias Braun50ec0b52017-05-19 22:37:09 +000043#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000044#include "llvm/IR/DiagnosticInfo.h"
Hal Finkel60db0582014-09-07 18:57:58 +000045#include "llvm/IR/Dominators.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000046#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000047#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/GlobalAlias.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000049#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000050#include "llvm/IR/GlobalVariable.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000051#include "llvm/IR/InstrTypes.h"
52#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/Instructions.h"
54#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000055#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000056#include "llvm/IR/LLVMContext.h"
57#include "llvm/IR/Metadata.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000058#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000059#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000060#include "llvm/IR/PatternMatch.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000061#include "llvm/IR/Type.h"
62#include "llvm/IR/User.h"
63#include "llvm/IR/Value.h"
64#include "llvm/Support/Casting.h"
65#include "llvm/Support/CommandLine.h"
66#include "llvm/Support/Compiler.h"
67#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000068#include "llvm/Support/KnownBits.h"
Chris Lattner965c7692008-06-02 01:18:21 +000069#include "llvm/Support/MathExtras.h"
Matthias Braun37e5d792016-01-28 06:29:33 +000070#include <algorithm>
71#include <array>
Eugene Zelenko75075ef2017-09-01 21:37:29 +000072#include <cassert>
73#include <cstdint>
74#include <iterator>
Fangrui Songf78650a2018-07-30 19:41:25 +000075#include <utility>
Eugene Zelenko75075ef2017-09-01 21:37:29 +000076
Chris Lattner965c7692008-06-02 01:18:21 +000077using namespace llvm;
Duncan Sandsd3951082011-01-25 09:38:29 +000078using namespace llvm::PatternMatch;
79
80const unsigned MaxDepth = 6;
81
Philip Reames1c292272015-03-10 22:43:20 +000082// Controls the number of uses of the value searched for possible
83// dominating comparisons.
84static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
Igor Laevskycea9ede2015-09-29 14:57:52 +000085 cl::Hidden, cl::init(20));
Philip Reames1c292272015-03-10 22:43:20 +000086
Craig Topper6b3940a2017-05-03 22:25:19 +000087/// Returns the bitwidth of the given scalar or pointer type. For vector types,
88/// returns the element type's bitwidth.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000089static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
Duncan Sandsd3951082011-01-25 09:38:29 +000090 if (unsigned BitWidth = Ty->getScalarSizeInBits())
91 return BitWidth;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +000092
Elena Demikhovsky945b7e52018-02-14 06:58:08 +000093 return DL.getIndexTypeSizeInBits(Ty);
Duncan Sandsd3951082011-01-25 09:38:29 +000094}
Chris Lattner965c7692008-06-02 01:18:21 +000095
Benjamin Kramercfd8d902014-09-12 08:56:53 +000096namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +000097
Hal Finkel60db0582014-09-07 18:57:58 +000098// Simplifying using an assume can only be done in a particular control-flow
99// context (the context instruction provides that context). If an assume and
100// the context instruction are not in the same block then the DT helps in
101// figuring out if we can use it.
102struct Query {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000103 const DataLayout &DL;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000104 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +0000105 const Instruction *CxtI;
106 const DominatorTree *DT;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000107
Sanjay Patel54656ca2017-02-06 18:26:06 +0000108 // Unlike the other analyses, this may be a nullptr because not all clients
109 // provide it currently.
110 OptimizationRemarkEmitter *ORE;
Hal Finkel60db0582014-09-07 18:57:58 +0000111
Matthias Braun37e5d792016-01-28 06:29:33 +0000112 /// Set of assumptions that should be excluded from further queries.
113 /// This is because of the potential for mutual recursion to cause
114 /// computeKnownBits to repeatedly visit the same assume intrinsic. The
115 /// classic case of this is assume(x = y), which will attempt to determine
116 /// bits in x from bits in y, which will attempt to determine bits in y from
117 /// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
Craig Topper6e11a052017-05-08 16:22:48 +0000118 /// isKnownNonZero, which calls computeKnownBits and isKnownToBeAPowerOfTwo
119 /// (all of which can call computeKnownBits), and so on.
Li Huang755f75f2016-10-15 19:00:04 +0000120 std::array<const Value *, MaxDepth> Excluded;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000121
Florian Hahn19f9e322018-08-17 14:39:04 +0000122 /// If true, it is safe to use metadata during simplification.
123 InstrInfoQuery IIQ;
124
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000125 unsigned NumExcluded = 0;
Matthias Braun37e5d792016-01-28 06:29:33 +0000126
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000127 Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000128 const DominatorTree *DT, bool UseInstrInfo,
129 OptimizationRemarkEmitter *ORE = nullptr)
130 : DL(DL), AC(AC), CxtI(CxtI), DT(DT), ORE(ORE), IIQ(UseInstrInfo) {}
Hal Finkel60db0582014-09-07 18:57:58 +0000131
132 Query(const Query &Q, const Value *NewExcl)
Florian Hahn19f9e322018-08-17 14:39:04 +0000133 : DL(Q.DL), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT), ORE(Q.ORE), IIQ(Q.IIQ),
Sanjay Patel54656ca2017-02-06 18:26:06 +0000134 NumExcluded(Q.NumExcluded) {
Matthias Braun37e5d792016-01-28 06:29:33 +0000135 Excluded = Q.Excluded;
136 Excluded[NumExcluded++] = NewExcl;
137 assert(NumExcluded <= Excluded.size());
138 }
139
140 bool isExcluded(const Value *Value) const {
141 if (NumExcluded == 0)
142 return false;
143 auto End = Excluded.begin() + NumExcluded;
144 return std::find(Excluded.begin(), End, Value) != End;
Hal Finkel60db0582014-09-07 18:57:58 +0000145 }
146};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000147
Benjamin Kramercfd8d902014-09-12 08:56:53 +0000148} // end anonymous namespace
Hal Finkel60db0582014-09-07 18:57:58 +0000149
Sanjay Patel547e9752014-11-04 16:09:50 +0000150// Given the provided Value and, potentially, a context instruction, return
Hal Finkel60db0582014-09-07 18:57:58 +0000151// the preferred context instruction (if any).
152static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
153 // If we've been provided with a context instruction, then use that (provided
154 // it has been inserted).
155 if (CxtI && CxtI->getParent())
156 return CxtI;
157
158 // If the value is really an already-inserted instruction, then use that.
159 CxtI = dyn_cast<Instruction>(V);
160 if (CxtI && CxtI->getParent())
161 return CxtI;
162
163 return nullptr;
164}
165
Craig Topperb45eabc2017-04-26 16:39:58 +0000166static void computeKnownBits(const Value *V, KnownBits &Known,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000167 unsigned Depth, const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000168
Craig Topperb45eabc2017-04-26 16:39:58 +0000169void llvm::computeKnownBits(const Value *V, KnownBits &Known,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000170 const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000171 AssumptionCache *AC, const Instruction *CxtI,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000172 const DominatorTree *DT,
Florian Hahn19f9e322018-08-17 14:39:04 +0000173 OptimizationRemarkEmitter *ORE, bool UseInstrInfo) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000174 ::computeKnownBits(V, Known, Depth,
Florian Hahn19f9e322018-08-17 14:39:04 +0000175 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
Hal Finkel60db0582014-09-07 18:57:58 +0000176}
177
Craig Topper6e11a052017-05-08 16:22:48 +0000178static KnownBits computeKnownBits(const Value *V, unsigned Depth,
179 const Query &Q);
180
181KnownBits llvm::computeKnownBits(const Value *V, const DataLayout &DL,
182 unsigned Depth, AssumptionCache *AC,
183 const Instruction *CxtI,
Craig Toppera2025ea2017-05-24 16:53:03 +0000184 const DominatorTree *DT,
Florian Hahn19f9e322018-08-17 14:39:04 +0000185 OptimizationRemarkEmitter *ORE,
186 bool UseInstrInfo) {
187 return ::computeKnownBits(
188 V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, 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,
Florian Hahn19f9e322018-08-17 14:39:04 +0000192 const DataLayout &DL, AssumptionCache *AC,
193 const Instruction *CxtI, const DominatorTree *DT,
194 bool UseInstrInfo) {
Jingyue Wuca321902015-05-14 23:53:19 +0000195 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");
Roman Lebedev620b3da2018-04-15 18:59:33 +0000199 // Look for an inverted mask: (X & ~M) op (Y & M).
200 Value *M;
201 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
202 match(RHS, m_c_And(m_Specific(M), m_Value())))
203 return true;
204 if (match(RHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
205 match(LHS, m_c_And(m_Specific(M), m_Value())))
206 return true;
Jingyue Wuca321902015-05-14 23:53:19 +0000207 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
Craig Topperb45eabc2017-04-26 16:39:58 +0000208 KnownBits LHSKnown(IT->getBitWidth());
209 KnownBits RHSKnown(IT->getBitWidth());
Florian Hahn19f9e322018-08-17 14:39:04 +0000210 computeKnownBits(LHS, LHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
211 computeKnownBits(RHS, RHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
Craig Topperb45eabc2017-04-26 16:39:58 +0000212 return (LHSKnown.Zero | RHSKnown.Zero).isAllOnesValue();
Jingyue Wuca321902015-05-14 23:53:19 +0000213}
214
Zaara Syeda3a7578c2017-05-31 17:12:38 +0000215bool llvm::isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI) {
216 for (const User *U : CxtI->users()) {
217 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
218 if (IC->isEquality())
219 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
220 if (C->isNullValue())
221 continue;
222 return false;
223 }
224 return true;
225}
226
Pete Cooper35b00d52016-08-13 01:05:32 +0000227static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000228 const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000229
Pete Cooper35b00d52016-08-13 01:05:32 +0000230bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
Florian Hahn19f9e322018-08-17 14:39:04 +0000231 bool OrZero, unsigned Depth,
232 AssumptionCache *AC, const Instruction *CxtI,
233 const DominatorTree *DT, bool UseInstrInfo) {
234 return ::isKnownToBeAPowerOfTwo(
235 V, OrZero, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000236}
237
Pete Cooper35b00d52016-08-13 01:05:32 +0000238static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000239
Pete Cooper35b00d52016-08-13 01:05:32 +0000240bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000241 AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000242 const DominatorTree *DT, bool UseInstrInfo) {
243 return ::isKnownNonZero(V, Depth,
244 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000245}
246
Pete Cooper35b00d52016-08-13 01:05:32 +0000247bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL,
Florian Hahn19f9e322018-08-17 14:39:04 +0000248 unsigned Depth, AssumptionCache *AC,
249 const Instruction *CxtI, const DominatorTree *DT,
250 bool UseInstrInfo) {
251 KnownBits Known =
252 computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
Craig Topper6e11a052017-05-08 16:22:48 +0000253 return Known.isNonNegative();
Jingyue Wu10fcea52015-08-20 18:27:04 +0000254}
255
Pete Cooper35b00d52016-08-13 01:05:32 +0000256bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000257 AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000258 const DominatorTree *DT, bool UseInstrInfo) {
Philip Reames8f12eba2016-03-09 21:31:47 +0000259 if (auto *CI = dyn_cast<ConstantInt>(V))
260 return CI->getValue().isStrictlyPositive();
Sanjoy Das6082c1a2016-05-07 02:08:15 +0000261
Philip Reames8f12eba2016-03-09 21:31:47 +0000262 // TODO: We'd doing two recursive queries here. We should factor this such
263 // that only a single query is needed.
Florian Hahn19f9e322018-08-17 14:39:04 +0000264 return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT, UseInstrInfo) &&
265 isKnownNonZero(V, DL, Depth, AC, CxtI, DT, UseInstrInfo);
Philip Reames8f12eba2016-03-09 21:31:47 +0000266}
267
Pete Cooper35b00d52016-08-13 01:05:32 +0000268bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000269 AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000270 const DominatorTree *DT, bool UseInstrInfo) {
271 KnownBits Known =
272 computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
Craig Topper6e11a052017-05-08 16:22:48 +0000273 return Known.isNegative();
Nick Lewycky762f8a82016-04-21 00:53:14 +0000274}
275
Pete Cooper35b00d52016-08-13 01:05:32 +0000276static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q);
James Molloy1d88d6f2015-10-22 13:18:42 +0000277
Pete Cooper35b00d52016-08-13 01:05:32 +0000278bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
Florian Hahn19f9e322018-08-17 14:39:04 +0000279 const DataLayout &DL, AssumptionCache *AC,
280 const Instruction *CxtI, const DominatorTree *DT,
281 bool UseInstrInfo) {
282 return ::isKnownNonEqual(V1, V2,
283 Query(DL, AC, safeCxtI(V1, safeCxtI(V2, CxtI)), DT,
284 UseInstrInfo, /*ORE=*/nullptr));
James Molloy1d88d6f2015-10-22 13:18:42 +0000285}
286
Pete Cooper35b00d52016-08-13 01:05:32 +0000287static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000288 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000289
Pete Cooper35b00d52016-08-13 01:05:32 +0000290bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
Florian Hahn19f9e322018-08-17 14:39:04 +0000291 const DataLayout &DL, unsigned Depth,
292 AssumptionCache *AC, const Instruction *CxtI,
293 const DominatorTree *DT, bool UseInstrInfo) {
294 return ::MaskedValueIsZero(
295 V, Mask, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000296}
297
Pete Cooper35b00d52016-08-13 01:05:32 +0000298static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
299 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000300
Pete Cooper35b00d52016-08-13 01:05:32 +0000301unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000302 unsigned Depth, AssumptionCache *AC,
303 const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000304 const DominatorTree *DT, bool UseInstrInfo) {
305 return ::ComputeNumSignBits(
306 V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Hal Finkel60db0582014-09-07 18:57:58 +0000307}
308
Craig Topper8fbb74b2017-03-24 22:12:10 +0000309static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
310 bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000311 KnownBits &KnownOut, KnownBits &Known2,
Craig Topper8fbb74b2017-03-24 22:12:10 +0000312 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000313 unsigned BitWidth = KnownOut.getBitWidth();
Craig Topper8fbb74b2017-03-24 22:12:10 +0000314
315 // If an initial sequence of bits in the result is not needed, the
316 // corresponding bits in the operands are not needed.
Craig Topperb45eabc2017-04-26 16:39:58 +0000317 KnownBits LHSKnown(BitWidth);
318 computeKnownBits(Op0, LHSKnown, Depth + 1, Q);
319 computeKnownBits(Op1, Known2, Depth + 1, Q);
Craig Topper8fbb74b2017-03-24 22:12:10 +0000320
Craig Topperb498a232017-08-08 16:29:35 +0000321 KnownOut = KnownBits::computeForAddSub(Add, NSW, LHSKnown, Known2);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000322}
323
Pete Cooper35b00d52016-08-13 01:05:32 +0000324static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000325 KnownBits &Known, KnownBits &Known2,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000326 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000327 unsigned BitWidth = Known.getBitWidth();
328 computeKnownBits(Op1, Known, Depth + 1, Q);
329 computeKnownBits(Op0, Known2, Depth + 1, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000330
331 bool isKnownNegative = false;
332 bool isKnownNonNegative = false;
333 // If the multiplication is known not to overflow, compute the sign bit.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000334 if (NSW) {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000335 if (Op0 == Op1) {
336 // The product of a number with itself is non-negative.
337 isKnownNonNegative = true;
338 } else {
Craig Topperca48af32017-04-29 16:43:11 +0000339 bool isKnownNonNegativeOp1 = Known.isNonNegative();
340 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
341 bool isKnownNegativeOp1 = Known.isNegative();
342 bool isKnownNegativeOp0 = Known2.isNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000343 // The product of two numbers with the same sign is non-negative.
344 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
345 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
346 // The product of a negative number and a non-negative number is either
347 // negative or zero.
348 if (!isKnownNonNegative)
349 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000350 isKnownNonZero(Op0, Depth, Q)) ||
Nick Lewyckyfa306072012-03-18 23:28:48 +0000351 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000352 isKnownNonZero(Op1, Depth, Q));
Nick Lewyckyfa306072012-03-18 23:28:48 +0000353 }
354 }
355
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000356 assert(!Known.hasConflict() && !Known2.hasConflict());
357 // Compute a conservative estimate for high known-0 bits.
Craig Topper8df66c62017-05-12 17:20:30 +0000358 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
359 Known2.countMinLeadingZeros(),
Nick Lewyckyfa306072012-03-18 23:28:48 +0000360 BitWidth) - BitWidth;
Nick Lewyckyfa306072012-03-18 23:28:48 +0000361 LeadZ = std::min(LeadZ, BitWidth);
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000362
363 // The result of the bottom bits of an integer multiply can be
364 // inferred by looking at the bottom bits of both operands and
365 // multiplying them together.
366 // We can infer at least the minimum number of known trailing bits
367 // of both operands. Depending on number of trailing zeros, we can
368 // infer more bits, because (a*b) <=> ((a/m) * (b/n)) * (m*n) assuming
369 // a and b are divisible by m and n respectively.
370 // We then calculate how many of those bits are inferrable and set
371 // the output. For example, the i8 mul:
372 // a = XXXX1100 (12)
373 // b = XXXX1110 (14)
374 // We know the bottom 3 bits are zero since the first can be divided by
375 // 4 and the second by 2, thus having ((12/4) * (14/2)) * (2*4).
376 // Applying the multiplication to the trimmed arguments gets:
377 // XX11 (3)
378 // X111 (7)
379 // -------
380 // XX11
381 // XX11
382 // XX11
383 // XX11
384 // -------
385 // XXXXX01
386 // Which allows us to infer the 2 LSBs. Since we're multiplying the result
387 // by 8, the bottom 3 bits will be 0, so we can infer a total of 5 bits.
388 // The proof for this can be described as:
389 // Pre: (C1 >= 0) && (C1 < (1 << C5)) && (C2 >= 0) && (C2 < (1 << C6)) &&
390 // (C7 == (1 << (umin(countTrailingZeros(C1), C5) +
391 // umin(countTrailingZeros(C2), C6) +
392 // umin(C5 - umin(countTrailingZeros(C1), C5),
393 // C6 - umin(countTrailingZeros(C2), C6)))) - 1)
394 // %aa = shl i8 %a, C5
395 // %bb = shl i8 %b, C6
396 // %aaa = or i8 %aa, C1
397 // %bbb = or i8 %bb, C2
398 // %mul = mul i8 %aaa, %bbb
399 // %mask = and i8 %mul, C7
400 // =>
401 // %mask = i8 ((C1*C2)&C7)
402 // Where C5, C6 describe the known bits of %a, %b
403 // C1, C2 describe the known bottom bits of %a, %b.
404 // C7 describes the mask of the known bits of the result.
405 APInt Bottom0 = Known.One;
406 APInt Bottom1 = Known2.One;
407
408 // How many times we'd be able to divide each argument by 2 (shr by 1).
409 // This gives us the number of trailing zeros on the multiplication result.
410 unsigned TrailBitsKnown0 = (Known.Zero | Known.One).countTrailingOnes();
411 unsigned TrailBitsKnown1 = (Known2.Zero | Known2.One).countTrailingOnes();
412 unsigned TrailZero0 = Known.countMinTrailingZeros();
413 unsigned TrailZero1 = Known2.countMinTrailingZeros();
414 unsigned TrailZ = TrailZero0 + TrailZero1;
415
416 // Figure out the fewest known-bits operand.
417 unsigned SmallestOperand = std::min(TrailBitsKnown0 - TrailZero0,
418 TrailBitsKnown1 - TrailZero1);
419 unsigned ResultBitsKnown = std::min(SmallestOperand + TrailZ, BitWidth);
420
421 APInt BottomKnown = Bottom0.getLoBits(TrailBitsKnown0) *
422 Bottom1.getLoBits(TrailBitsKnown1);
423
Craig Topperf0aeee02017-05-05 17:36:09 +0000424 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000425 Known.Zero.setHighBits(LeadZ);
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000426 Known.Zero |= (~BottomKnown).getLoBits(ResultBitsKnown);
427 Known.One |= BottomKnown.getLoBits(ResultBitsKnown);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000428
429 // Only make use of no-wrap flags if we failed to compute the sign bit
430 // directly. This matters if the multiplication always overflows, in
431 // which case we prefer to follow the result of the direct computation,
432 // though as the program is invoking undefined behaviour we can choose
433 // whatever we like here.
Craig Topperca48af32017-04-29 16:43:11 +0000434 if (isKnownNonNegative && !Known.isNegative())
435 Known.makeNonNegative();
436 else if (isKnownNegative && !Known.isNonNegative())
437 Known.makeNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000438}
439
Jingyue Wu37fcb592014-06-19 16:50:16 +0000440void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
Craig Topperf42b23f2017-04-28 06:28:56 +0000441 KnownBits &Known) {
442 unsigned BitWidth = Known.getBitWidth();
Rafael Espindola53190532012-03-30 15:52:11 +0000443 unsigned NumRanges = Ranges.getNumOperands() / 2;
444 assert(NumRanges >= 1);
445
Craig Topperf42b23f2017-04-28 06:28:56 +0000446 Known.Zero.setAllBits();
447 Known.One.setAllBits();
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000448
Rafael Espindola53190532012-03-30 15:52:11 +0000449 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000450 ConstantInt *Lower =
451 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
452 ConstantInt *Upper =
453 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
Rafael Espindola53190532012-03-30 15:52:11 +0000454 ConstantRange Range(Lower->getValue(), Upper->getValue());
Rafael Espindola53190532012-03-30 15:52:11 +0000455
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000456 // The first CommonPrefixBits of all values in Range are equal.
457 unsigned CommonPrefixBits =
458 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
459
460 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
Craig Topperf42b23f2017-04-28 06:28:56 +0000461 Known.One &= Range.getUnsignedMax() & Mask;
462 Known.Zero &= ~Range.getUnsignedMax() & Mask;
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000463 }
Rafael Espindola53190532012-03-30 15:52:11 +0000464}
Jay Foad5a29c362014-05-15 12:12:55 +0000465
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000466static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
Hal Finkel60db0582014-09-07 18:57:58 +0000467 SmallVector<const Value *, 16> WorkSet(1, I);
468 SmallPtrSet<const Value *, 32> Visited;
469 SmallPtrSet<const Value *, 16> EphValues;
470
Hal Finkelf2199b22015-10-23 20:37:08 +0000471 // The instruction defining an assumption's condition itself is always
472 // considered ephemeral to that assumption (even if it has other
473 // non-ephemeral users). See r246696's test case for an example.
David Majnemer0a16c222016-08-11 21:15:00 +0000474 if (is_contained(I->operands(), E))
Hal Finkelf2199b22015-10-23 20:37:08 +0000475 return true;
476
Hal Finkel60db0582014-09-07 18:57:58 +0000477 while (!WorkSet.empty()) {
478 const Value *V = WorkSet.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +0000479 if (!Visited.insert(V).second)
Hal Finkel60db0582014-09-07 18:57:58 +0000480 continue;
481
482 // If all uses of this value are ephemeral, then so is this value.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000483 if (llvm::all_of(V->users(), [&](const User *U) {
484 return EphValues.count(U);
485 })) {
Hal Finkel60db0582014-09-07 18:57:58 +0000486 if (V == E)
487 return true;
488
Hal Finkelb03dd4b2017-08-14 17:11:43 +0000489 if (V == I || isSafeToSpeculativelyExecute(V)) {
490 EphValues.insert(V);
491 if (const User *U = dyn_cast<User>(V))
492 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
493 J != JE; ++J)
494 WorkSet.push_back(*J);
495 }
Hal Finkel60db0582014-09-07 18:57:58 +0000496 }
497 }
498
499 return false;
500}
501
502// Is this an intrinsic that cannot be speculated but also cannot trap?
Haicheng Wua4461512017-12-15 14:34:41 +0000503bool llvm::isAssumeLikeIntrinsic(const Instruction *I) {
Hal Finkel60db0582014-09-07 18:57:58 +0000504 if (const CallInst *CI = dyn_cast<CallInst>(I))
505 if (Function *F = CI->getCalledFunction())
506 switch (F->getIntrinsicID()) {
507 default: break;
508 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
509 case Intrinsic::assume:
Dan Gohman2c74fe92017-11-08 21:59:51 +0000510 case Intrinsic::sideeffect:
Hal Finkel60db0582014-09-07 18:57:58 +0000511 case Intrinsic::dbg_declare:
512 case Intrinsic::dbg_value:
Shiva Chen2c864552018-05-09 02:40:45 +0000513 case Intrinsic::dbg_label:
Hal Finkel60db0582014-09-07 18:57:58 +0000514 case Intrinsic::invariant_start:
515 case Intrinsic::invariant_end:
516 case Intrinsic::lifetime_start:
517 case Intrinsic::lifetime_end:
518 case Intrinsic::objectsize:
519 case Intrinsic::ptr_annotation:
520 case Intrinsic::var_annotation:
521 return true;
522 }
523
524 return false;
525}
526
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000527bool llvm::isValidAssumeForContext(const Instruction *Inv,
528 const Instruction *CxtI,
529 const DominatorTree *DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000530 // There are two restrictions on the use of an assume:
531 // 1. The assume must dominate the context (or the control flow must
532 // reach the assume whenever it reaches the context).
533 // 2. The context must not be in the assume's set of ephemeral values
534 // (otherwise we will use the assume to prove that the condition
535 // feeding the assume is trivially true, thus causing the removal of
536 // the assume).
537
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000538 if (DT) {
Pete Cooper54a02552016-08-12 01:00:15 +0000539 if (DT->dominates(Inv, CxtI))
Hal Finkel60db0582014-09-07 18:57:58 +0000540 return true;
Pete Cooper54a02552016-08-12 01:00:15 +0000541 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
542 // We don't have a DT, but this trivially dominates.
543 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000544 }
545
Pete Cooper54a02552016-08-12 01:00:15 +0000546 // With or without a DT, the only remaining case we will check is if the
547 // instructions are in the same BB. Give up if that is not the case.
548 if (Inv->getParent() != CxtI->getParent())
549 return false;
550
Vedant Kumard3196742018-02-28 19:08:52 +0000551 // If we have a dom tree, then we now know that the assume doesn't dominate
Pete Cooper54a02552016-08-12 01:00:15 +0000552 // the other instruction. If we don't have a dom tree then we can check if
553 // the assume is first in the BB.
554 if (!DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000555 // Search forward from the assume until we reach the context (or the end
556 // of the block); the common case is that the assume will come first.
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000557 for (auto I = std::next(BasicBlock::const_iterator(Inv)),
Hal Finkel60db0582014-09-07 18:57:58 +0000558 IE = Inv->getParent()->end(); I != IE; ++I)
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000559 if (&*I == CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000560 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000561 }
562
Pete Cooper54a02552016-08-12 01:00:15 +0000563 // The context comes first, but they're both in the same block. Make sure
564 // there is nothing in between that might interrupt the control flow.
565 for (BasicBlock::const_iterator I =
566 std::next(BasicBlock::const_iterator(CxtI)), IE(Inv);
567 I != IE; ++I)
568 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
569 return false;
570
571 return !isEphemeralValueOf(Inv, CxtI);
Hal Finkel60db0582014-09-07 18:57:58 +0000572}
573
Craig Topperb45eabc2017-04-26 16:39:58 +0000574static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
575 unsigned Depth, const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000576 // Use of assumptions is context-sensitive. If we don't have a context, we
577 // cannot use them!
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000578 if (!Q.AC || !Q.CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000579 return;
580
Craig Topperb45eabc2017-04-26 16:39:58 +0000581 unsigned BitWidth = Known.getBitWidth();
Hal Finkel60db0582014-09-07 18:57:58 +0000582
Hal Finkel8a9a7832017-01-11 13:24:24 +0000583 // Note that the patterns below need to be kept in sync with the code
584 // in AssumptionCache::updateAffectedValues.
585
586 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000587 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +0000588 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000589 CallInst *I = cast<CallInst>(AssumeVH);
590 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
591 "Got assumption for the wrong function!");
592 if (Q.isExcluded(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000593 continue;
594
Vedant Kumard3196742018-02-28 19:08:52 +0000595 // Warning: This loop can end up being somewhat performance sensitive.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000596 // We're running this loop for once for each value queried resulting in a
597 // runtime of ~O(#assumes * #values).
Philip Reames00d3b272014-11-24 23:44:28 +0000598
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000599 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
600 "must be an assume intrinsic");
601
602 Value *Arg = I->getArgOperand(0);
603
604 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000605 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000606 Known.setAllOnes();
Hal Finkel60db0582014-09-07 18:57:58 +0000607 return;
608 }
Sanjay Patel96669962017-01-17 18:15:49 +0000609 if (match(Arg, m_Not(m_Specific(V))) &&
610 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
611 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000612 Known.setAllZero();
Sanjay Patel96669962017-01-17 18:15:49 +0000613 return;
614 }
Hal Finkel60db0582014-09-07 18:57:58 +0000615
David Majnemer9b609752014-12-12 23:59:29 +0000616 // The remaining tests are all recursive, so bail out if we hit the limit.
617 if (Depth == MaxDepth)
618 continue;
619
Hal Finkel60db0582014-09-07 18:57:58 +0000620 Value *A, *B;
621 auto m_V = m_CombineOr(m_Specific(V),
622 m_CombineOr(m_PtrToInt(m_Specific(V)),
623 m_BitCast(m_Specific(V))));
624
625 CmpInst::Predicate Pred;
Igor Laevskycec8f472017-12-05 12:18:15 +0000626 uint64_t C;
Hal Finkel60db0582014-09-07 18:57:58 +0000627 // assume(v = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000628 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000629 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000630 KnownBits RHSKnown(BitWidth);
631 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
632 Known.Zero |= RHSKnown.Zero;
633 Known.One |= RHSKnown.One;
Hal Finkel60db0582014-09-07 18:57:58 +0000634 // assume(v & b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000635 } else if (match(Arg,
636 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000637 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000638 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000639 KnownBits RHSKnown(BitWidth);
640 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
641 KnownBits MaskKnown(BitWidth);
642 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel60db0582014-09-07 18:57:58 +0000643
644 // For those bits in the mask that are known to be one, we can propagate
645 // known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000646 Known.Zero |= RHSKnown.Zero & MaskKnown.One;
647 Known.One |= RHSKnown.One & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000648 // assume(~(v & b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000649 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
650 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000651 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000652 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000653 KnownBits RHSKnown(BitWidth);
654 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
655 KnownBits MaskKnown(BitWidth);
656 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000657
658 // For those bits in the mask that are known to be one, we can propagate
659 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000660 Known.Zero |= RHSKnown.One & MaskKnown.One;
661 Known.One |= RHSKnown.Zero & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000662 // assume(v | b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000663 } else if (match(Arg,
664 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000665 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000666 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000667 KnownBits RHSKnown(BitWidth);
668 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
669 KnownBits BKnown(BitWidth);
670 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000671
672 // For those bits in B that are known to be zero, we can propagate known
673 // bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000674 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
675 Known.One |= RHSKnown.One & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000676 // assume(~(v | b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000677 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
678 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000679 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000680 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000681 KnownBits RHSKnown(BitWidth);
682 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
683 KnownBits BKnown(BitWidth);
684 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000685
686 // For those bits in B that are known to be zero, we can propagate
687 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000688 Known.Zero |= RHSKnown.One & BKnown.Zero;
689 Known.One |= RHSKnown.Zero & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000690 // assume(v ^ b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000691 } else if (match(Arg,
692 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000693 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000694 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000695 KnownBits RHSKnown(BitWidth);
696 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
697 KnownBits BKnown(BitWidth);
698 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000699
700 // For those bits in B that are known to be zero, we can propagate known
701 // bits from the RHS to V. For those bits in B that are known to be one,
702 // we can propagate inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000703 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
704 Known.One |= RHSKnown.One & BKnown.Zero;
705 Known.Zero |= RHSKnown.One & BKnown.One;
706 Known.One |= RHSKnown.Zero & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000707 // assume(~(v ^ b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000708 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
709 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000710 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000711 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000712 KnownBits RHSKnown(BitWidth);
713 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
714 KnownBits BKnown(BitWidth);
715 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000716
717 // For those bits in B that are known to be zero, we can propagate
718 // inverted known bits from the RHS to V. For those bits in B that are
719 // known to be one, we can propagate known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000720 Known.Zero |= RHSKnown.One & BKnown.Zero;
721 Known.One |= RHSKnown.Zero & BKnown.Zero;
722 Known.Zero |= RHSKnown.Zero & BKnown.One;
723 Known.One |= RHSKnown.One & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000724 // assume(v << c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000725 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
726 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000727 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000728 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
729 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000730 KnownBits RHSKnown(BitWidth);
731 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000732 // For those bits in RHS that are known, we can propagate them to known
733 // bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000734 RHSKnown.Zero.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000735 Known.Zero |= RHSKnown.Zero;
Igor Laevskycec8f472017-12-05 12:18:15 +0000736 RHSKnown.One.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000737 Known.One |= RHSKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000738 // assume(~(v << c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000739 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
740 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000741 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000742 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
743 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000744 KnownBits RHSKnown(BitWidth);
745 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000746 // For those bits in RHS that are known, we can propagate them inverted
747 // to known bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000748 RHSKnown.One.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000749 Known.Zero |= RHSKnown.One;
Igor Laevskycec8f472017-12-05 12:18:15 +0000750 RHSKnown.Zero.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000751 Known.One |= RHSKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000752 // assume(v >> c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000753 } else if (match(Arg,
Craig Topper7b66ffe2017-06-24 06:24:04 +0000754 m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000755 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000756 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000757 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
758 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000759 KnownBits RHSKnown(BitWidth);
760 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000761 // For those bits in RHS that are known, we can propagate them to known
762 // bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000763 Known.Zero |= RHSKnown.Zero << C;
764 Known.One |= RHSKnown.One << C;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000765 // assume(~(v >> c) = a)
Craig Topper7b66ffe2017-06-24 06:24:04 +0000766 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shr(m_V, m_ConstantInt(C))),
Philip Reames00d3b272014-11-24 23:44:28 +0000767 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000768 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000769 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
770 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000771 KnownBits RHSKnown(BitWidth);
772 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000773 // For those bits in RHS that are known, we can propagate them inverted
774 // to known bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000775 Known.Zero |= RHSKnown.One << C;
776 Known.One |= RHSKnown.Zero << C;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000777 // assume(v >=_s c) where c is non-negative
Philip Reames00d3b272014-11-24 23:44:28 +0000778 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000779 Pred == ICmpInst::ICMP_SGE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000780 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000781 KnownBits RHSKnown(BitWidth);
782 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000783
Craig Topperca48af32017-04-29 16:43:11 +0000784 if (RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000785 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000786 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000787 }
788 // assume(v >_s c) where c is at least -1.
Philip Reames00d3b272014-11-24 23:44:28 +0000789 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000790 Pred == ICmpInst::ICMP_SGT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000791 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000792 KnownBits RHSKnown(BitWidth);
793 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000794
Craig Topperf0aeee02017-05-05 17:36:09 +0000795 if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000796 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000797 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000798 }
799 // assume(v <=_s c) where c is negative
Philip Reames00d3b272014-11-24 23:44:28 +0000800 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000801 Pred == ICmpInst::ICMP_SLE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000802 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000803 KnownBits RHSKnown(BitWidth);
804 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000805
Craig Topperca48af32017-04-29 16:43:11 +0000806 if (RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000807 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000808 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000809 }
810 // assume(v <_s c) where c is non-positive
Philip Reames00d3b272014-11-24 23:44:28 +0000811 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000812 Pred == ICmpInst::ICMP_SLT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000813 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000814 KnownBits RHSKnown(BitWidth);
815 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000816
Craig Topperf0aeee02017-05-05 17:36:09 +0000817 if (RHSKnown.isZero() || RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000818 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000819 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000820 }
821 // assume(v <=_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000822 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000823 Pred == ICmpInst::ICMP_ULE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000824 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000825 KnownBits RHSKnown(BitWidth);
826 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000827
828 // Whatever high bits in c are zero are known to be zero.
Craig Topper8df66c62017-05-12 17:20:30 +0000829 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
830 // assume(v <_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000831 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000832 Pred == ICmpInst::ICMP_ULT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000833 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000834 KnownBits RHSKnown(BitWidth);
835 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000836
Sanjay Patela60aec12018-02-08 14:52:40 +0000837 // If the RHS is known zero, then this assumption must be wrong (nothing
838 // is unsigned less than zero). Signal a conflict and get out of here.
839 if (RHSKnown.isZero()) {
840 Known.Zero.setAllBits();
841 Known.One.setAllBits();
842 break;
843 }
844
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000845 // Whatever high bits in c are zero are known to be zero (if c is a power
846 // of 2, then one more).
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000847 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
Craig Topper8df66c62017-05-12 17:20:30 +0000848 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000849 else
Craig Topper8df66c62017-05-12 17:20:30 +0000850 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
Hal Finkel60db0582014-09-07 18:57:58 +0000851 }
852 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000853
854 // If assumptions conflict with each other or previous known bits, then we
Sanjay Patel54656ca2017-02-06 18:26:06 +0000855 // have a logical fallacy. It's possible that the assumption is not reachable,
856 // so this isn't a real bug. On the other hand, the program may have undefined
857 // behavior, or we might have a bug in the compiler. We can't assert/crash, so
858 // clear out the known bits, try to warn the user, and hope for the best.
Craig Topperb45eabc2017-04-26 16:39:58 +0000859 if (Known.Zero.intersects(Known.One)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000860 Known.resetAll();
Sanjay Patel54656ca2017-02-06 18:26:06 +0000861
Vivek Pandya95906582017-10-11 17:12:59 +0000862 if (Q.ORE)
863 Q.ORE->emit([&]() {
864 auto *CxtI = const_cast<Instruction *>(Q.CxtI);
865 return OptimizationRemarkAnalysis("value-tracking", "BadAssumption",
866 CxtI)
867 << "Detected conflicting code assumptions. Program may "
868 "have undefined behavior, or compiler may have "
869 "internal error.";
870 });
Sanjay Patel25f6d712017-02-01 15:41:32 +0000871 }
Hal Finkel60db0582014-09-07 18:57:58 +0000872}
873
Sanjay Patelb7d12382017-10-16 14:46:37 +0000874/// Compute known bits from a shift operator, including those with a
875/// non-constant shift amount. Known is the output of this function. Known2 is a
876/// pre-allocated temporary with the same bit width as Known. KZF and KOF are
Vedant Kumard3196742018-02-28 19:08:52 +0000877/// operator-specific functions that, given the known-zero or known-one bits
Sanjay Patelb7d12382017-10-16 14:46:37 +0000878/// respectively, and a shift amount, compute the implied known-zero or
879/// known-one bits of the shift operator's result respectively for that shift
880/// amount. The results from calling KZF and KOF are conservatively combined for
881/// all permitted shift amounts.
David Majnemer54690dc2016-08-23 20:52:00 +0000882static void computeKnownBitsFromShiftOperator(
Craig Topperb45eabc2017-04-26 16:39:58 +0000883 const Operator *I, KnownBits &Known, KnownBits &Known2,
884 unsigned Depth, const Query &Q,
Sam McCalld0d43e62017-12-04 12:51:49 +0000885 function_ref<APInt(const APInt &, unsigned)> KZF,
886 function_ref<APInt(const APInt &, unsigned)> KOF) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000887 unsigned BitWidth = Known.getBitWidth();
Hal Finkelf2199b22015-10-23 20:37:08 +0000888
889 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
890 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
891
Craig Topperb45eabc2017-04-26 16:39:58 +0000892 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Sam McCalld0d43e62017-12-04 12:51:49 +0000893 Known.Zero = KZF(Known.Zero, ShiftAmt);
894 Known.One = KOF(Known.One, ShiftAmt);
Sanjay Patele272be72017-10-12 17:31:46 +0000895 // If the known bits conflict, this must be an overflowing left shift, so
896 // the shift result is poison. We can return anything we want. Choose 0 for
897 // the best folding opportunity.
898 if (Known.hasConflict())
899 Known.setAllZero();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +0000900
Hal Finkelf2199b22015-10-23 20:37:08 +0000901 return;
902 }
903
Craig Topperb45eabc2017-04-26 16:39:58 +0000904 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000905
Sanjay Patele272be72017-10-12 17:31:46 +0000906 // If the shift amount could be greater than or equal to the bit-width of the
907 // LHS, the value could be poison, but bail out because the check below is
908 // expensive. TODO: Should we just carry on?
Craig Topperb45eabc2017-04-26 16:39:58 +0000909 if ((~Known.Zero).uge(BitWidth)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000910 Known.resetAll();
Oliver Stannard06204112017-03-14 10:13:17 +0000911 return;
912 }
913
Craig Topperb45eabc2017-04-26 16:39:58 +0000914 // Note: We cannot use Known.Zero.getLimitedValue() here, because if
Hal Finkelf2199b22015-10-23 20:37:08 +0000915 // BitWidth > 64 and any upper bits are known, we'll end up returning the
916 // limit value (which implies all bits are known).
Craig Topperb45eabc2017-04-26 16:39:58 +0000917 uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
918 uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
Hal Finkelf2199b22015-10-23 20:37:08 +0000919
920 // It would be more-clearly correct to use the two temporaries for this
921 // calculation. Reusing the APInts here to prevent unnecessary allocations.
Craig Topperf0aeee02017-05-05 17:36:09 +0000922 Known.resetAll();
Hal Finkelf2199b22015-10-23 20:37:08 +0000923
James Molloy493e57d2015-10-26 14:10:46 +0000924 // If we know the shifter operand is nonzero, we can sometimes infer more
925 // known bits. However this is expensive to compute, so be lazy about it and
926 // only compute it when absolutely necessary.
927 Optional<bool> ShifterOperandIsNonZero;
928
Hal Finkelf2199b22015-10-23 20:37:08 +0000929 // Early exit if we can't constrain any well-defined shift amount.
Craig Topperf93b7b12017-06-14 17:04:59 +0000930 if (!(ShiftAmtKZ & (PowerOf2Ceil(BitWidth) - 1)) &&
931 !(ShiftAmtKO & (PowerOf2Ceil(BitWidth) - 1))) {
Sanjay Patelb7d12382017-10-16 14:46:37 +0000932 ShifterOperandIsNonZero = isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000933 if (!*ShifterOperandIsNonZero)
934 return;
935 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000936
Craig Topperb45eabc2017-04-26 16:39:58 +0000937 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000938
Craig Topperb45eabc2017-04-26 16:39:58 +0000939 Known.Zero.setAllBits();
940 Known.One.setAllBits();
Hal Finkelf2199b22015-10-23 20:37:08 +0000941 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
942 // Combine the shifted known input bits only for those shift amounts
943 // compatible with its known constraints.
944 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
945 continue;
946 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
947 continue;
James Molloy493e57d2015-10-26 14:10:46 +0000948 // If we know the shifter is nonzero, we may be able to infer more known
949 // bits. This check is sunk down as far as possible to avoid the expensive
950 // call to isKnownNonZero if the cheaper checks above fail.
951 if (ShiftAmt == 0) {
952 if (!ShifterOperandIsNonZero.hasValue())
953 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000954 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000955 if (*ShifterOperandIsNonZero)
956 continue;
957 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000958
Sam McCalld0d43e62017-12-04 12:51:49 +0000959 Known.Zero &= KZF(Known2.Zero, ShiftAmt);
960 Known.One &= KOF(Known2.One, ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +0000961 }
962
Sanjay Patele272be72017-10-12 17:31:46 +0000963 // If the known bits conflict, the result is poison. Return a 0 and hope the
964 // caller can further optimize that.
965 if (Known.hasConflict())
966 Known.setAllZero();
Hal Finkelf2199b22015-10-23 20:37:08 +0000967}
968
Craig Topperb45eabc2017-04-26 16:39:58 +0000969static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known,
970 unsigned Depth, const Query &Q) {
971 unsigned BitWidth = Known.getBitWidth();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000972
Craig Topperb45eabc2017-04-26 16:39:58 +0000973 KnownBits Known2(Known);
Dan Gohman80ca01c2009-07-17 20:47:02 +0000974 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +0000975 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +0000976 case Instruction::Load:
Florian Hahn19f9e322018-08-17 14:39:04 +0000977 if (MDNode *MD =
978 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +0000979 computeKnownBitsFromRangeMetadata(*MD, Known);
Jay Foad5a29c362014-05-15 12:12:55 +0000980 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000981 case Instruction::And: {
982 // If either the LHS or the RHS are Zero, the result is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +0000983 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
984 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000985
Chris Lattner965c7692008-06-02 01:18:21 +0000986 // Output known-1 bits are only known if set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000987 Known.One &= Known2.One;
Chris Lattner965c7692008-06-02 01:18:21 +0000988 // Output known-0 are known to be clear if zero in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000989 Known.Zero |= Known2.Zero;
Philip Reames2d858742015-11-10 18:46:14 +0000990
991 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
992 // here we handle the more general case of adding any odd number by
993 // matching the form add(x, add(x, y)) where y is odd.
994 // TODO: This could be generalized to clearing any bit set in y where the
995 // following bit is known to be unset in y.
Roman Lebedev6959b8e2018-04-27 21:23:20 +0000996 Value *X = nullptr, *Y = nullptr;
Craig Topperb45eabc2017-04-26 16:39:58 +0000997 if (!Known.Zero[0] && !Known.One[0] &&
Roman Lebedev6959b8e2018-04-27 21:23:20 +0000998 match(I, m_c_BinOp(m_Value(X), m_Add(m_Deferred(X), m_Value(Y))))) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000999 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001000 computeKnownBits(Y, Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001001 if (Known2.countMinTrailingOnes() > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001002 Known.Zero.setBit(0);
Philip Reames2d858742015-11-10 18:46:14 +00001003 }
Jay Foad5a29c362014-05-15 12:12:55 +00001004 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001005 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001006 case Instruction::Or:
Craig Topperb45eabc2017-04-26 16:39:58 +00001007 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
1008 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001009
Chris Lattner965c7692008-06-02 01:18:21 +00001010 // Output known-0 bits are only known if clear in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001011 Known.Zero &= Known2.Zero;
Chris Lattner965c7692008-06-02 01:18:21 +00001012 // Output known-1 are known to be set if set in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001013 Known.One |= Known2.One;
Jay Foad5a29c362014-05-15 12:12:55 +00001014 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001015 case Instruction::Xor: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001016 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
1017 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001018
Chris Lattner965c7692008-06-02 01:18:21 +00001019 // Output known-0 bits are known if clear or set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001020 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
Chris Lattner965c7692008-06-02 01:18:21 +00001021 // Output known-1 are known to be set if set in only one of the LHS, RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001022 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
1023 Known.Zero = std::move(KnownZeroOut);
Jay Foad5a29c362014-05-15 12:12:55 +00001024 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001025 }
1026 case Instruction::Mul: {
Florian Hahn19f9e322018-08-17 14:39:04 +00001027 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Craig Topperb45eabc2017-04-26 16:39:58 +00001028 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, Known,
1029 Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001030 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001031 }
1032 case Instruction::UDiv: {
1033 // For the purposes of computing leading zeros we can conservatively
1034 // treat a udiv as a logical right shift by the power of 2 known to
1035 // be less than the denominator.
Craig Topperb45eabc2017-04-26 16:39:58 +00001036 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001037 unsigned LeadZ = Known2.countMinLeadingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001038
Craig Topperf0aeee02017-05-05 17:36:09 +00001039 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001040 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001041 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
1042 if (RHSMaxLeadingZeros != BitWidth)
1043 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
Chris Lattner965c7692008-06-02 01:18:21 +00001044
Craig Topperb45eabc2017-04-26 16:39:58 +00001045 Known.Zero.setHighBits(LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +00001046 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001047 }
David Majnemera19d0f22016-08-06 08:16:00 +00001048 case Instruction::Select: {
Craig Toppere953dec2017-04-13 20:39:37 +00001049 const Value *LHS, *RHS;
David Majnemera19d0f22016-08-06 08:16:00 +00001050 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
1051 if (SelectPatternResult::isMinOrMax(SPF)) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001052 computeKnownBits(RHS, Known, Depth + 1, Q);
1053 computeKnownBits(LHS, Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +00001054 } else {
Craig Topperb45eabc2017-04-26 16:39:58 +00001055 computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
1056 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +00001057 }
1058
1059 unsigned MaxHighOnes = 0;
1060 unsigned MaxHighZeros = 0;
1061 if (SPF == SPF_SMAX) {
1062 // If both sides are negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +00001063 if (Known.isNegative() && Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001064 // We can derive a lower bound on the result by taking the max of the
1065 // leading one bits.
Craig Topper8df66c62017-05-12 17:20:30 +00001066 MaxHighOnes =
1067 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001068 // If either side is non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +00001069 else if (Known.isNonNegative() || Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001070 MaxHighZeros = 1;
1071 } else if (SPF == SPF_SMIN) {
1072 // If both sides are non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +00001073 if (Known.isNonNegative() && Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001074 // We can derive an upper bound on the result by taking the max of the
1075 // leading zero bits.
Craig Topper8df66c62017-05-12 17:20:30 +00001076 MaxHighZeros = std::max(Known.countMinLeadingZeros(),
1077 Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +00001078 // If either side is negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +00001079 else if (Known.isNegative() || Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001080 MaxHighOnes = 1;
1081 } else if (SPF == SPF_UMAX) {
1082 // We can derive a lower bound on the result by taking the max of the
1083 // leading one bits.
1084 MaxHighOnes =
Craig Topper8df66c62017-05-12 17:20:30 +00001085 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001086 } else if (SPF == SPF_UMIN) {
1087 // We can derive an upper bound on the result by taking the max of the
1088 // leading zero bits.
1089 MaxHighZeros =
Craig Topper8df66c62017-05-12 17:20:30 +00001090 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topper8f77dca2018-05-25 19:18:09 +00001091 } else if (SPF == SPF_ABS) {
1092 // RHS from matchSelectPattern returns the negation part of abs pattern.
1093 // If the negate has an NSW flag we can assume the sign bit of the result
1094 // will be 0 because that makes abs(INT_MIN) undefined.
Florian Hahn19f9e322018-08-17 14:39:04 +00001095 if (Q.IIQ.hasNoSignedWrap(cast<Instruction>(RHS)))
Craig Topper8f77dca2018-05-25 19:18:09 +00001096 MaxHighZeros = 1;
David Majnemera19d0f22016-08-06 08:16:00 +00001097 }
1098
Chris Lattner965c7692008-06-02 01:18:21 +00001099 // Only known if known in both the LHS and RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001100 Known.One &= Known2.One;
1101 Known.Zero &= Known2.Zero;
David Majnemera19d0f22016-08-06 08:16:00 +00001102 if (MaxHighOnes > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001103 Known.One.setHighBits(MaxHighOnes);
David Majnemera19d0f22016-08-06 08:16:00 +00001104 if (MaxHighZeros > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001105 Known.Zero.setHighBits(MaxHighZeros);
Jay Foad5a29c362014-05-15 12:12:55 +00001106 break;
David Majnemera19d0f22016-08-06 08:16:00 +00001107 }
Chris Lattner965c7692008-06-02 01:18:21 +00001108 case Instruction::FPTrunc:
1109 case Instruction::FPExt:
1110 case Instruction::FPToUI:
1111 case Instruction::FPToSI:
1112 case Instruction::SIToFP:
1113 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +00001114 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +00001115 case Instruction::PtrToInt:
1116 case Instruction::IntToPtr:
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001117 // Fall through and handle them the same as zext/trunc.
1118 LLVM_FALLTHROUGH;
Chris Lattner965c7692008-06-02 01:18:21 +00001119 case Instruction::ZExt:
1120 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +00001121 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +00001122
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001123 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +00001124 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1125 // which fall through here.
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001126 Type *ScalarTy = SrcTy->getScalarType();
1127 SrcBitWidth = ScalarTy->isPointerTy() ?
1128 Q.DL.getIndexTypeSizeInBits(ScalarTy) :
1129 Q.DL.getTypeSizeInBits(ScalarTy);
Nadav Rotem15198e92012-10-26 17:17:05 +00001130
1131 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Craig Topperd938fd12017-05-03 22:07:25 +00001132 Known = Known.zextOrTrunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001133 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Craig Topperd938fd12017-05-03 22:07:25 +00001134 Known = Known.zextOrTrunc(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +00001135 // Any top bits are known to be zero.
1136 if (BitWidth > SrcBitWidth)
Craig Topperb45eabc2017-04-26 16:39:58 +00001137 Known.Zero.setBitsFrom(SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001138 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001139 }
1140 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +00001141 Type *SrcTy = I->getOperand(0)->getType();
Vedant Kumarb3091da2018-07-06 20:17:42 +00001142 if (SrcTy->isIntOrPtrTy() &&
Chris Lattneredb84072009-07-02 16:04:08 +00001143 // TODO: For now, not handling conversions like:
1144 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +00001145 !I->getType()->isVectorTy()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001146 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +00001147 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001148 }
1149 break;
1150 }
1151 case Instruction::SExt: {
1152 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001153 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +00001154
Craig Topperd938fd12017-05-03 22:07:25 +00001155 Known = Known.trunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001156 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001157 // If the sign bit of the input is known set or clear, then we know the
1158 // top bits of the result.
Craig Topperd938fd12017-05-03 22:07:25 +00001159 Known = Known.sext(BitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001160 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001161 }
Hal Finkelf2199b22015-10-23 20:37:08 +00001162 case Instruction::Shl: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001163 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Florian Hahn19f9e322018-08-17 14:39:04 +00001164 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Sam McCalld0d43e62017-12-04 12:51:49 +00001165 auto KZF = [NSW](const APInt &KnownZero, unsigned ShiftAmt) {
1166 APInt KZResult = KnownZero << ShiftAmt;
1167 KZResult.setLowBits(ShiftAmt); // Low bits known 0.
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001168 // If this shift has "nsw" keyword, then the result is either a poison
1169 // value or has the same sign bit as the first operand.
Sam McCalld0d43e62017-12-04 12:51:49 +00001170 if (NSW && KnownZero.isSignBitSet())
1171 KZResult.setSignBit();
1172 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001173 };
1174
Sam McCalld0d43e62017-12-04 12:51:49 +00001175 auto KOF = [NSW](const APInt &KnownOne, unsigned ShiftAmt) {
1176 APInt KOResult = KnownOne << ShiftAmt;
1177 if (NSW && KnownOne.isSignBitSet())
1178 KOResult.setSignBit();
1179 return KOResult;
1180 };
1181
1182 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001183 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001184 }
1185 case Instruction::LShr: {
Sanjay Patelb7d12382017-10-16 14:46:37 +00001186 // (lshr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Sam McCalld0d43e62017-12-04 12:51:49 +00001187 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1188 APInt KZResult = KnownZero.lshr(ShiftAmt);
1189 // High bits known zero.
1190 KZResult.setHighBits(ShiftAmt);
1191 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001192 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001193
Sam McCalld0d43e62017-12-04 12:51:49 +00001194 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1195 return KnownOne.lshr(ShiftAmt);
1196 };
1197
1198 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001199 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001200 }
1201 case Instruction::AShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001202 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Sam McCalld0d43e62017-12-04 12:51:49 +00001203 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1204 return KnownZero.ashr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001205 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001206
Sam McCalld0d43e62017-12-04 12:51:49 +00001207 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1208 return KnownOne.ashr(ShiftAmt);
1209 };
1210
1211 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001212 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001213 }
Chris Lattner965c7692008-06-02 01:18:21 +00001214 case Instruction::Sub: {
Florian Hahn19f9e322018-08-17 14:39:04 +00001215 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Jay Foada0653a32014-05-14 21:14:37 +00001216 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001217 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001218 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001219 }
Chris Lattner965c7692008-06-02 01:18:21 +00001220 case Instruction::Add: {
Florian Hahn19f9e322018-08-17 14:39:04 +00001221 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Jay Foada0653a32014-05-14 21:14:37 +00001222 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001223 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001224 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001225 }
1226 case Instruction::SRem:
1227 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001228 APInt RA = Rem->getValue().abs();
1229 if (RA.isPowerOf2()) {
1230 APInt LowBits = RA - 1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001231 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001232
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001233 // The low bits of the first operand are unchanged by the srem.
Craig Topperb45eabc2017-04-26 16:39:58 +00001234 Known.Zero = Known2.Zero & LowBits;
1235 Known.One = Known2.One & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001236
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001237 // If the first operand is non-negative or has all low bits zero, then
1238 // the upper bits are all zero.
Craig Topperca48af32017-04-29 16:43:11 +00001239 if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
Craig Topperb45eabc2017-04-26 16:39:58 +00001240 Known.Zero |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001241
1242 // If the first operand is negative and not all low bits are zero, then
1243 // the upper bits are all one.
Craig Topperca48af32017-04-29 16:43:11 +00001244 if (Known2.isNegative() && LowBits.intersects(Known2.One))
Craig Topperb45eabc2017-04-26 16:39:58 +00001245 Known.One |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001246
Craig Topperb45eabc2017-04-26 16:39:58 +00001247 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Craig Topperda886c62017-04-16 21:46:12 +00001248 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001249 }
1250 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001251
1252 // The sign bit is the LHS's sign bit, except when the result of the
1253 // remainder is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +00001254 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topperda886c62017-04-16 21:46:12 +00001255 // If it's known zero, our sign bit is also zero.
Craig Topperca48af32017-04-29 16:43:11 +00001256 if (Known2.isNonNegative())
1257 Known.makeNonNegative();
Nick Lewyckye4679792011-03-07 01:50:10 +00001258
Chris Lattner965c7692008-06-02 01:18:21 +00001259 break;
1260 case Instruction::URem: {
1261 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001262 const APInt &RA = Rem->getValue();
Chris Lattner965c7692008-06-02 01:18:21 +00001263 if (RA.isPowerOf2()) {
1264 APInt LowBits = (RA - 1);
Craig Topperb45eabc2017-04-26 16:39:58 +00001265 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1266 Known.Zero |= ~LowBits;
1267 Known.One &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001268 break;
1269 }
1270 }
1271
1272 // Since the result is less than or equal to either operand, any leading
1273 // zero bits in either operand must also exist in the result.
Craig Topperb45eabc2017-04-26 16:39:58 +00001274 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1275 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001276
Craig Topper8df66c62017-05-12 17:20:30 +00001277 unsigned Leaders =
1278 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topperf0aeee02017-05-05 17:36:09 +00001279 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001280 Known.Zero.setHighBits(Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001281 break;
1282 }
1283
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001284 case Instruction::Alloca: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001285 const AllocaInst *AI = cast<AllocaInst>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001286 unsigned Align = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001287 if (Align == 0)
Eduard Burtescu90c44492016-01-18 00:10:01 +00001288 Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001289
Chris Lattner965c7692008-06-02 01:18:21 +00001290 if (Align > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001291 Known.Zero.setLowBits(countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001292 break;
1293 }
1294 case Instruction::GetElementPtr: {
1295 // Analyze all of the subscripts of this getelementptr instruction
1296 // to determine if we can prove known low zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001297 KnownBits LocalKnown(BitWidth);
1298 computeKnownBits(I->getOperand(0), LocalKnown, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001299 unsigned TrailZ = LocalKnown.countMinTrailingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001300
1301 gep_type_iterator GTI = gep_type_begin(I);
1302 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1303 Value *Index = I->getOperand(i);
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001304 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chris Lattner965c7692008-06-02 01:18:21 +00001305 // Handle struct member offset arithmetic.
Matt Arsenault74742a12013-08-19 21:43:16 +00001306
1307 // Handle case when index is vector zeroinitializer
1308 Constant *CIndex = cast<Constant>(Index);
1309 if (CIndex->isZeroValue())
1310 continue;
1311
1312 if (CIndex->getType()->isVectorTy())
1313 Index = CIndex->getSplatValue();
1314
Chris Lattner965c7692008-06-02 01:18:21 +00001315 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001316 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001317 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001318 TrailZ = std::min<unsigned>(TrailZ,
1319 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001320 } else {
1321 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001322 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001323 if (!IndexedTy->isSized()) {
1324 TrailZ = 0;
1325 break;
1326 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001327 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001328 uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
Craig Topperb45eabc2017-04-26 16:39:58 +00001329 LocalKnown.Zero = LocalKnown.One = APInt(GEPOpiBits, 0);
1330 computeKnownBits(Index, LocalKnown, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001331 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001332 unsigned(countTrailingZeros(TypeSize) +
Craig Topper8df66c62017-05-12 17:20:30 +00001333 LocalKnown.countMinTrailingZeros()));
Chris Lattner965c7692008-06-02 01:18:21 +00001334 }
1335 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001336
Craig Topperb45eabc2017-04-26 16:39:58 +00001337 Known.Zero.setLowBits(TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001338 break;
1339 }
1340 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001341 const PHINode *P = cast<PHINode>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001342 // Handle the case of a simple two-predecessor recurrence PHI.
1343 // There's a lot more that could theoretically be done here, but
1344 // this is sufficient to catch some interesting cases.
1345 if (P->getNumIncomingValues() == 2) {
1346 for (unsigned i = 0; i != 2; ++i) {
1347 Value *L = P->getIncomingValue(i);
1348 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001349 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001350 if (!LU)
1351 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001352 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001353 // Check for operations that have the property that if
1354 // both their operands have low zero bits, the result
Artur Pilipenkobc76eca2016-08-22 13:14:07 +00001355 // will have low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001356 if (Opcode == Instruction::Add ||
1357 Opcode == Instruction::Sub ||
1358 Opcode == Instruction::And ||
1359 Opcode == Instruction::Or ||
1360 Opcode == Instruction::Mul) {
1361 Value *LL = LU->getOperand(0);
1362 Value *LR = LU->getOperand(1);
1363 // Find a recurrence.
1364 if (LL == I)
1365 L = LR;
1366 else if (LR == I)
1367 L = LL;
1368 else
1369 break;
1370 // Ok, we have a PHI of the form L op= R. Check for low
1371 // zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001372 computeKnownBits(R, Known2, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001373
1374 // We need to take the minimum number of known bits
Craig Topperb45eabc2017-04-26 16:39:58 +00001375 KnownBits Known3(Known);
1376 computeKnownBits(L, Known3, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001377
Craig Topper8df66c62017-05-12 17:20:30 +00001378 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1379 Known3.countMinTrailingZeros()));
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001380
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001381 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU);
Florian Hahn19f9e322018-08-17 14:39:04 +00001382 if (OverflowOp && Q.IIQ.hasNoSignedWrap(OverflowOp)) {
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001383 // If initial value of recurrence is nonnegative, and we are adding
1384 // a nonnegative number with nsw, the result can only be nonnegative
1385 // or poison value regardless of the number of times we execute the
1386 // add in phi recurrence. If initial value is negative and we are
1387 // adding a negative number with nsw, the result can only be
1388 // negative or poison value. Similar arguments apply to sub and mul.
1389 //
1390 // (add non-negative, non-negative) --> non-negative
1391 // (add negative, negative) --> negative
1392 if (Opcode == Instruction::Add) {
Craig Topperca48af32017-04-29 16:43:11 +00001393 if (Known2.isNonNegative() && Known3.isNonNegative())
1394 Known.makeNonNegative();
1395 else if (Known2.isNegative() && Known3.isNegative())
1396 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001397 }
1398
1399 // (sub nsw non-negative, negative) --> non-negative
1400 // (sub nsw negative, non-negative) --> negative
1401 else if (Opcode == Instruction::Sub && LL == I) {
Craig Topperca48af32017-04-29 16:43:11 +00001402 if (Known2.isNonNegative() && Known3.isNegative())
1403 Known.makeNonNegative();
1404 else if (Known2.isNegative() && Known3.isNonNegative())
1405 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001406 }
1407
1408 // (mul nsw non-negative, non-negative) --> non-negative
Craig Topperca48af32017-04-29 16:43:11 +00001409 else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1410 Known3.isNonNegative())
1411 Known.makeNonNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001412 }
1413
Chris Lattner965c7692008-06-02 01:18:21 +00001414 break;
1415 }
1416 }
1417 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001418
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001419 // Unreachable blocks may have zero-operand PHI nodes.
1420 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001421 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001422
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001423 // Otherwise take the unions of the known bit sets of the operands,
1424 // taking conservative care to avoid excessive recursion.
Craig Topperb45eabc2017-04-26 16:39:58 +00001425 if (Depth < MaxDepth - 1 && !Known.Zero && !Known.One) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001426 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001427 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001428 break;
1429
Craig Topperb45eabc2017-04-26 16:39:58 +00001430 Known.Zero.setAllBits();
1431 Known.One.setAllBits();
Pete Cooper833f34d2015-05-12 20:05:31 +00001432 for (Value *IncValue : P->incoming_values()) {
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001433 // Skip direct self references.
Pete Cooper833f34d2015-05-12 20:05:31 +00001434 if (IncValue == P) continue;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001435
Craig Topperb45eabc2017-04-26 16:39:58 +00001436 Known2 = KnownBits(BitWidth);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001437 // Recurse, but cap the recursion to one level, because we don't
1438 // want to waste time spinning around in loops.
Craig Topperb45eabc2017-04-26 16:39:58 +00001439 computeKnownBits(IncValue, Known2, MaxDepth - 1, Q);
1440 Known.Zero &= Known2.Zero;
1441 Known.One &= Known2.One;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001442 // If all bits have been ruled out, there's no need to check
1443 // more operands.
Craig Topperb45eabc2017-04-26 16:39:58 +00001444 if (!Known.Zero && !Known.One)
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001445 break;
1446 }
1447 }
Chris Lattner965c7692008-06-02 01:18:21 +00001448 break;
1449 }
1450 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001451 case Instruction::Invoke:
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001452 // If range metadata is attached to this call, set known bits from that,
1453 // and then intersect with known bits based on other properties of the
1454 // function.
Florian Hahn19f9e322018-08-17 14:39:04 +00001455 if (MDNode *MD =
1456 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +00001457 computeKnownBitsFromRangeMetadata(*MD, Known);
Pete Cooper35b00d52016-08-13 01:05:32 +00001458 if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001459 computeKnownBits(RV, Known2, Depth + 1, Q);
1460 Known.Zero |= Known2.Zero;
1461 Known.One |= Known2.One;
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001462 }
Pete Cooper35b00d52016-08-13 01:05:32 +00001463 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001464 switch (II->getIntrinsicID()) {
1465 default: break;
Chad Rosier85204292017-01-17 17:23:51 +00001466 case Intrinsic::bitreverse:
Craig Topperb45eabc2017-04-26 16:39:58 +00001467 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1468 Known.Zero |= Known2.Zero.reverseBits();
1469 Known.One |= Known2.One.reverseBits();
Chad Rosier85204292017-01-17 17:23:51 +00001470 break;
Philip Reames675418e2015-10-06 20:20:45 +00001471 case Intrinsic::bswap:
Craig Topperb45eabc2017-04-26 16:39:58 +00001472 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1473 Known.Zero |= Known2.Zero.byteSwap();
1474 Known.One |= Known2.One.byteSwap();
Philip Reames675418e2015-10-06 20:20:45 +00001475 break;
Craig Topper868813f2017-05-08 17:22:34 +00001476 case Intrinsic::ctlz: {
1477 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1478 // If we have a known 1, its position is our upper bound.
1479 unsigned PossibleLZ = Known2.One.countLeadingZeros();
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001480 // If this call is undefined for 0, the result will be less than 2^n.
1481 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
Craig Topper868813f2017-05-08 17:22:34 +00001482 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1483 unsigned LowBits = Log2_32(PossibleLZ)+1;
1484 Known.Zero.setBitsFrom(LowBits);
1485 break;
1486 }
1487 case Intrinsic::cttz: {
1488 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1489 // If we have a known 1, its position is our upper bound.
1490 unsigned PossibleTZ = Known2.One.countTrailingZeros();
1491 // If this call is undefined for 0, the result will be less than 2^n.
1492 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1493 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1494 unsigned LowBits = Log2_32(PossibleTZ)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001495 Known.Zero.setBitsFrom(LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001496 break;
1497 }
1498 case Intrinsic::ctpop: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001499 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001500 // We can bound the space the count needs. Also, bits known to be zero
1501 // can't contribute to the population.
Craig Topper8df66c62017-05-12 17:20:30 +00001502 unsigned BitsPossiblySet = Known2.countMaxPopulation();
Craig Topper66df10f2017-04-14 06:43:34 +00001503 unsigned LowBits = Log2_32(BitsPossiblySet)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001504 Known.Zero.setBitsFrom(LowBits);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001505 // TODO: we could bound KnownOne using the lower bound on the number
1506 // of bits which might be set provided by popcnt KnownOne2.
Chris Lattner965c7692008-06-02 01:18:21 +00001507 break;
1508 }
Chad Rosierb3628842011-05-26 23:13:19 +00001509 case Intrinsic::x86_sse42_crc32_64_64:
Craig Topperb45eabc2017-04-26 16:39:58 +00001510 Known.Zero.setBitsFrom(32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001511 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001512 }
1513 }
1514 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00001515 case Instruction::ExtractElement:
1516 // Look through extract element. At the moment we keep this simple and skip
1517 // tracking the specific element. But at least we might find information
1518 // valid for all elements of the vector (for example if vector is sign
1519 // extended, shifted, etc).
Craig Topperb45eabc2017-04-26 16:39:58 +00001520 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Bjorn Pettersson39616032016-10-06 09:56:21 +00001521 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001522 case Instruction::ExtractValue:
1523 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001524 const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001525 if (EVI->getNumIndices() != 1) break;
1526 if (EVI->getIndices()[0] == 0) {
1527 switch (II->getIntrinsicID()) {
1528 default: break;
1529 case Intrinsic::uadd_with_overflow:
1530 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001531 computeKnownBitsAddSub(true, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001532 II->getArgOperand(1), false, Known, Known2,
1533 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001534 break;
1535 case Intrinsic::usub_with_overflow:
1536 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001537 computeKnownBitsAddSub(false, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001538 II->getArgOperand(1), false, Known, Known2,
1539 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001540 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001541 case Intrinsic::umul_with_overflow:
1542 case Intrinsic::smul_with_overflow:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001543 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
Craig Topperb45eabc2017-04-26 16:39:58 +00001544 Known, Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001545 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001546 }
1547 }
1548 }
Chris Lattner965c7692008-06-02 01:18:21 +00001549 }
Jingyue Wu12b0c282015-06-15 05:46:29 +00001550}
1551
1552/// Determine which bits of V are known to be either zero or one and return
Craig Topper6e11a052017-05-08 16:22:48 +00001553/// them.
1554KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1555 KnownBits Known(getBitWidth(V->getType(), Q.DL));
1556 computeKnownBits(V, Known, Depth, Q);
1557 return Known;
1558}
1559
1560/// Determine which bits of V are known to be either zero or one and return
Craig Topperb45eabc2017-04-26 16:39:58 +00001561/// them in the Known bit set.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001562///
1563/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1564/// we cannot optimize based on the assumption that it is zero without changing
1565/// it to be an explicit zero. If we don't change it to zero, other code could
1566/// optimized based on the contradictory assumption that it is non-zero.
1567/// Because instcombine aggressively folds operations with undef args anyway,
1568/// this won't lose us code quality.
1569///
1570/// This function is defined on values with integer type, values with pointer
1571/// type, and vectors of integers. In the case
1572/// where V is a vector, known zero, and known one values are the
1573/// same width as the vector element, and the bit is set only if it is true
1574/// for all of the elements in the vector.
Craig Topperb45eabc2017-04-26 16:39:58 +00001575void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
1576 const Query &Q) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001577 assert(V && "No Value?");
1578 assert(Depth <= MaxDepth && "Limit Search Depth");
Craig Topperb45eabc2017-04-26 16:39:58 +00001579 unsigned BitWidth = Known.getBitWidth();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001580
Craig Topperfde47232017-07-09 07:04:03 +00001581 assert((V->getType()->isIntOrIntVectorTy(BitWidth) ||
Craig Topper95d23472017-07-09 07:04:00 +00001582 V->getType()->isPtrOrPtrVectorTy()) &&
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001583 "Not integer or pointer type!");
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001584
1585 Type *ScalarTy = V->getType()->getScalarType();
1586 unsigned ExpectedWidth = ScalarTy->isPointerTy() ?
1587 Q.DL.getIndexTypeSizeInBits(ScalarTy) : Q.DL.getTypeSizeInBits(ScalarTy);
1588 assert(ExpectedWidth == BitWidth && "V and Known should have same BitWidth");
Craig Topperd73c6b42017-03-23 07:06:39 +00001589 (void)BitWidth;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001590 (void)ExpectedWidth;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001591
Sanjay Patelc96f6db2016-09-16 21:20:36 +00001592 const APInt *C;
1593 if (match(V, m_APInt(C))) {
1594 // We know all of the bits for a scalar constant or a splat vector constant!
Craig Topperb45eabc2017-04-26 16:39:58 +00001595 Known.One = *C;
1596 Known.Zero = ~Known.One;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001597 return;
1598 }
1599 // Null and aggregate-zero are all-zeros.
Sanjay Patele8dc0902016-05-23 17:57:54 +00001600 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001601 Known.setAllZero();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001602 return;
1603 }
1604 // Handle a constant vector by taking the intersection of the known bits of
David Majnemer3918cdd2016-05-04 06:13:33 +00001605 // each element.
Pete Cooper35b00d52016-08-13 01:05:32 +00001606 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001607 // We know that CDS must be a vector of integers. Take the intersection of
1608 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001609 Known.Zero.setAllBits(); Known.One.setAllBits();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001610 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Craig Topperb98ee582017-10-21 16:35:39 +00001611 APInt Elt = CDS->getElementAsAPInt(i);
Craig Topperb45eabc2017-04-26 16:39:58 +00001612 Known.Zero &= ~Elt;
1613 Known.One &= Elt;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001614 }
1615 return;
1616 }
1617
Pete Cooper35b00d52016-08-13 01:05:32 +00001618 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
David Majnemer3918cdd2016-05-04 06:13:33 +00001619 // We know that CV must be a vector of integers. Take the intersection of
1620 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001621 Known.Zero.setAllBits(); Known.One.setAllBits();
David Majnemer3918cdd2016-05-04 06:13:33 +00001622 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1623 Constant *Element = CV->getAggregateElement(i);
1624 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1625 if (!ElementCI) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001626 Known.resetAll();
David Majnemer3918cdd2016-05-04 06:13:33 +00001627 return;
1628 }
Craig Topperb98ee582017-10-21 16:35:39 +00001629 const APInt &Elt = ElementCI->getValue();
Craig Topperb45eabc2017-04-26 16:39:58 +00001630 Known.Zero &= ~Elt;
1631 Known.One &= Elt;
David Majnemer3918cdd2016-05-04 06:13:33 +00001632 }
1633 return;
1634 }
1635
Jingyue Wu12b0c282015-06-15 05:46:29 +00001636 // Start out not knowing anything.
Craig Topperf0aeee02017-05-05 17:36:09 +00001637 Known.resetAll();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001638
Duncan P. N. Exon Smithb1b208a2016-09-24 20:42:02 +00001639 // We can't imply anything about undefs.
1640 if (isa<UndefValue>(V))
1641 return;
1642
1643 // There's no point in looking through other users of ConstantData for
1644 // assumptions. Confirm that we've handled them all.
1645 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1646
Jingyue Wu12b0c282015-06-15 05:46:29 +00001647 // Limit search depth.
1648 // All recursive calls that increase depth must come after this.
1649 if (Depth == MaxDepth)
1650 return;
1651
1652 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1653 // the bits of its aliasee.
Pete Cooper35b00d52016-08-13 01:05:32 +00001654 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001655 if (!GA->isInterposable())
Craig Topperb45eabc2017-04-26 16:39:58 +00001656 computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001657 return;
1658 }
1659
Pete Cooper35b00d52016-08-13 01:05:32 +00001660 if (const Operator *I = dyn_cast<Operator>(V))
Craig Topperb45eabc2017-04-26 16:39:58 +00001661 computeKnownBitsFromOperator(I, Known, Depth, Q);
Sanjay Patela67559c2015-09-25 20:12:43 +00001662
Craig Topperb45eabc2017-04-26 16:39:58 +00001663 // Aligned pointers have trailing zeros - refine Known.Zero set
Artur Pilipenko029d8532015-09-30 11:55:45 +00001664 if (V->getType()->isPointerTy()) {
Artur Pilipenkoae51afc2016-02-24 12:25:10 +00001665 unsigned Align = V->getPointerAlignment(Q.DL);
Artur Pilipenko029d8532015-09-30 11:55:45 +00001666 if (Align)
Craig Topperb45eabc2017-04-26 16:39:58 +00001667 Known.Zero.setLowBits(countTrailingZeros(Align));
Artur Pilipenko029d8532015-09-30 11:55:45 +00001668 }
1669
Craig Topperb45eabc2017-04-26 16:39:58 +00001670 // computeKnownBitsFromAssume strictly refines Known.
1671 // Therefore, we run them after computeKnownBitsFromOperator.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001672
1673 // Check whether a nearby assume intrinsic can determine some known bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001674 computeKnownBitsFromAssume(V, Known, Depth, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001675
Craig Topperb45eabc2017-04-26 16:39:58 +00001676 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001677}
1678
Sanjay Patelaee84212014-11-04 16:27:42 +00001679/// Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001680/// bit set when defined. For vectors return true if every element is known to
Sanjay Patelaee84212014-11-04 16:27:42 +00001681/// be a power of two when defined. Supports values with integer or pointer
Duncan Sandsd3951082011-01-25 09:38:29 +00001682/// types and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001683bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001684 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00001685 assert(Depth <= MaxDepth && "Limit Search Depth");
1686
Simon Pilgrim9f2ae7e2018-02-06 18:39:23 +00001687 // Attempt to match against constants.
1688 if (OrZero && match(V, m_Power2OrZero()))
1689 return true;
1690 if (match(V, m_Power2()))
1691 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001692
1693 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1694 // it is shifted off the end then the result is undefined.
1695 if (match(V, m_Shl(m_One(), m_Value())))
1696 return true;
1697
Craig Topperbcfd2d12017-04-20 16:56:25 +00001698 // (signmask) >>l X is clearly a power of two if the one is not shifted off
1699 // the bottom. If it is shifted off the bottom then the result is undefined.
1700 if (match(V, m_LShr(m_SignMask(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001701 return true;
1702
1703 // The remaining tests are all recursive, so bail out if we hit the limit.
1704 if (Depth++ == MaxDepth)
1705 return false;
1706
Craig Topper9f008862014-04-15 04:59:12 +00001707 Value *X = nullptr, *Y = nullptr;
Sanjay Patel41160c22015-12-30 22:40:52 +00001708 // A shift left or a logical shift right of a power of two is a power of two
1709 // or zero.
Duncan Sands985ba632011-10-28 18:30:05 +00001710 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
Sanjay Patel41160c22015-12-30 22:40:52 +00001711 match(V, m_LShr(m_Value(X), m_Value()))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001712 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
Duncan Sands985ba632011-10-28 18:30:05 +00001713
Pete Cooper35b00d52016-08-13 01:05:32 +00001714 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001715 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001716
Pete Cooper35b00d52016-08-13 01:05:32 +00001717 if (const SelectInst *SI = dyn_cast<SelectInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001718 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1719 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
Duncan Sandsba286d72011-10-26 20:55:21 +00001720
Duncan Sandsba286d72011-10-26 20:55:21 +00001721 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1722 // A power of two and'd with anything is a power of two or zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001723 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1724 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
Duncan Sandsba286d72011-10-26 20:55:21 +00001725 return true;
1726 // X & (-X) is always a power of two or zero.
1727 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1728 return true;
1729 return false;
1730 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001731
David Majnemerb7d54092013-07-30 21:01:36 +00001732 // Adding a power-of-two or zero to the same power-of-two or zero yields
1733 // either the original power-of-two, a larger power-of-two or zero.
1734 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001735 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
Florian Hahn19f9e322018-08-17 14:39:04 +00001736 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
1737 Q.IIQ.hasNoSignedWrap(VOBO)) {
David Majnemerb7d54092013-07-30 21:01:36 +00001738 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1739 match(X, m_And(m_Value(), m_Specific(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001740 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001741 return true;
1742 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1743 match(Y, m_And(m_Value(), m_Specific(X))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001744 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001745 return true;
1746
1747 unsigned BitWidth = V->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00001748 KnownBits LHSBits(BitWidth);
1749 computeKnownBits(X, LHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001750
Craig Topperb45eabc2017-04-26 16:39:58 +00001751 KnownBits RHSBits(BitWidth);
1752 computeKnownBits(Y, RHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001753 // If i8 V is a power of two or zero:
1754 // ZeroBits: 1 1 1 0 1 1 1 1
1755 // ~ZeroBits: 0 0 0 1 0 0 0 0
Craig Topperb45eabc2017-04-26 16:39:58 +00001756 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
David Majnemerb7d54092013-07-30 21:01:36 +00001757 // If OrZero isn't set, we cannot give back a zero result.
1758 // Make sure either the LHS or RHS has a bit set.
Craig Topperb45eabc2017-04-26 16:39:58 +00001759 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
David Majnemerb7d54092013-07-30 21:01:36 +00001760 return true;
1761 }
1762 }
David Majnemerbeab5672013-05-18 19:30:37 +00001763
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001764 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001765 // is a power of two only if the first operand is a power of two and not
1766 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001767 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1768 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001769 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001770 Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001771 }
1772
Duncan Sandsd3951082011-01-25 09:38:29 +00001773 return false;
1774}
1775
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001776/// Test whether a GEP's result is known to be non-null.
Chandler Carruth80d3e562012-12-07 02:08:58 +00001777///
1778/// Uses properties inherent in a GEP to try to determine whether it is known
1779/// to be non-null.
1780///
1781/// Currently this routine does not support vector GEPs.
Pete Cooper35b00d52016-08-13 01:05:32 +00001782static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001783 const Query &Q) {
Manoj Gupta77eeac32018-07-09 22:27:23 +00001784 const Function *F = nullptr;
1785 if (const Instruction *I = dyn_cast<Instruction>(GEP))
1786 F = I->getFunction();
1787
1788 if (!GEP->isInBounds() ||
1789 NullPointerIsDefined(F, GEP->getPointerAddressSpace()))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001790 return false;
1791
1792 // FIXME: Support vector-GEPs.
1793 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1794
1795 // If the base pointer is non-null, we cannot walk to a null address with an
1796 // inbounds GEP in address space zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001797 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001798 return true;
1799
Chandler Carruth80d3e562012-12-07 02:08:58 +00001800 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1801 // If so, then the GEP cannot produce a null pointer, as doing so would
1802 // inherently violate the inbounds contract within address space zero.
1803 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1804 GTI != GTE; ++GTI) {
1805 // Struct types are easy -- they must always be indexed by a constant.
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001806 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001807 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1808 unsigned ElementIdx = OpC->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001809 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chandler Carruth80d3e562012-12-07 02:08:58 +00001810 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1811 if (ElementOffset > 0)
1812 return true;
1813 continue;
1814 }
1815
1816 // If we have a zero-sized type, the index doesn't matter. Keep looping.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001817 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
Chandler Carruth80d3e562012-12-07 02:08:58 +00001818 continue;
1819
1820 // Fast path the constant operand case both for efficiency and so we don't
1821 // increment Depth when just zipping down an all-constant GEP.
1822 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1823 if (!OpC->isZero())
1824 return true;
1825 continue;
1826 }
1827
1828 // We post-increment Depth here because while isKnownNonZero increments it
1829 // as well, when we pop back up that increment won't persist. We don't want
1830 // to recurse 10k times just because we have 10k GEP operands. We don't
1831 // bail completely out because we want to handle constant GEPs regardless
1832 // of depth.
1833 if (Depth++ >= MaxDepth)
1834 continue;
1835
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001836 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001837 return true;
1838 }
1839
1840 return false;
1841}
1842
Nuno Lopes404f1062017-09-09 18:23:11 +00001843static bool isKnownNonNullFromDominatingCondition(const Value *V,
1844 const Instruction *CtxI,
1845 const DominatorTree *DT) {
1846 assert(V->getType()->isPointerTy() && "V must be pointer type");
1847 assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull");
1848
1849 if (!CtxI || !DT)
1850 return false;
1851
1852 unsigned NumUsesExplored = 0;
1853 for (auto *U : V->users()) {
1854 // Avoid massive lists
1855 if (NumUsesExplored >= DomConditionsMaxUses)
1856 break;
1857 NumUsesExplored++;
1858
1859 // If the value is used as an argument to a call or invoke, then argument
1860 // attributes may provide an answer about null-ness.
1861 if (auto CS = ImmutableCallSite(U))
1862 if (auto *CalledFunc = CS.getCalledFunction())
1863 for (const Argument &Arg : CalledFunc->args())
1864 if (CS.getArgOperand(Arg.getArgNo()) == V &&
1865 Arg.hasNonNullAttr() && DT->dominates(CS.getInstruction(), CtxI))
1866 return true;
1867
1868 // Consider only compare instructions uniquely controlling a branch
1869 CmpInst::Predicate Pred;
1870 if (!match(const_cast<User *>(U),
1871 m_c_ICmp(Pred, m_Specific(V), m_Zero())) ||
1872 (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE))
1873 continue;
1874
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001875 SmallVector<const User *, 4> WorkList;
1876 SmallPtrSet<const User *, 4> Visited;
Nuno Lopes404f1062017-09-09 18:23:11 +00001877 for (auto *CmpU : U->users()) {
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001878 assert(WorkList.empty() && "Should be!");
1879 if (Visited.insert(CmpU).second)
1880 WorkList.push_back(CmpU);
Nuno Lopes404f1062017-09-09 18:23:11 +00001881
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001882 while (!WorkList.empty()) {
1883 auto *Curr = WorkList.pop_back_val();
1884
1885 // If a user is an AND, add all its users to the work list. We only
1886 // propagate "pred != null" condition through AND because it is only
1887 // correct to assume that all conditions of AND are met in true branch.
1888 // TODO: Support similar logic of OR and EQ predicate?
1889 if (Pred == ICmpInst::ICMP_NE)
1890 if (auto *BO = dyn_cast<BinaryOperator>(Curr))
1891 if (BO->getOpcode() == Instruction::And) {
1892 for (auto *BOU : BO->users())
1893 if (Visited.insert(BOU).second)
1894 WorkList.push_back(BOU);
1895 continue;
1896 }
1897
1898 if (const BranchInst *BI = dyn_cast<BranchInst>(Curr)) {
1899 assert(BI->isConditional() && "uses a comparison!");
1900
1901 BasicBlock *NonNullSuccessor =
1902 BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0);
1903 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
1904 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
1905 return true;
Max Kazantsev3c284bd2018-08-30 03:39:16 +00001906 } else if (Pred == ICmpInst::ICMP_NE && isGuard(Curr) &&
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001907 DT->dominates(cast<Instruction>(Curr), CtxI)) {
Nuno Lopes404f1062017-09-09 18:23:11 +00001908 return true;
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001909 }
Nuno Lopes404f1062017-09-09 18:23:11 +00001910 }
1911 }
1912 }
1913
1914 return false;
1915}
1916
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001917/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1918/// ensure that the value it's attached to is never Value? 'RangeType' is
1919/// is the type of the value described by the range.
Pete Cooper35b00d52016-08-13 01:05:32 +00001920static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001921 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1922 assert(NumRanges >= 1);
1923 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001924 ConstantInt *Lower =
1925 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1926 ConstantInt *Upper =
1927 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001928 ConstantRange Range(Lower->getValue(), Upper->getValue());
1929 if (Range.contains(Value))
1930 return false;
1931 }
1932 return true;
1933}
1934
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001935/// Return true if the given value is known to be non-zero when defined. For
1936/// vectors, return true if every element is known to be non-zero when
1937/// defined. For pointers, if the context instruction and dominator tree are
1938/// specified, perform context-sensitive analysis and return true if the
1939/// pointer couldn't possibly be null at the specified instruction.
1940/// Supports values with integer or pointer type and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001941bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) {
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001942 if (auto *C = dyn_cast<Constant>(V)) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001943 if (C->isNullValue())
1944 return false;
1945 if (isa<ConstantInt>(C))
1946 // Must be non-zero due to null test above.
1947 return true;
Sanjay Patel23019d12016-05-24 14:18:49 +00001948
1949 // For constant vectors, check that all elements are undefined or known
1950 // non-zero to determine that the whole vector is known non-zero.
1951 if (auto *VecTy = dyn_cast<VectorType>(C->getType())) {
1952 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
1953 Constant *Elt = C->getAggregateElement(i);
1954 if (!Elt || Elt->isNullValue())
1955 return false;
1956 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
1957 return false;
1958 }
1959 return true;
1960 }
1961
Nuno Lopes404f1062017-09-09 18:23:11 +00001962 // A global variable in address space 0 is non null unless extern weak
1963 // or an absolute symbol reference. Other address spaces may have null as a
1964 // valid address for a global, so we can't assume anything.
1965 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1966 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
1967 GV->getType()->getAddressSpace() == 0)
1968 return true;
1969 } else
1970 return false;
Duncan Sandsd3951082011-01-25 09:38:29 +00001971 }
1972
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001973 if (auto *I = dyn_cast<Instruction>(V)) {
Florian Hahn19f9e322018-08-17 14:39:04 +00001974 if (MDNode *Ranges = Q.IIQ.getMetadata(I, LLVMContext::MD_range)) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001975 // If the possible ranges don't contain zero, then the value is
1976 // definitely non-zero.
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001977 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001978 const APInt ZeroValue(Ty->getBitWidth(), 0);
1979 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1980 return true;
1981 }
1982 }
1983 }
1984
Karl-Johan Karlssonebaaa2d2018-05-30 15:56:46 +00001985 // Some of the tests below are recursive, so bail out if we hit the limit.
1986 if (Depth++ >= MaxDepth)
1987 return false;
1988
Nuno Lopes404f1062017-09-09 18:23:11 +00001989 // Check for pointer simplifications.
1990 if (V->getType()->isPointerTy()) {
1991 // Alloca never returns null, malloc might.
1992 if (isa<AllocaInst>(V) && Q.DL.getAllocaAddrSpace() == 0)
1993 return true;
1994
1995 // A byval, inalloca, or nonnull argument is never null.
1996 if (const Argument *A = dyn_cast<Argument>(V))
1997 if (A->hasByValOrInAllocaAttr() || A->hasNonNullAttr())
1998 return true;
1999
2000 // A Load tagged with nonnull metadata is never null.
2001 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
Florian Hahn19f9e322018-08-17 14:39:04 +00002002 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull))
Nuno Lopes404f1062017-09-09 18:23:11 +00002003 return true;
2004
Piotr Padlewski5642a422018-05-18 23:54:33 +00002005 if (auto CS = ImmutableCallSite(V)) {
Nuno Lopes404f1062017-09-09 18:23:11 +00002006 if (CS.isReturnNonNull())
2007 return true;
Piotr Padlewskid6f73462018-05-23 09:16:44 +00002008 if (const auto *RP = getArgumentAliasingToReturnedPointer(CS))
Karl-Johan Karlssonebaaa2d2018-05-30 15:56:46 +00002009 return isKnownNonZero(RP, Depth, Q);
Piotr Padlewski5642a422018-05-18 23:54:33 +00002010 }
Nuno Lopes404f1062017-09-09 18:23:11 +00002011 }
2012
Duncan Sandsd3951082011-01-25 09:38:29 +00002013
Nuno Lopes404f1062017-09-09 18:23:11 +00002014 // Check for recursive pointer simplifications.
Chandler Carruth80d3e562012-12-07 02:08:58 +00002015 if (V->getType()->isPointerTy()) {
Nuno Lopes404f1062017-09-09 18:23:11 +00002016 if (isKnownNonNullFromDominatingCondition(V, Q.CxtI, Q.DT))
Sanjoy Das6082c1a2016-05-07 02:08:15 +00002017 return true;
Nuno Lopes404f1062017-09-09 18:23:11 +00002018
Pete Cooper35b00d52016-08-13 01:05:32 +00002019 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002020 if (isGEPKnownNonNull(GEP, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00002021 return true;
2022 }
2023
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002024 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00002025
2026 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00002027 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00002028 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002029 return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002030
2031 // ext X != 0 if X != 0.
2032 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002033 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002034
Duncan Sands2e9e4f12011-01-29 13:27:00 +00002035 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00002036 // if the lowest bit is shifted off the end.
Craig Topper6b3940a2017-05-03 22:25:19 +00002037 if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002038 // shl nuw can't remove any non-zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002039 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Florian Hahn19f9e322018-08-17 14:39:04 +00002040 if (Q.IIQ.hasNoUnsignedWrap(BO))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002041 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002042
Craig Topperb45eabc2017-04-26 16:39:58 +00002043 KnownBits Known(BitWidth);
2044 computeKnownBits(X, Known, Depth, Q);
2045 if (Known.One[0])
Duncan Sandsd3951082011-01-25 09:38:29 +00002046 return true;
2047 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00002048 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00002049 // defined if the sign bit is shifted off the end.
2050 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002051 // shr exact can only shift out zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002052 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002053 if (BO->isExact())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002054 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002055
Craig Topper6e11a052017-05-08 16:22:48 +00002056 KnownBits Known = computeKnownBits(X, Depth, Q);
2057 if (Known.isNegative())
Duncan Sandsd3951082011-01-25 09:38:29 +00002058 return true;
James Molloyb6be1eb2015-09-24 16:06:32 +00002059
2060 // If the shifter operand is a constant, and all of the bits shifted
2061 // out are known to be zero, and X is known non-zero then at least one
2062 // non-zero bit must remain.
2063 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
James Molloyb6be1eb2015-09-24 16:06:32 +00002064 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
2065 // Is there a known one in the portion not shifted out?
Craig Topper8df66c62017-05-12 17:20:30 +00002066 if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
James Molloyb6be1eb2015-09-24 16:06:32 +00002067 return true;
2068 // Are all the bits to be shifted out known zero?
NAKAMURA Takumi76bab1f2017-07-11 02:31:51 +00002069 if (Known.countMinTrailingZeros() >= ShiftVal)
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002070 return isKnownNonZero(X, Depth, Q);
James Molloyb6be1eb2015-09-24 16:06:32 +00002071 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002072 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002073 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00002074 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002075 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002076 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002077 // X + Y.
2078 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Craig Topper6e11a052017-05-08 16:22:48 +00002079 KnownBits XKnown = computeKnownBits(X, Depth, Q);
2080 KnownBits YKnown = computeKnownBits(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002081
2082 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00002083 // zero unless both X and Y are zero.
Craig Topper6e11a052017-05-08 16:22:48 +00002084 if (XKnown.isNonNegative() && YKnown.isNonNegative())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002085 if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00002086 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00002087
2088 // If X and Y are both negative (as signed values) then their sum is not
2089 // zero unless both X and Y equal INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002090 if (XKnown.isNegative() && YKnown.isNegative()) {
Duncan Sandsd3951082011-01-25 09:38:29 +00002091 APInt Mask = APInt::getSignedMaxValue(BitWidth);
2092 // The sign bit of X is set. If some other bit is set then X is not equal
2093 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002094 if (XKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00002095 return true;
2096 // The sign bit of Y is set. If some other bit is set then Y is not equal
2097 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002098 if (YKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00002099 return true;
2100 }
2101
2102 // The sum of a non-negative number and a power of two is not zero.
Craig Topper6e11a052017-05-08 16:22:48 +00002103 if (XKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002104 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002105 return true;
Craig Topper6e11a052017-05-08 16:22:48 +00002106 if (YKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002107 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002108 return true;
2109 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00002110 // X * Y.
2111 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00002112 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Duncan Sands7cb61e52011-10-27 19:16:21 +00002113 // If X and Y are non-zero then so is X * Y as long as the multiplication
2114 // does not overflow.
Florian Hahn19f9e322018-08-17 14:39:04 +00002115 if ((Q.IIQ.hasNoSignedWrap(BO) || Q.IIQ.hasNoUnsignedWrap(BO)) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002116 isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00002117 return true;
2118 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002119 // (C ? X : Y) != 0 if X != 0 and Y != 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00002120 else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002121 if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
2122 isKnownNonZero(SI->getFalseValue(), Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002123 return true;
2124 }
James Molloy897048b2015-09-29 14:08:45 +00002125 // PHI
Pete Cooper35b00d52016-08-13 01:05:32 +00002126 else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
James Molloy897048b2015-09-29 14:08:45 +00002127 // Try and detect a recurrence that monotonically increases from a
2128 // starting value, as these are common as induction variables.
2129 if (PN->getNumIncomingValues() == 2) {
2130 Value *Start = PN->getIncomingValue(0);
2131 Value *Induction = PN->getIncomingValue(1);
2132 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
2133 std::swap(Start, Induction);
2134 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
2135 if (!C->isZero() && !C->isNegative()) {
2136 ConstantInt *X;
Florian Hahn19f9e322018-08-17 14:39:04 +00002137 if (Q.IIQ.UseInstrInfo &&
2138 (match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
James Molloy897048b2015-09-29 14:08:45 +00002139 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
2140 !X->isNegative())
2141 return true;
2142 }
2143 }
2144 }
Jun Bum Limca832662016-02-01 17:03:07 +00002145 // Check if all incoming values are non-zero constant.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002146 bool AllNonZeroConstants = llvm::all_of(PN->operands(), [](Value *V) {
Craig Topper79ab6432017-07-06 18:39:47 +00002147 return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZero();
Jun Bum Limca832662016-02-01 17:03:07 +00002148 });
2149 if (AllNonZeroConstants)
2150 return true;
James Molloy897048b2015-09-29 14:08:45 +00002151 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002152
Craig Topperb45eabc2017-04-26 16:39:58 +00002153 KnownBits Known(BitWidth);
2154 computeKnownBits(V, Known, Depth, Q);
2155 return Known.One != 0;
Duncan Sandsd3951082011-01-25 09:38:29 +00002156}
2157
James Molloy1d88d6f2015-10-22 13:18:42 +00002158/// Return true if V2 == V1 + X, where X is known non-zero.
Pete Cooper35b00d52016-08-13 01:05:32 +00002159static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) {
2160 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
James Molloy1d88d6f2015-10-22 13:18:42 +00002161 if (!BO || BO->getOpcode() != Instruction::Add)
2162 return false;
2163 Value *Op = nullptr;
2164 if (V2 == BO->getOperand(0))
2165 Op = BO->getOperand(1);
2166 else if (V2 == BO->getOperand(1))
2167 Op = BO->getOperand(0);
2168 else
2169 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002170 return isKnownNonZero(Op, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002171}
2172
2173/// Return true if it is known that V1 != V2.
Pete Cooper35b00d52016-08-13 01:05:32 +00002174static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) {
Craig Topper3002d5b2017-06-06 07:13:15 +00002175 if (V1 == V2)
James Molloy1d88d6f2015-10-22 13:18:42 +00002176 return false;
2177 if (V1->getType() != V2->getType())
2178 // We can't look through casts yet.
2179 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002180 if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
James Molloy1d88d6f2015-10-22 13:18:42 +00002181 return true;
2182
Craig Topper3002d5b2017-06-06 07:13:15 +00002183 if (V1->getType()->isIntOrIntVectorTy()) {
James Molloy1d88d6f2015-10-22 13:18:42 +00002184 // Are any known bits in V1 contradictory to known bits in V2? If V1
2185 // has a known zero where V2 has a known one, they must not be equal.
Craig Topper8e662f72017-06-06 07:13:11 +00002186 KnownBits Known1 = computeKnownBits(V1, 0, Q);
2187 KnownBits Known2 = computeKnownBits(V2, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002188
Craig Topper8365df82017-06-06 07:13:09 +00002189 if (Known1.Zero.intersects(Known2.One) ||
2190 Known2.Zero.intersects(Known1.One))
James Molloy1d88d6f2015-10-22 13:18:42 +00002191 return true;
2192 }
2193 return false;
2194}
2195
Sanjay Patelaee84212014-11-04 16:27:42 +00002196/// Return true if 'V & Mask' is known to be zero. We use this predicate to
2197/// simplify operations downstream. Mask is known to be zero for bits that V
2198/// cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00002199///
2200/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002201/// type, and vectors of integers. In the case
Chris Lattner4bc28252009-09-08 00:06:16 +00002202/// where V is a vector, the mask, known zero, and known one values are the
2203/// same width as the vector element, and the bit is set only if it is true
2204/// for all of the elements in the vector.
Pete Cooper35b00d52016-08-13 01:05:32 +00002205bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002206 const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002207 KnownBits Known(Mask.getBitWidth());
2208 computeKnownBits(V, Known, Depth, Q);
2209 return Mask.isSubsetOf(Known.Zero);
Chris Lattner965c7692008-06-02 01:18:21 +00002210}
2211
Craig Topperbec15b62018-08-22 23:27:50 +00002212// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
2213// Returns the input and lower/upper bounds.
2214static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
2215 const APInt *&CLow, const APInt *&CHigh) {
Craig Topper15f86922018-08-23 17:15:02 +00002216 assert(isa<Operator>(Select) &&
2217 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
Craig Topperdfa176e2018-08-23 17:45:53 +00002218 "Input should be a Select!");
Craig Topperbec15b62018-08-22 23:27:50 +00002219
2220 const Value *LHS, *RHS, *LHS2, *RHS2;
2221 SelectPatternFlavor SPF = matchSelectPattern(Select, LHS, RHS).Flavor;
2222 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
2223 return false;
2224
2225 if (!match(RHS, m_APInt(CLow)))
2226 return false;
2227
2228 SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor;
2229 if (getInverseMinMaxFlavor(SPF) != SPF2)
2230 return false;
2231
2232 if (!match(RHS2, m_APInt(CHigh)))
2233 return false;
2234
2235 if (SPF == SPF_SMIN)
2236 std::swap(CLow, CHigh);
2237
2238 In = LHS2;
2239 return CLow->sle(*CHigh);
2240}
2241
Sanjay Patela06d9892016-06-22 19:20:59 +00002242/// For vector constants, loop over the elements and find the constant with the
2243/// minimum number of sign bits. Return 0 if the value is not a vector constant
2244/// or if any element was not analyzed; otherwise, return the count for the
2245/// element with the minimum number of sign bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002246static unsigned computeNumSignBitsVectorConstant(const Value *V,
2247 unsigned TyBits) {
2248 const auto *CV = dyn_cast<Constant>(V);
Sanjay Patela06d9892016-06-22 19:20:59 +00002249 if (!CV || !CV->getType()->isVectorTy())
2250 return 0;
Chris Lattner965c7692008-06-02 01:18:21 +00002251
Sanjay Patela06d9892016-06-22 19:20:59 +00002252 unsigned MinSignBits = TyBits;
2253 unsigned NumElts = CV->getType()->getVectorNumElements();
2254 for (unsigned i = 0; i != NumElts; ++i) {
2255 // If we find a non-ConstantInt, bail out.
2256 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
2257 if (!Elt)
2258 return 0;
2259
Craig Topper8e8b6ef2017-10-21 16:35:41 +00002260 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
Sanjay Patela06d9892016-06-22 19:20:59 +00002261 }
2262
2263 return MinSignBits;
2264}
Chris Lattner965c7692008-06-02 01:18:21 +00002265
Sanjoy Das39a684d2017-02-25 20:30:45 +00002266static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2267 const Query &Q);
2268
2269static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
2270 const Query &Q) {
2271 unsigned Result = ComputeNumSignBitsImpl(V, Depth, Q);
2272 assert(Result > 0 && "At least one sign bit needs to be present!");
2273 return Result;
2274}
2275
Sanjay Patelaee84212014-11-04 16:27:42 +00002276/// Return the number of times the sign bit of the register is replicated into
2277/// the other bits. We know that at least 1 bit is always equal to the sign bit
2278/// (itself), but other cases can give us information. For example, immediately
2279/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
Sanjay Patela06d9892016-06-22 19:20:59 +00002280/// other, so we return 3. For vectors, return the number of sign bits for the
Vedant Kumard3196742018-02-28 19:08:52 +00002281/// vector element with the minimum number of known sign bits.
Sanjoy Das39a684d2017-02-25 20:30:45 +00002282static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2283 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00002284 assert(Depth <= MaxDepth && "Limit Search Depth");
Sanjoy Das39a684d2017-02-25 20:30:45 +00002285
2286 // We return the minimum number of sign bits that are guaranteed to be present
2287 // in V, so for undef we have to conservatively return 1. We don't have the
2288 // same behavior for poison though -- that's a FIXME today.
2289
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00002290 Type *ScalarTy = V->getType()->getScalarType();
2291 unsigned TyBits = ScalarTy->isPointerTy() ?
2292 Q.DL.getIndexTypeSizeInBits(ScalarTy) :
2293 Q.DL.getTypeSizeInBits(ScalarTy);
2294
Chris Lattner965c7692008-06-02 01:18:21 +00002295 unsigned Tmp, Tmp2;
2296 unsigned FirstAnswer = 1;
2297
Jay Foada0653a32014-05-14 21:14:37 +00002298 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00002299 // below.
2300
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002301 if (Depth == MaxDepth)
Chris Lattner965c7692008-06-02 01:18:21 +00002302 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002303
Pete Cooper35b00d52016-08-13 01:05:32 +00002304 const Operator *U = dyn_cast<Operator>(V);
Dan Gohman80ca01c2009-07-17 20:47:02 +00002305 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00002306 default: break;
2307 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00002308 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002309 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00002310
Nadav Rotemc99a3872015-03-06 00:23:58 +00002311 case Instruction::SDiv: {
Nadav Rotem029c5c72015-03-03 21:39:02 +00002312 const APInt *Denominator;
2313 // sdiv X, C -> adds log(C) sign bits.
2314 if (match(U->getOperand(1), m_APInt(Denominator))) {
2315
2316 // Ignore non-positive denominator.
2317 if (!Denominator->isStrictlyPositive())
2318 break;
2319
2320 // Calculate the incoming numerator bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002321 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotem029c5c72015-03-03 21:39:02 +00002322
2323 // Add floor(log(C)) bits to the numerator bits.
2324 return std::min(TyBits, NumBits + Denominator->logBase2());
2325 }
2326 break;
Nadav Rotemc99a3872015-03-06 00:23:58 +00002327 }
2328
2329 case Instruction::SRem: {
2330 const APInt *Denominator;
Sanjoy Dase561fee2015-03-25 22:33:53 +00002331 // srem X, C -> we know that the result is within [-C+1,C) when C is a
2332 // positive constant. This let us put a lower bound on the number of sign
2333 // bits.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002334 if (match(U->getOperand(1), m_APInt(Denominator))) {
2335
2336 // Ignore non-positive denominator.
2337 if (!Denominator->isStrictlyPositive())
2338 break;
2339
2340 // Calculate the incoming numerator bits. SRem by a positive constant
2341 // can't lower the number of sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002342 unsigned NumrBits =
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002343 ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotemc99a3872015-03-06 00:23:58 +00002344
2345 // Calculate the leading sign bit constraints by examining the
Sanjoy Dase561fee2015-03-25 22:33:53 +00002346 // denominator. Given that the denominator is positive, there are two
2347 // cases:
2348 //
2349 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
2350 // (1 << ceilLogBase2(C)).
2351 //
2352 // 2. the numerator is negative. Then the result range is (-C,0] and
2353 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2354 //
2355 // Thus a lower bound on the number of sign bits is `TyBits -
2356 // ceilLogBase2(C)`.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002357
Sanjoy Dase561fee2015-03-25 22:33:53 +00002358 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
Nadav Rotemc99a3872015-03-06 00:23:58 +00002359 return std::max(NumrBits, ResBits);
2360 }
2361 break;
2362 }
Nadav Rotem029c5c72015-03-03 21:39:02 +00002363
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002364 case Instruction::AShr: {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002365 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002366 // ashr X, C -> adds C sign bits. Vectors too.
2367 const APInt *ShAmt;
2368 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Simon Pilgrim67207262018-01-01 22:44:59 +00002369 if (ShAmt->uge(TyBits))
Sanjoy Das39a684d2017-02-25 20:30:45 +00002370 break; // Bad shift.
Simon Pilgrim67207262018-01-01 22:44:59 +00002371 unsigned ShAmtLimited = ShAmt->getZExtValue();
Sanjoy Das39a684d2017-02-25 20:30:45 +00002372 Tmp += ShAmtLimited;
Chris Lattner965c7692008-06-02 01:18:21 +00002373 if (Tmp > TyBits) Tmp = TyBits;
2374 }
2375 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002376 }
2377 case Instruction::Shl: {
2378 const APInt *ShAmt;
2379 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00002380 // shl destroys sign bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002381 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Simon Pilgrim67207262018-01-01 22:44:59 +00002382 if (ShAmt->uge(TyBits) || // Bad shift.
2383 ShAmt->uge(Tmp)) break; // Shifted all sign bits out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002384 Tmp2 = ShAmt->getZExtValue();
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002385 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00002386 }
2387 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002388 }
Chris Lattner965c7692008-06-02 01:18:21 +00002389 case Instruction::And:
2390 case Instruction::Or:
2391 case Instruction::Xor: // NOT is handled here.
2392 // Logical binary ops preserve the number of sign bits at the worst.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002393 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002394 if (Tmp != 1) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002395 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002396 FirstAnswer = std::min(Tmp, Tmp2);
2397 // We computed what we know about the sign bits as our first
2398 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00002399 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00002400 }
2401 break;
2402
Craig Topperbec15b62018-08-22 23:27:50 +00002403 case Instruction::Select: {
2404 // If we have a clamp pattern, we know that the number of sign bits will be
2405 // the minimum of the clamp min/max range.
2406 const Value *X;
2407 const APInt *CLow, *CHigh;
2408 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
2409 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
2410
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002411 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002412 if (Tmp == 1) break;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002413 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002414 return std::min(Tmp, Tmp2);
Craig Topperbec15b62018-08-22 23:27:50 +00002415 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002416
Chris Lattner965c7692008-06-02 01:18:21 +00002417 case Instruction::Add:
2418 // Add can have at most one carry bit. Thus we know that the output
2419 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002420 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002421 if (Tmp == 1) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002422
Chris Lattner965c7692008-06-02 01:18:21 +00002423 // Special case decrementing a value (ADD X, -1):
David Majnemera55027f2014-12-26 09:20:17 +00002424 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00002425 if (CRHS->isAllOnesValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002426 KnownBits Known(TyBits);
2427 computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002428
Chris Lattner965c7692008-06-02 01:18:21 +00002429 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2430 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002431 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002432 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002433
Chris Lattner965c7692008-06-02 01:18:21 +00002434 // If we are subtracting one from a positive number, there is no carry
2435 // out of the result.
Craig Topperca48af32017-04-29 16:43:11 +00002436 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002437 return Tmp;
2438 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002439
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002440 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002441 if (Tmp2 == 1) break;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002442 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002443
Chris Lattner965c7692008-06-02 01:18:21 +00002444 case Instruction::Sub:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002445 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002446 if (Tmp2 == 1) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002447
Chris Lattner965c7692008-06-02 01:18:21 +00002448 // Handle NEG.
David Majnemera55027f2014-12-26 09:20:17 +00002449 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
Chris Lattner965c7692008-06-02 01:18:21 +00002450 if (CLHS->isNullValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002451 KnownBits Known(TyBits);
2452 computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002453 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2454 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002455 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002456 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002457
Chris Lattner965c7692008-06-02 01:18:21 +00002458 // If the input is known to be positive (the sign bit is known clear),
2459 // the output of the NEG has the same number of sign bits as the input.
Craig Topperca48af32017-04-29 16:43:11 +00002460 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002461 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00002462
Chris Lattner965c7692008-06-02 01:18:21 +00002463 // Otherwise, we treat this like a SUB.
2464 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002465
Chris Lattner965c7692008-06-02 01:18:21 +00002466 // Sub can have at most one carry bit. Thus we know that the output
2467 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002468 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002469 if (Tmp == 1) break;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002470 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002471
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002472 case Instruction::Mul: {
2473 // The output of the Mul can be at most twice the valid bits in the inputs.
2474 unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002475 if (SignBitsOp0 == 1) break;
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002476 unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002477 if (SignBitsOp1 == 1) break;
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002478 unsigned OutValidBits =
2479 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
2480 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
2481 }
2482
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002483 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00002484 const PHINode *PN = cast<PHINode>(U);
David Majnemer6ee8d172015-01-04 07:06:53 +00002485 unsigned NumIncomingValues = PN->getNumIncomingValues();
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002486 // Don't analyze large in-degree PHIs.
David Majnemer6ee8d172015-01-04 07:06:53 +00002487 if (NumIncomingValues > 4) break;
2488 // Unreachable blocks may have zero-operand PHI nodes.
2489 if (NumIncomingValues == 0) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002490
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002491 // Take the minimum of all incoming values. This can't infinitely loop
2492 // because of our depth threshold.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002493 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
David Majnemer6ee8d172015-01-04 07:06:53 +00002494 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002495 if (Tmp == 1) return Tmp;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002496 Tmp = std::min(
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002497 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002498 }
2499 return Tmp;
2500 }
2501
Chris Lattner965c7692008-06-02 01:18:21 +00002502 case Instruction::Trunc:
2503 // FIXME: it's tricky to do anything useful for this, but it is an important
2504 // case for targets like X86.
2505 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00002506
2507 case Instruction::ExtractElement:
2508 // Look through extract element. At the moment we keep this simple and skip
2509 // tracking the specific element. But at least we might find information
2510 // valid for all elements of the vector (for example if vector is sign
2511 // extended, shifted, etc).
2512 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Sanjay Patelcc9e4012018-10-26 21:05:14 +00002513
Sanjay Patela68096c2018-11-02 15:51:47 +00002514 case Instruction::ShuffleVector: {
Sanjay Patelcac28b42018-11-03 13:18:55 +00002515 // TODO: This is copied almost directly from the SelectionDAG version of
2516 // ComputeNumSignBits. It would be better if we could share common
2517 // code. If not, make sure that changes are translated to the DAG.
2518
2519 // Collect the minimum number of sign bits that are shared by every vector
2520 // element referenced by the shuffle.
2521 auto *Shuf = cast<ShuffleVectorInst>(U);
2522 int NumElts = Shuf->getOperand(0)->getType()->getVectorNumElements();
2523 int NumMaskElts = Shuf->getMask()->getType()->getVectorNumElements();
2524 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2525 for (int i = 0; i != NumMaskElts; ++i) {
2526 int M = Shuf->getMaskValue(i);
2527 assert(M < NumElts * 2 && "Invalid shuffle mask constant");
2528 // For undef elements, we don't know anything about the common state of
2529 // the shuffle result.
2530 if (M == -1)
2531 return 1;
2532 if (M < NumElts)
2533 DemandedLHS.setBit(M % NumElts);
2534 else
2535 DemandedRHS.setBit(M % NumElts);
2536 }
2537 Tmp = std::numeric_limits<unsigned>::max();
2538 if (!!DemandedLHS)
2539 Tmp = ComputeNumSignBits(Shuf->getOperand(0), Depth + 1, Q);
2540 if (!!DemandedRHS) {
2541 Tmp2 = ComputeNumSignBits(Shuf->getOperand(1), Depth + 1, Q);
2542 Tmp = std::min(Tmp, Tmp2);
2543 }
2544 // If we don't know anything, early out and try computeKnownBits fall-back.
2545 if (Tmp == 1)
Sanjay Patelcc9e4012018-10-26 21:05:14 +00002546 break;
Sanjay Patelcac28b42018-11-03 13:18:55 +00002547 assert(Tmp <= V->getType()->getScalarSizeInBits() &&
2548 "Failed to determine minimum sign bits");
2549 return Tmp;
Chris Lattner965c7692008-06-02 01:18:21 +00002550 }
Sanjay Patela68096c2018-11-02 15:51:47 +00002551 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002552
Chris Lattner965c7692008-06-02 01:18:21 +00002553 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2554 // use this information.
Sanjay Patela06d9892016-06-22 19:20:59 +00002555
2556 // If we can examine all elements of a vector constant successfully, we're
2557 // done (we can't do any better than that). If not, keep trying.
2558 if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits))
2559 return VecSignBits;
2560
Craig Topperb45eabc2017-04-26 16:39:58 +00002561 KnownBits Known(TyBits);
2562 computeKnownBits(V, Known, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002563
Sanjay Patele0536212016-06-23 17:41:59 +00002564 // If we know that the sign bit is either zero or one, determine the number of
2565 // identical bits in the top of the input value.
Craig Topper8df66c62017-05-12 17:20:30 +00002566 return std::max(FirstAnswer, Known.countMinSignBits());
Chris Lattner965c7692008-06-02 01:18:21 +00002567}
Chris Lattnera12a6de2008-06-02 01:29:46 +00002568
Sanjay Patelaee84212014-11-04 16:27:42 +00002569/// This function computes the integer multiple of Base that equals V.
2570/// If successful, it returns true and returns the multiple in
2571/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00002572/// through SExt instructions only if LookThroughSExt is true.
2573bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00002574 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00002575 const unsigned MaxDepth = 6;
2576
Dan Gohman6a976bb2009-11-18 00:58:27 +00002577 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00002578 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002579 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00002580
Chris Lattner229907c2011-07-18 04:54:35 +00002581 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00002582
Dan Gohman6a976bb2009-11-18 00:58:27 +00002583 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00002584
2585 if (Base == 0)
2586 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002587
Victor Hernandez47444882009-11-10 08:28:35 +00002588 if (Base == 1) {
2589 Multiple = V;
2590 return true;
2591 }
2592
2593 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2594 Constant *BaseVal = ConstantInt::get(T, Base);
2595 if (CO && CO == BaseVal) {
2596 // Multiple is 1.
2597 Multiple = ConstantInt::get(T, 1);
2598 return true;
2599 }
2600
2601 if (CI && CI->getZExtValue() % Base == 0) {
2602 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00002603 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00002604 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002605
Victor Hernandez47444882009-11-10 08:28:35 +00002606 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002607
Victor Hernandez47444882009-11-10 08:28:35 +00002608 Operator *I = dyn_cast<Operator>(V);
2609 if (!I) return false;
2610
2611 switch (I->getOpcode()) {
2612 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002613 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00002614 if (!LookThroughSExt) return false;
2615 // otherwise fall through to ZExt
Galina Kistanova244621f2017-05-31 22:16:24 +00002616 LLVM_FALLTHROUGH;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002617 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00002618 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2619 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00002620 case Instruction::Shl:
2621 case Instruction::Mul: {
2622 Value *Op0 = I->getOperand(0);
2623 Value *Op1 = I->getOperand(1);
2624
2625 if (I->getOpcode() == Instruction::Shl) {
2626 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2627 if (!Op1CI) return false;
2628 // Turn Op0 << Op1 into Op0 * 2^Op1
2629 APInt Op1Int = Op1CI->getValue();
2630 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00002631 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002632 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00002633 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00002634 }
2635
Craig Topper9f008862014-04-15 04:59:12 +00002636 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002637 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2638 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2639 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002640 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002641 MulC->getType()->getPrimitiveSizeInBits())
2642 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002643 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002644 MulC->getType()->getPrimitiveSizeInBits())
2645 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002646
Chris Lattner72d283c2010-09-05 17:20:46 +00002647 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2648 Multiple = ConstantExpr::getMul(MulC, Op1C);
2649 return true;
2650 }
Victor Hernandez47444882009-11-10 08:28:35 +00002651
2652 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2653 if (Mul0CI->getValue() == 1) {
2654 // V == Base * Op1, so return Op1
2655 Multiple = Op1;
2656 return true;
2657 }
2658 }
2659
Craig Topper9f008862014-04-15 04:59:12 +00002660 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002661 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2662 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2663 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002664 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002665 MulC->getType()->getPrimitiveSizeInBits())
2666 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002667 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002668 MulC->getType()->getPrimitiveSizeInBits())
2669 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002670
Chris Lattner72d283c2010-09-05 17:20:46 +00002671 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2672 Multiple = ConstantExpr::getMul(MulC, Op0C);
2673 return true;
2674 }
Victor Hernandez47444882009-11-10 08:28:35 +00002675
2676 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2677 if (Mul1CI->getValue() == 1) {
2678 // V == Base * Op0, so return Op0
2679 Multiple = Op0;
2680 return true;
2681 }
2682 }
Victor Hernandez47444882009-11-10 08:28:35 +00002683 }
2684 }
2685
2686 // We could not determine if V is a multiple of Base.
2687 return false;
2688}
2689
David Majnemerb4b27232016-04-19 19:10:21 +00002690Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS,
2691 const TargetLibraryInfo *TLI) {
2692 const Function *F = ICS.getCalledFunction();
2693 if (!F)
2694 return Intrinsic::not_intrinsic;
2695
2696 if (F->isIntrinsic())
2697 return F->getIntrinsicID();
2698
2699 if (!TLI)
2700 return Intrinsic::not_intrinsic;
2701
David L. Jonesd21529f2017-01-23 23:16:46 +00002702 LibFunc Func;
David Majnemerb4b27232016-04-19 19:10:21 +00002703 // We're going to make assumptions on the semantics of the functions, check
2704 // that the target knows that it's available in this environment and it does
2705 // not have local linkage.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002706 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func))
2707 return Intrinsic::not_intrinsic;
2708
2709 if (!ICS.onlyReadsMemory())
David Majnemerb4b27232016-04-19 19:10:21 +00002710 return Intrinsic::not_intrinsic;
2711
2712 // Otherwise check if we have a call to a function that can be turned into a
2713 // vector intrinsic.
2714 switch (Func) {
2715 default:
2716 break;
David L. Jonesd21529f2017-01-23 23:16:46 +00002717 case LibFunc_sin:
2718 case LibFunc_sinf:
2719 case LibFunc_sinl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002720 return Intrinsic::sin;
David L. Jonesd21529f2017-01-23 23:16:46 +00002721 case LibFunc_cos:
2722 case LibFunc_cosf:
2723 case LibFunc_cosl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002724 return Intrinsic::cos;
David L. Jonesd21529f2017-01-23 23:16:46 +00002725 case LibFunc_exp:
2726 case LibFunc_expf:
2727 case LibFunc_expl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002728 return Intrinsic::exp;
David L. Jonesd21529f2017-01-23 23:16:46 +00002729 case LibFunc_exp2:
2730 case LibFunc_exp2f:
2731 case LibFunc_exp2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002732 return Intrinsic::exp2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002733 case LibFunc_log:
2734 case LibFunc_logf:
2735 case LibFunc_logl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002736 return Intrinsic::log;
David L. Jonesd21529f2017-01-23 23:16:46 +00002737 case LibFunc_log10:
2738 case LibFunc_log10f:
2739 case LibFunc_log10l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002740 return Intrinsic::log10;
David L. Jonesd21529f2017-01-23 23:16:46 +00002741 case LibFunc_log2:
2742 case LibFunc_log2f:
2743 case LibFunc_log2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002744 return Intrinsic::log2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002745 case LibFunc_fabs:
2746 case LibFunc_fabsf:
2747 case LibFunc_fabsl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002748 return Intrinsic::fabs;
David L. Jonesd21529f2017-01-23 23:16:46 +00002749 case LibFunc_fmin:
2750 case LibFunc_fminf:
2751 case LibFunc_fminl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002752 return Intrinsic::minnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002753 case LibFunc_fmax:
2754 case LibFunc_fmaxf:
2755 case LibFunc_fmaxl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002756 return Intrinsic::maxnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002757 case LibFunc_copysign:
2758 case LibFunc_copysignf:
2759 case LibFunc_copysignl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002760 return Intrinsic::copysign;
David L. Jonesd21529f2017-01-23 23:16:46 +00002761 case LibFunc_floor:
2762 case LibFunc_floorf:
2763 case LibFunc_floorl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002764 return Intrinsic::floor;
David L. Jonesd21529f2017-01-23 23:16:46 +00002765 case LibFunc_ceil:
2766 case LibFunc_ceilf:
2767 case LibFunc_ceill:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002768 return Intrinsic::ceil;
David L. Jonesd21529f2017-01-23 23:16:46 +00002769 case LibFunc_trunc:
2770 case LibFunc_truncf:
2771 case LibFunc_truncl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002772 return Intrinsic::trunc;
David L. Jonesd21529f2017-01-23 23:16:46 +00002773 case LibFunc_rint:
2774 case LibFunc_rintf:
2775 case LibFunc_rintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002776 return Intrinsic::rint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002777 case LibFunc_nearbyint:
2778 case LibFunc_nearbyintf:
2779 case LibFunc_nearbyintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002780 return Intrinsic::nearbyint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002781 case LibFunc_round:
2782 case LibFunc_roundf:
2783 case LibFunc_roundl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002784 return Intrinsic::round;
David L. Jonesd21529f2017-01-23 23:16:46 +00002785 case LibFunc_pow:
2786 case LibFunc_powf:
2787 case LibFunc_powl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002788 return Intrinsic::pow;
David L. Jonesd21529f2017-01-23 23:16:46 +00002789 case LibFunc_sqrt:
2790 case LibFunc_sqrtf:
2791 case LibFunc_sqrtl:
Sanjay Patel86d24f12017-11-06 22:40:09 +00002792 return Intrinsic::sqrt;
David Majnemerb4b27232016-04-19 19:10:21 +00002793 }
2794
2795 return Intrinsic::not_intrinsic;
2796}
2797
Sanjay Patelaee84212014-11-04 16:27:42 +00002798/// Return true if we can prove that the specified FP value is never equal to
2799/// -0.0.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002800///
2801/// NOTE: this function will need to be revisited when we support non-default
2802/// rounding modes!
David Majnemer3ee5f342016-04-13 06:55:52 +00002803bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
2804 unsigned Depth) {
Sanjay Patel20df88a2017-11-13 17:56:23 +00002805 if (auto *CFP = dyn_cast<ConstantFP>(V))
Chris Lattnera12a6de2008-06-02 01:29:46 +00002806 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00002807
Sanjay Patel20df88a2017-11-13 17:56:23 +00002808 // Limit search depth.
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002809 if (Depth == MaxDepth)
Sanjay Patel20df88a2017-11-13 17:56:23 +00002810 return false;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002811
Sanjay Patel20df88a2017-11-13 17:56:23 +00002812 auto *Op = dyn_cast<Operator>(V);
2813 if (!Op)
2814 return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00002815
Sanjay Patel20df88a2017-11-13 17:56:23 +00002816 // Check if the nsz fast-math flag is set.
2817 if (auto *FPO = dyn_cast<FPMathOperator>(Op))
Michael Ilseman0f128372012-12-06 00:07:09 +00002818 if (FPO->hasNoSignedZeros())
2819 return true;
2820
Sanjay Patel9e3d8f42017-11-13 17:40:47 +00002821 // (fadd x, 0.0) is guaranteed to return +0.0, not -0.0.
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002822 if (match(Op, m_FAdd(m_Value(), m_PosZeroFP())))
Sanjay Patel9e3d8f42017-11-13 17:40:47 +00002823 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002824
Chris Lattnera12a6de2008-06-02 01:29:46 +00002825 // sitofp and uitofp turn into +0.0 for zero.
Sanjay Patel20df88a2017-11-13 17:56:23 +00002826 if (isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op))
Chris Lattnera12a6de2008-06-02 01:29:46 +00002827 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002828
Sanjay Patel20df88a2017-11-13 17:56:23 +00002829 if (auto *Call = dyn_cast<CallInst>(Op)) {
2830 Intrinsic::ID IID = getIntrinsicForCallSite(Call, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002831 switch (IID) {
2832 default:
2833 break;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002834 // sqrt(-0.0) = -0.0, no other negative results are possible.
David Majnemer3ee5f342016-04-13 06:55:52 +00002835 case Intrinsic::sqrt:
Matt Arsenault56b31d82018-08-06 15:16:26 +00002836 case Intrinsic::canonicalize:
Sanjay Patel20df88a2017-11-13 17:56:23 +00002837 return CannotBeNegativeZero(Call->getArgOperand(0), TLI, Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002838 // fabs(x) != -0.0
2839 case Intrinsic::fabs:
2840 return true;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002841 }
David Majnemer3ee5f342016-04-13 06:55:52 +00002842 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002843
Chris Lattnera12a6de2008-06-02 01:29:46 +00002844 return false;
2845}
2846
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002847/// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
2848/// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
2849/// bit despite comparing equal.
2850static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
2851 const TargetLibraryInfo *TLI,
2852 bool SignBitOnly,
2853 unsigned Depth) {
Justin Lebar322c1272017-01-27 00:58:34 +00002854 // TODO: This function does not do the right thing when SignBitOnly is true
2855 // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
2856 // which flips the sign bits of NaNs. See
2857 // https://llvm.org/bugs/show_bug.cgi?id=31702.
2858
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002859 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2860 return !CFP->getValueAPF().isNegative() ||
2861 (!SignBitOnly && CFP->getValueAPF().isZero());
2862 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002863
Craig Topper69c89722018-02-26 22:33:17 +00002864 // Handle vector of constants.
2865 if (auto *CV = dyn_cast<Constant>(V)) {
2866 if (CV->getType()->isVectorTy()) {
2867 unsigned NumElts = CV->getType()->getVectorNumElements();
2868 for (unsigned i = 0; i != NumElts; ++i) {
2869 auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
2870 if (!CFP)
2871 return false;
2872 if (CFP->getValueAPF().isNegative() &&
2873 (SignBitOnly || !CFP->getValueAPF().isZero()))
2874 return false;
2875 }
2876
2877 // All non-negative ConstantFPs.
2878 return true;
2879 }
2880 }
2881
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002882 if (Depth == MaxDepth)
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002883 return false; // Limit search depth.
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002884
2885 const Operator *I = dyn_cast<Operator>(V);
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002886 if (!I)
2887 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002888
2889 switch (I->getOpcode()) {
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002890 default:
2891 break;
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002892 // Unsigned integers are always nonnegative.
2893 case Instruction::UIToFP:
2894 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002895 case Instruction::FMul:
2896 // x*x is always non-negative or a NaN.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002897 if (I->getOperand(0) == I->getOperand(1) &&
2898 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002899 return true;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002900
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002901 LLVM_FALLTHROUGH;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002902 case Instruction::FAdd:
2903 case Instruction::FDiv:
2904 case Instruction::FRem:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002905 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2906 Depth + 1) &&
2907 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2908 Depth + 1);
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002909 case Instruction::Select:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002910 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2911 Depth + 1) &&
2912 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2913 Depth + 1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002914 case Instruction::FPExt:
2915 case Instruction::FPTrunc:
2916 // Widening/narrowing never change sign.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002917 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2918 Depth + 1);
Craig Topper30199102018-02-27 19:53:45 +00002919 case Instruction::ExtractElement:
2920 // Look through extract element. At the moment we keep this simple and skip
2921 // tracking the specific element. But at least we might find information
2922 // valid for all elements of the vector.
2923 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2924 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002925 case Instruction::Call:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002926 const auto *CI = cast<CallInst>(I);
2927 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002928 switch (IID) {
2929 default:
2930 break;
2931 case Intrinsic::maxnum:
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00002932 return (isKnownNeverNaN(I->getOperand(0), TLI) &&
Sanjay Patelf9a0d592018-08-02 13:46:20 +00002933 cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI,
2934 SignBitOnly, Depth + 1)) ||
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00002935 (isKnownNeverNaN(I->getOperand(1), TLI) &&
Sanjay Patelf9a0d592018-08-02 13:46:20 +00002936 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI,
2937 SignBitOnly, Depth + 1));
2938
Thomas Livelyc3392502018-10-19 19:01:26 +00002939 case Intrinsic::maximum:
2940 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2941 Depth + 1) ||
2942 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2943 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002944 case Intrinsic::minnum:
Thomas Livelyc3392502018-10-19 19:01:26 +00002945 case Intrinsic::minimum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002946 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2947 Depth + 1) &&
2948 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2949 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002950 case Intrinsic::exp:
2951 case Intrinsic::exp2:
2952 case Intrinsic::fabs:
David Majnemer3ee5f342016-04-13 06:55:52 +00002953 return true;
Justin Lebar7e3184c2017-01-26 00:10:26 +00002954
2955 case Intrinsic::sqrt:
2956 // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0.
2957 if (!SignBitOnly)
2958 return true;
2959 return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
2960 CannotBeNegativeZero(CI->getOperand(0), TLI));
2961
David Majnemer3ee5f342016-04-13 06:55:52 +00002962 case Intrinsic::powi:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002963 if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
David Majnemer3ee5f342016-04-13 06:55:52 +00002964 // powi(x,n) is non-negative if n is even.
Justin Lebar7e3184c2017-01-26 00:10:26 +00002965 if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
David Majnemer3ee5f342016-04-13 06:55:52 +00002966 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002967 }
Justin Lebar322c1272017-01-27 00:58:34 +00002968 // TODO: This is not correct. Given that exp is an integer, here are the
2969 // ways that pow can return a negative value:
2970 //
2971 // pow(x, exp) --> negative if exp is odd and x is negative.
2972 // pow(-0, exp) --> -inf if exp is negative odd.
2973 // pow(-0, exp) --> -0 if exp is positive odd.
2974 // pow(-inf, exp) --> -0 if exp is negative odd.
2975 // pow(-inf, exp) --> -inf if exp is positive odd.
2976 //
2977 // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
2978 // but we must return false if x == -0. Unfortunately we do not currently
2979 // have a way of expressing this constraint. See details in
2980 // https://llvm.org/bugs/show_bug.cgi?id=31702.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002981 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2982 Depth + 1);
Justin Lebar322c1272017-01-27 00:58:34 +00002983
David Majnemer3ee5f342016-04-13 06:55:52 +00002984 case Intrinsic::fma:
2985 case Intrinsic::fmuladd:
2986 // x*x+y is non-negative if y is non-negative.
2987 return I->getOperand(0) == I->getOperand(1) &&
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002988 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
2989 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2990 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002991 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002992 break;
2993 }
Sanjoy Das6082c1a2016-05-07 02:08:15 +00002994 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002995}
2996
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002997bool llvm::CannotBeOrderedLessThanZero(const Value *V,
2998 const TargetLibraryInfo *TLI) {
2999 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
3000}
3001
3002bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
3003 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
3004}
3005
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003006bool llvm::isKnownNeverNaN(const Value *V, const TargetLibraryInfo *TLI,
3007 unsigned Depth) {
Sanjay Patel6840c5f2017-09-05 23:13:13 +00003008 assert(V->getType()->isFPOrFPVectorTy() && "Querying for NaN on non-FP type");
3009
3010 // If we're told that NaNs won't happen, assume they won't.
3011 if (auto *FPMathOp = dyn_cast<FPMathOperator>(V))
3012 if (FPMathOp->hasNoNaNs())
3013 return true;
3014
Sanjay Patel6840c5f2017-09-05 23:13:13 +00003015 // Handle scalar constants.
3016 if (auto *CFP = dyn_cast<ConstantFP>(V))
3017 return !CFP->isNaN();
3018
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003019 if (Depth == MaxDepth)
3020 return false;
3021
Matt Arsenault450fcc72018-08-20 16:51:00 +00003022 if (auto *Inst = dyn_cast<Instruction>(V)) {
3023 switch (Inst->getOpcode()) {
3024 case Instruction::FAdd:
3025 case Instruction::FMul:
3026 case Instruction::FSub:
3027 case Instruction::FDiv:
3028 case Instruction::FRem: {
3029 // TODO: Need isKnownNeverInfinity
3030 return false;
3031 }
3032 case Instruction::Select: {
3033 return isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) &&
3034 isKnownNeverNaN(Inst->getOperand(2), TLI, Depth + 1);
3035 }
3036 case Instruction::SIToFP:
3037 case Instruction::UIToFP:
3038 return true;
3039 case Instruction::FPTrunc:
3040 case Instruction::FPExt:
3041 return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1);
3042 default:
3043 break;
3044 }
3045 }
3046
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003047 if (const auto *II = dyn_cast<IntrinsicInst>(V)) {
3048 switch (II->getIntrinsicID()) {
3049 case Intrinsic::canonicalize:
3050 case Intrinsic::fabs:
3051 case Intrinsic::copysign:
Matt Arsenault450fcc72018-08-20 16:51:00 +00003052 case Intrinsic::exp:
3053 case Intrinsic::exp2:
3054 case Intrinsic::floor:
3055 case Intrinsic::ceil:
3056 case Intrinsic::trunc:
3057 case Intrinsic::rint:
3058 case Intrinsic::nearbyint:
3059 case Intrinsic::round:
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003060 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1);
3061 case Intrinsic::sqrt:
3062 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) &&
3063 CannotBeOrderedLessThanZero(II->getArgOperand(0), TLI);
3064 default:
3065 return false;
3066 }
3067 }
3068
Sanjay Patel6840c5f2017-09-05 23:13:13 +00003069 // Bail out for constant expressions, but try to handle vector constants.
3070 if (!V->getType()->isVectorTy() || !isa<Constant>(V))
3071 return false;
3072
3073 // For vectors, verify that each element is not NaN.
3074 unsigned NumElts = V->getType()->getVectorNumElements();
3075 for (unsigned i = 0; i != NumElts; ++i) {
3076 Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
3077 if (!Elt)
3078 return false;
3079 if (isa<UndefValue>(Elt))
3080 continue;
3081 auto *CElt = dyn_cast<ConstantFP>(Elt);
3082 if (!CElt || CElt->isNaN())
3083 return false;
3084 }
3085 // All elements were confirmed not-NaN or undefined.
3086 return true;
3087}
3088
Chris Lattner9cb10352010-12-26 20:15:01 +00003089Value *llvm::isBytewiseValue(Value *V) {
JF Bastien73d8e4e2018-09-21 05:17:42 +00003090
Chris Lattner9cb10352010-12-26 20:15:01 +00003091 // All byte-wide stores are splatable, even of arbitrary variables.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003092 if (V->getType()->isIntegerTy(8))
3093 return V;
3094
3095 LLVMContext &Ctx = V->getContext();
3096
3097 // Undef don't care.
3098 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
3099 if (isa<UndefValue>(V))
3100 return UndefInt8;
3101
3102 Constant *C = dyn_cast<Constant>(V);
3103 if (!C) {
3104 // Conceptually, we could handle things like:
3105 // %a = zext i8 %X to i16
3106 // %b = shl i16 %a, 8
3107 // %c = or i16 %a, %b
3108 // but until there is an example that actually needs this, it doesn't seem
3109 // worth worrying about.
3110 return nullptr;
3111 }
Chris Lattneracf6b072011-02-19 19:35:49 +00003112
3113 // Handle 'null' ConstantArrayZero etc.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003114 if (C->isNullValue())
3115 return Constant::getNullValue(Type::getInt8Ty(Ctx));
Craig Topper1bef2c82012-12-22 19:15:35 +00003116
JF Bastien73d8e4e2018-09-21 05:17:42 +00003117 // Constant floating-point values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00003118 // corresponding integer value is "byteable". An important case is 0.0.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003119 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3120 Type *Ty = nullptr;
3121 if (CFP->getType()->isHalfTy())
3122 Ty = Type::getInt16Ty(Ctx);
3123 else if (CFP->getType()->isFloatTy())
3124 Ty = Type::getInt32Ty(Ctx);
3125 else if (CFP->getType()->isDoubleTy())
3126 Ty = Type::getInt64Ty(Ctx);
Chris Lattner9cb10352010-12-26 20:15:01 +00003127 // Don't handle long double formats, which have strange constraints.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003128 return Ty ? isBytewiseValue(ConstantExpr::getBitCast(CFP, Ty)) : nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00003129 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003130
Benjamin Kramer17d90152015-02-07 19:29:02 +00003131 // We can handle constant integers that are multiple of 8 bits.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003132 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
Benjamin Kramer17d90152015-02-07 19:29:02 +00003133 if (CI->getBitWidth() % 8 == 0) {
3134 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
Benjamin Kramerb4b51502015-03-25 16:49:59 +00003135 if (!CI->getValue().isSplat(8))
Benjamin Kramer17d90152015-02-07 19:29:02 +00003136 return nullptr;
JF Bastien73d8e4e2018-09-21 05:17:42 +00003137 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
Chris Lattner9cb10352010-12-26 20:15:01 +00003138 }
3139 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003140
JF Bastien73d8e4e2018-09-21 05:17:42 +00003141 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
3142 if (LHS == RHS)
3143 return LHS;
3144 if (!LHS || !RHS)
Craig Topper9f008862014-04-15 04:59:12 +00003145 return nullptr;
JF Bastien73d8e4e2018-09-21 05:17:42 +00003146 if (LHS == UndefInt8)
3147 return RHS;
3148 if (RHS == UndefInt8)
3149 return LHS;
3150 return nullptr;
3151 };
Craig Topper1bef2c82012-12-22 19:15:35 +00003152
JF Bastien73d8e4e2018-09-21 05:17:42 +00003153 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(C)) {
3154 Value *Val = UndefInt8;
3155 for (unsigned I = 0, E = CA->getNumElements(); I != E; ++I)
3156 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I)))))
Craig Topper9f008862014-04-15 04:59:12 +00003157 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00003158 return Val;
3159 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00003160
JF Bastien73d8e4e2018-09-21 05:17:42 +00003161 if (isa<ConstantVector>(C)) {
3162 Constant *Splat = cast<ConstantVector>(C)->getSplatValue();
3163 return Splat ? isBytewiseValue(Splat) : nullptr;
3164 }
3165
3166 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
3167 Value *Val = UndefInt8;
3168 for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I)
3169 if (!(Val = Merge(Val, isBytewiseValue(C->getOperand(I)))))
3170 return nullptr;
3171 return Val;
3172 }
3173
3174 // Don't try to handle the handful of other constants.
Craig Topper9f008862014-04-15 04:59:12 +00003175 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00003176}
3177
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003178// This is the recursive version of BuildSubAggregate. It takes a few different
3179// arguments. Idxs is the index within the nested struct From that we are
3180// looking at now (which is of type IndexedType). IdxSkip is the number of
3181// indices from Idxs that should be left out when inserting into the resulting
3182// struct. To is the result struct built so far, new insertvalue instructions
3183// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00003184static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00003185 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00003186 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00003187 Instruction *InsertBefore) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003188 StructType *STy = dyn_cast<StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003189 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003190 // Save the original To argument so we can modify it
3191 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003192 // General case, the type indexed by Idxs is a struct
3193 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3194 // Process each struct element recursively
3195 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003196 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003197 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003198 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003199 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003200 if (!To) {
3201 // Couldn't find any inserted value for this index? Cleanup
3202 while (PrevTo != OrigTo) {
3203 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
3204 PrevTo = Del->getAggregateOperand();
3205 Del->eraseFromParent();
3206 }
3207 // Stop processing elements
3208 break;
3209 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003210 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00003211 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003212 if (To)
3213 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003214 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003215 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
3216 // the struct's elements had a value that was inserted directly. In the latter
3217 // case, perhaps we can't determine each of the subelements individually, but
3218 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00003219
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003220 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00003221 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003222
3223 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00003224 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003225
Vedant Kumard3196742018-02-28 19:08:52 +00003226 // Insert the value in the new (sub) aggregate
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003227 return InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
3228 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003229}
3230
3231// This helper takes a nested struct and extracts a part of it (which is again a
3232// struct) into a new value. For example, given the struct:
3233// { a, { b, { c, d }, e } }
3234// and the indices "1, 1" this returns
3235// { c, d }.
3236//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003237// It does this by inserting an insertvalue for each element in the resulting
3238// struct, as opposed to just inserting a single struct. This will only work if
3239// each of the elements of the substruct are known (ie, inserted into From by an
3240// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003241//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003242// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00003243static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00003244 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00003245 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00003246 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00003247 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00003248 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00003249 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003250 unsigned IdxSkip = Idxs.size();
3251
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003252 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003253}
3254
Vedant Kumard3196742018-02-28 19:08:52 +00003255/// Given an aggregate and a sequence of indices, see if the scalar value
3256/// indexed is already around as a register, for example if it was inserted
3257/// directly into the aggregate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003258///
3259/// If InsertBefore is not null, this function will duplicate (modified)
3260/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00003261Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
3262 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003263 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003264 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00003265 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003266 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003267 // We have indices, so V should have an indexable type.
3268 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
3269 "Not looking at a struct or array?");
3270 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
3271 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00003272
Chris Lattner67058832012-01-25 06:48:06 +00003273 if (Constant *C = dyn_cast<Constant>(V)) {
3274 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00003275 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00003276 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
3277 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003278
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003279 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003280 // Loop the indices for the insertvalue instruction in parallel with the
3281 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00003282 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003283 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
3284 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00003285 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003286 // We can't handle this without inserting insertvalues
3287 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00003288 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003289
3290 // The requested index identifies a part of a nested aggregate. Handle
3291 // this specially. For example,
3292 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
3293 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
3294 // %C = extractvalue {i32, { i32, i32 } } %B, 1
3295 // This can be changed into
3296 // %A = insertvalue {i32, i32 } undef, i32 10, 0
3297 // %C = insertvalue {i32, i32 } %A, i32 11, 1
3298 // which allows the unused 0,0 element from the nested struct to be
3299 // removed.
3300 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
3301 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00003302 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003303
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003304 // This insert value inserts something else than what we are looking for.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003305 // See if the (aggregate) value inserted into has the value we are
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003306 // looking for, then.
3307 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00003308 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003309 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003310 }
3311 // If we end up here, the indices of the insertvalue match with those
3312 // requested (though possibly only partially). Now we recursively look at
3313 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00003314 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00003315 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003316 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003317 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003318
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003319 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003320 // If we're extracting a value from an aggregate that was extracted from
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003321 // something else, we can extract from that something else directly instead.
3322 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00003323
3324 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00003325 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003326 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00003327 SmallVector<unsigned, 5> Idxs;
3328 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003329 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00003330 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00003331
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003332 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00003333 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003334
Craig Topper1bef2c82012-12-22 19:15:35 +00003335 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003336 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00003337
Jay Foad57aa6362011-07-13 10:26:04 +00003338 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003339 }
3340 // Otherwise, we don't know (such as, extracting from a function return value
3341 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00003342 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003343}
Evan Chengda3db112008-06-30 07:31:25 +00003344
Sanjay Patelaee84212014-11-04 16:27:42 +00003345/// Analyze the specified pointer to see if it can be expressed as a base
3346/// pointer plus a constant offset. Return the base and offset to the caller.
Chris Lattnere28618d2010-11-30 22:25:26 +00003347Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003348 const DataLayout &DL) {
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003349 unsigned BitWidth = DL.getIndexTypeSizeInBits(Ptr->getType());
Nuno Lopes368c4d02012-12-31 20:48:35 +00003350 APInt ByteOffset(BitWidth, 0);
Chandler Carruth76641272016-01-04 07:23:12 +00003351
3352 // We walk up the defs but use a visited set to handle unreachable code. In
3353 // that case, we stop after accumulating the cycle once (not that it
3354 // matters).
3355 SmallPtrSet<Value *, 16> Visited;
3356 while (Visited.insert(Ptr).second) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003357 if (Ptr->getType()->isVectorTy())
3358 break;
Craig Topper1bef2c82012-12-22 19:15:35 +00003359
Nuno Lopes368c4d02012-12-31 20:48:35 +00003360 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Tom Stellard17eb3412016-10-07 14:23:29 +00003361 // If one of the values we have visited is an addrspacecast, then
3362 // the pointer type of this GEP may be different from the type
3363 // of the Ptr parameter which was passed to this function. This
3364 // means when we construct GEPOffset, we need to use the size
3365 // of GEP's pointer type rather than the size of the original
3366 // pointer type.
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003367 APInt GEPOffset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003368 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
3369 break;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00003370
Tom Stellard17eb3412016-10-07 14:23:29 +00003371 ByteOffset += GEPOffset.getSExtValue();
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00003372
Nuno Lopes368c4d02012-12-31 20:48:35 +00003373 Ptr = GEP->getPointerOperand();
Tom Stellard17eb3412016-10-07 14:23:29 +00003374 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
3375 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003376 Ptr = cast<Operator>(Ptr)->getOperand(0);
3377 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003378 if (GA->isInterposable())
Nuno Lopes368c4d02012-12-31 20:48:35 +00003379 break;
3380 Ptr = GA->getAliasee();
Chris Lattnere28618d2010-11-30 22:25:26 +00003381 } else {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003382 break;
Chris Lattnere28618d2010-11-30 22:25:26 +00003383 }
3384 }
Nuno Lopes368c4d02012-12-31 20:48:35 +00003385 Offset = ByteOffset.getSExtValue();
3386 return Ptr;
Chris Lattnere28618d2010-11-30 22:25:26 +00003387}
3388
Matthias Braun50ec0b52017-05-19 22:37:09 +00003389bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP,
3390 unsigned CharSize) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003391 // Make sure the GEP has exactly three arguments.
3392 if (GEP->getNumOperands() != 3)
3393 return false;
3394
Matthias Braun50ec0b52017-05-19 22:37:09 +00003395 // Make sure the index-ee is a pointer to array of \p CharSize integers.
3396 // CharSize.
David L Kreitzer752c1442016-04-13 14:31:06 +00003397 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
Matthias Braun50ec0b52017-05-19 22:37:09 +00003398 if (!AT || !AT->getElementType()->isIntegerTy(CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +00003399 return false;
3400
3401 // Check to make sure that the first operand of the GEP is an integer and
3402 // has value 0 so that we are sure we're indexing into the initializer.
3403 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
3404 if (!FirstIdx || !FirstIdx->isZero())
3405 return false;
3406
3407 return true;
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003408}
Chris Lattnere28618d2010-11-30 22:25:26 +00003409
Matthias Braun50ec0b52017-05-19 22:37:09 +00003410bool llvm::getConstantDataArrayInfo(const Value *V,
3411 ConstantDataArraySlice &Slice,
3412 unsigned ElementSize, uint64_t Offset) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003413 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00003414
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003415 // Look through bitcast instructions and geps.
3416 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00003417
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00003418 // If the value is a GEP instruction or constant expression, treat it as an
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003419 // offset.
3420 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003421 // The GEP operator should be based on a pointer to string constant, and is
3422 // indexing into the string constant.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003423 if (!isGEPBasedOnPointerToString(GEP, ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003424 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003425
Evan Chengda3db112008-06-30 07:31:25 +00003426 // If the second index isn't a ConstantInt, then this is a variable index
3427 // into the array. If this occurs, we can't say anything meaningful about
3428 // the string.
3429 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00003430 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00003431 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003432 else
3433 return false;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003434 return getConstantDataArrayInfo(GEP->getOperand(0), Slice, ElementSize,
3435 StartIdx + Offset);
Evan Chengda3db112008-06-30 07:31:25 +00003436 }
Nick Lewycky46209882011-10-20 00:34:35 +00003437
Evan Chengda3db112008-06-30 07:31:25 +00003438 // The GEP instruction, constant or instruction, must reference a global
3439 // variable that is a constant and is initialized. The referenced constant
3440 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003441 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00003442 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003443 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003444
Matthias Braun50ec0b52017-05-19 22:37:09 +00003445 const ConstantDataArray *Array;
3446 ArrayType *ArrayTy;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003447 if (GV->getInitializer()->isNullValue()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003448 Type *GVTy = GV->getValueType();
3449 if ( (ArrayTy = dyn_cast<ArrayType>(GVTy)) ) {
Sanjay Patel2ad88f82017-06-12 22:34:37 +00003450 // A zeroinitializer for the array; there is no ConstantDataArray.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003451 Array = nullptr;
3452 } else {
3453 const DataLayout &DL = GV->getParent()->getDataLayout();
3454 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy);
3455 uint64_t Length = SizeInBytes / (ElementSize / 8);
3456 if (Length <= Offset)
3457 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003458
Matthias Braun50ec0b52017-05-19 22:37:09 +00003459 Slice.Array = nullptr;
3460 Slice.Offset = 0;
3461 Slice.Length = Length - Offset;
3462 return true;
3463 }
3464 } else {
3465 // This must be a ConstantDataArray.
3466 Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
3467 if (!Array)
3468 return false;
3469 ArrayTy = Array->getType();
3470 }
3471 if (!ArrayTy->getElementType()->isIntegerTy(ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003472 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003473
Matthias Braun50ec0b52017-05-19 22:37:09 +00003474 uint64_t NumElts = ArrayTy->getArrayNumElements();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003475 if (Offset > NumElts)
3476 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003477
Matthias Braun50ec0b52017-05-19 22:37:09 +00003478 Slice.Array = Array;
3479 Slice.Offset = Offset;
3480 Slice.Length = NumElts - Offset;
3481 return true;
3482}
3483
3484/// This function computes the length of a null-terminated C string pointed to
3485/// by V. If successful, it returns true and returns the string in Str.
3486/// If unsuccessful, it returns false.
3487bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
3488 uint64_t Offset, bool TrimAtNul) {
3489 ConstantDataArraySlice Slice;
3490 if (!getConstantDataArrayInfo(V, Slice, 8, Offset))
3491 return false;
3492
3493 if (Slice.Array == nullptr) {
3494 if (TrimAtNul) {
3495 Str = StringRef();
3496 return true;
3497 }
3498 if (Slice.Length == 1) {
3499 Str = StringRef("", 1);
3500 return true;
3501 }
Sanjay Patelfef83e82017-06-09 14:21:18 +00003502 // We cannot instantiate a StringRef as we do not have an appropriate string
Matthias Braun50ec0b52017-05-19 22:37:09 +00003503 // of 0s at hand.
3504 return false;
3505 }
3506
3507 // Start out with the entire array in the StringRef.
3508 Str = Slice.Array->getAsString();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003509 // Skip over 'offset' bytes.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003510 Str = Str.substr(Slice.Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00003511
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003512 if (TrimAtNul) {
3513 // Trim off the \0 and anything after it. If the array is not nul
3514 // terminated, we just return the whole end of string. The client may know
3515 // some other way that the string is length-bound.
3516 Str = Str.substr(0, Str.find('\0'));
3517 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003518 return true;
Evan Chengda3db112008-06-30 07:31:25 +00003519}
Eric Christopher4899cbc2010-03-05 06:58:57 +00003520
3521// These next two are very similar to the above, but also look through PHI
3522// nodes.
3523// TODO: See if we can integrate these two together.
3524
Sanjay Patelaee84212014-11-04 16:27:42 +00003525/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003526/// the specified pointer, return 'len+1'. If we can't, return 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00003527static uint64_t GetStringLengthH(const Value *V,
Matthias Braun50ec0b52017-05-19 22:37:09 +00003528 SmallPtrSetImpl<const PHINode*> &PHIs,
3529 unsigned CharSize) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003530 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003531 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00003532
3533 // If this is a PHI node, there are two cases: either we have already seen it
3534 // or we haven't.
Pete Cooper35b00d52016-08-13 01:05:32 +00003535 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
David Blaikie70573dc2014-11-19 07:49:26 +00003536 if (!PHIs.insert(PN).second)
Eric Christopher4899cbc2010-03-05 06:58:57 +00003537 return ~0ULL; // already in the set.
3538
3539 // If it was new, see if all the input strings are the same length.
3540 uint64_t LenSoFar = ~0ULL;
Pete Cooper833f34d2015-05-12 20:05:31 +00003541 for (Value *IncValue : PN->incoming_values()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003542 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003543 if (Len == 0) return 0; // Unknown length -> unknown.
3544
3545 if (Len == ~0ULL) continue;
3546
3547 if (Len != LenSoFar && LenSoFar != ~0ULL)
3548 return 0; // Disagree -> unknown.
3549 LenSoFar = Len;
3550 }
3551
3552 // Success, all agree.
3553 return LenSoFar;
3554 }
3555
3556 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
Pete Cooper35b00d52016-08-13 01:05:32 +00003557 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003558 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003559 if (Len1 == 0) return 0;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003560 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003561 if (Len2 == 0) return 0;
3562 if (Len1 == ~0ULL) return Len2;
3563 if (Len2 == ~0ULL) return Len1;
3564 if (Len1 != Len2) return 0;
3565 return Len1;
3566 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003567
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003568 // Otherwise, see if we can read the string.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003569 ConstantDataArraySlice Slice;
3570 if (!getConstantDataArrayInfo(V, Slice, CharSize))
Eric Christopher4899cbc2010-03-05 06:58:57 +00003571 return 0;
3572
Matthias Braun50ec0b52017-05-19 22:37:09 +00003573 if (Slice.Array == nullptr)
3574 return 1;
3575
3576 // Search for nul characters
3577 unsigned NullIndex = 0;
3578 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
3579 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
3580 break;
3581 }
3582
3583 return NullIndex + 1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003584}
3585
Sanjay Patelaee84212014-11-04 16:27:42 +00003586/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003587/// the specified pointer, return 'len+1'. If we can't, return 0.
David Bolvansky1f343fa2018-05-22 20:27:36 +00003588uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
David Bolvansky41f4b642018-05-22 15:41:23 +00003589 if (!V->getType()->isPointerTy())
3590 return 0;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003591
Pete Cooper35b00d52016-08-13 01:05:32 +00003592 SmallPtrSet<const PHINode*, 32> PHIs;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003593 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003594 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
3595 // an empty string as a length.
3596 return Len == ~0ULL ? 1 : Len;
3597}
Dan Gohmana4fcd242010-12-15 20:02:24 +00003598
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003599const Value *llvm::getArgumentAliasingToReturnedPointer(ImmutableCallSite CS) {
3600 assert(CS &&
3601 "getArgumentAliasingToReturnedPointer only works on nonnull CallSite");
3602 if (const Value *RV = CS.getReturnedArgOperand())
3603 return RV;
3604 // This can be used only as a aliasing property.
3605 if (isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(CS))
3606 return CS.getArgOperand(0);
3607 return nullptr;
3608}
3609
3610bool llvm::isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
Piotr Padlewski5b3db452018-07-02 04:49:30 +00003611 ImmutableCallSite CS) {
3612 return CS.getIntrinsicID() == Intrinsic::launder_invariant_group ||
3613 CS.getIntrinsicID() == Intrinsic::strip_invariant_group;
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003614}
3615
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003616/// \p PN defines a loop-variant pointer to an object. Check if the
Adam Nemete2b885c2015-04-23 20:09:20 +00003617/// previous iteration of the loop was referring to the same object as \p PN.
Pete Cooper35b00d52016-08-13 01:05:32 +00003618static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
3619 const LoopInfo *LI) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003620 // Find the loop-defined value.
3621 Loop *L = LI->getLoopFor(PN->getParent());
3622 if (PN->getNumIncomingValues() != 2)
3623 return true;
3624
3625 // Find the value from previous iteration.
3626 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3627 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3628 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3629 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3630 return true;
3631
3632 // If a new pointer is loaded in the loop, the pointer references a different
3633 // object in every iteration. E.g.:
3634 // for (i)
3635 // int *p = a[i];
3636 // ...
3637 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3638 if (!L->isLoopInvariant(Load->getPointerOperand()))
3639 return false;
3640 return true;
3641}
3642
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003643Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3644 unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003645 if (!V->getType()->isPointerTy())
3646 return V;
3647 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3648 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3649 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00003650 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3651 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003652 V = cast<Operator>(V)->getOperand(0);
3653 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003654 if (GA->isInterposable())
Dan Gohmana4fcd242010-12-15 20:02:24 +00003655 return V;
3656 V = GA->getAliasee();
Craig Topper85482412017-04-12 22:29:23 +00003657 } else if (isa<AllocaInst>(V)) {
3658 // An alloca can't be further simplified.
3659 return V;
Dan Gohmana4fcd242010-12-15 20:02:24 +00003660 } else {
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003661 if (auto CS = CallSite(V)) {
Piotr Padlewski5b3db452018-07-02 04:49:30 +00003662 // CaptureTracking can know about special capturing properties of some
3663 // intrinsics like launder.invariant.group, that can't be expressed with
3664 // the attributes, but have properties like returning aliasing pointer.
3665 // Because some analysis may assume that nocaptured pointer is not
3666 // returned from some special intrinsic (because function would have to
3667 // be marked with returns attribute), it is crucial to use this function
3668 // because it should be in sync with CaptureTracking. Not using it may
3669 // cause weird miscompilations where 2 aliasing pointers are assumed to
3670 // noalias.
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003671 if (auto *RP = getArgumentAliasingToReturnedPointer(CS)) {
3672 V = RP;
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003673 continue;
3674 }
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003675 }
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003676
Dan Gohman05b18f12010-12-15 20:49:55 +00003677 // See if InstructionSimplify knows any relevant tricks.
3678 if (Instruction *I = dyn_cast<Instruction>(V))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003679 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00003680 if (Value *Simplified = SimplifyInstruction(I, {DL, I})) {
Dan Gohman05b18f12010-12-15 20:49:55 +00003681 V = Simplified;
3682 continue;
3683 }
3684
Dan Gohmana4fcd242010-12-15 20:02:24 +00003685 return V;
3686 }
3687 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3688 }
3689 return V;
3690}
Nick Lewycky3e334a42011-06-27 04:20:45 +00003691
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003692void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
Adam Nemete2b885c2015-04-23 20:09:20 +00003693 const DataLayout &DL, LoopInfo *LI,
3694 unsigned MaxLookup) {
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003695 SmallPtrSet<Value *, 4> Visited;
3696 SmallVector<Value *, 4> Worklist;
3697 Worklist.push_back(V);
3698 do {
3699 Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003700 P = GetUnderlyingObject(P, DL, MaxLookup);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003701
David Blaikie70573dc2014-11-19 07:49:26 +00003702 if (!Visited.insert(P).second)
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003703 continue;
3704
3705 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
3706 Worklist.push_back(SI->getTrueValue());
3707 Worklist.push_back(SI->getFalseValue());
3708 continue;
3709 }
3710
3711 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003712 // If this PHI changes the underlying object in every iteration of the
3713 // loop, don't look through it. Consider:
3714 // int **A;
3715 // for (i) {
3716 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
3717 // Curr = A[i];
3718 // *Prev, *Curr;
3719 //
3720 // Prev is tracking Curr one iteration behind so they refer to different
3721 // underlying objects.
3722 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3723 isSameUnderlyingObjectInLoop(PN, LI))
Pete Cooper833f34d2015-05-12 20:05:31 +00003724 for (Value *IncValue : PN->incoming_values())
3725 Worklist.push_back(IncValue);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003726 continue;
3727 }
3728
3729 Objects.push_back(P);
3730 } while (!Worklist.empty());
3731}
3732
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003733/// This is the function that does the work of looking through basic
3734/// ptrtoint+arithmetic+inttoptr sequences.
3735static const Value *getUnderlyingObjectFromInt(const Value *V) {
3736 do {
3737 if (const Operator *U = dyn_cast<Operator>(V)) {
3738 // If we find a ptrtoint, we can transfer control back to the
3739 // regular getUnderlyingObjectFromInt.
3740 if (U->getOpcode() == Instruction::PtrToInt)
3741 return U->getOperand(0);
3742 // If we find an add of a constant, a multiplied value, or a phi, it's
3743 // likely that the other operand will lead us to the base
3744 // object. We don't have to worry about the case where the
3745 // object address is somehow being computed by the multiply,
3746 // because our callers only care when the result is an
3747 // identifiable object.
3748 if (U->getOpcode() != Instruction::Add ||
3749 (!isa<ConstantInt>(U->getOperand(1)) &&
3750 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
3751 !isa<PHINode>(U->getOperand(1))))
3752 return V;
3753 V = U->getOperand(0);
3754 } else {
3755 return V;
3756 }
3757 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
3758 } while (true);
3759}
3760
3761/// This is a wrapper around GetUnderlyingObjects and adds support for basic
3762/// ptrtoint+arithmetic+inttoptr sequences.
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003763/// It returns false if unidentified object is found in GetUnderlyingObjects.
3764bool llvm::getUnderlyingObjectsForCodeGen(const Value *V,
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003765 SmallVectorImpl<Value *> &Objects,
3766 const DataLayout &DL) {
3767 SmallPtrSet<const Value *, 16> Visited;
3768 SmallVector<const Value *, 4> Working(1, V);
3769 do {
3770 V = Working.pop_back_val();
3771
3772 SmallVector<Value *, 4> Objs;
3773 GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
3774
3775 for (Value *V : Objs) {
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003776 if (!Visited.insert(V).second)
3777 continue;
3778 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
3779 const Value *O =
3780 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
3781 if (O->getType()->isPointerTy()) {
3782 Working.push_back(O);
3783 continue;
3784 }
3785 }
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003786 // If GetUnderlyingObjects fails to find an identifiable object,
3787 // getUnderlyingObjectsForCodeGen also fails for safety.
3788 if (!isIdentifiedObject(V)) {
3789 Objects.clear();
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003790 return false;
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003791 }
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003792 Objects.push_back(const_cast<Value *>(V));
3793 }
3794 } while (!Working.empty());
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003795 return true;
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003796}
3797
Sanjay Patelaee84212014-11-04 16:27:42 +00003798/// Return true if the only users of this pointer are lifetime markers.
Nick Lewycky3e334a42011-06-27 04:20:45 +00003799bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003800 for (const User *U : V->users()) {
3801 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00003802 if (!II) return false;
3803
3804 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
3805 II->getIntrinsicID() != Intrinsic::lifetime_end)
3806 return false;
3807 }
3808 return true;
3809}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003810
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003811bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3812 const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003813 const DominatorTree *DT) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00003814 const Operator *Inst = dyn_cast<Operator>(V);
3815 if (!Inst)
3816 return false;
3817
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003818 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3819 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3820 if (C->canTrap())
3821 return false;
3822
3823 switch (Inst->getOpcode()) {
3824 default:
3825 return true;
3826 case Instruction::UDiv:
David Majnemerf20d7c42014-11-04 23:49:08 +00003827 case Instruction::URem: {
3828 // x / y is undefined if y == 0.
3829 const APInt *V;
3830 if (match(Inst->getOperand(1), m_APInt(V)))
3831 return *V != 0;
3832 return false;
3833 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003834 case Instruction::SDiv:
3835 case Instruction::SRem: {
David Majnemerf20d7c42014-11-04 23:49:08 +00003836 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
David Majnemer8a6578a2015-02-01 19:10:19 +00003837 const APInt *Numerator, *Denominator;
3838 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3839 return false;
3840 // We cannot hoist this division if the denominator is 0.
3841 if (*Denominator == 0)
3842 return false;
3843 // It's safe to hoist if the denominator is not 0 or -1.
3844 if (*Denominator != -1)
3845 return true;
3846 // At this point we know that the denominator is -1. It is safe to hoist as
3847 // long we know that the numerator is not INT_MIN.
3848 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3849 return !Numerator->isMinSignedValue();
3850 // The numerator *might* be MinSignedValue.
David Majnemerf20d7c42014-11-04 23:49:08 +00003851 return false;
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003852 }
3853 case Instruction::Load: {
3854 const LoadInst *LI = cast<LoadInst>(Inst);
Kostya Serebryany0b458282013-11-21 07:29:28 +00003855 if (!LI->isUnordered() ||
3856 // Speculative load may create a race that did not exist in the source.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003857 LI->getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
Kostya Serebryany5cb86d52015-10-14 00:21:05 +00003858 // Speculative load may load data from dirty regions.
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00003859 LI->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3860 LI->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003861 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003862 const DataLayout &DL = LI->getModule()->getDataLayout();
Sean Silva45835e72016-07-02 23:47:27 +00003863 return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
3864 LI->getAlignment(), DL, CtxI, DT);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003865 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003866 case Instruction::Call: {
Matt Arsenaultcf5e7fe2017-04-28 21:13:09 +00003867 auto *CI = cast<const CallInst>(Inst);
3868 const Function *Callee = CI->getCalledFunction();
David Majnemer0a92f862015-08-28 21:13:39 +00003869
Matt Arsenault6a288c12017-05-03 02:26:10 +00003870 // The called function could have undefined behavior or side-effects, even
3871 // if marked readnone nounwind.
3872 return Callee && Callee->isSpeculatable();
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003873 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003874 case Instruction::VAArg:
3875 case Instruction::Alloca:
3876 case Instruction::Invoke:
3877 case Instruction::PHI:
3878 case Instruction::Store:
3879 case Instruction::Ret:
3880 case Instruction::Br:
3881 case Instruction::IndirectBr:
3882 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003883 case Instruction::Unreachable:
3884 case Instruction::Fence:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003885 case Instruction::AtomicRMW:
3886 case Instruction::AtomicCmpXchg:
David Majnemer654e1302015-07-31 17:58:14 +00003887 case Instruction::LandingPad:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003888 case Instruction::Resume:
David Majnemer8a1c45d2015-12-12 05:38:55 +00003889 case Instruction::CatchSwitch:
David Majnemer654e1302015-07-31 17:58:14 +00003890 case Instruction::CatchPad:
David Majnemer654e1302015-07-31 17:58:14 +00003891 case Instruction::CatchRet:
3892 case Instruction::CleanupPad:
3893 case Instruction::CleanupRet:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003894 return false; // Misc instructions which have effects
3895 }
3896}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003897
Quentin Colombet6443cce2015-08-06 18:44:34 +00003898bool llvm::mayBeMemoryDependent(const Instruction &I) {
3899 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3900}
3901
Florian Hahn19f9e322018-08-17 14:39:04 +00003902OverflowResult llvm::computeOverflowForUnsignedMul(
3903 const Value *LHS, const Value *RHS, const DataLayout &DL,
3904 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
3905 bool UseInstrInfo) {
David Majnemer491331a2015-01-02 07:29:43 +00003906 // Multiplying n * m significant bits yields a result of n + m significant
3907 // bits. If the total number of significant bits does not exceed the
3908 // result bit width (minus 1), there is no overflow.
3909 // This means if we have enough leading zero bits in the operands
3910 // we can guarantee that the result does not overflow.
3911 // Ref: "Hacker's Delight" by Henry Warren
3912 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00003913 KnownBits LHSKnown(BitWidth);
3914 KnownBits RHSKnown(BitWidth);
Florian Hahn19f9e322018-08-17 14:39:04 +00003915 computeKnownBits(LHS, LHSKnown, DL, /*Depth=*/0, AC, CxtI, DT, nullptr,
3916 UseInstrInfo);
3917 computeKnownBits(RHS, RHSKnown, DL, /*Depth=*/0, AC, CxtI, DT, nullptr,
3918 UseInstrInfo);
David Majnemer491331a2015-01-02 07:29:43 +00003919 // Note that underestimating the number of zero bits gives a more
3920 // conservative answer.
Craig Topper8df66c62017-05-12 17:20:30 +00003921 unsigned ZeroBits = LHSKnown.countMinLeadingZeros() +
3922 RHSKnown.countMinLeadingZeros();
David Majnemer491331a2015-01-02 07:29:43 +00003923 // First handle the easy case: if we have enough zero bits there's
3924 // definitely no overflow.
3925 if (ZeroBits >= BitWidth)
3926 return OverflowResult::NeverOverflows;
3927
3928 // Get the largest possible values for each operand.
Craig Topperb45eabc2017-04-26 16:39:58 +00003929 APInt LHSMax = ~LHSKnown.Zero;
3930 APInt RHSMax = ~RHSKnown.Zero;
David Majnemer491331a2015-01-02 07:29:43 +00003931
3932 // We know the multiply operation doesn't overflow if the maximum values for
3933 // each operand will not overflow after we multiply them together.
David Majnemerc8a576b2015-01-02 07:29:47 +00003934 bool MaxOverflow;
Craig Topper9b71a402017-04-19 21:09:45 +00003935 (void)LHSMax.umul_ov(RHSMax, MaxOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003936 if (!MaxOverflow)
3937 return OverflowResult::NeverOverflows;
David Majnemer491331a2015-01-02 07:29:43 +00003938
David Majnemerc8a576b2015-01-02 07:29:47 +00003939 // We know it always overflows if multiplying the smallest possible values for
3940 // the operands also results in overflow.
3941 bool MinOverflow;
Craig Topperb45eabc2017-04-26 16:39:58 +00003942 (void)LHSKnown.One.umul_ov(RHSKnown.One, MinOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003943 if (MinOverflow)
3944 return OverflowResult::AlwaysOverflows;
3945
3946 return OverflowResult::MayOverflow;
David Majnemer491331a2015-01-02 07:29:43 +00003947}
David Majnemer5310c1e2015-01-07 00:39:50 +00003948
Florian Hahn19f9e322018-08-17 14:39:04 +00003949OverflowResult
3950llvm::computeOverflowForSignedMul(const Value *LHS, const Value *RHS,
3951 const DataLayout &DL, AssumptionCache *AC,
3952 const Instruction *CxtI,
3953 const DominatorTree *DT, bool UseInstrInfo) {
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00003954 // Multiplying n * m significant bits yields a result of n + m significant
3955 // bits. If the total number of significant bits does not exceed the
3956 // result bit width (minus 1), there is no overflow.
3957 // This means if we have enough leading sign bits in the operands
3958 // we can guarantee that the result does not overflow.
3959 // Ref: "Hacker's Delight" by Henry Warren
3960 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
3961
3962 // Note that underestimating the number of sign bits gives a more
3963 // conservative answer.
3964 unsigned SignBits = ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) +
3965 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT);
3966
3967 // First handle the easy case: if we have enough sign bits there's
3968 // definitely no overflow.
3969 if (SignBits > BitWidth + 1)
3970 return OverflowResult::NeverOverflows;
3971
3972 // There are two ambiguous cases where there can be no overflow:
3973 // SignBits == BitWidth + 1 and
3974 // SignBits == BitWidth
3975 // The second case is difficult to check, therefore we only handle the
3976 // first case.
3977 if (SignBits == BitWidth + 1) {
3978 // It overflows only when both arguments are negative and the true
3979 // product is exactly the minimum negative number.
3980 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
3981 // For simplicity we just check if at least one side is not negative.
Florian Hahn19f9e322018-08-17 14:39:04 +00003982 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
3983 nullptr, UseInstrInfo);
3984 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
3985 nullptr, UseInstrInfo);
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00003986 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
3987 return OverflowResult::NeverOverflows;
3988 }
3989 return OverflowResult::MayOverflow;
3990}
3991
Florian Hahn19f9e322018-08-17 14:39:04 +00003992OverflowResult llvm::computeOverflowForUnsignedAdd(
3993 const Value *LHS, const Value *RHS, const DataLayout &DL,
3994 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
3995 bool UseInstrInfo) {
3996 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
3997 nullptr, UseInstrInfo);
Craig Topper6e11a052017-05-08 16:22:48 +00003998 if (LHSKnown.isNonNegative() || LHSKnown.isNegative()) {
Florian Hahn19f9e322018-08-17 14:39:04 +00003999 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
4000 nullptr, UseInstrInfo);
David Majnemer5310c1e2015-01-07 00:39:50 +00004001
Craig Topper6e11a052017-05-08 16:22:48 +00004002 if (LHSKnown.isNegative() && RHSKnown.isNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00004003 // The sign bit is set in both cases: this MUST overflow.
David Majnemer5310c1e2015-01-07 00:39:50 +00004004 return OverflowResult::AlwaysOverflows;
4005 }
4006
Craig Topper6e11a052017-05-08 16:22:48 +00004007 if (LHSKnown.isNonNegative() && RHSKnown.isNonNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00004008 // The sign bit is clear in both cases: this CANNOT overflow.
David Majnemer5310c1e2015-01-07 00:39:50 +00004009 return OverflowResult::NeverOverflows;
4010 }
4011 }
4012
4013 return OverflowResult::MayOverflow;
4014}
James Molloy71b91c22015-05-11 14:42:20 +00004015
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004016/// Return true if we can prove that adding the two values of the
Craig Topperbb973722017-05-15 02:44:08 +00004017/// knownbits will not overflow.
4018/// Otherwise return false.
4019static bool checkRippleForSignedAdd(const KnownBits &LHSKnown,
4020 const KnownBits &RHSKnown) {
4021 // Addition of two 2's complement numbers having opposite signs will never
4022 // overflow.
4023 if ((LHSKnown.isNegative() && RHSKnown.isNonNegative()) ||
4024 (LHSKnown.isNonNegative() && RHSKnown.isNegative()))
4025 return true;
4026
4027 // If either of the values is known to be non-negative, adding them can only
4028 // overflow if the second is also non-negative, so we can assume that.
Fangrui Songf78650a2018-07-30 19:41:25 +00004029 // Two non-negative numbers will only overflow if there is a carry to the
Craig Topperbb973722017-05-15 02:44:08 +00004030 // sign bit, so we can check if even when the values are as big as possible
4031 // there is no overflow to the sign bit.
4032 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative()) {
4033 APInt MaxLHS = ~LHSKnown.Zero;
4034 MaxLHS.clearSignBit();
4035 APInt MaxRHS = ~RHSKnown.Zero;
4036 MaxRHS.clearSignBit();
4037 APInt Result = std::move(MaxLHS) + std::move(MaxRHS);
4038 return Result.isSignBitClear();
4039 }
4040
4041 // If either of the values is known to be negative, adding them can only
4042 // overflow if the second is also negative, so we can assume that.
4043 // Two negative number will only overflow if there is no carry to the sign
4044 // bit, so we can check if even when the values are as small as possible
4045 // there is overflow to the sign bit.
4046 if (LHSKnown.isNegative() || RHSKnown.isNegative()) {
4047 APInt MinLHS = LHSKnown.One;
4048 MinLHS.clearSignBit();
4049 APInt MinRHS = RHSKnown.One;
4050 MinRHS.clearSignBit();
4051 APInt Result = std::move(MinLHS) + std::move(MinRHS);
4052 return Result.isSignBitSet();
4053 }
4054
4055 // If we reached here it means that we know nothing about the sign bits.
Fangrui Songf78650a2018-07-30 19:41:25 +00004056 // In this case we can't know if there will be an overflow, since by
Craig Topperbb973722017-05-15 02:44:08 +00004057 // changing the sign bits any two values can be made to overflow.
4058 return false;
4059}
4060
Pete Cooper35b00d52016-08-13 01:05:32 +00004061static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
4062 const Value *RHS,
4063 const AddOperator *Add,
4064 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004065 AssumptionCache *AC,
Pete Cooper35b00d52016-08-13 01:05:32 +00004066 const Instruction *CxtI,
4067 const DominatorTree *DT) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00004068 if (Add && Add->hasNoSignedWrap()) {
4069 return OverflowResult::NeverOverflows;
4070 }
4071
Craig Topperbb973722017-05-15 02:44:08 +00004072 // If LHS and RHS each have at least two sign bits, the addition will look
4073 // like
4074 //
4075 // XX..... +
4076 // YY.....
4077 //
4078 // If the carry into the most significant position is 0, X and Y can't both
4079 // be 1 and therefore the carry out of the addition is also 0.
4080 //
4081 // If the carry into the most significant position is 1, X and Y can't both
4082 // be 0 and therefore the carry out of the addition is also 1.
4083 //
4084 // Since the carry into the most significant position is always equal to
4085 // the carry out of the addition, there is no signed overflow.
4086 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4087 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4088 return OverflowResult::NeverOverflows;
4089
Craig Topper6e11a052017-05-08 16:22:48 +00004090 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
4091 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00004092
Craig Topperbb973722017-05-15 02:44:08 +00004093 if (checkRippleForSignedAdd(LHSKnown, RHSKnown))
Jingyue Wu10fcea52015-08-20 18:27:04 +00004094 return OverflowResult::NeverOverflows;
Jingyue Wu10fcea52015-08-20 18:27:04 +00004095
4096 // The remaining code needs Add to be available. Early returns if not so.
4097 if (!Add)
4098 return OverflowResult::MayOverflow;
4099
4100 // If the sign of Add is the same as at least one of the operands, this add
4101 // CANNOT overflow. This is particularly useful when the sum is
4102 // @llvm.assume'ed non-negative rather than proved so from analyzing its
4103 // operands.
4104 bool LHSOrRHSKnownNonNegative =
Craig Topper6e11a052017-05-08 16:22:48 +00004105 (LHSKnown.isNonNegative() || RHSKnown.isNonNegative());
Fangrui Songf78650a2018-07-30 19:41:25 +00004106 bool LHSOrRHSKnownNegative =
Craig Topperbb973722017-05-15 02:44:08 +00004107 (LHSKnown.isNegative() || RHSKnown.isNegative());
Jingyue Wu10fcea52015-08-20 18:27:04 +00004108 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
Craig Topper6e11a052017-05-08 16:22:48 +00004109 KnownBits AddKnown = computeKnownBits(Add, DL, /*Depth=*/0, AC, CxtI, DT);
4110 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
4111 (AddKnown.isNegative() && LHSOrRHSKnownNegative)) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00004112 return OverflowResult::NeverOverflows;
4113 }
4114 }
4115
4116 return OverflowResult::MayOverflow;
4117}
4118
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004119OverflowResult llvm::computeOverflowForUnsignedSub(const Value *LHS,
4120 const Value *RHS,
4121 const DataLayout &DL,
4122 AssumptionCache *AC,
4123 const Instruction *CxtI,
4124 const DominatorTree *DT) {
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004125 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
Nikita Popovcf596a82018-11-28 16:37:04 +00004126 if (LHSKnown.isNonNegative() || LHSKnown.isNegative()) {
4127 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
4128
4129 // If the LHS is negative and the RHS is non-negative, no unsigned wrap.
4130 if (LHSKnown.isNegative() && RHSKnown.isNonNegative())
4131 return OverflowResult::NeverOverflows;
4132
4133 // If the LHS is non-negative and the RHS negative, we always wrap.
4134 if (LHSKnown.isNonNegative() && RHSKnown.isNegative())
4135 return OverflowResult::AlwaysOverflows;
4136 }
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004137
4138 return OverflowResult::MayOverflow;
4139}
4140
4141OverflowResult llvm::computeOverflowForSignedSub(const Value *LHS,
4142 const Value *RHS,
4143 const DataLayout &DL,
4144 AssumptionCache *AC,
4145 const Instruction *CxtI,
4146 const DominatorTree *DT) {
4147 // If LHS and RHS each have at least two sign bits, the subtraction
4148 // cannot overflow.
4149 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4150 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4151 return OverflowResult::NeverOverflows;
4152
4153 KnownBits LHSKnown = computeKnownBits(LHS, DL, 0, AC, CxtI, DT);
4154
4155 KnownBits RHSKnown = computeKnownBits(RHS, DL, 0, AC, CxtI, DT);
4156
4157 // Subtraction of two 2's complement numbers having identical signs will
4158 // never overflow.
4159 if ((LHSKnown.isNegative() && RHSKnown.isNegative()) ||
4160 (LHSKnown.isNonNegative() && RHSKnown.isNonNegative()))
4161 return OverflowResult::NeverOverflows;
4162
4163 // TODO: implement logic similar to checkRippleForAdd
4164 return OverflowResult::MayOverflow;
4165}
4166
Pete Cooper35b00d52016-08-13 01:05:32 +00004167bool llvm::isOverflowIntrinsicNoWrap(const IntrinsicInst *II,
4168 const DominatorTree &DT) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004169#ifndef NDEBUG
4170 auto IID = II->getIntrinsicID();
4171 assert((IID == Intrinsic::sadd_with_overflow ||
4172 IID == Intrinsic::uadd_with_overflow ||
4173 IID == Intrinsic::ssub_with_overflow ||
4174 IID == Intrinsic::usub_with_overflow ||
4175 IID == Intrinsic::smul_with_overflow ||
4176 IID == Intrinsic::umul_with_overflow) &&
4177 "Not an overflow intrinsic!");
4178#endif
4179
Pete Cooper35b00d52016-08-13 01:05:32 +00004180 SmallVector<const BranchInst *, 2> GuardingBranches;
4181 SmallVector<const ExtractValueInst *, 2> Results;
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004182
Pete Cooper35b00d52016-08-13 01:05:32 +00004183 for (const User *U : II->users()) {
4184 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004185 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
4186
4187 if (EVI->getIndices()[0] == 0)
4188 Results.push_back(EVI);
4189 else {
4190 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
4191
Pete Cooper35b00d52016-08-13 01:05:32 +00004192 for (const auto *U : EVI->users())
4193 if (const auto *B = dyn_cast<BranchInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004194 assert(B->isConditional() && "How else is it using an i1?");
4195 GuardingBranches.push_back(B);
4196 }
4197 }
4198 } else {
4199 // We are using the aggregate directly in a way we don't want to analyze
4200 // here (storing it to a global, say).
4201 return false;
4202 }
4203 }
4204
Pete Cooper35b00d52016-08-13 01:05:32 +00004205 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004206 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
4207 if (!NoWrapEdge.isSingleEdge())
4208 return false;
4209
4210 // Check if all users of the add are provably no-wrap.
Pete Cooper35b00d52016-08-13 01:05:32 +00004211 for (const auto *Result : Results) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004212 // If the extractvalue itself is not executed on overflow, the we don't
4213 // need to check each use separately, since domination is transitive.
4214 if (DT.dominates(NoWrapEdge, Result->getParent()))
4215 continue;
4216
4217 for (auto &RU : Result->uses())
4218 if (!DT.dominates(NoWrapEdge, RU))
4219 return false;
4220 }
4221
4222 return true;
4223 };
4224
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004225 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004226}
4227
4228
Pete Cooper35b00d52016-08-13 01:05:32 +00004229OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004230 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004231 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004232 const Instruction *CxtI,
4233 const DominatorTree *DT) {
4234 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004235 Add, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00004236}
4237
Pete Cooper35b00d52016-08-13 01:05:32 +00004238OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
4239 const Value *RHS,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004240 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004241 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004242 const Instruction *CxtI,
4243 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004244 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00004245}
4246
Jingyue Wu42f1d672015-07-28 18:22:40 +00004247bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004248 // A memory operation returns normally if it isn't volatile. A volatile
4249 // operation is allowed to trap.
4250 //
4251 // An atomic operation isn't guaranteed to return in a reasonable amount of
4252 // time because it's possible for another thread to interfere with it for an
4253 // arbitrary length of time, but programs aren't allowed to rely on that.
4254 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
4255 return !LI->isVolatile();
4256 if (const StoreInst *SI = dyn_cast<StoreInst>(I))
4257 return !SI->isVolatile();
4258 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
4259 return !CXI->isVolatile();
4260 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
4261 return !RMWI->isVolatile();
4262 if (const MemIntrinsic *MII = dyn_cast<MemIntrinsic>(I))
4263 return !MII->isVolatile();
Jingyue Wu42f1d672015-07-28 18:22:40 +00004264
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004265 // If there is no successor, then execution can't transfer to it.
4266 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I))
4267 return !CRI->unwindsToCaller();
4268 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I))
4269 return !CatchSwitch->unwindsToCaller();
4270 if (isa<ResumeInst>(I))
4271 return false;
4272 if (isa<ReturnInst>(I))
4273 return false;
Sebastian Pop4a4d2452017-03-08 01:54:50 +00004274 if (isa<UnreachableInst>(I))
4275 return false;
Sanjoy Das9a65cd22016-06-08 17:48:36 +00004276
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004277 // Calls can throw, or contain an infinite loop, or kill the process.
Sanjoy Das09455302016-12-31 22:12:31 +00004278 if (auto CS = ImmutableCallSite(I)) {
Sanjoy Das3bb2dbd2016-12-31 22:12:34 +00004279 // Call sites that throw have implicit non-local control flow.
4280 if (!CS.doesNotThrow())
4281 return false;
4282
4283 // Non-throwing call sites can loop infinitely, call exit/pthread_exit
4284 // etc. and thus not return. However, LLVM already assumes that
4285 //
4286 // - Thread exiting actions are modeled as writes to memory invisible to
4287 // the program.
4288 //
4289 // - Loops that don't have side effects (side effects are volatile/atomic
4290 // stores and IO) always terminate (see http://llvm.org/PR965).
4291 // Furthermore IO itself is also modeled as writes to memory invisible to
4292 // the program.
4293 //
4294 // We rely on those assumptions here, and use the memory effects of the call
4295 // target as a proxy for checking that it always returns.
4296
4297 // FIXME: This isn't aggressive enough; a call which only writes to a global
4298 // is guaranteed to return.
Sanjoy Dasd7e82062016-06-14 20:23:16 +00004299 return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory() ||
Dan Gohman2c74fe92017-11-08 21:59:51 +00004300 match(I, m_Intrinsic<Intrinsic::assume>()) ||
4301 match(I, m_Intrinsic<Intrinsic::sideeffect>());
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004302 }
4303
4304 // Other instructions return normally.
4305 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004306}
4307
Philip Reamesfbffd122018-03-08 21:25:30 +00004308bool llvm::isGuaranteedToTransferExecutionToSuccessor(const BasicBlock *BB) {
4309 // TODO: This is slightly consdervative for invoke instruction since exiting
4310 // via an exception *is* normal control for them.
4311 for (auto I = BB->begin(), E = BB->end(); I != E; ++I)
4312 if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
4313 return false;
4314 return true;
4315}
4316
Jingyue Wu42f1d672015-07-28 18:22:40 +00004317bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
4318 const Loop *L) {
4319 // The loop header is guaranteed to be executed for every iteration.
4320 //
4321 // FIXME: Relax this constraint to cover all basic blocks that are
4322 // guaranteed to be executed at every iteration.
4323 if (I->getParent() != L->getHeader()) return false;
4324
4325 for (const Instruction &LI : *L->getHeader()) {
4326 if (&LI == I) return true;
4327 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
4328 }
4329 llvm_unreachable("Instruction not contained in its own parent basic block.");
4330}
4331
4332bool llvm::propagatesFullPoison(const Instruction *I) {
4333 switch (I->getOpcode()) {
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004334 case Instruction::Add:
4335 case Instruction::Sub:
4336 case Instruction::Xor:
4337 case Instruction::Trunc:
4338 case Instruction::BitCast:
4339 case Instruction::AddrSpaceCast:
Sanjoy Das5cd6c5ca2017-02-22 06:52:32 +00004340 case Instruction::Mul:
4341 case Instruction::Shl:
4342 case Instruction::GetElementPtr:
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004343 // These operations all propagate poison unconditionally. Note that poison
4344 // is not any particular value, so xor or subtraction of poison with
4345 // itself still yields poison, not zero.
4346 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004347
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004348 case Instruction::AShr:
4349 case Instruction::SExt:
4350 // For these operations, one bit of the input is replicated across
4351 // multiple output bits. A replicated poison bit is still poison.
4352 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004353
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004354 case Instruction::ICmp:
4355 // Comparing poison with any value yields poison. This is why, for
4356 // instance, x s< (x +nsw 1) can be folded to true.
4357 return true;
Sanjoy Das70c2bbd2016-05-29 00:31:18 +00004358
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004359 default:
4360 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004361 }
4362}
4363
4364const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
4365 switch (I->getOpcode()) {
4366 case Instruction::Store:
4367 return cast<StoreInst>(I)->getPointerOperand();
4368
4369 case Instruction::Load:
4370 return cast<LoadInst>(I)->getPointerOperand();
4371
4372 case Instruction::AtomicCmpXchg:
4373 return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
4374
4375 case Instruction::AtomicRMW:
4376 return cast<AtomicRMWInst>(I)->getPointerOperand();
4377
4378 case Instruction::UDiv:
4379 case Instruction::SDiv:
4380 case Instruction::URem:
4381 case Instruction::SRem:
4382 return I->getOperand(1);
4383
4384 default:
4385 return nullptr;
4386 }
4387}
4388
Sanjoy Das08989c72017-04-30 19:41:19 +00004389bool llvm::programUndefinedIfFullPoison(const Instruction *PoisonI) {
Jingyue Wu42f1d672015-07-28 18:22:40 +00004390 // We currently only look for uses of poison values within the same basic
4391 // block, as that makes it easier to guarantee that the uses will be
4392 // executed given that PoisonI is executed.
4393 //
4394 // FIXME: Expand this to consider uses beyond the same basic block. To do
4395 // this, look out for the distinction between post-dominance and strong
4396 // post-dominance.
4397 const BasicBlock *BB = PoisonI->getParent();
4398
4399 // Set of instructions that we have proved will yield poison if PoisonI
4400 // does.
4401 SmallSet<const Value *, 16> YieldsPoison;
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004402 SmallSet<const BasicBlock *, 4> Visited;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004403 YieldsPoison.insert(PoisonI);
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004404 Visited.insert(PoisonI->getParent());
Jingyue Wu42f1d672015-07-28 18:22:40 +00004405
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004406 BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end();
Jingyue Wu42f1d672015-07-28 18:22:40 +00004407
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004408 unsigned Iter = 0;
4409 while (Iter++ < MaxDepth) {
4410 for (auto &I : make_range(Begin, End)) {
4411 if (&I != PoisonI) {
4412 const Value *NotPoison = getGuaranteedNonFullPoisonOp(&I);
4413 if (NotPoison != nullptr && YieldsPoison.count(NotPoison))
4414 return true;
4415 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
4416 return false;
4417 }
4418
4419 // Mark poison that propagates from I through uses of I.
4420 if (YieldsPoison.count(&I)) {
4421 for (const User *User : I.users()) {
4422 const Instruction *UserI = cast<Instruction>(User);
4423 if (propagatesFullPoison(UserI))
4424 YieldsPoison.insert(User);
4425 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004426 }
4427 }
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004428
4429 if (auto *NextBB = BB->getSingleSuccessor()) {
4430 if (Visited.insert(NextBB).second) {
4431 BB = NextBB;
4432 Begin = BB->getFirstNonPHI()->getIterator();
4433 End = BB->end();
4434 continue;
4435 }
4436 }
4437
4438 break;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004439 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004440 return false;
4441}
4442
Pete Cooper35b00d52016-08-13 01:05:32 +00004443static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
James Molloy134bec22015-08-11 09:12:57 +00004444 if (FMF.noNaNs())
4445 return true;
4446
4447 if (auto *C = dyn_cast<ConstantFP>(V))
4448 return !C->isNaN();
Thomas Livelyd47b5c72018-09-28 21:36:43 +00004449
4450 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
4451 if (!C->getElementType()->isFloatingPointTy())
4452 return false;
4453 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
4454 if (C->getElementAsAPFloat(I).isNaN())
4455 return false;
4456 }
4457 return true;
4458 }
4459
James Molloy134bec22015-08-11 09:12:57 +00004460 return false;
4461}
4462
Pete Cooper35b00d52016-08-13 01:05:32 +00004463static bool isKnownNonZero(const Value *V) {
James Molloy134bec22015-08-11 09:12:57 +00004464 if (auto *C = dyn_cast<ConstantFP>(V))
4465 return !C->isZero();
Thomas Livelyd47b5c72018-09-28 21:36:43 +00004466
4467 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
4468 if (!C->getElementType()->isFloatingPointTy())
4469 return false;
4470 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
4471 if (C->getElementAsAPFloat(I).isZero())
4472 return false;
4473 }
4474 return true;
4475 }
4476
James Molloy134bec22015-08-11 09:12:57 +00004477 return false;
4478}
4479
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004480/// Match clamp pattern for float types without care about NaNs or signed zeros.
4481/// Given non-min/max outer cmp/select from the clamp pattern this
4482/// function recognizes if it can be substitued by a "canonical" min/max
4483/// pattern.
4484static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred,
4485 Value *CmpLHS, Value *CmpRHS,
4486 Value *TrueVal, Value *FalseVal,
4487 Value *&LHS, Value *&RHS) {
4488 // Try to match
4489 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
4490 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
4491 // and return description of the outer Max/Min.
4492
4493 // First, check if select has inverse order:
4494 if (CmpRHS == FalseVal) {
4495 std::swap(TrueVal, FalseVal);
4496 Pred = CmpInst::getInversePredicate(Pred);
4497 }
4498
4499 // Assume success now. If there's no match, callers should not use these anyway.
4500 LHS = TrueVal;
4501 RHS = FalseVal;
4502
4503 const APFloat *FC1;
4504 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
4505 return {SPF_UNKNOWN, SPNB_NA, false};
4506
4507 const APFloat *FC2;
4508 switch (Pred) {
4509 case CmpInst::FCMP_OLT:
4510 case CmpInst::FCMP_OLE:
4511 case CmpInst::FCMP_ULT:
4512 case CmpInst::FCMP_ULE:
4513 if (match(FalseVal,
4514 m_CombineOr(m_OrdFMin(m_Specific(CmpLHS), m_APFloat(FC2)),
4515 m_UnordFMin(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4516 FC1->compare(*FC2) == APFloat::cmpResult::cmpLessThan)
4517 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
4518 break;
4519 case CmpInst::FCMP_OGT:
4520 case CmpInst::FCMP_OGE:
4521 case CmpInst::FCMP_UGT:
4522 case CmpInst::FCMP_UGE:
4523 if (match(FalseVal,
4524 m_CombineOr(m_OrdFMax(m_Specific(CmpLHS), m_APFloat(FC2)),
4525 m_UnordFMax(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4526 FC1->compare(*FC2) == APFloat::cmpResult::cmpGreaterThan)
4527 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
4528 break;
4529 default:
4530 break;
4531 }
4532
4533 return {SPF_UNKNOWN, SPNB_NA, false};
4534}
4535
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004536/// Recognize variations of:
4537/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
4538static SelectPatternResult matchClamp(CmpInst::Predicate Pred,
4539 Value *CmpLHS, Value *CmpRHS,
4540 Value *TrueVal, Value *FalseVal) {
4541 // Swap the select operands and predicate to match the patterns below.
4542 if (CmpRHS != TrueVal) {
4543 Pred = ICmpInst::getSwappedPredicate(Pred);
4544 std::swap(TrueVal, FalseVal);
4545 }
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004546 const APInt *C1;
4547 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
4548 const APInt *C2;
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004549 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
4550 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004551 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004552 return {SPF_SMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004553
4554 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
4555 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004556 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004557 return {SPF_SMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004558
4559 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
4560 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004561 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004562 return {SPF_UMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004563
4564 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
4565 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004566 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004567 return {SPF_UMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004568 }
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004569 return {SPF_UNKNOWN, SPNB_NA, false};
4570}
4571
Sanjay Patel78114302018-01-02 20:56:45 +00004572/// Recognize variations of:
4573/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
4574static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred,
4575 Value *CmpLHS, Value *CmpRHS,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004576 Value *TVal, Value *FVal,
4577 unsigned Depth) {
Sanjay Patel78114302018-01-02 20:56:45 +00004578 // TODO: Allow FP min/max with nnan/nsz.
4579 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
4580
4581 Value *A, *B;
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004582 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
Sanjay Patel78114302018-01-02 20:56:45 +00004583 if (!SelectPatternResult::isMinOrMax(L.Flavor))
4584 return {SPF_UNKNOWN, SPNB_NA, false};
4585
4586 Value *C, *D;
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004587 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
Sanjay Patel78114302018-01-02 20:56:45 +00004588 if (L.Flavor != R.Flavor)
4589 return {SPF_UNKNOWN, SPNB_NA, false};
4590
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004591 // We have something like: x Pred y ? min(a, b) : min(c, d).
4592 // Try to match the compare to the min/max operations of the select operands.
4593 // First, make sure we have the right compare predicate.
Sanjay Patel78114302018-01-02 20:56:45 +00004594 switch (L.Flavor) {
4595 case SPF_SMIN:
4596 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
4597 Pred = ICmpInst::getSwappedPredicate(Pred);
4598 std::swap(CmpLHS, CmpRHS);
4599 }
4600 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
4601 break;
4602 return {SPF_UNKNOWN, SPNB_NA, false};
4603 case SPF_SMAX:
4604 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
4605 Pred = ICmpInst::getSwappedPredicate(Pred);
4606 std::swap(CmpLHS, CmpRHS);
4607 }
4608 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
4609 break;
4610 return {SPF_UNKNOWN, SPNB_NA, false};
4611 case SPF_UMIN:
4612 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
4613 Pred = ICmpInst::getSwappedPredicate(Pred);
4614 std::swap(CmpLHS, CmpRHS);
4615 }
4616 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
4617 break;
4618 return {SPF_UNKNOWN, SPNB_NA, false};
4619 case SPF_UMAX:
4620 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
4621 Pred = ICmpInst::getSwappedPredicate(Pred);
4622 std::swap(CmpLHS, CmpRHS);
4623 }
4624 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
4625 break;
4626 return {SPF_UNKNOWN, SPNB_NA, false};
4627 default:
Sanjay Patel7dfe96a2018-01-08 18:31:13 +00004628 return {SPF_UNKNOWN, SPNB_NA, false};
Sanjay Patel78114302018-01-02 20:56:45 +00004629 }
4630
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004631 // If there is a common operand in the already matched min/max and the other
4632 // min/max operands match the compare operands (either directly or inverted),
4633 // then this is min/max of the same flavor.
4634
Sanjay Patel78114302018-01-02 20:56:45 +00004635 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004636 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
4637 if (D == B) {
4638 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4639 match(A, m_Not(m_Specific(CmpRHS)))))
4640 return {L.Flavor, SPNB_NA, false};
4641 }
Sanjay Patel78114302018-01-02 20:56:45 +00004642 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004643 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
4644 if (C == B) {
4645 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4646 match(A, m_Not(m_Specific(CmpRHS)))))
4647 return {L.Flavor, SPNB_NA, false};
4648 }
Sanjay Patel78114302018-01-02 20:56:45 +00004649 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004650 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
4651 if (D == A) {
4652 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4653 match(B, m_Not(m_Specific(CmpRHS)))))
4654 return {L.Flavor, SPNB_NA, false};
4655 }
Sanjay Patel78114302018-01-02 20:56:45 +00004656 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004657 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
4658 if (C == A) {
4659 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4660 match(B, m_Not(m_Specific(CmpRHS)))))
4661 return {L.Flavor, SPNB_NA, false};
4662 }
Sanjay Patel78114302018-01-02 20:56:45 +00004663
4664 return {SPF_UNKNOWN, SPNB_NA, false};
4665}
4666
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004667/// Match non-obvious integer minimum and maximum sequences.
4668static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
4669 Value *CmpLHS, Value *CmpRHS,
4670 Value *TrueVal, Value *FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004671 Value *&LHS, Value *&RHS,
4672 unsigned Depth) {
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004673 // Assume success. If there's no match, callers should not use these anyway.
4674 LHS = TrueVal;
4675 RHS = FalseVal;
4676
4677 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
4678 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4679 return SPR;
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004680
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004681 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
Sanjay Patel78114302018-01-02 20:56:45 +00004682 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4683 return SPR;
Fangrui Songf78650a2018-07-30 19:41:25 +00004684
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004685 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
Sanjay Patel819f0962016-11-13 19:30:19 +00004686 return {SPF_UNKNOWN, SPNB_NA, false};
4687
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004688 // Z = X -nsw Y
4689 // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
4690 // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
4691 if (match(TrueVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004692 match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004693 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004694
4695 // Z = X -nsw Y
4696 // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
4697 // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
4698 if (match(FalseVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004699 match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004700 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004701
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004702 const APInt *C1;
Sanjay Patel819f0962016-11-13 19:30:19 +00004703 if (!match(CmpRHS, m_APInt(C1)))
4704 return {SPF_UNKNOWN, SPNB_NA, false};
4705
4706 // An unsigned min/max can be written with a signed compare.
4707 const APInt *C2;
4708 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
4709 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
4710 // Is the sign bit set?
4711 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
4712 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
Craig Topper81d772c2017-11-08 19:38:45 +00004713 if (Pred == CmpInst::ICMP_SLT && C1->isNullValue() &&
4714 C2->isMaxSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004715 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004716
4717 // Is the sign bit clear?
4718 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
4719 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004720 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
4721 C2->isMinSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004722 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004723 }
4724
4725 // Look through 'not' ops to find disguised signed min/max.
4726 // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C)
4727 // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C)
4728 if (match(TrueVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004729 match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2)
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004730 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004731
4732 // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X)
4733 // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X)
4734 if (match(FalseVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004735 match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2)
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004736 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004737
4738 return {SPF_UNKNOWN, SPNB_NA, false};
4739}
4740
Chen Zheng69bb0642018-07-21 12:27:54 +00004741bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW) {
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004742 assert(X && Y && "Invalid operand");
4743
Chen Zheng69bb0642018-07-21 12:27:54 +00004744 // X = sub (0, Y) || X = sub nsw (0, Y)
4745 if ((!NeedNSW && match(X, m_Sub(m_ZeroInt(), m_Specific(Y)))) ||
4746 (NeedNSW && match(X, m_NSWSub(m_ZeroInt(), m_Specific(Y)))))
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004747 return true;
4748
Chen Zheng69bb0642018-07-21 12:27:54 +00004749 // Y = sub (0, X) || Y = sub nsw (0, X)
4750 if ((!NeedNSW && match(Y, m_Sub(m_ZeroInt(), m_Specific(X)))) ||
4751 (NeedNSW && match(Y, m_NSWSub(m_ZeroInt(), m_Specific(X)))))
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004752 return true;
4753
Chen Zheng69bb0642018-07-21 12:27:54 +00004754 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004755 Value *A, *B;
Chen Zheng69bb0642018-07-21 12:27:54 +00004756 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
4757 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
4758 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
4759 match(Y, m_NSWSub(m_Specific(B), m_Specific(A)))));
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004760}
4761
James Molloy134bec22015-08-11 09:12:57 +00004762static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
4763 FastMathFlags FMF,
James Molloy270ef8c2015-05-15 16:04:50 +00004764 Value *CmpLHS, Value *CmpRHS,
4765 Value *TrueVal, Value *FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004766 Value *&LHS, Value *&RHS,
4767 unsigned Depth) {
Sanjay Patele7c94ef2018-11-04 14:28:48 +00004768 if (CmpInst::isFPPredicate(Pred)) {
4769 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
4770 // 0.0 operand, set the compare's 0.0 operands to that same value for the
4771 // purpose of identifying min/max. Disregard vector constants with undefined
4772 // elements because those can not be back-propagated for analysis.
4773 Value *OutputZeroVal = nullptr;
4774 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
4775 !cast<Constant>(TrueVal)->containsUndefElement())
4776 OutputZeroVal = TrueVal;
4777 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
4778 !cast<Constant>(FalseVal)->containsUndefElement())
4779 OutputZeroVal = FalseVal;
4780
4781 if (OutputZeroVal) {
4782 if (match(CmpLHS, m_AnyZeroFP()))
4783 CmpLHS = OutputZeroVal;
4784 if (match(CmpRHS, m_AnyZeroFP()))
4785 CmpRHS = OutputZeroVal;
4786 }
4787 }
4788
James Molloy71b91c22015-05-11 14:42:20 +00004789 LHS = CmpLHS;
4790 RHS = CmpRHS;
4791
Sanjay Patel9a399792017-12-26 15:09:19 +00004792 // Signed zero may return inconsistent results between implementations.
4793 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
4794 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
4795 // Therefore, we behave conservatively and only proceed if at least one of the
4796 // operands is known to not be zero or if we don't care about signed zero.
James Molloy134bec22015-08-11 09:12:57 +00004797 switch (Pred) {
4798 default: break;
Sanjay Patel9a399792017-12-26 15:09:19 +00004799 // FIXME: Include OGT/OLT/UGT/ULT.
James Molloy134bec22015-08-11 09:12:57 +00004800 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
4801 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
4802 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4803 !isKnownNonZero(CmpRHS))
4804 return {SPF_UNKNOWN, SPNB_NA, false};
4805 }
4806
4807 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
4808 bool Ordered = false;
4809
4810 // When given one NaN and one non-NaN input:
4811 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
4812 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
4813 // ordered comparison fails), which could be NaN or non-NaN.
4814 // so here we discover exactly what NaN behavior is required/accepted.
4815 if (CmpInst::isFPPredicate(Pred)) {
4816 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
4817 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
4818
4819 if (LHSSafe && RHSSafe) {
4820 // Both operands are known non-NaN.
4821 NaNBehavior = SPNB_RETURNS_ANY;
4822 } else if (CmpInst::isOrdered(Pred)) {
4823 // An ordered comparison will return false when given a NaN, so it
4824 // returns the RHS.
4825 Ordered = true;
4826 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004827 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004828 NaNBehavior = SPNB_RETURNS_NAN;
4829 else if (RHSSafe)
4830 NaNBehavior = SPNB_RETURNS_OTHER;
4831 else
4832 // Completely unsafe.
4833 return {SPF_UNKNOWN, SPNB_NA, false};
4834 } else {
4835 Ordered = false;
4836 // An unordered comparison will return true when given a NaN, so it
4837 // returns the LHS.
4838 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004839 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004840 NaNBehavior = SPNB_RETURNS_OTHER;
4841 else if (RHSSafe)
4842 NaNBehavior = SPNB_RETURNS_NAN;
4843 else
4844 // Completely unsafe.
4845 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004846 }
4847 }
4848
James Molloy71b91c22015-05-11 14:42:20 +00004849 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
James Molloy134bec22015-08-11 09:12:57 +00004850 std::swap(CmpLHS, CmpRHS);
4851 Pred = CmpInst::getSwappedPredicate(Pred);
4852 if (NaNBehavior == SPNB_RETURNS_NAN)
4853 NaNBehavior = SPNB_RETURNS_OTHER;
4854 else if (NaNBehavior == SPNB_RETURNS_OTHER)
4855 NaNBehavior = SPNB_RETURNS_NAN;
4856 Ordered = !Ordered;
4857 }
4858
4859 // ([if]cmp X, Y) ? X : Y
4860 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
James Molloy71b91c22015-05-11 14:42:20 +00004861 switch (Pred) {
James Molloy134bec22015-08-11 09:12:57 +00004862 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
James Molloy71b91c22015-05-11 14:42:20 +00004863 case ICmpInst::ICMP_UGT:
James Molloy134bec22015-08-11 09:12:57 +00004864 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004865 case ICmpInst::ICMP_SGT:
James Molloy134bec22015-08-11 09:12:57 +00004866 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004867 case ICmpInst::ICMP_ULT:
James Molloy134bec22015-08-11 09:12:57 +00004868 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004869 case ICmpInst::ICMP_SLT:
James Molloy134bec22015-08-11 09:12:57 +00004870 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
4871 case FCmpInst::FCMP_UGT:
4872 case FCmpInst::FCMP_UGE:
4873 case FCmpInst::FCMP_OGT:
4874 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
4875 case FCmpInst::FCMP_ULT:
4876 case FCmpInst::FCMP_ULE:
4877 case FCmpInst::FCMP_OLT:
4878 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
James Molloy71b91c22015-05-11 14:42:20 +00004879 }
4880 }
Fangrui Songf78650a2018-07-30 19:41:25 +00004881
Chen Zhengccc84222018-07-16 02:23:00 +00004882 if (isKnownNegation(TrueVal, FalseVal)) {
4883 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
4884 // match against either LHS or sext(LHS).
4885 auto MaybeSExtCmpLHS =
4886 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
4887 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
4888 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
4889 if (match(TrueVal, MaybeSExtCmpLHS)) {
4890 // Set the return values. If the compare uses the negated value (-X >s 0),
4891 // swap the return values because the negated value is always 'RHS'.
Sanjay Patel284ba0c2018-07-02 14:43:40 +00004892 LHS = TrueVal;
4893 RHS = FalseVal;
Chen Zhengccc84222018-07-16 02:23:00 +00004894 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
4895 std::swap(LHS, RHS);
4896
4897 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
4898 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
4899 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
4900 return {SPF_ABS, SPNB_NA, false};
4901
4902 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
4903 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
4904 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
4905 return {SPF_NABS, SPNB_NA, false};
4906 }
4907 else if (match(FalseVal, MaybeSExtCmpLHS)) {
4908 // Set the return values. If the compare uses the negated value (-X >s 0),
4909 // swap the return values because the negated value is always 'RHS'.
Sanjay Patel284ba0c2018-07-02 14:43:40 +00004910 LHS = FalseVal;
4911 RHS = TrueVal;
Chen Zhengccc84222018-07-16 02:23:00 +00004912 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
4913 std::swap(LHS, RHS);
4914
4915 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
4916 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
4917 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
4918 return {SPF_NABS, SPNB_NA, false};
4919
4920 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
4921 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
4922 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
4923 return {SPF_ABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004924 }
James Molloy71b91c22015-05-11 14:42:20 +00004925 }
4926
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004927 if (CmpInst::isIntPredicate(Pred))
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004928 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004929
4930 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
4931 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
4932 // semantics than minNum. Be conservative in such case.
4933 if (NaNBehavior != SPNB_RETURNS_ANY ||
4934 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4935 !isKnownNonZero(CmpRHS)))
4936 return {SPF_UNKNOWN, SPNB_NA, false};
4937
4938 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
James Molloy71b91c22015-05-11 14:42:20 +00004939}
James Molloy270ef8c2015-05-15 16:04:50 +00004940
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004941/// Helps to match a select pattern in case of a type mismatch.
4942///
4943/// The function processes the case when type of true and false values of a
4944/// select instruction differs from type of the cmp instruction operands because
Vedant Kumar1a8456d2018-03-02 18:57:02 +00004945/// of a cast instruction. The function checks if it is legal to move the cast
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004946/// operation after "select". If yes, it returns the new second value of
4947/// "select" (with the assumption that cast is moved):
4948/// 1. As operand of cast instruction when both values of "select" are same cast
4949/// instructions.
4950/// 2. As restored constant (by applying reverse cast operation) when the first
4951/// value of the "select" is a cast operation and the second value is a
4952/// constant.
4953/// NOTE: We return only the new second value because the first value could be
4954/// accessed as operand of cast instruction.
James Molloy569cea62015-09-02 17:25:25 +00004955static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
4956 Instruction::CastOps *CastOp) {
Sanjay Patel14a4b812017-01-29 16:34:57 +00004957 auto *Cast1 = dyn_cast<CastInst>(V1);
4958 if (!Cast1)
James Molloy270ef8c2015-05-15 16:04:50 +00004959 return nullptr;
James Molloy270ef8c2015-05-15 16:04:50 +00004960
Sanjay Patel14a4b812017-01-29 16:34:57 +00004961 *CastOp = Cast1->getOpcode();
4962 Type *SrcTy = Cast1->getSrcTy();
4963 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
4964 // If V1 and V2 are both the same cast from the same type, look through V1.
4965 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
4966 return Cast2->getOperand(0);
James Molloy569cea62015-09-02 17:25:25 +00004967 return nullptr;
4968 }
4969
Sanjay Patel14a4b812017-01-29 16:34:57 +00004970 auto *C = dyn_cast<Constant>(V2);
4971 if (!C)
4972 return nullptr;
4973
David Majnemerd2a074b2016-04-29 18:40:34 +00004974 Constant *CastedTo = nullptr;
Sanjay Patel14a4b812017-01-29 16:34:57 +00004975 switch (*CastOp) {
4976 case Instruction::ZExt:
4977 if (CmpI->isUnsigned())
4978 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
4979 break;
4980 case Instruction::SExt:
4981 if (CmpI->isSigned())
4982 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
4983 break;
4984 case Instruction::Trunc:
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004985 Constant *CmpConst;
Nikolai Bozhenov9723f122017-10-18 14:24:50 +00004986 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
4987 CmpConst->getType() == SrcTy) {
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004988 // Here we have the following case:
4989 //
4990 // %cond = cmp iN %x, CmpConst
4991 // %tr = trunc iN %x to iK
4992 // %narrowsel = select i1 %cond, iK %t, iK C
4993 //
4994 // We can always move trunc after select operation:
4995 //
4996 // %cond = cmp iN %x, CmpConst
4997 // %widesel = select i1 %cond, iN %x, iN CmpConst
4998 // %tr = trunc iN %widesel to iK
4999 //
5000 // Note that C could be extended in any way because we don't care about
5001 // upper bits after truncation. It can't be abs pattern, because it would
5002 // look like:
5003 //
5004 // select i1 %cond, x, -x.
5005 //
5006 // So only min/max pattern could be matched. Such match requires widened C
5007 // == CmpConst. That is why set widened C = CmpConst, condition trunc
5008 // CmpConst == C is checked below.
5009 CastedTo = CmpConst;
5010 } else {
5011 CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
5012 }
Sanjay Patel14a4b812017-01-29 16:34:57 +00005013 break;
5014 case Instruction::FPTrunc:
5015 CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
5016 break;
5017 case Instruction::FPExt:
5018 CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
5019 break;
5020 case Instruction::FPToUI:
5021 CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
5022 break;
5023 case Instruction::FPToSI:
5024 CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
5025 break;
5026 case Instruction::UIToFP:
5027 CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
5028 break;
5029 case Instruction::SIToFP:
5030 CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
5031 break;
5032 default:
5033 break;
5034 }
David Majnemerd2a074b2016-04-29 18:40:34 +00005035
5036 if (!CastedTo)
5037 return nullptr;
5038
David Majnemerd2a074b2016-04-29 18:40:34 +00005039 // Make sure the cast doesn't lose any information.
Sanjay Patel14a4b812017-01-29 16:34:57 +00005040 Constant *CastedBack =
5041 ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
David Majnemerd2a074b2016-04-29 18:40:34 +00005042 if (CastedBack != C)
5043 return nullptr;
5044
5045 return CastedTo;
James Molloy270ef8c2015-05-15 16:04:50 +00005046}
5047
Sanjay Patele8dc0902016-05-23 17:57:54 +00005048SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005049 Instruction::CastOps *CastOp,
5050 unsigned Depth) {
5051 if (Depth >= MaxDepth)
5052 return {SPF_UNKNOWN, SPNB_NA, false};
5053
James Molloy270ef8c2015-05-15 16:04:50 +00005054 SelectInst *SI = dyn_cast<SelectInst>(V);
James Molloy134bec22015-08-11 09:12:57 +00005055 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00005056
James Molloy134bec22015-08-11 09:12:57 +00005057 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
5058 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00005059
James Molloy134bec22015-08-11 09:12:57 +00005060 CmpInst::Predicate Pred = CmpI->getPredicate();
James Molloy270ef8c2015-05-15 16:04:50 +00005061 Value *CmpLHS = CmpI->getOperand(0);
5062 Value *CmpRHS = CmpI->getOperand(1);
5063 Value *TrueVal = SI->getTrueValue();
5064 Value *FalseVal = SI->getFalseValue();
James Molloy134bec22015-08-11 09:12:57 +00005065 FastMathFlags FMF;
5066 if (isa<FPMathOperator>(CmpI))
5067 FMF = CmpI->getFastMathFlags();
James Molloy270ef8c2015-05-15 16:04:50 +00005068
5069 // Bail out early.
5070 if (CmpI->isEquality())
James Molloy134bec22015-08-11 09:12:57 +00005071 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00005072
5073 // Deal with type mismatches.
5074 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
Sanjay Patel9a399792017-12-26 15:09:19 +00005075 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
5076 // If this is a potential fmin/fmax with a cast to integer, then ignore
5077 // -0.0 because there is no corresponding integer value.
5078 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
5079 FMF.setNoSignedZeros();
James Molloy134bec22015-08-11 09:12:57 +00005080 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00005081 cast<CastInst>(TrueVal)->getOperand(0), C,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005082 LHS, RHS, Depth);
Sanjay Patel9a399792017-12-26 15:09:19 +00005083 }
5084 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
5085 // If this is a potential fmin/fmax with a cast to integer, then ignore
5086 // -0.0 because there is no corresponding integer value.
5087 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
5088 FMF.setNoSignedZeros();
James Molloy134bec22015-08-11 09:12:57 +00005089 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00005090 C, cast<CastInst>(FalseVal)->getOperand(0),
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005091 LHS, RHS, Depth);
Sanjay Patel9a399792017-12-26 15:09:19 +00005092 }
James Molloy270ef8c2015-05-15 16:04:50 +00005093 }
James Molloy134bec22015-08-11 09:12:57 +00005094 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005095 LHS, RHS, Depth);
James Molloy270ef8c2015-05-15 16:04:50 +00005096}
Sanjoy Dasa7e13782015-10-24 05:37:35 +00005097
Sanjay Patel7ed0bc22018-03-06 16:57:55 +00005098CmpInst::Predicate llvm::getMinMaxPred(SelectPatternFlavor SPF, bool Ordered) {
5099 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
5100 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
5101 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
5102 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
5103 if (SPF == SPF_FMINNUM)
5104 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
5105 if (SPF == SPF_FMAXNUM)
5106 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
5107 llvm_unreachable("unhandled!");
5108}
5109
5110SelectPatternFlavor llvm::getInverseMinMaxFlavor(SelectPatternFlavor SPF) {
5111 if (SPF == SPF_SMIN) return SPF_SMAX;
5112 if (SPF == SPF_UMIN) return SPF_UMAX;
5113 if (SPF == SPF_SMAX) return SPF_SMIN;
5114 if (SPF == SPF_UMAX) return SPF_UMIN;
5115 llvm_unreachable("unhandled!");
5116}
5117
5118CmpInst::Predicate llvm::getInverseMinMaxPred(SelectPatternFlavor SPF) {
5119 return getMinMaxPred(getInverseMinMaxFlavor(SPF));
5120}
5121
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005122/// Return true if "icmp Pred LHS RHS" is always true.
Chad Rosiere42b44b2017-07-28 14:39:06 +00005123static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
5124 const Value *RHS, const DataLayout &DL,
5125 unsigned Depth) {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005126 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005127 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
5128 return true;
5129
5130 switch (Pred) {
5131 default:
5132 return false;
5133
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005134 case CmpInst::ICMP_SLE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005135 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005136
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005137 // LHS s<= LHS +_{nsw} C if C >= 0
Sanjoy Dasdc26df42015-11-11 00:16:41 +00005138 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005139 return !C->isNegative();
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005140 return false;
5141 }
5142
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005143 case CmpInst::ICMP_ULE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005144 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005145
Sanjoy Dasdc26df42015-11-11 00:16:41 +00005146 // LHS u<= LHS +_{nuw} C for any C
5147 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasc01b4d22015-11-06 19:01:03 +00005148 return true;
Sanjoy Das92568102015-11-10 23:56:20 +00005149
5150 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
Pete Cooper35b00d52016-08-13 01:05:32 +00005151 auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
5152 const Value *&X,
Sanjoy Das92568102015-11-10 23:56:20 +00005153 const APInt *&CA, const APInt *&CB) {
5154 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
5155 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
5156 return true;
5157
5158 // If X & C == 0 then (X | C) == X +_{nuw} C
5159 if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
5160 match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
Craig Topperb45eabc2017-04-26 16:39:58 +00005161 KnownBits Known(CA->getBitWidth());
Chad Rosiere42b44b2017-07-28 14:39:06 +00005162 computeKnownBits(X, Known, DL, Depth + 1, /*AC*/ nullptr,
5163 /*CxtI*/ nullptr, /*DT*/ nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +00005164 if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
Sanjoy Das92568102015-11-10 23:56:20 +00005165 return true;
5166 }
5167
5168 return false;
5169 };
5170
Pete Cooper35b00d52016-08-13 01:05:32 +00005171 const Value *X;
Sanjoy Das92568102015-11-10 23:56:20 +00005172 const APInt *CLHS, *CRHS;
Sanjoy Dasdc26df42015-11-11 00:16:41 +00005173 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
5174 return CLHS->ule(*CRHS);
Sanjoy Das92568102015-11-10 23:56:20 +00005175
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005176 return false;
5177 }
5178 }
5179}
5180
5181/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
Chad Rosier41dd31f2016-04-20 19:15:26 +00005182/// ALHS ARHS" is true. Otherwise, return None.
5183static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00005184isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
Chad Rosiere42b44b2017-07-28 14:39:06 +00005185 const Value *ARHS, const Value *BLHS, const Value *BRHS,
5186 const DataLayout &DL, unsigned Depth) {
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005187 switch (Pred) {
5188 default:
Chad Rosier41dd31f2016-04-20 19:15:26 +00005189 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005190
5191 case CmpInst::ICMP_SLT:
5192 case CmpInst::ICMP_SLE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00005193 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth) &&
5194 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00005195 return true;
5196 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005197
5198 case CmpInst::ICMP_ULT:
5199 case CmpInst::ICMP_ULE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00005200 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth) &&
5201 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00005202 return true;
5203 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005204 }
5205}
5206
Chad Rosier226a7342016-05-05 17:41:19 +00005207/// Return true if the operands of the two compares match. IsSwappedOps is true
5208/// when the operands match, but are swapped.
Pete Cooper35b00d52016-08-13 01:05:32 +00005209static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
5210 const Value *BLHS, const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00005211 bool &IsSwappedOps) {
5212
5213 bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
5214 IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
5215 return IsMatchingOps || IsSwappedOps;
5216}
5217
Chad Rosier41dd31f2016-04-20 19:15:26 +00005218/// Return true if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS BRHS" is
5219/// true. Return false if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS
5220/// BRHS" is false. Otherwise, return None if we can't infer anything.
5221static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
Pete Cooper35b00d52016-08-13 01:05:32 +00005222 const Value *ALHS,
5223 const Value *ARHS,
Chad Rosier41dd31f2016-04-20 19:15:26 +00005224 CmpInst::Predicate BPred,
Pete Cooper35b00d52016-08-13 01:05:32 +00005225 const Value *BLHS,
5226 const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00005227 bool IsSwappedOps) {
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005228 // Canonicalize the operands so they're matching.
5229 if (IsSwappedOps) {
5230 std::swap(BLHS, BRHS);
5231 BPred = ICmpInst::getSwappedPredicate(BPred);
5232 }
Chad Rosier99bc4802016-04-21 16:18:02 +00005233 if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005234 return true;
Chad Rosier99bc4802016-04-21 16:18:02 +00005235 if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
Chad Rosier41dd31f2016-04-20 19:15:26 +00005236 return false;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005237
Chad Rosier41dd31f2016-04-20 19:15:26 +00005238 return None;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005239}
5240
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005241/// Return true if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS C2" is
5242/// true. Return false if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS
5243/// C2" is false. Otherwise, return None if we can't infer anything.
5244static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00005245isImpliedCondMatchingImmOperands(CmpInst::Predicate APred, const Value *ALHS,
5246 const ConstantInt *C1,
5247 CmpInst::Predicate BPred,
5248 const Value *BLHS, const ConstantInt *C2) {
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005249 assert(ALHS == BLHS && "LHS operands must match.");
5250 ConstantRange DomCR =
5251 ConstantRange::makeExactICmpRegion(APred, C1->getValue());
5252 ConstantRange CR =
5253 ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
5254 ConstantRange Intersection = DomCR.intersectWith(CR);
5255 ConstantRange Difference = DomCR.difference(CR);
5256 if (Intersection.isEmptySet())
5257 return false;
5258 if (Difference.isEmptySet())
5259 return true;
5260 return None;
5261}
5262
Chad Rosier2f498032017-07-28 18:47:43 +00005263/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
5264/// false. Otherwise, return None if we can't infer anything.
5265static Optional<bool> isImpliedCondICmps(const ICmpInst *LHS,
5266 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00005267 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00005268 unsigned Depth) {
5269 Value *ALHS = LHS->getOperand(0);
5270 Value *ARHS = LHS->getOperand(1);
Chad Rosiera72a9ff2017-07-06 20:00:25 +00005271 // The rest of the logic assumes the LHS condition is true. If that's not the
5272 // case, invert the predicate to make it so.
Chad Rosier2f498032017-07-28 18:47:43 +00005273 ICmpInst::Predicate APred =
Chad Rosierdfd1de62017-08-01 20:18:54 +00005274 LHSIsTrue ? LHS->getPredicate() : LHS->getInversePredicate();
Chad Rosier2f498032017-07-28 18:47:43 +00005275
5276 Value *BLHS = RHS->getOperand(0);
5277 Value *BRHS = RHS->getOperand(1);
5278 ICmpInst::Predicate BPred = RHS->getPredicate();
Chad Rosiere2cbd132016-04-25 17:23:36 +00005279
Chad Rosier226a7342016-05-05 17:41:19 +00005280 // Can we infer anything when the two compares have matching operands?
5281 bool IsSwappedOps;
5282 if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, IsSwappedOps)) {
5283 if (Optional<bool> Implication = isImpliedCondMatchingOperands(
5284 APred, ALHS, ARHS, BPred, BLHS, BRHS, IsSwappedOps))
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005285 return Implication;
Chad Rosier226a7342016-05-05 17:41:19 +00005286 // No amount of additional analysis will infer the second condition, so
5287 // early exit.
5288 return None;
5289 }
5290
5291 // Can we infer anything when the LHS operands match and the RHS operands are
5292 // constants (not necessarily matching)?
5293 if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
5294 if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
5295 APred, ALHS, cast<ConstantInt>(ARHS), BPred, BLHS,
5296 cast<ConstantInt>(BRHS)))
5297 return Implication;
5298 // No amount of additional analysis will infer the second condition, so
5299 // early exit.
5300 return None;
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005301 }
5302
Chad Rosier41dd31f2016-04-20 19:15:26 +00005303 if (APred == BPred)
Chad Rosiere42b44b2017-07-28 14:39:06 +00005304 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth);
Chad Rosier41dd31f2016-04-20 19:15:26 +00005305 return None;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00005306}
Chad Rosier2f498032017-07-28 18:47:43 +00005307
Chad Rosierf73a10d2017-08-01 19:22:36 +00005308/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
5309/// false. Otherwise, return None if we can't infer anything. We expect the
5310/// RHS to be an icmp and the LHS to be an 'and' or an 'or' instruction.
5311static Optional<bool> isImpliedCondAndOr(const BinaryOperator *LHS,
5312 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00005313 const DataLayout &DL, bool LHSIsTrue,
Chad Rosierf73a10d2017-08-01 19:22:36 +00005314 unsigned Depth) {
5315 // The LHS must be an 'or' or an 'and' instruction.
5316 assert((LHS->getOpcode() == Instruction::And ||
5317 LHS->getOpcode() == Instruction::Or) &&
5318 "Expected LHS to be 'and' or 'or'.");
5319
Davide Italiano1a943a92017-08-09 16:06:54 +00005320 assert(Depth <= MaxDepth && "Hit recursion limit");
Chad Rosierf73a10d2017-08-01 19:22:36 +00005321
5322 // If the result of an 'or' is false, then we know both legs of the 'or' are
5323 // false. Similarly, if the result of an 'and' is true, then we know both
5324 // legs of the 'and' are true.
5325 Value *ALHS, *ARHS;
Chad Rosierdfd1de62017-08-01 20:18:54 +00005326 if ((!LHSIsTrue && match(LHS, m_Or(m_Value(ALHS), m_Value(ARHS)))) ||
5327 (LHSIsTrue && match(LHS, m_And(m_Value(ALHS), m_Value(ARHS))))) {
Chad Rosierf73a10d2017-08-01 19:22:36 +00005328 // FIXME: Make this non-recursion.
5329 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00005330 isImpliedCondition(ALHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00005331 return Implication;
5332 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00005333 isImpliedCondition(ARHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00005334 return Implication;
5335 return None;
5336 }
5337 return None;
5338}
5339
Chad Rosier2f498032017-07-28 18:47:43 +00005340Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00005341 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00005342 unsigned Depth) {
Davide Italiano30e51942017-08-09 15:13:50 +00005343 // Bail out when we hit the limit.
5344 if (Depth == MaxDepth)
5345 return None;
5346
Chad Rosierf73a10d2017-08-01 19:22:36 +00005347 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
5348 // example.
Chad Rosier2f498032017-07-28 18:47:43 +00005349 if (LHS->getType() != RHS->getType())
5350 return None;
5351
5352 Type *OpTy = LHS->getType();
Chad Rosierf73a10d2017-08-01 19:22:36 +00005353 assert(OpTy->isIntOrIntVectorTy(1) && "Expected integer type only!");
Chad Rosier2f498032017-07-28 18:47:43 +00005354
5355 // LHS ==> RHS by definition
5356 if (LHS == RHS)
Chad Rosierdfd1de62017-08-01 20:18:54 +00005357 return LHSIsTrue;
Chad Rosier2f498032017-07-28 18:47:43 +00005358
Chad Rosierf73a10d2017-08-01 19:22:36 +00005359 // FIXME: Extending the code below to handle vectors.
Chad Rosier2f498032017-07-28 18:47:43 +00005360 if (OpTy->isVectorTy())
Chad Rosier2f498032017-07-28 18:47:43 +00005361 return None;
Chad Rosierf73a10d2017-08-01 19:22:36 +00005362
Chad Rosier2f498032017-07-28 18:47:43 +00005363 assert(OpTy->isIntegerTy(1) && "implied by above");
5364
Chad Rosier2f498032017-07-28 18:47:43 +00005365 // Both LHS and RHS are icmps.
Chad Rosierf73a10d2017-08-01 19:22:36 +00005366 const ICmpInst *LHSCmp = dyn_cast<ICmpInst>(LHS);
5367 const ICmpInst *RHSCmp = dyn_cast<ICmpInst>(RHS);
5368 if (LHSCmp && RHSCmp)
Chad Rosierdfd1de62017-08-01 20:18:54 +00005369 return isImpliedCondICmps(LHSCmp, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00005370
Chad Rosierf73a10d2017-08-01 19:22:36 +00005371 // The LHS should be an 'or' or an 'and' instruction. We expect the RHS to be
5372 // an icmp. FIXME: Add support for and/or on the RHS.
5373 const BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHS);
5374 if (LHSBO && RHSCmp) {
5375 if ((LHSBO->getOpcode() == Instruction::And ||
5376 LHSBO->getOpcode() == Instruction::Or))
Chad Rosierdfd1de62017-08-01 20:18:54 +00005377 return isImpliedCondAndOr(LHSBO, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00005378 }
Chad Rosierf73a10d2017-08-01 19:22:36 +00005379 return None;
Chad Rosier2f498032017-07-28 18:47:43 +00005380}