blob: fd3db4c6ad2ccff77841934a9337d36019d1f656 [file] [log] [blame]
Chris Lattner965c7692008-06-02 01:18:21 +00001//===- ValueTracking.cpp - Walk computations to compute properties --------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner965c7692008-06-02 01:18:21 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file contains routines that help analyze properties that chains of
10// computations have.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000015#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/None.h"
James Molloy493e57d2015-10-26 14:10:46 +000019#include "llvm/ADT/Optional.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000020#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000022#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/StringRef.h"
25#include "llvm/ADT/iterator_range.h"
26#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000027#include "llvm/Analysis/AssumptionCache.h"
Max Kazantsev3c284bd2018-08-30 03:39:16 +000028#include "llvm/Analysis/GuardUtils.h"
Dan Gohman949ab782010-12-15 20:10:26 +000029#include "llvm/Analysis/InstructionSimplify.h"
Artur Pilipenko31bcca42016-02-24 12:49:04 +000030#include "llvm/Analysis/Loads.h"
Adam Nemete2b885c2015-04-23 20:09:20 +000031#include "llvm/Analysis/LoopInfo.h"
Adam Nemet0965da22017-10-09 23:19:02 +000032#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000033#include "llvm/Analysis/TargetLibraryInfo.h"
34#include "llvm/IR/Argument.h"
35#include "llvm/IR/Attributes.h"
36#include "llvm/IR/BasicBlock.h"
Nick Lewyckyec373542014-05-20 05:13:21 +000037#include "llvm/IR/CallSite.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000038#include "llvm/IR/Constant.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000039#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/Constants.h"
Matthias Braun50ec0b52017-05-19 22:37:09 +000041#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000042#include "llvm/IR/DiagnosticInfo.h"
Hal Finkel60db0582014-09-07 18:57:58 +000043#include "llvm/IR/Dominators.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000044#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000045#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/GlobalAlias.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000047#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/GlobalVariable.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000049#include "llvm/IR/InstrTypes.h"
50#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/Instructions.h"
52#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000053#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000054#include "llvm/IR/LLVMContext.h"
55#include "llvm/IR/Metadata.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000056#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000057#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000058#include "llvm/IR/PatternMatch.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000059#include "llvm/IR/Type.h"
60#include "llvm/IR/User.h"
61#include "llvm/IR/Value.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/CommandLine.h"
64#include "llvm/Support/Compiler.h"
65#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000066#include "llvm/Support/KnownBits.h"
Chris Lattner965c7692008-06-02 01:18:21 +000067#include "llvm/Support/MathExtras.h"
Matthias Braun37e5d792016-01-28 06:29:33 +000068#include <algorithm>
69#include <array>
Eugene Zelenko75075ef2017-09-01 21:37:29 +000070#include <cassert>
71#include <cstdint>
72#include <iterator>
Fangrui Songf78650a2018-07-30 19:41:25 +000073#include <utility>
Eugene Zelenko75075ef2017-09-01 21:37:29 +000074
Chris Lattner965c7692008-06-02 01:18:21 +000075using namespace llvm;
Duncan Sandsd3951082011-01-25 09:38:29 +000076using namespace llvm::PatternMatch;
77
78const unsigned MaxDepth = 6;
79
Philip Reames1c292272015-03-10 22:43:20 +000080// Controls the number of uses of the value searched for possible
81// dominating comparisons.
82static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
Igor Laevskycea9ede2015-09-29 14:57:52 +000083 cl::Hidden, cl::init(20));
Philip Reames1c292272015-03-10 22:43:20 +000084
Craig Topper6b3940a2017-05-03 22:25:19 +000085/// Returns the bitwidth of the given scalar or pointer type. For vector types,
86/// returns the element type's bitwidth.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000087static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
Duncan Sandsd3951082011-01-25 09:38:29 +000088 if (unsigned BitWidth = Ty->getScalarSizeInBits())
89 return BitWidth;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +000090
Elena Demikhovsky945b7e52018-02-14 06:58:08 +000091 return DL.getIndexTypeSizeInBits(Ty);
Duncan Sandsd3951082011-01-25 09:38:29 +000092}
Chris Lattner965c7692008-06-02 01:18:21 +000093
Benjamin Kramercfd8d902014-09-12 08:56:53 +000094namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +000095
Hal Finkel60db0582014-09-07 18:57:58 +000096// Simplifying using an assume can only be done in a particular control-flow
97// context (the context instruction provides that context). If an assume and
98// the context instruction are not in the same block then the DT helps in
99// figuring out if we can use it.
100struct Query {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000101 const DataLayout &DL;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000102 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +0000103 const Instruction *CxtI;
104 const DominatorTree *DT;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000105
Sanjay Patel54656ca2017-02-06 18:26:06 +0000106 // Unlike the other analyses, this may be a nullptr because not all clients
107 // provide it currently.
108 OptimizationRemarkEmitter *ORE;
Hal Finkel60db0582014-09-07 18:57:58 +0000109
Matthias Braun37e5d792016-01-28 06:29:33 +0000110 /// Set of assumptions that should be excluded from further queries.
111 /// This is because of the potential for mutual recursion to cause
112 /// computeKnownBits to repeatedly visit the same assume intrinsic. The
113 /// classic case of this is assume(x = y), which will attempt to determine
114 /// bits in x from bits in y, which will attempt to determine bits in y from
115 /// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
Craig Topper6e11a052017-05-08 16:22:48 +0000116 /// isKnownNonZero, which calls computeKnownBits and isKnownToBeAPowerOfTwo
117 /// (all of which can call computeKnownBits), and so on.
Li Huang755f75f2016-10-15 19:00:04 +0000118 std::array<const Value *, MaxDepth> Excluded;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000119
Florian Hahn19f9e322018-08-17 14:39:04 +0000120 /// If true, it is safe to use metadata during simplification.
121 InstrInfoQuery IIQ;
122
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000123 unsigned NumExcluded = 0;
Matthias Braun37e5d792016-01-28 06:29:33 +0000124
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000125 Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000126 const DominatorTree *DT, bool UseInstrInfo,
127 OptimizationRemarkEmitter *ORE = nullptr)
128 : DL(DL), AC(AC), CxtI(CxtI), DT(DT), ORE(ORE), IIQ(UseInstrInfo) {}
Hal Finkel60db0582014-09-07 18:57:58 +0000129
130 Query(const Query &Q, const Value *NewExcl)
Florian Hahn19f9e322018-08-17 14:39:04 +0000131 : 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 +0000132 NumExcluded(Q.NumExcluded) {
Matthias Braun37e5d792016-01-28 06:29:33 +0000133 Excluded = Q.Excluded;
134 Excluded[NumExcluded++] = NewExcl;
135 assert(NumExcluded <= Excluded.size());
136 }
137
138 bool isExcluded(const Value *Value) const {
139 if (NumExcluded == 0)
140 return false;
141 auto End = Excluded.begin() + NumExcluded;
142 return std::find(Excluded.begin(), End, Value) != End;
Hal Finkel60db0582014-09-07 18:57:58 +0000143 }
144};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000145
Benjamin Kramercfd8d902014-09-12 08:56:53 +0000146} // end anonymous namespace
Hal Finkel60db0582014-09-07 18:57:58 +0000147
Sanjay Patel547e9752014-11-04 16:09:50 +0000148// Given the provided Value and, potentially, a context instruction, return
Hal Finkel60db0582014-09-07 18:57:58 +0000149// the preferred context instruction (if any).
150static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
151 // If we've been provided with a context instruction, then use that (provided
152 // it has been inserted).
153 if (CxtI && CxtI->getParent())
154 return CxtI;
155
156 // If the value is really an already-inserted instruction, then use that.
157 CxtI = dyn_cast<Instruction>(V);
158 if (CxtI && CxtI->getParent())
159 return CxtI;
160
161 return nullptr;
162}
163
Craig Topperb45eabc2017-04-26 16:39:58 +0000164static void computeKnownBits(const Value *V, KnownBits &Known,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000165 unsigned Depth, const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000166
Craig Topperb45eabc2017-04-26 16:39:58 +0000167void llvm::computeKnownBits(const Value *V, KnownBits &Known,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000168 const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000169 AssumptionCache *AC, const Instruction *CxtI,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000170 const DominatorTree *DT,
Florian Hahn19f9e322018-08-17 14:39:04 +0000171 OptimizationRemarkEmitter *ORE, bool UseInstrInfo) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000172 ::computeKnownBits(V, Known, Depth,
Florian Hahn19f9e322018-08-17 14:39:04 +0000173 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
Hal Finkel60db0582014-09-07 18:57:58 +0000174}
175
Craig Topper6e11a052017-05-08 16:22:48 +0000176static KnownBits computeKnownBits(const Value *V, unsigned Depth,
177 const Query &Q);
178
179KnownBits llvm::computeKnownBits(const Value *V, const DataLayout &DL,
180 unsigned Depth, AssumptionCache *AC,
181 const Instruction *CxtI,
Craig Toppera2025ea2017-05-24 16:53:03 +0000182 const DominatorTree *DT,
Florian Hahn19f9e322018-08-17 14:39:04 +0000183 OptimizationRemarkEmitter *ORE,
184 bool UseInstrInfo) {
185 return ::computeKnownBits(
186 V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
Craig Topper6e11a052017-05-08 16:22:48 +0000187}
188
Pete Cooper35b00d52016-08-13 01:05:32 +0000189bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
Florian Hahn19f9e322018-08-17 14:39:04 +0000190 const DataLayout &DL, AssumptionCache *AC,
191 const Instruction *CxtI, const DominatorTree *DT,
192 bool UseInstrInfo) {
Jingyue Wuca321902015-05-14 23:53:19 +0000193 assert(LHS->getType() == RHS->getType() &&
194 "LHS and RHS should have the same type");
195 assert(LHS->getType()->isIntOrIntVectorTy() &&
196 "LHS and RHS should be integers");
Roman Lebedev620b3da2018-04-15 18:59:33 +0000197 // Look for an inverted mask: (X & ~M) op (Y & M).
198 Value *M;
199 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
200 match(RHS, m_c_And(m_Specific(M), m_Value())))
201 return true;
202 if (match(RHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
203 match(LHS, m_c_And(m_Specific(M), m_Value())))
204 return true;
Jingyue Wuca321902015-05-14 23:53:19 +0000205 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
Craig Topperb45eabc2017-04-26 16:39:58 +0000206 KnownBits LHSKnown(IT->getBitWidth());
207 KnownBits RHSKnown(IT->getBitWidth());
Florian Hahn19f9e322018-08-17 14:39:04 +0000208 computeKnownBits(LHS, LHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
209 computeKnownBits(RHS, RHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
Craig Topperb45eabc2017-04-26 16:39:58 +0000210 return (LHSKnown.Zero | RHSKnown.Zero).isAllOnesValue();
Jingyue Wuca321902015-05-14 23:53:19 +0000211}
212
Zaara Syeda3a7578c2017-05-31 17:12:38 +0000213bool llvm::isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI) {
214 for (const User *U : CxtI->users()) {
215 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
216 if (IC->isEquality())
217 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
218 if (C->isNullValue())
219 continue;
220 return false;
221 }
222 return true;
223}
224
Pete Cooper35b00d52016-08-13 01:05:32 +0000225static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000226 const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000227
Pete Cooper35b00d52016-08-13 01:05:32 +0000228bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
Florian Hahn19f9e322018-08-17 14:39:04 +0000229 bool OrZero, unsigned Depth,
230 AssumptionCache *AC, const Instruction *CxtI,
231 const DominatorTree *DT, bool UseInstrInfo) {
232 return ::isKnownToBeAPowerOfTwo(
233 V, OrZero, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000234}
235
Pete Cooper35b00d52016-08-13 01:05:32 +0000236static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000237
Pete Cooper35b00d52016-08-13 01:05:32 +0000238bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000239 AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000240 const DominatorTree *DT, bool UseInstrInfo) {
241 return ::isKnownNonZero(V, Depth,
242 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000243}
244
Pete Cooper35b00d52016-08-13 01:05:32 +0000245bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL,
Florian Hahn19f9e322018-08-17 14:39:04 +0000246 unsigned Depth, AssumptionCache *AC,
247 const Instruction *CxtI, const DominatorTree *DT,
248 bool UseInstrInfo) {
249 KnownBits Known =
250 computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
Craig Topper6e11a052017-05-08 16:22:48 +0000251 return Known.isNonNegative();
Jingyue Wu10fcea52015-08-20 18:27:04 +0000252}
253
Pete Cooper35b00d52016-08-13 01:05:32 +0000254bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000255 AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000256 const DominatorTree *DT, bool UseInstrInfo) {
Philip Reames8f12eba2016-03-09 21:31:47 +0000257 if (auto *CI = dyn_cast<ConstantInt>(V))
258 return CI->getValue().isStrictlyPositive();
Sanjoy Das6082c1a2016-05-07 02:08:15 +0000259
Philip Reames8f12eba2016-03-09 21:31:47 +0000260 // TODO: We'd doing two recursive queries here. We should factor this such
261 // that only a single query is needed.
Florian Hahn19f9e322018-08-17 14:39:04 +0000262 return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT, UseInstrInfo) &&
263 isKnownNonZero(V, DL, Depth, AC, CxtI, DT, UseInstrInfo);
Philip Reames8f12eba2016-03-09 21:31:47 +0000264}
265
Pete Cooper35b00d52016-08-13 01:05:32 +0000266bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000267 AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000268 const DominatorTree *DT, bool UseInstrInfo) {
269 KnownBits Known =
270 computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
Craig Topper6e11a052017-05-08 16:22:48 +0000271 return Known.isNegative();
Nick Lewycky762f8a82016-04-21 00:53:14 +0000272}
273
Pete Cooper35b00d52016-08-13 01:05:32 +0000274static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q);
James Molloy1d88d6f2015-10-22 13:18:42 +0000275
Pete Cooper35b00d52016-08-13 01:05:32 +0000276bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
Florian Hahn19f9e322018-08-17 14:39:04 +0000277 const DataLayout &DL, AssumptionCache *AC,
278 const Instruction *CxtI, const DominatorTree *DT,
279 bool UseInstrInfo) {
280 return ::isKnownNonEqual(V1, V2,
281 Query(DL, AC, safeCxtI(V1, safeCxtI(V2, CxtI)), DT,
282 UseInstrInfo, /*ORE=*/nullptr));
James Molloy1d88d6f2015-10-22 13:18:42 +0000283}
284
Pete Cooper35b00d52016-08-13 01:05:32 +0000285static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000286 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000287
Pete Cooper35b00d52016-08-13 01:05:32 +0000288bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
Florian Hahn19f9e322018-08-17 14:39:04 +0000289 const DataLayout &DL, unsigned Depth,
290 AssumptionCache *AC, const Instruction *CxtI,
291 const DominatorTree *DT, bool UseInstrInfo) {
292 return ::MaskedValueIsZero(
293 V, Mask, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000294}
295
Pete Cooper35b00d52016-08-13 01:05:32 +0000296static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
297 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000298
Pete Cooper35b00d52016-08-13 01:05:32 +0000299unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000300 unsigned Depth, AssumptionCache *AC,
301 const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000302 const DominatorTree *DT, bool UseInstrInfo) {
303 return ::ComputeNumSignBits(
304 V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Hal Finkel60db0582014-09-07 18:57:58 +0000305}
306
Craig Topper8fbb74b2017-03-24 22:12:10 +0000307static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
308 bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000309 KnownBits &KnownOut, KnownBits &Known2,
Craig Topper8fbb74b2017-03-24 22:12:10 +0000310 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000311 unsigned BitWidth = KnownOut.getBitWidth();
Craig Topper8fbb74b2017-03-24 22:12:10 +0000312
313 // If an initial sequence of bits in the result is not needed, the
314 // corresponding bits in the operands are not needed.
Craig Topperb45eabc2017-04-26 16:39:58 +0000315 KnownBits LHSKnown(BitWidth);
316 computeKnownBits(Op0, LHSKnown, Depth + 1, Q);
317 computeKnownBits(Op1, Known2, Depth + 1, Q);
Craig Topper8fbb74b2017-03-24 22:12:10 +0000318
Craig Topperb498a232017-08-08 16:29:35 +0000319 KnownOut = KnownBits::computeForAddSub(Add, NSW, LHSKnown, Known2);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000320}
321
Pete Cooper35b00d52016-08-13 01:05:32 +0000322static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000323 KnownBits &Known, KnownBits &Known2,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000324 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000325 unsigned BitWidth = Known.getBitWidth();
326 computeKnownBits(Op1, Known, Depth + 1, Q);
327 computeKnownBits(Op0, Known2, Depth + 1, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000328
329 bool isKnownNegative = false;
330 bool isKnownNonNegative = false;
331 // If the multiplication is known not to overflow, compute the sign bit.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000332 if (NSW) {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000333 if (Op0 == Op1) {
334 // The product of a number with itself is non-negative.
335 isKnownNonNegative = true;
336 } else {
Craig Topperca48af32017-04-29 16:43:11 +0000337 bool isKnownNonNegativeOp1 = Known.isNonNegative();
338 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
339 bool isKnownNegativeOp1 = Known.isNegative();
340 bool isKnownNegativeOp0 = Known2.isNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000341 // The product of two numbers with the same sign is non-negative.
342 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
343 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
344 // The product of a negative number and a non-negative number is either
345 // negative or zero.
346 if (!isKnownNonNegative)
347 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000348 isKnownNonZero(Op0, Depth, Q)) ||
Nick Lewyckyfa306072012-03-18 23:28:48 +0000349 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000350 isKnownNonZero(Op1, Depth, Q));
Nick Lewyckyfa306072012-03-18 23:28:48 +0000351 }
352 }
353
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000354 assert(!Known.hasConflict() && !Known2.hasConflict());
355 // Compute a conservative estimate for high known-0 bits.
Craig Topper8df66c62017-05-12 17:20:30 +0000356 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
357 Known2.countMinLeadingZeros(),
Nick Lewyckyfa306072012-03-18 23:28:48 +0000358 BitWidth) - BitWidth;
Nick Lewyckyfa306072012-03-18 23:28:48 +0000359 LeadZ = std::min(LeadZ, BitWidth);
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000360
361 // The result of the bottom bits of an integer multiply can be
362 // inferred by looking at the bottom bits of both operands and
363 // multiplying them together.
364 // We can infer at least the minimum number of known trailing bits
365 // of both operands. Depending on number of trailing zeros, we can
366 // infer more bits, because (a*b) <=> ((a/m) * (b/n)) * (m*n) assuming
367 // a and b are divisible by m and n respectively.
368 // We then calculate how many of those bits are inferrable and set
369 // the output. For example, the i8 mul:
370 // a = XXXX1100 (12)
371 // b = XXXX1110 (14)
372 // We know the bottom 3 bits are zero since the first can be divided by
373 // 4 and the second by 2, thus having ((12/4) * (14/2)) * (2*4).
374 // Applying the multiplication to the trimmed arguments gets:
375 // XX11 (3)
376 // X111 (7)
377 // -------
378 // XX11
379 // XX11
380 // XX11
381 // XX11
382 // -------
383 // XXXXX01
384 // Which allows us to infer the 2 LSBs. Since we're multiplying the result
385 // by 8, the bottom 3 bits will be 0, so we can infer a total of 5 bits.
386 // The proof for this can be described as:
387 // Pre: (C1 >= 0) && (C1 < (1 << C5)) && (C2 >= 0) && (C2 < (1 << C6)) &&
388 // (C7 == (1 << (umin(countTrailingZeros(C1), C5) +
389 // umin(countTrailingZeros(C2), C6) +
390 // umin(C5 - umin(countTrailingZeros(C1), C5),
391 // C6 - umin(countTrailingZeros(C2), C6)))) - 1)
392 // %aa = shl i8 %a, C5
393 // %bb = shl i8 %b, C6
394 // %aaa = or i8 %aa, C1
395 // %bbb = or i8 %bb, C2
396 // %mul = mul i8 %aaa, %bbb
397 // %mask = and i8 %mul, C7
398 // =>
399 // %mask = i8 ((C1*C2)&C7)
400 // Where C5, C6 describe the known bits of %a, %b
401 // C1, C2 describe the known bottom bits of %a, %b.
402 // C7 describes the mask of the known bits of the result.
403 APInt Bottom0 = Known.One;
404 APInt Bottom1 = Known2.One;
405
406 // How many times we'd be able to divide each argument by 2 (shr by 1).
407 // This gives us the number of trailing zeros on the multiplication result.
408 unsigned TrailBitsKnown0 = (Known.Zero | Known.One).countTrailingOnes();
409 unsigned TrailBitsKnown1 = (Known2.Zero | Known2.One).countTrailingOnes();
410 unsigned TrailZero0 = Known.countMinTrailingZeros();
411 unsigned TrailZero1 = Known2.countMinTrailingZeros();
412 unsigned TrailZ = TrailZero0 + TrailZero1;
413
414 // Figure out the fewest known-bits operand.
415 unsigned SmallestOperand = std::min(TrailBitsKnown0 - TrailZero0,
416 TrailBitsKnown1 - TrailZero1);
417 unsigned ResultBitsKnown = std::min(SmallestOperand + TrailZ, BitWidth);
418
419 APInt BottomKnown = Bottom0.getLoBits(TrailBitsKnown0) *
420 Bottom1.getLoBits(TrailBitsKnown1);
421
Craig Topperf0aeee02017-05-05 17:36:09 +0000422 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000423 Known.Zero.setHighBits(LeadZ);
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000424 Known.Zero |= (~BottomKnown).getLoBits(ResultBitsKnown);
425 Known.One |= BottomKnown.getLoBits(ResultBitsKnown);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000426
427 // Only make use of no-wrap flags if we failed to compute the sign bit
428 // directly. This matters if the multiplication always overflows, in
429 // which case we prefer to follow the result of the direct computation,
430 // though as the program is invoking undefined behaviour we can choose
431 // whatever we like here.
Craig Topperca48af32017-04-29 16:43:11 +0000432 if (isKnownNonNegative && !Known.isNegative())
433 Known.makeNonNegative();
434 else if (isKnownNegative && !Known.isNonNegative())
435 Known.makeNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000436}
437
Jingyue Wu37fcb592014-06-19 16:50:16 +0000438void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
Craig Topperf42b23f2017-04-28 06:28:56 +0000439 KnownBits &Known) {
440 unsigned BitWidth = Known.getBitWidth();
Rafael Espindola53190532012-03-30 15:52:11 +0000441 unsigned NumRanges = Ranges.getNumOperands() / 2;
442 assert(NumRanges >= 1);
443
Craig Topperf42b23f2017-04-28 06:28:56 +0000444 Known.Zero.setAllBits();
445 Known.One.setAllBits();
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000446
Rafael Espindola53190532012-03-30 15:52:11 +0000447 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000448 ConstantInt *Lower =
449 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
450 ConstantInt *Upper =
451 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
Rafael Espindola53190532012-03-30 15:52:11 +0000452 ConstantRange Range(Lower->getValue(), Upper->getValue());
Rafael Espindola53190532012-03-30 15:52:11 +0000453
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000454 // The first CommonPrefixBits of all values in Range are equal.
455 unsigned CommonPrefixBits =
456 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
457
458 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
Craig Topperf42b23f2017-04-28 06:28:56 +0000459 Known.One &= Range.getUnsignedMax() & Mask;
460 Known.Zero &= ~Range.getUnsignedMax() & Mask;
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000461 }
Rafael Espindola53190532012-03-30 15:52:11 +0000462}
Jay Foad5a29c362014-05-15 12:12:55 +0000463
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000464static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
Hal Finkel60db0582014-09-07 18:57:58 +0000465 SmallVector<const Value *, 16> WorkSet(1, I);
466 SmallPtrSet<const Value *, 32> Visited;
467 SmallPtrSet<const Value *, 16> EphValues;
468
Hal Finkelf2199b22015-10-23 20:37:08 +0000469 // The instruction defining an assumption's condition itself is always
470 // considered ephemeral to that assumption (even if it has other
471 // non-ephemeral users). See r246696's test case for an example.
David Majnemer0a16c222016-08-11 21:15:00 +0000472 if (is_contained(I->operands(), E))
Hal Finkelf2199b22015-10-23 20:37:08 +0000473 return true;
474
Hal Finkel60db0582014-09-07 18:57:58 +0000475 while (!WorkSet.empty()) {
476 const Value *V = WorkSet.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +0000477 if (!Visited.insert(V).second)
Hal Finkel60db0582014-09-07 18:57:58 +0000478 continue;
479
480 // If all uses of this value are ephemeral, then so is this value.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000481 if (llvm::all_of(V->users(), [&](const User *U) {
482 return EphValues.count(U);
483 })) {
Hal Finkel60db0582014-09-07 18:57:58 +0000484 if (V == E)
485 return true;
486
Hal Finkelb03dd4b2017-08-14 17:11:43 +0000487 if (V == I || isSafeToSpeculativelyExecute(V)) {
488 EphValues.insert(V);
489 if (const User *U = dyn_cast<User>(V))
490 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
491 J != JE; ++J)
492 WorkSet.push_back(*J);
493 }
Hal Finkel60db0582014-09-07 18:57:58 +0000494 }
495 }
496
497 return false;
498}
499
500// Is this an intrinsic that cannot be speculated but also cannot trap?
Haicheng Wua4461512017-12-15 14:34:41 +0000501bool llvm::isAssumeLikeIntrinsic(const Instruction *I) {
Hal Finkel60db0582014-09-07 18:57:58 +0000502 if (const CallInst *CI = dyn_cast<CallInst>(I))
503 if (Function *F = CI->getCalledFunction())
504 switch (F->getIntrinsicID()) {
505 default: break;
506 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
507 case Intrinsic::assume:
Dan Gohman2c74fe92017-11-08 21:59:51 +0000508 case Intrinsic::sideeffect:
Hal Finkel60db0582014-09-07 18:57:58 +0000509 case Intrinsic::dbg_declare:
510 case Intrinsic::dbg_value:
Shiva Chen2c864552018-05-09 02:40:45 +0000511 case Intrinsic::dbg_label:
Hal Finkel60db0582014-09-07 18:57:58 +0000512 case Intrinsic::invariant_start:
513 case Intrinsic::invariant_end:
514 case Intrinsic::lifetime_start:
515 case Intrinsic::lifetime_end:
516 case Intrinsic::objectsize:
517 case Intrinsic::ptr_annotation:
518 case Intrinsic::var_annotation:
519 return true;
520 }
521
522 return false;
523}
524
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000525bool llvm::isValidAssumeForContext(const Instruction *Inv,
526 const Instruction *CxtI,
527 const DominatorTree *DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000528 // There are two restrictions on the use of an assume:
529 // 1. The assume must dominate the context (or the control flow must
530 // reach the assume whenever it reaches the context).
531 // 2. The context must not be in the assume's set of ephemeral values
532 // (otherwise we will use the assume to prove that the condition
533 // feeding the assume is trivially true, thus causing the removal of
534 // the assume).
535
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000536 if (DT) {
Pete Cooper54a02552016-08-12 01:00:15 +0000537 if (DT->dominates(Inv, CxtI))
Hal Finkel60db0582014-09-07 18:57:58 +0000538 return true;
Pete Cooper54a02552016-08-12 01:00:15 +0000539 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
540 // We don't have a DT, but this trivially dominates.
541 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000542 }
543
Pete Cooper54a02552016-08-12 01:00:15 +0000544 // With or without a DT, the only remaining case we will check is if the
545 // instructions are in the same BB. Give up if that is not the case.
546 if (Inv->getParent() != CxtI->getParent())
547 return false;
548
Vedant Kumard3196742018-02-28 19:08:52 +0000549 // If we have a dom tree, then we now know that the assume doesn't dominate
Pete Cooper54a02552016-08-12 01:00:15 +0000550 // the other instruction. If we don't have a dom tree then we can check if
551 // the assume is first in the BB.
552 if (!DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000553 // Search forward from the assume until we reach the context (or the end
554 // of the block); the common case is that the assume will come first.
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000555 for (auto I = std::next(BasicBlock::const_iterator(Inv)),
Hal Finkel60db0582014-09-07 18:57:58 +0000556 IE = Inv->getParent()->end(); I != IE; ++I)
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000557 if (&*I == CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000558 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000559 }
560
Nikita Popov2a4f26b2019-08-13 17:15:42 +0000561 // Don't let an assume affect itself - this would cause the problems
562 // `isEphemeralValueOf` is trying to prevent, and it would also make
563 // the loop below go out of bounds.
564 if (Inv == CxtI)
565 return false;
566
Pete Cooper54a02552016-08-12 01:00:15 +0000567 // The context comes first, but they're both in the same block. Make sure
568 // there is nothing in between that might interrupt the control flow.
569 for (BasicBlock::const_iterator I =
570 std::next(BasicBlock::const_iterator(CxtI)), IE(Inv);
571 I != IE; ++I)
Nikita Popov2a4f26b2019-08-13 17:15:42 +0000572 if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
Pete Cooper54a02552016-08-12 01:00:15 +0000573 return false;
574
575 return !isEphemeralValueOf(Inv, CxtI);
Hal Finkel60db0582014-09-07 18:57:58 +0000576}
577
Craig Topperb45eabc2017-04-26 16:39:58 +0000578static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
579 unsigned Depth, const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000580 // Use of assumptions is context-sensitive. If we don't have a context, we
581 // cannot use them!
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000582 if (!Q.AC || !Q.CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000583 return;
584
Craig Topperb45eabc2017-04-26 16:39:58 +0000585 unsigned BitWidth = Known.getBitWidth();
Hal Finkel60db0582014-09-07 18:57:58 +0000586
Hal Finkel8a9a7832017-01-11 13:24:24 +0000587 // Note that the patterns below need to be kept in sync with the code
588 // in AssumptionCache::updateAffectedValues.
589
590 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000591 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +0000592 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000593 CallInst *I = cast<CallInst>(AssumeVH);
594 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
595 "Got assumption for the wrong function!");
596 if (Q.isExcluded(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000597 continue;
598
Vedant Kumard3196742018-02-28 19:08:52 +0000599 // Warning: This loop can end up being somewhat performance sensitive.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000600 // We're running this loop for once for each value queried resulting in a
601 // runtime of ~O(#assumes * #values).
Philip Reames00d3b272014-11-24 23:44:28 +0000602
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000603 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
604 "must be an assume intrinsic");
605
606 Value *Arg = I->getArgOperand(0);
607
608 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000609 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000610 Known.setAllOnes();
Hal Finkel60db0582014-09-07 18:57:58 +0000611 return;
612 }
Sanjay Patel96669962017-01-17 18:15:49 +0000613 if (match(Arg, m_Not(m_Specific(V))) &&
614 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
615 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000616 Known.setAllZero();
Sanjay Patel96669962017-01-17 18:15:49 +0000617 return;
618 }
Hal Finkel60db0582014-09-07 18:57:58 +0000619
David Majnemer9b609752014-12-12 23:59:29 +0000620 // The remaining tests are all recursive, so bail out if we hit the limit.
621 if (Depth == MaxDepth)
622 continue;
623
Sander de Smalen0e66db52019-04-10 16:24:48 +0000624 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
625 if (!Cmp)
626 continue;
627
Hal Finkel60db0582014-09-07 18:57:58 +0000628 Value *A, *B;
Sanjay Patel2a707032019-03-03 18:59:33 +0000629 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
Hal Finkel60db0582014-09-07 18:57:58 +0000630
631 CmpInst::Predicate Pred;
Igor Laevskycec8f472017-12-05 12:18:15 +0000632 uint64_t C;
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000633 switch (Cmp->getPredicate()) {
634 default:
635 break;
636 case ICmpInst::ICMP_EQ:
Sander de Smalen0e66db52019-04-10 16:24:48 +0000637 // assume(v = a)
638 if (match(Cmp, m_c_ICmp(Pred, m_V, m_Value(A))) &&
639 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
640 KnownBits RHSKnown(BitWidth);
641 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
642 Known.Zero |= RHSKnown.Zero;
643 Known.One |= RHSKnown.One;
644 // assume(v & b = a)
645 } else if (match(Cmp,
646 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
647 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
648 KnownBits RHSKnown(BitWidth);
649 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
650 KnownBits MaskKnown(BitWidth);
651 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel60db0582014-09-07 18:57:58 +0000652
Sander de Smalen0e66db52019-04-10 16:24:48 +0000653 // For those bits in the mask that are known to be one, we can propagate
654 // known bits from the RHS to V.
655 Known.Zero |= RHSKnown.Zero & MaskKnown.One;
656 Known.One |= RHSKnown.One & MaskKnown.One;
657 // assume(~(v & b) = a)
658 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
659 m_Value(A))) &&
660 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
661 KnownBits RHSKnown(BitWidth);
662 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
663 KnownBits MaskKnown(BitWidth);
664 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000665
Sander de Smalen0e66db52019-04-10 16:24:48 +0000666 // For those bits in the mask that are known to be one, we can propagate
667 // inverted known bits from the RHS to V.
668 Known.Zero |= RHSKnown.One & MaskKnown.One;
669 Known.One |= RHSKnown.Zero & MaskKnown.One;
670 // assume(v | b = a)
671 } else if (match(Cmp,
672 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
673 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
674 KnownBits RHSKnown(BitWidth);
675 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
676 KnownBits BKnown(BitWidth);
677 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000678
Sander de Smalen0e66db52019-04-10 16:24:48 +0000679 // For those bits in B that are known to be zero, we can propagate known
680 // bits from the RHS to V.
681 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
682 Known.One |= RHSKnown.One & BKnown.Zero;
683 // assume(~(v | b) = a)
684 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
685 m_Value(A))) &&
686 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
687 KnownBits RHSKnown(BitWidth);
688 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
689 KnownBits BKnown(BitWidth);
690 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000691
Sander de Smalen0e66db52019-04-10 16:24:48 +0000692 // For those bits in B that are known to be zero, we can propagate
693 // inverted known bits from the RHS to V.
694 Known.Zero |= RHSKnown.One & BKnown.Zero;
695 Known.One |= RHSKnown.Zero & BKnown.Zero;
696 // assume(v ^ b = a)
697 } else if (match(Cmp,
698 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
699 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
700 KnownBits RHSKnown(BitWidth);
701 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
702 KnownBits BKnown(BitWidth);
703 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000704
Sander de Smalen0e66db52019-04-10 16:24:48 +0000705 // For those bits in B that are known to be zero, we can propagate known
706 // bits from the RHS to V. For those bits in B that are known to be one,
707 // we can propagate inverted known bits from the RHS to V.
708 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
709 Known.One |= RHSKnown.One & BKnown.Zero;
710 Known.Zero |= RHSKnown.One & BKnown.One;
711 Known.One |= RHSKnown.Zero & BKnown.One;
712 // assume(~(v ^ b) = a)
713 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
714 m_Value(A))) &&
715 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
716 KnownBits RHSKnown(BitWidth);
717 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
718 KnownBits BKnown(BitWidth);
719 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000720
Sander de Smalen0e66db52019-04-10 16:24:48 +0000721 // For those bits in B that are known to be zero, we can propagate
722 // inverted known bits from the RHS to V. For those bits in B that are
723 // known to be one, we can propagate known bits from the RHS to V.
724 Known.Zero |= RHSKnown.One & BKnown.Zero;
725 Known.One |= RHSKnown.Zero & BKnown.Zero;
726 Known.Zero |= RHSKnown.Zero & BKnown.One;
727 Known.One |= RHSKnown.One & BKnown.One;
728 // assume(v << c = a)
729 } else if (match(Cmp, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
730 m_Value(A))) &&
731 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
732 KnownBits RHSKnown(BitWidth);
733 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
734 // For those bits in RHS that are known, we can propagate them to known
735 // bits in V shifted to the right by C.
736 RHSKnown.Zero.lshrInPlace(C);
737 Known.Zero |= RHSKnown.Zero;
738 RHSKnown.One.lshrInPlace(C);
739 Known.One |= RHSKnown.One;
740 // assume(~(v << c) = a)
741 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
742 m_Value(A))) &&
743 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
744 KnownBits RHSKnown(BitWidth);
745 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
746 // 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.
748 RHSKnown.One.lshrInPlace(C);
749 Known.Zero |= RHSKnown.One;
750 RHSKnown.Zero.lshrInPlace(C);
751 Known.One |= RHSKnown.Zero;
752 // assume(v >> c = a)
753 } else if (match(Cmp, m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)),
754 m_Value(A))) &&
755 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
756 KnownBits RHSKnown(BitWidth);
757 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
758 // For those bits in RHS that are known, we can propagate them to known
759 // bits in V shifted to the right by C.
760 Known.Zero |= RHSKnown.Zero << C;
761 Known.One |= RHSKnown.One << C;
762 // assume(~(v >> c) = a)
763 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_Shr(m_V, m_ConstantInt(C))),
764 m_Value(A))) &&
765 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
766 KnownBits RHSKnown(BitWidth);
767 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
768 // For those bits in RHS that are known, we can propagate them inverted
769 // to known bits in V shifted to the right by C.
770 Known.Zero |= RHSKnown.One << C;
771 Known.One |= RHSKnown.Zero << C;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000772 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000773 break;
774 case ICmpInst::ICMP_SGE:
Sander de Smalen0e66db52019-04-10 16:24:48 +0000775 // assume(v >=_s c) where c is non-negative
776 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
777 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
778 KnownBits RHSKnown(BitWidth);
779 computeKnownBits(A, RHSKnown, Depth + 1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000780
Sander de Smalen0e66db52019-04-10 16:24:48 +0000781 if (RHSKnown.isNonNegative()) {
782 // We know that the sign bit is zero.
783 Known.makeNonNegative();
784 }
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000785 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000786 break;
787 case ICmpInst::ICMP_SGT:
Sander de Smalen0e66db52019-04-10 16:24:48 +0000788 // assume(v >_s c) where c is at least -1.
789 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
790 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
791 KnownBits RHSKnown(BitWidth);
792 computeKnownBits(A, RHSKnown, Depth + 1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000793
Sander de Smalen0e66db52019-04-10 16:24:48 +0000794 if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
795 // We know that the sign bit is zero.
796 Known.makeNonNegative();
797 }
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000798 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000799 break;
800 case ICmpInst::ICMP_SLE:
Sander de Smalen0e66db52019-04-10 16:24:48 +0000801 // assume(v <=_s c) where c is negative
802 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
803 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
804 KnownBits RHSKnown(BitWidth);
805 computeKnownBits(A, RHSKnown, Depth + 1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000806
Sander de Smalen0e66db52019-04-10 16:24:48 +0000807 if (RHSKnown.isNegative()) {
808 // We know that the sign bit is one.
809 Known.makeNegative();
810 }
811 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000812 break;
813 case ICmpInst::ICMP_SLT:
Sander de Smalen0e66db52019-04-10 16:24:48 +0000814 // assume(v <_s c) where c is non-positive
815 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
816 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
817 KnownBits RHSKnown(BitWidth);
818 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
819
820 if (RHSKnown.isZero() || RHSKnown.isNegative()) {
821 // We know that the sign bit is one.
822 Known.makeNegative();
823 }
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000824 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000825 break;
826 case ICmpInst::ICMP_ULE:
827 // assume(v <=_u c)
Sander de Smalen0e66db52019-04-10 16:24:48 +0000828 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
829 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
830 KnownBits RHSKnown(BitWidth);
831 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000832
Sander de Smalen0e66db52019-04-10 16:24:48 +0000833 // Whatever high bits in c are zero are known to be zero.
Craig Topper8df66c62017-05-12 17:20:30 +0000834 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
Sander de Smalen0e66db52019-04-10 16:24:48 +0000835 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000836 break;
837 case ICmpInst::ICMP_ULT:
Sander de Smalen0e66db52019-04-10 16:24:48 +0000838 // assume(v <_u c)
Sander de Smalen0e66db52019-04-10 16:24:48 +0000839 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
840 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
841 KnownBits RHSKnown(BitWidth);
842 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
843
844 // If the RHS is known zero, then this assumption must be wrong (nothing
845 // is unsigned less than zero). Signal a conflict and get out of here.
846 if (RHSKnown.isZero()) {
847 Known.Zero.setAllBits();
848 Known.One.setAllBits();
849 break;
850 }
851
852 // Whatever high bits in c are zero are known to be zero (if c is a power
853 // of 2, then one more).
854 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
855 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
856 else
857 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
858 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000859 break;
Hal Finkel60db0582014-09-07 18:57:58 +0000860 }
861 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000862
863 // If assumptions conflict with each other or previous known bits, then we
Sanjay Patel54656ca2017-02-06 18:26:06 +0000864 // have a logical fallacy. It's possible that the assumption is not reachable,
865 // so this isn't a real bug. On the other hand, the program may have undefined
866 // behavior, or we might have a bug in the compiler. We can't assert/crash, so
867 // clear out the known bits, try to warn the user, and hope for the best.
Craig Topperb45eabc2017-04-26 16:39:58 +0000868 if (Known.Zero.intersects(Known.One)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000869 Known.resetAll();
Sanjay Patel54656ca2017-02-06 18:26:06 +0000870
Vivek Pandya95906582017-10-11 17:12:59 +0000871 if (Q.ORE)
872 Q.ORE->emit([&]() {
873 auto *CxtI = const_cast<Instruction *>(Q.CxtI);
874 return OptimizationRemarkAnalysis("value-tracking", "BadAssumption",
875 CxtI)
876 << "Detected conflicting code assumptions. Program may "
877 "have undefined behavior, or compiler may have "
878 "internal error.";
879 });
Sanjay Patel25f6d712017-02-01 15:41:32 +0000880 }
Hal Finkel60db0582014-09-07 18:57:58 +0000881}
882
Sanjay Patelb7d12382017-10-16 14:46:37 +0000883/// Compute known bits from a shift operator, including those with a
884/// non-constant shift amount. Known is the output of this function. Known2 is a
885/// pre-allocated temporary with the same bit width as Known. KZF and KOF are
Vedant Kumard3196742018-02-28 19:08:52 +0000886/// operator-specific functions that, given the known-zero or known-one bits
Sanjay Patelb7d12382017-10-16 14:46:37 +0000887/// respectively, and a shift amount, compute the implied known-zero or
888/// known-one bits of the shift operator's result respectively for that shift
889/// amount. The results from calling KZF and KOF are conservatively combined for
890/// all permitted shift amounts.
David Majnemer54690dc2016-08-23 20:52:00 +0000891static void computeKnownBitsFromShiftOperator(
Craig Topperb45eabc2017-04-26 16:39:58 +0000892 const Operator *I, KnownBits &Known, KnownBits &Known2,
893 unsigned Depth, const Query &Q,
Sam McCalld0d43e62017-12-04 12:51:49 +0000894 function_ref<APInt(const APInt &, unsigned)> KZF,
895 function_ref<APInt(const APInt &, unsigned)> KOF) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000896 unsigned BitWidth = Known.getBitWidth();
Hal Finkelf2199b22015-10-23 20:37:08 +0000897
898 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
899 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
900
Craig Topperb45eabc2017-04-26 16:39:58 +0000901 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Sam McCalld0d43e62017-12-04 12:51:49 +0000902 Known.Zero = KZF(Known.Zero, ShiftAmt);
903 Known.One = KOF(Known.One, ShiftAmt);
Sanjay Patele272be72017-10-12 17:31:46 +0000904 // If the known bits conflict, this must be an overflowing left shift, so
905 // the shift result is poison. We can return anything we want. Choose 0 for
906 // the best folding opportunity.
907 if (Known.hasConflict())
908 Known.setAllZero();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +0000909
Hal Finkelf2199b22015-10-23 20:37:08 +0000910 return;
911 }
912
Craig Topperb45eabc2017-04-26 16:39:58 +0000913 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000914
Sanjay Patele272be72017-10-12 17:31:46 +0000915 // If the shift amount could be greater than or equal to the bit-width of the
916 // LHS, the value could be poison, but bail out because the check below is
917 // expensive. TODO: Should we just carry on?
Craig Topperb45eabc2017-04-26 16:39:58 +0000918 if ((~Known.Zero).uge(BitWidth)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000919 Known.resetAll();
Oliver Stannard06204112017-03-14 10:13:17 +0000920 return;
921 }
922
Craig Topperb45eabc2017-04-26 16:39:58 +0000923 // Note: We cannot use Known.Zero.getLimitedValue() here, because if
Hal Finkelf2199b22015-10-23 20:37:08 +0000924 // BitWidth > 64 and any upper bits are known, we'll end up returning the
925 // limit value (which implies all bits are known).
Craig Topperb45eabc2017-04-26 16:39:58 +0000926 uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
927 uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
Hal Finkelf2199b22015-10-23 20:37:08 +0000928
929 // It would be more-clearly correct to use the two temporaries for this
930 // calculation. Reusing the APInts here to prevent unnecessary allocations.
Craig Topperf0aeee02017-05-05 17:36:09 +0000931 Known.resetAll();
Hal Finkelf2199b22015-10-23 20:37:08 +0000932
James Molloy493e57d2015-10-26 14:10:46 +0000933 // If we know the shifter operand is nonzero, we can sometimes infer more
934 // known bits. However this is expensive to compute, so be lazy about it and
935 // only compute it when absolutely necessary.
936 Optional<bool> ShifterOperandIsNonZero;
937
Hal Finkelf2199b22015-10-23 20:37:08 +0000938 // Early exit if we can't constrain any well-defined shift amount.
Craig Topperf93b7b12017-06-14 17:04:59 +0000939 if (!(ShiftAmtKZ & (PowerOf2Ceil(BitWidth) - 1)) &&
940 !(ShiftAmtKO & (PowerOf2Ceil(BitWidth) - 1))) {
Sanjay Patelb7d12382017-10-16 14:46:37 +0000941 ShifterOperandIsNonZero = isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000942 if (!*ShifterOperandIsNonZero)
943 return;
944 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000945
Craig Topperb45eabc2017-04-26 16:39:58 +0000946 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000947
Craig Topperb45eabc2017-04-26 16:39:58 +0000948 Known.Zero.setAllBits();
949 Known.One.setAllBits();
Hal Finkelf2199b22015-10-23 20:37:08 +0000950 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
951 // Combine the shifted known input bits only for those shift amounts
952 // compatible with its known constraints.
953 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
954 continue;
955 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
956 continue;
James Molloy493e57d2015-10-26 14:10:46 +0000957 // If we know the shifter is nonzero, we may be able to infer more known
958 // bits. This check is sunk down as far as possible to avoid the expensive
959 // call to isKnownNonZero if the cheaper checks above fail.
960 if (ShiftAmt == 0) {
961 if (!ShifterOperandIsNonZero.hasValue())
962 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000963 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000964 if (*ShifterOperandIsNonZero)
965 continue;
966 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000967
Sam McCalld0d43e62017-12-04 12:51:49 +0000968 Known.Zero &= KZF(Known2.Zero, ShiftAmt);
969 Known.One &= KOF(Known2.One, ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +0000970 }
971
Sanjay Patele272be72017-10-12 17:31:46 +0000972 // If the known bits conflict, the result is poison. Return a 0 and hope the
973 // caller can further optimize that.
974 if (Known.hasConflict())
975 Known.setAllZero();
Hal Finkelf2199b22015-10-23 20:37:08 +0000976}
977
Craig Topperb45eabc2017-04-26 16:39:58 +0000978static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known,
979 unsigned Depth, const Query &Q) {
980 unsigned BitWidth = Known.getBitWidth();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000981
Craig Topperb45eabc2017-04-26 16:39:58 +0000982 KnownBits Known2(Known);
Dan Gohman80ca01c2009-07-17 20:47:02 +0000983 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +0000984 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +0000985 case Instruction::Load:
Florian Hahn19f9e322018-08-17 14:39:04 +0000986 if (MDNode *MD =
987 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +0000988 computeKnownBitsFromRangeMetadata(*MD, Known);
Jay Foad5a29c362014-05-15 12:12:55 +0000989 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000990 case Instruction::And: {
991 // If either the LHS or the RHS are Zero, the result is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +0000992 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
993 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000994
Chris Lattner965c7692008-06-02 01:18:21 +0000995 // Output known-1 bits are only known if set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000996 Known.One &= Known2.One;
Chris Lattner965c7692008-06-02 01:18:21 +0000997 // Output known-0 are known to be clear if zero in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000998 Known.Zero |= Known2.Zero;
Philip Reames2d858742015-11-10 18:46:14 +0000999
1000 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1001 // here we handle the more general case of adding any odd number by
1002 // matching the form add(x, add(x, y)) where y is odd.
1003 // TODO: This could be generalized to clearing any bit set in y where the
1004 // following bit is known to be unset in y.
Roman Lebedev6959b8e2018-04-27 21:23:20 +00001005 Value *X = nullptr, *Y = nullptr;
Craig Topperb45eabc2017-04-26 16:39:58 +00001006 if (!Known.Zero[0] && !Known.One[0] &&
Roman Lebedev6959b8e2018-04-27 21:23:20 +00001007 match(I, m_c_BinOp(m_Value(X), m_Add(m_Deferred(X), m_Value(Y))))) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001008 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001009 computeKnownBits(Y, Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001010 if (Known2.countMinTrailingOnes() > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001011 Known.Zero.setBit(0);
Philip Reames2d858742015-11-10 18:46:14 +00001012 }
Jay Foad5a29c362014-05-15 12:12:55 +00001013 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001014 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001015 case Instruction::Or:
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 only known if clear in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001020 Known.Zero &= Known2.Zero;
Chris Lattner965c7692008-06-02 01:18:21 +00001021 // Output known-1 are known to be set if set in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001022 Known.One |= Known2.One;
Jay Foad5a29c362014-05-15 12:12:55 +00001023 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001024 case Instruction::Xor: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001025 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
1026 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001027
Chris Lattner965c7692008-06-02 01:18:21 +00001028 // Output known-0 bits are known if clear or set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001029 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
Chris Lattner965c7692008-06-02 01:18:21 +00001030 // Output known-1 are known to be set if set in only one of the LHS, RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001031 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
1032 Known.Zero = std::move(KnownZeroOut);
Jay Foad5a29c362014-05-15 12:12:55 +00001033 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001034 }
1035 case Instruction::Mul: {
Florian Hahn19f9e322018-08-17 14:39:04 +00001036 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Craig Topperb45eabc2017-04-26 16:39:58 +00001037 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, Known,
1038 Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001039 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001040 }
1041 case Instruction::UDiv: {
1042 // For the purposes of computing leading zeros we can conservatively
1043 // treat a udiv as a logical right shift by the power of 2 known to
1044 // be less than the denominator.
Craig Topperb45eabc2017-04-26 16:39:58 +00001045 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001046 unsigned LeadZ = Known2.countMinLeadingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001047
Craig Topperf0aeee02017-05-05 17:36:09 +00001048 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001049 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001050 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
1051 if (RHSMaxLeadingZeros != BitWidth)
1052 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
Chris Lattner965c7692008-06-02 01:18:21 +00001053
Craig Topperb45eabc2017-04-26 16:39:58 +00001054 Known.Zero.setHighBits(LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +00001055 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001056 }
David Majnemera19d0f22016-08-06 08:16:00 +00001057 case Instruction::Select: {
Simon Pilgrimf62293e2019-09-23 13:15:52 +00001058 const Value *LHS = nullptr, *RHS = nullptr;
David Majnemera19d0f22016-08-06 08:16:00 +00001059 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
1060 if (SelectPatternResult::isMinOrMax(SPF)) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001061 computeKnownBits(RHS, Known, Depth + 1, Q);
1062 computeKnownBits(LHS, Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +00001063 } else {
Craig Topperb45eabc2017-04-26 16:39:58 +00001064 computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
1065 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +00001066 }
1067
1068 unsigned MaxHighOnes = 0;
1069 unsigned MaxHighZeros = 0;
1070 if (SPF == SPF_SMAX) {
1071 // If both sides are negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +00001072 if (Known.isNegative() && Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001073 // We can derive a lower bound on the result by taking the max of the
1074 // leading one bits.
Craig Topper8df66c62017-05-12 17:20:30 +00001075 MaxHighOnes =
1076 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001077 // If either side is non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +00001078 else if (Known.isNonNegative() || Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001079 MaxHighZeros = 1;
1080 } else if (SPF == SPF_SMIN) {
1081 // If both sides are non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +00001082 if (Known.isNonNegative() && Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001083 // We can derive an upper bound on the result by taking the max of the
1084 // leading zero bits.
Craig Topper8df66c62017-05-12 17:20:30 +00001085 MaxHighZeros = std::max(Known.countMinLeadingZeros(),
1086 Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +00001087 // If either side is negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +00001088 else if (Known.isNegative() || Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001089 MaxHighOnes = 1;
1090 } else if (SPF == SPF_UMAX) {
1091 // We can derive a lower bound on the result by taking the max of the
1092 // leading one bits.
1093 MaxHighOnes =
Craig Topper8df66c62017-05-12 17:20:30 +00001094 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001095 } else if (SPF == SPF_UMIN) {
1096 // We can derive an upper bound on the result by taking the max of the
1097 // leading zero bits.
1098 MaxHighZeros =
Craig Topper8df66c62017-05-12 17:20:30 +00001099 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topper8f77dca2018-05-25 19:18:09 +00001100 } else if (SPF == SPF_ABS) {
1101 // RHS from matchSelectPattern returns the negation part of abs pattern.
1102 // If the negate has an NSW flag we can assume the sign bit of the result
1103 // will be 0 because that makes abs(INT_MIN) undefined.
Craig Topper66c08432019-08-07 18:28:16 +00001104 if (match(RHS, m_Neg(m_Specific(LHS))) &&
1105 Q.IIQ.hasNoSignedWrap(cast<Instruction>(RHS)))
Craig Topper8f77dca2018-05-25 19:18:09 +00001106 MaxHighZeros = 1;
David Majnemera19d0f22016-08-06 08:16:00 +00001107 }
1108
Chris Lattner965c7692008-06-02 01:18:21 +00001109 // Only known if known in both the LHS and RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001110 Known.One &= Known2.One;
1111 Known.Zero &= Known2.Zero;
David Majnemera19d0f22016-08-06 08:16:00 +00001112 if (MaxHighOnes > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001113 Known.One.setHighBits(MaxHighOnes);
David Majnemera19d0f22016-08-06 08:16:00 +00001114 if (MaxHighZeros > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001115 Known.Zero.setHighBits(MaxHighZeros);
Jay Foad5a29c362014-05-15 12:12:55 +00001116 break;
David Majnemera19d0f22016-08-06 08:16:00 +00001117 }
Chris Lattner965c7692008-06-02 01:18:21 +00001118 case Instruction::FPTrunc:
1119 case Instruction::FPExt:
1120 case Instruction::FPToUI:
1121 case Instruction::FPToSI:
1122 case Instruction::SIToFP:
1123 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +00001124 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +00001125 case Instruction::PtrToInt:
1126 case Instruction::IntToPtr:
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001127 // Fall through and handle them the same as zext/trunc.
1128 LLVM_FALLTHROUGH;
Chris Lattner965c7692008-06-02 01:18:21 +00001129 case Instruction::ZExt:
1130 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +00001131 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +00001132
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001133 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +00001134 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1135 // which fall through here.
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001136 Type *ScalarTy = SrcTy->getScalarType();
1137 SrcBitWidth = ScalarTy->isPointerTy() ?
1138 Q.DL.getIndexTypeSizeInBits(ScalarTy) :
1139 Q.DL.getTypeSizeInBits(ScalarTy);
Nadav Rotem15198e92012-10-26 17:17:05 +00001140
1141 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Bjorn Petterssond30f3082019-02-28 15:45:29 +00001142 Known = Known.zextOrTrunc(SrcBitWidth, false);
Craig Topperb45eabc2017-04-26 16:39:58 +00001143 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Bjorn Petterssond30f3082019-02-28 15:45:29 +00001144 Known = Known.zextOrTrunc(BitWidth, true /* ExtendedBitsAreKnownZero */);
Jay Foad5a29c362014-05-15 12:12:55 +00001145 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001146 }
1147 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +00001148 Type *SrcTy = I->getOperand(0)->getType();
Vedant Kumarb3091da2018-07-06 20:17:42 +00001149 if (SrcTy->isIntOrPtrTy() &&
Chris Lattneredb84072009-07-02 16:04:08 +00001150 // TODO: For now, not handling conversions like:
1151 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +00001152 !I->getType()->isVectorTy()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001153 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +00001154 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001155 }
1156 break;
1157 }
1158 case Instruction::SExt: {
1159 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001160 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +00001161
Craig Topperd938fd12017-05-03 22:07:25 +00001162 Known = Known.trunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001163 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001164 // If the sign bit of the input is known set or clear, then we know the
1165 // top bits of the result.
Craig Topperd938fd12017-05-03 22:07:25 +00001166 Known = Known.sext(BitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001167 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001168 }
Hal Finkelf2199b22015-10-23 20:37:08 +00001169 case Instruction::Shl: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001170 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Florian Hahn19f9e322018-08-17 14:39:04 +00001171 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Sam McCalld0d43e62017-12-04 12:51:49 +00001172 auto KZF = [NSW](const APInt &KnownZero, unsigned ShiftAmt) {
1173 APInt KZResult = KnownZero << ShiftAmt;
1174 KZResult.setLowBits(ShiftAmt); // Low bits known 0.
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001175 // If this shift has "nsw" keyword, then the result is either a poison
1176 // value or has the same sign bit as the first operand.
Sam McCalld0d43e62017-12-04 12:51:49 +00001177 if (NSW && KnownZero.isSignBitSet())
1178 KZResult.setSignBit();
1179 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001180 };
1181
Sam McCalld0d43e62017-12-04 12:51:49 +00001182 auto KOF = [NSW](const APInt &KnownOne, unsigned ShiftAmt) {
1183 APInt KOResult = KnownOne << ShiftAmt;
1184 if (NSW && KnownOne.isSignBitSet())
1185 KOResult.setSignBit();
1186 return KOResult;
1187 };
1188
1189 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001190 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001191 }
1192 case Instruction::LShr: {
Sanjay Patelb7d12382017-10-16 14:46:37 +00001193 // (lshr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Sam McCalld0d43e62017-12-04 12:51:49 +00001194 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1195 APInt KZResult = KnownZero.lshr(ShiftAmt);
1196 // High bits known zero.
1197 KZResult.setHighBits(ShiftAmt);
1198 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001199 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001200
Sam McCalld0d43e62017-12-04 12:51:49 +00001201 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1202 return KnownOne.lshr(ShiftAmt);
1203 };
1204
1205 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001206 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001207 }
1208 case Instruction::AShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001209 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Sam McCalld0d43e62017-12-04 12:51:49 +00001210 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1211 return KnownZero.ashr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001212 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001213
Sam McCalld0d43e62017-12-04 12:51:49 +00001214 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1215 return KnownOne.ashr(ShiftAmt);
1216 };
1217
1218 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001219 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001220 }
Chris Lattner965c7692008-06-02 01:18:21 +00001221 case Instruction::Sub: {
Florian Hahn19f9e322018-08-17 14:39:04 +00001222 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Jay Foada0653a32014-05-14 21:14:37 +00001223 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001224 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001225 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001226 }
Chris Lattner965c7692008-06-02 01:18:21 +00001227 case Instruction::Add: {
Florian Hahn19f9e322018-08-17 14:39:04 +00001228 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Jay Foada0653a32014-05-14 21:14:37 +00001229 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001230 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001231 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001232 }
1233 case Instruction::SRem:
1234 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001235 APInt RA = Rem->getValue().abs();
1236 if (RA.isPowerOf2()) {
1237 APInt LowBits = RA - 1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001238 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001239
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001240 // The low bits of the first operand are unchanged by the srem.
Craig Topperb45eabc2017-04-26 16:39:58 +00001241 Known.Zero = Known2.Zero & LowBits;
1242 Known.One = Known2.One & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001243
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001244 // If the first operand is non-negative or has all low bits zero, then
1245 // the upper bits are all zero.
Craig Topperca48af32017-04-29 16:43:11 +00001246 if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
Craig Topperb45eabc2017-04-26 16:39:58 +00001247 Known.Zero |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001248
1249 // If the first operand is negative and not all low bits are zero, then
1250 // the upper bits are all one.
Craig Topperca48af32017-04-29 16:43:11 +00001251 if (Known2.isNegative() && LowBits.intersects(Known2.One))
Craig Topperb45eabc2017-04-26 16:39:58 +00001252 Known.One |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001253
Craig Topperb45eabc2017-04-26 16:39:58 +00001254 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Craig Topperda886c62017-04-16 21:46:12 +00001255 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001256 }
1257 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001258
1259 // The sign bit is the LHS's sign bit, except when the result of the
1260 // remainder is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +00001261 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topperda886c62017-04-16 21:46:12 +00001262 // If it's known zero, our sign bit is also zero.
Craig Topperca48af32017-04-29 16:43:11 +00001263 if (Known2.isNonNegative())
1264 Known.makeNonNegative();
Nick Lewyckye4679792011-03-07 01:50:10 +00001265
Chris Lattner965c7692008-06-02 01:18:21 +00001266 break;
1267 case Instruction::URem: {
1268 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001269 const APInt &RA = Rem->getValue();
Chris Lattner965c7692008-06-02 01:18:21 +00001270 if (RA.isPowerOf2()) {
1271 APInt LowBits = (RA - 1);
Craig Topperb45eabc2017-04-26 16:39:58 +00001272 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1273 Known.Zero |= ~LowBits;
1274 Known.One &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001275 break;
1276 }
1277 }
1278
1279 // Since the result is less than or equal to either operand, any leading
1280 // zero bits in either operand must also exist in the result.
Craig Topperb45eabc2017-04-26 16:39:58 +00001281 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1282 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001283
Craig Topper8df66c62017-05-12 17:20:30 +00001284 unsigned Leaders =
1285 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topperf0aeee02017-05-05 17:36:09 +00001286 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001287 Known.Zero.setHighBits(Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001288 break;
1289 }
1290
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001291 case Instruction::Alloca: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001292 const AllocaInst *AI = cast<AllocaInst>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001293 unsigned Align = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001294 if (Align == 0)
Eduard Burtescu90c44492016-01-18 00:10:01 +00001295 Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001296
Chris Lattner965c7692008-06-02 01:18:21 +00001297 if (Align > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001298 Known.Zero.setLowBits(countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001299 break;
1300 }
1301 case Instruction::GetElementPtr: {
1302 // Analyze all of the subscripts of this getelementptr instruction
1303 // to determine if we can prove known low zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001304 KnownBits LocalKnown(BitWidth);
1305 computeKnownBits(I->getOperand(0), LocalKnown, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001306 unsigned TrailZ = LocalKnown.countMinTrailingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001307
1308 gep_type_iterator GTI = gep_type_begin(I);
1309 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1310 Value *Index = I->getOperand(i);
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001311 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chris Lattner965c7692008-06-02 01:18:21 +00001312 // Handle struct member offset arithmetic.
Matt Arsenault74742a12013-08-19 21:43:16 +00001313
1314 // Handle case when index is vector zeroinitializer
1315 Constant *CIndex = cast<Constant>(Index);
1316 if (CIndex->isZeroValue())
1317 continue;
1318
1319 if (CIndex->getType()->isVectorTy())
1320 Index = CIndex->getSplatValue();
1321
Chris Lattner965c7692008-06-02 01:18:21 +00001322 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001323 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001324 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001325 TrailZ = std::min<unsigned>(TrailZ,
1326 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001327 } else {
1328 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001329 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001330 if (!IndexedTy->isSized()) {
1331 TrailZ = 0;
1332 break;
1333 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001334 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001335 uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
Craig Topperb45eabc2017-04-26 16:39:58 +00001336 LocalKnown.Zero = LocalKnown.One = APInt(GEPOpiBits, 0);
1337 computeKnownBits(Index, LocalKnown, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001338 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001339 unsigned(countTrailingZeros(TypeSize) +
Craig Topper8df66c62017-05-12 17:20:30 +00001340 LocalKnown.countMinTrailingZeros()));
Chris Lattner965c7692008-06-02 01:18:21 +00001341 }
1342 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001343
Craig Topperb45eabc2017-04-26 16:39:58 +00001344 Known.Zero.setLowBits(TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001345 break;
1346 }
1347 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001348 const PHINode *P = cast<PHINode>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001349 // Handle the case of a simple two-predecessor recurrence PHI.
1350 // There's a lot more that could theoretically be done here, but
1351 // this is sufficient to catch some interesting cases.
1352 if (P->getNumIncomingValues() == 2) {
1353 for (unsigned i = 0; i != 2; ++i) {
1354 Value *L = P->getIncomingValue(i);
1355 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001356 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001357 if (!LU)
1358 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001359 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001360 // Check for operations that have the property that if
1361 // both their operands have low zero bits, the result
Artur Pilipenkobc76eca2016-08-22 13:14:07 +00001362 // will have low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001363 if (Opcode == Instruction::Add ||
1364 Opcode == Instruction::Sub ||
1365 Opcode == Instruction::And ||
1366 Opcode == Instruction::Or ||
1367 Opcode == Instruction::Mul) {
1368 Value *LL = LU->getOperand(0);
1369 Value *LR = LU->getOperand(1);
1370 // Find a recurrence.
1371 if (LL == I)
1372 L = LR;
1373 else if (LR == I)
1374 L = LL;
1375 else
Florian Hahn75be1a92019-08-16 09:15:02 +00001376 continue; // Check for recurrence with L and R flipped.
Chris Lattner965c7692008-06-02 01:18:21 +00001377 // Ok, we have a PHI of the form L op= R. Check for low
1378 // zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001379 computeKnownBits(R, Known2, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001380
1381 // We need to take the minimum number of known bits
Craig Topperb45eabc2017-04-26 16:39:58 +00001382 KnownBits Known3(Known);
1383 computeKnownBits(L, Known3, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001384
Craig Topper8df66c62017-05-12 17:20:30 +00001385 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1386 Known3.countMinTrailingZeros()));
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001387
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001388 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU);
Florian Hahn19f9e322018-08-17 14:39:04 +00001389 if (OverflowOp && Q.IIQ.hasNoSignedWrap(OverflowOp)) {
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001390 // If initial value of recurrence is nonnegative, and we are adding
1391 // a nonnegative number with nsw, the result can only be nonnegative
1392 // or poison value regardless of the number of times we execute the
1393 // add in phi recurrence. If initial value is negative and we are
1394 // adding a negative number with nsw, the result can only be
1395 // negative or poison value. Similar arguments apply to sub and mul.
1396 //
1397 // (add non-negative, non-negative) --> non-negative
1398 // (add negative, negative) --> negative
1399 if (Opcode == Instruction::Add) {
Craig Topperca48af32017-04-29 16:43:11 +00001400 if (Known2.isNonNegative() && Known3.isNonNegative())
1401 Known.makeNonNegative();
1402 else if (Known2.isNegative() && Known3.isNegative())
1403 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001404 }
1405
1406 // (sub nsw non-negative, negative) --> non-negative
1407 // (sub nsw negative, non-negative) --> negative
1408 else if (Opcode == Instruction::Sub && LL == I) {
Craig Topperca48af32017-04-29 16:43:11 +00001409 if (Known2.isNonNegative() && Known3.isNegative())
1410 Known.makeNonNegative();
1411 else if (Known2.isNegative() && Known3.isNonNegative())
1412 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001413 }
1414
1415 // (mul nsw non-negative, non-negative) --> non-negative
Craig Topperca48af32017-04-29 16:43:11 +00001416 else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1417 Known3.isNonNegative())
1418 Known.makeNonNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001419 }
1420
Chris Lattner965c7692008-06-02 01:18:21 +00001421 break;
1422 }
1423 }
1424 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001425
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001426 // Unreachable blocks may have zero-operand PHI nodes.
1427 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001428 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001429
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001430 // Otherwise take the unions of the known bit sets of the operands,
1431 // taking conservative care to avoid excessive recursion.
Craig Topperb45eabc2017-04-26 16:39:58 +00001432 if (Depth < MaxDepth - 1 && !Known.Zero && !Known.One) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001433 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001434 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001435 break;
1436
Craig Topperb45eabc2017-04-26 16:39:58 +00001437 Known.Zero.setAllBits();
1438 Known.One.setAllBits();
Pete Cooper833f34d2015-05-12 20:05:31 +00001439 for (Value *IncValue : P->incoming_values()) {
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001440 // Skip direct self references.
Pete Cooper833f34d2015-05-12 20:05:31 +00001441 if (IncValue == P) continue;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001442
Craig Topperb45eabc2017-04-26 16:39:58 +00001443 Known2 = KnownBits(BitWidth);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001444 // Recurse, but cap the recursion to one level, because we don't
1445 // want to waste time spinning around in loops.
Craig Topperb45eabc2017-04-26 16:39:58 +00001446 computeKnownBits(IncValue, Known2, MaxDepth - 1, Q);
1447 Known.Zero &= Known2.Zero;
1448 Known.One &= Known2.One;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001449 // If all bits have been ruled out, there's no need to check
1450 // more operands.
Craig Topperb45eabc2017-04-26 16:39:58 +00001451 if (!Known.Zero && !Known.One)
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001452 break;
1453 }
1454 }
Chris Lattner965c7692008-06-02 01:18:21 +00001455 break;
1456 }
1457 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001458 case Instruction::Invoke:
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001459 // If range metadata is attached to this call, set known bits from that,
1460 // and then intersect with known bits based on other properties of the
1461 // function.
Florian Hahn19f9e322018-08-17 14:39:04 +00001462 if (MDNode *MD =
1463 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +00001464 computeKnownBitsFromRangeMetadata(*MD, Known);
Pete Cooper35b00d52016-08-13 01:05:32 +00001465 if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001466 computeKnownBits(RV, Known2, Depth + 1, Q);
1467 Known.Zero |= Known2.Zero;
1468 Known.One |= Known2.One;
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001469 }
Pete Cooper35b00d52016-08-13 01:05:32 +00001470 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001471 switch (II->getIntrinsicID()) {
1472 default: break;
Chad Rosier85204292017-01-17 17:23:51 +00001473 case Intrinsic::bitreverse:
Craig Topperb45eabc2017-04-26 16:39:58 +00001474 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1475 Known.Zero |= Known2.Zero.reverseBits();
1476 Known.One |= Known2.One.reverseBits();
Chad Rosier85204292017-01-17 17:23:51 +00001477 break;
Philip Reames675418e2015-10-06 20:20:45 +00001478 case Intrinsic::bswap:
Craig Topperb45eabc2017-04-26 16:39:58 +00001479 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1480 Known.Zero |= Known2.Zero.byteSwap();
1481 Known.One |= Known2.One.byteSwap();
Philip Reames675418e2015-10-06 20:20:45 +00001482 break;
Craig Topper868813f2017-05-08 17:22:34 +00001483 case Intrinsic::ctlz: {
1484 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1485 // If we have a known 1, its position is our upper bound.
1486 unsigned PossibleLZ = Known2.One.countLeadingZeros();
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001487 // If this call is undefined for 0, the result will be less than 2^n.
1488 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
Craig Topper868813f2017-05-08 17:22:34 +00001489 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1490 unsigned LowBits = Log2_32(PossibleLZ)+1;
1491 Known.Zero.setBitsFrom(LowBits);
1492 break;
1493 }
1494 case Intrinsic::cttz: {
1495 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1496 // If we have a known 1, its position is our upper bound.
1497 unsigned PossibleTZ = Known2.One.countTrailingZeros();
1498 // If this call is undefined for 0, the result will be less than 2^n.
1499 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1500 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1501 unsigned LowBits = Log2_32(PossibleTZ)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001502 Known.Zero.setBitsFrom(LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001503 break;
1504 }
1505 case Intrinsic::ctpop: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001506 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001507 // We can bound the space the count needs. Also, bits known to be zero
1508 // can't contribute to the population.
Craig Topper8df66c62017-05-12 17:20:30 +00001509 unsigned BitsPossiblySet = Known2.countMaxPopulation();
Craig Topper66df10f2017-04-14 06:43:34 +00001510 unsigned LowBits = Log2_32(BitsPossiblySet)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001511 Known.Zero.setBitsFrom(LowBits);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001512 // TODO: we could bound KnownOne using the lower bound on the number
1513 // of bits which might be set provided by popcnt KnownOne2.
Chris Lattner965c7692008-06-02 01:18:21 +00001514 break;
1515 }
Nikita Popov687b92c2018-12-02 14:14:11 +00001516 case Intrinsic::fshr:
1517 case Intrinsic::fshl: {
1518 const APInt *SA;
1519 if (!match(I->getOperand(2), m_APInt(SA)))
1520 break;
1521
1522 // Normalize to funnel shift left.
1523 uint64_t ShiftAmt = SA->urem(BitWidth);
1524 if (II->getIntrinsicID() == Intrinsic::fshr)
1525 ShiftAmt = BitWidth - ShiftAmt;
1526
1527 KnownBits Known3(Known);
1528 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1529 computeKnownBits(I->getOperand(1), Known3, Depth + 1, Q);
1530
1531 Known.Zero =
1532 Known2.Zero.shl(ShiftAmt) | Known3.Zero.lshr(BitWidth - ShiftAmt);
1533 Known.One =
1534 Known2.One.shl(ShiftAmt) | Known3.One.lshr(BitWidth - ShiftAmt);
1535 break;
1536 }
Nikita Popoved3ca922019-03-01 20:07:04 +00001537 case Intrinsic::uadd_sat:
1538 case Intrinsic::usub_sat: {
1539 bool IsAdd = II->getIntrinsicID() == Intrinsic::uadd_sat;
1540 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1541 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1542
1543 // Add: Leading ones of either operand are preserved.
1544 // Sub: Leading zeros of LHS and leading ones of RHS are preserved
1545 // as leading zeros in the result.
1546 unsigned LeadingKnown;
1547 if (IsAdd)
1548 LeadingKnown = std::max(Known.countMinLeadingOnes(),
1549 Known2.countMinLeadingOnes());
1550 else
1551 LeadingKnown = std::max(Known.countMinLeadingZeros(),
1552 Known2.countMinLeadingOnes());
1553
1554 Known = KnownBits::computeForAddSub(
1555 IsAdd, /* NSW */ false, Known, Known2);
1556
1557 // We select between the operation result and all-ones/zero
1558 // respectively, so we can preserve known ones/zeros.
1559 if (IsAdd) {
1560 Known.One.setHighBits(LeadingKnown);
1561 Known.Zero.clearAllBits();
1562 } else {
1563 Known.Zero.setHighBits(LeadingKnown);
1564 Known.One.clearAllBits();
1565 }
1566 break;
1567 }
Chad Rosierb3628842011-05-26 23:13:19 +00001568 case Intrinsic::x86_sse42_crc32_64_64:
Craig Topperb45eabc2017-04-26 16:39:58 +00001569 Known.Zero.setBitsFrom(32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001570 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001571 }
1572 }
1573 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00001574 case Instruction::ExtractElement:
1575 // Look through extract element. At the moment we keep this simple and skip
1576 // tracking the specific element. But at least we might find information
1577 // valid for all elements of the vector (for example if vector is sign
1578 // extended, shifted, etc).
Craig Topperb45eabc2017-04-26 16:39:58 +00001579 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Bjorn Pettersson39616032016-10-06 09:56:21 +00001580 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001581 case Instruction::ExtractValue:
1582 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001583 const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001584 if (EVI->getNumIndices() != 1) break;
1585 if (EVI->getIndices()[0] == 0) {
1586 switch (II->getIntrinsicID()) {
1587 default: break;
1588 case Intrinsic::uadd_with_overflow:
1589 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001590 computeKnownBitsAddSub(true, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001591 II->getArgOperand(1), false, Known, Known2,
1592 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001593 break;
1594 case Intrinsic::usub_with_overflow:
1595 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001596 computeKnownBitsAddSub(false, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001597 II->getArgOperand(1), false, Known, Known2,
1598 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001599 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001600 case Intrinsic::umul_with_overflow:
1601 case Intrinsic::smul_with_overflow:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001602 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
Craig Topperb45eabc2017-04-26 16:39:58 +00001603 Known, Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001604 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001605 }
1606 }
1607 }
Chris Lattner965c7692008-06-02 01:18:21 +00001608 }
Jingyue Wu12b0c282015-06-15 05:46:29 +00001609}
1610
1611/// Determine which bits of V are known to be either zero or one and return
Craig Topper6e11a052017-05-08 16:22:48 +00001612/// them.
1613KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1614 KnownBits Known(getBitWidth(V->getType(), Q.DL));
1615 computeKnownBits(V, Known, Depth, Q);
1616 return Known;
1617}
1618
1619/// Determine which bits of V are known to be either zero or one and return
Craig Topperb45eabc2017-04-26 16:39:58 +00001620/// them in the Known bit set.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001621///
1622/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1623/// we cannot optimize based on the assumption that it is zero without changing
1624/// it to be an explicit zero. If we don't change it to zero, other code could
1625/// optimized based on the contradictory assumption that it is non-zero.
1626/// Because instcombine aggressively folds operations with undef args anyway,
1627/// this won't lose us code quality.
1628///
1629/// This function is defined on values with integer type, values with pointer
1630/// type, and vectors of integers. In the case
1631/// where V is a vector, known zero, and known one values are the
1632/// same width as the vector element, and the bit is set only if it is true
1633/// for all of the elements in the vector.
Craig Topperb45eabc2017-04-26 16:39:58 +00001634void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
1635 const Query &Q) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001636 assert(V && "No Value?");
1637 assert(Depth <= MaxDepth && "Limit Search Depth");
Craig Topperb45eabc2017-04-26 16:39:58 +00001638 unsigned BitWidth = Known.getBitWidth();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001639
Craig Topperfde47232017-07-09 07:04:03 +00001640 assert((V->getType()->isIntOrIntVectorTy(BitWidth) ||
Craig Topper95d23472017-07-09 07:04:00 +00001641 V->getType()->isPtrOrPtrVectorTy()) &&
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001642 "Not integer or pointer type!");
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001643
1644 Type *ScalarTy = V->getType()->getScalarType();
1645 unsigned ExpectedWidth = ScalarTy->isPointerTy() ?
1646 Q.DL.getIndexTypeSizeInBits(ScalarTy) : Q.DL.getTypeSizeInBits(ScalarTy);
1647 assert(ExpectedWidth == BitWidth && "V and Known should have same BitWidth");
Craig Topperd73c6b42017-03-23 07:06:39 +00001648 (void)BitWidth;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001649 (void)ExpectedWidth;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001650
Sanjay Patelc96f6db2016-09-16 21:20:36 +00001651 const APInt *C;
1652 if (match(V, m_APInt(C))) {
1653 // We know all of the bits for a scalar constant or a splat vector constant!
Craig Topperb45eabc2017-04-26 16:39:58 +00001654 Known.One = *C;
1655 Known.Zero = ~Known.One;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001656 return;
1657 }
1658 // Null and aggregate-zero are all-zeros.
Sanjay Patele8dc0902016-05-23 17:57:54 +00001659 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001660 Known.setAllZero();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001661 return;
1662 }
1663 // Handle a constant vector by taking the intersection of the known bits of
David Majnemer3918cdd2016-05-04 06:13:33 +00001664 // each element.
Pete Cooper35b00d52016-08-13 01:05:32 +00001665 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001666 // We know that CDS must be a vector of integers. Take the intersection of
1667 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001668 Known.Zero.setAllBits(); Known.One.setAllBits();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001669 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Craig Topperb98ee582017-10-21 16:35:39 +00001670 APInt Elt = CDS->getElementAsAPInt(i);
Craig Topperb45eabc2017-04-26 16:39:58 +00001671 Known.Zero &= ~Elt;
1672 Known.One &= Elt;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001673 }
1674 return;
1675 }
1676
Pete Cooper35b00d52016-08-13 01:05:32 +00001677 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
David Majnemer3918cdd2016-05-04 06:13:33 +00001678 // We know that CV must be a vector of integers. Take the intersection of
1679 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001680 Known.Zero.setAllBits(); Known.One.setAllBits();
David Majnemer3918cdd2016-05-04 06:13:33 +00001681 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1682 Constant *Element = CV->getAggregateElement(i);
1683 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1684 if (!ElementCI) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001685 Known.resetAll();
David Majnemer3918cdd2016-05-04 06:13:33 +00001686 return;
1687 }
Craig Topperb98ee582017-10-21 16:35:39 +00001688 const APInt &Elt = ElementCI->getValue();
Craig Topperb45eabc2017-04-26 16:39:58 +00001689 Known.Zero &= ~Elt;
1690 Known.One &= Elt;
David Majnemer3918cdd2016-05-04 06:13:33 +00001691 }
1692 return;
1693 }
1694
Jingyue Wu12b0c282015-06-15 05:46:29 +00001695 // Start out not knowing anything.
Craig Topperf0aeee02017-05-05 17:36:09 +00001696 Known.resetAll();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001697
Duncan P. N. Exon Smithb1b208a2016-09-24 20:42:02 +00001698 // We can't imply anything about undefs.
1699 if (isa<UndefValue>(V))
1700 return;
1701
1702 // There's no point in looking through other users of ConstantData for
1703 // assumptions. Confirm that we've handled them all.
1704 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1705
Jingyue Wu12b0c282015-06-15 05:46:29 +00001706 // Limit search depth.
1707 // All recursive calls that increase depth must come after this.
1708 if (Depth == MaxDepth)
1709 return;
1710
1711 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1712 // the bits of its aliasee.
Pete Cooper35b00d52016-08-13 01:05:32 +00001713 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001714 if (!GA->isInterposable())
Craig Topperb45eabc2017-04-26 16:39:58 +00001715 computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001716 return;
1717 }
1718
Pete Cooper35b00d52016-08-13 01:05:32 +00001719 if (const Operator *I = dyn_cast<Operator>(V))
Craig Topperb45eabc2017-04-26 16:39:58 +00001720 computeKnownBitsFromOperator(I, Known, Depth, Q);
Sanjay Patela67559c2015-09-25 20:12:43 +00001721
Craig Topperb45eabc2017-04-26 16:39:58 +00001722 // Aligned pointers have trailing zeros - refine Known.Zero set
Artur Pilipenko029d8532015-09-30 11:55:45 +00001723 if (V->getType()->isPointerTy()) {
Artur Pilipenkoae51afc2016-02-24 12:25:10 +00001724 unsigned Align = V->getPointerAlignment(Q.DL);
Artur Pilipenko029d8532015-09-30 11:55:45 +00001725 if (Align)
Craig Topperb45eabc2017-04-26 16:39:58 +00001726 Known.Zero.setLowBits(countTrailingZeros(Align));
Artur Pilipenko029d8532015-09-30 11:55:45 +00001727 }
1728
Craig Topperb45eabc2017-04-26 16:39:58 +00001729 // computeKnownBitsFromAssume strictly refines Known.
1730 // Therefore, we run them after computeKnownBitsFromOperator.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001731
1732 // Check whether a nearby assume intrinsic can determine some known bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001733 computeKnownBitsFromAssume(V, Known, Depth, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001734
Craig Topperb45eabc2017-04-26 16:39:58 +00001735 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001736}
1737
Sanjay Patelaee84212014-11-04 16:27:42 +00001738/// Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001739/// bit set when defined. For vectors return true if every element is known to
Sanjay Patelaee84212014-11-04 16:27:42 +00001740/// be a power of two when defined. Supports values with integer or pointer
Duncan Sandsd3951082011-01-25 09:38:29 +00001741/// types and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001742bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001743 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00001744 assert(Depth <= MaxDepth && "Limit Search Depth");
1745
Simon Pilgrim9f2ae7e2018-02-06 18:39:23 +00001746 // Attempt to match against constants.
1747 if (OrZero && match(V, m_Power2OrZero()))
1748 return true;
1749 if (match(V, m_Power2()))
1750 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001751
1752 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1753 // it is shifted off the end then the result is undefined.
1754 if (match(V, m_Shl(m_One(), m_Value())))
1755 return true;
1756
Craig Topperbcfd2d12017-04-20 16:56:25 +00001757 // (signmask) >>l X is clearly a power of two if the one is not shifted off
1758 // the bottom. If it is shifted off the bottom then the result is undefined.
1759 if (match(V, m_LShr(m_SignMask(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001760 return true;
1761
1762 // The remaining tests are all recursive, so bail out if we hit the limit.
1763 if (Depth++ == MaxDepth)
1764 return false;
1765
Craig Topper9f008862014-04-15 04:59:12 +00001766 Value *X = nullptr, *Y = nullptr;
Sanjay Patel41160c22015-12-30 22:40:52 +00001767 // A shift left or a logical shift right of a power of two is a power of two
1768 // or zero.
Duncan Sands985ba632011-10-28 18:30:05 +00001769 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
Sanjay Patel41160c22015-12-30 22:40:52 +00001770 match(V, m_LShr(m_Value(X), m_Value()))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001771 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
Duncan Sands985ba632011-10-28 18:30:05 +00001772
Pete Cooper35b00d52016-08-13 01:05:32 +00001773 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001774 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001775
Pete Cooper35b00d52016-08-13 01:05:32 +00001776 if (const SelectInst *SI = dyn_cast<SelectInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001777 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1778 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
Duncan Sandsba286d72011-10-26 20:55:21 +00001779
Duncan Sandsba286d72011-10-26 20:55:21 +00001780 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1781 // A power of two and'd with anything is a power of two or zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001782 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1783 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
Duncan Sandsba286d72011-10-26 20:55:21 +00001784 return true;
1785 // X & (-X) is always a power of two or zero.
1786 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1787 return true;
1788 return false;
1789 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001790
David Majnemerb7d54092013-07-30 21:01:36 +00001791 // Adding a power-of-two or zero to the same power-of-two or zero yields
1792 // either the original power-of-two, a larger power-of-two or zero.
1793 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001794 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
Florian Hahn19f9e322018-08-17 14:39:04 +00001795 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
1796 Q.IIQ.hasNoSignedWrap(VOBO)) {
David Majnemerb7d54092013-07-30 21:01:36 +00001797 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1798 match(X, m_And(m_Value(), m_Specific(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001799 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001800 return true;
1801 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1802 match(Y, m_And(m_Value(), m_Specific(X))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001803 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001804 return true;
1805
1806 unsigned BitWidth = V->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00001807 KnownBits LHSBits(BitWidth);
1808 computeKnownBits(X, LHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001809
Craig Topperb45eabc2017-04-26 16:39:58 +00001810 KnownBits RHSBits(BitWidth);
1811 computeKnownBits(Y, RHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001812 // If i8 V is a power of two or zero:
1813 // ZeroBits: 1 1 1 0 1 1 1 1
1814 // ~ZeroBits: 0 0 0 1 0 0 0 0
Craig Topperb45eabc2017-04-26 16:39:58 +00001815 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
David Majnemerb7d54092013-07-30 21:01:36 +00001816 // If OrZero isn't set, we cannot give back a zero result.
1817 // Make sure either the LHS or RHS has a bit set.
Craig Topperb45eabc2017-04-26 16:39:58 +00001818 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
David Majnemerb7d54092013-07-30 21:01:36 +00001819 return true;
1820 }
1821 }
David Majnemerbeab5672013-05-18 19:30:37 +00001822
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001823 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001824 // is a power of two only if the first operand is a power of two and not
1825 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001826 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1827 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001828 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001829 Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001830 }
1831
Duncan Sandsd3951082011-01-25 09:38:29 +00001832 return false;
1833}
1834
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001835/// Test whether a GEP's result is known to be non-null.
Chandler Carruth80d3e562012-12-07 02:08:58 +00001836///
1837/// Uses properties inherent in a GEP to try to determine whether it is known
1838/// to be non-null.
1839///
1840/// Currently this routine does not support vector GEPs.
Pete Cooper35b00d52016-08-13 01:05:32 +00001841static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001842 const Query &Q) {
Manoj Gupta77eeac32018-07-09 22:27:23 +00001843 const Function *F = nullptr;
1844 if (const Instruction *I = dyn_cast<Instruction>(GEP))
1845 F = I->getFunction();
1846
1847 if (!GEP->isInBounds() ||
1848 NullPointerIsDefined(F, GEP->getPointerAddressSpace()))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001849 return false;
1850
1851 // FIXME: Support vector-GEPs.
1852 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1853
1854 // If the base pointer is non-null, we cannot walk to a null address with an
1855 // inbounds GEP in address space zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001856 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001857 return true;
1858
Chandler Carruth80d3e562012-12-07 02:08:58 +00001859 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1860 // If so, then the GEP cannot produce a null pointer, as doing so would
1861 // inherently violate the inbounds contract within address space zero.
1862 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1863 GTI != GTE; ++GTI) {
1864 // Struct types are easy -- they must always be indexed by a constant.
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001865 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001866 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1867 unsigned ElementIdx = OpC->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001868 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chandler Carruth80d3e562012-12-07 02:08:58 +00001869 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1870 if (ElementOffset > 0)
1871 return true;
1872 continue;
1873 }
1874
1875 // If we have a zero-sized type, the index doesn't matter. Keep looping.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001876 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
Chandler Carruth80d3e562012-12-07 02:08:58 +00001877 continue;
1878
1879 // Fast path the constant operand case both for efficiency and so we don't
1880 // increment Depth when just zipping down an all-constant GEP.
1881 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1882 if (!OpC->isZero())
1883 return true;
1884 continue;
1885 }
1886
1887 // We post-increment Depth here because while isKnownNonZero increments it
1888 // as well, when we pop back up that increment won't persist. We don't want
1889 // to recurse 10k times just because we have 10k GEP operands. We don't
1890 // bail completely out because we want to handle constant GEPs regardless
1891 // of depth.
1892 if (Depth++ >= MaxDepth)
1893 continue;
1894
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001895 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001896 return true;
1897 }
1898
1899 return false;
1900}
1901
Nikita Popov9fd02a72019-05-08 14:50:01 +00001902static bool isKnownNonNullFromDominatingCondition(const Value *V,
Nuno Lopes404f1062017-09-09 18:23:11 +00001903 const Instruction *CtxI,
1904 const DominatorTree *DT) {
Nikita Popov9fd02a72019-05-08 14:50:01 +00001905 assert(V->getType()->isPointerTy() && "V must be pointer type");
Nuno Lopes404f1062017-09-09 18:23:11 +00001906 assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull");
1907
1908 if (!CtxI || !DT)
1909 return false;
1910
1911 unsigned NumUsesExplored = 0;
1912 for (auto *U : V->users()) {
1913 // Avoid massive lists
1914 if (NumUsesExplored >= DomConditionsMaxUses)
1915 break;
1916 NumUsesExplored++;
1917
Nikita Popov9fd02a72019-05-08 14:50:01 +00001918 // If the value is used as an argument to a call or invoke, then argument
1919 // attributes may provide an answer about null-ness.
1920 if (auto CS = ImmutableCallSite(U))
1921 if (auto *CalledFunc = CS.getCalledFunction())
1922 for (const Argument &Arg : CalledFunc->args())
1923 if (CS.getArgOperand(Arg.getArgNo()) == V &&
1924 Arg.hasNonNullAttr() && DT->dominates(CS.getInstruction(), CtxI))
1925 return true;
Nuno Lopes404f1062017-09-09 18:23:11 +00001926
1927 // Consider only compare instructions uniquely controlling a branch
1928 CmpInst::Predicate Pred;
1929 if (!match(const_cast<User *>(U),
1930 m_c_ICmp(Pred, m_Specific(V), m_Zero())) ||
1931 (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE))
1932 continue;
1933
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001934 SmallVector<const User *, 4> WorkList;
1935 SmallPtrSet<const User *, 4> Visited;
Nuno Lopes404f1062017-09-09 18:23:11 +00001936 for (auto *CmpU : U->users()) {
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001937 assert(WorkList.empty() && "Should be!");
1938 if (Visited.insert(CmpU).second)
1939 WorkList.push_back(CmpU);
Nuno Lopes404f1062017-09-09 18:23:11 +00001940
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001941 while (!WorkList.empty()) {
1942 auto *Curr = WorkList.pop_back_val();
1943
1944 // If a user is an AND, add all its users to the work list. We only
1945 // propagate "pred != null" condition through AND because it is only
1946 // correct to assume that all conditions of AND are met in true branch.
1947 // TODO: Support similar logic of OR and EQ predicate?
1948 if (Pred == ICmpInst::ICMP_NE)
1949 if (auto *BO = dyn_cast<BinaryOperator>(Curr))
1950 if (BO->getOpcode() == Instruction::And) {
1951 for (auto *BOU : BO->users())
1952 if (Visited.insert(BOU).second)
1953 WorkList.push_back(BOU);
1954 continue;
1955 }
1956
1957 if (const BranchInst *BI = dyn_cast<BranchInst>(Curr)) {
1958 assert(BI->isConditional() && "uses a comparison!");
1959
1960 BasicBlock *NonNullSuccessor =
1961 BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0);
1962 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
1963 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
1964 return true;
Max Kazantsev3c284bd2018-08-30 03:39:16 +00001965 } else if (Pred == ICmpInst::ICMP_NE && isGuard(Curr) &&
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001966 DT->dominates(cast<Instruction>(Curr), CtxI)) {
Nuno Lopes404f1062017-09-09 18:23:11 +00001967 return true;
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001968 }
Nuno Lopes404f1062017-09-09 18:23:11 +00001969 }
1970 }
1971 }
1972
1973 return false;
1974}
1975
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001976/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1977/// ensure that the value it's attached to is never Value? 'RangeType' is
1978/// is the type of the value described by the range.
Pete Cooper35b00d52016-08-13 01:05:32 +00001979static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001980 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1981 assert(NumRanges >= 1);
1982 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001983 ConstantInt *Lower =
1984 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1985 ConstantInt *Upper =
1986 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001987 ConstantRange Range(Lower->getValue(), Upper->getValue());
1988 if (Range.contains(Value))
1989 return false;
1990 }
1991 return true;
1992}
1993
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001994/// Return true if the given value is known to be non-zero when defined. For
1995/// vectors, return true if every element is known to be non-zero when
1996/// defined. For pointers, if the context instruction and dominator tree are
1997/// specified, perform context-sensitive analysis and return true if the
1998/// pointer couldn't possibly be null at the specified instruction.
1999/// Supports values with integer or pointer type and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00002000bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) {
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00002001 if (auto *C = dyn_cast<Constant>(V)) {
Duncan Sandsd3951082011-01-25 09:38:29 +00002002 if (C->isNullValue())
2003 return false;
2004 if (isa<ConstantInt>(C))
2005 // Must be non-zero due to null test above.
2006 return true;
Sanjay Patel23019d12016-05-24 14:18:49 +00002007
Johannes Doerfert2d63fbb2019-07-15 03:24:35 +00002008 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
2009 // See the comment for IntToPtr/PtrToInt instructions below.
2010 if (CE->getOpcode() == Instruction::IntToPtr ||
2011 CE->getOpcode() == Instruction::PtrToInt)
2012 if (Q.DL.getTypeSizeInBits(CE->getOperand(0)->getType()) <=
2013 Q.DL.getTypeSizeInBits(CE->getType()))
2014 return isKnownNonZero(CE->getOperand(0), Depth, Q);
2015 }
2016
Sanjay Patel23019d12016-05-24 14:18:49 +00002017 // For constant vectors, check that all elements are undefined or known
2018 // non-zero to determine that the whole vector is known non-zero.
2019 if (auto *VecTy = dyn_cast<VectorType>(C->getType())) {
2020 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
2021 Constant *Elt = C->getAggregateElement(i);
2022 if (!Elt || Elt->isNullValue())
2023 return false;
2024 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
2025 return false;
2026 }
2027 return true;
2028 }
2029
Nuno Lopes404f1062017-09-09 18:23:11 +00002030 // A global variable in address space 0 is non null unless extern weak
2031 // or an absolute symbol reference. Other address spaces may have null as a
2032 // valid address for a global, so we can't assume anything.
2033 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2034 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
2035 GV->getType()->getAddressSpace() == 0)
2036 return true;
2037 } else
2038 return false;
Duncan Sandsd3951082011-01-25 09:38:29 +00002039 }
2040
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00002041 if (auto *I = dyn_cast<Instruction>(V)) {
Florian Hahn19f9e322018-08-17 14:39:04 +00002042 if (MDNode *Ranges = Q.IIQ.getMetadata(I, LLVMContext::MD_range)) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00002043 // If the possible ranges don't contain zero, then the value is
2044 // definitely non-zero.
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00002045 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00002046 const APInt ZeroValue(Ty->getBitWidth(), 0);
2047 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
2048 return true;
2049 }
2050 }
2051 }
2052
Karl-Johan Karlssonebaaa2d2018-05-30 15:56:46 +00002053 // Some of the tests below are recursive, so bail out if we hit the limit.
2054 if (Depth++ >= MaxDepth)
2055 return false;
2056
Nuno Lopes404f1062017-09-09 18:23:11 +00002057 // Check for pointer simplifications.
2058 if (V->getType()->isPointerTy()) {
2059 // Alloca never returns null, malloc might.
2060 if (isa<AllocaInst>(V) && Q.DL.getAllocaAddrSpace() == 0)
2061 return true;
2062
2063 // A byval, inalloca, or nonnull argument is never null.
2064 if (const Argument *A = dyn_cast<Argument>(V))
2065 if (A->hasByValOrInAllocaAttr() || A->hasNonNullAttr())
2066 return true;
2067
2068 // A Load tagged with nonnull metadata is never null.
2069 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
Florian Hahn19f9e322018-08-17 14:39:04 +00002070 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull))
Nuno Lopes404f1062017-09-09 18:23:11 +00002071 return true;
2072
Chandler Carruth363ac682019-01-07 05:42:51 +00002073 if (const auto *Call = dyn_cast<CallBase>(V)) {
2074 if (Call->isReturnNonNull())
Nuno Lopes404f1062017-09-09 18:23:11 +00002075 return true;
Florian Hahnfd72bf22019-08-15 12:13:02 +00002076 if (const auto *RP = getArgumentAliasingToReturnedPointer(Call, true))
Karl-Johan Karlssonebaaa2d2018-05-30 15:56:46 +00002077 return isKnownNonZero(RP, Depth, Q);
Piotr Padlewski5642a422018-05-18 23:54:33 +00002078 }
Nuno Lopes404f1062017-09-09 18:23:11 +00002079 }
2080
Duncan Sandsd3951082011-01-25 09:38:29 +00002081
Nuno Lopes404f1062017-09-09 18:23:11 +00002082 // Check for recursive pointer simplifications.
Chandler Carruth80d3e562012-12-07 02:08:58 +00002083 if (V->getType()->isPointerTy()) {
Nikita Popov9fd02a72019-05-08 14:50:01 +00002084 if (isKnownNonNullFromDominatingCondition(V, Q.CxtI, Q.DT))
2085 return true;
2086
Johannes Doerfert00102c72019-01-26 23:40:35 +00002087 // Look through bitcast operations, GEPs, and int2ptr instructions as they
2088 // do not alter the value, or at least not the nullness property of the
2089 // value, e.g., int2ptr is allowed to zero/sign extend the value.
2090 //
2091 // Note that we have to take special care to avoid looking through
2092 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
2093 // as casts that can alter the value, e.g., AddrSpaceCasts.
Pete Cooper35b00d52016-08-13 01:05:32 +00002094 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002095 if (isGEPKnownNonNull(GEP, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00002096 return true;
Johannes Doerfert00102c72019-01-26 23:40:35 +00002097
2098 if (auto *BCO = dyn_cast<BitCastOperator>(V))
2099 return isKnownNonZero(BCO->getOperand(0), Depth, Q);
2100
2101 if (auto *I2P = dyn_cast<IntToPtrInst>(V))
2102 if (Q.DL.getTypeSizeInBits(I2P->getSrcTy()) <=
2103 Q.DL.getTypeSizeInBits(I2P->getDestTy()))
2104 return isKnownNonZero(I2P->getOperand(0), Depth, Q);
Chandler Carruth80d3e562012-12-07 02:08:58 +00002105 }
2106
Johannes Doerfert00102c72019-01-26 23:40:35 +00002107 // Similar to int2ptr above, we can look through ptr2int here if the cast
2108 // is a no-op or an extend and not a truncate.
2109 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
2110 if (Q.DL.getTypeSizeInBits(P2I->getSrcTy()) <=
2111 Q.DL.getTypeSizeInBits(P2I->getDestTy()))
2112 return isKnownNonZero(P2I->getOperand(0), Depth, Q);
2113
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002114 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00002115
2116 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00002117 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00002118 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002119 return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002120
2121 // ext X != 0 if X != 0.
2122 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002123 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002124
Duncan Sands2e9e4f12011-01-29 13:27:00 +00002125 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00002126 // if the lowest bit is shifted off the end.
Craig Topper6b3940a2017-05-03 22:25:19 +00002127 if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002128 // shl nuw can't remove any non-zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002129 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Florian Hahn19f9e322018-08-17 14:39:04 +00002130 if (Q.IIQ.hasNoUnsignedWrap(BO))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002131 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002132
Craig Topperb45eabc2017-04-26 16:39:58 +00002133 KnownBits Known(BitWidth);
2134 computeKnownBits(X, Known, Depth, Q);
2135 if (Known.One[0])
Duncan Sandsd3951082011-01-25 09:38:29 +00002136 return true;
2137 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00002138 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00002139 // defined if the sign bit is shifted off the end.
2140 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002141 // shr exact can only shift out zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002142 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002143 if (BO->isExact())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002144 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002145
Craig Topper6e11a052017-05-08 16:22:48 +00002146 KnownBits Known = computeKnownBits(X, Depth, Q);
2147 if (Known.isNegative())
Duncan Sandsd3951082011-01-25 09:38:29 +00002148 return true;
James Molloyb6be1eb2015-09-24 16:06:32 +00002149
2150 // If the shifter operand is a constant, and all of the bits shifted
2151 // out are known to be zero, and X is known non-zero then at least one
2152 // non-zero bit must remain.
2153 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
James Molloyb6be1eb2015-09-24 16:06:32 +00002154 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
2155 // Is there a known one in the portion not shifted out?
Craig Topper8df66c62017-05-12 17:20:30 +00002156 if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
James Molloyb6be1eb2015-09-24 16:06:32 +00002157 return true;
2158 // Are all the bits to be shifted out known zero?
NAKAMURA Takumi76bab1f2017-07-11 02:31:51 +00002159 if (Known.countMinTrailingZeros() >= ShiftVal)
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002160 return isKnownNonZero(X, Depth, Q);
James Molloyb6be1eb2015-09-24 16:06:32 +00002161 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002162 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002163 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00002164 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002165 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002166 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002167 // X + Y.
2168 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Craig Topper6e11a052017-05-08 16:22:48 +00002169 KnownBits XKnown = computeKnownBits(X, Depth, Q);
2170 KnownBits YKnown = computeKnownBits(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002171
2172 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00002173 // zero unless both X and Y are zero.
Craig Topper6e11a052017-05-08 16:22:48 +00002174 if (XKnown.isNonNegative() && YKnown.isNonNegative())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002175 if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00002176 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00002177
2178 // If X and Y are both negative (as signed values) then their sum is not
2179 // zero unless both X and Y equal INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002180 if (XKnown.isNegative() && YKnown.isNegative()) {
Duncan Sandsd3951082011-01-25 09:38:29 +00002181 APInt Mask = APInt::getSignedMaxValue(BitWidth);
2182 // The sign bit of X is set. If some other bit is set then X is not equal
2183 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002184 if (XKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00002185 return true;
2186 // The sign bit of Y is set. If some other bit is set then Y is not equal
2187 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002188 if (YKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00002189 return true;
2190 }
2191
2192 // The sum of a non-negative number and a power of two is not zero.
Craig Topper6e11a052017-05-08 16:22:48 +00002193 if (XKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002194 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002195 return true;
Craig Topper6e11a052017-05-08 16:22:48 +00002196 if (YKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002197 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002198 return true;
2199 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00002200 // X * Y.
2201 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00002202 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Duncan Sands7cb61e52011-10-27 19:16:21 +00002203 // If X and Y are non-zero then so is X * Y as long as the multiplication
2204 // does not overflow.
Florian Hahn19f9e322018-08-17 14:39:04 +00002205 if ((Q.IIQ.hasNoSignedWrap(BO) || Q.IIQ.hasNoUnsignedWrap(BO)) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002206 isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00002207 return true;
2208 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002209 // (C ? X : Y) != 0 if X != 0 and Y != 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00002210 else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002211 if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
2212 isKnownNonZero(SI->getFalseValue(), Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002213 return true;
2214 }
James Molloy897048b2015-09-29 14:08:45 +00002215 // PHI
Pete Cooper35b00d52016-08-13 01:05:32 +00002216 else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
James Molloy897048b2015-09-29 14:08:45 +00002217 // Try and detect a recurrence that monotonically increases from a
2218 // starting value, as these are common as induction variables.
2219 if (PN->getNumIncomingValues() == 2) {
2220 Value *Start = PN->getIncomingValue(0);
2221 Value *Induction = PN->getIncomingValue(1);
2222 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
2223 std::swap(Start, Induction);
2224 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
2225 if (!C->isZero() && !C->isNegative()) {
2226 ConstantInt *X;
Florian Hahn19f9e322018-08-17 14:39:04 +00002227 if (Q.IIQ.UseInstrInfo &&
2228 (match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
James Molloy897048b2015-09-29 14:08:45 +00002229 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
2230 !X->isNegative())
2231 return true;
2232 }
2233 }
2234 }
Jun Bum Limca832662016-02-01 17:03:07 +00002235 // Check if all incoming values are non-zero constant.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002236 bool AllNonZeroConstants = llvm::all_of(PN->operands(), [](Value *V) {
Craig Topper79ab6432017-07-06 18:39:47 +00002237 return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZero();
Jun Bum Limca832662016-02-01 17:03:07 +00002238 });
2239 if (AllNonZeroConstants)
2240 return true;
James Molloy897048b2015-09-29 14:08:45 +00002241 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002242
Craig Topperb45eabc2017-04-26 16:39:58 +00002243 KnownBits Known(BitWidth);
2244 computeKnownBits(V, Known, Depth, Q);
2245 return Known.One != 0;
Duncan Sandsd3951082011-01-25 09:38:29 +00002246}
2247
James Molloy1d88d6f2015-10-22 13:18:42 +00002248/// Return true if V2 == V1 + X, where X is known non-zero.
Pete Cooper35b00d52016-08-13 01:05:32 +00002249static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) {
2250 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
James Molloy1d88d6f2015-10-22 13:18:42 +00002251 if (!BO || BO->getOpcode() != Instruction::Add)
2252 return false;
2253 Value *Op = nullptr;
2254 if (V2 == BO->getOperand(0))
2255 Op = BO->getOperand(1);
2256 else if (V2 == BO->getOperand(1))
2257 Op = BO->getOperand(0);
2258 else
2259 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002260 return isKnownNonZero(Op, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002261}
2262
2263/// Return true if it is known that V1 != V2.
Pete Cooper35b00d52016-08-13 01:05:32 +00002264static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) {
Craig Topper3002d5b2017-06-06 07:13:15 +00002265 if (V1 == V2)
James Molloy1d88d6f2015-10-22 13:18:42 +00002266 return false;
2267 if (V1->getType() != V2->getType())
2268 // We can't look through casts yet.
2269 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002270 if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
James Molloy1d88d6f2015-10-22 13:18:42 +00002271 return true;
2272
Craig Topper3002d5b2017-06-06 07:13:15 +00002273 if (V1->getType()->isIntOrIntVectorTy()) {
James Molloy1d88d6f2015-10-22 13:18:42 +00002274 // Are any known bits in V1 contradictory to known bits in V2? If V1
2275 // has a known zero where V2 has a known one, they must not be equal.
Craig Topper8e662f72017-06-06 07:13:11 +00002276 KnownBits Known1 = computeKnownBits(V1, 0, Q);
2277 KnownBits Known2 = computeKnownBits(V2, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002278
Craig Topper8365df82017-06-06 07:13:09 +00002279 if (Known1.Zero.intersects(Known2.One) ||
2280 Known2.Zero.intersects(Known1.One))
James Molloy1d88d6f2015-10-22 13:18:42 +00002281 return true;
2282 }
2283 return false;
2284}
2285
Sanjay Patelaee84212014-11-04 16:27:42 +00002286/// Return true if 'V & Mask' is known to be zero. We use this predicate to
2287/// simplify operations downstream. Mask is known to be zero for bits that V
2288/// cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00002289///
2290/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002291/// type, and vectors of integers. In the case
Chris Lattner4bc28252009-09-08 00:06:16 +00002292/// where V is a vector, the mask, known zero, and known one values are the
2293/// same width as the vector element, and the bit is set only if it is true
2294/// for all of the elements in the vector.
Pete Cooper35b00d52016-08-13 01:05:32 +00002295bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002296 const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002297 KnownBits Known(Mask.getBitWidth());
2298 computeKnownBits(V, Known, Depth, Q);
2299 return Mask.isSubsetOf(Known.Zero);
Chris Lattner965c7692008-06-02 01:18:21 +00002300}
2301
Craig Topperbec15b62018-08-22 23:27:50 +00002302// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
2303// Returns the input and lower/upper bounds.
2304static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
2305 const APInt *&CLow, const APInt *&CHigh) {
Craig Topper15f86922018-08-23 17:15:02 +00002306 assert(isa<Operator>(Select) &&
2307 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
Craig Topperdfa176e2018-08-23 17:45:53 +00002308 "Input should be a Select!");
Craig Topperbec15b62018-08-22 23:27:50 +00002309
Simon Pilgrimf62293e2019-09-23 13:15:52 +00002310 const Value *LHS = nullptr, *RHS = nullptr;
Craig Topperbec15b62018-08-22 23:27:50 +00002311 SelectPatternFlavor SPF = matchSelectPattern(Select, LHS, RHS).Flavor;
2312 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
2313 return false;
2314
2315 if (!match(RHS, m_APInt(CLow)))
2316 return false;
2317
Simon Pilgrimf62293e2019-09-23 13:15:52 +00002318 const Value *LHS2 = nullptr, *RHS2 = nullptr;
Craig Topperbec15b62018-08-22 23:27:50 +00002319 SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor;
2320 if (getInverseMinMaxFlavor(SPF) != SPF2)
2321 return false;
2322
2323 if (!match(RHS2, m_APInt(CHigh)))
2324 return false;
2325
2326 if (SPF == SPF_SMIN)
2327 std::swap(CLow, CHigh);
2328
2329 In = LHS2;
2330 return CLow->sle(*CHigh);
2331}
2332
Sanjay Patela06d9892016-06-22 19:20:59 +00002333/// For vector constants, loop over the elements and find the constant with the
2334/// minimum number of sign bits. Return 0 if the value is not a vector constant
2335/// or if any element was not analyzed; otherwise, return the count for the
2336/// element with the minimum number of sign bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002337static unsigned computeNumSignBitsVectorConstant(const Value *V,
2338 unsigned TyBits) {
2339 const auto *CV = dyn_cast<Constant>(V);
Sanjay Patela06d9892016-06-22 19:20:59 +00002340 if (!CV || !CV->getType()->isVectorTy())
2341 return 0;
Chris Lattner965c7692008-06-02 01:18:21 +00002342
Sanjay Patela06d9892016-06-22 19:20:59 +00002343 unsigned MinSignBits = TyBits;
2344 unsigned NumElts = CV->getType()->getVectorNumElements();
2345 for (unsigned i = 0; i != NumElts; ++i) {
2346 // If we find a non-ConstantInt, bail out.
2347 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
2348 if (!Elt)
2349 return 0;
2350
Craig Topper8e8b6ef2017-10-21 16:35:41 +00002351 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
Sanjay Patela06d9892016-06-22 19:20:59 +00002352 }
2353
2354 return MinSignBits;
2355}
Chris Lattner965c7692008-06-02 01:18:21 +00002356
Sanjoy Das39a684d2017-02-25 20:30:45 +00002357static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2358 const Query &Q);
2359
2360static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
2361 const Query &Q) {
2362 unsigned Result = ComputeNumSignBitsImpl(V, Depth, Q);
2363 assert(Result > 0 && "At least one sign bit needs to be present!");
2364 return Result;
2365}
2366
Sanjay Patelaee84212014-11-04 16:27:42 +00002367/// Return the number of times the sign bit of the register is replicated into
2368/// the other bits. We know that at least 1 bit is always equal to the sign bit
2369/// (itself), but other cases can give us information. For example, immediately
2370/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
Sanjay Patela06d9892016-06-22 19:20:59 +00002371/// other, so we return 3. For vectors, return the number of sign bits for the
Vedant Kumard3196742018-02-28 19:08:52 +00002372/// vector element with the minimum number of known sign bits.
Sanjoy Das39a684d2017-02-25 20:30:45 +00002373static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2374 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00002375 assert(Depth <= MaxDepth && "Limit Search Depth");
Sanjoy Das39a684d2017-02-25 20:30:45 +00002376
2377 // We return the minimum number of sign bits that are guaranteed to be present
2378 // in V, so for undef we have to conservatively return 1. We don't have the
2379 // same behavior for poison though -- that's a FIXME today.
2380
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00002381 Type *ScalarTy = V->getType()->getScalarType();
2382 unsigned TyBits = ScalarTy->isPointerTy() ?
2383 Q.DL.getIndexTypeSizeInBits(ScalarTy) :
2384 Q.DL.getTypeSizeInBits(ScalarTy);
2385
Chris Lattner965c7692008-06-02 01:18:21 +00002386 unsigned Tmp, Tmp2;
2387 unsigned FirstAnswer = 1;
2388
Jay Foada0653a32014-05-14 21:14:37 +00002389 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00002390 // below.
2391
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002392 if (Depth == MaxDepth)
Chris Lattner965c7692008-06-02 01:18:21 +00002393 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002394
Pete Cooper35b00d52016-08-13 01:05:32 +00002395 const Operator *U = dyn_cast<Operator>(V);
Dan Gohman80ca01c2009-07-17 20:47:02 +00002396 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00002397 default: break;
2398 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00002399 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002400 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00002401
Nadav Rotemc99a3872015-03-06 00:23:58 +00002402 case Instruction::SDiv: {
Nadav Rotem029c5c72015-03-03 21:39:02 +00002403 const APInt *Denominator;
2404 // sdiv X, C -> adds log(C) sign bits.
2405 if (match(U->getOperand(1), m_APInt(Denominator))) {
2406
2407 // Ignore non-positive denominator.
2408 if (!Denominator->isStrictlyPositive())
2409 break;
2410
2411 // Calculate the incoming numerator bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002412 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotem029c5c72015-03-03 21:39:02 +00002413
2414 // Add floor(log(C)) bits to the numerator bits.
2415 return std::min(TyBits, NumBits + Denominator->logBase2());
2416 }
2417 break;
Nadav Rotemc99a3872015-03-06 00:23:58 +00002418 }
2419
2420 case Instruction::SRem: {
2421 const APInt *Denominator;
Sanjoy Dase561fee2015-03-25 22:33:53 +00002422 // srem X, C -> we know that the result is within [-C+1,C) when C is a
2423 // positive constant. This let us put a lower bound on the number of sign
2424 // bits.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002425 if (match(U->getOperand(1), m_APInt(Denominator))) {
2426
2427 // Ignore non-positive denominator.
2428 if (!Denominator->isStrictlyPositive())
2429 break;
2430
2431 // Calculate the incoming numerator bits. SRem by a positive constant
2432 // can't lower the number of sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002433 unsigned NumrBits =
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002434 ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotemc99a3872015-03-06 00:23:58 +00002435
2436 // Calculate the leading sign bit constraints by examining the
Sanjoy Dase561fee2015-03-25 22:33:53 +00002437 // denominator. Given that the denominator is positive, there are two
2438 // cases:
2439 //
2440 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
2441 // (1 << ceilLogBase2(C)).
2442 //
2443 // 2. the numerator is negative. Then the result range is (-C,0] and
2444 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2445 //
2446 // Thus a lower bound on the number of sign bits is `TyBits -
2447 // ceilLogBase2(C)`.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002448
Sanjoy Dase561fee2015-03-25 22:33:53 +00002449 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
Nadav Rotemc99a3872015-03-06 00:23:58 +00002450 return std::max(NumrBits, ResBits);
2451 }
2452 break;
2453 }
Nadav Rotem029c5c72015-03-03 21:39:02 +00002454
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002455 case Instruction::AShr: {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002456 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002457 // ashr X, C -> adds C sign bits. Vectors too.
2458 const APInt *ShAmt;
2459 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Simon Pilgrim67207262018-01-01 22:44:59 +00002460 if (ShAmt->uge(TyBits))
Sanjoy Das39a684d2017-02-25 20:30:45 +00002461 break; // Bad shift.
Simon Pilgrim67207262018-01-01 22:44:59 +00002462 unsigned ShAmtLimited = ShAmt->getZExtValue();
Sanjoy Das39a684d2017-02-25 20:30:45 +00002463 Tmp += ShAmtLimited;
Chris Lattner965c7692008-06-02 01:18:21 +00002464 if (Tmp > TyBits) Tmp = TyBits;
2465 }
2466 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002467 }
2468 case Instruction::Shl: {
2469 const APInt *ShAmt;
2470 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00002471 // shl destroys sign bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002472 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Simon Pilgrim67207262018-01-01 22:44:59 +00002473 if (ShAmt->uge(TyBits) || // Bad shift.
2474 ShAmt->uge(Tmp)) break; // Shifted all sign bits out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002475 Tmp2 = ShAmt->getZExtValue();
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002476 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00002477 }
2478 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002479 }
Chris Lattner965c7692008-06-02 01:18:21 +00002480 case Instruction::And:
2481 case Instruction::Or:
2482 case Instruction::Xor: // NOT is handled here.
2483 // Logical binary ops preserve the number of sign bits at the worst.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002484 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002485 if (Tmp != 1) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002486 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002487 FirstAnswer = std::min(Tmp, Tmp2);
2488 // We computed what we know about the sign bits as our first
2489 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00002490 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00002491 }
2492 break;
2493
Craig Topperbec15b62018-08-22 23:27:50 +00002494 case Instruction::Select: {
2495 // If we have a clamp pattern, we know that the number of sign bits will be
2496 // the minimum of the clamp min/max range.
2497 const Value *X;
2498 const APInt *CLow, *CHigh;
2499 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
2500 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
2501
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002502 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002503 if (Tmp == 1) break;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002504 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002505 return std::min(Tmp, Tmp2);
Craig Topperbec15b62018-08-22 23:27:50 +00002506 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002507
Chris Lattner965c7692008-06-02 01:18:21 +00002508 case Instruction::Add:
2509 // Add can have at most one carry bit. Thus we know that the output
2510 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002511 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002512 if (Tmp == 1) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002513
Chris Lattner965c7692008-06-02 01:18:21 +00002514 // Special case decrementing a value (ADD X, -1):
David Majnemera55027f2014-12-26 09:20:17 +00002515 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00002516 if (CRHS->isAllOnesValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002517 KnownBits Known(TyBits);
2518 computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002519
Chris Lattner965c7692008-06-02 01:18:21 +00002520 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2521 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002522 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002523 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002524
Chris Lattner965c7692008-06-02 01:18:21 +00002525 // If we are subtracting one from a positive number, there is no carry
2526 // out of the result.
Craig Topperca48af32017-04-29 16:43:11 +00002527 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002528 return Tmp;
2529 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002530
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002531 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002532 if (Tmp2 == 1) break;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002533 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002534
Chris Lattner965c7692008-06-02 01:18:21 +00002535 case Instruction::Sub:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002536 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002537 if (Tmp2 == 1) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002538
Chris Lattner965c7692008-06-02 01:18:21 +00002539 // Handle NEG.
David Majnemera55027f2014-12-26 09:20:17 +00002540 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
Chris Lattner965c7692008-06-02 01:18:21 +00002541 if (CLHS->isNullValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002542 KnownBits Known(TyBits);
2543 computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002544 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2545 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002546 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002547 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002548
Chris Lattner965c7692008-06-02 01:18:21 +00002549 // If the input is known to be positive (the sign bit is known clear),
2550 // the output of the NEG has the same number of sign bits as the input.
Craig Topperca48af32017-04-29 16:43:11 +00002551 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002552 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00002553
Chris Lattner965c7692008-06-02 01:18:21 +00002554 // Otherwise, we treat this like a SUB.
2555 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002556
Chris Lattner965c7692008-06-02 01:18:21 +00002557 // Sub can have at most one carry bit. Thus we know that the output
2558 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002559 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002560 if (Tmp == 1) break;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002561 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002562
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002563 case Instruction::Mul: {
2564 // The output of the Mul can be at most twice the valid bits in the inputs.
2565 unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002566 if (SignBitsOp0 == 1) break;
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002567 unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002568 if (SignBitsOp1 == 1) break;
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002569 unsigned OutValidBits =
2570 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
2571 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
2572 }
2573
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002574 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00002575 const PHINode *PN = cast<PHINode>(U);
David Majnemer6ee8d172015-01-04 07:06:53 +00002576 unsigned NumIncomingValues = PN->getNumIncomingValues();
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002577 // Don't analyze large in-degree PHIs.
David Majnemer6ee8d172015-01-04 07:06:53 +00002578 if (NumIncomingValues > 4) break;
2579 // Unreachable blocks may have zero-operand PHI nodes.
2580 if (NumIncomingValues == 0) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002581
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002582 // Take the minimum of all incoming values. This can't infinitely loop
2583 // because of our depth threshold.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002584 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
David Majnemer6ee8d172015-01-04 07:06:53 +00002585 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002586 if (Tmp == 1) return Tmp;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002587 Tmp = std::min(
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002588 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002589 }
2590 return Tmp;
2591 }
2592
Chris Lattner965c7692008-06-02 01:18:21 +00002593 case Instruction::Trunc:
2594 // FIXME: it's tricky to do anything useful for this, but it is an important
2595 // case for targets like X86.
2596 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00002597
2598 case Instruction::ExtractElement:
2599 // Look through extract element. At the moment we keep this simple and skip
2600 // tracking the specific element. But at least we might find information
2601 // valid for all elements of the vector (for example if vector is sign
2602 // extended, shifted, etc).
2603 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Sanjay Patelcc9e4012018-10-26 21:05:14 +00002604
Sanjay Patela68096c2018-11-02 15:51:47 +00002605 case Instruction::ShuffleVector: {
Sanjay Patelcac28b42018-11-03 13:18:55 +00002606 // TODO: This is copied almost directly from the SelectionDAG version of
2607 // ComputeNumSignBits. It would be better if we could share common
2608 // code. If not, make sure that changes are translated to the DAG.
2609
2610 // Collect the minimum number of sign bits that are shared by every vector
2611 // element referenced by the shuffle.
2612 auto *Shuf = cast<ShuffleVectorInst>(U);
2613 int NumElts = Shuf->getOperand(0)->getType()->getVectorNumElements();
2614 int NumMaskElts = Shuf->getMask()->getType()->getVectorNumElements();
2615 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2616 for (int i = 0; i != NumMaskElts; ++i) {
2617 int M = Shuf->getMaskValue(i);
2618 assert(M < NumElts * 2 && "Invalid shuffle mask constant");
2619 // For undef elements, we don't know anything about the common state of
2620 // the shuffle result.
2621 if (M == -1)
2622 return 1;
2623 if (M < NumElts)
2624 DemandedLHS.setBit(M % NumElts);
2625 else
2626 DemandedRHS.setBit(M % NumElts);
2627 }
2628 Tmp = std::numeric_limits<unsigned>::max();
2629 if (!!DemandedLHS)
2630 Tmp = ComputeNumSignBits(Shuf->getOperand(0), Depth + 1, Q);
2631 if (!!DemandedRHS) {
2632 Tmp2 = ComputeNumSignBits(Shuf->getOperand(1), Depth + 1, Q);
2633 Tmp = std::min(Tmp, Tmp2);
2634 }
2635 // If we don't know anything, early out and try computeKnownBits fall-back.
2636 if (Tmp == 1)
Sanjay Patelcc9e4012018-10-26 21:05:14 +00002637 break;
Sanjay Patelcac28b42018-11-03 13:18:55 +00002638 assert(Tmp <= V->getType()->getScalarSizeInBits() &&
2639 "Failed to determine minimum sign bits");
2640 return Tmp;
Chris Lattner965c7692008-06-02 01:18:21 +00002641 }
Sanjay Patela68096c2018-11-02 15:51:47 +00002642 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002643
Chris Lattner965c7692008-06-02 01:18:21 +00002644 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2645 // use this information.
Sanjay Patela06d9892016-06-22 19:20:59 +00002646
2647 // If we can examine all elements of a vector constant successfully, we're
2648 // done (we can't do any better than that). If not, keep trying.
2649 if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits))
2650 return VecSignBits;
2651
Craig Topperb45eabc2017-04-26 16:39:58 +00002652 KnownBits Known(TyBits);
2653 computeKnownBits(V, Known, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002654
Sanjay Patele0536212016-06-23 17:41:59 +00002655 // If we know that the sign bit is either zero or one, determine the number of
2656 // identical bits in the top of the input value.
Craig Topper8df66c62017-05-12 17:20:30 +00002657 return std::max(FirstAnswer, Known.countMinSignBits());
Chris Lattner965c7692008-06-02 01:18:21 +00002658}
Chris Lattnera12a6de2008-06-02 01:29:46 +00002659
Sanjay Patelaee84212014-11-04 16:27:42 +00002660/// This function computes the integer multiple of Base that equals V.
2661/// If successful, it returns true and returns the multiple in
2662/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00002663/// through SExt instructions only if LookThroughSExt is true.
2664bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00002665 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00002666 const unsigned MaxDepth = 6;
2667
Dan Gohman6a976bb2009-11-18 00:58:27 +00002668 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00002669 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002670 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00002671
Chris Lattner229907c2011-07-18 04:54:35 +00002672 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00002673
Dan Gohman6a976bb2009-11-18 00:58:27 +00002674 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00002675
2676 if (Base == 0)
2677 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002678
Victor Hernandez47444882009-11-10 08:28:35 +00002679 if (Base == 1) {
2680 Multiple = V;
2681 return true;
2682 }
2683
2684 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2685 Constant *BaseVal = ConstantInt::get(T, Base);
2686 if (CO && CO == BaseVal) {
2687 // Multiple is 1.
2688 Multiple = ConstantInt::get(T, 1);
2689 return true;
2690 }
2691
2692 if (CI && CI->getZExtValue() % Base == 0) {
2693 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00002694 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00002695 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002696
Victor Hernandez47444882009-11-10 08:28:35 +00002697 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002698
Victor Hernandez47444882009-11-10 08:28:35 +00002699 Operator *I = dyn_cast<Operator>(V);
2700 if (!I) return false;
2701
2702 switch (I->getOpcode()) {
2703 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002704 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00002705 if (!LookThroughSExt) return false;
2706 // otherwise fall through to ZExt
Galina Kistanova244621f2017-05-31 22:16:24 +00002707 LLVM_FALLTHROUGH;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002708 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00002709 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2710 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00002711 case Instruction::Shl:
2712 case Instruction::Mul: {
2713 Value *Op0 = I->getOperand(0);
2714 Value *Op1 = I->getOperand(1);
2715
2716 if (I->getOpcode() == Instruction::Shl) {
2717 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2718 if (!Op1CI) return false;
2719 // Turn Op0 << Op1 into Op0 * 2^Op1
2720 APInt Op1Int = Op1CI->getValue();
2721 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00002722 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002723 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00002724 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00002725 }
2726
Craig Topper9f008862014-04-15 04:59:12 +00002727 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002728 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2729 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2730 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002731 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002732 MulC->getType()->getPrimitiveSizeInBits())
2733 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002734 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002735 MulC->getType()->getPrimitiveSizeInBits())
2736 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002737
Chris Lattner72d283c2010-09-05 17:20:46 +00002738 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2739 Multiple = ConstantExpr::getMul(MulC, Op1C);
2740 return true;
2741 }
Victor Hernandez47444882009-11-10 08:28:35 +00002742
2743 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2744 if (Mul0CI->getValue() == 1) {
2745 // V == Base * Op1, so return Op1
2746 Multiple = Op1;
2747 return true;
2748 }
2749 }
2750
Craig Topper9f008862014-04-15 04:59:12 +00002751 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002752 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2753 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2754 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002755 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002756 MulC->getType()->getPrimitiveSizeInBits())
2757 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002758 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002759 MulC->getType()->getPrimitiveSizeInBits())
2760 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002761
Chris Lattner72d283c2010-09-05 17:20:46 +00002762 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2763 Multiple = ConstantExpr::getMul(MulC, Op0C);
2764 return true;
2765 }
Victor Hernandez47444882009-11-10 08:28:35 +00002766
2767 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2768 if (Mul1CI->getValue() == 1) {
2769 // V == Base * Op0, so return Op0
2770 Multiple = Op0;
2771 return true;
2772 }
2773 }
Victor Hernandez47444882009-11-10 08:28:35 +00002774 }
2775 }
2776
2777 // We could not determine if V is a multiple of Base.
2778 return false;
2779}
2780
David Majnemerb4b27232016-04-19 19:10:21 +00002781Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS,
2782 const TargetLibraryInfo *TLI) {
2783 const Function *F = ICS.getCalledFunction();
2784 if (!F)
2785 return Intrinsic::not_intrinsic;
2786
2787 if (F->isIntrinsic())
2788 return F->getIntrinsicID();
2789
2790 if (!TLI)
2791 return Intrinsic::not_intrinsic;
2792
David L. Jonesd21529f2017-01-23 23:16:46 +00002793 LibFunc Func;
David Majnemerb4b27232016-04-19 19:10:21 +00002794 // We're going to make assumptions on the semantics of the functions, check
2795 // that the target knows that it's available in this environment and it does
2796 // not have local linkage.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002797 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func))
2798 return Intrinsic::not_intrinsic;
2799
2800 if (!ICS.onlyReadsMemory())
David Majnemerb4b27232016-04-19 19:10:21 +00002801 return Intrinsic::not_intrinsic;
2802
2803 // Otherwise check if we have a call to a function that can be turned into a
2804 // vector intrinsic.
2805 switch (Func) {
2806 default:
2807 break;
David L. Jonesd21529f2017-01-23 23:16:46 +00002808 case LibFunc_sin:
2809 case LibFunc_sinf:
2810 case LibFunc_sinl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002811 return Intrinsic::sin;
David L. Jonesd21529f2017-01-23 23:16:46 +00002812 case LibFunc_cos:
2813 case LibFunc_cosf:
2814 case LibFunc_cosl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002815 return Intrinsic::cos;
David L. Jonesd21529f2017-01-23 23:16:46 +00002816 case LibFunc_exp:
2817 case LibFunc_expf:
2818 case LibFunc_expl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002819 return Intrinsic::exp;
David L. Jonesd21529f2017-01-23 23:16:46 +00002820 case LibFunc_exp2:
2821 case LibFunc_exp2f:
2822 case LibFunc_exp2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002823 return Intrinsic::exp2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002824 case LibFunc_log:
2825 case LibFunc_logf:
2826 case LibFunc_logl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002827 return Intrinsic::log;
David L. Jonesd21529f2017-01-23 23:16:46 +00002828 case LibFunc_log10:
2829 case LibFunc_log10f:
2830 case LibFunc_log10l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002831 return Intrinsic::log10;
David L. Jonesd21529f2017-01-23 23:16:46 +00002832 case LibFunc_log2:
2833 case LibFunc_log2f:
2834 case LibFunc_log2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002835 return Intrinsic::log2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002836 case LibFunc_fabs:
2837 case LibFunc_fabsf:
2838 case LibFunc_fabsl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002839 return Intrinsic::fabs;
David L. Jonesd21529f2017-01-23 23:16:46 +00002840 case LibFunc_fmin:
2841 case LibFunc_fminf:
2842 case LibFunc_fminl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002843 return Intrinsic::minnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002844 case LibFunc_fmax:
2845 case LibFunc_fmaxf:
2846 case LibFunc_fmaxl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002847 return Intrinsic::maxnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002848 case LibFunc_copysign:
2849 case LibFunc_copysignf:
2850 case LibFunc_copysignl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002851 return Intrinsic::copysign;
David L. Jonesd21529f2017-01-23 23:16:46 +00002852 case LibFunc_floor:
2853 case LibFunc_floorf:
2854 case LibFunc_floorl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002855 return Intrinsic::floor;
David L. Jonesd21529f2017-01-23 23:16:46 +00002856 case LibFunc_ceil:
2857 case LibFunc_ceilf:
2858 case LibFunc_ceill:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002859 return Intrinsic::ceil;
David L. Jonesd21529f2017-01-23 23:16:46 +00002860 case LibFunc_trunc:
2861 case LibFunc_truncf:
2862 case LibFunc_truncl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002863 return Intrinsic::trunc;
David L. Jonesd21529f2017-01-23 23:16:46 +00002864 case LibFunc_rint:
2865 case LibFunc_rintf:
2866 case LibFunc_rintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002867 return Intrinsic::rint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002868 case LibFunc_nearbyint:
2869 case LibFunc_nearbyintf:
2870 case LibFunc_nearbyintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002871 return Intrinsic::nearbyint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002872 case LibFunc_round:
2873 case LibFunc_roundf:
2874 case LibFunc_roundl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002875 return Intrinsic::round;
David L. Jonesd21529f2017-01-23 23:16:46 +00002876 case LibFunc_pow:
2877 case LibFunc_powf:
2878 case LibFunc_powl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002879 return Intrinsic::pow;
David L. Jonesd21529f2017-01-23 23:16:46 +00002880 case LibFunc_sqrt:
2881 case LibFunc_sqrtf:
2882 case LibFunc_sqrtl:
Sanjay Patel86d24f12017-11-06 22:40:09 +00002883 return Intrinsic::sqrt;
David Majnemerb4b27232016-04-19 19:10:21 +00002884 }
2885
2886 return Intrinsic::not_intrinsic;
2887}
2888
Sanjay Patelaee84212014-11-04 16:27:42 +00002889/// Return true if we can prove that the specified FP value is never equal to
2890/// -0.0.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002891///
2892/// NOTE: this function will need to be revisited when we support non-default
2893/// rounding modes!
David Majnemer3ee5f342016-04-13 06:55:52 +00002894bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
2895 unsigned Depth) {
Sanjay Patel20df88a2017-11-13 17:56:23 +00002896 if (auto *CFP = dyn_cast<ConstantFP>(V))
Chris Lattnera12a6de2008-06-02 01:29:46 +00002897 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00002898
Sanjay Patel20df88a2017-11-13 17:56:23 +00002899 // Limit search depth.
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002900 if (Depth == MaxDepth)
Sanjay Patel20df88a2017-11-13 17:56:23 +00002901 return false;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002902
Sanjay Patel20df88a2017-11-13 17:56:23 +00002903 auto *Op = dyn_cast<Operator>(V);
2904 if (!Op)
2905 return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00002906
Sanjay Patel20df88a2017-11-13 17:56:23 +00002907 // Check if the nsz fast-math flag is set.
2908 if (auto *FPO = dyn_cast<FPMathOperator>(Op))
Michael Ilseman0f128372012-12-06 00:07:09 +00002909 if (FPO->hasNoSignedZeros())
2910 return true;
2911
Sanjay Patel9e3d8f42017-11-13 17:40:47 +00002912 // (fadd x, 0.0) is guaranteed to return +0.0, not -0.0.
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002913 if (match(Op, m_FAdd(m_Value(), m_PosZeroFP())))
Sanjay Patel9e3d8f42017-11-13 17:40:47 +00002914 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002915
Chris Lattnera12a6de2008-06-02 01:29:46 +00002916 // sitofp and uitofp turn into +0.0 for zero.
Sanjay Patel20df88a2017-11-13 17:56:23 +00002917 if (isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op))
Chris Lattnera12a6de2008-06-02 01:29:46 +00002918 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002919
Sanjay Patel20df88a2017-11-13 17:56:23 +00002920 if (auto *Call = dyn_cast<CallInst>(Op)) {
2921 Intrinsic::ID IID = getIntrinsicForCallSite(Call, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002922 switch (IID) {
2923 default:
2924 break;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002925 // sqrt(-0.0) = -0.0, no other negative results are possible.
David Majnemer3ee5f342016-04-13 06:55:52 +00002926 case Intrinsic::sqrt:
Matt Arsenault56b31d82018-08-06 15:16:26 +00002927 case Intrinsic::canonicalize:
Sanjay Patel20df88a2017-11-13 17:56:23 +00002928 return CannotBeNegativeZero(Call->getArgOperand(0), TLI, Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002929 // fabs(x) != -0.0
2930 case Intrinsic::fabs:
2931 return true;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002932 }
David Majnemer3ee5f342016-04-13 06:55:52 +00002933 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002934
Chris Lattnera12a6de2008-06-02 01:29:46 +00002935 return false;
2936}
2937
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002938/// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
2939/// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
2940/// bit despite comparing equal.
2941static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
2942 const TargetLibraryInfo *TLI,
2943 bool SignBitOnly,
2944 unsigned Depth) {
Justin Lebar322c1272017-01-27 00:58:34 +00002945 // TODO: This function does not do the right thing when SignBitOnly is true
2946 // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
2947 // which flips the sign bits of NaNs. See
2948 // https://llvm.org/bugs/show_bug.cgi?id=31702.
2949
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002950 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2951 return !CFP->getValueAPF().isNegative() ||
2952 (!SignBitOnly && CFP->getValueAPF().isZero());
2953 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002954
Craig Topper69c89722018-02-26 22:33:17 +00002955 // Handle vector of constants.
2956 if (auto *CV = dyn_cast<Constant>(V)) {
2957 if (CV->getType()->isVectorTy()) {
2958 unsigned NumElts = CV->getType()->getVectorNumElements();
2959 for (unsigned i = 0; i != NumElts; ++i) {
2960 auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
2961 if (!CFP)
2962 return false;
2963 if (CFP->getValueAPF().isNegative() &&
2964 (SignBitOnly || !CFP->getValueAPF().isZero()))
2965 return false;
2966 }
2967
2968 // All non-negative ConstantFPs.
2969 return true;
2970 }
2971 }
2972
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002973 if (Depth == MaxDepth)
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002974 return false; // Limit search depth.
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002975
2976 const Operator *I = dyn_cast<Operator>(V);
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002977 if (!I)
2978 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002979
2980 switch (I->getOpcode()) {
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002981 default:
2982 break;
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002983 // Unsigned integers are always nonnegative.
2984 case Instruction::UIToFP:
2985 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002986 case Instruction::FMul:
2987 // x*x is always non-negative or a NaN.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002988 if (I->getOperand(0) == I->getOperand(1) &&
2989 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002990 return true;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002991
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002992 LLVM_FALLTHROUGH;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002993 case Instruction::FAdd:
2994 case Instruction::FDiv:
2995 case Instruction::FRem:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002996 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2997 Depth + 1) &&
2998 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2999 Depth + 1);
Fiona Glaserdb7824f2016-01-12 23:37:30 +00003000 case Instruction::Select:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00003001 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3002 Depth + 1) &&
3003 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
3004 Depth + 1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003005 case Instruction::FPExt:
3006 case Instruction::FPTrunc:
3007 // Widening/narrowing never change sign.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00003008 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3009 Depth + 1);
Craig Topper30199102018-02-27 19:53:45 +00003010 case Instruction::ExtractElement:
3011 // Look through extract element. At the moment we keep this simple and skip
3012 // tracking the specific element. But at least we might find information
3013 // valid for all elements of the vector.
3014 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3015 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00003016 case Instruction::Call:
Justin Lebar7e3184c2017-01-26 00:10:26 +00003017 const auto *CI = cast<CallInst>(I);
3018 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00003019 switch (IID) {
3020 default:
3021 break;
3022 case Intrinsic::maxnum:
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003023 return (isKnownNeverNaN(I->getOperand(0), TLI) &&
Sanjay Patelf9a0d592018-08-02 13:46:20 +00003024 cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI,
3025 SignBitOnly, Depth + 1)) ||
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003026 (isKnownNeverNaN(I->getOperand(1), TLI) &&
Sanjay Patelf9a0d592018-08-02 13:46:20 +00003027 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI,
3028 SignBitOnly, Depth + 1));
3029
Thomas Livelyc3392502018-10-19 19:01:26 +00003030 case Intrinsic::maximum:
3031 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3032 Depth + 1) ||
3033 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3034 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00003035 case Intrinsic::minnum:
Thomas Livelyc3392502018-10-19 19:01:26 +00003036 case Intrinsic::minimum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00003037 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3038 Depth + 1) &&
3039 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3040 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00003041 case Intrinsic::exp:
3042 case Intrinsic::exp2:
3043 case Intrinsic::fabs:
David Majnemer3ee5f342016-04-13 06:55:52 +00003044 return true;
Justin Lebar7e3184c2017-01-26 00:10:26 +00003045
3046 case Intrinsic::sqrt:
3047 // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0.
3048 if (!SignBitOnly)
3049 return true;
3050 return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
3051 CannotBeNegativeZero(CI->getOperand(0), TLI));
3052
David Majnemer3ee5f342016-04-13 06:55:52 +00003053 case Intrinsic::powi:
Justin Lebar7e3184c2017-01-26 00:10:26 +00003054 if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
David Majnemer3ee5f342016-04-13 06:55:52 +00003055 // powi(x,n) is non-negative if n is even.
Justin Lebar7e3184c2017-01-26 00:10:26 +00003056 if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
David Majnemer3ee5f342016-04-13 06:55:52 +00003057 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003058 }
Justin Lebar322c1272017-01-27 00:58:34 +00003059 // TODO: This is not correct. Given that exp is an integer, here are the
3060 // ways that pow can return a negative value:
3061 //
3062 // pow(x, exp) --> negative if exp is odd and x is negative.
3063 // pow(-0, exp) --> -inf if exp is negative odd.
3064 // pow(-0, exp) --> -0 if exp is positive odd.
3065 // pow(-inf, exp) --> -0 if exp is negative odd.
3066 // pow(-inf, exp) --> -inf if exp is positive odd.
3067 //
3068 // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
3069 // but we must return false if x == -0. Unfortunately we do not currently
3070 // have a way of expressing this constraint. See details in
3071 // https://llvm.org/bugs/show_bug.cgi?id=31702.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00003072 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3073 Depth + 1);
Justin Lebar322c1272017-01-27 00:58:34 +00003074
David Majnemer3ee5f342016-04-13 06:55:52 +00003075 case Intrinsic::fma:
3076 case Intrinsic::fmuladd:
3077 // x*x+y is non-negative if y is non-negative.
3078 return I->getOperand(0) == I->getOperand(1) &&
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00003079 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
3080 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
3081 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00003082 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003083 break;
3084 }
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003085 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003086}
3087
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00003088bool llvm::CannotBeOrderedLessThanZero(const Value *V,
3089 const TargetLibraryInfo *TLI) {
3090 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
3091}
3092
3093bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
3094 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
3095}
3096
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003097bool llvm::isKnownNeverNaN(const Value *V, const TargetLibraryInfo *TLI,
3098 unsigned Depth) {
Sanjay Patel6840c5f2017-09-05 23:13:13 +00003099 assert(V->getType()->isFPOrFPVectorTy() && "Querying for NaN on non-FP type");
3100
3101 // If we're told that NaNs won't happen, assume they won't.
3102 if (auto *FPMathOp = dyn_cast<FPMathOperator>(V))
3103 if (FPMathOp->hasNoNaNs())
3104 return true;
3105
Sanjay Patel6840c5f2017-09-05 23:13:13 +00003106 // Handle scalar constants.
3107 if (auto *CFP = dyn_cast<ConstantFP>(V))
3108 return !CFP->isNaN();
3109
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003110 if (Depth == MaxDepth)
3111 return false;
3112
Matt Arsenault450fcc72018-08-20 16:51:00 +00003113 if (auto *Inst = dyn_cast<Instruction>(V)) {
3114 switch (Inst->getOpcode()) {
3115 case Instruction::FAdd:
3116 case Instruction::FMul:
3117 case Instruction::FSub:
3118 case Instruction::FDiv:
3119 case Instruction::FRem: {
3120 // TODO: Need isKnownNeverInfinity
3121 return false;
3122 }
3123 case Instruction::Select: {
3124 return isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) &&
3125 isKnownNeverNaN(Inst->getOperand(2), TLI, Depth + 1);
3126 }
3127 case Instruction::SIToFP:
3128 case Instruction::UIToFP:
3129 return true;
3130 case Instruction::FPTrunc:
3131 case Instruction::FPExt:
3132 return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1);
3133 default:
3134 break;
3135 }
3136 }
3137
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003138 if (const auto *II = dyn_cast<IntrinsicInst>(V)) {
3139 switch (II->getIntrinsicID()) {
3140 case Intrinsic::canonicalize:
3141 case Intrinsic::fabs:
3142 case Intrinsic::copysign:
Matt Arsenault450fcc72018-08-20 16:51:00 +00003143 case Intrinsic::exp:
3144 case Intrinsic::exp2:
3145 case Intrinsic::floor:
3146 case Intrinsic::ceil:
3147 case Intrinsic::trunc:
3148 case Intrinsic::rint:
3149 case Intrinsic::nearbyint:
3150 case Intrinsic::round:
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003151 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1);
3152 case Intrinsic::sqrt:
3153 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) &&
3154 CannotBeOrderedLessThanZero(II->getArgOperand(0), TLI);
Sanjay Patele088d032019-05-07 22:58:31 +00003155 case Intrinsic::minnum:
3156 case Intrinsic::maxnum:
3157 // If either operand is not NaN, the result is not NaN.
3158 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) ||
3159 isKnownNeverNaN(II->getArgOperand(1), TLI, Depth + 1);
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003160 default:
3161 return false;
3162 }
3163 }
3164
Sanjay Patel6840c5f2017-09-05 23:13:13 +00003165 // Bail out for constant expressions, but try to handle vector constants.
3166 if (!V->getType()->isVectorTy() || !isa<Constant>(V))
3167 return false;
3168
3169 // For vectors, verify that each element is not NaN.
3170 unsigned NumElts = V->getType()->getVectorNumElements();
3171 for (unsigned i = 0; i != NumElts; ++i) {
3172 Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
3173 if (!Elt)
3174 return false;
3175 if (isa<UndefValue>(Elt))
3176 continue;
3177 auto *CElt = dyn_cast<ConstantFP>(Elt);
3178 if (!CElt || CElt->isNaN())
3179 return false;
3180 }
3181 // All elements were confirmed not-NaN or undefined.
3182 return true;
3183}
3184
Vitaly Bukad03bd1d2019-07-10 22:53:52 +00003185Value *llvm::isBytewiseValue(Value *V, const DataLayout &DL) {
JF Bastien73d8e4e2018-09-21 05:17:42 +00003186
Chris Lattner9cb10352010-12-26 20:15:01 +00003187 // All byte-wide stores are splatable, even of arbitrary variables.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003188 if (V->getType()->isIntegerTy(8))
3189 return V;
3190
3191 LLVMContext &Ctx = V->getContext();
3192
3193 // Undef don't care.
3194 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
3195 if (isa<UndefValue>(V))
3196 return UndefInt8;
3197
Vitaly Buka52096ee2019-07-12 02:23:07 +00003198 const uint64_t Size = DL.getTypeStoreSize(V->getType());
3199 if (!Size)
3200 return UndefInt8;
3201
JF Bastien73d8e4e2018-09-21 05:17:42 +00003202 Constant *C = dyn_cast<Constant>(V);
3203 if (!C) {
3204 // Conceptually, we could handle things like:
3205 // %a = zext i8 %X to i16
3206 // %b = shl i16 %a, 8
3207 // %c = or i16 %a, %b
3208 // but until there is an example that actually needs this, it doesn't seem
3209 // worth worrying about.
3210 return nullptr;
3211 }
Chris Lattneracf6b072011-02-19 19:35:49 +00003212
3213 // Handle 'null' ConstantArrayZero etc.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003214 if (C->isNullValue())
3215 return Constant::getNullValue(Type::getInt8Ty(Ctx));
Craig Topper1bef2c82012-12-22 19:15:35 +00003216
JF Bastien73d8e4e2018-09-21 05:17:42 +00003217 // Constant floating-point values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00003218 // corresponding integer value is "byteable". An important case is 0.0.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003219 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3220 Type *Ty = nullptr;
3221 if (CFP->getType()->isHalfTy())
3222 Ty = Type::getInt16Ty(Ctx);
3223 else if (CFP->getType()->isFloatTy())
3224 Ty = Type::getInt32Ty(Ctx);
3225 else if (CFP->getType()->isDoubleTy())
3226 Ty = Type::getInt64Ty(Ctx);
Chris Lattner9cb10352010-12-26 20:15:01 +00003227 // Don't handle long double formats, which have strange constraints.
Vitaly Bukad03bd1d2019-07-10 22:53:52 +00003228 return Ty ? isBytewiseValue(ConstantExpr::getBitCast(CFP, Ty), DL)
3229 : nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00003230 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003231
Benjamin Kramer17d90152015-02-07 19:29:02 +00003232 // We can handle constant integers that are multiple of 8 bits.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003233 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
Benjamin Kramer17d90152015-02-07 19:29:02 +00003234 if (CI->getBitWidth() % 8 == 0) {
3235 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
Benjamin Kramerb4b51502015-03-25 16:49:59 +00003236 if (!CI->getValue().isSplat(8))
Benjamin Kramer17d90152015-02-07 19:29:02 +00003237 return nullptr;
JF Bastien73d8e4e2018-09-21 05:17:42 +00003238 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
Chris Lattner9cb10352010-12-26 20:15:01 +00003239 }
3240 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003241
Vitaly Bukac559e632019-07-12 01:42:03 +00003242 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
3243 if (CE->getOpcode() == Instruction::IntToPtr) {
3244 auto PS = DL.getPointerSizeInBits(
3245 cast<PointerType>(CE->getType())->getAddressSpace());
3246 return isBytewiseValue(
3247 ConstantExpr::getIntegerCast(CE->getOperand(0),
3248 Type::getIntNTy(Ctx, PS), false),
3249 DL);
3250 }
3251 }
3252
JF Bastien73d8e4e2018-09-21 05:17:42 +00003253 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
3254 if (LHS == RHS)
3255 return LHS;
3256 if (!LHS || !RHS)
Craig Topper9f008862014-04-15 04:59:12 +00003257 return nullptr;
JF Bastien73d8e4e2018-09-21 05:17:42 +00003258 if (LHS == UndefInt8)
3259 return RHS;
3260 if (RHS == UndefInt8)
3261 return LHS;
3262 return nullptr;
3263 };
Craig Topper1bef2c82012-12-22 19:15:35 +00003264
JF Bastien73d8e4e2018-09-21 05:17:42 +00003265 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(C)) {
3266 Value *Val = UndefInt8;
3267 for (unsigned I = 0, E = CA->getNumElements(); I != E; ++I)
Vitaly Bukad03bd1d2019-07-10 22:53:52 +00003268 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
Craig Topper9f008862014-04-15 04:59:12 +00003269 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00003270 return Val;
3271 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00003272
Vitaly Bukab1bff762019-07-12 22:37:55 +00003273 if (isa<ConstantAggregate>(C)) {
JF Bastien73d8e4e2018-09-21 05:17:42 +00003274 Value *Val = UndefInt8;
3275 for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I)
Vitaly Bukad03bd1d2019-07-10 22:53:52 +00003276 if (!(Val = Merge(Val, isBytewiseValue(C->getOperand(I), DL))))
JF Bastien73d8e4e2018-09-21 05:17:42 +00003277 return nullptr;
3278 return Val;
3279 }
3280
3281 // Don't try to handle the handful of other constants.
Craig Topper9f008862014-04-15 04:59:12 +00003282 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00003283}
3284
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003285// This is the recursive version of BuildSubAggregate. It takes a few different
3286// arguments. Idxs is the index within the nested struct From that we are
3287// looking at now (which is of type IndexedType). IdxSkip is the number of
3288// indices from Idxs that should be left out when inserting into the resulting
3289// struct. To is the result struct built so far, new insertvalue instructions
3290// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00003291static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00003292 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00003293 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00003294 Instruction *InsertBefore) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003295 StructType *STy = dyn_cast<StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003296 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003297 // Save the original To argument so we can modify it
3298 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003299 // General case, the type indexed by Idxs is a struct
3300 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3301 // Process each struct element recursively
3302 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003303 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003304 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003305 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003306 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003307 if (!To) {
3308 // Couldn't find any inserted value for this index? Cleanup
3309 while (PrevTo != OrigTo) {
3310 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
3311 PrevTo = Del->getAggregateOperand();
3312 Del->eraseFromParent();
3313 }
3314 // Stop processing elements
3315 break;
3316 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003317 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00003318 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003319 if (To)
3320 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003321 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003322 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
3323 // the struct's elements had a value that was inserted directly. In the latter
3324 // case, perhaps we can't determine each of the subelements individually, but
3325 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00003326
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003327 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00003328 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003329
3330 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00003331 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003332
Vedant Kumard3196742018-02-28 19:08:52 +00003333 // Insert the value in the new (sub) aggregate
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003334 return InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
3335 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003336}
3337
3338// This helper takes a nested struct and extracts a part of it (which is again a
3339// struct) into a new value. For example, given the struct:
3340// { a, { b, { c, d }, e } }
3341// and the indices "1, 1" this returns
3342// { c, d }.
3343//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003344// It does this by inserting an insertvalue for each element in the resulting
3345// struct, as opposed to just inserting a single struct. This will only work if
3346// each of the elements of the substruct are known (ie, inserted into From by an
3347// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003348//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003349// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00003350static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00003351 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00003352 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00003353 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00003354 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00003355 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00003356 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003357 unsigned IdxSkip = Idxs.size();
3358
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003359 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003360}
3361
Vedant Kumard3196742018-02-28 19:08:52 +00003362/// Given an aggregate and a sequence of indices, see if the scalar value
3363/// indexed is already around as a register, for example if it was inserted
3364/// directly into the aggregate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003365///
3366/// If InsertBefore is not null, this function will duplicate (modified)
3367/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00003368Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
3369 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003370 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003371 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00003372 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003373 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003374 // We have indices, so V should have an indexable type.
3375 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
3376 "Not looking at a struct or array?");
3377 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
3378 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00003379
Chris Lattner67058832012-01-25 06:48:06 +00003380 if (Constant *C = dyn_cast<Constant>(V)) {
3381 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00003382 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00003383 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
3384 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003385
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003386 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003387 // Loop the indices for the insertvalue instruction in parallel with the
3388 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00003389 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003390 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
3391 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00003392 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003393 // We can't handle this without inserting insertvalues
3394 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00003395 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003396
3397 // The requested index identifies a part of a nested aggregate. Handle
3398 // this specially. For example,
3399 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
3400 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
3401 // %C = extractvalue {i32, { i32, i32 } } %B, 1
3402 // This can be changed into
3403 // %A = insertvalue {i32, i32 } undef, i32 10, 0
3404 // %C = insertvalue {i32, i32 } %A, i32 11, 1
3405 // which allows the unused 0,0 element from the nested struct to be
3406 // removed.
3407 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
3408 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00003409 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003410
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003411 // This insert value inserts something else than what we are looking for.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003412 // See if the (aggregate) value inserted into has the value we are
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003413 // looking for, then.
3414 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00003415 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003416 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003417 }
3418 // If we end up here, the indices of the insertvalue match with those
3419 // requested (though possibly only partially). Now we recursively look at
3420 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00003421 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00003422 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003423 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003424 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003425
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003426 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003427 // If we're extracting a value from an aggregate that was extracted from
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003428 // something else, we can extract from that something else directly instead.
3429 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00003430
3431 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00003432 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003433 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00003434 SmallVector<unsigned, 5> Idxs;
3435 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003436 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00003437 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00003438
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003439 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00003440 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003441
Craig Topper1bef2c82012-12-22 19:15:35 +00003442 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003443 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00003444
Jay Foad57aa6362011-07-13 10:26:04 +00003445 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003446 }
3447 // Otherwise, we don't know (such as, extracting from a function return value
3448 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00003449 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003450}
Evan Chengda3db112008-06-30 07:31:25 +00003451
Matthias Braun50ec0b52017-05-19 22:37:09 +00003452bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP,
3453 unsigned CharSize) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003454 // Make sure the GEP has exactly three arguments.
3455 if (GEP->getNumOperands() != 3)
3456 return false;
3457
Matthias Braun50ec0b52017-05-19 22:37:09 +00003458 // Make sure the index-ee is a pointer to array of \p CharSize integers.
3459 // CharSize.
David L Kreitzer752c1442016-04-13 14:31:06 +00003460 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
Matthias Braun50ec0b52017-05-19 22:37:09 +00003461 if (!AT || !AT->getElementType()->isIntegerTy(CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +00003462 return false;
3463
3464 // Check to make sure that the first operand of the GEP is an integer and
3465 // has value 0 so that we are sure we're indexing into the initializer.
3466 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
3467 if (!FirstIdx || !FirstIdx->isZero())
3468 return false;
3469
3470 return true;
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003471}
Chris Lattnere28618d2010-11-30 22:25:26 +00003472
Matthias Braun50ec0b52017-05-19 22:37:09 +00003473bool llvm::getConstantDataArrayInfo(const Value *V,
3474 ConstantDataArraySlice &Slice,
3475 unsigned ElementSize, uint64_t Offset) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003476 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00003477
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003478 // Look through bitcast instructions and geps.
3479 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00003480
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00003481 // If the value is a GEP instruction or constant expression, treat it as an
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003482 // offset.
3483 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003484 // The GEP operator should be based on a pointer to string constant, and is
3485 // indexing into the string constant.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003486 if (!isGEPBasedOnPointerToString(GEP, ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003487 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003488
Evan Chengda3db112008-06-30 07:31:25 +00003489 // If the second index isn't a ConstantInt, then this is a variable index
3490 // into the array. If this occurs, we can't say anything meaningful about
3491 // the string.
3492 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00003493 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00003494 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003495 else
3496 return false;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003497 return getConstantDataArrayInfo(GEP->getOperand(0), Slice, ElementSize,
3498 StartIdx + Offset);
Evan Chengda3db112008-06-30 07:31:25 +00003499 }
Nick Lewycky46209882011-10-20 00:34:35 +00003500
Evan Chengda3db112008-06-30 07:31:25 +00003501 // The GEP instruction, constant or instruction, must reference a global
3502 // variable that is a constant and is initialized. The referenced constant
3503 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003504 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00003505 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003506 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003507
Matthias Braun50ec0b52017-05-19 22:37:09 +00003508 const ConstantDataArray *Array;
3509 ArrayType *ArrayTy;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003510 if (GV->getInitializer()->isNullValue()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003511 Type *GVTy = GV->getValueType();
3512 if ( (ArrayTy = dyn_cast<ArrayType>(GVTy)) ) {
Sanjay Patel2ad88f82017-06-12 22:34:37 +00003513 // A zeroinitializer for the array; there is no ConstantDataArray.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003514 Array = nullptr;
3515 } else {
3516 const DataLayout &DL = GV->getParent()->getDataLayout();
3517 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy);
3518 uint64_t Length = SizeInBytes / (ElementSize / 8);
3519 if (Length <= Offset)
3520 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003521
Matthias Braun50ec0b52017-05-19 22:37:09 +00003522 Slice.Array = nullptr;
3523 Slice.Offset = 0;
3524 Slice.Length = Length - Offset;
3525 return true;
3526 }
3527 } else {
3528 // This must be a ConstantDataArray.
3529 Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
3530 if (!Array)
3531 return false;
3532 ArrayTy = Array->getType();
3533 }
3534 if (!ArrayTy->getElementType()->isIntegerTy(ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003535 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003536
Matthias Braun50ec0b52017-05-19 22:37:09 +00003537 uint64_t NumElts = ArrayTy->getArrayNumElements();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003538 if (Offset > NumElts)
3539 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003540
Matthias Braun50ec0b52017-05-19 22:37:09 +00003541 Slice.Array = Array;
3542 Slice.Offset = Offset;
3543 Slice.Length = NumElts - Offset;
3544 return true;
3545}
3546
3547/// This function computes the length of a null-terminated C string pointed to
3548/// by V. If successful, it returns true and returns the string in Str.
3549/// If unsuccessful, it returns false.
3550bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
3551 uint64_t Offset, bool TrimAtNul) {
3552 ConstantDataArraySlice Slice;
3553 if (!getConstantDataArrayInfo(V, Slice, 8, Offset))
3554 return false;
3555
3556 if (Slice.Array == nullptr) {
3557 if (TrimAtNul) {
3558 Str = StringRef();
3559 return true;
3560 }
3561 if (Slice.Length == 1) {
3562 Str = StringRef("", 1);
3563 return true;
3564 }
Sanjay Patelfef83e82017-06-09 14:21:18 +00003565 // We cannot instantiate a StringRef as we do not have an appropriate string
Matthias Braun50ec0b52017-05-19 22:37:09 +00003566 // of 0s at hand.
3567 return false;
3568 }
3569
3570 // Start out with the entire array in the StringRef.
3571 Str = Slice.Array->getAsString();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003572 // Skip over 'offset' bytes.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003573 Str = Str.substr(Slice.Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00003574
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003575 if (TrimAtNul) {
3576 // Trim off the \0 and anything after it. If the array is not nul
3577 // terminated, we just return the whole end of string. The client may know
3578 // some other way that the string is length-bound.
3579 Str = Str.substr(0, Str.find('\0'));
3580 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003581 return true;
Evan Chengda3db112008-06-30 07:31:25 +00003582}
Eric Christopher4899cbc2010-03-05 06:58:57 +00003583
3584// These next two are very similar to the above, but also look through PHI
3585// nodes.
3586// TODO: See if we can integrate these two together.
3587
Sanjay Patelaee84212014-11-04 16:27:42 +00003588/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003589/// the specified pointer, return 'len+1'. If we can't, return 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00003590static uint64_t GetStringLengthH(const Value *V,
Matthias Braun50ec0b52017-05-19 22:37:09 +00003591 SmallPtrSetImpl<const PHINode*> &PHIs,
3592 unsigned CharSize) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003593 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003594 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00003595
3596 // If this is a PHI node, there are two cases: either we have already seen it
3597 // or we haven't.
Pete Cooper35b00d52016-08-13 01:05:32 +00003598 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
David Blaikie70573dc2014-11-19 07:49:26 +00003599 if (!PHIs.insert(PN).second)
Eric Christopher4899cbc2010-03-05 06:58:57 +00003600 return ~0ULL; // already in the set.
3601
3602 // If it was new, see if all the input strings are the same length.
3603 uint64_t LenSoFar = ~0ULL;
Pete Cooper833f34d2015-05-12 20:05:31 +00003604 for (Value *IncValue : PN->incoming_values()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003605 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003606 if (Len == 0) return 0; // Unknown length -> unknown.
3607
3608 if (Len == ~0ULL) continue;
3609
3610 if (Len != LenSoFar && LenSoFar != ~0ULL)
3611 return 0; // Disagree -> unknown.
3612 LenSoFar = Len;
3613 }
3614
3615 // Success, all agree.
3616 return LenSoFar;
3617 }
3618
3619 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
Pete Cooper35b00d52016-08-13 01:05:32 +00003620 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003621 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003622 if (Len1 == 0) return 0;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003623 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003624 if (Len2 == 0) return 0;
3625 if (Len1 == ~0ULL) return Len2;
3626 if (Len2 == ~0ULL) return Len1;
3627 if (Len1 != Len2) return 0;
3628 return Len1;
3629 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003630
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003631 // Otherwise, see if we can read the string.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003632 ConstantDataArraySlice Slice;
3633 if (!getConstantDataArrayInfo(V, Slice, CharSize))
Eric Christopher4899cbc2010-03-05 06:58:57 +00003634 return 0;
3635
Matthias Braun50ec0b52017-05-19 22:37:09 +00003636 if (Slice.Array == nullptr)
3637 return 1;
3638
3639 // Search for nul characters
3640 unsigned NullIndex = 0;
3641 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
3642 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
3643 break;
3644 }
3645
3646 return NullIndex + 1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003647}
3648
Sanjay Patelaee84212014-11-04 16:27:42 +00003649/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003650/// the specified pointer, return 'len+1'. If we can't, return 0.
David Bolvansky1f343fa2018-05-22 20:27:36 +00003651uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
David Bolvansky41f4b642018-05-22 15:41:23 +00003652 if (!V->getType()->isPointerTy())
3653 return 0;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003654
Pete Cooper35b00d52016-08-13 01:05:32 +00003655 SmallPtrSet<const PHINode*, 32> PHIs;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003656 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003657 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
3658 // an empty string as a length.
3659 return Len == ~0ULL ? 1 : Len;
3660}
Dan Gohmana4fcd242010-12-15 20:02:24 +00003661
Florian Hahnfd72bf22019-08-15 12:13:02 +00003662const Value *
3663llvm::getArgumentAliasingToReturnedPointer(const CallBase *Call,
3664 bool MustPreserveNullness) {
Chandler Carruth363ac682019-01-07 05:42:51 +00003665 assert(Call &&
3666 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
3667 if (const Value *RV = Call->getReturnedArgOperand())
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003668 return RV;
3669 // This can be used only as a aliasing property.
Florian Hahnfd72bf22019-08-15 12:13:02 +00003670 if (isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
3671 Call, MustPreserveNullness))
Chandler Carruth363ac682019-01-07 05:42:51 +00003672 return Call->getArgOperand(0);
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003673 return nullptr;
3674}
3675
3676bool llvm::isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
Florian Hahnfd72bf22019-08-15 12:13:02 +00003677 const CallBase *Call, bool MustPreserveNullness) {
Chandler Carruth363ac682019-01-07 05:42:51 +00003678 return Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
Evgeniy Stepanov50dc28b2019-07-03 20:19:14 +00003679 Call->getIntrinsicID() == Intrinsic::strip_invariant_group ||
Evgeniy Stepanovd752f5e2019-07-17 19:24:02 +00003680 Call->getIntrinsicID() == Intrinsic::aarch64_irg ||
Florian Hahn3f2850b2019-08-15 18:39:56 +00003681 Call->getIntrinsicID() == Intrinsic::aarch64_tagp ||
3682 (!MustPreserveNullness &&
3683 Call->getIntrinsicID() == Intrinsic::ptrmask);
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003684}
3685
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003686/// \p PN defines a loop-variant pointer to an object. Check if the
Adam Nemete2b885c2015-04-23 20:09:20 +00003687/// previous iteration of the loop was referring to the same object as \p PN.
Pete Cooper35b00d52016-08-13 01:05:32 +00003688static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
3689 const LoopInfo *LI) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003690 // Find the loop-defined value.
3691 Loop *L = LI->getLoopFor(PN->getParent());
3692 if (PN->getNumIncomingValues() != 2)
3693 return true;
3694
3695 // Find the value from previous iteration.
3696 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3697 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3698 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3699 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3700 return true;
3701
3702 // If a new pointer is loaded in the loop, the pointer references a different
3703 // object in every iteration. E.g.:
3704 // for (i)
3705 // int *p = a[i];
3706 // ...
3707 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3708 if (!L->isLoopInvariant(Load->getPointerOperand()))
3709 return false;
3710 return true;
3711}
3712
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003713Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3714 unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003715 if (!V->getType()->isPointerTy())
3716 return V;
3717 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3718 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3719 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00003720 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3721 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003722 V = cast<Operator>(V)->getOperand(0);
3723 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003724 if (GA->isInterposable())
Dan Gohmana4fcd242010-12-15 20:02:24 +00003725 return V;
3726 V = GA->getAliasee();
Craig Topper85482412017-04-12 22:29:23 +00003727 } else if (isa<AllocaInst>(V)) {
3728 // An alloca can't be further simplified.
3729 return V;
Dan Gohmana4fcd242010-12-15 20:02:24 +00003730 } else {
Chandler Carruth363ac682019-01-07 05:42:51 +00003731 if (auto *Call = dyn_cast<CallBase>(V)) {
Piotr Padlewski5b3db452018-07-02 04:49:30 +00003732 // CaptureTracking can know about special capturing properties of some
3733 // intrinsics like launder.invariant.group, that can't be expressed with
3734 // the attributes, but have properties like returning aliasing pointer.
3735 // Because some analysis may assume that nocaptured pointer is not
3736 // returned from some special intrinsic (because function would have to
3737 // be marked with returns attribute), it is crucial to use this function
3738 // because it should be in sync with CaptureTracking. Not using it may
3739 // cause weird miscompilations where 2 aliasing pointers are assumed to
3740 // noalias.
Florian Hahn3f2850b2019-08-15 18:39:56 +00003741 if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) {
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003742 V = RP;
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003743 continue;
3744 }
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003745 }
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003746
Dan Gohman05b18f12010-12-15 20:49:55 +00003747 // See if InstructionSimplify knows any relevant tricks.
3748 if (Instruction *I = dyn_cast<Instruction>(V))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003749 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00003750 if (Value *Simplified = SimplifyInstruction(I, {DL, I})) {
Dan Gohman05b18f12010-12-15 20:49:55 +00003751 V = Simplified;
3752 continue;
3753 }
3754
Dan Gohmana4fcd242010-12-15 20:02:24 +00003755 return V;
3756 }
3757 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3758 }
3759 return V;
3760}
Nick Lewycky3e334a42011-06-27 04:20:45 +00003761
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003762void llvm::GetUnderlyingObjects(const Value *V,
3763 SmallVectorImpl<const Value *> &Objects,
Adam Nemete2b885c2015-04-23 20:09:20 +00003764 const DataLayout &DL, LoopInfo *LI,
3765 unsigned MaxLookup) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003766 SmallPtrSet<const Value *, 4> Visited;
3767 SmallVector<const Value *, 4> Worklist;
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003768 Worklist.push_back(V);
3769 do {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003770 const Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003771 P = GetUnderlyingObject(P, DL, MaxLookup);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003772
David Blaikie70573dc2014-11-19 07:49:26 +00003773 if (!Visited.insert(P).second)
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003774 continue;
3775
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003776 if (auto *SI = dyn_cast<SelectInst>(P)) {
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003777 Worklist.push_back(SI->getTrueValue());
3778 Worklist.push_back(SI->getFalseValue());
3779 continue;
3780 }
3781
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003782 if (auto *PN = dyn_cast<PHINode>(P)) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003783 // If this PHI changes the underlying object in every iteration of the
3784 // loop, don't look through it. Consider:
3785 // int **A;
3786 // for (i) {
3787 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
3788 // Curr = A[i];
3789 // *Prev, *Curr;
3790 //
3791 // Prev is tracking Curr one iteration behind so they refer to different
3792 // underlying objects.
3793 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3794 isSameUnderlyingObjectInLoop(PN, LI))
Pete Cooper833f34d2015-05-12 20:05:31 +00003795 for (Value *IncValue : PN->incoming_values())
3796 Worklist.push_back(IncValue);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003797 continue;
3798 }
3799
3800 Objects.push_back(P);
3801 } while (!Worklist.empty());
3802}
3803
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003804/// This is the function that does the work of looking through basic
3805/// ptrtoint+arithmetic+inttoptr sequences.
3806static const Value *getUnderlyingObjectFromInt(const Value *V) {
3807 do {
3808 if (const Operator *U = dyn_cast<Operator>(V)) {
3809 // If we find a ptrtoint, we can transfer control back to the
3810 // regular getUnderlyingObjectFromInt.
3811 if (U->getOpcode() == Instruction::PtrToInt)
3812 return U->getOperand(0);
3813 // If we find an add of a constant, a multiplied value, or a phi, it's
3814 // likely that the other operand will lead us to the base
3815 // object. We don't have to worry about the case where the
3816 // object address is somehow being computed by the multiply,
3817 // because our callers only care when the result is an
3818 // identifiable object.
3819 if (U->getOpcode() != Instruction::Add ||
3820 (!isa<ConstantInt>(U->getOperand(1)) &&
3821 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
3822 !isa<PHINode>(U->getOperand(1))))
3823 return V;
3824 V = U->getOperand(0);
3825 } else {
3826 return V;
3827 }
3828 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
3829 } while (true);
3830}
3831
3832/// This is a wrapper around GetUnderlyingObjects and adds support for basic
3833/// ptrtoint+arithmetic+inttoptr sequences.
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003834/// It returns false if unidentified object is found in GetUnderlyingObjects.
3835bool llvm::getUnderlyingObjectsForCodeGen(const Value *V,
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003836 SmallVectorImpl<Value *> &Objects,
3837 const DataLayout &DL) {
3838 SmallPtrSet<const Value *, 16> Visited;
3839 SmallVector<const Value *, 4> Working(1, V);
3840 do {
3841 V = Working.pop_back_val();
3842
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003843 SmallVector<const Value *, 4> Objs;
3844 GetUnderlyingObjects(V, Objs, DL);
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003845
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003846 for (const Value *V : Objs) {
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003847 if (!Visited.insert(V).second)
3848 continue;
3849 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
3850 const Value *O =
3851 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
3852 if (O->getType()->isPointerTy()) {
3853 Working.push_back(O);
3854 continue;
3855 }
3856 }
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003857 // If GetUnderlyingObjects fails to find an identifiable object,
3858 // getUnderlyingObjectsForCodeGen also fails for safety.
3859 if (!isIdentifiedObject(V)) {
3860 Objects.clear();
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003861 return false;
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003862 }
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003863 Objects.push_back(const_cast<Value *>(V));
3864 }
3865 } while (!Working.empty());
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003866 return true;
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003867}
3868
Sanjay Patelaee84212014-11-04 16:27:42 +00003869/// Return true if the only users of this pointer are lifetime markers.
Nick Lewycky3e334a42011-06-27 04:20:45 +00003870bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003871 for (const User *U : V->users()) {
3872 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00003873 if (!II) return false;
3874
Vedant Kumarb264d692018-12-21 21:49:40 +00003875 if (!II->isLifetimeStartOrEnd())
Nick Lewycky3e334a42011-06-27 04:20:45 +00003876 return false;
3877 }
3878 return true;
3879}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003880
Philip Reames1e1db802019-09-10 21:12:29 +00003881bool llvm::mustSuppressSpeculation(const LoadInst &LI) {
3882 if (!LI.isUnordered())
3883 return true;
3884 const Function &F = *LI.getFunction();
3885 // Speculative load may create a race that did not exist in the source.
3886 return F.hasFnAttribute(Attribute::SanitizeThread) ||
3887 // Speculative load may load data from dirty regions.
3888 F.hasFnAttribute(Attribute::SanitizeAddress) ||
3889 F.hasFnAttribute(Attribute::SanitizeHWAddress);
3890}
3891
3892
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003893bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3894 const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003895 const DominatorTree *DT) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00003896 const Operator *Inst = dyn_cast<Operator>(V);
3897 if (!Inst)
3898 return false;
3899
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003900 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3901 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3902 if (C->canTrap())
3903 return false;
3904
3905 switch (Inst->getOpcode()) {
3906 default:
3907 return true;
3908 case Instruction::UDiv:
David Majnemerf20d7c42014-11-04 23:49:08 +00003909 case Instruction::URem: {
3910 // x / y is undefined if y == 0.
3911 const APInt *V;
3912 if (match(Inst->getOperand(1), m_APInt(V)))
3913 return *V != 0;
3914 return false;
3915 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003916 case Instruction::SDiv:
3917 case Instruction::SRem: {
David Majnemerf20d7c42014-11-04 23:49:08 +00003918 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
David Majnemer8a6578a2015-02-01 19:10:19 +00003919 const APInt *Numerator, *Denominator;
3920 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3921 return false;
3922 // We cannot hoist this division if the denominator is 0.
3923 if (*Denominator == 0)
3924 return false;
3925 // It's safe to hoist if the denominator is not 0 or -1.
3926 if (*Denominator != -1)
3927 return true;
3928 // At this point we know that the denominator is -1. It is safe to hoist as
3929 // long we know that the numerator is not INT_MIN.
3930 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3931 return !Numerator->isMinSignedValue();
3932 // The numerator *might* be MinSignedValue.
David Majnemerf20d7c42014-11-04 23:49:08 +00003933 return false;
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003934 }
3935 case Instruction::Load: {
3936 const LoadInst *LI = cast<LoadInst>(Inst);
Philip Reames1e1db802019-09-10 21:12:29 +00003937 if (mustSuppressSpeculation(*LI))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003938 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003939 const DataLayout &DL = LI->getModule()->getDataLayout();
Sean Silva45835e72016-07-02 23:47:27 +00003940 return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
Tim Northover60afa492019-07-09 11:35:35 +00003941 LI->getType(), LI->getAlignment(),
3942 DL, CtxI, DT);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003943 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003944 case Instruction::Call: {
Matt Arsenaultcf5e7fe2017-04-28 21:13:09 +00003945 auto *CI = cast<const CallInst>(Inst);
3946 const Function *Callee = CI->getCalledFunction();
David Majnemer0a92f862015-08-28 21:13:39 +00003947
Matt Arsenault6a288c12017-05-03 02:26:10 +00003948 // The called function could have undefined behavior or side-effects, even
3949 // if marked readnone nounwind.
3950 return Callee && Callee->isSpeculatable();
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003951 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003952 case Instruction::VAArg:
3953 case Instruction::Alloca:
3954 case Instruction::Invoke:
Craig Topper784929d2019-02-08 20:48:56 +00003955 case Instruction::CallBr:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003956 case Instruction::PHI:
3957 case Instruction::Store:
3958 case Instruction::Ret:
3959 case Instruction::Br:
3960 case Instruction::IndirectBr:
3961 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003962 case Instruction::Unreachable:
3963 case Instruction::Fence:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003964 case Instruction::AtomicRMW:
3965 case Instruction::AtomicCmpXchg:
David Majnemer654e1302015-07-31 17:58:14 +00003966 case Instruction::LandingPad:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003967 case Instruction::Resume:
David Majnemer8a1c45d2015-12-12 05:38:55 +00003968 case Instruction::CatchSwitch:
David Majnemer654e1302015-07-31 17:58:14 +00003969 case Instruction::CatchPad:
David Majnemer654e1302015-07-31 17:58:14 +00003970 case Instruction::CatchRet:
3971 case Instruction::CleanupPad:
3972 case Instruction::CleanupRet:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003973 return false; // Misc instructions which have effects
3974 }
3975}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003976
Quentin Colombet6443cce2015-08-06 18:44:34 +00003977bool llvm::mayBeMemoryDependent(const Instruction &I) {
3978 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3979}
3980
Nikita Popovd0f13e62019-05-26 13:22:01 +00003981/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
3982static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR) {
3983 switch (OR) {
3984 case ConstantRange::OverflowResult::MayOverflow:
3985 return OverflowResult::MayOverflow;
Nikita Popov332c1002019-05-28 18:08:31 +00003986 case ConstantRange::OverflowResult::AlwaysOverflowsLow:
3987 return OverflowResult::AlwaysOverflowsLow;
3988 case ConstantRange::OverflowResult::AlwaysOverflowsHigh:
3989 return OverflowResult::AlwaysOverflowsHigh;
Nikita Popovd0f13e62019-05-26 13:22:01 +00003990 case ConstantRange::OverflowResult::NeverOverflows:
3991 return OverflowResult::NeverOverflows;
3992 }
3993 llvm_unreachable("Unknown OverflowResult");
3994}
3995
3996/// Combine constant ranges from computeConstantRange() and computeKnownBits().
3997static ConstantRange computeConstantRangeIncludingKnownBits(
3998 const Value *V, bool ForSigned, const DataLayout &DL, unsigned Depth,
3999 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4000 OptimizationRemarkEmitter *ORE = nullptr, bool UseInstrInfo = true) {
4001 KnownBits Known = computeKnownBits(
4002 V, DL, Depth, AC, CxtI, DT, ORE, UseInstrInfo);
4003 ConstantRange CR1 = ConstantRange::fromKnownBits(Known, ForSigned);
4004 ConstantRange CR2 = computeConstantRange(V, UseInstrInfo);
4005 ConstantRange::PreferredRangeType RangeType =
4006 ForSigned ? ConstantRange::Signed : ConstantRange::Unsigned;
4007 return CR1.intersectWith(CR2, RangeType);
4008}
4009
Florian Hahn19f9e322018-08-17 14:39:04 +00004010OverflowResult llvm::computeOverflowForUnsignedMul(
4011 const Value *LHS, const Value *RHS, const DataLayout &DL,
4012 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4013 bool UseInstrInfo) {
Nikita Popovd0f13e62019-05-26 13:22:01 +00004014 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
4015 nullptr, UseInstrInfo);
4016 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
4017 nullptr, UseInstrInfo);
4018 ConstantRange LHSRange = ConstantRange::fromKnownBits(LHSKnown, false);
4019 ConstantRange RHSRange = ConstantRange::fromKnownBits(RHSKnown, false);
4020 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
David Majnemer491331a2015-01-02 07:29:43 +00004021}
David Majnemer5310c1e2015-01-07 00:39:50 +00004022
Florian Hahn19f9e322018-08-17 14:39:04 +00004023OverflowResult
4024llvm::computeOverflowForSignedMul(const Value *LHS, const Value *RHS,
4025 const DataLayout &DL, AssumptionCache *AC,
4026 const Instruction *CxtI,
4027 const DominatorTree *DT, bool UseInstrInfo) {
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004028 // Multiplying n * m significant bits yields a result of n + m significant
4029 // bits. If the total number of significant bits does not exceed the
4030 // result bit width (minus 1), there is no overflow.
4031 // This means if we have enough leading sign bits in the operands
4032 // we can guarantee that the result does not overflow.
4033 // Ref: "Hacker's Delight" by Henry Warren
4034 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
4035
4036 // Note that underestimating the number of sign bits gives a more
4037 // conservative answer.
4038 unsigned SignBits = ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) +
4039 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT);
4040
4041 // First handle the easy case: if we have enough sign bits there's
4042 // definitely no overflow.
4043 if (SignBits > BitWidth + 1)
4044 return OverflowResult::NeverOverflows;
4045
4046 // There are two ambiguous cases where there can be no overflow:
4047 // SignBits == BitWidth + 1 and
4048 // SignBits == BitWidth
4049 // The second case is difficult to check, therefore we only handle the
4050 // first case.
4051 if (SignBits == BitWidth + 1) {
4052 // It overflows only when both arguments are negative and the true
4053 // product is exactly the minimum negative number.
4054 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
4055 // For simplicity we just check if at least one side is not negative.
Florian Hahn19f9e322018-08-17 14:39:04 +00004056 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
4057 nullptr, UseInstrInfo);
4058 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
4059 nullptr, UseInstrInfo);
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004060 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
4061 return OverflowResult::NeverOverflows;
4062 }
4063 return OverflowResult::MayOverflow;
4064}
4065
Florian Hahn19f9e322018-08-17 14:39:04 +00004066OverflowResult llvm::computeOverflowForUnsignedAdd(
4067 const Value *LHS, const Value *RHS, const DataLayout &DL,
4068 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4069 bool UseInstrInfo) {
Nikita Popov20838192019-03-19 17:53:56 +00004070 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4071 LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
4072 nullptr, UseInstrInfo);
4073 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4074 RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
4075 nullptr, UseInstrInfo);
Nikita Popov614b1be2019-03-15 18:37:45 +00004076 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
David Majnemer5310c1e2015-01-07 00:39:50 +00004077}
James Molloy71b91c22015-05-11 14:42:20 +00004078
Pete Cooper35b00d52016-08-13 01:05:32 +00004079static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
4080 const Value *RHS,
4081 const AddOperator *Add,
4082 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004083 AssumptionCache *AC,
Pete Cooper35b00d52016-08-13 01:05:32 +00004084 const Instruction *CxtI,
4085 const DominatorTree *DT) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00004086 if (Add && Add->hasNoSignedWrap()) {
4087 return OverflowResult::NeverOverflows;
4088 }
4089
Craig Topperbb973722017-05-15 02:44:08 +00004090 // If LHS and RHS each have at least two sign bits, the addition will look
4091 // like
4092 //
4093 // XX..... +
4094 // YY.....
4095 //
4096 // If the carry into the most significant position is 0, X and Y can't both
4097 // be 1 and therefore the carry out of the addition is also 0.
4098 //
4099 // If the carry into the most significant position is 1, X and Y can't both
4100 // be 0 and therefore the carry out of the addition is also 1.
4101 //
4102 // Since the carry into the most significant position is always equal to
4103 // the carry out of the addition, there is no signed overflow.
4104 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4105 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4106 return OverflowResult::NeverOverflows;
4107
Nikita Popov10edd2b2019-04-09 16:12:59 +00004108 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4109 LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4110 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4111 RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
Nikita Popov322e2db2019-03-17 21:25:26 +00004112 OverflowResult OR =
4113 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
4114 if (OR != OverflowResult::MayOverflow)
4115 return OR;
Jingyue Wu10fcea52015-08-20 18:27:04 +00004116
4117 // The remaining code needs Add to be available. Early returns if not so.
4118 if (!Add)
4119 return OverflowResult::MayOverflow;
4120
4121 // If the sign of Add is the same as at least one of the operands, this add
Nikita Popov280a6b02019-03-22 17:51:40 +00004122 // CANNOT overflow. If this can be determined from the known bits of the
4123 // operands the above signedAddMayOverflow() check will have already done so.
4124 // The only other way to improve on the known bits is from an assumption, so
4125 // call computeKnownBitsFromAssume() directly.
Jingyue Wu10fcea52015-08-20 18:27:04 +00004126 bool LHSOrRHSKnownNonNegative =
Nikita Popov6e9157d2019-04-09 07:13:09 +00004127 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
Fangrui Songf78650a2018-07-30 19:41:25 +00004128 bool LHSOrRHSKnownNegative =
Nikita Popov6e9157d2019-04-09 07:13:09 +00004129 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
Jingyue Wu10fcea52015-08-20 18:27:04 +00004130 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
Nikita Popov6e9157d2019-04-09 07:13:09 +00004131 KnownBits AddKnown(LHSRange.getBitWidth());
Nikita Popov280a6b02019-03-22 17:51:40 +00004132 computeKnownBitsFromAssume(
4133 Add, AddKnown, /*Depth=*/0, Query(DL, AC, CxtI, DT, true));
Craig Topper6e11a052017-05-08 16:22:48 +00004134 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
Nikita Popov280a6b02019-03-22 17:51:40 +00004135 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
Jingyue Wu10fcea52015-08-20 18:27:04 +00004136 return OverflowResult::NeverOverflows;
Jingyue Wu10fcea52015-08-20 18:27:04 +00004137 }
4138
4139 return OverflowResult::MayOverflow;
4140}
4141
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004142OverflowResult llvm::computeOverflowForUnsignedSub(const Value *LHS,
4143 const Value *RHS,
4144 const DataLayout &DL,
4145 AssumptionCache *AC,
4146 const Instruction *CxtI,
4147 const DominatorTree *DT) {
Nikita Popov20838192019-03-19 17:53:56 +00004148 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4149 LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
4150 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4151 RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
Nikita Popov614b1be2019-03-15 18:37:45 +00004152 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004153}
4154
4155OverflowResult llvm::computeOverflowForSignedSub(const Value *LHS,
4156 const Value *RHS,
4157 const DataLayout &DL,
4158 AssumptionCache *AC,
4159 const Instruction *CxtI,
4160 const DominatorTree *DT) {
4161 // If LHS and RHS each have at least two sign bits, the subtraction
4162 // cannot overflow.
4163 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4164 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4165 return OverflowResult::NeverOverflows;
4166
Nikita Popov4b2323d2019-04-09 17:01:49 +00004167 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4168 LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4169 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4170 RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
Nikita Popov3af5b282019-03-21 17:23:51 +00004171 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004172}
4173
Nikita Popov79dffc62019-04-16 18:55:16 +00004174bool llvm::isOverflowIntrinsicNoWrap(const WithOverflowInst *WO,
Pete Cooper35b00d52016-08-13 01:05:32 +00004175 const DominatorTree &DT) {
Pete Cooper35b00d52016-08-13 01:05:32 +00004176 SmallVector<const BranchInst *, 2> GuardingBranches;
4177 SmallVector<const ExtractValueInst *, 2> Results;
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004178
Nikita Popov79dffc62019-04-16 18:55:16 +00004179 for (const User *U : WO->users()) {
Pete Cooper35b00d52016-08-13 01:05:32 +00004180 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004181 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
4182
4183 if (EVI->getIndices()[0] == 0)
4184 Results.push_back(EVI);
4185 else {
4186 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
4187
Pete Cooper35b00d52016-08-13 01:05:32 +00004188 for (const auto *U : EVI->users())
4189 if (const auto *B = dyn_cast<BranchInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004190 assert(B->isConditional() && "How else is it using an i1?");
4191 GuardingBranches.push_back(B);
4192 }
4193 }
4194 } else {
4195 // We are using the aggregate directly in a way we don't want to analyze
4196 // here (storing it to a global, say).
4197 return false;
4198 }
4199 }
4200
Pete Cooper35b00d52016-08-13 01:05:32 +00004201 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004202 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
4203 if (!NoWrapEdge.isSingleEdge())
4204 return false;
4205
4206 // Check if all users of the add are provably no-wrap.
Pete Cooper35b00d52016-08-13 01:05:32 +00004207 for (const auto *Result : Results) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004208 // If the extractvalue itself is not executed on overflow, the we don't
4209 // need to check each use separately, since domination is transitive.
4210 if (DT.dominates(NoWrapEdge, Result->getParent()))
4211 continue;
4212
4213 for (auto &RU : Result->uses())
4214 if (!DT.dominates(NoWrapEdge, RU))
4215 return false;
4216 }
4217
4218 return true;
4219 };
4220
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004221 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004222}
4223
4224
Pete Cooper35b00d52016-08-13 01:05:32 +00004225OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004226 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004227 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004228 const Instruction *CxtI,
4229 const DominatorTree *DT) {
4230 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004231 Add, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00004232}
4233
Pete Cooper35b00d52016-08-13 01:05:32 +00004234OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
4235 const Value *RHS,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004236 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004237 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004238 const Instruction *CxtI,
4239 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004240 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00004241}
4242
Jingyue Wu42f1d672015-07-28 18:22:40 +00004243bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
Hideto Ueno98d281a2019-07-29 13:35:34 +00004244 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
4245 // of time because it's possible for another thread to interfere with it for an
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004246 // arbitrary length of time, but programs aren't allowed to rely on that.
Jingyue Wu42f1d672015-07-28 18:22:40 +00004247
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004248 // If there is no successor, then execution can't transfer to it.
4249 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I))
4250 return !CRI->unwindsToCaller();
4251 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I))
4252 return !CatchSwitch->unwindsToCaller();
4253 if (isa<ResumeInst>(I))
4254 return false;
4255 if (isa<ReturnInst>(I))
4256 return false;
Sebastian Pop4a4d2452017-03-08 01:54:50 +00004257 if (isa<UnreachableInst>(I))
4258 return false;
Sanjoy Das9a65cd22016-06-08 17:48:36 +00004259
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004260 // Calls can throw, or contain an infinite loop, or kill the process.
Sanjoy Das09455302016-12-31 22:12:31 +00004261 if (auto CS = ImmutableCallSite(I)) {
Sanjoy Das3bb2dbd2016-12-31 22:12:34 +00004262 // Call sites that throw have implicit non-local control flow.
4263 if (!CS.doesNotThrow())
4264 return false;
4265
Johannes Doerfert6ed459f2019-06-27 19:29:48 +00004266 // A function which doens't throw and has "willreturn" attribute will
4267 // always return.
4268 if (CS.hasFnAttr(Attribute::WillReturn))
4269 return true;
4270
Sanjoy Das3bb2dbd2016-12-31 22:12:34 +00004271 // Non-throwing call sites can loop infinitely, call exit/pthread_exit
4272 // etc. and thus not return. However, LLVM already assumes that
4273 //
4274 // - Thread exiting actions are modeled as writes to memory invisible to
4275 // the program.
4276 //
4277 // - Loops that don't have side effects (side effects are volatile/atomic
4278 // stores and IO) always terminate (see http://llvm.org/PR965).
4279 // Furthermore IO itself is also modeled as writes to memory invisible to
4280 // the program.
4281 //
4282 // We rely on those assumptions here, and use the memory effects of the call
4283 // target as a proxy for checking that it always returns.
4284
4285 // FIXME: This isn't aggressive enough; a call which only writes to a global
4286 // is guaranteed to return.
Hideto Ueno6e2be4e2019-07-30 18:35:29 +00004287 return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory();
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004288 }
4289
4290 // Other instructions return normally.
4291 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004292}
4293
Philip Reamesfbffd122018-03-08 21:25:30 +00004294bool llvm::isGuaranteedToTransferExecutionToSuccessor(const BasicBlock *BB) {
Hiroshi Inouec437f312019-01-30 05:26:31 +00004295 // TODO: This is slightly conservative for invoke instruction since exiting
Philip Reamesfbffd122018-03-08 21:25:30 +00004296 // via an exception *is* normal control for them.
4297 for (auto I = BB->begin(), E = BB->end(); I != E; ++I)
4298 if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
4299 return false;
4300 return true;
4301}
4302
Jingyue Wu42f1d672015-07-28 18:22:40 +00004303bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
4304 const Loop *L) {
4305 // The loop header is guaranteed to be executed for every iteration.
4306 //
4307 // FIXME: Relax this constraint to cover all basic blocks that are
4308 // guaranteed to be executed at every iteration.
4309 if (I->getParent() != L->getHeader()) return false;
4310
4311 for (const Instruction &LI : *L->getHeader()) {
4312 if (&LI == I) return true;
4313 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
4314 }
4315 llvm_unreachable("Instruction not contained in its own parent basic block.");
4316}
4317
4318bool llvm::propagatesFullPoison(const Instruction *I) {
Nikita Popovad81d422019-06-13 19:45:36 +00004319 // TODO: This should include all instructions apart from phis, selects and
4320 // call-like instructions.
Jingyue Wu42f1d672015-07-28 18:22:40 +00004321 switch (I->getOpcode()) {
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004322 case Instruction::Add:
4323 case Instruction::Sub:
4324 case Instruction::Xor:
4325 case Instruction::Trunc:
4326 case Instruction::BitCast:
4327 case Instruction::AddrSpaceCast:
Sanjoy Das5cd6c5ca2017-02-22 06:52:32 +00004328 case Instruction::Mul:
4329 case Instruction::Shl:
4330 case Instruction::GetElementPtr:
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004331 // These operations all propagate poison unconditionally. Note that poison
4332 // is not any particular value, so xor or subtraction of poison with
4333 // itself still yields poison, not zero.
4334 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004335
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004336 case Instruction::AShr:
4337 case Instruction::SExt:
4338 // For these operations, one bit of the input is replicated across
4339 // multiple output bits. A replicated poison bit is still poison.
4340 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004341
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004342 case Instruction::ICmp:
4343 // Comparing poison with any value yields poison. This is why, for
4344 // instance, x s< (x +nsw 1) can be folded to true.
4345 return true;
Sanjoy Das70c2bbd2016-05-29 00:31:18 +00004346
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004347 default:
4348 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004349 }
4350}
4351
4352const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
4353 switch (I->getOpcode()) {
4354 case Instruction::Store:
4355 return cast<StoreInst>(I)->getPointerOperand();
4356
4357 case Instruction::Load:
4358 return cast<LoadInst>(I)->getPointerOperand();
4359
4360 case Instruction::AtomicCmpXchg:
4361 return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
4362
4363 case Instruction::AtomicRMW:
4364 return cast<AtomicRMWInst>(I)->getPointerOperand();
4365
4366 case Instruction::UDiv:
4367 case Instruction::SDiv:
4368 case Instruction::URem:
4369 case Instruction::SRem:
4370 return I->getOperand(1);
4371
4372 default:
Philip Reames038e01d2019-06-13 19:27:56 +00004373 // Note: It's really tempting to think that a conditional branch or
4374 // switch should be listed here, but that's incorrect. It's not
4375 // branching off of poison which is UB, it is executing a side effecting
Johannes Doerfert3ed286a2019-07-11 01:14:48 +00004376 // instruction which follows the branch.
Jingyue Wu42f1d672015-07-28 18:22:40 +00004377 return nullptr;
4378 }
4379}
4380
Philip Reames4bf1c232019-06-10 20:41:27 +00004381bool llvm::mustTriggerUB(const Instruction *I,
4382 const SmallSet<const Value *, 16>& KnownPoison) {
4383 auto *NotPoison = getGuaranteedNonFullPoisonOp(I);
4384 return (NotPoison && KnownPoison.count(NotPoison));
4385}
4386
4387
Sanjoy Das08989c72017-04-30 19:41:19 +00004388bool llvm::programUndefinedIfFullPoison(const Instruction *PoisonI) {
Jingyue Wu42f1d672015-07-28 18:22:40 +00004389 // We currently only look for uses of poison values within the same basic
4390 // block, as that makes it easier to guarantee that the uses will be
4391 // executed given that PoisonI is executed.
4392 //
4393 // FIXME: Expand this to consider uses beyond the same basic block. To do
4394 // this, look out for the distinction between post-dominance and strong
4395 // post-dominance.
4396 const BasicBlock *BB = PoisonI->getParent();
4397
4398 // Set of instructions that we have proved will yield poison if PoisonI
4399 // does.
4400 SmallSet<const Value *, 16> YieldsPoison;
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004401 SmallSet<const BasicBlock *, 4> Visited;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004402 YieldsPoison.insert(PoisonI);
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004403 Visited.insert(PoisonI->getParent());
Jingyue Wu42f1d672015-07-28 18:22:40 +00004404
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004405 BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end();
Jingyue Wu42f1d672015-07-28 18:22:40 +00004406
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004407 unsigned Iter = 0;
4408 while (Iter++ < MaxDepth) {
4409 for (auto &I : make_range(Begin, End)) {
4410 if (&I != PoisonI) {
Philip Reames4bf1c232019-06-10 20:41:27 +00004411 if (mustTriggerUB(&I, YieldsPoison))
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004412 return true;
4413 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
4414 return false;
4415 }
4416
4417 // Mark poison that propagates from I through uses of I.
4418 if (YieldsPoison.count(&I)) {
4419 for (const User *User : I.users()) {
4420 const Instruction *UserI = cast<Instruction>(User);
4421 if (propagatesFullPoison(UserI))
4422 YieldsPoison.insert(User);
4423 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004424 }
4425 }
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004426
4427 if (auto *NextBB = BB->getSingleSuccessor()) {
4428 if (Visited.insert(NextBB).second) {
4429 BB = NextBB;
4430 Begin = BB->getFirstNonPHI()->getIterator();
4431 End = BB->end();
4432 continue;
4433 }
4434 }
4435
4436 break;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004437 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004438 return false;
4439}
4440
Pete Cooper35b00d52016-08-13 01:05:32 +00004441static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
James Molloy134bec22015-08-11 09:12:57 +00004442 if (FMF.noNaNs())
4443 return true;
4444
4445 if (auto *C = dyn_cast<ConstantFP>(V))
4446 return !C->isNaN();
Thomas Livelyd47b5c72018-09-28 21:36:43 +00004447
4448 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
4449 if (!C->getElementType()->isFloatingPointTy())
4450 return false;
4451 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
4452 if (C->getElementAsAPFloat(I).isNaN())
4453 return false;
4454 }
4455 return true;
4456 }
4457
James Molloy134bec22015-08-11 09:12:57 +00004458 return false;
4459}
4460
Pete Cooper35b00d52016-08-13 01:05:32 +00004461static bool isKnownNonZero(const Value *V) {
James Molloy134bec22015-08-11 09:12:57 +00004462 if (auto *C = dyn_cast<ConstantFP>(V))
4463 return !C->isZero();
Thomas Livelyd47b5c72018-09-28 21:36:43 +00004464
4465 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
4466 if (!C->getElementType()->isFloatingPointTy())
4467 return false;
4468 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
4469 if (C->getElementAsAPFloat(I).isZero())
4470 return false;
4471 }
4472 return true;
4473 }
4474
James Molloy134bec22015-08-11 09:12:57 +00004475 return false;
4476}
4477
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004478/// Match clamp pattern for float types without care about NaNs or signed zeros.
4479/// Given non-min/max outer cmp/select from the clamp pattern this
4480/// function recognizes if it can be substitued by a "canonical" min/max
4481/// pattern.
4482static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred,
4483 Value *CmpLHS, Value *CmpRHS,
4484 Value *TrueVal, Value *FalseVal,
4485 Value *&LHS, Value *&RHS) {
4486 // Try to match
4487 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
4488 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
4489 // and return description of the outer Max/Min.
4490
4491 // First, check if select has inverse order:
4492 if (CmpRHS == FalseVal) {
4493 std::swap(TrueVal, FalseVal);
4494 Pred = CmpInst::getInversePredicate(Pred);
4495 }
4496
4497 // Assume success now. If there's no match, callers should not use these anyway.
4498 LHS = TrueVal;
4499 RHS = FalseVal;
4500
4501 const APFloat *FC1;
4502 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
4503 return {SPF_UNKNOWN, SPNB_NA, false};
4504
4505 const APFloat *FC2;
4506 switch (Pred) {
4507 case CmpInst::FCMP_OLT:
4508 case CmpInst::FCMP_OLE:
4509 case CmpInst::FCMP_ULT:
4510 case CmpInst::FCMP_ULE:
4511 if (match(FalseVal,
4512 m_CombineOr(m_OrdFMin(m_Specific(CmpLHS), m_APFloat(FC2)),
4513 m_UnordFMin(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4514 FC1->compare(*FC2) == APFloat::cmpResult::cmpLessThan)
4515 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
4516 break;
4517 case CmpInst::FCMP_OGT:
4518 case CmpInst::FCMP_OGE:
4519 case CmpInst::FCMP_UGT:
4520 case CmpInst::FCMP_UGE:
4521 if (match(FalseVal,
4522 m_CombineOr(m_OrdFMax(m_Specific(CmpLHS), m_APFloat(FC2)),
4523 m_UnordFMax(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4524 FC1->compare(*FC2) == APFloat::cmpResult::cmpGreaterThan)
4525 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
4526 break;
4527 default:
4528 break;
4529 }
4530
4531 return {SPF_UNKNOWN, SPNB_NA, false};
4532}
4533
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004534/// Recognize variations of:
4535/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
4536static SelectPatternResult matchClamp(CmpInst::Predicate Pred,
4537 Value *CmpLHS, Value *CmpRHS,
4538 Value *TrueVal, Value *FalseVal) {
4539 // Swap the select operands and predicate to match the patterns below.
4540 if (CmpRHS != TrueVal) {
4541 Pred = ICmpInst::getSwappedPredicate(Pred);
4542 std::swap(TrueVal, FalseVal);
4543 }
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004544 const APInt *C1;
4545 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
4546 const APInt *C2;
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004547 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
4548 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004549 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004550 return {SPF_SMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004551
4552 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
4553 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004554 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004555 return {SPF_SMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004556
4557 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
4558 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004559 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004560 return {SPF_UMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004561
4562 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
4563 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004564 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004565 return {SPF_UMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004566 }
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004567 return {SPF_UNKNOWN, SPNB_NA, false};
4568}
4569
Sanjay Patel78114302018-01-02 20:56:45 +00004570/// Recognize variations of:
4571/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
4572static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred,
4573 Value *CmpLHS, Value *CmpRHS,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004574 Value *TVal, Value *FVal,
4575 unsigned Depth) {
Sanjay Patel78114302018-01-02 20:56:45 +00004576 // TODO: Allow FP min/max with nnan/nsz.
4577 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
4578
Simon Pilgrimf62293e2019-09-23 13:15:52 +00004579 Value *A = nullptr, *B = nullptr;
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004580 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
Sanjay Patel78114302018-01-02 20:56:45 +00004581 if (!SelectPatternResult::isMinOrMax(L.Flavor))
4582 return {SPF_UNKNOWN, SPNB_NA, false};
4583
Simon Pilgrimf62293e2019-09-23 13:15:52 +00004584 Value *C = nullptr, *D = nullptr;
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004585 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
Sanjay Patel78114302018-01-02 20:56:45 +00004586 if (L.Flavor != R.Flavor)
4587 return {SPF_UNKNOWN, SPNB_NA, false};
4588
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004589 // We have something like: x Pred y ? min(a, b) : min(c, d).
4590 // Try to match the compare to the min/max operations of the select operands.
4591 // First, make sure we have the right compare predicate.
Sanjay Patel78114302018-01-02 20:56:45 +00004592 switch (L.Flavor) {
4593 case SPF_SMIN:
4594 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
4595 Pred = ICmpInst::getSwappedPredicate(Pred);
4596 std::swap(CmpLHS, CmpRHS);
4597 }
4598 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
4599 break;
4600 return {SPF_UNKNOWN, SPNB_NA, false};
4601 case SPF_SMAX:
4602 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
4603 Pred = ICmpInst::getSwappedPredicate(Pred);
4604 std::swap(CmpLHS, CmpRHS);
4605 }
4606 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
4607 break;
4608 return {SPF_UNKNOWN, SPNB_NA, false};
4609 case SPF_UMIN:
4610 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
4611 Pred = ICmpInst::getSwappedPredicate(Pred);
4612 std::swap(CmpLHS, CmpRHS);
4613 }
4614 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
4615 break;
4616 return {SPF_UNKNOWN, SPNB_NA, false};
4617 case SPF_UMAX:
4618 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
4619 Pred = ICmpInst::getSwappedPredicate(Pred);
4620 std::swap(CmpLHS, CmpRHS);
4621 }
4622 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
4623 break;
4624 return {SPF_UNKNOWN, SPNB_NA, false};
4625 default:
Sanjay Patel7dfe96a2018-01-08 18:31:13 +00004626 return {SPF_UNKNOWN, SPNB_NA, false};
Sanjay Patel78114302018-01-02 20:56:45 +00004627 }
4628
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004629 // If there is a common operand in the already matched min/max and the other
4630 // min/max operands match the compare operands (either directly or inverted),
4631 // then this is min/max of the same flavor.
4632
Sanjay Patel78114302018-01-02 20:56:45 +00004633 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004634 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
4635 if (D == B) {
4636 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4637 match(A, m_Not(m_Specific(CmpRHS)))))
4638 return {L.Flavor, SPNB_NA, false};
4639 }
Sanjay Patel78114302018-01-02 20:56:45 +00004640 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004641 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
4642 if (C == B) {
4643 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4644 match(A, m_Not(m_Specific(CmpRHS)))))
4645 return {L.Flavor, SPNB_NA, false};
4646 }
Sanjay Patel78114302018-01-02 20:56:45 +00004647 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004648 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
4649 if (D == A) {
4650 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4651 match(B, m_Not(m_Specific(CmpRHS)))))
4652 return {L.Flavor, SPNB_NA, false};
4653 }
Sanjay Patel78114302018-01-02 20:56:45 +00004654 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004655 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
4656 if (C == A) {
4657 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4658 match(B, m_Not(m_Specific(CmpRHS)))))
4659 return {L.Flavor, SPNB_NA, false};
4660 }
Sanjay Patel78114302018-01-02 20:56:45 +00004661
4662 return {SPF_UNKNOWN, SPNB_NA, false};
4663}
4664
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004665/// Match non-obvious integer minimum and maximum sequences.
4666static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
4667 Value *CmpLHS, Value *CmpRHS,
4668 Value *TrueVal, Value *FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004669 Value *&LHS, Value *&RHS,
4670 unsigned Depth) {
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004671 // Assume success. If there's no match, callers should not use these anyway.
4672 LHS = TrueVal;
4673 RHS = FalseVal;
4674
4675 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
4676 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4677 return SPR;
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004678
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004679 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
Sanjay Patel78114302018-01-02 20:56:45 +00004680 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4681 return SPR;
Fangrui Songf78650a2018-07-30 19:41:25 +00004682
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004683 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
Sanjay Patel819f0962016-11-13 19:30:19 +00004684 return {SPF_UNKNOWN, SPNB_NA, false};
4685
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004686 // Z = X -nsw Y
4687 // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
4688 // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
4689 if (match(TrueVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004690 match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004691 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004692
4693 // Z = X -nsw Y
4694 // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
4695 // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
4696 if (match(FalseVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004697 match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004698 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004699
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004700 const APInt *C1;
Sanjay Patel819f0962016-11-13 19:30:19 +00004701 if (!match(CmpRHS, m_APInt(C1)))
4702 return {SPF_UNKNOWN, SPNB_NA, false};
4703
4704 // An unsigned min/max can be written with a signed compare.
4705 const APInt *C2;
4706 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
4707 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
4708 // Is the sign bit set?
4709 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
4710 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
Craig Topper81d772c2017-11-08 19:38:45 +00004711 if (Pred == CmpInst::ICMP_SLT && C1->isNullValue() &&
4712 C2->isMaxSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004713 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004714
4715 // Is the sign bit clear?
4716 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
4717 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004718 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
4719 C2->isMinSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004720 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004721 }
4722
4723 // Look through 'not' ops to find disguised signed min/max.
4724 // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C)
4725 // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C)
4726 if (match(TrueVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004727 match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2)
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004728 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004729
4730 // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X)
4731 // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X)
4732 if (match(FalseVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004733 match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2)
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004734 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004735
4736 return {SPF_UNKNOWN, SPNB_NA, false};
4737}
4738
Chen Zheng69bb0642018-07-21 12:27:54 +00004739bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW) {
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004740 assert(X && Y && "Invalid operand");
4741
Chen Zheng69bb0642018-07-21 12:27:54 +00004742 // X = sub (0, Y) || X = sub nsw (0, Y)
4743 if ((!NeedNSW && match(X, m_Sub(m_ZeroInt(), m_Specific(Y)))) ||
4744 (NeedNSW && match(X, m_NSWSub(m_ZeroInt(), m_Specific(Y)))))
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004745 return true;
4746
Chen Zheng69bb0642018-07-21 12:27:54 +00004747 // Y = sub (0, X) || Y = sub nsw (0, X)
4748 if ((!NeedNSW && match(Y, m_Sub(m_ZeroInt(), m_Specific(X)))) ||
4749 (NeedNSW && match(Y, m_NSWSub(m_ZeroInt(), m_Specific(X)))))
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004750 return true;
4751
Chen Zheng69bb0642018-07-21 12:27:54 +00004752 // 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 +00004753 Value *A, *B;
Chen Zheng69bb0642018-07-21 12:27:54 +00004754 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
4755 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
4756 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
4757 match(Y, m_NSWSub(m_Specific(B), m_Specific(A)))));
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004758}
4759
James Molloy134bec22015-08-11 09:12:57 +00004760static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
4761 FastMathFlags FMF,
James Molloy270ef8c2015-05-15 16:04:50 +00004762 Value *CmpLHS, Value *CmpRHS,
4763 Value *TrueVal, Value *FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004764 Value *&LHS, Value *&RHS,
4765 unsigned Depth) {
Sanjay Patele7c94ef2018-11-04 14:28:48 +00004766 if (CmpInst::isFPPredicate(Pred)) {
4767 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
4768 // 0.0 operand, set the compare's 0.0 operands to that same value for the
4769 // purpose of identifying min/max. Disregard vector constants with undefined
4770 // elements because those can not be back-propagated for analysis.
4771 Value *OutputZeroVal = nullptr;
4772 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
4773 !cast<Constant>(TrueVal)->containsUndefElement())
4774 OutputZeroVal = TrueVal;
4775 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
4776 !cast<Constant>(FalseVal)->containsUndefElement())
4777 OutputZeroVal = FalseVal;
4778
4779 if (OutputZeroVal) {
4780 if (match(CmpLHS, m_AnyZeroFP()))
4781 CmpLHS = OutputZeroVal;
4782 if (match(CmpRHS, m_AnyZeroFP()))
4783 CmpRHS = OutputZeroVal;
4784 }
4785 }
4786
James Molloy71b91c22015-05-11 14:42:20 +00004787 LHS = CmpLHS;
4788 RHS = CmpRHS;
4789
Sanjay Patel9a399792017-12-26 15:09:19 +00004790 // Signed zero may return inconsistent results between implementations.
4791 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
4792 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
4793 // Therefore, we behave conservatively and only proceed if at least one of the
4794 // operands is known to not be zero or if we don't care about signed zero.
James Molloy134bec22015-08-11 09:12:57 +00004795 switch (Pred) {
4796 default: break;
Sanjay Patel9a399792017-12-26 15:09:19 +00004797 // FIXME: Include OGT/OLT/UGT/ULT.
James Molloy134bec22015-08-11 09:12:57 +00004798 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
4799 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
4800 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4801 !isKnownNonZero(CmpRHS))
4802 return {SPF_UNKNOWN, SPNB_NA, false};
4803 }
4804
4805 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
4806 bool Ordered = false;
4807
4808 // When given one NaN and one non-NaN input:
4809 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
4810 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
4811 // ordered comparison fails), which could be NaN or non-NaN.
4812 // so here we discover exactly what NaN behavior is required/accepted.
4813 if (CmpInst::isFPPredicate(Pred)) {
4814 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
4815 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
4816
4817 if (LHSSafe && RHSSafe) {
4818 // Both operands are known non-NaN.
4819 NaNBehavior = SPNB_RETURNS_ANY;
4820 } else if (CmpInst::isOrdered(Pred)) {
4821 // An ordered comparison will return false when given a NaN, so it
4822 // returns the RHS.
4823 Ordered = true;
4824 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004825 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004826 NaNBehavior = SPNB_RETURNS_NAN;
4827 else if (RHSSafe)
4828 NaNBehavior = SPNB_RETURNS_OTHER;
4829 else
4830 // Completely unsafe.
4831 return {SPF_UNKNOWN, SPNB_NA, false};
4832 } else {
4833 Ordered = false;
4834 // An unordered comparison will return true when given a NaN, so it
4835 // returns the LHS.
4836 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004837 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004838 NaNBehavior = SPNB_RETURNS_OTHER;
4839 else if (RHSSafe)
4840 NaNBehavior = SPNB_RETURNS_NAN;
4841 else
4842 // Completely unsafe.
4843 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004844 }
4845 }
4846
James Molloy71b91c22015-05-11 14:42:20 +00004847 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
James Molloy134bec22015-08-11 09:12:57 +00004848 std::swap(CmpLHS, CmpRHS);
4849 Pred = CmpInst::getSwappedPredicate(Pred);
4850 if (NaNBehavior == SPNB_RETURNS_NAN)
4851 NaNBehavior = SPNB_RETURNS_OTHER;
4852 else if (NaNBehavior == SPNB_RETURNS_OTHER)
4853 NaNBehavior = SPNB_RETURNS_NAN;
4854 Ordered = !Ordered;
4855 }
4856
4857 // ([if]cmp X, Y) ? X : Y
4858 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
James Molloy71b91c22015-05-11 14:42:20 +00004859 switch (Pred) {
James Molloy134bec22015-08-11 09:12:57 +00004860 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
James Molloy71b91c22015-05-11 14:42:20 +00004861 case ICmpInst::ICMP_UGT:
James Molloy134bec22015-08-11 09:12:57 +00004862 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004863 case ICmpInst::ICMP_SGT:
James Molloy134bec22015-08-11 09:12:57 +00004864 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004865 case ICmpInst::ICMP_ULT:
James Molloy134bec22015-08-11 09:12:57 +00004866 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004867 case ICmpInst::ICMP_SLT:
James Molloy134bec22015-08-11 09:12:57 +00004868 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
4869 case FCmpInst::FCMP_UGT:
4870 case FCmpInst::FCMP_UGE:
4871 case FCmpInst::FCMP_OGT:
4872 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
4873 case FCmpInst::FCMP_ULT:
4874 case FCmpInst::FCMP_ULE:
4875 case FCmpInst::FCMP_OLT:
4876 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
James Molloy71b91c22015-05-11 14:42:20 +00004877 }
4878 }
Fangrui Songf78650a2018-07-30 19:41:25 +00004879
Chen Zhengccc84222018-07-16 02:23:00 +00004880 if (isKnownNegation(TrueVal, FalseVal)) {
4881 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
4882 // match against either LHS or sext(LHS).
4883 auto MaybeSExtCmpLHS =
4884 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
4885 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
4886 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
4887 if (match(TrueVal, MaybeSExtCmpLHS)) {
4888 // Set the return values. If the compare uses the negated value (-X >s 0),
4889 // swap the return values because the negated value is always 'RHS'.
Sanjay Patel284ba0c2018-07-02 14:43:40 +00004890 LHS = TrueVal;
4891 RHS = FalseVal;
Chen Zhengccc84222018-07-16 02:23:00 +00004892 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
4893 std::swap(LHS, RHS);
4894
4895 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
4896 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
4897 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
4898 return {SPF_ABS, SPNB_NA, false};
4899
Simon Pilgrima56f2822019-03-19 16:24:55 +00004900 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
4901 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
4902 return {SPF_ABS, SPNB_NA, false};
4903
Chen Zhengccc84222018-07-16 02:23:00 +00004904 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
4905 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
4906 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
4907 return {SPF_NABS, SPNB_NA, false};
4908 }
4909 else if (match(FalseVal, MaybeSExtCmpLHS)) {
4910 // Set the return values. If the compare uses the negated value (-X >s 0),
4911 // swap the return values because the negated value is always 'RHS'.
Sanjay Patel284ba0c2018-07-02 14:43:40 +00004912 LHS = FalseVal;
4913 RHS = TrueVal;
Chen Zhengccc84222018-07-16 02:23:00 +00004914 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
4915 std::swap(LHS, RHS);
4916
4917 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
4918 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
4919 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
4920 return {SPF_NABS, SPNB_NA, false};
4921
4922 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
4923 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
4924 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
4925 return {SPF_ABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004926 }
James Molloy71b91c22015-05-11 14:42:20 +00004927 }
4928
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004929 if (CmpInst::isIntPredicate(Pred))
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004930 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004931
4932 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
4933 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
4934 // semantics than minNum. Be conservative in such case.
4935 if (NaNBehavior != SPNB_RETURNS_ANY ||
4936 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4937 !isKnownNonZero(CmpRHS)))
4938 return {SPF_UNKNOWN, SPNB_NA, false};
4939
4940 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
James Molloy71b91c22015-05-11 14:42:20 +00004941}
James Molloy270ef8c2015-05-15 16:04:50 +00004942
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004943/// Helps to match a select pattern in case of a type mismatch.
4944///
4945/// The function processes the case when type of true and false values of a
4946/// select instruction differs from type of the cmp instruction operands because
Vedant Kumar1a8456d2018-03-02 18:57:02 +00004947/// of a cast instruction. The function checks if it is legal to move the cast
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004948/// operation after "select". If yes, it returns the new second value of
4949/// "select" (with the assumption that cast is moved):
4950/// 1. As operand of cast instruction when both values of "select" are same cast
4951/// instructions.
4952/// 2. As restored constant (by applying reverse cast operation) when the first
4953/// value of the "select" is a cast operation and the second value is a
4954/// constant.
4955/// NOTE: We return only the new second value because the first value could be
4956/// accessed as operand of cast instruction.
James Molloy569cea62015-09-02 17:25:25 +00004957static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
4958 Instruction::CastOps *CastOp) {
Sanjay Patel14a4b812017-01-29 16:34:57 +00004959 auto *Cast1 = dyn_cast<CastInst>(V1);
4960 if (!Cast1)
James Molloy270ef8c2015-05-15 16:04:50 +00004961 return nullptr;
James Molloy270ef8c2015-05-15 16:04:50 +00004962
Sanjay Patel14a4b812017-01-29 16:34:57 +00004963 *CastOp = Cast1->getOpcode();
4964 Type *SrcTy = Cast1->getSrcTy();
4965 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
4966 // If V1 and V2 are both the same cast from the same type, look through V1.
4967 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
4968 return Cast2->getOperand(0);
James Molloy569cea62015-09-02 17:25:25 +00004969 return nullptr;
4970 }
4971
Sanjay Patel14a4b812017-01-29 16:34:57 +00004972 auto *C = dyn_cast<Constant>(V2);
4973 if (!C)
4974 return nullptr;
4975
David Majnemerd2a074b2016-04-29 18:40:34 +00004976 Constant *CastedTo = nullptr;
Sanjay Patel14a4b812017-01-29 16:34:57 +00004977 switch (*CastOp) {
4978 case Instruction::ZExt:
4979 if (CmpI->isUnsigned())
4980 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
4981 break;
4982 case Instruction::SExt:
4983 if (CmpI->isSigned())
4984 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
4985 break;
4986 case Instruction::Trunc:
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004987 Constant *CmpConst;
Nikolai Bozhenov9723f122017-10-18 14:24:50 +00004988 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
4989 CmpConst->getType() == SrcTy) {
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004990 // Here we have the following case:
4991 //
4992 // %cond = cmp iN %x, CmpConst
4993 // %tr = trunc iN %x to iK
4994 // %narrowsel = select i1 %cond, iK %t, iK C
4995 //
4996 // We can always move trunc after select operation:
4997 //
4998 // %cond = cmp iN %x, CmpConst
4999 // %widesel = select i1 %cond, iN %x, iN CmpConst
5000 // %tr = trunc iN %widesel to iK
5001 //
5002 // Note that C could be extended in any way because we don't care about
5003 // upper bits after truncation. It can't be abs pattern, because it would
5004 // look like:
5005 //
5006 // select i1 %cond, x, -x.
5007 //
5008 // So only min/max pattern could be matched. Such match requires widened C
5009 // == CmpConst. That is why set widened C = CmpConst, condition trunc
5010 // CmpConst == C is checked below.
5011 CastedTo = CmpConst;
5012 } else {
5013 CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
5014 }
Sanjay Patel14a4b812017-01-29 16:34:57 +00005015 break;
5016 case Instruction::FPTrunc:
5017 CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
5018 break;
5019 case Instruction::FPExt:
5020 CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
5021 break;
5022 case Instruction::FPToUI:
5023 CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
5024 break;
5025 case Instruction::FPToSI:
5026 CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
5027 break;
5028 case Instruction::UIToFP:
5029 CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
5030 break;
5031 case Instruction::SIToFP:
5032 CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
5033 break;
5034 default:
5035 break;
5036 }
David Majnemerd2a074b2016-04-29 18:40:34 +00005037
5038 if (!CastedTo)
5039 return nullptr;
5040
David Majnemerd2a074b2016-04-29 18:40:34 +00005041 // Make sure the cast doesn't lose any information.
Sanjay Patel14a4b812017-01-29 16:34:57 +00005042 Constant *CastedBack =
5043 ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
David Majnemerd2a074b2016-04-29 18:40:34 +00005044 if (CastedBack != C)
5045 return nullptr;
5046
5047 return CastedTo;
James Molloy270ef8c2015-05-15 16:04:50 +00005048}
5049
Sanjay Patele8dc0902016-05-23 17:57:54 +00005050SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005051 Instruction::CastOps *CastOp,
5052 unsigned Depth) {
5053 if (Depth >= MaxDepth)
5054 return {SPF_UNKNOWN, SPNB_NA, false};
5055
James Molloy270ef8c2015-05-15 16:04:50 +00005056 SelectInst *SI = dyn_cast<SelectInst>(V);
James Molloy134bec22015-08-11 09:12:57 +00005057 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00005058
James Molloy134bec22015-08-11 09:12:57 +00005059 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
5060 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00005061
Joseph Tremoulet3bc6e2a2019-06-13 15:24:11 +00005062 Value *TrueVal = SI->getTrueValue();
5063 Value *FalseVal = SI->getFalseValue();
5064
5065 return llvm::matchDecomposedSelectPattern(CmpI, TrueVal, FalseVal, LHS, RHS,
5066 CastOp, Depth);
5067}
5068
5069SelectPatternResult llvm::matchDecomposedSelectPattern(
5070 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
5071 Instruction::CastOps *CastOp, unsigned Depth) {
James Molloy134bec22015-08-11 09:12:57 +00005072 CmpInst::Predicate Pred = CmpI->getPredicate();
James Molloy270ef8c2015-05-15 16:04:50 +00005073 Value *CmpLHS = CmpI->getOperand(0);
5074 Value *CmpRHS = CmpI->getOperand(1);
James Molloy134bec22015-08-11 09:12:57 +00005075 FastMathFlags FMF;
5076 if (isa<FPMathOperator>(CmpI))
5077 FMF = CmpI->getFastMathFlags();
James Molloy270ef8c2015-05-15 16:04:50 +00005078
5079 // Bail out early.
5080 if (CmpI->isEquality())
James Molloy134bec22015-08-11 09:12:57 +00005081 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00005082
5083 // Deal with type mismatches.
5084 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
Sanjay Patel9a399792017-12-26 15:09:19 +00005085 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
5086 // If this is a potential fmin/fmax with a cast to integer, then ignore
5087 // -0.0 because there is no corresponding integer value.
5088 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
5089 FMF.setNoSignedZeros();
James Molloy134bec22015-08-11 09:12:57 +00005090 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00005091 cast<CastInst>(TrueVal)->getOperand(0), C,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005092 LHS, RHS, Depth);
Sanjay Patel9a399792017-12-26 15:09:19 +00005093 }
5094 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
5095 // If this is a potential fmin/fmax with a cast to integer, then ignore
5096 // -0.0 because there is no corresponding integer value.
5097 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
5098 FMF.setNoSignedZeros();
James Molloy134bec22015-08-11 09:12:57 +00005099 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00005100 C, cast<CastInst>(FalseVal)->getOperand(0),
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005101 LHS, RHS, Depth);
Sanjay Patel9a399792017-12-26 15:09:19 +00005102 }
James Molloy270ef8c2015-05-15 16:04:50 +00005103 }
James Molloy134bec22015-08-11 09:12:57 +00005104 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005105 LHS, RHS, Depth);
James Molloy270ef8c2015-05-15 16:04:50 +00005106}
Sanjoy Dasa7e13782015-10-24 05:37:35 +00005107
Sanjay Patel7ed0bc22018-03-06 16:57:55 +00005108CmpInst::Predicate llvm::getMinMaxPred(SelectPatternFlavor SPF, bool Ordered) {
5109 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
5110 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
5111 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
5112 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
5113 if (SPF == SPF_FMINNUM)
5114 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
5115 if (SPF == SPF_FMAXNUM)
5116 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
5117 llvm_unreachable("unhandled!");
5118}
5119
5120SelectPatternFlavor llvm::getInverseMinMaxFlavor(SelectPatternFlavor SPF) {
5121 if (SPF == SPF_SMIN) return SPF_SMAX;
5122 if (SPF == SPF_UMIN) return SPF_UMAX;
5123 if (SPF == SPF_SMAX) return SPF_SMIN;
5124 if (SPF == SPF_UMAX) return SPF_UMIN;
5125 llvm_unreachable("unhandled!");
5126}
5127
5128CmpInst::Predicate llvm::getInverseMinMaxPred(SelectPatternFlavor SPF) {
5129 return getMinMaxPred(getInverseMinMaxFlavor(SPF));
5130}
5131
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005132/// Return true if "icmp Pred LHS RHS" is always true.
Chad Rosiere42b44b2017-07-28 14:39:06 +00005133static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
5134 const Value *RHS, const DataLayout &DL,
5135 unsigned Depth) {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005136 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005137 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
5138 return true;
5139
5140 switch (Pred) {
5141 default:
5142 return false;
5143
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005144 case CmpInst::ICMP_SLE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005145 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005146
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005147 // LHS s<= LHS +_{nsw} C if C >= 0
Sanjoy Dasdc26df42015-11-11 00:16:41 +00005148 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005149 return !C->isNegative();
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005150 return false;
5151 }
5152
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005153 case CmpInst::ICMP_ULE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005154 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005155
Sanjoy Dasdc26df42015-11-11 00:16:41 +00005156 // LHS u<= LHS +_{nuw} C for any C
5157 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasc01b4d22015-11-06 19:01:03 +00005158 return true;
Sanjoy Das92568102015-11-10 23:56:20 +00005159
5160 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
Pete Cooper35b00d52016-08-13 01:05:32 +00005161 auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
5162 const Value *&X,
Sanjoy Das92568102015-11-10 23:56:20 +00005163 const APInt *&CA, const APInt *&CB) {
5164 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
5165 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
5166 return true;
5167
5168 // If X & C == 0 then (X | C) == X +_{nuw} C
5169 if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
5170 match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
Craig Topperb45eabc2017-04-26 16:39:58 +00005171 KnownBits Known(CA->getBitWidth());
Chad Rosiere42b44b2017-07-28 14:39:06 +00005172 computeKnownBits(X, Known, DL, Depth + 1, /*AC*/ nullptr,
5173 /*CxtI*/ nullptr, /*DT*/ nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +00005174 if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
Sanjoy Das92568102015-11-10 23:56:20 +00005175 return true;
5176 }
5177
5178 return false;
5179 };
5180
Pete Cooper35b00d52016-08-13 01:05:32 +00005181 const Value *X;
Sanjoy Das92568102015-11-10 23:56:20 +00005182 const APInt *CLHS, *CRHS;
Sanjoy Dasdc26df42015-11-11 00:16:41 +00005183 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
5184 return CLHS->ule(*CRHS);
Sanjoy Das92568102015-11-10 23:56:20 +00005185
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005186 return false;
5187 }
5188 }
5189}
5190
5191/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
Chad Rosier41dd31f2016-04-20 19:15:26 +00005192/// ALHS ARHS" is true. Otherwise, return None.
5193static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00005194isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
Chad Rosiere42b44b2017-07-28 14:39:06 +00005195 const Value *ARHS, const Value *BLHS, const Value *BRHS,
5196 const DataLayout &DL, unsigned Depth) {
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005197 switch (Pred) {
5198 default:
Chad Rosier41dd31f2016-04-20 19:15:26 +00005199 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005200
5201 case CmpInst::ICMP_SLT:
5202 case CmpInst::ICMP_SLE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00005203 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth) &&
5204 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00005205 return true;
5206 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005207
5208 case CmpInst::ICMP_ULT:
5209 case CmpInst::ICMP_ULE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00005210 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth) &&
5211 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00005212 return true;
5213 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005214 }
5215}
5216
Chad Rosier226a7342016-05-05 17:41:19 +00005217/// Return true if the operands of the two compares match. IsSwappedOps is true
5218/// when the operands match, but are swapped.
Pete Cooper35b00d52016-08-13 01:05:32 +00005219static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
5220 const Value *BLHS, const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00005221 bool &IsSwappedOps) {
5222
5223 bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
5224 IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
5225 return IsMatchingOps || IsSwappedOps;
5226}
5227
Sanjay Patel798c5982018-12-19 16:49:18 +00005228/// Return true if "icmp1 APred X, Y" implies "icmp2 BPred X, Y" is true.
5229/// Return false if "icmp1 APred X, Y" implies "icmp2 BPred X, Y" is false.
5230/// Otherwise, return None if we can't infer anything.
Chad Rosier41dd31f2016-04-20 19:15:26 +00005231static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
Chad Rosier41dd31f2016-04-20 19:15:26 +00005232 CmpInst::Predicate BPred,
Sanjay Patel798c5982018-12-19 16:49:18 +00005233 bool AreSwappedOps) {
5234 // Canonicalize the predicate as if the operands were not commuted.
5235 if (AreSwappedOps)
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005236 BPred = ICmpInst::getSwappedPredicate(BPred);
Sanjay Patel798c5982018-12-19 16:49:18 +00005237
Chad Rosier99bc4802016-04-21 16:18:02 +00005238 if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005239 return true;
Chad Rosier99bc4802016-04-21 16:18:02 +00005240 if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
Chad Rosier41dd31f2016-04-20 19:15:26 +00005241 return false;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005242
Chad Rosier41dd31f2016-04-20 19:15:26 +00005243 return None;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005244}
5245
Sanjay Patel798c5982018-12-19 16:49:18 +00005246/// Return true if "icmp APred X, C1" implies "icmp BPred X, C2" is true.
5247/// Return false if "icmp APred X, C1" implies "icmp BPred X, C2" is false.
5248/// Otherwise, return None if we can't infer anything.
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005249static Optional<bool>
Sanjay Patel798c5982018-12-19 16:49:18 +00005250isImpliedCondMatchingImmOperands(CmpInst::Predicate APred,
Pete Cooper35b00d52016-08-13 01:05:32 +00005251 const ConstantInt *C1,
5252 CmpInst::Predicate BPred,
Sanjay Patel798c5982018-12-19 16:49:18 +00005253 const ConstantInt *C2) {
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005254 ConstantRange DomCR =
5255 ConstantRange::makeExactICmpRegion(APred, C1->getValue());
5256 ConstantRange CR =
5257 ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
5258 ConstantRange Intersection = DomCR.intersectWith(CR);
5259 ConstantRange Difference = DomCR.difference(CR);
5260 if (Intersection.isEmptySet())
5261 return false;
5262 if (Difference.isEmptySet())
5263 return true;
5264 return None;
5265}
5266
Chad Rosier2f498032017-07-28 18:47:43 +00005267/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
5268/// false. Otherwise, return None if we can't infer anything.
5269static Optional<bool> isImpliedCondICmps(const ICmpInst *LHS,
5270 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00005271 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00005272 unsigned Depth) {
5273 Value *ALHS = LHS->getOperand(0);
5274 Value *ARHS = LHS->getOperand(1);
Chad Rosiera72a9ff2017-07-06 20:00:25 +00005275 // The rest of the logic assumes the LHS condition is true. If that's not the
5276 // case, invert the predicate to make it so.
Chad Rosier2f498032017-07-28 18:47:43 +00005277 ICmpInst::Predicate APred =
Chad Rosierdfd1de62017-08-01 20:18:54 +00005278 LHSIsTrue ? LHS->getPredicate() : LHS->getInversePredicate();
Chad Rosier2f498032017-07-28 18:47:43 +00005279
5280 Value *BLHS = RHS->getOperand(0);
5281 Value *BRHS = RHS->getOperand(1);
5282 ICmpInst::Predicate BPred = RHS->getPredicate();
Chad Rosiere2cbd132016-04-25 17:23:36 +00005283
Chad Rosier226a7342016-05-05 17:41:19 +00005284 // Can we infer anything when the two compares have matching operands?
Sanjay Patel798c5982018-12-19 16:49:18 +00005285 bool AreSwappedOps;
5286 if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, AreSwappedOps)) {
Chad Rosier226a7342016-05-05 17:41:19 +00005287 if (Optional<bool> Implication = isImpliedCondMatchingOperands(
Sanjay Patel798c5982018-12-19 16:49:18 +00005288 APred, BPred, AreSwappedOps))
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005289 return Implication;
Chad Rosier226a7342016-05-05 17:41:19 +00005290 // No amount of additional analysis will infer the second condition, so
5291 // early exit.
5292 return None;
5293 }
5294
5295 // Can we infer anything when the LHS operands match and the RHS operands are
5296 // constants (not necessarily matching)?
5297 if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
5298 if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
Sanjay Patel798c5982018-12-19 16:49:18 +00005299 APred, cast<ConstantInt>(ARHS), BPred, cast<ConstantInt>(BRHS)))
Chad Rosier226a7342016-05-05 17:41:19 +00005300 return Implication;
5301 // No amount of additional analysis will infer the second condition, so
5302 // early exit.
5303 return None;
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005304 }
5305
Chad Rosier41dd31f2016-04-20 19:15:26 +00005306 if (APred == BPred)
Chad Rosiere42b44b2017-07-28 14:39:06 +00005307 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth);
Chad Rosier41dd31f2016-04-20 19:15:26 +00005308 return None;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00005309}
Chad Rosier2f498032017-07-28 18:47:43 +00005310
Chad Rosierf73a10d2017-08-01 19:22:36 +00005311/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
5312/// false. Otherwise, return None if we can't infer anything. We expect the
5313/// RHS to be an icmp and the LHS to be an 'and' or an 'or' instruction.
5314static Optional<bool> isImpliedCondAndOr(const BinaryOperator *LHS,
5315 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00005316 const DataLayout &DL, bool LHSIsTrue,
Chad Rosierf73a10d2017-08-01 19:22:36 +00005317 unsigned Depth) {
5318 // The LHS must be an 'or' or an 'and' instruction.
5319 assert((LHS->getOpcode() == Instruction::And ||
5320 LHS->getOpcode() == Instruction::Or) &&
5321 "Expected LHS to be 'and' or 'or'.");
5322
Davide Italiano1a943a92017-08-09 16:06:54 +00005323 assert(Depth <= MaxDepth && "Hit recursion limit");
Chad Rosierf73a10d2017-08-01 19:22:36 +00005324
5325 // If the result of an 'or' is false, then we know both legs of the 'or' are
5326 // false. Similarly, if the result of an 'and' is true, then we know both
5327 // legs of the 'and' are true.
5328 Value *ALHS, *ARHS;
Chad Rosierdfd1de62017-08-01 20:18:54 +00005329 if ((!LHSIsTrue && match(LHS, m_Or(m_Value(ALHS), m_Value(ARHS)))) ||
5330 (LHSIsTrue && match(LHS, m_And(m_Value(ALHS), m_Value(ARHS))))) {
Chad Rosierf73a10d2017-08-01 19:22:36 +00005331 // FIXME: Make this non-recursion.
5332 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00005333 isImpliedCondition(ALHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00005334 return Implication;
5335 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00005336 isImpliedCondition(ARHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00005337 return Implication;
5338 return None;
5339 }
5340 return None;
5341}
5342
Chad Rosier2f498032017-07-28 18:47:43 +00005343Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00005344 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00005345 unsigned Depth) {
Davide Italiano30e51942017-08-09 15:13:50 +00005346 // Bail out when we hit the limit.
5347 if (Depth == MaxDepth)
5348 return None;
5349
Chad Rosierf73a10d2017-08-01 19:22:36 +00005350 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
5351 // example.
Chad Rosier2f498032017-07-28 18:47:43 +00005352 if (LHS->getType() != RHS->getType())
5353 return None;
5354
5355 Type *OpTy = LHS->getType();
Chad Rosierf73a10d2017-08-01 19:22:36 +00005356 assert(OpTy->isIntOrIntVectorTy(1) && "Expected integer type only!");
Chad Rosier2f498032017-07-28 18:47:43 +00005357
5358 // LHS ==> RHS by definition
5359 if (LHS == RHS)
Chad Rosierdfd1de62017-08-01 20:18:54 +00005360 return LHSIsTrue;
Chad Rosier2f498032017-07-28 18:47:43 +00005361
Chad Rosierf73a10d2017-08-01 19:22:36 +00005362 // FIXME: Extending the code below to handle vectors.
Chad Rosier2f498032017-07-28 18:47:43 +00005363 if (OpTy->isVectorTy())
Chad Rosier2f498032017-07-28 18:47:43 +00005364 return None;
Chad Rosierf73a10d2017-08-01 19:22:36 +00005365
Chad Rosier2f498032017-07-28 18:47:43 +00005366 assert(OpTy->isIntegerTy(1) && "implied by above");
5367
Chad Rosier2f498032017-07-28 18:47:43 +00005368 // Both LHS and RHS are icmps.
Chad Rosierf73a10d2017-08-01 19:22:36 +00005369 const ICmpInst *LHSCmp = dyn_cast<ICmpInst>(LHS);
5370 const ICmpInst *RHSCmp = dyn_cast<ICmpInst>(RHS);
5371 if (LHSCmp && RHSCmp)
Chad Rosierdfd1de62017-08-01 20:18:54 +00005372 return isImpliedCondICmps(LHSCmp, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00005373
Chad Rosierf73a10d2017-08-01 19:22:36 +00005374 // The LHS should be an 'or' or an 'and' instruction. We expect the RHS to be
5375 // an icmp. FIXME: Add support for and/or on the RHS.
5376 const BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHS);
5377 if (LHSBO && RHSCmp) {
5378 if ((LHSBO->getOpcode() == Instruction::And ||
5379 LHSBO->getOpcode() == Instruction::Or))
Chad Rosierdfd1de62017-08-01 20:18:54 +00005380 return isImpliedCondAndOr(LHSBO, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00005381 }
Chad Rosierf73a10d2017-08-01 19:22:36 +00005382 return None;
Chad Rosier2f498032017-07-28 18:47:43 +00005383}
Sanjay Patel7d82d372018-12-02 13:26:03 +00005384
5385Optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
5386 const Instruction *ContextI,
5387 const DataLayout &DL) {
5388 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
5389 if (!ContextI || !ContextI->getParent())
5390 return None;
5391
5392 // TODO: This is a poor/cheap way to determine dominance. Should we use a
5393 // dominator tree (eg, from a SimplifyQuery) instead?
5394 const BasicBlock *ContextBB = ContextI->getParent();
5395 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
5396 if (!PredBB)
5397 return None;
5398
5399 // We need a conditional branch in the predecessor.
5400 Value *PredCond;
5401 BasicBlock *TrueBB, *FalseBB;
5402 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
5403 return None;
5404
5405 // The branch should get simplified. Don't bother simplifying this condition.
5406 if (TrueBB == FalseBB)
5407 return None;
5408
5409 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
5410 "Predecessor block does not point to successor?");
5411
5412 // Is this condition implied by the predecessor condition?
5413 bool CondIsTrue = TrueBB == ContextBB;
5414 return isImpliedCondition(PredCond, Cond, DL, CondIsTrue);
5415}
Nikita Popov49097592019-03-09 21:17:42 +00005416
5417static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower,
5418 APInt &Upper, const InstrInfoQuery &IIQ) {
5419 unsigned Width = Lower.getBitWidth();
5420 const APInt *C;
5421 switch (BO.getOpcode()) {
5422 case Instruction::Add:
5423 if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
5424 // FIXME: If we have both nuw and nsw, we should reduce the range further.
5425 if (IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(&BO))) {
5426 // 'add nuw x, C' produces [C, UINT_MAX].
5427 Lower = *C;
5428 } else if (IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(&BO))) {
5429 if (C->isNegative()) {
5430 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
5431 Lower = APInt::getSignedMinValue(Width);
5432 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
5433 } else {
5434 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
5435 Lower = APInt::getSignedMinValue(Width) + *C;
5436 Upper = APInt::getSignedMaxValue(Width) + 1;
5437 }
5438 }
5439 }
5440 break;
5441
5442 case Instruction::And:
5443 if (match(BO.getOperand(1), m_APInt(C)))
5444 // 'and x, C' produces [0, C].
5445 Upper = *C + 1;
5446 break;
5447
5448 case Instruction::Or:
5449 if (match(BO.getOperand(1), m_APInt(C)))
5450 // 'or x, C' produces [C, UINT_MAX].
5451 Lower = *C;
5452 break;
5453
5454 case Instruction::AShr:
5455 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
5456 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
5457 Lower = APInt::getSignedMinValue(Width).ashr(*C);
5458 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
5459 } else if (match(BO.getOperand(0), m_APInt(C))) {
5460 unsigned ShiftAmount = Width - 1;
5461 if (!C->isNullValue() && IIQ.isExact(&BO))
5462 ShiftAmount = C->countTrailingZeros();
5463 if (C->isNegative()) {
5464 // 'ashr C, x' produces [C, C >> (Width-1)]
5465 Lower = *C;
5466 Upper = C->ashr(ShiftAmount) + 1;
5467 } else {
5468 // 'ashr C, x' produces [C >> (Width-1), C]
5469 Lower = C->ashr(ShiftAmount);
5470 Upper = *C + 1;
5471 }
5472 }
5473 break;
5474
5475 case Instruction::LShr:
5476 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
5477 // 'lshr x, C' produces [0, UINT_MAX >> C].
5478 Upper = APInt::getAllOnesValue(Width).lshr(*C) + 1;
5479 } else if (match(BO.getOperand(0), m_APInt(C))) {
5480 // 'lshr C, x' produces [C >> (Width-1), C].
5481 unsigned ShiftAmount = Width - 1;
5482 if (!C->isNullValue() && IIQ.isExact(&BO))
5483 ShiftAmount = C->countTrailingZeros();
5484 Lower = C->lshr(ShiftAmount);
5485 Upper = *C + 1;
5486 }
5487 break;
5488
5489 case Instruction::Shl:
5490 if (match(BO.getOperand(0), m_APInt(C))) {
5491 if (IIQ.hasNoUnsignedWrap(&BO)) {
5492 // 'shl nuw C, x' produces [C, C << CLZ(C)]
5493 Lower = *C;
5494 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
5495 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
5496 if (C->isNegative()) {
5497 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
5498 unsigned ShiftAmount = C->countLeadingOnes() - 1;
5499 Lower = C->shl(ShiftAmount);
5500 Upper = *C + 1;
5501 } else {
5502 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
5503 unsigned ShiftAmount = C->countLeadingZeros() - 1;
5504 Lower = *C;
5505 Upper = C->shl(ShiftAmount) + 1;
5506 }
5507 }
5508 }
5509 break;
5510
5511 case Instruction::SDiv:
5512 if (match(BO.getOperand(1), m_APInt(C))) {
5513 APInt IntMin = APInt::getSignedMinValue(Width);
5514 APInt IntMax = APInt::getSignedMaxValue(Width);
5515 if (C->isAllOnesValue()) {
5516 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
5517 // where C != -1 and C != 0 and C != 1
5518 Lower = IntMin + 1;
5519 Upper = IntMax + 1;
5520 } else if (C->countLeadingZeros() < Width - 1) {
5521 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
5522 // where C != -1 and C != 0 and C != 1
5523 Lower = IntMin.sdiv(*C);
5524 Upper = IntMax.sdiv(*C);
5525 if (Lower.sgt(Upper))
5526 std::swap(Lower, Upper);
5527 Upper = Upper + 1;
5528 assert(Upper != Lower && "Upper part of range has wrapped!");
5529 }
5530 } else if (match(BO.getOperand(0), m_APInt(C))) {
5531 if (C->isMinSignedValue()) {
5532 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
5533 Lower = *C;
5534 Upper = Lower.lshr(1) + 1;
5535 } else {
5536 // 'sdiv C, x' produces [-|C|, |C|].
5537 Upper = C->abs() + 1;
5538 Lower = (-Upper) + 1;
5539 }
5540 }
5541 break;
5542
5543 case Instruction::UDiv:
5544 if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
5545 // 'udiv x, C' produces [0, UINT_MAX / C].
5546 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
5547 } else if (match(BO.getOperand(0), m_APInt(C))) {
5548 // 'udiv C, x' produces [0, C].
5549 Upper = *C + 1;
5550 }
5551 break;
5552
5553 case Instruction::SRem:
5554 if (match(BO.getOperand(1), m_APInt(C))) {
5555 // 'srem x, C' produces (-|C|, |C|).
5556 Upper = C->abs();
5557 Lower = (-Upper) + 1;
5558 }
5559 break;
5560
5561 case Instruction::URem:
5562 if (match(BO.getOperand(1), m_APInt(C)))
5563 // 'urem x, C' produces [0, C).
5564 Upper = *C;
5565 break;
5566
5567 default:
5568 break;
5569 }
5570}
5571
5572static void setLimitsForIntrinsic(const IntrinsicInst &II, APInt &Lower,
5573 APInt &Upper) {
5574 unsigned Width = Lower.getBitWidth();
5575 const APInt *C;
5576 switch (II.getIntrinsicID()) {
5577 case Intrinsic::uadd_sat:
5578 // uadd.sat(x, C) produces [C, UINT_MAX].
5579 if (match(II.getOperand(0), m_APInt(C)) ||
5580 match(II.getOperand(1), m_APInt(C)))
5581 Lower = *C;
5582 break;
5583 case Intrinsic::sadd_sat:
5584 if (match(II.getOperand(0), m_APInt(C)) ||
5585 match(II.getOperand(1), m_APInt(C))) {
5586 if (C->isNegative()) {
5587 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
5588 Lower = APInt::getSignedMinValue(Width);
5589 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
5590 } else {
5591 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
5592 Lower = APInt::getSignedMinValue(Width) + *C;
5593 Upper = APInt::getSignedMaxValue(Width) + 1;
5594 }
5595 }
5596 break;
5597 case Intrinsic::usub_sat:
5598 // usub.sat(C, x) produces [0, C].
5599 if (match(II.getOperand(0), m_APInt(C)))
5600 Upper = *C + 1;
5601 // usub.sat(x, C) produces [0, UINT_MAX - C].
5602 else if (match(II.getOperand(1), m_APInt(C)))
5603 Upper = APInt::getMaxValue(Width) - *C + 1;
5604 break;
5605 case Intrinsic::ssub_sat:
5606 if (match(II.getOperand(0), m_APInt(C))) {
5607 if (C->isNegative()) {
5608 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
5609 Lower = APInt::getSignedMinValue(Width);
5610 Upper = *C - APInt::getSignedMinValue(Width) + 1;
5611 } else {
5612 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
5613 Lower = *C - APInt::getSignedMaxValue(Width);
5614 Upper = APInt::getSignedMaxValue(Width) + 1;
5615 }
5616 } else if (match(II.getOperand(1), m_APInt(C))) {
5617 if (C->isNegative()) {
5618 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
5619 Lower = APInt::getSignedMinValue(Width) - *C;
5620 Upper = APInt::getSignedMaxValue(Width) + 1;
5621 } else {
5622 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
5623 Lower = APInt::getSignedMinValue(Width);
5624 Upper = APInt::getSignedMaxValue(Width) - *C + 1;
5625 }
5626 }
5627 break;
5628 default:
5629 break;
5630 }
5631}
5632
Nikita Popovf89343b2019-03-18 21:20:03 +00005633static void setLimitsForSelectPattern(const SelectInst &SI, APInt &Lower,
Craig Topper66c08432019-08-07 18:28:16 +00005634 APInt &Upper, const InstrInfoQuery &IIQ) {
Simon Pilgrimf62293e2019-09-23 13:15:52 +00005635 const Value *LHS = nullptr, *RHS = nullptr;
Nikita Popovf89343b2019-03-18 21:20:03 +00005636 SelectPatternResult R = matchSelectPattern(&SI, LHS, RHS);
5637 if (R.Flavor == SPF_UNKNOWN)
5638 return;
5639
5640 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
5641
Nikita Popov00b5eca2019-03-20 18:16:02 +00005642 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
5643 // If the negation part of the abs (in RHS) has the NSW flag,
5644 // then the result of abs(X) is [0..SIGNED_MAX],
5645 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
Nikita Popovf89343b2019-03-18 21:20:03 +00005646 Lower = APInt::getNullValue(BitWidth);
Craig Topper66c08432019-08-07 18:28:16 +00005647 if (match(RHS, m_Neg(m_Specific(LHS))) &&
5648 IIQ.hasNoSignedWrap(cast<Instruction>(RHS)))
Nikita Popov00b5eca2019-03-20 18:16:02 +00005649 Upper = APInt::getSignedMaxValue(BitWidth) + 1;
5650 else
5651 Upper = APInt::getSignedMinValue(BitWidth) + 1;
Nikita Popovf89343b2019-03-18 21:20:03 +00005652 return;
5653 }
5654
5655 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
5656 // The result of -abs(X) is <= 0.
5657 Lower = APInt::getSignedMinValue(BitWidth);
5658 Upper = APInt(BitWidth, 1);
5659 return;
5660 }
5661
Nikita Popov3db93ac2019-04-07 17:22:16 +00005662 const APInt *C;
5663 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
5664 return;
5665
5666 switch (R.Flavor) {
5667 case SPF_UMIN:
5668 Upper = *C + 1;
5669 break;
5670 case SPF_UMAX:
5671 Lower = *C;
5672 break;
5673 case SPF_SMIN:
5674 Lower = APInt::getSignedMinValue(BitWidth);
5675 Upper = *C + 1;
5676 break;
5677 case SPF_SMAX:
5678 Lower = *C;
5679 Upper = APInt::getSignedMaxValue(BitWidth) + 1;
5680 break;
5681 default:
5682 break;
5683 }
Nikita Popovf89343b2019-03-18 21:20:03 +00005684}
5685
Nikita Popov49097592019-03-09 21:17:42 +00005686ConstantRange llvm::computeConstantRange(const Value *V, bool UseInstrInfo) {
5687 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
5688
Nikita Popov20838192019-03-19 17:53:56 +00005689 const APInt *C;
5690 if (match(V, m_APInt(C)))
5691 return ConstantRange(*C);
5692
Nikita Popov49097592019-03-09 21:17:42 +00005693 InstrInfoQuery IIQ(UseInstrInfo);
5694 unsigned BitWidth = V->getType()->getScalarSizeInBits();
5695 APInt Lower = APInt(BitWidth, 0);
5696 APInt Upper = APInt(BitWidth, 0);
5697 if (auto *BO = dyn_cast<BinaryOperator>(V))
5698 setLimitsForBinOp(*BO, Lower, Upper, IIQ);
5699 else if (auto *II = dyn_cast<IntrinsicInst>(V))
5700 setLimitsForIntrinsic(*II, Lower, Upper);
Nikita Popovf89343b2019-03-18 21:20:03 +00005701 else if (auto *SI = dyn_cast<SelectInst>(V))
Craig Topper66c08432019-08-07 18:28:16 +00005702 setLimitsForSelectPattern(*SI, Lower, Upper, IIQ);
Nikita Popov49097592019-03-09 21:17:42 +00005703
Nikita Popovdbc3fba2019-04-21 15:22:54 +00005704 ConstantRange CR = ConstantRange::getNonEmpty(Lower, Upper);
Nikita Popov49097592019-03-09 21:17:42 +00005705
5706 if (auto *I = dyn_cast<Instruction>(V))
5707 if (auto *Range = IIQ.getMetadata(I, LLVMContext::MD_range))
5708 CR = CR.intersectWith(getConstantRangeFromMetadata(*Range));
5709
5710 return CR;
5711}
Evgeniy Stepanov75344952019-08-15 22:58:28 +00005712
Evgeniy Stepanov55ccd162019-08-19 21:08:04 +00005713static Optional<int64_t>
5714getOffsetFromIndex(const GEPOperator *GEP, unsigned Idx, const DataLayout &DL) {
Evgeniy Stepanov75344952019-08-15 22:58:28 +00005715 // Skip over the first indices.
5716 gep_type_iterator GTI = gep_type_begin(GEP);
5717 for (unsigned i = 1; i != Idx; ++i, ++GTI)
5718 /*skip along*/;
5719
5720 // Compute the offset implied by the rest of the indices.
5721 int64_t Offset = 0;
5722 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
5723 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
5724 if (!OpC)
Evgeniy Stepanov55ccd162019-08-19 21:08:04 +00005725 return None;
Evgeniy Stepanov75344952019-08-15 22:58:28 +00005726 if (OpC->isZero())
5727 continue; // No offset.
5728
5729 // Handle struct indices, which add their field offset to the pointer.
5730 if (StructType *STy = GTI.getStructTypeOrNull()) {
5731 Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5732 continue;
5733 }
5734
5735 // Otherwise, we have a sequential type like an array or vector. Multiply
5736 // the index by the ElementSize.
5737 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
5738 Offset += Size * OpC->getSExtValue();
5739 }
5740
5741 return Offset;
5742}
5743
Evgeniy Stepanov55ccd162019-08-19 21:08:04 +00005744Optional<int64_t> llvm::isPointerOffset(const Value *Ptr1, const Value *Ptr2,
5745 const DataLayout &DL) {
Evgeniy Stepanov75344952019-08-15 22:58:28 +00005746 Ptr1 = Ptr1->stripPointerCasts();
5747 Ptr2 = Ptr2->stripPointerCasts();
5748
5749 // Handle the trivial case first.
5750 if (Ptr1 == Ptr2) {
Evgeniy Stepanov55ccd162019-08-19 21:08:04 +00005751 return 0;
Evgeniy Stepanov75344952019-08-15 22:58:28 +00005752 }
5753
Evgeniy Stepanov55ccd162019-08-19 21:08:04 +00005754 const GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
5755 const GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
Evgeniy Stepanov75344952019-08-15 22:58:28 +00005756
5757 // If one pointer is a GEP and the other isn't, then see if the GEP is a
5758 // constant offset from the base, as in "P" and "gep P, 1".
5759 if (GEP1 && !GEP2 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
Evgeniy Stepanov55ccd162019-08-19 21:08:04 +00005760 auto Offset = getOffsetFromIndex(GEP1, 1, DL);
5761 if (!Offset)
5762 return None;
5763 return -*Offset;
Evgeniy Stepanov75344952019-08-15 22:58:28 +00005764 }
5765
5766 if (GEP2 && !GEP1 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
Evgeniy Stepanov55ccd162019-08-19 21:08:04 +00005767 return getOffsetFromIndex(GEP2, 1, DL);
Evgeniy Stepanov75344952019-08-15 22:58:28 +00005768 }
5769
5770 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
5771 // base. After that base, they may have some number of common (and
5772 // potentially variable) indices. After that they handle some constant
5773 // offset, which determines their offset from each other. At this point, we
5774 // handle no other case.
5775 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
Evgeniy Stepanov55ccd162019-08-19 21:08:04 +00005776 return None;
Evgeniy Stepanov75344952019-08-15 22:58:28 +00005777
5778 // Skip any common indices and track the GEP types.
5779 unsigned Idx = 1;
5780 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
5781 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
5782 break;
5783
Evgeniy Stepanov55ccd162019-08-19 21:08:04 +00005784 auto Offset1 = getOffsetFromIndex(GEP1, Idx, DL);
5785 auto Offset2 = getOffsetFromIndex(GEP2, Idx, DL);
5786 if (!Offset1 || !Offset2)
5787 return None;
5788 return *Offset2 - *Offset1;
Evgeniy Stepanov75344952019-08-15 22:58:28 +00005789}