blob: d3cbd07d646148380fe863e621a63d730470f26f [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"
41#include "llvm/IR/DataLayout.h"
Matthias Braun50ec0b52017-05-19 22:37:09 +000042#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000043#include "llvm/IR/DiagnosticInfo.h"
Hal Finkel60db0582014-09-07 18:57:58 +000044#include "llvm/IR/Dominators.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000045#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000046#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/GlobalAlias.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000048#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/GlobalVariable.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000050#include "llvm/IR/InstrTypes.h"
51#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000052#include "llvm/IR/Instructions.h"
53#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000054#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/LLVMContext.h"
56#include "llvm/IR/Metadata.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000057#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000059#include "llvm/IR/PatternMatch.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000060#include "llvm/IR/Type.h"
61#include "llvm/IR/User.h"
62#include "llvm/IR/Value.h"
63#include "llvm/Support/Casting.h"
64#include "llvm/Support/CommandLine.h"
65#include "llvm/Support/Compiler.h"
66#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000067#include "llvm/Support/KnownBits.h"
Chris Lattner965c7692008-06-02 01:18:21 +000068#include "llvm/Support/MathExtras.h"
Matthias Braun37e5d792016-01-28 06:29:33 +000069#include <algorithm>
70#include <array>
Eugene Zelenko75075ef2017-09-01 21:37:29 +000071#include <cassert>
72#include <cstdint>
73#include <iterator>
Fangrui Songf78650a2018-07-30 19:41:25 +000074#include <utility>
Eugene Zelenko75075ef2017-09-01 21:37:29 +000075
Chris Lattner965c7692008-06-02 01:18:21 +000076using namespace llvm;
Duncan Sandsd3951082011-01-25 09:38:29 +000077using namespace llvm::PatternMatch;
78
79const unsigned MaxDepth = 6;
80
Philip Reames1c292272015-03-10 22:43:20 +000081// Controls the number of uses of the value searched for possible
82// dominating comparisons.
83static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
Igor Laevskycea9ede2015-09-29 14:57:52 +000084 cl::Hidden, cl::init(20));
Philip Reames1c292272015-03-10 22:43:20 +000085
Craig Topper6b3940a2017-05-03 22:25:19 +000086/// Returns the bitwidth of the given scalar or pointer type. For vector types,
87/// returns the element type's bitwidth.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000088static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
Duncan Sandsd3951082011-01-25 09:38:29 +000089 if (unsigned BitWidth = Ty->getScalarSizeInBits())
90 return BitWidth;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +000091
Elena Demikhovsky945b7e52018-02-14 06:58:08 +000092 return DL.getIndexTypeSizeInBits(Ty);
Duncan Sandsd3951082011-01-25 09:38:29 +000093}
Chris Lattner965c7692008-06-02 01:18:21 +000094
Benjamin Kramercfd8d902014-09-12 08:56:53 +000095namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +000096
Hal Finkel60db0582014-09-07 18:57:58 +000097// Simplifying using an assume can only be done in a particular control-flow
98// context (the context instruction provides that context). If an assume and
99// the context instruction are not in the same block then the DT helps in
100// figuring out if we can use it.
101struct Query {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000102 const DataLayout &DL;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000103 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +0000104 const Instruction *CxtI;
105 const DominatorTree *DT;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000106
Sanjay Patel54656ca2017-02-06 18:26:06 +0000107 // Unlike the other analyses, this may be a nullptr because not all clients
108 // provide it currently.
109 OptimizationRemarkEmitter *ORE;
Hal Finkel60db0582014-09-07 18:57:58 +0000110
Matthias Braun37e5d792016-01-28 06:29:33 +0000111 /// Set of assumptions that should be excluded from further queries.
112 /// This is because of the potential for mutual recursion to cause
113 /// computeKnownBits to repeatedly visit the same assume intrinsic. The
114 /// classic case of this is assume(x = y), which will attempt to determine
115 /// bits in x from bits in y, which will attempt to determine bits in y from
116 /// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
Craig Topper6e11a052017-05-08 16:22:48 +0000117 /// isKnownNonZero, which calls computeKnownBits and isKnownToBeAPowerOfTwo
118 /// (all of which can call computeKnownBits), and so on.
Li Huang755f75f2016-10-15 19:00:04 +0000119 std::array<const Value *, MaxDepth> Excluded;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000120
Florian Hahn19f9e322018-08-17 14:39:04 +0000121 /// If true, it is safe to use metadata during simplification.
122 InstrInfoQuery IIQ;
123
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000124 unsigned NumExcluded = 0;
Matthias Braun37e5d792016-01-28 06:29:33 +0000125
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000126 Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000127 const DominatorTree *DT, bool UseInstrInfo,
128 OptimizationRemarkEmitter *ORE = nullptr)
129 : DL(DL), AC(AC), CxtI(CxtI), DT(DT), ORE(ORE), IIQ(UseInstrInfo) {}
Hal Finkel60db0582014-09-07 18:57:58 +0000130
131 Query(const Query &Q, const Value *NewExcl)
Florian Hahn19f9e322018-08-17 14:39:04 +0000132 : 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 +0000133 NumExcluded(Q.NumExcluded) {
Matthias Braun37e5d792016-01-28 06:29:33 +0000134 Excluded = Q.Excluded;
135 Excluded[NumExcluded++] = NewExcl;
136 assert(NumExcluded <= Excluded.size());
137 }
138
139 bool isExcluded(const Value *Value) const {
140 if (NumExcluded == 0)
141 return false;
142 auto End = Excluded.begin() + NumExcluded;
143 return std::find(Excluded.begin(), End, Value) != End;
Hal Finkel60db0582014-09-07 18:57:58 +0000144 }
145};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000146
Benjamin Kramercfd8d902014-09-12 08:56:53 +0000147} // end anonymous namespace
Hal Finkel60db0582014-09-07 18:57:58 +0000148
Sanjay Patel547e9752014-11-04 16:09:50 +0000149// Given the provided Value and, potentially, a context instruction, return
Hal Finkel60db0582014-09-07 18:57:58 +0000150// the preferred context instruction (if any).
151static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
152 // If we've been provided with a context instruction, then use that (provided
153 // it has been inserted).
154 if (CxtI && CxtI->getParent())
155 return CxtI;
156
157 // If the value is really an already-inserted instruction, then use that.
158 CxtI = dyn_cast<Instruction>(V);
159 if (CxtI && CxtI->getParent())
160 return CxtI;
161
162 return nullptr;
163}
164
Craig Topperb45eabc2017-04-26 16:39:58 +0000165static void computeKnownBits(const Value *V, KnownBits &Known,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000166 unsigned Depth, const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000167
Craig Topperb45eabc2017-04-26 16:39:58 +0000168void llvm::computeKnownBits(const Value *V, KnownBits &Known,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000169 const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000170 AssumptionCache *AC, const Instruction *CxtI,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000171 const DominatorTree *DT,
Florian Hahn19f9e322018-08-17 14:39:04 +0000172 OptimizationRemarkEmitter *ORE, bool UseInstrInfo) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000173 ::computeKnownBits(V, Known, Depth,
Florian Hahn19f9e322018-08-17 14:39:04 +0000174 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
Hal Finkel60db0582014-09-07 18:57:58 +0000175}
176
Craig Topper6e11a052017-05-08 16:22:48 +0000177static KnownBits computeKnownBits(const Value *V, unsigned Depth,
178 const Query &Q);
179
180KnownBits llvm::computeKnownBits(const Value *V, const DataLayout &DL,
181 unsigned Depth, AssumptionCache *AC,
182 const Instruction *CxtI,
Craig Toppera2025ea2017-05-24 16:53:03 +0000183 const DominatorTree *DT,
Florian Hahn19f9e322018-08-17 14:39:04 +0000184 OptimizationRemarkEmitter *ORE,
185 bool UseInstrInfo) {
186 return ::computeKnownBits(
187 V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
Craig Topper6e11a052017-05-08 16:22:48 +0000188}
189
Pete Cooper35b00d52016-08-13 01:05:32 +0000190bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
Florian Hahn19f9e322018-08-17 14:39:04 +0000191 const DataLayout &DL, AssumptionCache *AC,
192 const Instruction *CxtI, const DominatorTree *DT,
193 bool UseInstrInfo) {
Jingyue Wuca321902015-05-14 23:53:19 +0000194 assert(LHS->getType() == RHS->getType() &&
195 "LHS and RHS should have the same type");
196 assert(LHS->getType()->isIntOrIntVectorTy() &&
197 "LHS and RHS should be integers");
Roman Lebedev620b3da2018-04-15 18:59:33 +0000198 // Look for an inverted mask: (X & ~M) op (Y & M).
199 Value *M;
200 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
201 match(RHS, m_c_And(m_Specific(M), m_Value())))
202 return true;
203 if (match(RHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
204 match(LHS, m_c_And(m_Specific(M), m_Value())))
205 return true;
Jingyue Wuca321902015-05-14 23:53:19 +0000206 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
Craig Topperb45eabc2017-04-26 16:39:58 +0000207 KnownBits LHSKnown(IT->getBitWidth());
208 KnownBits RHSKnown(IT->getBitWidth());
Florian Hahn19f9e322018-08-17 14:39:04 +0000209 computeKnownBits(LHS, LHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
210 computeKnownBits(RHS, RHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
Craig Topperb45eabc2017-04-26 16:39:58 +0000211 return (LHSKnown.Zero | RHSKnown.Zero).isAllOnesValue();
Jingyue Wuca321902015-05-14 23:53:19 +0000212}
213
Zaara Syeda3a7578c2017-05-31 17:12:38 +0000214bool llvm::isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI) {
215 for (const User *U : CxtI->users()) {
216 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
217 if (IC->isEquality())
218 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
219 if (C->isNullValue())
220 continue;
221 return false;
222 }
223 return true;
224}
225
Pete Cooper35b00d52016-08-13 01:05:32 +0000226static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000227 const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000228
Pete Cooper35b00d52016-08-13 01:05:32 +0000229bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
Florian Hahn19f9e322018-08-17 14:39:04 +0000230 bool OrZero, unsigned Depth,
231 AssumptionCache *AC, const Instruction *CxtI,
232 const DominatorTree *DT, bool UseInstrInfo) {
233 return ::isKnownToBeAPowerOfTwo(
234 V, OrZero, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000235}
236
Pete Cooper35b00d52016-08-13 01:05:32 +0000237static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000238
Pete Cooper35b00d52016-08-13 01:05:32 +0000239bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000240 AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000241 const DominatorTree *DT, bool UseInstrInfo) {
242 return ::isKnownNonZero(V, Depth,
243 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000244}
245
Pete Cooper35b00d52016-08-13 01:05:32 +0000246bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL,
Florian Hahn19f9e322018-08-17 14:39:04 +0000247 unsigned Depth, AssumptionCache *AC,
248 const Instruction *CxtI, const DominatorTree *DT,
249 bool UseInstrInfo) {
250 KnownBits Known =
251 computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
Craig Topper6e11a052017-05-08 16:22:48 +0000252 return Known.isNonNegative();
Jingyue Wu10fcea52015-08-20 18:27:04 +0000253}
254
Pete Cooper35b00d52016-08-13 01:05:32 +0000255bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000256 AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000257 const DominatorTree *DT, bool UseInstrInfo) {
Philip Reames8f12eba2016-03-09 21:31:47 +0000258 if (auto *CI = dyn_cast<ConstantInt>(V))
259 return CI->getValue().isStrictlyPositive();
Sanjoy Das6082c1a2016-05-07 02:08:15 +0000260
Philip Reames8f12eba2016-03-09 21:31:47 +0000261 // TODO: We'd doing two recursive queries here. We should factor this such
262 // that only a single query is needed.
Florian Hahn19f9e322018-08-17 14:39:04 +0000263 return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT, UseInstrInfo) &&
264 isKnownNonZero(V, DL, Depth, AC, CxtI, DT, UseInstrInfo);
Philip Reames8f12eba2016-03-09 21:31:47 +0000265}
266
Pete Cooper35b00d52016-08-13 01:05:32 +0000267bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000268 AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000269 const DominatorTree *DT, bool UseInstrInfo) {
270 KnownBits Known =
271 computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
Craig Topper6e11a052017-05-08 16:22:48 +0000272 return Known.isNegative();
Nick Lewycky762f8a82016-04-21 00:53:14 +0000273}
274
Pete Cooper35b00d52016-08-13 01:05:32 +0000275static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q);
James Molloy1d88d6f2015-10-22 13:18:42 +0000276
Pete Cooper35b00d52016-08-13 01:05:32 +0000277bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
Florian Hahn19f9e322018-08-17 14:39:04 +0000278 const DataLayout &DL, AssumptionCache *AC,
279 const Instruction *CxtI, const DominatorTree *DT,
280 bool UseInstrInfo) {
281 return ::isKnownNonEqual(V1, V2,
282 Query(DL, AC, safeCxtI(V1, safeCxtI(V2, CxtI)), DT,
283 UseInstrInfo, /*ORE=*/nullptr));
James Molloy1d88d6f2015-10-22 13:18:42 +0000284}
285
Pete Cooper35b00d52016-08-13 01:05:32 +0000286static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000287 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000288
Pete Cooper35b00d52016-08-13 01:05:32 +0000289bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
Florian Hahn19f9e322018-08-17 14:39:04 +0000290 const DataLayout &DL, unsigned Depth,
291 AssumptionCache *AC, const Instruction *CxtI,
292 const DominatorTree *DT, bool UseInstrInfo) {
293 return ::MaskedValueIsZero(
294 V, Mask, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000295}
296
Pete Cooper35b00d52016-08-13 01:05:32 +0000297static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
298 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000299
Pete Cooper35b00d52016-08-13 01:05:32 +0000300unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000301 unsigned Depth, AssumptionCache *AC,
302 const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000303 const DominatorTree *DT, bool UseInstrInfo) {
304 return ::ComputeNumSignBits(
305 V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Hal Finkel60db0582014-09-07 18:57:58 +0000306}
307
Craig Topper8fbb74b2017-03-24 22:12:10 +0000308static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
309 bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000310 KnownBits &KnownOut, KnownBits &Known2,
Craig Topper8fbb74b2017-03-24 22:12:10 +0000311 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000312 unsigned BitWidth = KnownOut.getBitWidth();
Craig Topper8fbb74b2017-03-24 22:12:10 +0000313
314 // If an initial sequence of bits in the result is not needed, the
315 // corresponding bits in the operands are not needed.
Craig Topperb45eabc2017-04-26 16:39:58 +0000316 KnownBits LHSKnown(BitWidth);
317 computeKnownBits(Op0, LHSKnown, Depth + 1, Q);
318 computeKnownBits(Op1, Known2, Depth + 1, Q);
Craig Topper8fbb74b2017-03-24 22:12:10 +0000319
Craig Topperb498a232017-08-08 16:29:35 +0000320 KnownOut = KnownBits::computeForAddSub(Add, NSW, LHSKnown, Known2);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000321}
322
Pete Cooper35b00d52016-08-13 01:05:32 +0000323static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000324 KnownBits &Known, KnownBits &Known2,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000325 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000326 unsigned BitWidth = Known.getBitWidth();
327 computeKnownBits(Op1, Known, Depth + 1, Q);
328 computeKnownBits(Op0, Known2, Depth + 1, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000329
330 bool isKnownNegative = false;
331 bool isKnownNonNegative = false;
332 // If the multiplication is known not to overflow, compute the sign bit.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000333 if (NSW) {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000334 if (Op0 == Op1) {
335 // The product of a number with itself is non-negative.
336 isKnownNonNegative = true;
337 } else {
Craig Topperca48af32017-04-29 16:43:11 +0000338 bool isKnownNonNegativeOp1 = Known.isNonNegative();
339 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
340 bool isKnownNegativeOp1 = Known.isNegative();
341 bool isKnownNegativeOp0 = Known2.isNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000342 // The product of two numbers with the same sign is non-negative.
343 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
344 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
345 // The product of a negative number and a non-negative number is either
346 // negative or zero.
347 if (!isKnownNonNegative)
348 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000349 isKnownNonZero(Op0, Depth, Q)) ||
Nick Lewyckyfa306072012-03-18 23:28:48 +0000350 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000351 isKnownNonZero(Op1, Depth, Q));
Nick Lewyckyfa306072012-03-18 23:28:48 +0000352 }
353 }
354
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000355 assert(!Known.hasConflict() && !Known2.hasConflict());
356 // Compute a conservative estimate for high known-0 bits.
Craig Topper8df66c62017-05-12 17:20:30 +0000357 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
358 Known2.countMinLeadingZeros(),
Nick Lewyckyfa306072012-03-18 23:28:48 +0000359 BitWidth) - BitWidth;
Nick Lewyckyfa306072012-03-18 23:28:48 +0000360 LeadZ = std::min(LeadZ, BitWidth);
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000361
362 // The result of the bottom bits of an integer multiply can be
363 // inferred by looking at the bottom bits of both operands and
364 // multiplying them together.
365 // We can infer at least the minimum number of known trailing bits
366 // of both operands. Depending on number of trailing zeros, we can
367 // infer more bits, because (a*b) <=> ((a/m) * (b/n)) * (m*n) assuming
368 // a and b are divisible by m and n respectively.
369 // We then calculate how many of those bits are inferrable and set
370 // the output. For example, the i8 mul:
371 // a = XXXX1100 (12)
372 // b = XXXX1110 (14)
373 // We know the bottom 3 bits are zero since the first can be divided by
374 // 4 and the second by 2, thus having ((12/4) * (14/2)) * (2*4).
375 // Applying the multiplication to the trimmed arguments gets:
376 // XX11 (3)
377 // X111 (7)
378 // -------
379 // XX11
380 // XX11
381 // XX11
382 // XX11
383 // -------
384 // XXXXX01
385 // Which allows us to infer the 2 LSBs. Since we're multiplying the result
386 // by 8, the bottom 3 bits will be 0, so we can infer a total of 5 bits.
387 // The proof for this can be described as:
388 // Pre: (C1 >= 0) && (C1 < (1 << C5)) && (C2 >= 0) && (C2 < (1 << C6)) &&
389 // (C7 == (1 << (umin(countTrailingZeros(C1), C5) +
390 // umin(countTrailingZeros(C2), C6) +
391 // umin(C5 - umin(countTrailingZeros(C1), C5),
392 // C6 - umin(countTrailingZeros(C2), C6)))) - 1)
393 // %aa = shl i8 %a, C5
394 // %bb = shl i8 %b, C6
395 // %aaa = or i8 %aa, C1
396 // %bbb = or i8 %bb, C2
397 // %mul = mul i8 %aaa, %bbb
398 // %mask = and i8 %mul, C7
399 // =>
400 // %mask = i8 ((C1*C2)&C7)
401 // Where C5, C6 describe the known bits of %a, %b
402 // C1, C2 describe the known bottom bits of %a, %b.
403 // C7 describes the mask of the known bits of the result.
404 APInt Bottom0 = Known.One;
405 APInt Bottom1 = Known2.One;
406
407 // How many times we'd be able to divide each argument by 2 (shr by 1).
408 // This gives us the number of trailing zeros on the multiplication result.
409 unsigned TrailBitsKnown0 = (Known.Zero | Known.One).countTrailingOnes();
410 unsigned TrailBitsKnown1 = (Known2.Zero | Known2.One).countTrailingOnes();
411 unsigned TrailZero0 = Known.countMinTrailingZeros();
412 unsigned TrailZero1 = Known2.countMinTrailingZeros();
413 unsigned TrailZ = TrailZero0 + TrailZero1;
414
415 // Figure out the fewest known-bits operand.
416 unsigned SmallestOperand = std::min(TrailBitsKnown0 - TrailZero0,
417 TrailBitsKnown1 - TrailZero1);
418 unsigned ResultBitsKnown = std::min(SmallestOperand + TrailZ, BitWidth);
419
420 APInt BottomKnown = Bottom0.getLoBits(TrailBitsKnown0) *
421 Bottom1.getLoBits(TrailBitsKnown1);
422
Craig Topperf0aeee02017-05-05 17:36:09 +0000423 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000424 Known.Zero.setHighBits(LeadZ);
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000425 Known.Zero |= (~BottomKnown).getLoBits(ResultBitsKnown);
426 Known.One |= BottomKnown.getLoBits(ResultBitsKnown);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000427
428 // Only make use of no-wrap flags if we failed to compute the sign bit
429 // directly. This matters if the multiplication always overflows, in
430 // which case we prefer to follow the result of the direct computation,
431 // though as the program is invoking undefined behaviour we can choose
432 // whatever we like here.
Craig Topperca48af32017-04-29 16:43:11 +0000433 if (isKnownNonNegative && !Known.isNegative())
434 Known.makeNonNegative();
435 else if (isKnownNegative && !Known.isNonNegative())
436 Known.makeNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000437}
438
Jingyue Wu37fcb592014-06-19 16:50:16 +0000439void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
Craig Topperf42b23f2017-04-28 06:28:56 +0000440 KnownBits &Known) {
441 unsigned BitWidth = Known.getBitWidth();
Rafael Espindola53190532012-03-30 15:52:11 +0000442 unsigned NumRanges = Ranges.getNumOperands() / 2;
443 assert(NumRanges >= 1);
444
Craig Topperf42b23f2017-04-28 06:28:56 +0000445 Known.Zero.setAllBits();
446 Known.One.setAllBits();
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000447
Rafael Espindola53190532012-03-30 15:52:11 +0000448 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000449 ConstantInt *Lower =
450 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
451 ConstantInt *Upper =
452 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
Rafael Espindola53190532012-03-30 15:52:11 +0000453 ConstantRange Range(Lower->getValue(), Upper->getValue());
Rafael Espindola53190532012-03-30 15:52:11 +0000454
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000455 // The first CommonPrefixBits of all values in Range are equal.
456 unsigned CommonPrefixBits =
457 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
458
459 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
Craig Topperf42b23f2017-04-28 06:28:56 +0000460 Known.One &= Range.getUnsignedMax() & Mask;
461 Known.Zero &= ~Range.getUnsignedMax() & Mask;
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000462 }
Rafael Espindola53190532012-03-30 15:52:11 +0000463}
Jay Foad5a29c362014-05-15 12:12:55 +0000464
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000465static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
Hal Finkel60db0582014-09-07 18:57:58 +0000466 SmallVector<const Value *, 16> WorkSet(1, I);
467 SmallPtrSet<const Value *, 32> Visited;
468 SmallPtrSet<const Value *, 16> EphValues;
469
Hal Finkelf2199b22015-10-23 20:37:08 +0000470 // The instruction defining an assumption's condition itself is always
471 // considered ephemeral to that assumption (even if it has other
472 // non-ephemeral users). See r246696's test case for an example.
David Majnemer0a16c222016-08-11 21:15:00 +0000473 if (is_contained(I->operands(), E))
Hal Finkelf2199b22015-10-23 20:37:08 +0000474 return true;
475
Hal Finkel60db0582014-09-07 18:57:58 +0000476 while (!WorkSet.empty()) {
477 const Value *V = WorkSet.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +0000478 if (!Visited.insert(V).second)
Hal Finkel60db0582014-09-07 18:57:58 +0000479 continue;
480
481 // If all uses of this value are ephemeral, then so is this value.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000482 if (llvm::all_of(V->users(), [&](const User *U) {
483 return EphValues.count(U);
484 })) {
Hal Finkel60db0582014-09-07 18:57:58 +0000485 if (V == E)
486 return true;
487
Hal Finkelb03dd4b2017-08-14 17:11:43 +0000488 if (V == I || isSafeToSpeculativelyExecute(V)) {
489 EphValues.insert(V);
490 if (const User *U = dyn_cast<User>(V))
491 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
492 J != JE; ++J)
493 WorkSet.push_back(*J);
494 }
Hal Finkel60db0582014-09-07 18:57:58 +0000495 }
496 }
497
498 return false;
499}
500
501// Is this an intrinsic that cannot be speculated but also cannot trap?
Haicheng Wua4461512017-12-15 14:34:41 +0000502bool llvm::isAssumeLikeIntrinsic(const Instruction *I) {
Hal Finkel60db0582014-09-07 18:57:58 +0000503 if (const CallInst *CI = dyn_cast<CallInst>(I))
504 if (Function *F = CI->getCalledFunction())
505 switch (F->getIntrinsicID()) {
506 default: break;
507 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
508 case Intrinsic::assume:
Dan Gohman2c74fe92017-11-08 21:59:51 +0000509 case Intrinsic::sideeffect:
Hal Finkel60db0582014-09-07 18:57:58 +0000510 case Intrinsic::dbg_declare:
511 case Intrinsic::dbg_value:
Shiva Chen2c864552018-05-09 02:40:45 +0000512 case Intrinsic::dbg_label:
Hal Finkel60db0582014-09-07 18:57:58 +0000513 case Intrinsic::invariant_start:
514 case Intrinsic::invariant_end:
515 case Intrinsic::lifetime_start:
516 case Intrinsic::lifetime_end:
517 case Intrinsic::objectsize:
518 case Intrinsic::ptr_annotation:
519 case Intrinsic::var_annotation:
520 return true;
521 }
522
523 return false;
524}
525
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000526bool llvm::isValidAssumeForContext(const Instruction *Inv,
527 const Instruction *CxtI,
528 const DominatorTree *DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000529 // There are two restrictions on the use of an assume:
530 // 1. The assume must dominate the context (or the control flow must
531 // reach the assume whenever it reaches the context).
532 // 2. The context must not be in the assume's set of ephemeral values
533 // (otherwise we will use the assume to prove that the condition
534 // feeding the assume is trivially true, thus causing the removal of
535 // the assume).
536
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000537 if (DT) {
Pete Cooper54a02552016-08-12 01:00:15 +0000538 if (DT->dominates(Inv, CxtI))
Hal Finkel60db0582014-09-07 18:57:58 +0000539 return true;
Pete Cooper54a02552016-08-12 01:00:15 +0000540 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
541 // We don't have a DT, but this trivially dominates.
542 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000543 }
544
Pete Cooper54a02552016-08-12 01:00:15 +0000545 // With or without a DT, the only remaining case we will check is if the
546 // instructions are in the same BB. Give up if that is not the case.
547 if (Inv->getParent() != CxtI->getParent())
548 return false;
549
Vedant Kumard3196742018-02-28 19:08:52 +0000550 // If we have a dom tree, then we now know that the assume doesn't dominate
Pete Cooper54a02552016-08-12 01:00:15 +0000551 // the other instruction. If we don't have a dom tree then we can check if
552 // the assume is first in the BB.
553 if (!DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000554 // Search forward from the assume until we reach the context (or the end
555 // of the block); the common case is that the assume will come first.
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000556 for (auto I = std::next(BasicBlock::const_iterator(Inv)),
Hal Finkel60db0582014-09-07 18:57:58 +0000557 IE = Inv->getParent()->end(); I != IE; ++I)
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000558 if (&*I == CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000559 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000560 }
561
Pete Cooper54a02552016-08-12 01:00:15 +0000562 // The context comes first, but they're both in the same block. Make sure
563 // there is nothing in between that might interrupt the control flow.
564 for (BasicBlock::const_iterator I =
565 std::next(BasicBlock::const_iterator(CxtI)), IE(Inv);
566 I != IE; ++I)
567 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
568 return false;
569
570 return !isEphemeralValueOf(Inv, CxtI);
Hal Finkel60db0582014-09-07 18:57:58 +0000571}
572
Craig Topperb45eabc2017-04-26 16:39:58 +0000573static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
574 unsigned Depth, const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000575 // Use of assumptions is context-sensitive. If we don't have a context, we
576 // cannot use them!
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000577 if (!Q.AC || !Q.CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000578 return;
579
Craig Topperb45eabc2017-04-26 16:39:58 +0000580 unsigned BitWidth = Known.getBitWidth();
Hal Finkel60db0582014-09-07 18:57:58 +0000581
Hal Finkel8a9a7832017-01-11 13:24:24 +0000582 // Note that the patterns below need to be kept in sync with the code
583 // in AssumptionCache::updateAffectedValues.
584
585 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000586 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +0000587 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000588 CallInst *I = cast<CallInst>(AssumeVH);
589 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
590 "Got assumption for the wrong function!");
591 if (Q.isExcluded(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000592 continue;
593
Vedant Kumard3196742018-02-28 19:08:52 +0000594 // Warning: This loop can end up being somewhat performance sensitive.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000595 // We're running this loop for once for each value queried resulting in a
596 // runtime of ~O(#assumes * #values).
Philip Reames00d3b272014-11-24 23:44:28 +0000597
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000598 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
599 "must be an assume intrinsic");
600
601 Value *Arg = I->getArgOperand(0);
602
603 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000604 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000605 Known.setAllOnes();
Hal Finkel60db0582014-09-07 18:57:58 +0000606 return;
607 }
Sanjay Patel96669962017-01-17 18:15:49 +0000608 if (match(Arg, m_Not(m_Specific(V))) &&
609 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
610 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000611 Known.setAllZero();
Sanjay Patel96669962017-01-17 18:15:49 +0000612 return;
613 }
Hal Finkel60db0582014-09-07 18:57:58 +0000614
David Majnemer9b609752014-12-12 23:59:29 +0000615 // The remaining tests are all recursive, so bail out if we hit the limit.
616 if (Depth == MaxDepth)
617 continue;
618
Hal Finkel60db0582014-09-07 18:57:58 +0000619 Value *A, *B;
Sanjay Patel2a707032019-03-03 18:59:33 +0000620 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
Hal Finkel60db0582014-09-07 18:57:58 +0000621
622 CmpInst::Predicate Pred;
Igor Laevskycec8f472017-12-05 12:18:15 +0000623 uint64_t C;
Hal Finkel60db0582014-09-07 18:57:58 +0000624 // assume(v = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000625 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000626 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000627 KnownBits RHSKnown(BitWidth);
628 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
629 Known.Zero |= RHSKnown.Zero;
630 Known.One |= RHSKnown.One;
Hal Finkel60db0582014-09-07 18:57:58 +0000631 // assume(v & b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000632 } else if (match(Arg,
633 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000634 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000635 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000636 KnownBits RHSKnown(BitWidth);
637 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
638 KnownBits MaskKnown(BitWidth);
639 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel60db0582014-09-07 18:57:58 +0000640
641 // For those bits in the mask that are known to be one, we can propagate
642 // known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000643 Known.Zero |= RHSKnown.Zero & MaskKnown.One;
644 Known.One |= RHSKnown.One & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000645 // assume(~(v & b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000646 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
647 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000648 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000649 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000650 KnownBits RHSKnown(BitWidth);
651 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
652 KnownBits MaskKnown(BitWidth);
653 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000654
655 // For those bits in the mask that are known to be one, we can propagate
656 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000657 Known.Zero |= RHSKnown.One & MaskKnown.One;
658 Known.One |= RHSKnown.Zero & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000659 // assume(v | b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000660 } else if (match(Arg,
661 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000662 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000663 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000664 KnownBits RHSKnown(BitWidth);
665 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
666 KnownBits BKnown(BitWidth);
667 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000668
669 // For those bits in B that are known to be zero, we can propagate known
670 // bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000671 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
672 Known.One |= RHSKnown.One & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000673 // assume(~(v | b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000674 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
675 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000676 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000677 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000678 KnownBits RHSKnown(BitWidth);
679 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
680 KnownBits BKnown(BitWidth);
681 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000682
683 // For those bits in B that are known to be zero, we can propagate
684 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000685 Known.Zero |= RHSKnown.One & BKnown.Zero;
686 Known.One |= RHSKnown.Zero & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000687 // assume(v ^ b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000688 } else if (match(Arg,
689 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000690 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000691 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000692 KnownBits RHSKnown(BitWidth);
693 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
694 KnownBits BKnown(BitWidth);
695 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000696
697 // For those bits in B that are known to be zero, we can propagate known
698 // bits from the RHS to V. For those bits in B that are known to be one,
699 // we can propagate inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000700 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
701 Known.One |= RHSKnown.One & BKnown.Zero;
702 Known.Zero |= RHSKnown.One & BKnown.One;
703 Known.One |= RHSKnown.Zero & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000704 // assume(~(v ^ b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000705 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
706 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000707 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000708 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000709 KnownBits RHSKnown(BitWidth);
710 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
711 KnownBits BKnown(BitWidth);
712 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000713
714 // For those bits in B that are known to be zero, we can propagate
715 // inverted known bits from the RHS to V. For those bits in B that are
716 // known to be one, we can propagate known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000717 Known.Zero |= RHSKnown.One & BKnown.Zero;
718 Known.One |= RHSKnown.Zero & BKnown.Zero;
719 Known.Zero |= RHSKnown.Zero & BKnown.One;
720 Known.One |= RHSKnown.One & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000721 // assume(v << c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000722 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
723 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000724 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000725 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
726 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000727 KnownBits RHSKnown(BitWidth);
728 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000729 // For those bits in RHS that are known, we can propagate them to known
730 // bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000731 RHSKnown.Zero.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000732 Known.Zero |= RHSKnown.Zero;
Igor Laevskycec8f472017-12-05 12:18:15 +0000733 RHSKnown.One.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000734 Known.One |= RHSKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000735 // assume(~(v << c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000736 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
737 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000738 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000739 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
740 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000741 KnownBits RHSKnown(BitWidth);
742 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000743 // For those bits in RHS that are known, we can propagate them inverted
744 // to known bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000745 RHSKnown.One.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000746 Known.Zero |= RHSKnown.One;
Igor Laevskycec8f472017-12-05 12:18:15 +0000747 RHSKnown.Zero.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000748 Known.One |= RHSKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000749 // assume(v >> c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000750 } else if (match(Arg,
Craig Topper7b66ffe2017-06-24 06:24:04 +0000751 m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000752 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000753 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000754 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
755 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000756 KnownBits RHSKnown(BitWidth);
757 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000758 // For those bits in RHS that are known, we can propagate them to known
759 // bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000760 Known.Zero |= RHSKnown.Zero << C;
761 Known.One |= RHSKnown.One << C;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000762 // assume(~(v >> c) = a)
Craig Topper7b66ffe2017-06-24 06:24:04 +0000763 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shr(m_V, m_ConstantInt(C))),
Philip Reames00d3b272014-11-24 23:44:28 +0000764 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000765 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000766 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
767 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000768 KnownBits RHSKnown(BitWidth);
769 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000770 // For those bits in RHS that are known, we can propagate them inverted
771 // to known bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000772 Known.Zero |= RHSKnown.One << C;
773 Known.One |= RHSKnown.Zero << C;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000774 // assume(v >=_s c) where c is non-negative
Philip Reames00d3b272014-11-24 23:44:28 +0000775 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000776 Pred == ICmpInst::ICMP_SGE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000777 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000778 KnownBits RHSKnown(BitWidth);
779 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000780
Craig Topperca48af32017-04-29 16:43:11 +0000781 if (RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000782 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000783 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000784 }
785 // assume(v >_s c) where c is at least -1.
Philip Reames00d3b272014-11-24 23:44:28 +0000786 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000787 Pred == ICmpInst::ICMP_SGT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000788 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000789 KnownBits RHSKnown(BitWidth);
790 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000791
Craig Topperf0aeee02017-05-05 17:36:09 +0000792 if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000793 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000794 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000795 }
796 // assume(v <=_s c) where c is negative
Philip Reames00d3b272014-11-24 23:44:28 +0000797 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000798 Pred == ICmpInst::ICMP_SLE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000799 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000800 KnownBits RHSKnown(BitWidth);
801 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000802
Craig Topperca48af32017-04-29 16:43:11 +0000803 if (RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000804 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000805 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000806 }
807 // assume(v <_s c) where c is non-positive
Philip Reames00d3b272014-11-24 23:44:28 +0000808 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000809 Pred == ICmpInst::ICMP_SLT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000810 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000811 KnownBits RHSKnown(BitWidth);
812 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000813
Craig Topperf0aeee02017-05-05 17:36:09 +0000814 if (RHSKnown.isZero() || RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000815 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000816 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000817 }
818 // assume(v <=_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000819 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000820 Pred == ICmpInst::ICMP_ULE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000821 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000822 KnownBits RHSKnown(BitWidth);
823 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000824
825 // Whatever high bits in c are zero are known to be zero.
Craig Topper8df66c62017-05-12 17:20:30 +0000826 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
827 // assume(v <_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000828 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000829 Pred == ICmpInst::ICMP_ULT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000830 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000831 KnownBits RHSKnown(BitWidth);
832 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000833
Sanjay Patela60aec12018-02-08 14:52:40 +0000834 // If the RHS is known zero, then this assumption must be wrong (nothing
835 // is unsigned less than zero). Signal a conflict and get out of here.
836 if (RHSKnown.isZero()) {
837 Known.Zero.setAllBits();
838 Known.One.setAllBits();
839 break;
840 }
841
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000842 // Whatever high bits in c are zero are known to be zero (if c is a power
843 // of 2, then one more).
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000844 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
Craig Topper8df66c62017-05-12 17:20:30 +0000845 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000846 else
Craig Topper8df66c62017-05-12 17:20:30 +0000847 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
Hal Finkel60db0582014-09-07 18:57:58 +0000848 }
849 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000850
851 // If assumptions conflict with each other or previous known bits, then we
Sanjay Patel54656ca2017-02-06 18:26:06 +0000852 // have a logical fallacy. It's possible that the assumption is not reachable,
853 // so this isn't a real bug. On the other hand, the program may have undefined
854 // behavior, or we might have a bug in the compiler. We can't assert/crash, so
855 // clear out the known bits, try to warn the user, and hope for the best.
Craig Topperb45eabc2017-04-26 16:39:58 +0000856 if (Known.Zero.intersects(Known.One)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000857 Known.resetAll();
Sanjay Patel54656ca2017-02-06 18:26:06 +0000858
Vivek Pandya95906582017-10-11 17:12:59 +0000859 if (Q.ORE)
860 Q.ORE->emit([&]() {
861 auto *CxtI = const_cast<Instruction *>(Q.CxtI);
862 return OptimizationRemarkAnalysis("value-tracking", "BadAssumption",
863 CxtI)
864 << "Detected conflicting code assumptions. Program may "
865 "have undefined behavior, or compiler may have "
866 "internal error.";
867 });
Sanjay Patel25f6d712017-02-01 15:41:32 +0000868 }
Hal Finkel60db0582014-09-07 18:57:58 +0000869}
870
Sanjay Patelb7d12382017-10-16 14:46:37 +0000871/// Compute known bits from a shift operator, including those with a
872/// non-constant shift amount. Known is the output of this function. Known2 is a
873/// pre-allocated temporary with the same bit width as Known. KZF and KOF are
Vedant Kumard3196742018-02-28 19:08:52 +0000874/// operator-specific functions that, given the known-zero or known-one bits
Sanjay Patelb7d12382017-10-16 14:46:37 +0000875/// respectively, and a shift amount, compute the implied known-zero or
876/// known-one bits of the shift operator's result respectively for that shift
877/// amount. The results from calling KZF and KOF are conservatively combined for
878/// all permitted shift amounts.
David Majnemer54690dc2016-08-23 20:52:00 +0000879static void computeKnownBitsFromShiftOperator(
Craig Topperb45eabc2017-04-26 16:39:58 +0000880 const Operator *I, KnownBits &Known, KnownBits &Known2,
881 unsigned Depth, const Query &Q,
Sam McCalld0d43e62017-12-04 12:51:49 +0000882 function_ref<APInt(const APInt &, unsigned)> KZF,
883 function_ref<APInt(const APInt &, unsigned)> KOF) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000884 unsigned BitWidth = Known.getBitWidth();
Hal Finkelf2199b22015-10-23 20:37:08 +0000885
886 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
887 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
888
Craig Topperb45eabc2017-04-26 16:39:58 +0000889 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Sam McCalld0d43e62017-12-04 12:51:49 +0000890 Known.Zero = KZF(Known.Zero, ShiftAmt);
891 Known.One = KOF(Known.One, ShiftAmt);
Sanjay Patele272be72017-10-12 17:31:46 +0000892 // If the known bits conflict, this must be an overflowing left shift, so
893 // the shift result is poison. We can return anything we want. Choose 0 for
894 // the best folding opportunity.
895 if (Known.hasConflict())
896 Known.setAllZero();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +0000897
Hal Finkelf2199b22015-10-23 20:37:08 +0000898 return;
899 }
900
Craig Topperb45eabc2017-04-26 16:39:58 +0000901 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000902
Sanjay Patele272be72017-10-12 17:31:46 +0000903 // If the shift amount could be greater than or equal to the bit-width of the
904 // LHS, the value could be poison, but bail out because the check below is
905 // expensive. TODO: Should we just carry on?
Craig Topperb45eabc2017-04-26 16:39:58 +0000906 if ((~Known.Zero).uge(BitWidth)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000907 Known.resetAll();
Oliver Stannard06204112017-03-14 10:13:17 +0000908 return;
909 }
910
Craig Topperb45eabc2017-04-26 16:39:58 +0000911 // Note: We cannot use Known.Zero.getLimitedValue() here, because if
Hal Finkelf2199b22015-10-23 20:37:08 +0000912 // BitWidth > 64 and any upper bits are known, we'll end up returning the
913 // limit value (which implies all bits are known).
Craig Topperb45eabc2017-04-26 16:39:58 +0000914 uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
915 uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
Hal Finkelf2199b22015-10-23 20:37:08 +0000916
917 // It would be more-clearly correct to use the two temporaries for this
918 // calculation. Reusing the APInts here to prevent unnecessary allocations.
Craig Topperf0aeee02017-05-05 17:36:09 +0000919 Known.resetAll();
Hal Finkelf2199b22015-10-23 20:37:08 +0000920
James Molloy493e57d2015-10-26 14:10:46 +0000921 // If we know the shifter operand is nonzero, we can sometimes infer more
922 // known bits. However this is expensive to compute, so be lazy about it and
923 // only compute it when absolutely necessary.
924 Optional<bool> ShifterOperandIsNonZero;
925
Hal Finkelf2199b22015-10-23 20:37:08 +0000926 // Early exit if we can't constrain any well-defined shift amount.
Craig Topperf93b7b12017-06-14 17:04:59 +0000927 if (!(ShiftAmtKZ & (PowerOf2Ceil(BitWidth) - 1)) &&
928 !(ShiftAmtKO & (PowerOf2Ceil(BitWidth) - 1))) {
Sanjay Patelb7d12382017-10-16 14:46:37 +0000929 ShifterOperandIsNonZero = isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000930 if (!*ShifterOperandIsNonZero)
931 return;
932 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000933
Craig Topperb45eabc2017-04-26 16:39:58 +0000934 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000935
Craig Topperb45eabc2017-04-26 16:39:58 +0000936 Known.Zero.setAllBits();
937 Known.One.setAllBits();
Hal Finkelf2199b22015-10-23 20:37:08 +0000938 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
939 // Combine the shifted known input bits only for those shift amounts
940 // compatible with its known constraints.
941 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
942 continue;
943 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
944 continue;
James Molloy493e57d2015-10-26 14:10:46 +0000945 // If we know the shifter is nonzero, we may be able to infer more known
946 // bits. This check is sunk down as far as possible to avoid the expensive
947 // call to isKnownNonZero if the cheaper checks above fail.
948 if (ShiftAmt == 0) {
949 if (!ShifterOperandIsNonZero.hasValue())
950 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000951 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000952 if (*ShifterOperandIsNonZero)
953 continue;
954 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000955
Sam McCalld0d43e62017-12-04 12:51:49 +0000956 Known.Zero &= KZF(Known2.Zero, ShiftAmt);
957 Known.One &= KOF(Known2.One, ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +0000958 }
959
Sanjay Patele272be72017-10-12 17:31:46 +0000960 // If the known bits conflict, the result is poison. Return a 0 and hope the
961 // caller can further optimize that.
962 if (Known.hasConflict())
963 Known.setAllZero();
Hal Finkelf2199b22015-10-23 20:37:08 +0000964}
965
Craig Topperb45eabc2017-04-26 16:39:58 +0000966static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known,
967 unsigned Depth, const Query &Q) {
968 unsigned BitWidth = Known.getBitWidth();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000969
Craig Topperb45eabc2017-04-26 16:39:58 +0000970 KnownBits Known2(Known);
Dan Gohman80ca01c2009-07-17 20:47:02 +0000971 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +0000972 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +0000973 case Instruction::Load:
Florian Hahn19f9e322018-08-17 14:39:04 +0000974 if (MDNode *MD =
975 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +0000976 computeKnownBitsFromRangeMetadata(*MD, Known);
Jay Foad5a29c362014-05-15 12:12:55 +0000977 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000978 case Instruction::And: {
979 // If either the LHS or the RHS are Zero, the result is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +0000980 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
981 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000982
Chris Lattner965c7692008-06-02 01:18:21 +0000983 // Output known-1 bits are only known if set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000984 Known.One &= Known2.One;
Chris Lattner965c7692008-06-02 01:18:21 +0000985 // Output known-0 are known to be clear if zero in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000986 Known.Zero |= Known2.Zero;
Philip Reames2d858742015-11-10 18:46:14 +0000987
988 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
989 // here we handle the more general case of adding any odd number by
990 // matching the form add(x, add(x, y)) where y is odd.
991 // TODO: This could be generalized to clearing any bit set in y where the
992 // following bit is known to be unset in y.
Roman Lebedev6959b8e2018-04-27 21:23:20 +0000993 Value *X = nullptr, *Y = nullptr;
Craig Topperb45eabc2017-04-26 16:39:58 +0000994 if (!Known.Zero[0] && !Known.One[0] &&
Roman Lebedev6959b8e2018-04-27 21:23:20 +0000995 match(I, m_c_BinOp(m_Value(X), m_Add(m_Deferred(X), m_Value(Y))))) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000996 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000997 computeKnownBits(Y, Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000998 if (Known2.countMinTrailingOnes() > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +0000999 Known.Zero.setBit(0);
Philip Reames2d858742015-11-10 18:46:14 +00001000 }
Jay Foad5a29c362014-05-15 12:12:55 +00001001 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001002 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001003 case Instruction::Or:
Craig Topperb45eabc2017-04-26 16:39:58 +00001004 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
1005 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001006
Chris Lattner965c7692008-06-02 01:18:21 +00001007 // Output known-0 bits are only known if clear in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001008 Known.Zero &= Known2.Zero;
Chris Lattner965c7692008-06-02 01:18:21 +00001009 // Output known-1 are known to be set if set in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001010 Known.One |= Known2.One;
Jay Foad5a29c362014-05-15 12:12:55 +00001011 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001012 case Instruction::Xor: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001013 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
1014 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001015
Chris Lattner965c7692008-06-02 01:18:21 +00001016 // Output known-0 bits are known if clear or set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001017 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
Chris Lattner965c7692008-06-02 01:18:21 +00001018 // Output known-1 are known to be set if set in only one of the LHS, RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001019 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
1020 Known.Zero = std::move(KnownZeroOut);
Jay Foad5a29c362014-05-15 12:12:55 +00001021 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001022 }
1023 case Instruction::Mul: {
Florian Hahn19f9e322018-08-17 14:39:04 +00001024 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Craig Topperb45eabc2017-04-26 16:39:58 +00001025 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, Known,
1026 Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001027 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001028 }
1029 case Instruction::UDiv: {
1030 // For the purposes of computing leading zeros we can conservatively
1031 // treat a udiv as a logical right shift by the power of 2 known to
1032 // be less than the denominator.
Craig Topperb45eabc2017-04-26 16:39:58 +00001033 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001034 unsigned LeadZ = Known2.countMinLeadingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001035
Craig Topperf0aeee02017-05-05 17:36:09 +00001036 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001037 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001038 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
1039 if (RHSMaxLeadingZeros != BitWidth)
1040 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
Chris Lattner965c7692008-06-02 01:18:21 +00001041
Craig Topperb45eabc2017-04-26 16:39:58 +00001042 Known.Zero.setHighBits(LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +00001043 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001044 }
David Majnemera19d0f22016-08-06 08:16:00 +00001045 case Instruction::Select: {
Craig Toppere953dec2017-04-13 20:39:37 +00001046 const Value *LHS, *RHS;
David Majnemera19d0f22016-08-06 08:16:00 +00001047 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
1048 if (SelectPatternResult::isMinOrMax(SPF)) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001049 computeKnownBits(RHS, Known, Depth + 1, Q);
1050 computeKnownBits(LHS, Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +00001051 } else {
Craig Topperb45eabc2017-04-26 16:39:58 +00001052 computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
1053 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +00001054 }
1055
1056 unsigned MaxHighOnes = 0;
1057 unsigned MaxHighZeros = 0;
1058 if (SPF == SPF_SMAX) {
1059 // If both sides are negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +00001060 if (Known.isNegative() && Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001061 // We can derive a lower bound on the result by taking the max of the
1062 // leading one bits.
Craig Topper8df66c62017-05-12 17:20:30 +00001063 MaxHighOnes =
1064 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001065 // If either side is non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +00001066 else if (Known.isNonNegative() || Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001067 MaxHighZeros = 1;
1068 } else if (SPF == SPF_SMIN) {
1069 // If both sides are non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +00001070 if (Known.isNonNegative() && Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001071 // We can derive an upper bound on the result by taking the max of the
1072 // leading zero bits.
Craig Topper8df66c62017-05-12 17:20:30 +00001073 MaxHighZeros = std::max(Known.countMinLeadingZeros(),
1074 Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +00001075 // If either side is negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +00001076 else if (Known.isNegative() || Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001077 MaxHighOnes = 1;
1078 } else if (SPF == SPF_UMAX) {
1079 // We can derive a lower bound on the result by taking the max of the
1080 // leading one bits.
1081 MaxHighOnes =
Craig Topper8df66c62017-05-12 17:20:30 +00001082 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001083 } else if (SPF == SPF_UMIN) {
1084 // We can derive an upper bound on the result by taking the max of the
1085 // leading zero bits.
1086 MaxHighZeros =
Craig Topper8df66c62017-05-12 17:20:30 +00001087 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topper8f77dca2018-05-25 19:18:09 +00001088 } else if (SPF == SPF_ABS) {
1089 // RHS from matchSelectPattern returns the negation part of abs pattern.
1090 // If the negate has an NSW flag we can assume the sign bit of the result
1091 // will be 0 because that makes abs(INT_MIN) undefined.
Florian Hahn19f9e322018-08-17 14:39:04 +00001092 if (Q.IIQ.hasNoSignedWrap(cast<Instruction>(RHS)))
Craig Topper8f77dca2018-05-25 19:18:09 +00001093 MaxHighZeros = 1;
David Majnemera19d0f22016-08-06 08:16:00 +00001094 }
1095
Chris Lattner965c7692008-06-02 01:18:21 +00001096 // Only known if known in both the LHS and RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001097 Known.One &= Known2.One;
1098 Known.Zero &= Known2.Zero;
David Majnemera19d0f22016-08-06 08:16:00 +00001099 if (MaxHighOnes > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001100 Known.One.setHighBits(MaxHighOnes);
David Majnemera19d0f22016-08-06 08:16:00 +00001101 if (MaxHighZeros > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001102 Known.Zero.setHighBits(MaxHighZeros);
Jay Foad5a29c362014-05-15 12:12:55 +00001103 break;
David Majnemera19d0f22016-08-06 08:16:00 +00001104 }
Chris Lattner965c7692008-06-02 01:18:21 +00001105 case Instruction::FPTrunc:
1106 case Instruction::FPExt:
1107 case Instruction::FPToUI:
1108 case Instruction::FPToSI:
1109 case Instruction::SIToFP:
1110 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +00001111 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +00001112 case Instruction::PtrToInt:
1113 case Instruction::IntToPtr:
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001114 // Fall through and handle them the same as zext/trunc.
1115 LLVM_FALLTHROUGH;
Chris Lattner965c7692008-06-02 01:18:21 +00001116 case Instruction::ZExt:
1117 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +00001118 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +00001119
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001120 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +00001121 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1122 // which fall through here.
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001123 Type *ScalarTy = SrcTy->getScalarType();
1124 SrcBitWidth = ScalarTy->isPointerTy() ?
1125 Q.DL.getIndexTypeSizeInBits(ScalarTy) :
1126 Q.DL.getTypeSizeInBits(ScalarTy);
Nadav Rotem15198e92012-10-26 17:17:05 +00001127
1128 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Bjorn Petterssond30f3082019-02-28 15:45:29 +00001129 Known = Known.zextOrTrunc(SrcBitWidth, false);
Craig Topperb45eabc2017-04-26 16:39:58 +00001130 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Bjorn Petterssond30f3082019-02-28 15:45:29 +00001131 Known = Known.zextOrTrunc(BitWidth, true /* ExtendedBitsAreKnownZero */);
Jay Foad5a29c362014-05-15 12:12:55 +00001132 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001133 }
1134 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +00001135 Type *SrcTy = I->getOperand(0)->getType();
Vedant Kumarb3091da2018-07-06 20:17:42 +00001136 if (SrcTy->isIntOrPtrTy() &&
Chris Lattneredb84072009-07-02 16:04:08 +00001137 // TODO: For now, not handling conversions like:
1138 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +00001139 !I->getType()->isVectorTy()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001140 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +00001141 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001142 }
1143 break;
1144 }
1145 case Instruction::SExt: {
1146 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001147 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +00001148
Craig Topperd938fd12017-05-03 22:07:25 +00001149 Known = Known.trunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001150 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001151 // If the sign bit of the input is known set or clear, then we know the
1152 // top bits of the result.
Craig Topperd938fd12017-05-03 22:07:25 +00001153 Known = Known.sext(BitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001154 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001155 }
Hal Finkelf2199b22015-10-23 20:37:08 +00001156 case Instruction::Shl: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001157 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Florian Hahn19f9e322018-08-17 14:39:04 +00001158 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Sam McCalld0d43e62017-12-04 12:51:49 +00001159 auto KZF = [NSW](const APInt &KnownZero, unsigned ShiftAmt) {
1160 APInt KZResult = KnownZero << ShiftAmt;
1161 KZResult.setLowBits(ShiftAmt); // Low bits known 0.
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001162 // If this shift has "nsw" keyword, then the result is either a poison
1163 // value or has the same sign bit as the first operand.
Sam McCalld0d43e62017-12-04 12:51:49 +00001164 if (NSW && KnownZero.isSignBitSet())
1165 KZResult.setSignBit();
1166 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001167 };
1168
Sam McCalld0d43e62017-12-04 12:51:49 +00001169 auto KOF = [NSW](const APInt &KnownOne, unsigned ShiftAmt) {
1170 APInt KOResult = KnownOne << ShiftAmt;
1171 if (NSW && KnownOne.isSignBitSet())
1172 KOResult.setSignBit();
1173 return KOResult;
1174 };
1175
1176 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001177 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001178 }
1179 case Instruction::LShr: {
Sanjay Patelb7d12382017-10-16 14:46:37 +00001180 // (lshr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Sam McCalld0d43e62017-12-04 12:51:49 +00001181 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1182 APInt KZResult = KnownZero.lshr(ShiftAmt);
1183 // High bits known zero.
1184 KZResult.setHighBits(ShiftAmt);
1185 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001186 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001187
Sam McCalld0d43e62017-12-04 12:51:49 +00001188 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1189 return KnownOne.lshr(ShiftAmt);
1190 };
1191
1192 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001193 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001194 }
1195 case Instruction::AShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001196 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Sam McCalld0d43e62017-12-04 12:51:49 +00001197 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1198 return KnownZero.ashr(ShiftAmt);
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.ashr(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 }
Chris Lattner965c7692008-06-02 01:18:21 +00001208 case Instruction::Sub: {
Florian Hahn19f9e322018-08-17 14:39:04 +00001209 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Jay Foada0653a32014-05-14 21:14:37 +00001210 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001211 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001212 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001213 }
Chris Lattner965c7692008-06-02 01:18:21 +00001214 case Instruction::Add: {
Florian Hahn19f9e322018-08-17 14:39:04 +00001215 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Jay Foada0653a32014-05-14 21:14:37 +00001216 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001217 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001218 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001219 }
1220 case Instruction::SRem:
1221 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001222 APInt RA = Rem->getValue().abs();
1223 if (RA.isPowerOf2()) {
1224 APInt LowBits = RA - 1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001225 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001226
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001227 // The low bits of the first operand are unchanged by the srem.
Craig Topperb45eabc2017-04-26 16:39:58 +00001228 Known.Zero = Known2.Zero & LowBits;
1229 Known.One = Known2.One & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001230
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001231 // If the first operand is non-negative or has all low bits zero, then
1232 // the upper bits are all zero.
Craig Topperca48af32017-04-29 16:43:11 +00001233 if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
Craig Topperb45eabc2017-04-26 16:39:58 +00001234 Known.Zero |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001235
1236 // If the first operand is negative and not all low bits are zero, then
1237 // the upper bits are all one.
Craig Topperca48af32017-04-29 16:43:11 +00001238 if (Known2.isNegative() && LowBits.intersects(Known2.One))
Craig Topperb45eabc2017-04-26 16:39:58 +00001239 Known.One |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001240
Craig Topperb45eabc2017-04-26 16:39:58 +00001241 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Craig Topperda886c62017-04-16 21:46:12 +00001242 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001243 }
1244 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001245
1246 // The sign bit is the LHS's sign bit, except when the result of the
1247 // remainder is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +00001248 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topperda886c62017-04-16 21:46:12 +00001249 // If it's known zero, our sign bit is also zero.
Craig Topperca48af32017-04-29 16:43:11 +00001250 if (Known2.isNonNegative())
1251 Known.makeNonNegative();
Nick Lewyckye4679792011-03-07 01:50:10 +00001252
Chris Lattner965c7692008-06-02 01:18:21 +00001253 break;
1254 case Instruction::URem: {
1255 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001256 const APInt &RA = Rem->getValue();
Chris Lattner965c7692008-06-02 01:18:21 +00001257 if (RA.isPowerOf2()) {
1258 APInt LowBits = (RA - 1);
Craig Topperb45eabc2017-04-26 16:39:58 +00001259 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1260 Known.Zero |= ~LowBits;
1261 Known.One &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001262 break;
1263 }
1264 }
1265
1266 // Since the result is less than or equal to either operand, any leading
1267 // zero bits in either operand must also exist in the result.
Craig Topperb45eabc2017-04-26 16:39:58 +00001268 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1269 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001270
Craig Topper8df66c62017-05-12 17:20:30 +00001271 unsigned Leaders =
1272 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topperf0aeee02017-05-05 17:36:09 +00001273 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001274 Known.Zero.setHighBits(Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001275 break;
1276 }
1277
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001278 case Instruction::Alloca: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001279 const AllocaInst *AI = cast<AllocaInst>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001280 unsigned Align = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001281 if (Align == 0)
Eduard Burtescu90c44492016-01-18 00:10:01 +00001282 Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001283
Chris Lattner965c7692008-06-02 01:18:21 +00001284 if (Align > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001285 Known.Zero.setLowBits(countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001286 break;
1287 }
1288 case Instruction::GetElementPtr: {
1289 // Analyze all of the subscripts of this getelementptr instruction
1290 // to determine if we can prove known low zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001291 KnownBits LocalKnown(BitWidth);
1292 computeKnownBits(I->getOperand(0), LocalKnown, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001293 unsigned TrailZ = LocalKnown.countMinTrailingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001294
1295 gep_type_iterator GTI = gep_type_begin(I);
1296 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1297 Value *Index = I->getOperand(i);
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001298 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chris Lattner965c7692008-06-02 01:18:21 +00001299 // Handle struct member offset arithmetic.
Matt Arsenault74742a12013-08-19 21:43:16 +00001300
1301 // Handle case when index is vector zeroinitializer
1302 Constant *CIndex = cast<Constant>(Index);
1303 if (CIndex->isZeroValue())
1304 continue;
1305
1306 if (CIndex->getType()->isVectorTy())
1307 Index = CIndex->getSplatValue();
1308
Chris Lattner965c7692008-06-02 01:18:21 +00001309 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001310 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001311 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001312 TrailZ = std::min<unsigned>(TrailZ,
1313 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001314 } else {
1315 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001316 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001317 if (!IndexedTy->isSized()) {
1318 TrailZ = 0;
1319 break;
1320 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001321 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001322 uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
Craig Topperb45eabc2017-04-26 16:39:58 +00001323 LocalKnown.Zero = LocalKnown.One = APInt(GEPOpiBits, 0);
1324 computeKnownBits(Index, LocalKnown, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001325 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001326 unsigned(countTrailingZeros(TypeSize) +
Craig Topper8df66c62017-05-12 17:20:30 +00001327 LocalKnown.countMinTrailingZeros()));
Chris Lattner965c7692008-06-02 01:18:21 +00001328 }
1329 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001330
Craig Topperb45eabc2017-04-26 16:39:58 +00001331 Known.Zero.setLowBits(TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001332 break;
1333 }
1334 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001335 const PHINode *P = cast<PHINode>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001336 // Handle the case of a simple two-predecessor recurrence PHI.
1337 // There's a lot more that could theoretically be done here, but
1338 // this is sufficient to catch some interesting cases.
1339 if (P->getNumIncomingValues() == 2) {
1340 for (unsigned i = 0; i != 2; ++i) {
1341 Value *L = P->getIncomingValue(i);
1342 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001343 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001344 if (!LU)
1345 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001346 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001347 // Check for operations that have the property that if
1348 // both their operands have low zero bits, the result
Artur Pilipenkobc76eca2016-08-22 13:14:07 +00001349 // will have low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001350 if (Opcode == Instruction::Add ||
1351 Opcode == Instruction::Sub ||
1352 Opcode == Instruction::And ||
1353 Opcode == Instruction::Or ||
1354 Opcode == Instruction::Mul) {
1355 Value *LL = LU->getOperand(0);
1356 Value *LR = LU->getOperand(1);
1357 // Find a recurrence.
1358 if (LL == I)
1359 L = LR;
1360 else if (LR == I)
1361 L = LL;
1362 else
1363 break;
1364 // Ok, we have a PHI of the form L op= R. Check for low
1365 // zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001366 computeKnownBits(R, Known2, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001367
1368 // We need to take the minimum number of known bits
Craig Topperb45eabc2017-04-26 16:39:58 +00001369 KnownBits Known3(Known);
1370 computeKnownBits(L, Known3, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001371
Craig Topper8df66c62017-05-12 17:20:30 +00001372 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1373 Known3.countMinTrailingZeros()));
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001374
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001375 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU);
Florian Hahn19f9e322018-08-17 14:39:04 +00001376 if (OverflowOp && Q.IIQ.hasNoSignedWrap(OverflowOp)) {
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001377 // If initial value of recurrence is nonnegative, and we are adding
1378 // a nonnegative number with nsw, the result can only be nonnegative
1379 // or poison value regardless of the number of times we execute the
1380 // add in phi recurrence. If initial value is negative and we are
1381 // adding a negative number with nsw, the result can only be
1382 // negative or poison value. Similar arguments apply to sub and mul.
1383 //
1384 // (add non-negative, non-negative) --> non-negative
1385 // (add negative, negative) --> negative
1386 if (Opcode == Instruction::Add) {
Craig Topperca48af32017-04-29 16:43:11 +00001387 if (Known2.isNonNegative() && Known3.isNonNegative())
1388 Known.makeNonNegative();
1389 else if (Known2.isNegative() && Known3.isNegative())
1390 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001391 }
1392
1393 // (sub nsw non-negative, negative) --> non-negative
1394 // (sub nsw negative, non-negative) --> negative
1395 else if (Opcode == Instruction::Sub && LL == I) {
Craig Topperca48af32017-04-29 16:43:11 +00001396 if (Known2.isNonNegative() && Known3.isNegative())
1397 Known.makeNonNegative();
1398 else if (Known2.isNegative() && Known3.isNonNegative())
1399 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001400 }
1401
1402 // (mul nsw non-negative, non-negative) --> non-negative
Craig Topperca48af32017-04-29 16:43:11 +00001403 else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1404 Known3.isNonNegative())
1405 Known.makeNonNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001406 }
1407
Chris Lattner965c7692008-06-02 01:18:21 +00001408 break;
1409 }
1410 }
1411 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001412
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001413 // Unreachable blocks may have zero-operand PHI nodes.
1414 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001415 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001416
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001417 // Otherwise take the unions of the known bit sets of the operands,
1418 // taking conservative care to avoid excessive recursion.
Craig Topperb45eabc2017-04-26 16:39:58 +00001419 if (Depth < MaxDepth - 1 && !Known.Zero && !Known.One) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001420 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001421 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001422 break;
1423
Craig Topperb45eabc2017-04-26 16:39:58 +00001424 Known.Zero.setAllBits();
1425 Known.One.setAllBits();
Pete Cooper833f34d2015-05-12 20:05:31 +00001426 for (Value *IncValue : P->incoming_values()) {
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001427 // Skip direct self references.
Pete Cooper833f34d2015-05-12 20:05:31 +00001428 if (IncValue == P) continue;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001429
Craig Topperb45eabc2017-04-26 16:39:58 +00001430 Known2 = KnownBits(BitWidth);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001431 // Recurse, but cap the recursion to one level, because we don't
1432 // want to waste time spinning around in loops.
Craig Topperb45eabc2017-04-26 16:39:58 +00001433 computeKnownBits(IncValue, Known2, MaxDepth - 1, Q);
1434 Known.Zero &= Known2.Zero;
1435 Known.One &= Known2.One;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001436 // If all bits have been ruled out, there's no need to check
1437 // more operands.
Craig Topperb45eabc2017-04-26 16:39:58 +00001438 if (!Known.Zero && !Known.One)
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001439 break;
1440 }
1441 }
Chris Lattner965c7692008-06-02 01:18:21 +00001442 break;
1443 }
1444 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001445 case Instruction::Invoke:
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001446 // If range metadata is attached to this call, set known bits from that,
1447 // and then intersect with known bits based on other properties of the
1448 // function.
Florian Hahn19f9e322018-08-17 14:39:04 +00001449 if (MDNode *MD =
1450 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +00001451 computeKnownBitsFromRangeMetadata(*MD, Known);
Pete Cooper35b00d52016-08-13 01:05:32 +00001452 if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001453 computeKnownBits(RV, Known2, Depth + 1, Q);
1454 Known.Zero |= Known2.Zero;
1455 Known.One |= Known2.One;
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001456 }
Pete Cooper35b00d52016-08-13 01:05:32 +00001457 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001458 switch (II->getIntrinsicID()) {
1459 default: break;
Chad Rosier85204292017-01-17 17:23:51 +00001460 case Intrinsic::bitreverse:
Craig Topperb45eabc2017-04-26 16:39:58 +00001461 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1462 Known.Zero |= Known2.Zero.reverseBits();
1463 Known.One |= Known2.One.reverseBits();
Chad Rosier85204292017-01-17 17:23:51 +00001464 break;
Philip Reames675418e2015-10-06 20:20:45 +00001465 case Intrinsic::bswap:
Craig Topperb45eabc2017-04-26 16:39:58 +00001466 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1467 Known.Zero |= Known2.Zero.byteSwap();
1468 Known.One |= Known2.One.byteSwap();
Philip Reames675418e2015-10-06 20:20:45 +00001469 break;
Craig Topper868813f2017-05-08 17:22:34 +00001470 case Intrinsic::ctlz: {
1471 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1472 // If we have a known 1, its position is our upper bound.
1473 unsigned PossibleLZ = Known2.One.countLeadingZeros();
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001474 // If this call is undefined for 0, the result will be less than 2^n.
1475 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
Craig Topper868813f2017-05-08 17:22:34 +00001476 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1477 unsigned LowBits = Log2_32(PossibleLZ)+1;
1478 Known.Zero.setBitsFrom(LowBits);
1479 break;
1480 }
1481 case Intrinsic::cttz: {
1482 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1483 // If we have a known 1, its position is our upper bound.
1484 unsigned PossibleTZ = Known2.One.countTrailingZeros();
1485 // If this call is undefined for 0, the result will be less than 2^n.
1486 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1487 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1488 unsigned LowBits = Log2_32(PossibleTZ)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001489 Known.Zero.setBitsFrom(LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001490 break;
1491 }
1492 case Intrinsic::ctpop: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001493 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001494 // We can bound the space the count needs. Also, bits known to be zero
1495 // can't contribute to the population.
Craig Topper8df66c62017-05-12 17:20:30 +00001496 unsigned BitsPossiblySet = Known2.countMaxPopulation();
Craig Topper66df10f2017-04-14 06:43:34 +00001497 unsigned LowBits = Log2_32(BitsPossiblySet)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001498 Known.Zero.setBitsFrom(LowBits);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001499 // TODO: we could bound KnownOne using the lower bound on the number
1500 // of bits which might be set provided by popcnt KnownOne2.
Chris Lattner965c7692008-06-02 01:18:21 +00001501 break;
1502 }
Nikita Popov687b92c2018-12-02 14:14:11 +00001503 case Intrinsic::fshr:
1504 case Intrinsic::fshl: {
1505 const APInt *SA;
1506 if (!match(I->getOperand(2), m_APInt(SA)))
1507 break;
1508
1509 // Normalize to funnel shift left.
1510 uint64_t ShiftAmt = SA->urem(BitWidth);
1511 if (II->getIntrinsicID() == Intrinsic::fshr)
1512 ShiftAmt = BitWidth - ShiftAmt;
1513
1514 KnownBits Known3(Known);
1515 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1516 computeKnownBits(I->getOperand(1), Known3, Depth + 1, Q);
1517
1518 Known.Zero =
1519 Known2.Zero.shl(ShiftAmt) | Known3.Zero.lshr(BitWidth - ShiftAmt);
1520 Known.One =
1521 Known2.One.shl(ShiftAmt) | Known3.One.lshr(BitWidth - ShiftAmt);
1522 break;
1523 }
Nikita Popoved3ca922019-03-01 20:07:04 +00001524 case Intrinsic::uadd_sat:
1525 case Intrinsic::usub_sat: {
1526 bool IsAdd = II->getIntrinsicID() == Intrinsic::uadd_sat;
1527 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1528 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1529
1530 // Add: Leading ones of either operand are preserved.
1531 // Sub: Leading zeros of LHS and leading ones of RHS are preserved
1532 // as leading zeros in the result.
1533 unsigned LeadingKnown;
1534 if (IsAdd)
1535 LeadingKnown = std::max(Known.countMinLeadingOnes(),
1536 Known2.countMinLeadingOnes());
1537 else
1538 LeadingKnown = std::max(Known.countMinLeadingZeros(),
1539 Known2.countMinLeadingOnes());
1540
1541 Known = KnownBits::computeForAddSub(
1542 IsAdd, /* NSW */ false, Known, Known2);
1543
1544 // We select between the operation result and all-ones/zero
1545 // respectively, so we can preserve known ones/zeros.
1546 if (IsAdd) {
1547 Known.One.setHighBits(LeadingKnown);
1548 Known.Zero.clearAllBits();
1549 } else {
1550 Known.Zero.setHighBits(LeadingKnown);
1551 Known.One.clearAllBits();
1552 }
1553 break;
1554 }
Chad Rosierb3628842011-05-26 23:13:19 +00001555 case Intrinsic::x86_sse42_crc32_64_64:
Craig Topperb45eabc2017-04-26 16:39:58 +00001556 Known.Zero.setBitsFrom(32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001557 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001558 }
1559 }
1560 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00001561 case Instruction::ExtractElement:
1562 // Look through extract element. At the moment we keep this simple and skip
1563 // tracking the specific element. But at least we might find information
1564 // valid for all elements of the vector (for example if vector is sign
1565 // extended, shifted, etc).
Craig Topperb45eabc2017-04-26 16:39:58 +00001566 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Bjorn Pettersson39616032016-10-06 09:56:21 +00001567 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001568 case Instruction::ExtractValue:
1569 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001570 const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001571 if (EVI->getNumIndices() != 1) break;
1572 if (EVI->getIndices()[0] == 0) {
1573 switch (II->getIntrinsicID()) {
1574 default: break;
1575 case Intrinsic::uadd_with_overflow:
1576 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001577 computeKnownBitsAddSub(true, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001578 II->getArgOperand(1), false, Known, Known2,
1579 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001580 break;
1581 case Intrinsic::usub_with_overflow:
1582 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001583 computeKnownBitsAddSub(false, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001584 II->getArgOperand(1), false, Known, Known2,
1585 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001586 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001587 case Intrinsic::umul_with_overflow:
1588 case Intrinsic::smul_with_overflow:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001589 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
Craig Topperb45eabc2017-04-26 16:39:58 +00001590 Known, Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001591 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001592 }
1593 }
1594 }
Chris Lattner965c7692008-06-02 01:18:21 +00001595 }
Jingyue Wu12b0c282015-06-15 05:46:29 +00001596}
1597
1598/// Determine which bits of V are known to be either zero or one and return
Craig Topper6e11a052017-05-08 16:22:48 +00001599/// them.
1600KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1601 KnownBits Known(getBitWidth(V->getType(), Q.DL));
1602 computeKnownBits(V, Known, Depth, Q);
1603 return Known;
1604}
1605
1606/// Determine which bits of V are known to be either zero or one and return
Craig Topperb45eabc2017-04-26 16:39:58 +00001607/// them in the Known bit set.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001608///
1609/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1610/// we cannot optimize based on the assumption that it is zero without changing
1611/// it to be an explicit zero. If we don't change it to zero, other code could
1612/// optimized based on the contradictory assumption that it is non-zero.
1613/// Because instcombine aggressively folds operations with undef args anyway,
1614/// this won't lose us code quality.
1615///
1616/// This function is defined on values with integer type, values with pointer
1617/// type, and vectors of integers. In the case
1618/// where V is a vector, known zero, and known one values are the
1619/// same width as the vector element, and the bit is set only if it is true
1620/// for all of the elements in the vector.
Craig Topperb45eabc2017-04-26 16:39:58 +00001621void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
1622 const Query &Q) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001623 assert(V && "No Value?");
1624 assert(Depth <= MaxDepth && "Limit Search Depth");
Craig Topperb45eabc2017-04-26 16:39:58 +00001625 unsigned BitWidth = Known.getBitWidth();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001626
Craig Topperfde47232017-07-09 07:04:03 +00001627 assert((V->getType()->isIntOrIntVectorTy(BitWidth) ||
Craig Topper95d23472017-07-09 07:04:00 +00001628 V->getType()->isPtrOrPtrVectorTy()) &&
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001629 "Not integer or pointer type!");
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001630
1631 Type *ScalarTy = V->getType()->getScalarType();
1632 unsigned ExpectedWidth = ScalarTy->isPointerTy() ?
1633 Q.DL.getIndexTypeSizeInBits(ScalarTy) : Q.DL.getTypeSizeInBits(ScalarTy);
1634 assert(ExpectedWidth == BitWidth && "V and Known should have same BitWidth");
Craig Topperd73c6b42017-03-23 07:06:39 +00001635 (void)BitWidth;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001636 (void)ExpectedWidth;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001637
Sanjay Patelc96f6db2016-09-16 21:20:36 +00001638 const APInt *C;
1639 if (match(V, m_APInt(C))) {
1640 // We know all of the bits for a scalar constant or a splat vector constant!
Craig Topperb45eabc2017-04-26 16:39:58 +00001641 Known.One = *C;
1642 Known.Zero = ~Known.One;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001643 return;
1644 }
1645 // Null and aggregate-zero are all-zeros.
Sanjay Patele8dc0902016-05-23 17:57:54 +00001646 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001647 Known.setAllZero();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001648 return;
1649 }
1650 // Handle a constant vector by taking the intersection of the known bits of
David Majnemer3918cdd2016-05-04 06:13:33 +00001651 // each element.
Pete Cooper35b00d52016-08-13 01:05:32 +00001652 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001653 // We know that CDS must be a vector of integers. Take the intersection of
1654 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001655 Known.Zero.setAllBits(); Known.One.setAllBits();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001656 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Craig Topperb98ee582017-10-21 16:35:39 +00001657 APInt Elt = CDS->getElementAsAPInt(i);
Craig Topperb45eabc2017-04-26 16:39:58 +00001658 Known.Zero &= ~Elt;
1659 Known.One &= Elt;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001660 }
1661 return;
1662 }
1663
Pete Cooper35b00d52016-08-13 01:05:32 +00001664 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
David Majnemer3918cdd2016-05-04 06:13:33 +00001665 // We know that CV must be a vector of integers. Take the intersection of
1666 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001667 Known.Zero.setAllBits(); Known.One.setAllBits();
David Majnemer3918cdd2016-05-04 06:13:33 +00001668 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1669 Constant *Element = CV->getAggregateElement(i);
1670 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1671 if (!ElementCI) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001672 Known.resetAll();
David Majnemer3918cdd2016-05-04 06:13:33 +00001673 return;
1674 }
Craig Topperb98ee582017-10-21 16:35:39 +00001675 const APInt &Elt = ElementCI->getValue();
Craig Topperb45eabc2017-04-26 16:39:58 +00001676 Known.Zero &= ~Elt;
1677 Known.One &= Elt;
David Majnemer3918cdd2016-05-04 06:13:33 +00001678 }
1679 return;
1680 }
1681
Jingyue Wu12b0c282015-06-15 05:46:29 +00001682 // Start out not knowing anything.
Craig Topperf0aeee02017-05-05 17:36:09 +00001683 Known.resetAll();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001684
Duncan P. N. Exon Smithb1b208a2016-09-24 20:42:02 +00001685 // We can't imply anything about undefs.
1686 if (isa<UndefValue>(V))
1687 return;
1688
1689 // There's no point in looking through other users of ConstantData for
1690 // assumptions. Confirm that we've handled them all.
1691 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1692
Jingyue Wu12b0c282015-06-15 05:46:29 +00001693 // Limit search depth.
1694 // All recursive calls that increase depth must come after this.
1695 if (Depth == MaxDepth)
1696 return;
1697
1698 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1699 // the bits of its aliasee.
Pete Cooper35b00d52016-08-13 01:05:32 +00001700 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001701 if (!GA->isInterposable())
Craig Topperb45eabc2017-04-26 16:39:58 +00001702 computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001703 return;
1704 }
1705
Pete Cooper35b00d52016-08-13 01:05:32 +00001706 if (const Operator *I = dyn_cast<Operator>(V))
Craig Topperb45eabc2017-04-26 16:39:58 +00001707 computeKnownBitsFromOperator(I, Known, Depth, Q);
Sanjay Patela67559c2015-09-25 20:12:43 +00001708
Craig Topperb45eabc2017-04-26 16:39:58 +00001709 // Aligned pointers have trailing zeros - refine Known.Zero set
Artur Pilipenko029d8532015-09-30 11:55:45 +00001710 if (V->getType()->isPointerTy()) {
Artur Pilipenkoae51afc2016-02-24 12:25:10 +00001711 unsigned Align = V->getPointerAlignment(Q.DL);
Artur Pilipenko029d8532015-09-30 11:55:45 +00001712 if (Align)
Craig Topperb45eabc2017-04-26 16:39:58 +00001713 Known.Zero.setLowBits(countTrailingZeros(Align));
Artur Pilipenko029d8532015-09-30 11:55:45 +00001714 }
1715
Craig Topperb45eabc2017-04-26 16:39:58 +00001716 // computeKnownBitsFromAssume strictly refines Known.
1717 // Therefore, we run them after computeKnownBitsFromOperator.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001718
1719 // Check whether a nearby assume intrinsic can determine some known bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001720 computeKnownBitsFromAssume(V, Known, Depth, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001721
Craig Topperb45eabc2017-04-26 16:39:58 +00001722 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001723}
1724
Sanjay Patelaee84212014-11-04 16:27:42 +00001725/// Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001726/// bit set when defined. For vectors return true if every element is known to
Sanjay Patelaee84212014-11-04 16:27:42 +00001727/// be a power of two when defined. Supports values with integer or pointer
Duncan Sandsd3951082011-01-25 09:38:29 +00001728/// types and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001729bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001730 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00001731 assert(Depth <= MaxDepth && "Limit Search Depth");
1732
Simon Pilgrim9f2ae7e2018-02-06 18:39:23 +00001733 // Attempt to match against constants.
1734 if (OrZero && match(V, m_Power2OrZero()))
1735 return true;
1736 if (match(V, m_Power2()))
1737 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001738
1739 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1740 // it is shifted off the end then the result is undefined.
1741 if (match(V, m_Shl(m_One(), m_Value())))
1742 return true;
1743
Craig Topperbcfd2d12017-04-20 16:56:25 +00001744 // (signmask) >>l X is clearly a power of two if the one is not shifted off
1745 // the bottom. If it is shifted off the bottom then the result is undefined.
1746 if (match(V, m_LShr(m_SignMask(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001747 return true;
1748
1749 // The remaining tests are all recursive, so bail out if we hit the limit.
1750 if (Depth++ == MaxDepth)
1751 return false;
1752
Craig Topper9f008862014-04-15 04:59:12 +00001753 Value *X = nullptr, *Y = nullptr;
Sanjay Patel41160c22015-12-30 22:40:52 +00001754 // A shift left or a logical shift right of a power of two is a power of two
1755 // or zero.
Duncan Sands985ba632011-10-28 18:30:05 +00001756 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
Sanjay Patel41160c22015-12-30 22:40:52 +00001757 match(V, m_LShr(m_Value(X), m_Value()))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001758 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
Duncan Sands985ba632011-10-28 18:30:05 +00001759
Pete Cooper35b00d52016-08-13 01:05:32 +00001760 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001761 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001762
Pete Cooper35b00d52016-08-13 01:05:32 +00001763 if (const SelectInst *SI = dyn_cast<SelectInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001764 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1765 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
Duncan Sandsba286d72011-10-26 20:55:21 +00001766
Duncan Sandsba286d72011-10-26 20:55:21 +00001767 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1768 // A power of two and'd with anything is a power of two or zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001769 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1770 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
Duncan Sandsba286d72011-10-26 20:55:21 +00001771 return true;
1772 // X & (-X) is always a power of two or zero.
1773 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1774 return true;
1775 return false;
1776 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001777
David Majnemerb7d54092013-07-30 21:01:36 +00001778 // Adding a power-of-two or zero to the same power-of-two or zero yields
1779 // either the original power-of-two, a larger power-of-two or zero.
1780 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001781 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
Florian Hahn19f9e322018-08-17 14:39:04 +00001782 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
1783 Q.IIQ.hasNoSignedWrap(VOBO)) {
David Majnemerb7d54092013-07-30 21:01:36 +00001784 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1785 match(X, m_And(m_Value(), m_Specific(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001786 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001787 return true;
1788 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1789 match(Y, m_And(m_Value(), m_Specific(X))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001790 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001791 return true;
1792
1793 unsigned BitWidth = V->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00001794 KnownBits LHSBits(BitWidth);
1795 computeKnownBits(X, LHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001796
Craig Topperb45eabc2017-04-26 16:39:58 +00001797 KnownBits RHSBits(BitWidth);
1798 computeKnownBits(Y, RHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001799 // If i8 V is a power of two or zero:
1800 // ZeroBits: 1 1 1 0 1 1 1 1
1801 // ~ZeroBits: 0 0 0 1 0 0 0 0
Craig Topperb45eabc2017-04-26 16:39:58 +00001802 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
David Majnemerb7d54092013-07-30 21:01:36 +00001803 // If OrZero isn't set, we cannot give back a zero result.
1804 // Make sure either the LHS or RHS has a bit set.
Craig Topperb45eabc2017-04-26 16:39:58 +00001805 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
David Majnemerb7d54092013-07-30 21:01:36 +00001806 return true;
1807 }
1808 }
David Majnemerbeab5672013-05-18 19:30:37 +00001809
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001810 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001811 // is a power of two only if the first operand is a power of two and not
1812 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001813 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1814 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001815 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001816 Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001817 }
1818
Duncan Sandsd3951082011-01-25 09:38:29 +00001819 return false;
1820}
1821
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001822/// Test whether a GEP's result is known to be non-null.
Chandler Carruth80d3e562012-12-07 02:08:58 +00001823///
1824/// Uses properties inherent in a GEP to try to determine whether it is known
1825/// to be non-null.
1826///
1827/// Currently this routine does not support vector GEPs.
Pete Cooper35b00d52016-08-13 01:05:32 +00001828static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001829 const Query &Q) {
Manoj Gupta77eeac32018-07-09 22:27:23 +00001830 const Function *F = nullptr;
1831 if (const Instruction *I = dyn_cast<Instruction>(GEP))
1832 F = I->getFunction();
1833
1834 if (!GEP->isInBounds() ||
1835 NullPointerIsDefined(F, GEP->getPointerAddressSpace()))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001836 return false;
1837
1838 // FIXME: Support vector-GEPs.
1839 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1840
1841 // If the base pointer is non-null, we cannot walk to a null address with an
1842 // inbounds GEP in address space zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001843 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001844 return true;
1845
Chandler Carruth80d3e562012-12-07 02:08:58 +00001846 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1847 // If so, then the GEP cannot produce a null pointer, as doing so would
1848 // inherently violate the inbounds contract within address space zero.
1849 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1850 GTI != GTE; ++GTI) {
1851 // Struct types are easy -- they must always be indexed by a constant.
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001852 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001853 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1854 unsigned ElementIdx = OpC->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001855 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chandler Carruth80d3e562012-12-07 02:08:58 +00001856 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1857 if (ElementOffset > 0)
1858 return true;
1859 continue;
1860 }
1861
1862 // If we have a zero-sized type, the index doesn't matter. Keep looping.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001863 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
Chandler Carruth80d3e562012-12-07 02:08:58 +00001864 continue;
1865
1866 // Fast path the constant operand case both for efficiency and so we don't
1867 // increment Depth when just zipping down an all-constant GEP.
1868 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1869 if (!OpC->isZero())
1870 return true;
1871 continue;
1872 }
1873
1874 // We post-increment Depth here because while isKnownNonZero increments it
1875 // as well, when we pop back up that increment won't persist. We don't want
1876 // to recurse 10k times just because we have 10k GEP operands. We don't
1877 // bail completely out because we want to handle constant GEPs regardless
1878 // of depth.
1879 if (Depth++ >= MaxDepth)
1880 continue;
1881
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001882 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001883 return true;
1884 }
1885
1886 return false;
1887}
1888
Nuno Lopes404f1062017-09-09 18:23:11 +00001889static bool isKnownNonNullFromDominatingCondition(const Value *V,
1890 const Instruction *CtxI,
1891 const DominatorTree *DT) {
1892 assert(V->getType()->isPointerTy() && "V must be pointer type");
1893 assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull");
1894
1895 if (!CtxI || !DT)
1896 return false;
1897
1898 unsigned NumUsesExplored = 0;
1899 for (auto *U : V->users()) {
1900 // Avoid massive lists
1901 if (NumUsesExplored >= DomConditionsMaxUses)
1902 break;
1903 NumUsesExplored++;
1904
1905 // If the value is used as an argument to a call or invoke, then argument
1906 // attributes may provide an answer about null-ness.
1907 if (auto CS = ImmutableCallSite(U))
1908 if (auto *CalledFunc = CS.getCalledFunction())
1909 for (const Argument &Arg : CalledFunc->args())
1910 if (CS.getArgOperand(Arg.getArgNo()) == V &&
1911 Arg.hasNonNullAttr() && DT->dominates(CS.getInstruction(), CtxI))
1912 return true;
1913
1914 // Consider only compare instructions uniquely controlling a branch
1915 CmpInst::Predicate Pred;
1916 if (!match(const_cast<User *>(U),
1917 m_c_ICmp(Pred, m_Specific(V), m_Zero())) ||
1918 (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE))
1919 continue;
1920
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001921 SmallVector<const User *, 4> WorkList;
1922 SmallPtrSet<const User *, 4> Visited;
Nuno Lopes404f1062017-09-09 18:23:11 +00001923 for (auto *CmpU : U->users()) {
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001924 assert(WorkList.empty() && "Should be!");
1925 if (Visited.insert(CmpU).second)
1926 WorkList.push_back(CmpU);
Nuno Lopes404f1062017-09-09 18:23:11 +00001927
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001928 while (!WorkList.empty()) {
1929 auto *Curr = WorkList.pop_back_val();
1930
1931 // If a user is an AND, add all its users to the work list. We only
1932 // propagate "pred != null" condition through AND because it is only
1933 // correct to assume that all conditions of AND are met in true branch.
1934 // TODO: Support similar logic of OR and EQ predicate?
1935 if (Pred == ICmpInst::ICMP_NE)
1936 if (auto *BO = dyn_cast<BinaryOperator>(Curr))
1937 if (BO->getOpcode() == Instruction::And) {
1938 for (auto *BOU : BO->users())
1939 if (Visited.insert(BOU).second)
1940 WorkList.push_back(BOU);
1941 continue;
1942 }
1943
1944 if (const BranchInst *BI = dyn_cast<BranchInst>(Curr)) {
1945 assert(BI->isConditional() && "uses a comparison!");
1946
1947 BasicBlock *NonNullSuccessor =
1948 BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0);
1949 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
1950 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
1951 return true;
Max Kazantsev3c284bd2018-08-30 03:39:16 +00001952 } else if (Pred == ICmpInst::ICMP_NE && isGuard(Curr) &&
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001953 DT->dominates(cast<Instruction>(Curr), CtxI)) {
Nuno Lopes404f1062017-09-09 18:23:11 +00001954 return true;
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001955 }
Nuno Lopes404f1062017-09-09 18:23:11 +00001956 }
1957 }
1958 }
1959
1960 return false;
1961}
1962
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001963/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1964/// ensure that the value it's attached to is never Value? 'RangeType' is
1965/// is the type of the value described by the range.
Pete Cooper35b00d52016-08-13 01:05:32 +00001966static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001967 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1968 assert(NumRanges >= 1);
1969 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001970 ConstantInt *Lower =
1971 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1972 ConstantInt *Upper =
1973 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001974 ConstantRange Range(Lower->getValue(), Upper->getValue());
1975 if (Range.contains(Value))
1976 return false;
1977 }
1978 return true;
1979}
1980
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001981/// Return true if the given value is known to be non-zero when defined. For
1982/// vectors, return true if every element is known to be non-zero when
1983/// defined. For pointers, if the context instruction and dominator tree are
1984/// specified, perform context-sensitive analysis and return true if the
1985/// pointer couldn't possibly be null at the specified instruction.
1986/// Supports values with integer or pointer type and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001987bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) {
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001988 if (auto *C = dyn_cast<Constant>(V)) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001989 if (C->isNullValue())
1990 return false;
1991 if (isa<ConstantInt>(C))
1992 // Must be non-zero due to null test above.
1993 return true;
Sanjay Patel23019d12016-05-24 14:18:49 +00001994
1995 // For constant vectors, check that all elements are undefined or known
1996 // non-zero to determine that the whole vector is known non-zero.
1997 if (auto *VecTy = dyn_cast<VectorType>(C->getType())) {
1998 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
1999 Constant *Elt = C->getAggregateElement(i);
2000 if (!Elt || Elt->isNullValue())
2001 return false;
2002 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
2003 return false;
2004 }
2005 return true;
2006 }
2007
Nuno Lopes404f1062017-09-09 18:23:11 +00002008 // A global variable in address space 0 is non null unless extern weak
2009 // or an absolute symbol reference. Other address spaces may have null as a
2010 // valid address for a global, so we can't assume anything.
2011 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2012 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
2013 GV->getType()->getAddressSpace() == 0)
2014 return true;
2015 } else
2016 return false;
Duncan Sandsd3951082011-01-25 09:38:29 +00002017 }
2018
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00002019 if (auto *I = dyn_cast<Instruction>(V)) {
Florian Hahn19f9e322018-08-17 14:39:04 +00002020 if (MDNode *Ranges = Q.IIQ.getMetadata(I, LLVMContext::MD_range)) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00002021 // If the possible ranges don't contain zero, then the value is
2022 // definitely non-zero.
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00002023 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00002024 const APInt ZeroValue(Ty->getBitWidth(), 0);
2025 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
2026 return true;
2027 }
2028 }
2029 }
2030
Karl-Johan Karlssonebaaa2d2018-05-30 15:56:46 +00002031 // Some of the tests below are recursive, so bail out if we hit the limit.
2032 if (Depth++ >= MaxDepth)
2033 return false;
2034
Nuno Lopes404f1062017-09-09 18:23:11 +00002035 // Check for pointer simplifications.
2036 if (V->getType()->isPointerTy()) {
2037 // Alloca never returns null, malloc might.
2038 if (isa<AllocaInst>(V) && Q.DL.getAllocaAddrSpace() == 0)
2039 return true;
2040
2041 // A byval, inalloca, or nonnull argument is never null.
2042 if (const Argument *A = dyn_cast<Argument>(V))
2043 if (A->hasByValOrInAllocaAttr() || A->hasNonNullAttr())
2044 return true;
2045
2046 // A Load tagged with nonnull metadata is never null.
2047 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
Florian Hahn19f9e322018-08-17 14:39:04 +00002048 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull))
Nuno Lopes404f1062017-09-09 18:23:11 +00002049 return true;
2050
Chandler Carruth363ac682019-01-07 05:42:51 +00002051 if (const auto *Call = dyn_cast<CallBase>(V)) {
2052 if (Call->isReturnNonNull())
Nuno Lopes404f1062017-09-09 18:23:11 +00002053 return true;
Chandler Carruth363ac682019-01-07 05:42:51 +00002054 if (const auto *RP = getArgumentAliasingToReturnedPointer(Call))
Karl-Johan Karlssonebaaa2d2018-05-30 15:56:46 +00002055 return isKnownNonZero(RP, Depth, Q);
Piotr Padlewski5642a422018-05-18 23:54:33 +00002056 }
Nuno Lopes404f1062017-09-09 18:23:11 +00002057 }
2058
Duncan Sandsd3951082011-01-25 09:38:29 +00002059
Nuno Lopes404f1062017-09-09 18:23:11 +00002060 // Check for recursive pointer simplifications.
Chandler Carruth80d3e562012-12-07 02:08:58 +00002061 if (V->getType()->isPointerTy()) {
Nuno Lopes404f1062017-09-09 18:23:11 +00002062 if (isKnownNonNullFromDominatingCondition(V, Q.CxtI, Q.DT))
Sanjoy Das6082c1a2016-05-07 02:08:15 +00002063 return true;
Nuno Lopes404f1062017-09-09 18:23:11 +00002064
Johannes Doerfert00102c72019-01-26 23:40:35 +00002065 // Look through bitcast operations, GEPs, and int2ptr instructions as they
2066 // do not alter the value, or at least not the nullness property of the
2067 // value, e.g., int2ptr is allowed to zero/sign extend the value.
2068 //
2069 // Note that we have to take special care to avoid looking through
2070 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
2071 // as casts that can alter the value, e.g., AddrSpaceCasts.
Pete Cooper35b00d52016-08-13 01:05:32 +00002072 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002073 if (isGEPKnownNonNull(GEP, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00002074 return true;
Johannes Doerfert00102c72019-01-26 23:40:35 +00002075
2076 if (auto *BCO = dyn_cast<BitCastOperator>(V))
2077 return isKnownNonZero(BCO->getOperand(0), Depth, Q);
2078
2079 if (auto *I2P = dyn_cast<IntToPtrInst>(V))
2080 if (Q.DL.getTypeSizeInBits(I2P->getSrcTy()) <=
2081 Q.DL.getTypeSizeInBits(I2P->getDestTy()))
2082 return isKnownNonZero(I2P->getOperand(0), Depth, Q);
Chandler Carruth80d3e562012-12-07 02:08:58 +00002083 }
2084
Johannes Doerfert00102c72019-01-26 23:40:35 +00002085 // Similar to int2ptr above, we can look through ptr2int here if the cast
2086 // is a no-op or an extend and not a truncate.
2087 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
2088 if (Q.DL.getTypeSizeInBits(P2I->getSrcTy()) <=
2089 Q.DL.getTypeSizeInBits(P2I->getDestTy()))
2090 return isKnownNonZero(P2I->getOperand(0), Depth, Q);
2091
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002092 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00002093
2094 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00002095 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00002096 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002097 return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002098
2099 // ext X != 0 if X != 0.
2100 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002101 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002102
Duncan Sands2e9e4f12011-01-29 13:27:00 +00002103 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00002104 // if the lowest bit is shifted off the end.
Craig Topper6b3940a2017-05-03 22:25:19 +00002105 if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002106 // shl nuw can't remove any non-zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002107 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Florian Hahn19f9e322018-08-17 14:39:04 +00002108 if (Q.IIQ.hasNoUnsignedWrap(BO))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002109 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002110
Craig Topperb45eabc2017-04-26 16:39:58 +00002111 KnownBits Known(BitWidth);
2112 computeKnownBits(X, Known, Depth, Q);
2113 if (Known.One[0])
Duncan Sandsd3951082011-01-25 09:38:29 +00002114 return true;
2115 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00002116 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00002117 // defined if the sign bit is shifted off the end.
2118 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002119 // shr exact can only shift out zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002120 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002121 if (BO->isExact())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002122 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002123
Craig Topper6e11a052017-05-08 16:22:48 +00002124 KnownBits Known = computeKnownBits(X, Depth, Q);
2125 if (Known.isNegative())
Duncan Sandsd3951082011-01-25 09:38:29 +00002126 return true;
James Molloyb6be1eb2015-09-24 16:06:32 +00002127
2128 // If the shifter operand is a constant, and all of the bits shifted
2129 // out are known to be zero, and X is known non-zero then at least one
2130 // non-zero bit must remain.
2131 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
James Molloyb6be1eb2015-09-24 16:06:32 +00002132 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
2133 // Is there a known one in the portion not shifted out?
Craig Topper8df66c62017-05-12 17:20:30 +00002134 if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
James Molloyb6be1eb2015-09-24 16:06:32 +00002135 return true;
2136 // Are all the bits to be shifted out known zero?
NAKAMURA Takumi76bab1f2017-07-11 02:31:51 +00002137 if (Known.countMinTrailingZeros() >= ShiftVal)
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002138 return isKnownNonZero(X, Depth, Q);
James Molloyb6be1eb2015-09-24 16:06:32 +00002139 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002140 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002141 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00002142 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002143 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002144 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002145 // X + Y.
2146 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Craig Topper6e11a052017-05-08 16:22:48 +00002147 KnownBits XKnown = computeKnownBits(X, Depth, Q);
2148 KnownBits YKnown = computeKnownBits(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002149
2150 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00002151 // zero unless both X and Y are zero.
Craig Topper6e11a052017-05-08 16:22:48 +00002152 if (XKnown.isNonNegative() && YKnown.isNonNegative())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002153 if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00002154 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00002155
2156 // If X and Y are both negative (as signed values) then their sum is not
2157 // zero unless both X and Y equal INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002158 if (XKnown.isNegative() && YKnown.isNegative()) {
Duncan Sandsd3951082011-01-25 09:38:29 +00002159 APInt Mask = APInt::getSignedMaxValue(BitWidth);
2160 // The sign bit of X is set. If some other bit is set then X is not equal
2161 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002162 if (XKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00002163 return true;
2164 // The sign bit of Y is set. If some other bit is set then Y is not equal
2165 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002166 if (YKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00002167 return true;
2168 }
2169
2170 // The sum of a non-negative number and a power of two is not zero.
Craig Topper6e11a052017-05-08 16:22:48 +00002171 if (XKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002172 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002173 return true;
Craig Topper6e11a052017-05-08 16:22:48 +00002174 if (YKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002175 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002176 return true;
2177 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00002178 // X * Y.
2179 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00002180 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Duncan Sands7cb61e52011-10-27 19:16:21 +00002181 // If X and Y are non-zero then so is X * Y as long as the multiplication
2182 // does not overflow.
Florian Hahn19f9e322018-08-17 14:39:04 +00002183 if ((Q.IIQ.hasNoSignedWrap(BO) || Q.IIQ.hasNoUnsignedWrap(BO)) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002184 isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00002185 return true;
2186 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002187 // (C ? X : Y) != 0 if X != 0 and Y != 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00002188 else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002189 if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
2190 isKnownNonZero(SI->getFalseValue(), Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002191 return true;
2192 }
James Molloy897048b2015-09-29 14:08:45 +00002193 // PHI
Pete Cooper35b00d52016-08-13 01:05:32 +00002194 else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
James Molloy897048b2015-09-29 14:08:45 +00002195 // Try and detect a recurrence that monotonically increases from a
2196 // starting value, as these are common as induction variables.
2197 if (PN->getNumIncomingValues() == 2) {
2198 Value *Start = PN->getIncomingValue(0);
2199 Value *Induction = PN->getIncomingValue(1);
2200 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
2201 std::swap(Start, Induction);
2202 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
2203 if (!C->isZero() && !C->isNegative()) {
2204 ConstantInt *X;
Florian Hahn19f9e322018-08-17 14:39:04 +00002205 if (Q.IIQ.UseInstrInfo &&
2206 (match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
James Molloy897048b2015-09-29 14:08:45 +00002207 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
2208 !X->isNegative())
2209 return true;
2210 }
2211 }
2212 }
Jun Bum Limca832662016-02-01 17:03:07 +00002213 // Check if all incoming values are non-zero constant.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002214 bool AllNonZeroConstants = llvm::all_of(PN->operands(), [](Value *V) {
Craig Topper79ab6432017-07-06 18:39:47 +00002215 return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZero();
Jun Bum Limca832662016-02-01 17:03:07 +00002216 });
2217 if (AllNonZeroConstants)
2218 return true;
James Molloy897048b2015-09-29 14:08:45 +00002219 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002220
Craig Topperb45eabc2017-04-26 16:39:58 +00002221 KnownBits Known(BitWidth);
2222 computeKnownBits(V, Known, Depth, Q);
2223 return Known.One != 0;
Duncan Sandsd3951082011-01-25 09:38:29 +00002224}
2225
James Molloy1d88d6f2015-10-22 13:18:42 +00002226/// Return true if V2 == V1 + X, where X is known non-zero.
Pete Cooper35b00d52016-08-13 01:05:32 +00002227static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) {
2228 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
James Molloy1d88d6f2015-10-22 13:18:42 +00002229 if (!BO || BO->getOpcode() != Instruction::Add)
2230 return false;
2231 Value *Op = nullptr;
2232 if (V2 == BO->getOperand(0))
2233 Op = BO->getOperand(1);
2234 else if (V2 == BO->getOperand(1))
2235 Op = BO->getOperand(0);
2236 else
2237 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002238 return isKnownNonZero(Op, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002239}
2240
2241/// Return true if it is known that V1 != V2.
Pete Cooper35b00d52016-08-13 01:05:32 +00002242static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) {
Craig Topper3002d5b2017-06-06 07:13:15 +00002243 if (V1 == V2)
James Molloy1d88d6f2015-10-22 13:18:42 +00002244 return false;
2245 if (V1->getType() != V2->getType())
2246 // We can't look through casts yet.
2247 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002248 if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
James Molloy1d88d6f2015-10-22 13:18:42 +00002249 return true;
2250
Craig Topper3002d5b2017-06-06 07:13:15 +00002251 if (V1->getType()->isIntOrIntVectorTy()) {
James Molloy1d88d6f2015-10-22 13:18:42 +00002252 // Are any known bits in V1 contradictory to known bits in V2? If V1
2253 // has a known zero where V2 has a known one, they must not be equal.
Craig Topper8e662f72017-06-06 07:13:11 +00002254 KnownBits Known1 = computeKnownBits(V1, 0, Q);
2255 KnownBits Known2 = computeKnownBits(V2, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002256
Craig Topper8365df82017-06-06 07:13:09 +00002257 if (Known1.Zero.intersects(Known2.One) ||
2258 Known2.Zero.intersects(Known1.One))
James Molloy1d88d6f2015-10-22 13:18:42 +00002259 return true;
2260 }
2261 return false;
2262}
2263
Sanjay Patelaee84212014-11-04 16:27:42 +00002264/// Return true if 'V & Mask' is known to be zero. We use this predicate to
2265/// simplify operations downstream. Mask is known to be zero for bits that V
2266/// cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00002267///
2268/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002269/// type, and vectors of integers. In the case
Chris Lattner4bc28252009-09-08 00:06:16 +00002270/// where V is a vector, the mask, known zero, and known one values are the
2271/// same width as the vector element, and the bit is set only if it is true
2272/// for all of the elements in the vector.
Pete Cooper35b00d52016-08-13 01:05:32 +00002273bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002274 const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002275 KnownBits Known(Mask.getBitWidth());
2276 computeKnownBits(V, Known, Depth, Q);
2277 return Mask.isSubsetOf(Known.Zero);
Chris Lattner965c7692008-06-02 01:18:21 +00002278}
2279
Craig Topperbec15b62018-08-22 23:27:50 +00002280// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
2281// Returns the input and lower/upper bounds.
2282static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
2283 const APInt *&CLow, const APInt *&CHigh) {
Craig Topper15f86922018-08-23 17:15:02 +00002284 assert(isa<Operator>(Select) &&
2285 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
Craig Topperdfa176e2018-08-23 17:45:53 +00002286 "Input should be a Select!");
Craig Topperbec15b62018-08-22 23:27:50 +00002287
2288 const Value *LHS, *RHS, *LHS2, *RHS2;
2289 SelectPatternFlavor SPF = matchSelectPattern(Select, LHS, RHS).Flavor;
2290 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
2291 return false;
2292
2293 if (!match(RHS, m_APInt(CLow)))
2294 return false;
2295
2296 SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor;
2297 if (getInverseMinMaxFlavor(SPF) != SPF2)
2298 return false;
2299
2300 if (!match(RHS2, m_APInt(CHigh)))
2301 return false;
2302
2303 if (SPF == SPF_SMIN)
2304 std::swap(CLow, CHigh);
2305
2306 In = LHS2;
2307 return CLow->sle(*CHigh);
2308}
2309
Sanjay Patela06d9892016-06-22 19:20:59 +00002310/// For vector constants, loop over the elements and find the constant with the
2311/// minimum number of sign bits. Return 0 if the value is not a vector constant
2312/// or if any element was not analyzed; otherwise, return the count for the
2313/// element with the minimum number of sign bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002314static unsigned computeNumSignBitsVectorConstant(const Value *V,
2315 unsigned TyBits) {
2316 const auto *CV = dyn_cast<Constant>(V);
Sanjay Patela06d9892016-06-22 19:20:59 +00002317 if (!CV || !CV->getType()->isVectorTy())
2318 return 0;
Chris Lattner965c7692008-06-02 01:18:21 +00002319
Sanjay Patela06d9892016-06-22 19:20:59 +00002320 unsigned MinSignBits = TyBits;
2321 unsigned NumElts = CV->getType()->getVectorNumElements();
2322 for (unsigned i = 0; i != NumElts; ++i) {
2323 // If we find a non-ConstantInt, bail out.
2324 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
2325 if (!Elt)
2326 return 0;
2327
Craig Topper8e8b6ef2017-10-21 16:35:41 +00002328 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
Sanjay Patela06d9892016-06-22 19:20:59 +00002329 }
2330
2331 return MinSignBits;
2332}
Chris Lattner965c7692008-06-02 01:18:21 +00002333
Sanjoy Das39a684d2017-02-25 20:30:45 +00002334static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2335 const Query &Q);
2336
2337static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
2338 const Query &Q) {
2339 unsigned Result = ComputeNumSignBitsImpl(V, Depth, Q);
2340 assert(Result > 0 && "At least one sign bit needs to be present!");
2341 return Result;
2342}
2343
Sanjay Patelaee84212014-11-04 16:27:42 +00002344/// Return the number of times the sign bit of the register is replicated into
2345/// the other bits. We know that at least 1 bit is always equal to the sign bit
2346/// (itself), but other cases can give us information. For example, immediately
2347/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
Sanjay Patela06d9892016-06-22 19:20:59 +00002348/// other, so we return 3. For vectors, return the number of sign bits for the
Vedant Kumard3196742018-02-28 19:08:52 +00002349/// vector element with the minimum number of known sign bits.
Sanjoy Das39a684d2017-02-25 20:30:45 +00002350static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2351 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00002352 assert(Depth <= MaxDepth && "Limit Search Depth");
Sanjoy Das39a684d2017-02-25 20:30:45 +00002353
2354 // We return the minimum number of sign bits that are guaranteed to be present
2355 // in V, so for undef we have to conservatively return 1. We don't have the
2356 // same behavior for poison though -- that's a FIXME today.
2357
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00002358 Type *ScalarTy = V->getType()->getScalarType();
2359 unsigned TyBits = ScalarTy->isPointerTy() ?
2360 Q.DL.getIndexTypeSizeInBits(ScalarTy) :
2361 Q.DL.getTypeSizeInBits(ScalarTy);
2362
Chris Lattner965c7692008-06-02 01:18:21 +00002363 unsigned Tmp, Tmp2;
2364 unsigned FirstAnswer = 1;
2365
Jay Foada0653a32014-05-14 21:14:37 +00002366 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00002367 // below.
2368
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002369 if (Depth == MaxDepth)
Chris Lattner965c7692008-06-02 01:18:21 +00002370 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002371
Pete Cooper35b00d52016-08-13 01:05:32 +00002372 const Operator *U = dyn_cast<Operator>(V);
Dan Gohman80ca01c2009-07-17 20:47:02 +00002373 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00002374 default: break;
2375 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00002376 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002377 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00002378
Nadav Rotemc99a3872015-03-06 00:23:58 +00002379 case Instruction::SDiv: {
Nadav Rotem029c5c72015-03-03 21:39:02 +00002380 const APInt *Denominator;
2381 // sdiv X, C -> adds log(C) sign bits.
2382 if (match(U->getOperand(1), m_APInt(Denominator))) {
2383
2384 // Ignore non-positive denominator.
2385 if (!Denominator->isStrictlyPositive())
2386 break;
2387
2388 // Calculate the incoming numerator bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002389 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotem029c5c72015-03-03 21:39:02 +00002390
2391 // Add floor(log(C)) bits to the numerator bits.
2392 return std::min(TyBits, NumBits + Denominator->logBase2());
2393 }
2394 break;
Nadav Rotemc99a3872015-03-06 00:23:58 +00002395 }
2396
2397 case Instruction::SRem: {
2398 const APInt *Denominator;
Sanjoy Dase561fee2015-03-25 22:33:53 +00002399 // srem X, C -> we know that the result is within [-C+1,C) when C is a
2400 // positive constant. This let us put a lower bound on the number of sign
2401 // bits.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002402 if (match(U->getOperand(1), m_APInt(Denominator))) {
2403
2404 // Ignore non-positive denominator.
2405 if (!Denominator->isStrictlyPositive())
2406 break;
2407
2408 // Calculate the incoming numerator bits. SRem by a positive constant
2409 // can't lower the number of sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002410 unsigned NumrBits =
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002411 ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotemc99a3872015-03-06 00:23:58 +00002412
2413 // Calculate the leading sign bit constraints by examining the
Sanjoy Dase561fee2015-03-25 22:33:53 +00002414 // denominator. Given that the denominator is positive, there are two
2415 // cases:
2416 //
2417 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
2418 // (1 << ceilLogBase2(C)).
2419 //
2420 // 2. the numerator is negative. Then the result range is (-C,0] and
2421 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2422 //
2423 // Thus a lower bound on the number of sign bits is `TyBits -
2424 // ceilLogBase2(C)`.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002425
Sanjoy Dase561fee2015-03-25 22:33:53 +00002426 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
Nadav Rotemc99a3872015-03-06 00:23:58 +00002427 return std::max(NumrBits, ResBits);
2428 }
2429 break;
2430 }
Nadav Rotem029c5c72015-03-03 21:39:02 +00002431
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002432 case Instruction::AShr: {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002433 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002434 // ashr X, C -> adds C sign bits. Vectors too.
2435 const APInt *ShAmt;
2436 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Simon Pilgrim67207262018-01-01 22:44:59 +00002437 if (ShAmt->uge(TyBits))
Sanjoy Das39a684d2017-02-25 20:30:45 +00002438 break; // Bad shift.
Simon Pilgrim67207262018-01-01 22:44:59 +00002439 unsigned ShAmtLimited = ShAmt->getZExtValue();
Sanjoy Das39a684d2017-02-25 20:30:45 +00002440 Tmp += ShAmtLimited;
Chris Lattner965c7692008-06-02 01:18:21 +00002441 if (Tmp > TyBits) Tmp = TyBits;
2442 }
2443 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002444 }
2445 case Instruction::Shl: {
2446 const APInt *ShAmt;
2447 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00002448 // shl destroys sign bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002449 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Simon Pilgrim67207262018-01-01 22:44:59 +00002450 if (ShAmt->uge(TyBits) || // Bad shift.
2451 ShAmt->uge(Tmp)) break; // Shifted all sign bits out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002452 Tmp2 = ShAmt->getZExtValue();
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002453 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00002454 }
2455 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002456 }
Chris Lattner965c7692008-06-02 01:18:21 +00002457 case Instruction::And:
2458 case Instruction::Or:
2459 case Instruction::Xor: // NOT is handled here.
2460 // Logical binary ops preserve the number of sign bits at the worst.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002461 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002462 if (Tmp != 1) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002463 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002464 FirstAnswer = std::min(Tmp, Tmp2);
2465 // We computed what we know about the sign bits as our first
2466 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00002467 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00002468 }
2469 break;
2470
Craig Topperbec15b62018-08-22 23:27:50 +00002471 case Instruction::Select: {
2472 // If we have a clamp pattern, we know that the number of sign bits will be
2473 // the minimum of the clamp min/max range.
2474 const Value *X;
2475 const APInt *CLow, *CHigh;
2476 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
2477 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
2478
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002479 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002480 if (Tmp == 1) break;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002481 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002482 return std::min(Tmp, Tmp2);
Craig Topperbec15b62018-08-22 23:27:50 +00002483 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002484
Chris Lattner965c7692008-06-02 01:18:21 +00002485 case Instruction::Add:
2486 // Add can have at most one carry bit. Thus we know that the output
2487 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002488 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002489 if (Tmp == 1) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002490
Chris Lattner965c7692008-06-02 01:18:21 +00002491 // Special case decrementing a value (ADD X, -1):
David Majnemera55027f2014-12-26 09:20:17 +00002492 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00002493 if (CRHS->isAllOnesValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002494 KnownBits Known(TyBits);
2495 computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002496
Chris Lattner965c7692008-06-02 01:18:21 +00002497 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2498 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002499 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002500 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002501
Chris Lattner965c7692008-06-02 01:18:21 +00002502 // If we are subtracting one from a positive number, there is no carry
2503 // out of the result.
Craig Topperca48af32017-04-29 16:43:11 +00002504 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002505 return Tmp;
2506 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002507
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002508 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002509 if (Tmp2 == 1) break;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002510 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002511
Chris Lattner965c7692008-06-02 01:18:21 +00002512 case Instruction::Sub:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002513 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002514 if (Tmp2 == 1) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002515
Chris Lattner965c7692008-06-02 01:18:21 +00002516 // Handle NEG.
David Majnemera55027f2014-12-26 09:20:17 +00002517 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
Chris Lattner965c7692008-06-02 01:18:21 +00002518 if (CLHS->isNullValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002519 KnownBits Known(TyBits);
2520 computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002521 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2522 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002523 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002524 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002525
Chris Lattner965c7692008-06-02 01:18:21 +00002526 // If the input is known to be positive (the sign bit is known clear),
2527 // the output of the NEG has the same number of sign bits as the input.
Craig Topperca48af32017-04-29 16:43:11 +00002528 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002529 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00002530
Chris Lattner965c7692008-06-02 01:18:21 +00002531 // Otherwise, we treat this like a SUB.
2532 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002533
Chris Lattner965c7692008-06-02 01:18:21 +00002534 // Sub can have at most one carry bit. Thus we know that the output
2535 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002536 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002537 if (Tmp == 1) break;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002538 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002539
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002540 case Instruction::Mul: {
2541 // The output of the Mul can be at most twice the valid bits in the inputs.
2542 unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002543 if (SignBitsOp0 == 1) break;
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002544 unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002545 if (SignBitsOp1 == 1) break;
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002546 unsigned OutValidBits =
2547 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
2548 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
2549 }
2550
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002551 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00002552 const PHINode *PN = cast<PHINode>(U);
David Majnemer6ee8d172015-01-04 07:06:53 +00002553 unsigned NumIncomingValues = PN->getNumIncomingValues();
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002554 // Don't analyze large in-degree PHIs.
David Majnemer6ee8d172015-01-04 07:06:53 +00002555 if (NumIncomingValues > 4) break;
2556 // Unreachable blocks may have zero-operand PHI nodes.
2557 if (NumIncomingValues == 0) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002558
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002559 // Take the minimum of all incoming values. This can't infinitely loop
2560 // because of our depth threshold.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002561 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
David Majnemer6ee8d172015-01-04 07:06:53 +00002562 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002563 if (Tmp == 1) return Tmp;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002564 Tmp = std::min(
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002565 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002566 }
2567 return Tmp;
2568 }
2569
Chris Lattner965c7692008-06-02 01:18:21 +00002570 case Instruction::Trunc:
2571 // FIXME: it's tricky to do anything useful for this, but it is an important
2572 // case for targets like X86.
2573 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00002574
2575 case Instruction::ExtractElement:
2576 // Look through extract element. At the moment we keep this simple and skip
2577 // tracking the specific element. But at least we might find information
2578 // valid for all elements of the vector (for example if vector is sign
2579 // extended, shifted, etc).
2580 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Sanjay Patelcc9e4012018-10-26 21:05:14 +00002581
Sanjay Patela68096c2018-11-02 15:51:47 +00002582 case Instruction::ShuffleVector: {
Sanjay Patelcac28b42018-11-03 13:18:55 +00002583 // TODO: This is copied almost directly from the SelectionDAG version of
2584 // ComputeNumSignBits. It would be better if we could share common
2585 // code. If not, make sure that changes are translated to the DAG.
2586
2587 // Collect the minimum number of sign bits that are shared by every vector
2588 // element referenced by the shuffle.
2589 auto *Shuf = cast<ShuffleVectorInst>(U);
2590 int NumElts = Shuf->getOperand(0)->getType()->getVectorNumElements();
2591 int NumMaskElts = Shuf->getMask()->getType()->getVectorNumElements();
2592 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2593 for (int i = 0; i != NumMaskElts; ++i) {
2594 int M = Shuf->getMaskValue(i);
2595 assert(M < NumElts * 2 && "Invalid shuffle mask constant");
2596 // For undef elements, we don't know anything about the common state of
2597 // the shuffle result.
2598 if (M == -1)
2599 return 1;
2600 if (M < NumElts)
2601 DemandedLHS.setBit(M % NumElts);
2602 else
2603 DemandedRHS.setBit(M % NumElts);
2604 }
2605 Tmp = std::numeric_limits<unsigned>::max();
2606 if (!!DemandedLHS)
2607 Tmp = ComputeNumSignBits(Shuf->getOperand(0), Depth + 1, Q);
2608 if (!!DemandedRHS) {
2609 Tmp2 = ComputeNumSignBits(Shuf->getOperand(1), Depth + 1, Q);
2610 Tmp = std::min(Tmp, Tmp2);
2611 }
2612 // If we don't know anything, early out and try computeKnownBits fall-back.
2613 if (Tmp == 1)
Sanjay Patelcc9e4012018-10-26 21:05:14 +00002614 break;
Sanjay Patelcac28b42018-11-03 13:18:55 +00002615 assert(Tmp <= V->getType()->getScalarSizeInBits() &&
2616 "Failed to determine minimum sign bits");
2617 return Tmp;
Chris Lattner965c7692008-06-02 01:18:21 +00002618 }
Sanjay Patela68096c2018-11-02 15:51:47 +00002619 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002620
Chris Lattner965c7692008-06-02 01:18:21 +00002621 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2622 // use this information.
Sanjay Patela06d9892016-06-22 19:20:59 +00002623
2624 // If we can examine all elements of a vector constant successfully, we're
2625 // done (we can't do any better than that). If not, keep trying.
2626 if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits))
2627 return VecSignBits;
2628
Craig Topperb45eabc2017-04-26 16:39:58 +00002629 KnownBits Known(TyBits);
2630 computeKnownBits(V, Known, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002631
Sanjay Patele0536212016-06-23 17:41:59 +00002632 // If we know that the sign bit is either zero or one, determine the number of
2633 // identical bits in the top of the input value.
Craig Topper8df66c62017-05-12 17:20:30 +00002634 return std::max(FirstAnswer, Known.countMinSignBits());
Chris Lattner965c7692008-06-02 01:18:21 +00002635}
Chris Lattnera12a6de2008-06-02 01:29:46 +00002636
Sanjay Patelaee84212014-11-04 16:27:42 +00002637/// This function computes the integer multiple of Base that equals V.
2638/// If successful, it returns true and returns the multiple in
2639/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00002640/// through SExt instructions only if LookThroughSExt is true.
2641bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00002642 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00002643 const unsigned MaxDepth = 6;
2644
Dan Gohman6a976bb2009-11-18 00:58:27 +00002645 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00002646 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002647 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00002648
Chris Lattner229907c2011-07-18 04:54:35 +00002649 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00002650
Dan Gohman6a976bb2009-11-18 00:58:27 +00002651 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00002652
2653 if (Base == 0)
2654 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002655
Victor Hernandez47444882009-11-10 08:28:35 +00002656 if (Base == 1) {
2657 Multiple = V;
2658 return true;
2659 }
2660
2661 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2662 Constant *BaseVal = ConstantInt::get(T, Base);
2663 if (CO && CO == BaseVal) {
2664 // Multiple is 1.
2665 Multiple = ConstantInt::get(T, 1);
2666 return true;
2667 }
2668
2669 if (CI && CI->getZExtValue() % Base == 0) {
2670 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00002671 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00002672 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002673
Victor Hernandez47444882009-11-10 08:28:35 +00002674 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002675
Victor Hernandez47444882009-11-10 08:28:35 +00002676 Operator *I = dyn_cast<Operator>(V);
2677 if (!I) return false;
2678
2679 switch (I->getOpcode()) {
2680 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002681 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00002682 if (!LookThroughSExt) return false;
2683 // otherwise fall through to ZExt
Galina Kistanova244621f2017-05-31 22:16:24 +00002684 LLVM_FALLTHROUGH;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002685 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00002686 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2687 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00002688 case Instruction::Shl:
2689 case Instruction::Mul: {
2690 Value *Op0 = I->getOperand(0);
2691 Value *Op1 = I->getOperand(1);
2692
2693 if (I->getOpcode() == Instruction::Shl) {
2694 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2695 if (!Op1CI) return false;
2696 // Turn Op0 << Op1 into Op0 * 2^Op1
2697 APInt Op1Int = Op1CI->getValue();
2698 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00002699 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002700 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00002701 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00002702 }
2703
Craig Topper9f008862014-04-15 04:59:12 +00002704 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002705 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2706 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2707 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002708 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002709 MulC->getType()->getPrimitiveSizeInBits())
2710 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002711 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002712 MulC->getType()->getPrimitiveSizeInBits())
2713 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002714
Chris Lattner72d283c2010-09-05 17:20:46 +00002715 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2716 Multiple = ConstantExpr::getMul(MulC, Op1C);
2717 return true;
2718 }
Victor Hernandez47444882009-11-10 08:28:35 +00002719
2720 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2721 if (Mul0CI->getValue() == 1) {
2722 // V == Base * Op1, so return Op1
2723 Multiple = Op1;
2724 return true;
2725 }
2726 }
2727
Craig Topper9f008862014-04-15 04:59:12 +00002728 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002729 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2730 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2731 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002732 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002733 MulC->getType()->getPrimitiveSizeInBits())
2734 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002735 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002736 MulC->getType()->getPrimitiveSizeInBits())
2737 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002738
Chris Lattner72d283c2010-09-05 17:20:46 +00002739 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2740 Multiple = ConstantExpr::getMul(MulC, Op0C);
2741 return true;
2742 }
Victor Hernandez47444882009-11-10 08:28:35 +00002743
2744 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2745 if (Mul1CI->getValue() == 1) {
2746 // V == Base * Op0, so return Op0
2747 Multiple = Op0;
2748 return true;
2749 }
2750 }
Victor Hernandez47444882009-11-10 08:28:35 +00002751 }
2752 }
2753
2754 // We could not determine if V is a multiple of Base.
2755 return false;
2756}
2757
David Majnemerb4b27232016-04-19 19:10:21 +00002758Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS,
2759 const TargetLibraryInfo *TLI) {
2760 const Function *F = ICS.getCalledFunction();
2761 if (!F)
2762 return Intrinsic::not_intrinsic;
2763
2764 if (F->isIntrinsic())
2765 return F->getIntrinsicID();
2766
2767 if (!TLI)
2768 return Intrinsic::not_intrinsic;
2769
David L. Jonesd21529f2017-01-23 23:16:46 +00002770 LibFunc Func;
David Majnemerb4b27232016-04-19 19:10:21 +00002771 // We're going to make assumptions on the semantics of the functions, check
2772 // that the target knows that it's available in this environment and it does
2773 // not have local linkage.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002774 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func))
2775 return Intrinsic::not_intrinsic;
2776
2777 if (!ICS.onlyReadsMemory())
David Majnemerb4b27232016-04-19 19:10:21 +00002778 return Intrinsic::not_intrinsic;
2779
2780 // Otherwise check if we have a call to a function that can be turned into a
2781 // vector intrinsic.
2782 switch (Func) {
2783 default:
2784 break;
David L. Jonesd21529f2017-01-23 23:16:46 +00002785 case LibFunc_sin:
2786 case LibFunc_sinf:
2787 case LibFunc_sinl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002788 return Intrinsic::sin;
David L. Jonesd21529f2017-01-23 23:16:46 +00002789 case LibFunc_cos:
2790 case LibFunc_cosf:
2791 case LibFunc_cosl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002792 return Intrinsic::cos;
David L. Jonesd21529f2017-01-23 23:16:46 +00002793 case LibFunc_exp:
2794 case LibFunc_expf:
2795 case LibFunc_expl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002796 return Intrinsic::exp;
David L. Jonesd21529f2017-01-23 23:16:46 +00002797 case LibFunc_exp2:
2798 case LibFunc_exp2f:
2799 case LibFunc_exp2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002800 return Intrinsic::exp2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002801 case LibFunc_log:
2802 case LibFunc_logf:
2803 case LibFunc_logl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002804 return Intrinsic::log;
David L. Jonesd21529f2017-01-23 23:16:46 +00002805 case LibFunc_log10:
2806 case LibFunc_log10f:
2807 case LibFunc_log10l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002808 return Intrinsic::log10;
David L. Jonesd21529f2017-01-23 23:16:46 +00002809 case LibFunc_log2:
2810 case LibFunc_log2f:
2811 case LibFunc_log2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002812 return Intrinsic::log2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002813 case LibFunc_fabs:
2814 case LibFunc_fabsf:
2815 case LibFunc_fabsl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002816 return Intrinsic::fabs;
David L. Jonesd21529f2017-01-23 23:16:46 +00002817 case LibFunc_fmin:
2818 case LibFunc_fminf:
2819 case LibFunc_fminl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002820 return Intrinsic::minnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002821 case LibFunc_fmax:
2822 case LibFunc_fmaxf:
2823 case LibFunc_fmaxl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002824 return Intrinsic::maxnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002825 case LibFunc_copysign:
2826 case LibFunc_copysignf:
2827 case LibFunc_copysignl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002828 return Intrinsic::copysign;
David L. Jonesd21529f2017-01-23 23:16:46 +00002829 case LibFunc_floor:
2830 case LibFunc_floorf:
2831 case LibFunc_floorl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002832 return Intrinsic::floor;
David L. Jonesd21529f2017-01-23 23:16:46 +00002833 case LibFunc_ceil:
2834 case LibFunc_ceilf:
2835 case LibFunc_ceill:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002836 return Intrinsic::ceil;
David L. Jonesd21529f2017-01-23 23:16:46 +00002837 case LibFunc_trunc:
2838 case LibFunc_truncf:
2839 case LibFunc_truncl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002840 return Intrinsic::trunc;
David L. Jonesd21529f2017-01-23 23:16:46 +00002841 case LibFunc_rint:
2842 case LibFunc_rintf:
2843 case LibFunc_rintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002844 return Intrinsic::rint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002845 case LibFunc_nearbyint:
2846 case LibFunc_nearbyintf:
2847 case LibFunc_nearbyintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002848 return Intrinsic::nearbyint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002849 case LibFunc_round:
2850 case LibFunc_roundf:
2851 case LibFunc_roundl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002852 return Intrinsic::round;
David L. Jonesd21529f2017-01-23 23:16:46 +00002853 case LibFunc_pow:
2854 case LibFunc_powf:
2855 case LibFunc_powl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002856 return Intrinsic::pow;
David L. Jonesd21529f2017-01-23 23:16:46 +00002857 case LibFunc_sqrt:
2858 case LibFunc_sqrtf:
2859 case LibFunc_sqrtl:
Sanjay Patel86d24f12017-11-06 22:40:09 +00002860 return Intrinsic::sqrt;
David Majnemerb4b27232016-04-19 19:10:21 +00002861 }
2862
2863 return Intrinsic::not_intrinsic;
2864}
2865
Sanjay Patelaee84212014-11-04 16:27:42 +00002866/// Return true if we can prove that the specified FP value is never equal to
2867/// -0.0.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002868///
2869/// NOTE: this function will need to be revisited when we support non-default
2870/// rounding modes!
David Majnemer3ee5f342016-04-13 06:55:52 +00002871bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
2872 unsigned Depth) {
Sanjay Patel20df88a2017-11-13 17:56:23 +00002873 if (auto *CFP = dyn_cast<ConstantFP>(V))
Chris Lattnera12a6de2008-06-02 01:29:46 +00002874 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00002875
Sanjay Patel20df88a2017-11-13 17:56:23 +00002876 // Limit search depth.
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002877 if (Depth == MaxDepth)
Sanjay Patel20df88a2017-11-13 17:56:23 +00002878 return false;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002879
Sanjay Patel20df88a2017-11-13 17:56:23 +00002880 auto *Op = dyn_cast<Operator>(V);
2881 if (!Op)
2882 return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00002883
Sanjay Patel20df88a2017-11-13 17:56:23 +00002884 // Check if the nsz fast-math flag is set.
2885 if (auto *FPO = dyn_cast<FPMathOperator>(Op))
Michael Ilseman0f128372012-12-06 00:07:09 +00002886 if (FPO->hasNoSignedZeros())
2887 return true;
2888
Sanjay Patel9e3d8f42017-11-13 17:40:47 +00002889 // (fadd x, 0.0) is guaranteed to return +0.0, not -0.0.
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002890 if (match(Op, m_FAdd(m_Value(), m_PosZeroFP())))
Sanjay Patel9e3d8f42017-11-13 17:40:47 +00002891 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002892
Chris Lattnera12a6de2008-06-02 01:29:46 +00002893 // sitofp and uitofp turn into +0.0 for zero.
Sanjay Patel20df88a2017-11-13 17:56:23 +00002894 if (isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op))
Chris Lattnera12a6de2008-06-02 01:29:46 +00002895 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002896
Sanjay Patel20df88a2017-11-13 17:56:23 +00002897 if (auto *Call = dyn_cast<CallInst>(Op)) {
2898 Intrinsic::ID IID = getIntrinsicForCallSite(Call, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002899 switch (IID) {
2900 default:
2901 break;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002902 // sqrt(-0.0) = -0.0, no other negative results are possible.
David Majnemer3ee5f342016-04-13 06:55:52 +00002903 case Intrinsic::sqrt:
Matt Arsenault56b31d82018-08-06 15:16:26 +00002904 case Intrinsic::canonicalize:
Sanjay Patel20df88a2017-11-13 17:56:23 +00002905 return CannotBeNegativeZero(Call->getArgOperand(0), TLI, Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002906 // fabs(x) != -0.0
2907 case Intrinsic::fabs:
2908 return true;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002909 }
David Majnemer3ee5f342016-04-13 06:55:52 +00002910 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002911
Chris Lattnera12a6de2008-06-02 01:29:46 +00002912 return false;
2913}
2914
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002915/// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
2916/// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
2917/// bit despite comparing equal.
2918static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
2919 const TargetLibraryInfo *TLI,
2920 bool SignBitOnly,
2921 unsigned Depth) {
Justin Lebar322c1272017-01-27 00:58:34 +00002922 // TODO: This function does not do the right thing when SignBitOnly is true
2923 // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
2924 // which flips the sign bits of NaNs. See
2925 // https://llvm.org/bugs/show_bug.cgi?id=31702.
2926
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002927 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2928 return !CFP->getValueAPF().isNegative() ||
2929 (!SignBitOnly && CFP->getValueAPF().isZero());
2930 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002931
Craig Topper69c89722018-02-26 22:33:17 +00002932 // Handle vector of constants.
2933 if (auto *CV = dyn_cast<Constant>(V)) {
2934 if (CV->getType()->isVectorTy()) {
2935 unsigned NumElts = CV->getType()->getVectorNumElements();
2936 for (unsigned i = 0; i != NumElts; ++i) {
2937 auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
2938 if (!CFP)
2939 return false;
2940 if (CFP->getValueAPF().isNegative() &&
2941 (SignBitOnly || !CFP->getValueAPF().isZero()))
2942 return false;
2943 }
2944
2945 // All non-negative ConstantFPs.
2946 return true;
2947 }
2948 }
2949
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002950 if (Depth == MaxDepth)
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002951 return false; // Limit search depth.
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002952
2953 const Operator *I = dyn_cast<Operator>(V);
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002954 if (!I)
2955 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002956
2957 switch (I->getOpcode()) {
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002958 default:
2959 break;
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002960 // Unsigned integers are always nonnegative.
2961 case Instruction::UIToFP:
2962 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002963 case Instruction::FMul:
2964 // x*x is always non-negative or a NaN.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002965 if (I->getOperand(0) == I->getOperand(1) &&
2966 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002967 return true;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002968
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002969 LLVM_FALLTHROUGH;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002970 case Instruction::FAdd:
2971 case Instruction::FDiv:
2972 case Instruction::FRem:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002973 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2974 Depth + 1) &&
2975 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2976 Depth + 1);
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002977 case Instruction::Select:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002978 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2979 Depth + 1) &&
2980 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2981 Depth + 1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002982 case Instruction::FPExt:
2983 case Instruction::FPTrunc:
2984 // Widening/narrowing never change sign.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002985 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2986 Depth + 1);
Craig Topper30199102018-02-27 19:53:45 +00002987 case Instruction::ExtractElement:
2988 // Look through extract element. At the moment we keep this simple and skip
2989 // tracking the specific element. But at least we might find information
2990 // valid for all elements of the vector.
2991 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2992 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002993 case Instruction::Call:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002994 const auto *CI = cast<CallInst>(I);
2995 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002996 switch (IID) {
2997 default:
2998 break;
2999 case Intrinsic::maxnum:
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003000 return (isKnownNeverNaN(I->getOperand(0), TLI) &&
Sanjay Patelf9a0d592018-08-02 13:46:20 +00003001 cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI,
3002 SignBitOnly, Depth + 1)) ||
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003003 (isKnownNeverNaN(I->getOperand(1), TLI) &&
Sanjay Patelf9a0d592018-08-02 13:46:20 +00003004 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI,
3005 SignBitOnly, Depth + 1));
3006
Thomas Livelyc3392502018-10-19 19:01:26 +00003007 case Intrinsic::maximum:
3008 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3009 Depth + 1) ||
3010 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3011 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00003012 case Intrinsic::minnum:
Thomas Livelyc3392502018-10-19 19:01:26 +00003013 case Intrinsic::minimum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00003014 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3015 Depth + 1) &&
3016 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3017 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00003018 case Intrinsic::exp:
3019 case Intrinsic::exp2:
3020 case Intrinsic::fabs:
David Majnemer3ee5f342016-04-13 06:55:52 +00003021 return true;
Justin Lebar7e3184c2017-01-26 00:10:26 +00003022
3023 case Intrinsic::sqrt:
3024 // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0.
3025 if (!SignBitOnly)
3026 return true;
3027 return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
3028 CannotBeNegativeZero(CI->getOperand(0), TLI));
3029
David Majnemer3ee5f342016-04-13 06:55:52 +00003030 case Intrinsic::powi:
Justin Lebar7e3184c2017-01-26 00:10:26 +00003031 if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
David Majnemer3ee5f342016-04-13 06:55:52 +00003032 // powi(x,n) is non-negative if n is even.
Justin Lebar7e3184c2017-01-26 00:10:26 +00003033 if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
David Majnemer3ee5f342016-04-13 06:55:52 +00003034 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003035 }
Justin Lebar322c1272017-01-27 00:58:34 +00003036 // TODO: This is not correct. Given that exp is an integer, here are the
3037 // ways that pow can return a negative value:
3038 //
3039 // pow(x, exp) --> negative if exp is odd and x is negative.
3040 // pow(-0, exp) --> -inf if exp is negative odd.
3041 // pow(-0, exp) --> -0 if exp is positive odd.
3042 // pow(-inf, exp) --> -0 if exp is negative odd.
3043 // pow(-inf, exp) --> -inf if exp is positive odd.
3044 //
3045 // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
3046 // but we must return false if x == -0. Unfortunately we do not currently
3047 // have a way of expressing this constraint. See details in
3048 // https://llvm.org/bugs/show_bug.cgi?id=31702.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00003049 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3050 Depth + 1);
Justin Lebar322c1272017-01-27 00:58:34 +00003051
David Majnemer3ee5f342016-04-13 06:55:52 +00003052 case Intrinsic::fma:
3053 case Intrinsic::fmuladd:
3054 // x*x+y is non-negative if y is non-negative.
3055 return I->getOperand(0) == I->getOperand(1) &&
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00003056 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
3057 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
3058 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00003059 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003060 break;
3061 }
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003062 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003063}
3064
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00003065bool llvm::CannotBeOrderedLessThanZero(const Value *V,
3066 const TargetLibraryInfo *TLI) {
3067 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
3068}
3069
3070bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
3071 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
3072}
3073
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003074bool llvm::isKnownNeverNaN(const Value *V, const TargetLibraryInfo *TLI,
3075 unsigned Depth) {
Sanjay Patel6840c5f2017-09-05 23:13:13 +00003076 assert(V->getType()->isFPOrFPVectorTy() && "Querying for NaN on non-FP type");
3077
3078 // If we're told that NaNs won't happen, assume they won't.
3079 if (auto *FPMathOp = dyn_cast<FPMathOperator>(V))
3080 if (FPMathOp->hasNoNaNs())
3081 return true;
3082
Sanjay Patel6840c5f2017-09-05 23:13:13 +00003083 // Handle scalar constants.
3084 if (auto *CFP = dyn_cast<ConstantFP>(V))
3085 return !CFP->isNaN();
3086
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003087 if (Depth == MaxDepth)
3088 return false;
3089
Matt Arsenault450fcc72018-08-20 16:51:00 +00003090 if (auto *Inst = dyn_cast<Instruction>(V)) {
3091 switch (Inst->getOpcode()) {
3092 case Instruction::FAdd:
3093 case Instruction::FMul:
3094 case Instruction::FSub:
3095 case Instruction::FDiv:
3096 case Instruction::FRem: {
3097 // TODO: Need isKnownNeverInfinity
3098 return false;
3099 }
3100 case Instruction::Select: {
3101 return isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) &&
3102 isKnownNeverNaN(Inst->getOperand(2), TLI, Depth + 1);
3103 }
3104 case Instruction::SIToFP:
3105 case Instruction::UIToFP:
3106 return true;
3107 case Instruction::FPTrunc:
3108 case Instruction::FPExt:
3109 return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1);
3110 default:
3111 break;
3112 }
3113 }
3114
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003115 if (const auto *II = dyn_cast<IntrinsicInst>(V)) {
3116 switch (II->getIntrinsicID()) {
3117 case Intrinsic::canonicalize:
3118 case Intrinsic::fabs:
3119 case Intrinsic::copysign:
Matt Arsenault450fcc72018-08-20 16:51:00 +00003120 case Intrinsic::exp:
3121 case Intrinsic::exp2:
3122 case Intrinsic::floor:
3123 case Intrinsic::ceil:
3124 case Intrinsic::trunc:
3125 case Intrinsic::rint:
3126 case Intrinsic::nearbyint:
3127 case Intrinsic::round:
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003128 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1);
3129 case Intrinsic::sqrt:
3130 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) &&
3131 CannotBeOrderedLessThanZero(II->getArgOperand(0), TLI);
3132 default:
3133 return false;
3134 }
3135 }
3136
Sanjay Patel6840c5f2017-09-05 23:13:13 +00003137 // Bail out for constant expressions, but try to handle vector constants.
3138 if (!V->getType()->isVectorTy() || !isa<Constant>(V))
3139 return false;
3140
3141 // For vectors, verify that each element is not NaN.
3142 unsigned NumElts = V->getType()->getVectorNumElements();
3143 for (unsigned i = 0; i != NumElts; ++i) {
3144 Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
3145 if (!Elt)
3146 return false;
3147 if (isa<UndefValue>(Elt))
3148 continue;
3149 auto *CElt = dyn_cast<ConstantFP>(Elt);
3150 if (!CElt || CElt->isNaN())
3151 return false;
3152 }
3153 // All elements were confirmed not-NaN or undefined.
3154 return true;
3155}
3156
Chris Lattner9cb10352010-12-26 20:15:01 +00003157Value *llvm::isBytewiseValue(Value *V) {
JF Bastien73d8e4e2018-09-21 05:17:42 +00003158
Chris Lattner9cb10352010-12-26 20:15:01 +00003159 // All byte-wide stores are splatable, even of arbitrary variables.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003160 if (V->getType()->isIntegerTy(8))
3161 return V;
3162
3163 LLVMContext &Ctx = V->getContext();
3164
3165 // Undef don't care.
3166 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
3167 if (isa<UndefValue>(V))
3168 return UndefInt8;
3169
3170 Constant *C = dyn_cast<Constant>(V);
3171 if (!C) {
3172 // Conceptually, we could handle things like:
3173 // %a = zext i8 %X to i16
3174 // %b = shl i16 %a, 8
3175 // %c = or i16 %a, %b
3176 // but until there is an example that actually needs this, it doesn't seem
3177 // worth worrying about.
3178 return nullptr;
3179 }
Chris Lattneracf6b072011-02-19 19:35:49 +00003180
3181 // Handle 'null' ConstantArrayZero etc.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003182 if (C->isNullValue())
3183 return Constant::getNullValue(Type::getInt8Ty(Ctx));
Craig Topper1bef2c82012-12-22 19:15:35 +00003184
JF Bastien73d8e4e2018-09-21 05:17:42 +00003185 // Constant floating-point values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00003186 // corresponding integer value is "byteable". An important case is 0.0.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003187 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3188 Type *Ty = nullptr;
3189 if (CFP->getType()->isHalfTy())
3190 Ty = Type::getInt16Ty(Ctx);
3191 else if (CFP->getType()->isFloatTy())
3192 Ty = Type::getInt32Ty(Ctx);
3193 else if (CFP->getType()->isDoubleTy())
3194 Ty = Type::getInt64Ty(Ctx);
Chris Lattner9cb10352010-12-26 20:15:01 +00003195 // Don't handle long double formats, which have strange constraints.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003196 return Ty ? isBytewiseValue(ConstantExpr::getBitCast(CFP, Ty)) : nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00003197 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003198
Benjamin Kramer17d90152015-02-07 19:29:02 +00003199 // We can handle constant integers that are multiple of 8 bits.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003200 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
Benjamin Kramer17d90152015-02-07 19:29:02 +00003201 if (CI->getBitWidth() % 8 == 0) {
3202 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
Benjamin Kramerb4b51502015-03-25 16:49:59 +00003203 if (!CI->getValue().isSplat(8))
Benjamin Kramer17d90152015-02-07 19:29:02 +00003204 return nullptr;
JF Bastien73d8e4e2018-09-21 05:17:42 +00003205 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
Chris Lattner9cb10352010-12-26 20:15:01 +00003206 }
3207 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003208
JF Bastien73d8e4e2018-09-21 05:17:42 +00003209 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
3210 if (LHS == RHS)
3211 return LHS;
3212 if (!LHS || !RHS)
Craig Topper9f008862014-04-15 04:59:12 +00003213 return nullptr;
JF Bastien73d8e4e2018-09-21 05:17:42 +00003214 if (LHS == UndefInt8)
3215 return RHS;
3216 if (RHS == UndefInt8)
3217 return LHS;
3218 return nullptr;
3219 };
Craig Topper1bef2c82012-12-22 19:15:35 +00003220
JF Bastien73d8e4e2018-09-21 05:17:42 +00003221 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(C)) {
3222 Value *Val = UndefInt8;
3223 for (unsigned I = 0, E = CA->getNumElements(); I != E; ++I)
3224 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I)))))
Craig Topper9f008862014-04-15 04:59:12 +00003225 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00003226 return Val;
3227 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00003228
JF Bastien73d8e4e2018-09-21 05:17:42 +00003229 if (isa<ConstantVector>(C)) {
3230 Constant *Splat = cast<ConstantVector>(C)->getSplatValue();
3231 return Splat ? isBytewiseValue(Splat) : nullptr;
3232 }
3233
3234 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
3235 Value *Val = UndefInt8;
3236 for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I)
3237 if (!(Val = Merge(Val, isBytewiseValue(C->getOperand(I)))))
3238 return nullptr;
3239 return Val;
3240 }
3241
3242 // Don't try to handle the handful of other constants.
Craig Topper9f008862014-04-15 04:59:12 +00003243 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00003244}
3245
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003246// This is the recursive version of BuildSubAggregate. It takes a few different
3247// arguments. Idxs is the index within the nested struct From that we are
3248// looking at now (which is of type IndexedType). IdxSkip is the number of
3249// indices from Idxs that should be left out when inserting into the resulting
3250// struct. To is the result struct built so far, new insertvalue instructions
3251// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00003252static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00003253 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00003254 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00003255 Instruction *InsertBefore) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003256 StructType *STy = dyn_cast<StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003257 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003258 // Save the original To argument so we can modify it
3259 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003260 // General case, the type indexed by Idxs is a struct
3261 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3262 // Process each struct element recursively
3263 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003264 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003265 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003266 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003267 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003268 if (!To) {
3269 // Couldn't find any inserted value for this index? Cleanup
3270 while (PrevTo != OrigTo) {
3271 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
3272 PrevTo = Del->getAggregateOperand();
3273 Del->eraseFromParent();
3274 }
3275 // Stop processing elements
3276 break;
3277 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003278 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00003279 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003280 if (To)
3281 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003282 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003283 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
3284 // the struct's elements had a value that was inserted directly. In the latter
3285 // case, perhaps we can't determine each of the subelements individually, but
3286 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00003287
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003288 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00003289 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003290
3291 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00003292 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003293
Vedant Kumard3196742018-02-28 19:08:52 +00003294 // Insert the value in the new (sub) aggregate
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003295 return InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
3296 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003297}
3298
3299// This helper takes a nested struct and extracts a part of it (which is again a
3300// struct) into a new value. For example, given the struct:
3301// { a, { b, { c, d }, e } }
3302// and the indices "1, 1" this returns
3303// { c, d }.
3304//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003305// It does this by inserting an insertvalue for each element in the resulting
3306// struct, as opposed to just inserting a single struct. This will only work if
3307// each of the elements of the substruct are known (ie, inserted into From by an
3308// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003309//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003310// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00003311static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00003312 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00003313 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00003314 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00003315 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00003316 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00003317 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003318 unsigned IdxSkip = Idxs.size();
3319
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003320 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003321}
3322
Vedant Kumard3196742018-02-28 19:08:52 +00003323/// Given an aggregate and a sequence of indices, see if the scalar value
3324/// indexed is already around as a register, for example if it was inserted
3325/// directly into the aggregate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003326///
3327/// If InsertBefore is not null, this function will duplicate (modified)
3328/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00003329Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
3330 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003331 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003332 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00003333 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003334 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003335 // We have indices, so V should have an indexable type.
3336 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
3337 "Not looking at a struct or array?");
3338 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
3339 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00003340
Chris Lattner67058832012-01-25 06:48:06 +00003341 if (Constant *C = dyn_cast<Constant>(V)) {
3342 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00003343 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00003344 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
3345 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003346
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003347 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003348 // Loop the indices for the insertvalue instruction in parallel with the
3349 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00003350 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003351 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
3352 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00003353 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003354 // We can't handle this without inserting insertvalues
3355 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00003356 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003357
3358 // The requested index identifies a part of a nested aggregate. Handle
3359 // this specially. For example,
3360 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
3361 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
3362 // %C = extractvalue {i32, { i32, i32 } } %B, 1
3363 // This can be changed into
3364 // %A = insertvalue {i32, i32 } undef, i32 10, 0
3365 // %C = insertvalue {i32, i32 } %A, i32 11, 1
3366 // which allows the unused 0,0 element from the nested struct to be
3367 // removed.
3368 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
3369 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00003370 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003371
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003372 // This insert value inserts something else than what we are looking for.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003373 // See if the (aggregate) value inserted into has the value we are
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003374 // looking for, then.
3375 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00003376 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003377 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003378 }
3379 // If we end up here, the indices of the insertvalue match with those
3380 // requested (though possibly only partially). Now we recursively look at
3381 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00003382 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00003383 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003384 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003385 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003386
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003387 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003388 // If we're extracting a value from an aggregate that was extracted from
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003389 // something else, we can extract from that something else directly instead.
3390 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00003391
3392 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00003393 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003394 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00003395 SmallVector<unsigned, 5> Idxs;
3396 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003397 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00003398 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00003399
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003400 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00003401 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003402
Craig Topper1bef2c82012-12-22 19:15:35 +00003403 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003404 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00003405
Jay Foad57aa6362011-07-13 10:26:04 +00003406 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003407 }
3408 // Otherwise, we don't know (such as, extracting from a function return value
3409 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00003410 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003411}
Evan Chengda3db112008-06-30 07:31:25 +00003412
Sanjay Patelaee84212014-11-04 16:27:42 +00003413/// Analyze the specified pointer to see if it can be expressed as a base
3414/// pointer plus a constant offset. Return the base and offset to the caller.
Chris Lattnere28618d2010-11-30 22:25:26 +00003415Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003416 const DataLayout &DL) {
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003417 unsigned BitWidth = DL.getIndexTypeSizeInBits(Ptr->getType());
Nuno Lopes368c4d02012-12-31 20:48:35 +00003418 APInt ByteOffset(BitWidth, 0);
Chandler Carruth76641272016-01-04 07:23:12 +00003419
3420 // We walk up the defs but use a visited set to handle unreachable code. In
3421 // that case, we stop after accumulating the cycle once (not that it
3422 // matters).
3423 SmallPtrSet<Value *, 16> Visited;
3424 while (Visited.insert(Ptr).second) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003425 if (Ptr->getType()->isVectorTy())
3426 break;
Craig Topper1bef2c82012-12-22 19:15:35 +00003427
Nuno Lopes368c4d02012-12-31 20:48:35 +00003428 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Tom Stellard17eb3412016-10-07 14:23:29 +00003429 // If one of the values we have visited is an addrspacecast, then
3430 // the pointer type of this GEP may be different from the type
3431 // of the Ptr parameter which was passed to this function. This
3432 // means when we construct GEPOffset, we need to use the size
3433 // of GEP's pointer type rather than the size of the original
3434 // pointer type.
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003435 APInt GEPOffset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003436 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
3437 break;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00003438
Florian Hahn79024052019-01-04 14:53:22 +00003439 APInt OrigByteOffset(ByteOffset);
3440 ByteOffset += GEPOffset.sextOrTrunc(ByteOffset.getBitWidth());
3441 if (ByteOffset.getMinSignedBits() > 64) {
3442 // Stop traversal if the pointer offset wouldn't fit into int64_t
3443 // (this should be removed if Offset is updated to an APInt)
3444 ByteOffset = OrigByteOffset;
3445 break;
3446 }
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00003447
Nuno Lopes368c4d02012-12-31 20:48:35 +00003448 Ptr = GEP->getPointerOperand();
Tom Stellard17eb3412016-10-07 14:23:29 +00003449 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
3450 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003451 Ptr = cast<Operator>(Ptr)->getOperand(0);
3452 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003453 if (GA->isInterposable())
Nuno Lopes368c4d02012-12-31 20:48:35 +00003454 break;
3455 Ptr = GA->getAliasee();
Chris Lattnere28618d2010-11-30 22:25:26 +00003456 } else {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003457 break;
Chris Lattnere28618d2010-11-30 22:25:26 +00003458 }
3459 }
Nuno Lopes368c4d02012-12-31 20:48:35 +00003460 Offset = ByteOffset.getSExtValue();
3461 return Ptr;
Chris Lattnere28618d2010-11-30 22:25:26 +00003462}
3463
Matthias Braun50ec0b52017-05-19 22:37:09 +00003464bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP,
3465 unsigned CharSize) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003466 // Make sure the GEP has exactly three arguments.
3467 if (GEP->getNumOperands() != 3)
3468 return false;
3469
Matthias Braun50ec0b52017-05-19 22:37:09 +00003470 // Make sure the index-ee is a pointer to array of \p CharSize integers.
3471 // CharSize.
David L Kreitzer752c1442016-04-13 14:31:06 +00003472 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
Matthias Braun50ec0b52017-05-19 22:37:09 +00003473 if (!AT || !AT->getElementType()->isIntegerTy(CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +00003474 return false;
3475
3476 // Check to make sure that the first operand of the GEP is an integer and
3477 // has value 0 so that we are sure we're indexing into the initializer.
3478 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
3479 if (!FirstIdx || !FirstIdx->isZero())
3480 return false;
3481
3482 return true;
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003483}
Chris Lattnere28618d2010-11-30 22:25:26 +00003484
Matthias Braun50ec0b52017-05-19 22:37:09 +00003485bool llvm::getConstantDataArrayInfo(const Value *V,
3486 ConstantDataArraySlice &Slice,
3487 unsigned ElementSize, uint64_t Offset) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003488 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00003489
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003490 // Look through bitcast instructions and geps.
3491 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00003492
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00003493 // If the value is a GEP instruction or constant expression, treat it as an
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003494 // offset.
3495 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003496 // The GEP operator should be based on a pointer to string constant, and is
3497 // indexing into the string constant.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003498 if (!isGEPBasedOnPointerToString(GEP, ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003499 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003500
Evan Chengda3db112008-06-30 07:31:25 +00003501 // If the second index isn't a ConstantInt, then this is a variable index
3502 // into the array. If this occurs, we can't say anything meaningful about
3503 // the string.
3504 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00003505 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00003506 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003507 else
3508 return false;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003509 return getConstantDataArrayInfo(GEP->getOperand(0), Slice, ElementSize,
3510 StartIdx + Offset);
Evan Chengda3db112008-06-30 07:31:25 +00003511 }
Nick Lewycky46209882011-10-20 00:34:35 +00003512
Evan Chengda3db112008-06-30 07:31:25 +00003513 // The GEP instruction, constant or instruction, must reference a global
3514 // variable that is a constant and is initialized. The referenced constant
3515 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003516 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00003517 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003518 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003519
Matthias Braun50ec0b52017-05-19 22:37:09 +00003520 const ConstantDataArray *Array;
3521 ArrayType *ArrayTy;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003522 if (GV->getInitializer()->isNullValue()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003523 Type *GVTy = GV->getValueType();
3524 if ( (ArrayTy = dyn_cast<ArrayType>(GVTy)) ) {
Sanjay Patel2ad88f82017-06-12 22:34:37 +00003525 // A zeroinitializer for the array; there is no ConstantDataArray.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003526 Array = nullptr;
3527 } else {
3528 const DataLayout &DL = GV->getParent()->getDataLayout();
3529 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy);
3530 uint64_t Length = SizeInBytes / (ElementSize / 8);
3531 if (Length <= Offset)
3532 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003533
Matthias Braun50ec0b52017-05-19 22:37:09 +00003534 Slice.Array = nullptr;
3535 Slice.Offset = 0;
3536 Slice.Length = Length - Offset;
3537 return true;
3538 }
3539 } else {
3540 // This must be a ConstantDataArray.
3541 Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
3542 if (!Array)
3543 return false;
3544 ArrayTy = Array->getType();
3545 }
3546 if (!ArrayTy->getElementType()->isIntegerTy(ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003547 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003548
Matthias Braun50ec0b52017-05-19 22:37:09 +00003549 uint64_t NumElts = ArrayTy->getArrayNumElements();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003550 if (Offset > NumElts)
3551 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003552
Matthias Braun50ec0b52017-05-19 22:37:09 +00003553 Slice.Array = Array;
3554 Slice.Offset = Offset;
3555 Slice.Length = NumElts - Offset;
3556 return true;
3557}
3558
3559/// This function computes the length of a null-terminated C string pointed to
3560/// by V. If successful, it returns true and returns the string in Str.
3561/// If unsuccessful, it returns false.
3562bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
3563 uint64_t Offset, bool TrimAtNul) {
3564 ConstantDataArraySlice Slice;
3565 if (!getConstantDataArrayInfo(V, Slice, 8, Offset))
3566 return false;
3567
3568 if (Slice.Array == nullptr) {
3569 if (TrimAtNul) {
3570 Str = StringRef();
3571 return true;
3572 }
3573 if (Slice.Length == 1) {
3574 Str = StringRef("", 1);
3575 return true;
3576 }
Sanjay Patelfef83e82017-06-09 14:21:18 +00003577 // We cannot instantiate a StringRef as we do not have an appropriate string
Matthias Braun50ec0b52017-05-19 22:37:09 +00003578 // of 0s at hand.
3579 return false;
3580 }
3581
3582 // Start out with the entire array in the StringRef.
3583 Str = Slice.Array->getAsString();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003584 // Skip over 'offset' bytes.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003585 Str = Str.substr(Slice.Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00003586
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003587 if (TrimAtNul) {
3588 // Trim off the \0 and anything after it. If the array is not nul
3589 // terminated, we just return the whole end of string. The client may know
3590 // some other way that the string is length-bound.
3591 Str = Str.substr(0, Str.find('\0'));
3592 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003593 return true;
Evan Chengda3db112008-06-30 07:31:25 +00003594}
Eric Christopher4899cbc2010-03-05 06:58:57 +00003595
3596// These next two are very similar to the above, but also look through PHI
3597// nodes.
3598// TODO: See if we can integrate these two together.
3599
Sanjay Patelaee84212014-11-04 16:27:42 +00003600/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003601/// the specified pointer, return 'len+1'. If we can't, return 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00003602static uint64_t GetStringLengthH(const Value *V,
Matthias Braun50ec0b52017-05-19 22:37:09 +00003603 SmallPtrSetImpl<const PHINode*> &PHIs,
3604 unsigned CharSize) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003605 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003606 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00003607
3608 // If this is a PHI node, there are two cases: either we have already seen it
3609 // or we haven't.
Pete Cooper35b00d52016-08-13 01:05:32 +00003610 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
David Blaikie70573dc2014-11-19 07:49:26 +00003611 if (!PHIs.insert(PN).second)
Eric Christopher4899cbc2010-03-05 06:58:57 +00003612 return ~0ULL; // already in the set.
3613
3614 // If it was new, see if all the input strings are the same length.
3615 uint64_t LenSoFar = ~0ULL;
Pete Cooper833f34d2015-05-12 20:05:31 +00003616 for (Value *IncValue : PN->incoming_values()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003617 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003618 if (Len == 0) return 0; // Unknown length -> unknown.
3619
3620 if (Len == ~0ULL) continue;
3621
3622 if (Len != LenSoFar && LenSoFar != ~0ULL)
3623 return 0; // Disagree -> unknown.
3624 LenSoFar = Len;
3625 }
3626
3627 // Success, all agree.
3628 return LenSoFar;
3629 }
3630
3631 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
Pete Cooper35b00d52016-08-13 01:05:32 +00003632 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003633 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003634 if (Len1 == 0) return 0;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003635 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003636 if (Len2 == 0) return 0;
3637 if (Len1 == ~0ULL) return Len2;
3638 if (Len2 == ~0ULL) return Len1;
3639 if (Len1 != Len2) return 0;
3640 return Len1;
3641 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003642
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003643 // Otherwise, see if we can read the string.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003644 ConstantDataArraySlice Slice;
3645 if (!getConstantDataArrayInfo(V, Slice, CharSize))
Eric Christopher4899cbc2010-03-05 06:58:57 +00003646 return 0;
3647
Matthias Braun50ec0b52017-05-19 22:37:09 +00003648 if (Slice.Array == nullptr)
3649 return 1;
3650
3651 // Search for nul characters
3652 unsigned NullIndex = 0;
3653 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
3654 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
3655 break;
3656 }
3657
3658 return NullIndex + 1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003659}
3660
Sanjay Patelaee84212014-11-04 16:27:42 +00003661/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003662/// the specified pointer, return 'len+1'. If we can't, return 0.
David Bolvansky1f343fa2018-05-22 20:27:36 +00003663uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
David Bolvansky41f4b642018-05-22 15:41:23 +00003664 if (!V->getType()->isPointerTy())
3665 return 0;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003666
Pete Cooper35b00d52016-08-13 01:05:32 +00003667 SmallPtrSet<const PHINode*, 32> PHIs;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003668 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003669 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
3670 // an empty string as a length.
3671 return Len == ~0ULL ? 1 : Len;
3672}
Dan Gohmana4fcd242010-12-15 20:02:24 +00003673
Chandler Carruth363ac682019-01-07 05:42:51 +00003674const Value *llvm::getArgumentAliasingToReturnedPointer(const CallBase *Call) {
3675 assert(Call &&
3676 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
3677 if (const Value *RV = Call->getReturnedArgOperand())
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003678 return RV;
3679 // This can be used only as a aliasing property.
Chandler Carruth363ac682019-01-07 05:42:51 +00003680 if (isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(Call))
3681 return Call->getArgOperand(0);
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003682 return nullptr;
3683}
3684
3685bool llvm::isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
Chandler Carruth363ac682019-01-07 05:42:51 +00003686 const CallBase *Call) {
3687 return Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
3688 Call->getIntrinsicID() == Intrinsic::strip_invariant_group;
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003689}
3690
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003691/// \p PN defines a loop-variant pointer to an object. Check if the
Adam Nemete2b885c2015-04-23 20:09:20 +00003692/// previous iteration of the loop was referring to the same object as \p PN.
Pete Cooper35b00d52016-08-13 01:05:32 +00003693static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
3694 const LoopInfo *LI) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003695 // Find the loop-defined value.
3696 Loop *L = LI->getLoopFor(PN->getParent());
3697 if (PN->getNumIncomingValues() != 2)
3698 return true;
3699
3700 // Find the value from previous iteration.
3701 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3702 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3703 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3704 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3705 return true;
3706
3707 // If a new pointer is loaded in the loop, the pointer references a different
3708 // object in every iteration. E.g.:
3709 // for (i)
3710 // int *p = a[i];
3711 // ...
3712 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3713 if (!L->isLoopInvariant(Load->getPointerOperand()))
3714 return false;
3715 return true;
3716}
3717
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003718Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3719 unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003720 if (!V->getType()->isPointerTy())
3721 return V;
3722 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3723 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3724 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00003725 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3726 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003727 V = cast<Operator>(V)->getOperand(0);
3728 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003729 if (GA->isInterposable())
Dan Gohmana4fcd242010-12-15 20:02:24 +00003730 return V;
3731 V = GA->getAliasee();
Craig Topper85482412017-04-12 22:29:23 +00003732 } else if (isa<AllocaInst>(V)) {
3733 // An alloca can't be further simplified.
3734 return V;
Dan Gohmana4fcd242010-12-15 20:02:24 +00003735 } else {
Chandler Carruth363ac682019-01-07 05:42:51 +00003736 if (auto *Call = dyn_cast<CallBase>(V)) {
Piotr Padlewski5b3db452018-07-02 04:49:30 +00003737 // CaptureTracking can know about special capturing properties of some
3738 // intrinsics like launder.invariant.group, that can't be expressed with
3739 // the attributes, but have properties like returning aliasing pointer.
3740 // Because some analysis may assume that nocaptured pointer is not
3741 // returned from some special intrinsic (because function would have to
3742 // be marked with returns attribute), it is crucial to use this function
3743 // because it should be in sync with CaptureTracking. Not using it may
3744 // cause weird miscompilations where 2 aliasing pointers are assumed to
3745 // noalias.
Chandler Carruth363ac682019-01-07 05:42:51 +00003746 if (auto *RP = getArgumentAliasingToReturnedPointer(Call)) {
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003747 V = RP;
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003748 continue;
3749 }
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003750 }
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003751
Dan Gohman05b18f12010-12-15 20:49:55 +00003752 // See if InstructionSimplify knows any relevant tricks.
3753 if (Instruction *I = dyn_cast<Instruction>(V))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003754 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00003755 if (Value *Simplified = SimplifyInstruction(I, {DL, I})) {
Dan Gohman05b18f12010-12-15 20:49:55 +00003756 V = Simplified;
3757 continue;
3758 }
3759
Dan Gohmana4fcd242010-12-15 20:02:24 +00003760 return V;
3761 }
3762 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3763 }
3764 return V;
3765}
Nick Lewycky3e334a42011-06-27 04:20:45 +00003766
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003767void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
Adam Nemete2b885c2015-04-23 20:09:20 +00003768 const DataLayout &DL, LoopInfo *LI,
3769 unsigned MaxLookup) {
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003770 SmallPtrSet<Value *, 4> Visited;
3771 SmallVector<Value *, 4> Worklist;
3772 Worklist.push_back(V);
3773 do {
3774 Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003775 P = GetUnderlyingObject(P, DL, MaxLookup);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003776
David Blaikie70573dc2014-11-19 07:49:26 +00003777 if (!Visited.insert(P).second)
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003778 continue;
3779
3780 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
3781 Worklist.push_back(SI->getTrueValue());
3782 Worklist.push_back(SI->getFalseValue());
3783 continue;
3784 }
3785
3786 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003787 // If this PHI changes the underlying object in every iteration of the
3788 // loop, don't look through it. Consider:
3789 // int **A;
3790 // for (i) {
3791 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
3792 // Curr = A[i];
3793 // *Prev, *Curr;
3794 //
3795 // Prev is tracking Curr one iteration behind so they refer to different
3796 // underlying objects.
3797 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3798 isSameUnderlyingObjectInLoop(PN, LI))
Pete Cooper833f34d2015-05-12 20:05:31 +00003799 for (Value *IncValue : PN->incoming_values())
3800 Worklist.push_back(IncValue);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003801 continue;
3802 }
3803
3804 Objects.push_back(P);
3805 } while (!Worklist.empty());
3806}
3807
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003808/// This is the function that does the work of looking through basic
3809/// ptrtoint+arithmetic+inttoptr sequences.
3810static const Value *getUnderlyingObjectFromInt(const Value *V) {
3811 do {
3812 if (const Operator *U = dyn_cast<Operator>(V)) {
3813 // If we find a ptrtoint, we can transfer control back to the
3814 // regular getUnderlyingObjectFromInt.
3815 if (U->getOpcode() == Instruction::PtrToInt)
3816 return U->getOperand(0);
3817 // If we find an add of a constant, a multiplied value, or a phi, it's
3818 // likely that the other operand will lead us to the base
3819 // object. We don't have to worry about the case where the
3820 // object address is somehow being computed by the multiply,
3821 // because our callers only care when the result is an
3822 // identifiable object.
3823 if (U->getOpcode() != Instruction::Add ||
3824 (!isa<ConstantInt>(U->getOperand(1)) &&
3825 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
3826 !isa<PHINode>(U->getOperand(1))))
3827 return V;
3828 V = U->getOperand(0);
3829 } else {
3830 return V;
3831 }
3832 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
3833 } while (true);
3834}
3835
3836/// This is a wrapper around GetUnderlyingObjects and adds support for basic
3837/// ptrtoint+arithmetic+inttoptr sequences.
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003838/// It returns false if unidentified object is found in GetUnderlyingObjects.
3839bool llvm::getUnderlyingObjectsForCodeGen(const Value *V,
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003840 SmallVectorImpl<Value *> &Objects,
3841 const DataLayout &DL) {
3842 SmallPtrSet<const Value *, 16> Visited;
3843 SmallVector<const Value *, 4> Working(1, V);
3844 do {
3845 V = Working.pop_back_val();
3846
3847 SmallVector<Value *, 4> Objs;
3848 GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
3849
3850 for (Value *V : Objs) {
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003851 if (!Visited.insert(V).second)
3852 continue;
3853 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
3854 const Value *O =
3855 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
3856 if (O->getType()->isPointerTy()) {
3857 Working.push_back(O);
3858 continue;
3859 }
3860 }
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003861 // If GetUnderlyingObjects fails to find an identifiable object,
3862 // getUnderlyingObjectsForCodeGen also fails for safety.
3863 if (!isIdentifiedObject(V)) {
3864 Objects.clear();
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003865 return false;
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003866 }
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003867 Objects.push_back(const_cast<Value *>(V));
3868 }
3869 } while (!Working.empty());
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003870 return true;
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003871}
3872
Sanjay Patelaee84212014-11-04 16:27:42 +00003873/// Return true if the only users of this pointer are lifetime markers.
Nick Lewycky3e334a42011-06-27 04:20:45 +00003874bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003875 for (const User *U : V->users()) {
3876 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00003877 if (!II) return false;
3878
Vedant Kumarb264d692018-12-21 21:49:40 +00003879 if (!II->isLifetimeStartOrEnd())
Nick Lewycky3e334a42011-06-27 04:20:45 +00003880 return false;
3881 }
3882 return true;
3883}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003884
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003885bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3886 const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003887 const DominatorTree *DT) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00003888 const Operator *Inst = dyn_cast<Operator>(V);
3889 if (!Inst)
3890 return false;
3891
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003892 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3893 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3894 if (C->canTrap())
3895 return false;
3896
3897 switch (Inst->getOpcode()) {
3898 default:
3899 return true;
3900 case Instruction::UDiv:
David Majnemerf20d7c42014-11-04 23:49:08 +00003901 case Instruction::URem: {
3902 // x / y is undefined if y == 0.
3903 const APInt *V;
3904 if (match(Inst->getOperand(1), m_APInt(V)))
3905 return *V != 0;
3906 return false;
3907 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003908 case Instruction::SDiv:
3909 case Instruction::SRem: {
David Majnemerf20d7c42014-11-04 23:49:08 +00003910 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
David Majnemer8a6578a2015-02-01 19:10:19 +00003911 const APInt *Numerator, *Denominator;
3912 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3913 return false;
3914 // We cannot hoist this division if the denominator is 0.
3915 if (*Denominator == 0)
3916 return false;
3917 // It's safe to hoist if the denominator is not 0 or -1.
3918 if (*Denominator != -1)
3919 return true;
3920 // At this point we know that the denominator is -1. It is safe to hoist as
3921 // long we know that the numerator is not INT_MIN.
3922 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3923 return !Numerator->isMinSignedValue();
3924 // The numerator *might* be MinSignedValue.
David Majnemerf20d7c42014-11-04 23:49:08 +00003925 return false;
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003926 }
3927 case Instruction::Load: {
3928 const LoadInst *LI = cast<LoadInst>(Inst);
Kostya Serebryany0b458282013-11-21 07:29:28 +00003929 if (!LI->isUnordered() ||
3930 // Speculative load may create a race that did not exist in the source.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003931 LI->getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
Kostya Serebryany5cb86d52015-10-14 00:21:05 +00003932 // Speculative load may load data from dirty regions.
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00003933 LI->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3934 LI->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003935 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003936 const DataLayout &DL = LI->getModule()->getDataLayout();
Sean Silva45835e72016-07-02 23:47:27 +00003937 return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
3938 LI->getAlignment(), DL, CtxI, DT);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003939 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003940 case Instruction::Call: {
Matt Arsenaultcf5e7fe2017-04-28 21:13:09 +00003941 auto *CI = cast<const CallInst>(Inst);
3942 const Function *Callee = CI->getCalledFunction();
David Majnemer0a92f862015-08-28 21:13:39 +00003943
Matt Arsenault6a288c12017-05-03 02:26:10 +00003944 // The called function could have undefined behavior or side-effects, even
3945 // if marked readnone nounwind.
3946 return Callee && Callee->isSpeculatable();
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003947 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003948 case Instruction::VAArg:
3949 case Instruction::Alloca:
3950 case Instruction::Invoke:
Craig Topper784929d2019-02-08 20:48:56 +00003951 case Instruction::CallBr:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003952 case Instruction::PHI:
3953 case Instruction::Store:
3954 case Instruction::Ret:
3955 case Instruction::Br:
3956 case Instruction::IndirectBr:
3957 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003958 case Instruction::Unreachable:
3959 case Instruction::Fence:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003960 case Instruction::AtomicRMW:
3961 case Instruction::AtomicCmpXchg:
David Majnemer654e1302015-07-31 17:58:14 +00003962 case Instruction::LandingPad:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003963 case Instruction::Resume:
David Majnemer8a1c45d2015-12-12 05:38:55 +00003964 case Instruction::CatchSwitch:
David Majnemer654e1302015-07-31 17:58:14 +00003965 case Instruction::CatchPad:
David Majnemer654e1302015-07-31 17:58:14 +00003966 case Instruction::CatchRet:
3967 case Instruction::CleanupPad:
3968 case Instruction::CleanupRet:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003969 return false; // Misc instructions which have effects
3970 }
3971}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003972
Quentin Colombet6443cce2015-08-06 18:44:34 +00003973bool llvm::mayBeMemoryDependent(const Instruction &I) {
3974 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3975}
3976
Florian Hahn19f9e322018-08-17 14:39:04 +00003977OverflowResult llvm::computeOverflowForUnsignedMul(
3978 const Value *LHS, const Value *RHS, const DataLayout &DL,
3979 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
3980 bool UseInstrInfo) {
David Majnemer491331a2015-01-02 07:29:43 +00003981 // Multiplying n * m significant bits yields a result of n + m significant
3982 // bits. If the total number of significant bits does not exceed the
3983 // result bit width (minus 1), there is no overflow.
3984 // This means if we have enough leading zero bits in the operands
3985 // we can guarantee that the result does not overflow.
3986 // Ref: "Hacker's Delight" by Henry Warren
3987 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00003988 KnownBits LHSKnown(BitWidth);
3989 KnownBits RHSKnown(BitWidth);
Florian Hahn19f9e322018-08-17 14:39:04 +00003990 computeKnownBits(LHS, LHSKnown, DL, /*Depth=*/0, AC, CxtI, DT, nullptr,
3991 UseInstrInfo);
3992 computeKnownBits(RHS, RHSKnown, DL, /*Depth=*/0, AC, CxtI, DT, nullptr,
3993 UseInstrInfo);
David Majnemer491331a2015-01-02 07:29:43 +00003994 // Note that underestimating the number of zero bits gives a more
3995 // conservative answer.
Craig Topper8df66c62017-05-12 17:20:30 +00003996 unsigned ZeroBits = LHSKnown.countMinLeadingZeros() +
3997 RHSKnown.countMinLeadingZeros();
David Majnemer491331a2015-01-02 07:29:43 +00003998 // First handle the easy case: if we have enough zero bits there's
3999 // definitely no overflow.
4000 if (ZeroBits >= BitWidth)
4001 return OverflowResult::NeverOverflows;
4002
4003 // Get the largest possible values for each operand.
Craig Topperb45eabc2017-04-26 16:39:58 +00004004 APInt LHSMax = ~LHSKnown.Zero;
4005 APInt RHSMax = ~RHSKnown.Zero;
David Majnemer491331a2015-01-02 07:29:43 +00004006
4007 // We know the multiply operation doesn't overflow if the maximum values for
4008 // each operand will not overflow after we multiply them together.
David Majnemerc8a576b2015-01-02 07:29:47 +00004009 bool MaxOverflow;
Craig Topper9b71a402017-04-19 21:09:45 +00004010 (void)LHSMax.umul_ov(RHSMax, MaxOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00004011 if (!MaxOverflow)
4012 return OverflowResult::NeverOverflows;
David Majnemer491331a2015-01-02 07:29:43 +00004013
David Majnemerc8a576b2015-01-02 07:29:47 +00004014 // We know it always overflows if multiplying the smallest possible values for
4015 // the operands also results in overflow.
4016 bool MinOverflow;
Craig Topperb45eabc2017-04-26 16:39:58 +00004017 (void)LHSKnown.One.umul_ov(RHSKnown.One, MinOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00004018 if (MinOverflow)
4019 return OverflowResult::AlwaysOverflows;
4020
4021 return OverflowResult::MayOverflow;
David Majnemer491331a2015-01-02 07:29:43 +00004022}
David Majnemer5310c1e2015-01-07 00:39:50 +00004023
Florian Hahn19f9e322018-08-17 14:39:04 +00004024OverflowResult
4025llvm::computeOverflowForSignedMul(const Value *LHS, const Value *RHS,
4026 const DataLayout &DL, AssumptionCache *AC,
4027 const Instruction *CxtI,
4028 const DominatorTree *DT, bool UseInstrInfo) {
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004029 // Multiplying n * m significant bits yields a result of n + m significant
4030 // bits. If the total number of significant bits does not exceed the
4031 // result bit width (minus 1), there is no overflow.
4032 // This means if we have enough leading sign bits in the operands
4033 // we can guarantee that the result does not overflow.
4034 // Ref: "Hacker's Delight" by Henry Warren
4035 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
4036
4037 // Note that underestimating the number of sign bits gives a more
4038 // conservative answer.
4039 unsigned SignBits = ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) +
4040 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT);
4041
4042 // First handle the easy case: if we have enough sign bits there's
4043 // definitely no overflow.
4044 if (SignBits > BitWidth + 1)
4045 return OverflowResult::NeverOverflows;
4046
4047 // There are two ambiguous cases where there can be no overflow:
4048 // SignBits == BitWidth + 1 and
4049 // SignBits == BitWidth
4050 // The second case is difficult to check, therefore we only handle the
4051 // first case.
4052 if (SignBits == BitWidth + 1) {
4053 // It overflows only when both arguments are negative and the true
4054 // product is exactly the minimum negative number.
4055 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
4056 // For simplicity we just check if at least one side is not negative.
Florian Hahn19f9e322018-08-17 14:39:04 +00004057 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
4058 nullptr, UseInstrInfo);
4059 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
4060 nullptr, UseInstrInfo);
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004061 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
4062 return OverflowResult::NeverOverflows;
4063 }
4064 return OverflowResult::MayOverflow;
4065}
4066
Nikita Popov614b1be2019-03-15 18:37:45 +00004067/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
4068static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR) {
4069 switch (OR) {
4070 case ConstantRange::OverflowResult::MayOverflow:
4071 return OverflowResult::MayOverflow;
4072 case ConstantRange::OverflowResult::AlwaysOverflows:
4073 return OverflowResult::AlwaysOverflows;
4074 case ConstantRange::OverflowResult::NeverOverflows:
4075 return OverflowResult::NeverOverflows;
4076 }
4077 llvm_unreachable("Unknown OverflowResult");
4078}
4079
Nikita Popov20838192019-03-19 17:53:56 +00004080/// Combine constant ranges from computeConstantRange() and computeKnownBits().
4081static ConstantRange computeConstantRangeIncludingKnownBits(
4082 const Value *V, bool ForSigned, const DataLayout &DL, unsigned Depth,
4083 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4084 OptimizationRemarkEmitter *ORE = nullptr, bool UseInstrInfo = true) {
4085 KnownBits Known = computeKnownBits(
4086 V, DL, Depth, AC, CxtI, DT, ORE, UseInstrInfo);
4087 ConstantRange CR = computeConstantRange(V, UseInstrInfo);
4088 return ConstantRange::fromKnownBits(Known, ForSigned).intersectWith(CR);
4089}
4090
Florian Hahn19f9e322018-08-17 14:39:04 +00004091OverflowResult llvm::computeOverflowForUnsignedAdd(
4092 const Value *LHS, const Value *RHS, const DataLayout &DL,
4093 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4094 bool UseInstrInfo) {
Nikita Popov20838192019-03-19 17:53:56 +00004095 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4096 LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
4097 nullptr, UseInstrInfo);
4098 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4099 RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
4100 nullptr, UseInstrInfo);
Nikita Popov614b1be2019-03-15 18:37:45 +00004101 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
David Majnemer5310c1e2015-01-07 00:39:50 +00004102}
James Molloy71b91c22015-05-11 14:42:20 +00004103
Pete Cooper35b00d52016-08-13 01:05:32 +00004104static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
4105 const Value *RHS,
4106 const AddOperator *Add,
4107 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004108 AssumptionCache *AC,
Pete Cooper35b00d52016-08-13 01:05:32 +00004109 const Instruction *CxtI,
4110 const DominatorTree *DT) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00004111 if (Add && Add->hasNoSignedWrap()) {
4112 return OverflowResult::NeverOverflows;
4113 }
4114
Craig Topperbb973722017-05-15 02:44:08 +00004115 // If LHS and RHS each have at least two sign bits, the addition will look
4116 // like
4117 //
4118 // XX..... +
4119 // YY.....
4120 //
4121 // If the carry into the most significant position is 0, X and Y can't both
4122 // be 1 and therefore the carry out of the addition is also 0.
4123 //
4124 // If the carry into the most significant position is 1, X and Y can't both
4125 // be 0 and therefore the carry out of the addition is also 1.
4126 //
4127 // Since the carry into the most significant position is always equal to
4128 // the carry out of the addition, there is no signed overflow.
4129 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4130 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4131 return OverflowResult::NeverOverflows;
4132
Craig Topper6e11a052017-05-08 16:22:48 +00004133 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
4134 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
Nikita Popov322e2db2019-03-17 21:25:26 +00004135 ConstantRange LHSRange =
4136 ConstantRange::fromKnownBits(LHSKnown, /*signed*/ true);
4137 ConstantRange RHSRange =
4138 ConstantRange::fromKnownBits(RHSKnown, /*signed*/ true);
4139 OverflowResult OR =
4140 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
4141 if (OR != OverflowResult::MayOverflow)
4142 return OR;
Jingyue Wu10fcea52015-08-20 18:27:04 +00004143
4144 // The remaining code needs Add to be available. Early returns if not so.
4145 if (!Add)
4146 return OverflowResult::MayOverflow;
4147
4148 // If the sign of Add is the same as at least one of the operands, this add
Nikita Popov280a6b02019-03-22 17:51:40 +00004149 // CANNOT overflow. If this can be determined from the known bits of the
4150 // operands the above signedAddMayOverflow() check will have already done so.
4151 // The only other way to improve on the known bits is from an assumption, so
4152 // call computeKnownBitsFromAssume() directly.
Jingyue Wu10fcea52015-08-20 18:27:04 +00004153 bool LHSOrRHSKnownNonNegative =
Craig Topper6e11a052017-05-08 16:22:48 +00004154 (LHSKnown.isNonNegative() || RHSKnown.isNonNegative());
Fangrui Songf78650a2018-07-30 19:41:25 +00004155 bool LHSOrRHSKnownNegative =
Craig Topperbb973722017-05-15 02:44:08 +00004156 (LHSKnown.isNegative() || RHSKnown.isNegative());
Jingyue Wu10fcea52015-08-20 18:27:04 +00004157 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
Nikita Popov280a6b02019-03-22 17:51:40 +00004158 KnownBits AddKnown(LHSKnown.getBitWidth());
4159 computeKnownBitsFromAssume(
4160 Add, AddKnown, /*Depth=*/0, Query(DL, AC, CxtI, DT, true));
Craig Topper6e11a052017-05-08 16:22:48 +00004161 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
Nikita Popov280a6b02019-03-22 17:51:40 +00004162 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
Jingyue Wu10fcea52015-08-20 18:27:04 +00004163 return OverflowResult::NeverOverflows;
Jingyue Wu10fcea52015-08-20 18:27:04 +00004164 }
4165
4166 return OverflowResult::MayOverflow;
4167}
4168
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004169OverflowResult llvm::computeOverflowForUnsignedSub(const Value *LHS,
4170 const Value *RHS,
4171 const DataLayout &DL,
4172 AssumptionCache *AC,
4173 const Instruction *CxtI,
4174 const DominatorTree *DT) {
Nikita Popov20838192019-03-19 17:53:56 +00004175 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4176 LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
4177 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4178 RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
Nikita Popov614b1be2019-03-15 18:37:45 +00004179 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004180}
4181
4182OverflowResult llvm::computeOverflowForSignedSub(const Value *LHS,
4183 const Value *RHS,
4184 const DataLayout &DL,
4185 AssumptionCache *AC,
4186 const Instruction *CxtI,
4187 const DominatorTree *DT) {
4188 // If LHS and RHS each have at least two sign bits, the subtraction
4189 // cannot overflow.
4190 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4191 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4192 return OverflowResult::NeverOverflows;
4193
4194 KnownBits LHSKnown = computeKnownBits(LHS, DL, 0, AC, CxtI, DT);
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004195 KnownBits RHSKnown = computeKnownBits(RHS, DL, 0, AC, CxtI, DT);
Nikita Popov3af5b282019-03-21 17:23:51 +00004196 ConstantRange LHSRange =
4197 ConstantRange::fromKnownBits(LHSKnown, /*signed*/ true);
4198 ConstantRange RHSRange =
4199 ConstantRange::fromKnownBits(RHSKnown, /*signed*/ true);
4200 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004201}
4202
Pete Cooper35b00d52016-08-13 01:05:32 +00004203bool llvm::isOverflowIntrinsicNoWrap(const IntrinsicInst *II,
4204 const DominatorTree &DT) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004205#ifndef NDEBUG
4206 auto IID = II->getIntrinsicID();
4207 assert((IID == Intrinsic::sadd_with_overflow ||
4208 IID == Intrinsic::uadd_with_overflow ||
4209 IID == Intrinsic::ssub_with_overflow ||
4210 IID == Intrinsic::usub_with_overflow ||
4211 IID == Intrinsic::smul_with_overflow ||
4212 IID == Intrinsic::umul_with_overflow) &&
4213 "Not an overflow intrinsic!");
4214#endif
4215
Pete Cooper35b00d52016-08-13 01:05:32 +00004216 SmallVector<const BranchInst *, 2> GuardingBranches;
4217 SmallVector<const ExtractValueInst *, 2> Results;
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004218
Pete Cooper35b00d52016-08-13 01:05:32 +00004219 for (const User *U : II->users()) {
4220 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004221 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
4222
4223 if (EVI->getIndices()[0] == 0)
4224 Results.push_back(EVI);
4225 else {
4226 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
4227
Pete Cooper35b00d52016-08-13 01:05:32 +00004228 for (const auto *U : EVI->users())
4229 if (const auto *B = dyn_cast<BranchInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004230 assert(B->isConditional() && "How else is it using an i1?");
4231 GuardingBranches.push_back(B);
4232 }
4233 }
4234 } else {
4235 // We are using the aggregate directly in a way we don't want to analyze
4236 // here (storing it to a global, say).
4237 return false;
4238 }
4239 }
4240
Pete Cooper35b00d52016-08-13 01:05:32 +00004241 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004242 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
4243 if (!NoWrapEdge.isSingleEdge())
4244 return false;
4245
4246 // Check if all users of the add are provably no-wrap.
Pete Cooper35b00d52016-08-13 01:05:32 +00004247 for (const auto *Result : Results) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004248 // If the extractvalue itself is not executed on overflow, the we don't
4249 // need to check each use separately, since domination is transitive.
4250 if (DT.dominates(NoWrapEdge, Result->getParent()))
4251 continue;
4252
4253 for (auto &RU : Result->uses())
4254 if (!DT.dominates(NoWrapEdge, RU))
4255 return false;
4256 }
4257
4258 return true;
4259 };
4260
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004261 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004262}
4263
4264
Pete Cooper35b00d52016-08-13 01:05:32 +00004265OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004266 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004267 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004268 const Instruction *CxtI,
4269 const DominatorTree *DT) {
4270 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004271 Add, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00004272}
4273
Pete Cooper35b00d52016-08-13 01:05:32 +00004274OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
4275 const Value *RHS,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004276 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004277 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004278 const Instruction *CxtI,
4279 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004280 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00004281}
4282
Jingyue Wu42f1d672015-07-28 18:22:40 +00004283bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004284 // A memory operation returns normally if it isn't volatile. A volatile
4285 // operation is allowed to trap.
4286 //
4287 // An atomic operation isn't guaranteed to return in a reasonable amount of
4288 // time because it's possible for another thread to interfere with it for an
4289 // arbitrary length of time, but programs aren't allowed to rely on that.
4290 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
4291 return !LI->isVolatile();
4292 if (const StoreInst *SI = dyn_cast<StoreInst>(I))
4293 return !SI->isVolatile();
4294 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
4295 return !CXI->isVolatile();
4296 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
4297 return !RMWI->isVolatile();
4298 if (const MemIntrinsic *MII = dyn_cast<MemIntrinsic>(I))
4299 return !MII->isVolatile();
Jingyue Wu42f1d672015-07-28 18:22:40 +00004300
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004301 // If there is no successor, then execution can't transfer to it.
4302 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I))
4303 return !CRI->unwindsToCaller();
4304 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I))
4305 return !CatchSwitch->unwindsToCaller();
4306 if (isa<ResumeInst>(I))
4307 return false;
4308 if (isa<ReturnInst>(I))
4309 return false;
Sebastian Pop4a4d2452017-03-08 01:54:50 +00004310 if (isa<UnreachableInst>(I))
4311 return false;
Sanjoy Das9a65cd22016-06-08 17:48:36 +00004312
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004313 // Calls can throw, or contain an infinite loop, or kill the process.
Sanjoy Das09455302016-12-31 22:12:31 +00004314 if (auto CS = ImmutableCallSite(I)) {
Sanjoy Das3bb2dbd2016-12-31 22:12:34 +00004315 // Call sites that throw have implicit non-local control flow.
4316 if (!CS.doesNotThrow())
4317 return false;
4318
4319 // Non-throwing call sites can loop infinitely, call exit/pthread_exit
4320 // etc. and thus not return. However, LLVM already assumes that
4321 //
4322 // - Thread exiting actions are modeled as writes to memory invisible to
4323 // the program.
4324 //
4325 // - Loops that don't have side effects (side effects are volatile/atomic
4326 // stores and IO) always terminate (see http://llvm.org/PR965).
4327 // Furthermore IO itself is also modeled as writes to memory invisible to
4328 // the program.
4329 //
4330 // We rely on those assumptions here, and use the memory effects of the call
4331 // target as a proxy for checking that it always returns.
4332
4333 // FIXME: This isn't aggressive enough; a call which only writes to a global
4334 // is guaranteed to return.
Sanjoy Dasd7e82062016-06-14 20:23:16 +00004335 return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory() ||
Dan Gohman2c74fe92017-11-08 21:59:51 +00004336 match(I, m_Intrinsic<Intrinsic::assume>()) ||
Max Kazantsevb3168a42019-02-14 11:10:21 +00004337 match(I, m_Intrinsic<Intrinsic::sideeffect>()) ||
4338 match(I, m_Intrinsic<Intrinsic::experimental_widenable_condition>());
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004339 }
4340
4341 // Other instructions return normally.
4342 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004343}
4344
Philip Reamesfbffd122018-03-08 21:25:30 +00004345bool llvm::isGuaranteedToTransferExecutionToSuccessor(const BasicBlock *BB) {
Hiroshi Inouec437f312019-01-30 05:26:31 +00004346 // TODO: This is slightly conservative for invoke instruction since exiting
Philip Reamesfbffd122018-03-08 21:25:30 +00004347 // via an exception *is* normal control for them.
4348 for (auto I = BB->begin(), E = BB->end(); I != E; ++I)
4349 if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
4350 return false;
4351 return true;
4352}
4353
Jingyue Wu42f1d672015-07-28 18:22:40 +00004354bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
4355 const Loop *L) {
4356 // The loop header is guaranteed to be executed for every iteration.
4357 //
4358 // FIXME: Relax this constraint to cover all basic blocks that are
4359 // guaranteed to be executed at every iteration.
4360 if (I->getParent() != L->getHeader()) return false;
4361
4362 for (const Instruction &LI : *L->getHeader()) {
4363 if (&LI == I) return true;
4364 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
4365 }
4366 llvm_unreachable("Instruction not contained in its own parent basic block.");
4367}
4368
4369bool llvm::propagatesFullPoison(const Instruction *I) {
4370 switch (I->getOpcode()) {
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004371 case Instruction::Add:
4372 case Instruction::Sub:
4373 case Instruction::Xor:
4374 case Instruction::Trunc:
4375 case Instruction::BitCast:
4376 case Instruction::AddrSpaceCast:
Sanjoy Das5cd6c5ca2017-02-22 06:52:32 +00004377 case Instruction::Mul:
4378 case Instruction::Shl:
4379 case Instruction::GetElementPtr:
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004380 // These operations all propagate poison unconditionally. Note that poison
4381 // is not any particular value, so xor or subtraction of poison with
4382 // itself still yields poison, not zero.
4383 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004384
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004385 case Instruction::AShr:
4386 case Instruction::SExt:
4387 // For these operations, one bit of the input is replicated across
4388 // multiple output bits. A replicated poison bit is still poison.
4389 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004390
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004391 case Instruction::ICmp:
4392 // Comparing poison with any value yields poison. This is why, for
4393 // instance, x s< (x +nsw 1) can be folded to true.
4394 return true;
Sanjoy Das70c2bbd2016-05-29 00:31:18 +00004395
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004396 default:
4397 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004398 }
4399}
4400
4401const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
4402 switch (I->getOpcode()) {
4403 case Instruction::Store:
4404 return cast<StoreInst>(I)->getPointerOperand();
4405
4406 case Instruction::Load:
4407 return cast<LoadInst>(I)->getPointerOperand();
4408
4409 case Instruction::AtomicCmpXchg:
4410 return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
4411
4412 case Instruction::AtomicRMW:
4413 return cast<AtomicRMWInst>(I)->getPointerOperand();
4414
4415 case Instruction::UDiv:
4416 case Instruction::SDiv:
4417 case Instruction::URem:
4418 case Instruction::SRem:
4419 return I->getOperand(1);
4420
4421 default:
4422 return nullptr;
4423 }
4424}
4425
Sanjoy Das08989c72017-04-30 19:41:19 +00004426bool llvm::programUndefinedIfFullPoison(const Instruction *PoisonI) {
Jingyue Wu42f1d672015-07-28 18:22:40 +00004427 // We currently only look for uses of poison values within the same basic
4428 // block, as that makes it easier to guarantee that the uses will be
4429 // executed given that PoisonI is executed.
4430 //
4431 // FIXME: Expand this to consider uses beyond the same basic block. To do
4432 // this, look out for the distinction between post-dominance and strong
4433 // post-dominance.
4434 const BasicBlock *BB = PoisonI->getParent();
4435
4436 // Set of instructions that we have proved will yield poison if PoisonI
4437 // does.
4438 SmallSet<const Value *, 16> YieldsPoison;
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004439 SmallSet<const BasicBlock *, 4> Visited;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004440 YieldsPoison.insert(PoisonI);
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004441 Visited.insert(PoisonI->getParent());
Jingyue Wu42f1d672015-07-28 18:22:40 +00004442
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004443 BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end();
Jingyue Wu42f1d672015-07-28 18:22:40 +00004444
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004445 unsigned Iter = 0;
4446 while (Iter++ < MaxDepth) {
4447 for (auto &I : make_range(Begin, End)) {
4448 if (&I != PoisonI) {
4449 const Value *NotPoison = getGuaranteedNonFullPoisonOp(&I);
4450 if (NotPoison != nullptr && YieldsPoison.count(NotPoison))
4451 return true;
4452 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
4453 return false;
4454 }
4455
4456 // Mark poison that propagates from I through uses of I.
4457 if (YieldsPoison.count(&I)) {
4458 for (const User *User : I.users()) {
4459 const Instruction *UserI = cast<Instruction>(User);
4460 if (propagatesFullPoison(UserI))
4461 YieldsPoison.insert(User);
4462 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004463 }
4464 }
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004465
4466 if (auto *NextBB = BB->getSingleSuccessor()) {
4467 if (Visited.insert(NextBB).second) {
4468 BB = NextBB;
4469 Begin = BB->getFirstNonPHI()->getIterator();
4470 End = BB->end();
4471 continue;
4472 }
4473 }
4474
4475 break;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004476 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004477 return false;
4478}
4479
Pete Cooper35b00d52016-08-13 01:05:32 +00004480static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
James Molloy134bec22015-08-11 09:12:57 +00004481 if (FMF.noNaNs())
4482 return true;
4483
4484 if (auto *C = dyn_cast<ConstantFP>(V))
4485 return !C->isNaN();
Thomas Livelyd47b5c72018-09-28 21:36:43 +00004486
4487 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
4488 if (!C->getElementType()->isFloatingPointTy())
4489 return false;
4490 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
4491 if (C->getElementAsAPFloat(I).isNaN())
4492 return false;
4493 }
4494 return true;
4495 }
4496
James Molloy134bec22015-08-11 09:12:57 +00004497 return false;
4498}
4499
Pete Cooper35b00d52016-08-13 01:05:32 +00004500static bool isKnownNonZero(const Value *V) {
James Molloy134bec22015-08-11 09:12:57 +00004501 if (auto *C = dyn_cast<ConstantFP>(V))
4502 return !C->isZero();
Thomas Livelyd47b5c72018-09-28 21:36:43 +00004503
4504 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
4505 if (!C->getElementType()->isFloatingPointTy())
4506 return false;
4507 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
4508 if (C->getElementAsAPFloat(I).isZero())
4509 return false;
4510 }
4511 return true;
4512 }
4513
James Molloy134bec22015-08-11 09:12:57 +00004514 return false;
4515}
4516
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004517/// Match clamp pattern for float types without care about NaNs or signed zeros.
4518/// Given non-min/max outer cmp/select from the clamp pattern this
4519/// function recognizes if it can be substitued by a "canonical" min/max
4520/// pattern.
4521static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred,
4522 Value *CmpLHS, Value *CmpRHS,
4523 Value *TrueVal, Value *FalseVal,
4524 Value *&LHS, Value *&RHS) {
4525 // Try to match
4526 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
4527 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
4528 // and return description of the outer Max/Min.
4529
4530 // First, check if select has inverse order:
4531 if (CmpRHS == FalseVal) {
4532 std::swap(TrueVal, FalseVal);
4533 Pred = CmpInst::getInversePredicate(Pred);
4534 }
4535
4536 // Assume success now. If there's no match, callers should not use these anyway.
4537 LHS = TrueVal;
4538 RHS = FalseVal;
4539
4540 const APFloat *FC1;
4541 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
4542 return {SPF_UNKNOWN, SPNB_NA, false};
4543
4544 const APFloat *FC2;
4545 switch (Pred) {
4546 case CmpInst::FCMP_OLT:
4547 case CmpInst::FCMP_OLE:
4548 case CmpInst::FCMP_ULT:
4549 case CmpInst::FCMP_ULE:
4550 if (match(FalseVal,
4551 m_CombineOr(m_OrdFMin(m_Specific(CmpLHS), m_APFloat(FC2)),
4552 m_UnordFMin(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4553 FC1->compare(*FC2) == APFloat::cmpResult::cmpLessThan)
4554 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
4555 break;
4556 case CmpInst::FCMP_OGT:
4557 case CmpInst::FCMP_OGE:
4558 case CmpInst::FCMP_UGT:
4559 case CmpInst::FCMP_UGE:
4560 if (match(FalseVal,
4561 m_CombineOr(m_OrdFMax(m_Specific(CmpLHS), m_APFloat(FC2)),
4562 m_UnordFMax(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4563 FC1->compare(*FC2) == APFloat::cmpResult::cmpGreaterThan)
4564 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
4565 break;
4566 default:
4567 break;
4568 }
4569
4570 return {SPF_UNKNOWN, SPNB_NA, false};
4571}
4572
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004573/// Recognize variations of:
4574/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
4575static SelectPatternResult matchClamp(CmpInst::Predicate Pred,
4576 Value *CmpLHS, Value *CmpRHS,
4577 Value *TrueVal, Value *FalseVal) {
4578 // Swap the select operands and predicate to match the patterns below.
4579 if (CmpRHS != TrueVal) {
4580 Pred = ICmpInst::getSwappedPredicate(Pred);
4581 std::swap(TrueVal, FalseVal);
4582 }
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004583 const APInt *C1;
4584 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
4585 const APInt *C2;
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004586 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
4587 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004588 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004589 return {SPF_SMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004590
4591 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
4592 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004593 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004594 return {SPF_SMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004595
4596 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
4597 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004598 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004599 return {SPF_UMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004600
4601 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
4602 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004603 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004604 return {SPF_UMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004605 }
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004606 return {SPF_UNKNOWN, SPNB_NA, false};
4607}
4608
Sanjay Patel78114302018-01-02 20:56:45 +00004609/// Recognize variations of:
4610/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
4611static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred,
4612 Value *CmpLHS, Value *CmpRHS,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004613 Value *TVal, Value *FVal,
4614 unsigned Depth) {
Sanjay Patel78114302018-01-02 20:56:45 +00004615 // TODO: Allow FP min/max with nnan/nsz.
4616 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
4617
4618 Value *A, *B;
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004619 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
Sanjay Patel78114302018-01-02 20:56:45 +00004620 if (!SelectPatternResult::isMinOrMax(L.Flavor))
4621 return {SPF_UNKNOWN, SPNB_NA, false};
4622
4623 Value *C, *D;
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004624 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
Sanjay Patel78114302018-01-02 20:56:45 +00004625 if (L.Flavor != R.Flavor)
4626 return {SPF_UNKNOWN, SPNB_NA, false};
4627
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004628 // We have something like: x Pred y ? min(a, b) : min(c, d).
4629 // Try to match the compare to the min/max operations of the select operands.
4630 // First, make sure we have the right compare predicate.
Sanjay Patel78114302018-01-02 20:56:45 +00004631 switch (L.Flavor) {
4632 case SPF_SMIN:
4633 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
4634 Pred = ICmpInst::getSwappedPredicate(Pred);
4635 std::swap(CmpLHS, CmpRHS);
4636 }
4637 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
4638 break;
4639 return {SPF_UNKNOWN, SPNB_NA, false};
4640 case SPF_SMAX:
4641 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
4642 Pred = ICmpInst::getSwappedPredicate(Pred);
4643 std::swap(CmpLHS, CmpRHS);
4644 }
4645 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
4646 break;
4647 return {SPF_UNKNOWN, SPNB_NA, false};
4648 case SPF_UMIN:
4649 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
4650 Pred = ICmpInst::getSwappedPredicate(Pred);
4651 std::swap(CmpLHS, CmpRHS);
4652 }
4653 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
4654 break;
4655 return {SPF_UNKNOWN, SPNB_NA, false};
4656 case SPF_UMAX:
4657 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
4658 Pred = ICmpInst::getSwappedPredicate(Pred);
4659 std::swap(CmpLHS, CmpRHS);
4660 }
4661 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
4662 break;
4663 return {SPF_UNKNOWN, SPNB_NA, false};
4664 default:
Sanjay Patel7dfe96a2018-01-08 18:31:13 +00004665 return {SPF_UNKNOWN, SPNB_NA, false};
Sanjay Patel78114302018-01-02 20:56:45 +00004666 }
4667
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004668 // If there is a common operand in the already matched min/max and the other
4669 // min/max operands match the compare operands (either directly or inverted),
4670 // then this is min/max of the same flavor.
4671
Sanjay Patel78114302018-01-02 20:56:45 +00004672 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004673 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
4674 if (D == B) {
4675 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4676 match(A, m_Not(m_Specific(CmpRHS)))))
4677 return {L.Flavor, SPNB_NA, false};
4678 }
Sanjay Patel78114302018-01-02 20:56:45 +00004679 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004680 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
4681 if (C == B) {
4682 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4683 match(A, m_Not(m_Specific(CmpRHS)))))
4684 return {L.Flavor, SPNB_NA, false};
4685 }
Sanjay Patel78114302018-01-02 20:56:45 +00004686 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004687 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
4688 if (D == A) {
4689 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4690 match(B, m_Not(m_Specific(CmpRHS)))))
4691 return {L.Flavor, SPNB_NA, false};
4692 }
Sanjay Patel78114302018-01-02 20:56:45 +00004693 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004694 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
4695 if (C == A) {
4696 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4697 match(B, m_Not(m_Specific(CmpRHS)))))
4698 return {L.Flavor, SPNB_NA, false};
4699 }
Sanjay Patel78114302018-01-02 20:56:45 +00004700
4701 return {SPF_UNKNOWN, SPNB_NA, false};
4702}
4703
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004704/// Match non-obvious integer minimum and maximum sequences.
4705static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
4706 Value *CmpLHS, Value *CmpRHS,
4707 Value *TrueVal, Value *FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004708 Value *&LHS, Value *&RHS,
4709 unsigned Depth) {
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004710 // Assume success. If there's no match, callers should not use these anyway.
4711 LHS = TrueVal;
4712 RHS = FalseVal;
4713
4714 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
4715 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4716 return SPR;
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004717
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004718 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
Sanjay Patel78114302018-01-02 20:56:45 +00004719 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4720 return SPR;
Fangrui Songf78650a2018-07-30 19:41:25 +00004721
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004722 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
Sanjay Patel819f0962016-11-13 19:30:19 +00004723 return {SPF_UNKNOWN, SPNB_NA, false};
4724
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004725 // Z = X -nsw Y
4726 // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
4727 // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
4728 if (match(TrueVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004729 match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004730 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004731
4732 // Z = X -nsw Y
4733 // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
4734 // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
4735 if (match(FalseVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004736 match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004737 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004738
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004739 const APInt *C1;
Sanjay Patel819f0962016-11-13 19:30:19 +00004740 if (!match(CmpRHS, m_APInt(C1)))
4741 return {SPF_UNKNOWN, SPNB_NA, false};
4742
4743 // An unsigned min/max can be written with a signed compare.
4744 const APInt *C2;
4745 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
4746 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
4747 // Is the sign bit set?
4748 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
4749 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
Craig Topper81d772c2017-11-08 19:38:45 +00004750 if (Pred == CmpInst::ICMP_SLT && C1->isNullValue() &&
4751 C2->isMaxSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004752 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004753
4754 // Is the sign bit clear?
4755 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
4756 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004757 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
4758 C2->isMinSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004759 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004760 }
4761
4762 // Look through 'not' ops to find disguised signed min/max.
4763 // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C)
4764 // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C)
4765 if (match(TrueVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004766 match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2)
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004767 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004768
4769 // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X)
4770 // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X)
4771 if (match(FalseVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004772 match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2)
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004773 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004774
4775 return {SPF_UNKNOWN, SPNB_NA, false};
4776}
4777
Chen Zheng69bb0642018-07-21 12:27:54 +00004778bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW) {
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004779 assert(X && Y && "Invalid operand");
4780
Chen Zheng69bb0642018-07-21 12:27:54 +00004781 // X = sub (0, Y) || X = sub nsw (0, Y)
4782 if ((!NeedNSW && match(X, m_Sub(m_ZeroInt(), m_Specific(Y)))) ||
4783 (NeedNSW && match(X, m_NSWSub(m_ZeroInt(), m_Specific(Y)))))
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004784 return true;
4785
Chen Zheng69bb0642018-07-21 12:27:54 +00004786 // Y = sub (0, X) || Y = sub nsw (0, X)
4787 if ((!NeedNSW && match(Y, m_Sub(m_ZeroInt(), m_Specific(X)))) ||
4788 (NeedNSW && match(Y, m_NSWSub(m_ZeroInt(), m_Specific(X)))))
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004789 return true;
4790
Chen Zheng69bb0642018-07-21 12:27:54 +00004791 // 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 +00004792 Value *A, *B;
Chen Zheng69bb0642018-07-21 12:27:54 +00004793 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
4794 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
4795 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
4796 match(Y, m_NSWSub(m_Specific(B), m_Specific(A)))));
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004797}
4798
James Molloy134bec22015-08-11 09:12:57 +00004799static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
4800 FastMathFlags FMF,
James Molloy270ef8c2015-05-15 16:04:50 +00004801 Value *CmpLHS, Value *CmpRHS,
4802 Value *TrueVal, Value *FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004803 Value *&LHS, Value *&RHS,
4804 unsigned Depth) {
Sanjay Patele7c94ef2018-11-04 14:28:48 +00004805 if (CmpInst::isFPPredicate(Pred)) {
4806 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
4807 // 0.0 operand, set the compare's 0.0 operands to that same value for the
4808 // purpose of identifying min/max. Disregard vector constants with undefined
4809 // elements because those can not be back-propagated for analysis.
4810 Value *OutputZeroVal = nullptr;
4811 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
4812 !cast<Constant>(TrueVal)->containsUndefElement())
4813 OutputZeroVal = TrueVal;
4814 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
4815 !cast<Constant>(FalseVal)->containsUndefElement())
4816 OutputZeroVal = FalseVal;
4817
4818 if (OutputZeroVal) {
4819 if (match(CmpLHS, m_AnyZeroFP()))
4820 CmpLHS = OutputZeroVal;
4821 if (match(CmpRHS, m_AnyZeroFP()))
4822 CmpRHS = OutputZeroVal;
4823 }
4824 }
4825
James Molloy71b91c22015-05-11 14:42:20 +00004826 LHS = CmpLHS;
4827 RHS = CmpRHS;
4828
Sanjay Patel9a399792017-12-26 15:09:19 +00004829 // Signed zero may return inconsistent results between implementations.
4830 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
4831 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
4832 // Therefore, we behave conservatively and only proceed if at least one of the
4833 // operands is known to not be zero or if we don't care about signed zero.
James Molloy134bec22015-08-11 09:12:57 +00004834 switch (Pred) {
4835 default: break;
Sanjay Patel9a399792017-12-26 15:09:19 +00004836 // FIXME: Include OGT/OLT/UGT/ULT.
James Molloy134bec22015-08-11 09:12:57 +00004837 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
4838 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
4839 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4840 !isKnownNonZero(CmpRHS))
4841 return {SPF_UNKNOWN, SPNB_NA, false};
4842 }
4843
4844 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
4845 bool Ordered = false;
4846
4847 // When given one NaN and one non-NaN input:
4848 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
4849 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
4850 // ordered comparison fails), which could be NaN or non-NaN.
4851 // so here we discover exactly what NaN behavior is required/accepted.
4852 if (CmpInst::isFPPredicate(Pred)) {
4853 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
4854 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
4855
4856 if (LHSSafe && RHSSafe) {
4857 // Both operands are known non-NaN.
4858 NaNBehavior = SPNB_RETURNS_ANY;
4859 } else if (CmpInst::isOrdered(Pred)) {
4860 // An ordered comparison will return false when given a NaN, so it
4861 // returns the RHS.
4862 Ordered = true;
4863 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004864 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004865 NaNBehavior = SPNB_RETURNS_NAN;
4866 else if (RHSSafe)
4867 NaNBehavior = SPNB_RETURNS_OTHER;
4868 else
4869 // Completely unsafe.
4870 return {SPF_UNKNOWN, SPNB_NA, false};
4871 } else {
4872 Ordered = false;
4873 // An unordered comparison will return true when given a NaN, so it
4874 // returns the LHS.
4875 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004876 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004877 NaNBehavior = SPNB_RETURNS_OTHER;
4878 else if (RHSSafe)
4879 NaNBehavior = SPNB_RETURNS_NAN;
4880 else
4881 // Completely unsafe.
4882 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004883 }
4884 }
4885
James Molloy71b91c22015-05-11 14:42:20 +00004886 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
James Molloy134bec22015-08-11 09:12:57 +00004887 std::swap(CmpLHS, CmpRHS);
4888 Pred = CmpInst::getSwappedPredicate(Pred);
4889 if (NaNBehavior == SPNB_RETURNS_NAN)
4890 NaNBehavior = SPNB_RETURNS_OTHER;
4891 else if (NaNBehavior == SPNB_RETURNS_OTHER)
4892 NaNBehavior = SPNB_RETURNS_NAN;
4893 Ordered = !Ordered;
4894 }
4895
4896 // ([if]cmp X, Y) ? X : Y
4897 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
James Molloy71b91c22015-05-11 14:42:20 +00004898 switch (Pred) {
James Molloy134bec22015-08-11 09:12:57 +00004899 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
James Molloy71b91c22015-05-11 14:42:20 +00004900 case ICmpInst::ICMP_UGT:
James Molloy134bec22015-08-11 09:12:57 +00004901 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004902 case ICmpInst::ICMP_SGT:
James Molloy134bec22015-08-11 09:12:57 +00004903 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004904 case ICmpInst::ICMP_ULT:
James Molloy134bec22015-08-11 09:12:57 +00004905 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004906 case ICmpInst::ICMP_SLT:
James Molloy134bec22015-08-11 09:12:57 +00004907 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
4908 case FCmpInst::FCMP_UGT:
4909 case FCmpInst::FCMP_UGE:
4910 case FCmpInst::FCMP_OGT:
4911 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
4912 case FCmpInst::FCMP_ULT:
4913 case FCmpInst::FCMP_ULE:
4914 case FCmpInst::FCMP_OLT:
4915 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
James Molloy71b91c22015-05-11 14:42:20 +00004916 }
4917 }
Fangrui Songf78650a2018-07-30 19:41:25 +00004918
Chen Zhengccc84222018-07-16 02:23:00 +00004919 if (isKnownNegation(TrueVal, FalseVal)) {
4920 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
4921 // match against either LHS or sext(LHS).
4922 auto MaybeSExtCmpLHS =
4923 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
4924 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
4925 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
4926 if (match(TrueVal, MaybeSExtCmpLHS)) {
4927 // Set the return values. If the compare uses the negated value (-X >s 0),
4928 // swap the return values because the negated value is always 'RHS'.
Sanjay Patel284ba0c2018-07-02 14:43:40 +00004929 LHS = TrueVal;
4930 RHS = FalseVal;
Chen Zhengccc84222018-07-16 02:23:00 +00004931 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
4932 std::swap(LHS, RHS);
4933
4934 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
4935 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
4936 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
4937 return {SPF_ABS, SPNB_NA, false};
4938
Simon Pilgrima56f2822019-03-19 16:24:55 +00004939 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
4940 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
4941 return {SPF_ABS, SPNB_NA, false};
4942
Chen Zhengccc84222018-07-16 02:23:00 +00004943 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
4944 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
4945 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
4946 return {SPF_NABS, SPNB_NA, false};
4947 }
4948 else if (match(FalseVal, MaybeSExtCmpLHS)) {
4949 // Set the return values. If the compare uses the negated value (-X >s 0),
4950 // swap the return values because the negated value is always 'RHS'.
Sanjay Patel284ba0c2018-07-02 14:43:40 +00004951 LHS = FalseVal;
4952 RHS = TrueVal;
Chen Zhengccc84222018-07-16 02:23:00 +00004953 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
4954 std::swap(LHS, RHS);
4955
4956 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
4957 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
4958 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
4959 return {SPF_NABS, SPNB_NA, false};
4960
4961 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
4962 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
4963 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
4964 return {SPF_ABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004965 }
James Molloy71b91c22015-05-11 14:42:20 +00004966 }
4967
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004968 if (CmpInst::isIntPredicate(Pred))
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004969 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004970
4971 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
4972 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
4973 // semantics than minNum. Be conservative in such case.
4974 if (NaNBehavior != SPNB_RETURNS_ANY ||
4975 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4976 !isKnownNonZero(CmpRHS)))
4977 return {SPF_UNKNOWN, SPNB_NA, false};
4978
4979 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
James Molloy71b91c22015-05-11 14:42:20 +00004980}
James Molloy270ef8c2015-05-15 16:04:50 +00004981
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004982/// Helps to match a select pattern in case of a type mismatch.
4983///
4984/// The function processes the case when type of true and false values of a
4985/// select instruction differs from type of the cmp instruction operands because
Vedant Kumar1a8456d2018-03-02 18:57:02 +00004986/// of a cast instruction. The function checks if it is legal to move the cast
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004987/// operation after "select". If yes, it returns the new second value of
4988/// "select" (with the assumption that cast is moved):
4989/// 1. As operand of cast instruction when both values of "select" are same cast
4990/// instructions.
4991/// 2. As restored constant (by applying reverse cast operation) when the first
4992/// value of the "select" is a cast operation and the second value is a
4993/// constant.
4994/// NOTE: We return only the new second value because the first value could be
4995/// accessed as operand of cast instruction.
James Molloy569cea62015-09-02 17:25:25 +00004996static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
4997 Instruction::CastOps *CastOp) {
Sanjay Patel14a4b812017-01-29 16:34:57 +00004998 auto *Cast1 = dyn_cast<CastInst>(V1);
4999 if (!Cast1)
James Molloy270ef8c2015-05-15 16:04:50 +00005000 return nullptr;
James Molloy270ef8c2015-05-15 16:04:50 +00005001
Sanjay Patel14a4b812017-01-29 16:34:57 +00005002 *CastOp = Cast1->getOpcode();
5003 Type *SrcTy = Cast1->getSrcTy();
5004 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
5005 // If V1 and V2 are both the same cast from the same type, look through V1.
5006 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
5007 return Cast2->getOperand(0);
James Molloy569cea62015-09-02 17:25:25 +00005008 return nullptr;
5009 }
5010
Sanjay Patel14a4b812017-01-29 16:34:57 +00005011 auto *C = dyn_cast<Constant>(V2);
5012 if (!C)
5013 return nullptr;
5014
David Majnemerd2a074b2016-04-29 18:40:34 +00005015 Constant *CastedTo = nullptr;
Sanjay Patel14a4b812017-01-29 16:34:57 +00005016 switch (*CastOp) {
5017 case Instruction::ZExt:
5018 if (CmpI->isUnsigned())
5019 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
5020 break;
5021 case Instruction::SExt:
5022 if (CmpI->isSigned())
5023 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
5024 break;
5025 case Instruction::Trunc:
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00005026 Constant *CmpConst;
Nikolai Bozhenov9723f122017-10-18 14:24:50 +00005027 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
5028 CmpConst->getType() == SrcTy) {
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00005029 // Here we have the following case:
5030 //
5031 // %cond = cmp iN %x, CmpConst
5032 // %tr = trunc iN %x to iK
5033 // %narrowsel = select i1 %cond, iK %t, iK C
5034 //
5035 // We can always move trunc after select operation:
5036 //
5037 // %cond = cmp iN %x, CmpConst
5038 // %widesel = select i1 %cond, iN %x, iN CmpConst
5039 // %tr = trunc iN %widesel to iK
5040 //
5041 // Note that C could be extended in any way because we don't care about
5042 // upper bits after truncation. It can't be abs pattern, because it would
5043 // look like:
5044 //
5045 // select i1 %cond, x, -x.
5046 //
5047 // So only min/max pattern could be matched. Such match requires widened C
5048 // == CmpConst. That is why set widened C = CmpConst, condition trunc
5049 // CmpConst == C is checked below.
5050 CastedTo = CmpConst;
5051 } else {
5052 CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
5053 }
Sanjay Patel14a4b812017-01-29 16:34:57 +00005054 break;
5055 case Instruction::FPTrunc:
5056 CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
5057 break;
5058 case Instruction::FPExt:
5059 CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
5060 break;
5061 case Instruction::FPToUI:
5062 CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
5063 break;
5064 case Instruction::FPToSI:
5065 CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
5066 break;
5067 case Instruction::UIToFP:
5068 CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
5069 break;
5070 case Instruction::SIToFP:
5071 CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
5072 break;
5073 default:
5074 break;
5075 }
David Majnemerd2a074b2016-04-29 18:40:34 +00005076
5077 if (!CastedTo)
5078 return nullptr;
5079
David Majnemerd2a074b2016-04-29 18:40:34 +00005080 // Make sure the cast doesn't lose any information.
Sanjay Patel14a4b812017-01-29 16:34:57 +00005081 Constant *CastedBack =
5082 ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
David Majnemerd2a074b2016-04-29 18:40:34 +00005083 if (CastedBack != C)
5084 return nullptr;
5085
5086 return CastedTo;
James Molloy270ef8c2015-05-15 16:04:50 +00005087}
5088
Sanjay Patele8dc0902016-05-23 17:57:54 +00005089SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005090 Instruction::CastOps *CastOp,
5091 unsigned Depth) {
5092 if (Depth >= MaxDepth)
5093 return {SPF_UNKNOWN, SPNB_NA, false};
5094
James Molloy270ef8c2015-05-15 16:04:50 +00005095 SelectInst *SI = dyn_cast<SelectInst>(V);
James Molloy134bec22015-08-11 09:12:57 +00005096 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00005097
James Molloy134bec22015-08-11 09:12:57 +00005098 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
5099 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00005100
James Molloy134bec22015-08-11 09:12:57 +00005101 CmpInst::Predicate Pred = CmpI->getPredicate();
James Molloy270ef8c2015-05-15 16:04:50 +00005102 Value *CmpLHS = CmpI->getOperand(0);
5103 Value *CmpRHS = CmpI->getOperand(1);
5104 Value *TrueVal = SI->getTrueValue();
5105 Value *FalseVal = SI->getFalseValue();
James Molloy134bec22015-08-11 09:12:57 +00005106 FastMathFlags FMF;
5107 if (isa<FPMathOperator>(CmpI))
5108 FMF = CmpI->getFastMathFlags();
James Molloy270ef8c2015-05-15 16:04:50 +00005109
5110 // Bail out early.
5111 if (CmpI->isEquality())
James Molloy134bec22015-08-11 09:12:57 +00005112 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00005113
5114 // Deal with type mismatches.
5115 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
Sanjay Patel9a399792017-12-26 15:09:19 +00005116 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
5117 // If this is a potential fmin/fmax with a cast to integer, then ignore
5118 // -0.0 because there is no corresponding integer value.
5119 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
5120 FMF.setNoSignedZeros();
James Molloy134bec22015-08-11 09:12:57 +00005121 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00005122 cast<CastInst>(TrueVal)->getOperand(0), C,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005123 LHS, RHS, Depth);
Sanjay Patel9a399792017-12-26 15:09:19 +00005124 }
5125 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
5126 // If this is a potential fmin/fmax with a cast to integer, then ignore
5127 // -0.0 because there is no corresponding integer value.
5128 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
5129 FMF.setNoSignedZeros();
James Molloy134bec22015-08-11 09:12:57 +00005130 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00005131 C, cast<CastInst>(FalseVal)->getOperand(0),
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005132 LHS, RHS, Depth);
Sanjay Patel9a399792017-12-26 15:09:19 +00005133 }
James Molloy270ef8c2015-05-15 16:04:50 +00005134 }
James Molloy134bec22015-08-11 09:12:57 +00005135 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005136 LHS, RHS, Depth);
James Molloy270ef8c2015-05-15 16:04:50 +00005137}
Sanjoy Dasa7e13782015-10-24 05:37:35 +00005138
Sanjay Patel7ed0bc22018-03-06 16:57:55 +00005139CmpInst::Predicate llvm::getMinMaxPred(SelectPatternFlavor SPF, bool Ordered) {
5140 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
5141 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
5142 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
5143 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
5144 if (SPF == SPF_FMINNUM)
5145 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
5146 if (SPF == SPF_FMAXNUM)
5147 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
5148 llvm_unreachable("unhandled!");
5149}
5150
5151SelectPatternFlavor llvm::getInverseMinMaxFlavor(SelectPatternFlavor SPF) {
5152 if (SPF == SPF_SMIN) return SPF_SMAX;
5153 if (SPF == SPF_UMIN) return SPF_UMAX;
5154 if (SPF == SPF_SMAX) return SPF_SMIN;
5155 if (SPF == SPF_UMAX) return SPF_UMIN;
5156 llvm_unreachable("unhandled!");
5157}
5158
5159CmpInst::Predicate llvm::getInverseMinMaxPred(SelectPatternFlavor SPF) {
5160 return getMinMaxPred(getInverseMinMaxFlavor(SPF));
5161}
5162
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005163/// Return true if "icmp Pred LHS RHS" is always true.
Chad Rosiere42b44b2017-07-28 14:39:06 +00005164static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
5165 const Value *RHS, const DataLayout &DL,
5166 unsigned Depth) {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005167 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005168 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
5169 return true;
5170
5171 switch (Pred) {
5172 default:
5173 return false;
5174
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005175 case CmpInst::ICMP_SLE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005176 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005177
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005178 // LHS s<= LHS +_{nsw} C if C >= 0
Sanjoy Dasdc26df42015-11-11 00:16:41 +00005179 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005180 return !C->isNegative();
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005181 return false;
5182 }
5183
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005184 case CmpInst::ICMP_ULE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005185 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005186
Sanjoy Dasdc26df42015-11-11 00:16:41 +00005187 // LHS u<= LHS +_{nuw} C for any C
5188 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasc01b4d22015-11-06 19:01:03 +00005189 return true;
Sanjoy Das92568102015-11-10 23:56:20 +00005190
5191 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
Pete Cooper35b00d52016-08-13 01:05:32 +00005192 auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
5193 const Value *&X,
Sanjoy Das92568102015-11-10 23:56:20 +00005194 const APInt *&CA, const APInt *&CB) {
5195 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
5196 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
5197 return true;
5198
5199 // If X & C == 0 then (X | C) == X +_{nuw} C
5200 if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
5201 match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
Craig Topperb45eabc2017-04-26 16:39:58 +00005202 KnownBits Known(CA->getBitWidth());
Chad Rosiere42b44b2017-07-28 14:39:06 +00005203 computeKnownBits(X, Known, DL, Depth + 1, /*AC*/ nullptr,
5204 /*CxtI*/ nullptr, /*DT*/ nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +00005205 if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
Sanjoy Das92568102015-11-10 23:56:20 +00005206 return true;
5207 }
5208
5209 return false;
5210 };
5211
Pete Cooper35b00d52016-08-13 01:05:32 +00005212 const Value *X;
Sanjoy Das92568102015-11-10 23:56:20 +00005213 const APInt *CLHS, *CRHS;
Sanjoy Dasdc26df42015-11-11 00:16:41 +00005214 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
5215 return CLHS->ule(*CRHS);
Sanjoy Das92568102015-11-10 23:56:20 +00005216
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005217 return false;
5218 }
5219 }
5220}
5221
5222/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
Chad Rosier41dd31f2016-04-20 19:15:26 +00005223/// ALHS ARHS" is true. Otherwise, return None.
5224static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00005225isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
Chad Rosiere42b44b2017-07-28 14:39:06 +00005226 const Value *ARHS, const Value *BLHS, const Value *BRHS,
5227 const DataLayout &DL, unsigned Depth) {
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005228 switch (Pred) {
5229 default:
Chad Rosier41dd31f2016-04-20 19:15:26 +00005230 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005231
5232 case CmpInst::ICMP_SLT:
5233 case CmpInst::ICMP_SLE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00005234 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth) &&
5235 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00005236 return true;
5237 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005238
5239 case CmpInst::ICMP_ULT:
5240 case CmpInst::ICMP_ULE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00005241 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth) &&
5242 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00005243 return true;
5244 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005245 }
5246}
5247
Chad Rosier226a7342016-05-05 17:41:19 +00005248/// Return true if the operands of the two compares match. IsSwappedOps is true
5249/// when the operands match, but are swapped.
Pete Cooper35b00d52016-08-13 01:05:32 +00005250static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
5251 const Value *BLHS, const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00005252 bool &IsSwappedOps) {
5253
5254 bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
5255 IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
5256 return IsMatchingOps || IsSwappedOps;
5257}
5258
Sanjay Patel798c5982018-12-19 16:49:18 +00005259/// Return true if "icmp1 APred X, Y" implies "icmp2 BPred X, Y" is true.
5260/// Return false if "icmp1 APred X, Y" implies "icmp2 BPred X, Y" is false.
5261/// Otherwise, return None if we can't infer anything.
Chad Rosier41dd31f2016-04-20 19:15:26 +00005262static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
Chad Rosier41dd31f2016-04-20 19:15:26 +00005263 CmpInst::Predicate BPred,
Sanjay Patel798c5982018-12-19 16:49:18 +00005264 bool AreSwappedOps) {
5265 // Canonicalize the predicate as if the operands were not commuted.
5266 if (AreSwappedOps)
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005267 BPred = ICmpInst::getSwappedPredicate(BPred);
Sanjay Patel798c5982018-12-19 16:49:18 +00005268
Chad Rosier99bc4802016-04-21 16:18:02 +00005269 if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005270 return true;
Chad Rosier99bc4802016-04-21 16:18:02 +00005271 if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
Chad Rosier41dd31f2016-04-20 19:15:26 +00005272 return false;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005273
Chad Rosier41dd31f2016-04-20 19:15:26 +00005274 return None;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005275}
5276
Sanjay Patel798c5982018-12-19 16:49:18 +00005277/// Return true if "icmp APred X, C1" implies "icmp BPred X, C2" is true.
5278/// Return false if "icmp APred X, C1" implies "icmp BPred X, C2" is false.
5279/// Otherwise, return None if we can't infer anything.
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005280static Optional<bool>
Sanjay Patel798c5982018-12-19 16:49:18 +00005281isImpliedCondMatchingImmOperands(CmpInst::Predicate APred,
Pete Cooper35b00d52016-08-13 01:05:32 +00005282 const ConstantInt *C1,
5283 CmpInst::Predicate BPred,
Sanjay Patel798c5982018-12-19 16:49:18 +00005284 const ConstantInt *C2) {
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005285 ConstantRange DomCR =
5286 ConstantRange::makeExactICmpRegion(APred, C1->getValue());
5287 ConstantRange CR =
5288 ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
5289 ConstantRange Intersection = DomCR.intersectWith(CR);
5290 ConstantRange Difference = DomCR.difference(CR);
5291 if (Intersection.isEmptySet())
5292 return false;
5293 if (Difference.isEmptySet())
5294 return true;
5295 return None;
5296}
5297
Chad Rosier2f498032017-07-28 18:47:43 +00005298/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
5299/// false. Otherwise, return None if we can't infer anything.
5300static Optional<bool> isImpliedCondICmps(const ICmpInst *LHS,
5301 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00005302 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00005303 unsigned Depth) {
5304 Value *ALHS = LHS->getOperand(0);
5305 Value *ARHS = LHS->getOperand(1);
Chad Rosiera72a9ff2017-07-06 20:00:25 +00005306 // The rest of the logic assumes the LHS condition is true. If that's not the
5307 // case, invert the predicate to make it so.
Chad Rosier2f498032017-07-28 18:47:43 +00005308 ICmpInst::Predicate APred =
Chad Rosierdfd1de62017-08-01 20:18:54 +00005309 LHSIsTrue ? LHS->getPredicate() : LHS->getInversePredicate();
Chad Rosier2f498032017-07-28 18:47:43 +00005310
5311 Value *BLHS = RHS->getOperand(0);
5312 Value *BRHS = RHS->getOperand(1);
5313 ICmpInst::Predicate BPred = RHS->getPredicate();
Chad Rosiere2cbd132016-04-25 17:23:36 +00005314
Chad Rosier226a7342016-05-05 17:41:19 +00005315 // Can we infer anything when the two compares have matching operands?
Sanjay Patel798c5982018-12-19 16:49:18 +00005316 bool AreSwappedOps;
5317 if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, AreSwappedOps)) {
Chad Rosier226a7342016-05-05 17:41:19 +00005318 if (Optional<bool> Implication = isImpliedCondMatchingOperands(
Sanjay Patel798c5982018-12-19 16:49:18 +00005319 APred, BPred, AreSwappedOps))
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005320 return Implication;
Chad Rosier226a7342016-05-05 17:41:19 +00005321 // No amount of additional analysis will infer the second condition, so
5322 // early exit.
5323 return None;
5324 }
5325
5326 // Can we infer anything when the LHS operands match and the RHS operands are
5327 // constants (not necessarily matching)?
5328 if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
5329 if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
Sanjay Patel798c5982018-12-19 16:49:18 +00005330 APred, cast<ConstantInt>(ARHS), BPred, cast<ConstantInt>(BRHS)))
Chad Rosier226a7342016-05-05 17:41:19 +00005331 return Implication;
5332 // No amount of additional analysis will infer the second condition, so
5333 // early exit.
5334 return None;
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005335 }
5336
Chad Rosier41dd31f2016-04-20 19:15:26 +00005337 if (APred == BPred)
Chad Rosiere42b44b2017-07-28 14:39:06 +00005338 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth);
Chad Rosier41dd31f2016-04-20 19:15:26 +00005339 return None;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00005340}
Chad Rosier2f498032017-07-28 18:47:43 +00005341
Chad Rosierf73a10d2017-08-01 19:22:36 +00005342/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
5343/// false. Otherwise, return None if we can't infer anything. We expect the
5344/// RHS to be an icmp and the LHS to be an 'and' or an 'or' instruction.
5345static Optional<bool> isImpliedCondAndOr(const BinaryOperator *LHS,
5346 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00005347 const DataLayout &DL, bool LHSIsTrue,
Chad Rosierf73a10d2017-08-01 19:22:36 +00005348 unsigned Depth) {
5349 // The LHS must be an 'or' or an 'and' instruction.
5350 assert((LHS->getOpcode() == Instruction::And ||
5351 LHS->getOpcode() == Instruction::Or) &&
5352 "Expected LHS to be 'and' or 'or'.");
5353
Davide Italiano1a943a92017-08-09 16:06:54 +00005354 assert(Depth <= MaxDepth && "Hit recursion limit");
Chad Rosierf73a10d2017-08-01 19:22:36 +00005355
5356 // If the result of an 'or' is false, then we know both legs of the 'or' are
5357 // false. Similarly, if the result of an 'and' is true, then we know both
5358 // legs of the 'and' are true.
5359 Value *ALHS, *ARHS;
Chad Rosierdfd1de62017-08-01 20:18:54 +00005360 if ((!LHSIsTrue && match(LHS, m_Or(m_Value(ALHS), m_Value(ARHS)))) ||
5361 (LHSIsTrue && match(LHS, m_And(m_Value(ALHS), m_Value(ARHS))))) {
Chad Rosierf73a10d2017-08-01 19:22:36 +00005362 // FIXME: Make this non-recursion.
5363 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00005364 isImpliedCondition(ALHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00005365 return Implication;
5366 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00005367 isImpliedCondition(ARHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00005368 return Implication;
5369 return None;
5370 }
5371 return None;
5372}
5373
Chad Rosier2f498032017-07-28 18:47:43 +00005374Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00005375 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00005376 unsigned Depth) {
Davide Italiano30e51942017-08-09 15:13:50 +00005377 // Bail out when we hit the limit.
5378 if (Depth == MaxDepth)
5379 return None;
5380
Chad Rosierf73a10d2017-08-01 19:22:36 +00005381 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
5382 // example.
Chad Rosier2f498032017-07-28 18:47:43 +00005383 if (LHS->getType() != RHS->getType())
5384 return None;
5385
5386 Type *OpTy = LHS->getType();
Chad Rosierf73a10d2017-08-01 19:22:36 +00005387 assert(OpTy->isIntOrIntVectorTy(1) && "Expected integer type only!");
Chad Rosier2f498032017-07-28 18:47:43 +00005388
5389 // LHS ==> RHS by definition
5390 if (LHS == RHS)
Chad Rosierdfd1de62017-08-01 20:18:54 +00005391 return LHSIsTrue;
Chad Rosier2f498032017-07-28 18:47:43 +00005392
Chad Rosierf73a10d2017-08-01 19:22:36 +00005393 // FIXME: Extending the code below to handle vectors.
Chad Rosier2f498032017-07-28 18:47:43 +00005394 if (OpTy->isVectorTy())
Chad Rosier2f498032017-07-28 18:47:43 +00005395 return None;
Chad Rosierf73a10d2017-08-01 19:22:36 +00005396
Chad Rosier2f498032017-07-28 18:47:43 +00005397 assert(OpTy->isIntegerTy(1) && "implied by above");
5398
Chad Rosier2f498032017-07-28 18:47:43 +00005399 // Both LHS and RHS are icmps.
Chad Rosierf73a10d2017-08-01 19:22:36 +00005400 const ICmpInst *LHSCmp = dyn_cast<ICmpInst>(LHS);
5401 const ICmpInst *RHSCmp = dyn_cast<ICmpInst>(RHS);
5402 if (LHSCmp && RHSCmp)
Chad Rosierdfd1de62017-08-01 20:18:54 +00005403 return isImpliedCondICmps(LHSCmp, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00005404
Chad Rosierf73a10d2017-08-01 19:22:36 +00005405 // The LHS should be an 'or' or an 'and' instruction. We expect the RHS to be
5406 // an icmp. FIXME: Add support for and/or on the RHS.
5407 const BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHS);
5408 if (LHSBO && RHSCmp) {
5409 if ((LHSBO->getOpcode() == Instruction::And ||
5410 LHSBO->getOpcode() == Instruction::Or))
Chad Rosierdfd1de62017-08-01 20:18:54 +00005411 return isImpliedCondAndOr(LHSBO, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00005412 }
Chad Rosierf73a10d2017-08-01 19:22:36 +00005413 return None;
Chad Rosier2f498032017-07-28 18:47:43 +00005414}
Sanjay Patel7d82d372018-12-02 13:26:03 +00005415
5416Optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
5417 const Instruction *ContextI,
5418 const DataLayout &DL) {
5419 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
5420 if (!ContextI || !ContextI->getParent())
5421 return None;
5422
5423 // TODO: This is a poor/cheap way to determine dominance. Should we use a
5424 // dominator tree (eg, from a SimplifyQuery) instead?
5425 const BasicBlock *ContextBB = ContextI->getParent();
5426 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
5427 if (!PredBB)
5428 return None;
5429
5430 // We need a conditional branch in the predecessor.
5431 Value *PredCond;
5432 BasicBlock *TrueBB, *FalseBB;
5433 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
5434 return None;
5435
5436 // The branch should get simplified. Don't bother simplifying this condition.
5437 if (TrueBB == FalseBB)
5438 return None;
5439
5440 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
5441 "Predecessor block does not point to successor?");
5442
5443 // Is this condition implied by the predecessor condition?
5444 bool CondIsTrue = TrueBB == ContextBB;
5445 return isImpliedCondition(PredCond, Cond, DL, CondIsTrue);
5446}
Nikita Popov49097592019-03-09 21:17:42 +00005447
5448static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower,
5449 APInt &Upper, const InstrInfoQuery &IIQ) {
5450 unsigned Width = Lower.getBitWidth();
5451 const APInt *C;
5452 switch (BO.getOpcode()) {
5453 case Instruction::Add:
5454 if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
5455 // FIXME: If we have both nuw and nsw, we should reduce the range further.
5456 if (IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(&BO))) {
5457 // 'add nuw x, C' produces [C, UINT_MAX].
5458 Lower = *C;
5459 } else if (IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(&BO))) {
5460 if (C->isNegative()) {
5461 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
5462 Lower = APInt::getSignedMinValue(Width);
5463 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
5464 } else {
5465 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
5466 Lower = APInt::getSignedMinValue(Width) + *C;
5467 Upper = APInt::getSignedMaxValue(Width) + 1;
5468 }
5469 }
5470 }
5471 break;
5472
5473 case Instruction::And:
5474 if (match(BO.getOperand(1), m_APInt(C)))
5475 // 'and x, C' produces [0, C].
5476 Upper = *C + 1;
5477 break;
5478
5479 case Instruction::Or:
5480 if (match(BO.getOperand(1), m_APInt(C)))
5481 // 'or x, C' produces [C, UINT_MAX].
5482 Lower = *C;
5483 break;
5484
5485 case Instruction::AShr:
5486 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
5487 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
5488 Lower = APInt::getSignedMinValue(Width).ashr(*C);
5489 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
5490 } else if (match(BO.getOperand(0), m_APInt(C))) {
5491 unsigned ShiftAmount = Width - 1;
5492 if (!C->isNullValue() && IIQ.isExact(&BO))
5493 ShiftAmount = C->countTrailingZeros();
5494 if (C->isNegative()) {
5495 // 'ashr C, x' produces [C, C >> (Width-1)]
5496 Lower = *C;
5497 Upper = C->ashr(ShiftAmount) + 1;
5498 } else {
5499 // 'ashr C, x' produces [C >> (Width-1), C]
5500 Lower = C->ashr(ShiftAmount);
5501 Upper = *C + 1;
5502 }
5503 }
5504 break;
5505
5506 case Instruction::LShr:
5507 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
5508 // 'lshr x, C' produces [0, UINT_MAX >> C].
5509 Upper = APInt::getAllOnesValue(Width).lshr(*C) + 1;
5510 } else if (match(BO.getOperand(0), m_APInt(C))) {
5511 // 'lshr C, x' produces [C >> (Width-1), C].
5512 unsigned ShiftAmount = Width - 1;
5513 if (!C->isNullValue() && IIQ.isExact(&BO))
5514 ShiftAmount = C->countTrailingZeros();
5515 Lower = C->lshr(ShiftAmount);
5516 Upper = *C + 1;
5517 }
5518 break;
5519
5520 case Instruction::Shl:
5521 if (match(BO.getOperand(0), m_APInt(C))) {
5522 if (IIQ.hasNoUnsignedWrap(&BO)) {
5523 // 'shl nuw C, x' produces [C, C << CLZ(C)]
5524 Lower = *C;
5525 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
5526 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
5527 if (C->isNegative()) {
5528 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
5529 unsigned ShiftAmount = C->countLeadingOnes() - 1;
5530 Lower = C->shl(ShiftAmount);
5531 Upper = *C + 1;
5532 } else {
5533 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
5534 unsigned ShiftAmount = C->countLeadingZeros() - 1;
5535 Lower = *C;
5536 Upper = C->shl(ShiftAmount) + 1;
5537 }
5538 }
5539 }
5540 break;
5541
5542 case Instruction::SDiv:
5543 if (match(BO.getOperand(1), m_APInt(C))) {
5544 APInt IntMin = APInt::getSignedMinValue(Width);
5545 APInt IntMax = APInt::getSignedMaxValue(Width);
5546 if (C->isAllOnesValue()) {
5547 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
5548 // where C != -1 and C != 0 and C != 1
5549 Lower = IntMin + 1;
5550 Upper = IntMax + 1;
5551 } else if (C->countLeadingZeros() < Width - 1) {
5552 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
5553 // where C != -1 and C != 0 and C != 1
5554 Lower = IntMin.sdiv(*C);
5555 Upper = IntMax.sdiv(*C);
5556 if (Lower.sgt(Upper))
5557 std::swap(Lower, Upper);
5558 Upper = Upper + 1;
5559 assert(Upper != Lower && "Upper part of range has wrapped!");
5560 }
5561 } else if (match(BO.getOperand(0), m_APInt(C))) {
5562 if (C->isMinSignedValue()) {
5563 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
5564 Lower = *C;
5565 Upper = Lower.lshr(1) + 1;
5566 } else {
5567 // 'sdiv C, x' produces [-|C|, |C|].
5568 Upper = C->abs() + 1;
5569 Lower = (-Upper) + 1;
5570 }
5571 }
5572 break;
5573
5574 case Instruction::UDiv:
5575 if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
5576 // 'udiv x, C' produces [0, UINT_MAX / C].
5577 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
5578 } else if (match(BO.getOperand(0), m_APInt(C))) {
5579 // 'udiv C, x' produces [0, C].
5580 Upper = *C + 1;
5581 }
5582 break;
5583
5584 case Instruction::SRem:
5585 if (match(BO.getOperand(1), m_APInt(C))) {
5586 // 'srem x, C' produces (-|C|, |C|).
5587 Upper = C->abs();
5588 Lower = (-Upper) + 1;
5589 }
5590 break;
5591
5592 case Instruction::URem:
5593 if (match(BO.getOperand(1), m_APInt(C)))
5594 // 'urem x, C' produces [0, C).
5595 Upper = *C;
5596 break;
5597
5598 default:
5599 break;
5600 }
5601}
5602
5603static void setLimitsForIntrinsic(const IntrinsicInst &II, APInt &Lower,
5604 APInt &Upper) {
5605 unsigned Width = Lower.getBitWidth();
5606 const APInt *C;
5607 switch (II.getIntrinsicID()) {
5608 case Intrinsic::uadd_sat:
5609 // uadd.sat(x, C) produces [C, UINT_MAX].
5610 if (match(II.getOperand(0), m_APInt(C)) ||
5611 match(II.getOperand(1), m_APInt(C)))
5612 Lower = *C;
5613 break;
5614 case Intrinsic::sadd_sat:
5615 if (match(II.getOperand(0), m_APInt(C)) ||
5616 match(II.getOperand(1), m_APInt(C))) {
5617 if (C->isNegative()) {
5618 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
5619 Lower = APInt::getSignedMinValue(Width);
5620 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
5621 } else {
5622 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
5623 Lower = APInt::getSignedMinValue(Width) + *C;
5624 Upper = APInt::getSignedMaxValue(Width) + 1;
5625 }
5626 }
5627 break;
5628 case Intrinsic::usub_sat:
5629 // usub.sat(C, x) produces [0, C].
5630 if (match(II.getOperand(0), m_APInt(C)))
5631 Upper = *C + 1;
5632 // usub.sat(x, C) produces [0, UINT_MAX - C].
5633 else if (match(II.getOperand(1), m_APInt(C)))
5634 Upper = APInt::getMaxValue(Width) - *C + 1;
5635 break;
5636 case Intrinsic::ssub_sat:
5637 if (match(II.getOperand(0), m_APInt(C))) {
5638 if (C->isNegative()) {
5639 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
5640 Lower = APInt::getSignedMinValue(Width);
5641 Upper = *C - APInt::getSignedMinValue(Width) + 1;
5642 } else {
5643 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
5644 Lower = *C - APInt::getSignedMaxValue(Width);
5645 Upper = APInt::getSignedMaxValue(Width) + 1;
5646 }
5647 } else if (match(II.getOperand(1), m_APInt(C))) {
5648 if (C->isNegative()) {
5649 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
5650 Lower = APInt::getSignedMinValue(Width) - *C;
5651 Upper = APInt::getSignedMaxValue(Width) + 1;
5652 } else {
5653 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
5654 Lower = APInt::getSignedMinValue(Width);
5655 Upper = APInt::getSignedMaxValue(Width) - *C + 1;
5656 }
5657 }
5658 break;
5659 default:
5660 break;
5661 }
5662}
5663
Nikita Popovf89343b2019-03-18 21:20:03 +00005664static void setLimitsForSelectPattern(const SelectInst &SI, APInt &Lower,
5665 APInt &Upper) {
5666 const Value *LHS, *RHS;
5667 SelectPatternResult R = matchSelectPattern(&SI, LHS, RHS);
5668 if (R.Flavor == SPF_UNKNOWN)
5669 return;
5670
5671 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
5672
Nikita Popov00b5eca2019-03-20 18:16:02 +00005673 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
5674 // If the negation part of the abs (in RHS) has the NSW flag,
5675 // then the result of abs(X) is [0..SIGNED_MAX],
5676 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
Nikita Popovf89343b2019-03-18 21:20:03 +00005677 Lower = APInt::getNullValue(BitWidth);
Nikita Popov00b5eca2019-03-20 18:16:02 +00005678 if (cast<Instruction>(RHS)->hasNoSignedWrap())
5679 Upper = APInt::getSignedMaxValue(BitWidth) + 1;
5680 else
5681 Upper = APInt::getSignedMinValue(BitWidth) + 1;
Nikita Popovf89343b2019-03-18 21:20:03 +00005682 return;
5683 }
5684
5685 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
5686 // The result of -abs(X) is <= 0.
5687 Lower = APInt::getSignedMinValue(BitWidth);
5688 Upper = APInt(BitWidth, 1);
5689 return;
5690 }
5691
Nikita Popov3e9770d2019-03-18 22:26:27 +00005692 // TODO Handle min/max flavors.
Nikita Popovf89343b2019-03-18 21:20:03 +00005693}
5694
Nikita Popov49097592019-03-09 21:17:42 +00005695ConstantRange llvm::computeConstantRange(const Value *V, bool UseInstrInfo) {
5696 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
5697
Nikita Popov20838192019-03-19 17:53:56 +00005698 const APInt *C;
5699 if (match(V, m_APInt(C)))
5700 return ConstantRange(*C);
5701
Nikita Popov49097592019-03-09 21:17:42 +00005702 InstrInfoQuery IIQ(UseInstrInfo);
5703 unsigned BitWidth = V->getType()->getScalarSizeInBits();
5704 APInt Lower = APInt(BitWidth, 0);
5705 APInt Upper = APInt(BitWidth, 0);
5706 if (auto *BO = dyn_cast<BinaryOperator>(V))
5707 setLimitsForBinOp(*BO, Lower, Upper, IIQ);
5708 else if (auto *II = dyn_cast<IntrinsicInst>(V))
5709 setLimitsForIntrinsic(*II, Lower, Upper);
Nikita Popovf89343b2019-03-18 21:20:03 +00005710 else if (auto *SI = dyn_cast<SelectInst>(V))
5711 setLimitsForSelectPattern(*SI, Lower, Upper);
Nikita Popov49097592019-03-09 21:17:42 +00005712
5713 ConstantRange CR = Lower != Upper ? ConstantRange(Lower, Upper)
Nikita Popov977934f2019-03-24 09:34:40 +00005714 : ConstantRange::getFull(BitWidth);
Nikita Popov49097592019-03-09 21:17:42 +00005715
5716 if (auto *I = dyn_cast<Instruction>(V))
5717 if (auto *Range = IIQ.getMetadata(I, LLVMContext::MD_range))
5718 CR = CR.intersectWith(getConstantRangeFromMetadata(*Range));
5719
5720 return CR;
5721}