Bug Summary

File:llvm/lib/Analysis/ConstantFolding.cpp
Warning:line 2663, column 35
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ConstantFolding.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Analysis -I /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis -I include -I /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-command-line-argument -Wno-unknown-warning-option -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/build-llvm -ferror-limit 19 -fvisibility-inlines-hidden -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-26-234817-15343-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp

/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp

1//===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines routines for folding instructions into constants.
10//
11// Also, to supplement the basic IR ConstantExpr simplifications,
12// this file defines some additional folding routines that can make use of
13// DataLayout information. These functions cannot go in IR due to library
14// dependency issues.
15//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/Analysis/ConstantFolding.h"
19#include "llvm/ADT/APFloat.h"
20#include "llvm/ADT/APInt.h"
21#include "llvm/ADT/APSInt.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/Analysis/TargetFolder.h"
28#include "llvm/Analysis/TargetLibraryInfo.h"
29#include "llvm/Analysis/ValueTracking.h"
30#include "llvm/Analysis/VectorUtils.h"
31#include "llvm/Config/config.h"
32#include "llvm/IR/Constant.h"
33#include "llvm/IR/Constants.h"
34#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/DerivedTypes.h"
36#include "llvm/IR/Function.h"
37#include "llvm/IR/GlobalValue.h"
38#include "llvm/IR/GlobalVariable.h"
39#include "llvm/IR/InstrTypes.h"
40#include "llvm/IR/Instruction.h"
41#include "llvm/IR/Instructions.h"
42#include "llvm/IR/IntrinsicInst.h"
43#include "llvm/IR/Intrinsics.h"
44#include "llvm/IR/IntrinsicsAArch64.h"
45#include "llvm/IR/IntrinsicsAMDGPU.h"
46#include "llvm/IR/IntrinsicsARM.h"
47#include "llvm/IR/IntrinsicsWebAssembly.h"
48#include "llvm/IR/IntrinsicsX86.h"
49#include "llvm/IR/Operator.h"
50#include "llvm/IR/Type.h"
51#include "llvm/IR/Value.h"
52#include "llvm/Support/Casting.h"
53#include "llvm/Support/ErrorHandling.h"
54#include "llvm/Support/KnownBits.h"
55#include "llvm/Support/MathExtras.h"
56#include <cassert>
57#include <cerrno>
58#include <cfenv>
59#include <cmath>
60#include <cstddef>
61#include <cstdint>
62
63using namespace llvm;
64
65namespace {
66Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
67 ArrayRef<Constant *> Ops,
68 const DataLayout &DL,
69 const TargetLibraryInfo *TLI,
70 bool ForLoadOperand);
71
72//===----------------------------------------------------------------------===//
73// Constant Folding internal helper functions
74//===----------------------------------------------------------------------===//
75
76static Constant *foldConstVectorToAPInt(APInt &Result, Type *DestTy,
77 Constant *C, Type *SrcEltTy,
78 unsigned NumSrcElts,
79 const DataLayout &DL) {
80 // Now that we know that the input value is a vector of integers, just shift
81 // and insert them into our result.
82 unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy);
83 for (unsigned i = 0; i != NumSrcElts; ++i) {
84 Constant *Element;
85 if (DL.isLittleEndian())
86 Element = C->getAggregateElement(NumSrcElts - i - 1);
87 else
88 Element = C->getAggregateElement(i);
89
90 if (Element && isa<UndefValue>(Element)) {
91 Result <<= BitShift;
92 continue;
93 }
94
95 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
96 if (!ElementCI)
97 return ConstantExpr::getBitCast(C, DestTy);
98
99 Result <<= BitShift;
100 Result |= ElementCI->getValue().zextOrSelf(Result.getBitWidth());
101 }
102
103 return nullptr;
104}
105
106/// Constant fold bitcast, symbolically evaluating it with DataLayout.
107/// This always returns a non-null constant, but it may be a
108/// ConstantExpr if unfoldable.
109Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
110 assert(CastInst::castIsValid(Instruction::BitCast, C, DestTy) &&(static_cast <bool> (CastInst::castIsValid(Instruction::
BitCast, C, DestTy) && "Invalid constantexpr bitcast!"
) ? void (0) : __assert_fail ("CastInst::castIsValid(Instruction::BitCast, C, DestTy) && \"Invalid constantexpr bitcast!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 111, __extension__ __PRETTY_FUNCTION__))
111 "Invalid constantexpr bitcast!")(static_cast <bool> (CastInst::castIsValid(Instruction::
BitCast, C, DestTy) && "Invalid constantexpr bitcast!"
) ? void (0) : __assert_fail ("CastInst::castIsValid(Instruction::BitCast, C, DestTy) && \"Invalid constantexpr bitcast!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 111, __extension__ __PRETTY_FUNCTION__))
;
112
113 // Catch the obvious splat cases.
114 if (C->isNullValue() && !DestTy->isX86_MMXTy() && !DestTy->isX86_AMXTy())
115 return Constant::getNullValue(DestTy);
116 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() && !DestTy->isX86_AMXTy() &&
117 !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
118 return Constant::getAllOnesValue(DestTy);
119
120 if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
121 // Handle a vector->scalar integer/fp cast.
122 if (isa<IntegerType>(DestTy) || DestTy->isFloatingPointTy()) {
123 unsigned NumSrcElts = cast<FixedVectorType>(VTy)->getNumElements();
124 Type *SrcEltTy = VTy->getElementType();
125
126 // If the vector is a vector of floating point, convert it to vector of int
127 // to simplify things.
128 if (SrcEltTy->isFloatingPointTy()) {
129 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
130 auto *SrcIVTy = FixedVectorType::get(
131 IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
132 // Ask IR to do the conversion now that #elts line up.
133 C = ConstantExpr::getBitCast(C, SrcIVTy);
134 }
135
136 APInt Result(DL.getTypeSizeInBits(DestTy), 0);
137 if (Constant *CE = foldConstVectorToAPInt(Result, DestTy, C,
138 SrcEltTy, NumSrcElts, DL))
139 return CE;
140
141 if (isa<IntegerType>(DestTy))
142 return ConstantInt::get(DestTy, Result);
143
144 APFloat FP(DestTy->getFltSemantics(), Result);
145 return ConstantFP::get(DestTy->getContext(), FP);
146 }
147 }
148
149 // The code below only handles casts to vectors currently.
150 auto *DestVTy = dyn_cast<VectorType>(DestTy);
151 if (!DestVTy)
152 return ConstantExpr::getBitCast(C, DestTy);
153
154 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
155 // vector so the code below can handle it uniformly.
156 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
157 Constant *Ops = C; // don't take the address of C!
158 return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
159 }
160
161 // If this is a bitcast from constant vector -> vector, fold it.
162 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
163 return ConstantExpr::getBitCast(C, DestTy);
164
165 // If the element types match, IR can fold it.
166 unsigned NumDstElt = cast<FixedVectorType>(DestVTy)->getNumElements();
167 unsigned NumSrcElt = cast<FixedVectorType>(C->getType())->getNumElements();
168 if (NumDstElt == NumSrcElt)
169 return ConstantExpr::getBitCast(C, DestTy);
170
171 Type *SrcEltTy = cast<VectorType>(C->getType())->getElementType();
172 Type *DstEltTy = DestVTy->getElementType();
173
174 // Otherwise, we're changing the number of elements in a vector, which
175 // requires endianness information to do the right thing. For example,
176 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
177 // folds to (little endian):
178 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
179 // and to (big endian):
180 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
181
182 // First thing is first. We only want to think about integer here, so if
183 // we have something in FP form, recast it as integer.
184 if (DstEltTy->isFloatingPointTy()) {
185 // Fold to an vector of integers with same size as our FP type.
186 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
187 auto *DestIVTy = FixedVectorType::get(
188 IntegerType::get(C->getContext(), FPWidth), NumDstElt);
189 // Recursively handle this integer conversion, if possible.
190 C = FoldBitCast(C, DestIVTy, DL);
191
192 // Finally, IR can handle this now that #elts line up.
193 return ConstantExpr::getBitCast(C, DestTy);
194 }
195
196 // Okay, we know the destination is integer, if the input is FP, convert
197 // it to integer first.
198 if (SrcEltTy->isFloatingPointTy()) {
199 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
200 auto *SrcIVTy = FixedVectorType::get(
201 IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
202 // Ask IR to do the conversion now that #elts line up.
203 C = ConstantExpr::getBitCast(C, SrcIVTy);
204 // If IR wasn't able to fold it, bail out.
205 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
206 !isa<ConstantDataVector>(C))
207 return C;
208 }
209
210 // Now we know that the input and output vectors are both integer vectors
211 // of the same size, and that their #elements is not the same. Do the
212 // conversion here, which depends on whether the input or output has
213 // more elements.
214 bool isLittleEndian = DL.isLittleEndian();
215
216 SmallVector<Constant*, 32> Result;
217 if (NumDstElt < NumSrcElt) {
218 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
219 Constant *Zero = Constant::getNullValue(DstEltTy);
220 unsigned Ratio = NumSrcElt/NumDstElt;
221 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
222 unsigned SrcElt = 0;
223 for (unsigned i = 0; i != NumDstElt; ++i) {
224 // Build each element of the result.
225 Constant *Elt = Zero;
226 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
227 for (unsigned j = 0; j != Ratio; ++j) {
228 Constant *Src = C->getAggregateElement(SrcElt++);
229 if (Src && isa<UndefValue>(Src))
230 Src = Constant::getNullValue(
231 cast<VectorType>(C->getType())->getElementType());
232 else
233 Src = dyn_cast_or_null<ConstantInt>(Src);
234 if (!Src) // Reject constantexpr elements.
235 return ConstantExpr::getBitCast(C, DestTy);
236
237 // Zero extend the element to the right size.
238 Src = ConstantExpr::getZExt(Src, Elt->getType());
239
240 // Shift it to the right place, depending on endianness.
241 Src = ConstantExpr::getShl(Src,
242 ConstantInt::get(Src->getType(), ShiftAmt));
243 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
244
245 // Mix it in.
246 Elt = ConstantExpr::getOr(Elt, Src);
247 }
248 Result.push_back(Elt);
249 }
250 return ConstantVector::get(Result);
251 }
252
253 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
254 unsigned Ratio = NumDstElt/NumSrcElt;
255 unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
256
257 // Loop over each source value, expanding into multiple results.
258 for (unsigned i = 0; i != NumSrcElt; ++i) {
259 auto *Element = C->getAggregateElement(i);
260
261 if (!Element) // Reject constantexpr elements.
262 return ConstantExpr::getBitCast(C, DestTy);
263
264 if (isa<UndefValue>(Element)) {
265 // Correctly Propagate undef values.
266 Result.append(Ratio, UndefValue::get(DstEltTy));
267 continue;
268 }
269
270 auto *Src = dyn_cast<ConstantInt>(Element);
271 if (!Src)
272 return ConstantExpr::getBitCast(C, DestTy);
273
274 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
275 for (unsigned j = 0; j != Ratio; ++j) {
276 // Shift the piece of the value into the right place, depending on
277 // endianness.
278 Constant *Elt = ConstantExpr::getLShr(Src,
279 ConstantInt::get(Src->getType(), ShiftAmt));
280 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
281
282 // Truncate the element to an integer with the same pointer size and
283 // convert the element back to a pointer using a inttoptr.
284 if (DstEltTy->isPointerTy()) {
285 IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
286 Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
287 Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
288 continue;
289 }
290
291 // Truncate and remember this piece.
292 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
293 }
294 }
295
296 return ConstantVector::get(Result);
297}
298
299} // end anonymous namespace
300
301/// If this constant is a constant offset from a global, return the global and
302/// the constant. Because of constantexprs, this function is recursive.
303bool llvm::IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
304 APInt &Offset, const DataLayout &DL,
305 DSOLocalEquivalent **DSOEquiv) {
306 if (DSOEquiv)
307 *DSOEquiv = nullptr;
308
309 // Trivial case, constant is the global.
310 if ((GV = dyn_cast<GlobalValue>(C))) {
311 unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType());
312 Offset = APInt(BitWidth, 0);
313 return true;
314 }
315
316 if (auto *FoundDSOEquiv = dyn_cast<DSOLocalEquivalent>(C)) {
317 if (DSOEquiv)
318 *DSOEquiv = FoundDSOEquiv;
319 GV = FoundDSOEquiv->getGlobalValue();
320 unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType());
321 Offset = APInt(BitWidth, 0);
322 return true;
323 }
324
325 // Otherwise, if this isn't a constant expr, bail out.
326 auto *CE = dyn_cast<ConstantExpr>(C);
327 if (!CE) return false;
328
329 // Look through ptr->int and ptr->ptr casts.
330 if (CE->getOpcode() == Instruction::PtrToInt ||
331 CE->getOpcode() == Instruction::BitCast)
332 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL,
333 DSOEquiv);
334
335 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
336 auto *GEP = dyn_cast<GEPOperator>(CE);
337 if (!GEP)
338 return false;
339
340 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
341 APInt TmpOffset(BitWidth, 0);
342
343 // If the base isn't a global+constant, we aren't either.
344 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL,
345 DSOEquiv))
346 return false;
347
348 // Otherwise, add any offset that our operands provide.
349 if (!GEP->accumulateConstantOffset(DL, TmpOffset))
350 return false;
351
352 Offset = TmpOffset;
353 return true;
354}
355
356Constant *llvm::ConstantFoldLoadThroughBitcast(Constant *C, Type *DestTy,
357 const DataLayout &DL) {
358 do {
359 Type *SrcTy = C->getType();
360 uint64_t DestSize = DL.getTypeSizeInBits(DestTy);
361 uint64_t SrcSize = DL.getTypeSizeInBits(SrcTy);
362 if (SrcSize < DestSize)
363 return nullptr;
364
365 // Catch the obvious splat cases (since all-zeros can coerce non-integral
366 // pointers legally).
367 if (C->isNullValue() && !DestTy->isX86_MMXTy() && !DestTy->isX86_AMXTy())
368 return Constant::getNullValue(DestTy);
369 if (C->isAllOnesValue() &&
370 (DestTy->isIntegerTy() || DestTy->isFloatingPointTy() ||
371 DestTy->isVectorTy()) &&
372 !DestTy->isX86_AMXTy() && !DestTy->isX86_MMXTy() &&
373 !DestTy->isPtrOrPtrVectorTy())
374 // Get ones when the input is trivial, but
375 // only for supported types inside getAllOnesValue.
376 return Constant::getAllOnesValue(DestTy);
377
378 // If the type sizes are the same and a cast is legal, just directly
379 // cast the constant.
380 // But be careful not to coerce non-integral pointers illegally.
381 if (SrcSize == DestSize &&
382 DL.isNonIntegralPointerType(SrcTy->getScalarType()) ==
383 DL.isNonIntegralPointerType(DestTy->getScalarType())) {
384 Instruction::CastOps Cast = Instruction::BitCast;
385 // If we are going from a pointer to int or vice versa, we spell the cast
386 // differently.
387 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
388 Cast = Instruction::IntToPtr;
389 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
390 Cast = Instruction::PtrToInt;
391
392 if (CastInst::castIsValid(Cast, C, DestTy))
393 return ConstantExpr::getCast(Cast, C, DestTy);
394 }
395
396 // If this isn't an aggregate type, there is nothing we can do to drill down
397 // and find a bitcastable constant.
398 if (!SrcTy->isAggregateType() && !SrcTy->isVectorTy())
399 return nullptr;
400
401 // We're simulating a load through a pointer that was bitcast to point to
402 // a different type, so we can try to walk down through the initial
403 // elements of an aggregate to see if some part of the aggregate is
404 // castable to implement the "load" semantic model.
405 if (SrcTy->isStructTy()) {
406 // Struct types might have leading zero-length elements like [0 x i32],
407 // which are certainly not what we are looking for, so skip them.
408 unsigned Elem = 0;
409 Constant *ElemC;
410 do {
411 ElemC = C->getAggregateElement(Elem++);
412 } while (ElemC && DL.getTypeSizeInBits(ElemC->getType()).isZero());
413 C = ElemC;
414 } else {
415 C = C->getAggregateElement(0u);
416 }
417 } while (C);
418
419 return nullptr;
420}
421
422namespace {
423
424/// Recursive helper to read bits out of global. C is the constant being copied
425/// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
426/// results into and BytesLeft is the number of bytes left in
427/// the CurPtr buffer. DL is the DataLayout.
428bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr,
429 unsigned BytesLeft, const DataLayout &DL) {
430 assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&(static_cast <bool> (ByteOffset <= DL.getTypeAllocSize
(C->getType()) && "Out of range access") ? void (0
) : __assert_fail ("ByteOffset <= DL.getTypeAllocSize(C->getType()) && \"Out of range access\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 431, __extension__ __PRETTY_FUNCTION__))
431 "Out of range access")(static_cast <bool> (ByteOffset <= DL.getTypeAllocSize
(C->getType()) && "Out of range access") ? void (0
) : __assert_fail ("ByteOffset <= DL.getTypeAllocSize(C->getType()) && \"Out of range access\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 431, __extension__ __PRETTY_FUNCTION__))
;
432
433 // If this element is zero or undefined, we can just return since *CurPtr is
434 // zero initialized.
435 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
436 return true;
437
438 if (auto *CI = dyn_cast<ConstantInt>(C)) {
439 if (CI->getBitWidth() > 64 ||
440 (CI->getBitWidth() & 7) != 0)
441 return false;
442
443 uint64_t Val = CI->getZExtValue();
444 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
445
446 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
447 int n = ByteOffset;
448 if (!DL.isLittleEndian())
449 n = IntBytes - n - 1;
450 CurPtr[i] = (unsigned char)(Val >> (n * 8));
451 ++ByteOffset;
452 }
453 return true;
454 }
455
456 if (auto *CFP = dyn_cast<ConstantFP>(C)) {
457 if (CFP->getType()->isDoubleTy()) {
458 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
459 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
460 }
461 if (CFP->getType()->isFloatTy()){
462 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
463 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
464 }
465 if (CFP->getType()->isHalfTy()){
466 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
467 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
468 }
469 return false;
470 }
471
472 if (auto *CS = dyn_cast<ConstantStruct>(C)) {
473 const StructLayout *SL = DL.getStructLayout(CS->getType());
474 unsigned Index = SL->getElementContainingOffset(ByteOffset);
475 uint64_t CurEltOffset = SL->getElementOffset(Index);
476 ByteOffset -= CurEltOffset;
477
478 while (true) {
479 // If the element access is to the element itself and not to tail padding,
480 // read the bytes from the element.
481 uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
482
483 if (ByteOffset < EltSize &&
484 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
485 BytesLeft, DL))
486 return false;
487
488 ++Index;
489
490 // Check to see if we read from the last struct element, if so we're done.
491 if (Index == CS->getType()->getNumElements())
492 return true;
493
494 // If we read all of the bytes we needed from this element we're done.
495 uint64_t NextEltOffset = SL->getElementOffset(Index);
496
497 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
498 return true;
499
500 // Move to the next element of the struct.
501 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
502 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
503 ByteOffset = 0;
504 CurEltOffset = NextEltOffset;
505 }
506 // not reached.
507 }
508
509 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
510 isa<ConstantDataSequential>(C)) {
511 uint64_t NumElts;
512 Type *EltTy;
513 if (auto *AT = dyn_cast<ArrayType>(C->getType())) {
514 NumElts = AT->getNumElements();
515 EltTy = AT->getElementType();
516 } else {
517 NumElts = cast<FixedVectorType>(C->getType())->getNumElements();
518 EltTy = cast<FixedVectorType>(C->getType())->getElementType();
519 }
520 uint64_t EltSize = DL.getTypeAllocSize(EltTy);
521 uint64_t Index = ByteOffset / EltSize;
522 uint64_t Offset = ByteOffset - Index * EltSize;
523
524 for (; Index != NumElts; ++Index) {
525 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
526 BytesLeft, DL))
527 return false;
528
529 uint64_t BytesWritten = EltSize - Offset;
530 assert(BytesWritten <= EltSize && "Not indexing into this element?")(static_cast <bool> (BytesWritten <= EltSize &&
"Not indexing into this element?") ? void (0) : __assert_fail
("BytesWritten <= EltSize && \"Not indexing into this element?\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 530, __extension__ __PRETTY_FUNCTION__))
;
531 if (BytesWritten >= BytesLeft)
532 return true;
533
534 Offset = 0;
535 BytesLeft -= BytesWritten;
536 CurPtr += BytesWritten;
537 }
538 return true;
539 }
540
541 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
542 if (CE->getOpcode() == Instruction::IntToPtr &&
543 CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
544 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
545 BytesLeft, DL);
546 }
547 }
548
549 // Otherwise, unknown initializer type.
550 return false;
551}
552
553Constant *FoldReinterpretLoadFromConstPtr(Constant *C, Type *LoadTy,
554 const DataLayout &DL) {
555 // Bail out early. Not expect to load from scalable global variable.
556 if (isa<ScalableVectorType>(LoadTy))
557 return nullptr;
558
559 auto *PTy = cast<PointerType>(C->getType());
560 auto *IntType = dyn_cast<IntegerType>(LoadTy);
561
562 // If this isn't an integer load we can't fold it directly.
563 if (!IntType) {
564 unsigned AS = PTy->getAddressSpace();
565
566 // If this is a float/double load, we can try folding it as an int32/64 load
567 // and then bitcast the result. This can be useful for union cases. Note
568 // that address spaces don't matter here since we're not going to result in
569 // an actual new load.
570 Type *MapTy;
571 if (LoadTy->isHalfTy())
572 MapTy = Type::getInt16Ty(C->getContext());
573 else if (LoadTy->isFloatTy())
574 MapTy = Type::getInt32Ty(C->getContext());
575 else if (LoadTy->isDoubleTy())
576 MapTy = Type::getInt64Ty(C->getContext());
577 else if (LoadTy->isVectorTy()) {
578 MapTy = PointerType::getIntNTy(
579 C->getContext(), DL.getTypeSizeInBits(LoadTy).getFixedSize());
580 } else
581 return nullptr;
582
583 C = FoldBitCast(C, MapTy->getPointerTo(AS), DL);
584 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, MapTy, DL)) {
585 if (Res->isNullValue() && !LoadTy->isX86_MMXTy() &&
586 !LoadTy->isX86_AMXTy())
587 // Materializing a zero can be done trivially without a bitcast
588 return Constant::getNullValue(LoadTy);
589 Type *CastTy = LoadTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(LoadTy) : LoadTy;
590 Res = FoldBitCast(Res, CastTy, DL);
591 if (LoadTy->isPtrOrPtrVectorTy()) {
592 // For vector of pointer, we needed to first convert to a vector of integer, then do vector inttoptr
593 if (Res->isNullValue() && !LoadTy->isX86_MMXTy() &&
594 !LoadTy->isX86_AMXTy())
595 return Constant::getNullValue(LoadTy);
596 if (DL.isNonIntegralPointerType(LoadTy->getScalarType()))
597 // Be careful not to replace a load of an addrspace value with an inttoptr here
598 return nullptr;
599 Res = ConstantExpr::getCast(Instruction::IntToPtr, Res, LoadTy);
600 }
601 return Res;
602 }
603 return nullptr;
604 }
605
606 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
607 if (BytesLoaded > 32 || BytesLoaded == 0)
608 return nullptr;
609
610 GlobalValue *GVal;
611 APInt OffsetAI;
612 if (!IsConstantOffsetFromGlobal(C, GVal, OffsetAI, DL))
613 return nullptr;
614
615 auto *GV = dyn_cast<GlobalVariable>(GVal);
616 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
617 !GV->getInitializer()->getType()->isSized())
618 return nullptr;
619
620 int64_t Offset = OffsetAI.getSExtValue();
621 int64_t InitializerSize =
622 DL.getTypeAllocSize(GV->getInitializer()->getType()).getFixedSize();
623
624 // If we're not accessing anything in this constant, the result is undefined.
625 if (Offset <= -1 * static_cast<int64_t>(BytesLoaded))
626 return UndefValue::get(IntType);
627
628 // If we're not accessing anything in this constant, the result is undefined.
629 if (Offset >= InitializerSize)
630 return UndefValue::get(IntType);
631
632 unsigned char RawBytes[32] = {0};
633 unsigned char *CurPtr = RawBytes;
634 unsigned BytesLeft = BytesLoaded;
635
636 // If we're loading off the beginning of the global, some bytes may be valid.
637 if (Offset < 0) {
638 CurPtr += -Offset;
639 BytesLeft += Offset;
640 Offset = 0;
641 }
642
643 if (!ReadDataFromGlobal(GV->getInitializer(), Offset, CurPtr, BytesLeft, DL))
644 return nullptr;
645
646 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
647 if (DL.isLittleEndian()) {
648 ResultVal = RawBytes[BytesLoaded - 1];
649 for (unsigned i = 1; i != BytesLoaded; ++i) {
650 ResultVal <<= 8;
651 ResultVal |= RawBytes[BytesLoaded - 1 - i];
652 }
653 } else {
654 ResultVal = RawBytes[0];
655 for (unsigned i = 1; i != BytesLoaded; ++i) {
656 ResultVal <<= 8;
657 ResultVal |= RawBytes[i];
658 }
659 }
660
661 return ConstantInt::get(IntType->getContext(), ResultVal);
662}
663
664Constant *ConstantFoldLoadThroughBitcastExpr(ConstantExpr *CE, Type *DestTy,
665 const DataLayout &DL) {
666 auto *SrcPtr = CE->getOperand(0);
667 if (!SrcPtr->getType()->isPointerTy())
668 return nullptr;
669
670 return ConstantFoldLoadFromConstPtr(SrcPtr, DestTy, DL);
671}
672
673} // end anonymous namespace
674
675Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
676 const DataLayout &DL) {
677 // First, try the easy cases:
678 if (auto *GV = dyn_cast<GlobalVariable>(C))
679 if (GV->isConstant() && GV->hasDefinitiveInitializer())
680 return ConstantFoldLoadThroughBitcast(GV->getInitializer(), Ty, DL);
681
682 if (auto *GA = dyn_cast<GlobalAlias>(C))
683 if (GA->getAliasee() && !GA->isInterposable())
684 return ConstantFoldLoadFromConstPtr(GA->getAliasee(), Ty, DL);
685
686 // If the loaded value isn't a constant expr, we can't handle it.
687 auto *CE = dyn_cast<ConstantExpr>(C);
688 if (!CE)
689 return nullptr;
690
691 if (CE->getOpcode() == Instruction::GetElementPtr) {
692 if (auto *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
693 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
694 if (Constant *V = ConstantFoldLoadThroughGEPConstantExpr(
695 GV->getInitializer(), CE, Ty, DL))
696 return V;
697 }
698 } else {
699 // Try to simplify GEP if the pointer operand wasn't a GlobalVariable.
700 // SymbolicallyEvaluateGEP() with `ForLoadOperand = true` can potentially
701 // simplify the GEP more than it normally would have been, but should only
702 // be used for const folding loads.
703 SmallVector<Constant *> Ops;
704 for (unsigned I = 0, E = CE->getNumOperands(); I != E; ++I)
705 Ops.push_back(cast<Constant>(CE->getOperand(I)));
706 if (auto *Simplified = dyn_cast_or_null<ConstantExpr>(
707 SymbolicallyEvaluateGEP(cast<GEPOperator>(CE), Ops, DL, nullptr,
708 /*ForLoadOperand*/ true))) {
709 // If the symbolically evaluated GEP is another GEP, we can only const
710 // fold it if the resulting pointer operand is a GlobalValue. Otherwise
711 // there is nothing else to simplify since the GEP is already in the
712 // most simplified form.
713 if (isa<GEPOperator>(Simplified)) {
714 if (auto *GV = dyn_cast<GlobalVariable>(Simplified->getOperand(0))) {
715 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
716 if (Constant *V = ConstantFoldLoadThroughGEPConstantExpr(
717 GV->getInitializer(), Simplified, Ty, DL))
718 return V;
719 }
720 }
721 } else {
722 return ConstantFoldLoadFromConstPtr(Simplified, Ty, DL);
723 }
724 }
725 }
726 }
727
728 if (CE->getOpcode() == Instruction::BitCast)
729 if (Constant *LoadedC = ConstantFoldLoadThroughBitcastExpr(CE, Ty, DL))
730 return LoadedC;
731
732 // Instead of loading constant c string, use corresponding integer value
733 // directly if string length is small enough.
734 StringRef Str;
735 if (getConstantStringInfo(CE, Str) && !Str.empty()) {
736 size_t StrLen = Str.size();
737 unsigned NumBits = Ty->getPrimitiveSizeInBits();
738 // Replace load with immediate integer if the result is an integer or fp
739 // value.
740 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
741 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
742 APInt StrVal(NumBits, 0);
743 APInt SingleChar(NumBits, 0);
744 if (DL.isLittleEndian()) {
745 for (unsigned char C : reverse(Str.bytes())) {
746 SingleChar = static_cast<uint64_t>(C);
747 StrVal = (StrVal << 8) | SingleChar;
748 }
749 } else {
750 for (unsigned char C : Str.bytes()) {
751 SingleChar = static_cast<uint64_t>(C);
752 StrVal = (StrVal << 8) | SingleChar;
753 }
754 // Append NULL at the end.
755 SingleChar = 0;
756 StrVal = (StrVal << 8) | SingleChar;
757 }
758
759 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
760 if (Ty->isFloatingPointTy())
761 Res = ConstantExpr::getBitCast(Res, Ty);
762 return Res;
763 }
764 }
765
766 // If this load comes from anywhere in a constant global, and if the global
767 // is all undef or zero, we know what it loads.
768 if (auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(CE))) {
769 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
770 if (GV->getInitializer()->isNullValue())
771 return Constant::getNullValue(Ty);
772 if (isa<UndefValue>(GV->getInitializer()))
773 return UndefValue::get(Ty);
774 }
775 }
776
777 // Try hard to fold loads from bitcasted strange and non-type-safe things.
778 return FoldReinterpretLoadFromConstPtr(CE, Ty, DL);
779}
780
781namespace {
782
783/// One of Op0/Op1 is a constant expression.
784/// Attempt to symbolically evaluate the result of a binary operator merging
785/// these together. If target data info is available, it is provided as DL,
786/// otherwise DL is null.
787Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1,
788 const DataLayout &DL) {
789 // SROA
790
791 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
792 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
793 // bits.
794
795 if (Opc == Instruction::And) {
796 KnownBits Known0 = computeKnownBits(Op0, DL);
797 KnownBits Known1 = computeKnownBits(Op1, DL);
798 if ((Known1.One | Known0.Zero).isAllOnesValue()) {
799 // All the bits of Op0 that the 'and' could be masking are already zero.
800 return Op0;
801 }
802 if ((Known0.One | Known1.Zero).isAllOnesValue()) {
803 // All the bits of Op1 that the 'and' could be masking are already zero.
804 return Op1;
805 }
806
807 Known0 &= Known1;
808 if (Known0.isConstant())
809 return ConstantInt::get(Op0->getType(), Known0.getConstant());
810 }
811
812 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
813 // constant. This happens frequently when iterating over a global array.
814 if (Opc == Instruction::Sub) {
815 GlobalValue *GV1, *GV2;
816 APInt Offs1, Offs2;
817
818 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
819 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
820 unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
821
822 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
823 // PtrToInt may change the bitwidth so we have convert to the right size
824 // first.
825 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
826 Offs2.zextOrTrunc(OpSize));
827 }
828 }
829
830 return nullptr;
831}
832
833/// If array indices are not pointer-sized integers, explicitly cast them so
834/// that they aren't implicitly casted by the getelementptr.
835Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
836 Type *ResultTy, Optional<unsigned> InRangeIndex,
837 const DataLayout &DL, const TargetLibraryInfo *TLI) {
838 Type *IntIdxTy = DL.getIndexType(ResultTy);
839 Type *IntIdxScalarTy = IntIdxTy->getScalarType();
840
841 bool Any = false;
842 SmallVector<Constant*, 32> NewIdxs;
843 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
844 if ((i == 1 ||
845 !isa<StructType>(GetElementPtrInst::getIndexedType(
846 SrcElemTy, Ops.slice(1, i - 1)))) &&
847 Ops[i]->getType()->getScalarType() != IntIdxScalarTy) {
848 Any = true;
849 Type *NewType = Ops[i]->getType()->isVectorTy()
850 ? IntIdxTy
851 : IntIdxScalarTy;
852 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
853 true,
854 NewType,
855 true),
856 Ops[i], NewType));
857 } else
858 NewIdxs.push_back(Ops[i]);
859 }
860
861 if (!Any)
862 return nullptr;
863
864 Constant *C = ConstantExpr::getGetElementPtr(
865 SrcElemTy, Ops[0], NewIdxs, /*InBounds=*/false, InRangeIndex);
866 return ConstantFoldConstant(C, DL, TLI);
867}
868
869/// Strip the pointer casts, but preserve the address space information.
870Constant *StripPtrCastKeepAS(Constant *Ptr, bool ForLoadOperand) {
871 assert(Ptr->getType()->isPointerTy() && "Not a pointer type")(static_cast <bool> (Ptr->getType()->isPointerTy(
) && "Not a pointer type") ? void (0) : __assert_fail
("Ptr->getType()->isPointerTy() && \"Not a pointer type\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 871, __extension__ __PRETTY_FUNCTION__))
;
872 auto *OldPtrTy = cast<PointerType>(Ptr->getType());
873 Ptr = cast<Constant>(Ptr->stripPointerCasts());
874 if (ForLoadOperand) {
875 while (isa<GlobalAlias>(Ptr) && !cast<GlobalAlias>(Ptr)->isInterposable() &&
876 !cast<GlobalAlias>(Ptr)->getBaseObject()->isInterposable()) {
877 Ptr = cast<GlobalAlias>(Ptr)->getAliasee();
878 }
879 }
880
881 auto *NewPtrTy = cast<PointerType>(Ptr->getType());
882
883 // Preserve the address space number of the pointer.
884 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
885 Ptr = ConstantExpr::getPointerCast(
886 Ptr, PointerType::getWithSamePointeeType(NewPtrTy,
887 OldPtrTy->getAddressSpace()));
888 }
889 return Ptr;
890}
891
892/// If we can symbolically evaluate the GEP constant expression, do so.
893Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
894 ArrayRef<Constant *> Ops,
895 const DataLayout &DL,
896 const TargetLibraryInfo *TLI,
897 bool ForLoadOperand) {
898 const GEPOperator *InnermostGEP = GEP;
899 bool InBounds = GEP->isInBounds();
900
901 Type *SrcElemTy = GEP->getSourceElementType();
902 Type *ResElemTy = GEP->getResultElementType();
903 Type *ResTy = GEP->getType();
904 if (!SrcElemTy->isSized() || isa<ScalableVectorType>(SrcElemTy))
905 return nullptr;
906
907 if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy,
908 GEP->getInRangeIndex(), DL, TLI))
909 return C;
910
911 Constant *Ptr = Ops[0];
912 if (!Ptr->getType()->isPointerTy())
913 return nullptr;
914
915 Type *IntIdxTy = DL.getIndexType(Ptr->getType());
916
917 // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
918 // "inttoptr (sub (ptrtoint Ptr), V)"
919 if (Ops.size() == 2 && ResElemTy->isIntegerTy(8)) {
920 auto *CE = dyn_cast<ConstantExpr>(Ops[1]);
921 assert((!CE || CE->getType() == IntIdxTy) &&(static_cast <bool> ((!CE || CE->getType() == IntIdxTy
) && "CastGEPIndices didn't canonicalize index types!"
) ? void (0) : __assert_fail ("(!CE || CE->getType() == IntIdxTy) && \"CastGEPIndices didn't canonicalize index types!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 922, __extension__ __PRETTY_FUNCTION__))
922 "CastGEPIndices didn't canonicalize index types!")(static_cast <bool> ((!CE || CE->getType() == IntIdxTy
) && "CastGEPIndices didn't canonicalize index types!"
) ? void (0) : __assert_fail ("(!CE || CE->getType() == IntIdxTy) && \"CastGEPIndices didn't canonicalize index types!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 922, __extension__ __PRETTY_FUNCTION__))
;
923 if (CE && CE->getOpcode() == Instruction::Sub &&
924 CE->getOperand(0)->isNullValue()) {
925 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
926 Res = ConstantExpr::getSub(Res, CE->getOperand(1));
927 Res = ConstantExpr::getIntToPtr(Res, ResTy);
928 return ConstantFoldConstant(Res, DL, TLI);
929 }
930 }
931
932 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
933 if (!isa<ConstantInt>(Ops[i]))
934 return nullptr;
935
936 unsigned BitWidth = DL.getTypeSizeInBits(IntIdxTy);
937 APInt Offset =
938 APInt(BitWidth,
939 DL.getIndexedOffsetInType(
940 SrcElemTy,
941 makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
942 Ptr = StripPtrCastKeepAS(Ptr, ForLoadOperand);
943
944 // If this is a GEP of a GEP, fold it all into a single GEP.
945 while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
946 InnermostGEP = GEP;
947 InBounds &= GEP->isInBounds();
948
949 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
950
951 // Do not try the incorporate the sub-GEP if some index is not a number.
952 bool AllConstantInt = true;
953 for (Value *NestedOp : NestedOps)
954 if (!isa<ConstantInt>(NestedOp)) {
955 AllConstantInt = false;
956 break;
957 }
958 if (!AllConstantInt)
959 break;
960
961 Ptr = cast<Constant>(GEP->getOperand(0));
962 SrcElemTy = GEP->getSourceElementType();
963 Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps));
964 Ptr = StripPtrCastKeepAS(Ptr, ForLoadOperand);
965 }
966
967 // If the base value for this address is a literal integer value, fold the
968 // getelementptr to the resulting integer value casted to the pointer type.
969 APInt BasePtr(BitWidth, 0);
970 if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) {
971 if (CE->getOpcode() == Instruction::IntToPtr) {
972 if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
973 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
974 }
975 }
976
977 auto *PTy = cast<PointerType>(Ptr->getType());
978 if ((Ptr->isNullValue() || BasePtr != 0) &&
979 !DL.isNonIntegralPointerType(PTy)) {
980 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
981 return ConstantExpr::getIntToPtr(C, ResTy);
982 }
983
984 // Otherwise form a regular getelementptr. Recompute the indices so that
985 // we eliminate over-indexing of the notional static type array bounds.
986 // This makes it easy to determine if the getelementptr is "inbounds".
987 // Also, this helps GlobalOpt do SROA on GlobalVariables.
988
989 // For GEPs of GlobalValues, use the value type even for opaque pointers.
990 // Otherwise use an i8 GEP.
991 if (auto *GV = dyn_cast<GlobalValue>(Ptr))
992 SrcElemTy = GV->getValueType();
993 else if (!PTy->isOpaque())
994 SrcElemTy = PTy->getElementType();
995 else
996 SrcElemTy = Type::getInt8Ty(Ptr->getContext());
997
998 if (!SrcElemTy->isSized())
999 return nullptr;
1000
1001 Type *ElemTy = SrcElemTy;
1002 SmallVector<APInt> Indices = DL.getGEPIndicesForOffset(ElemTy, Offset);
1003 if (Offset != 0)
1004 return nullptr;
1005
1006 // Try to add additional zero indices to reach the desired result element
1007 // type.
1008 // TODO: Should we avoid extra zero indices if ResElemTy can't be reached and
1009 // we'll have to insert a bitcast anyway?
1010 while (ElemTy != ResElemTy) {
1011 Type *NextTy = GetElementPtrInst::getTypeAtIndex(ElemTy, (uint64_t)0);
1012 if (!NextTy)
1013 break;
1014
1015 Indices.push_back(APInt::getZero(isa<StructType>(ElemTy) ? 32 : BitWidth));
1016 ElemTy = NextTy;
1017 }
1018
1019 SmallVector<Constant *, 32> NewIdxs;
1020 for (const APInt &Index : Indices)
1021 NewIdxs.push_back(ConstantInt::get(
1022 Type::getIntNTy(Ptr->getContext(), Index.getBitWidth()), Index));
1023
1024 // Preserve the inrange index from the innermost GEP if possible. We must
1025 // have calculated the same indices up to and including the inrange index.
1026 Optional<unsigned> InRangeIndex;
1027 if (Optional<unsigned> LastIRIndex = InnermostGEP->getInRangeIndex())
1028 if (SrcElemTy == InnermostGEP->getSourceElementType() &&
1029 NewIdxs.size() > *LastIRIndex) {
1030 InRangeIndex = LastIRIndex;
1031 for (unsigned I = 0; I <= *LastIRIndex; ++I)
1032 if (NewIdxs[I] != InnermostGEP->getOperand(I + 1))
1033 return nullptr;
1034 }
1035
1036 // Create a GEP.
1037 Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs,
1038 InBounds, InRangeIndex);
1039 assert((static_cast <bool> (cast<PointerType>(C->getType
())->isOpaqueOrPointeeTypeMatches(ElemTy) && "Computed GetElementPtr has unexpected type!"
) ? void (0) : __assert_fail ("cast<PointerType>(C->getType())->isOpaqueOrPointeeTypeMatches(ElemTy) && \"Computed GetElementPtr has unexpected type!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 1041, __extension__ __PRETTY_FUNCTION__))
1040 cast<PointerType>(C->getType())->isOpaqueOrPointeeTypeMatches(ElemTy) &&(static_cast <bool> (cast<PointerType>(C->getType
())->isOpaqueOrPointeeTypeMatches(ElemTy) && "Computed GetElementPtr has unexpected type!"
) ? void (0) : __assert_fail ("cast<PointerType>(C->getType())->isOpaqueOrPointeeTypeMatches(ElemTy) && \"Computed GetElementPtr has unexpected type!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 1041, __extension__ __PRETTY_FUNCTION__))
1041 "Computed GetElementPtr has unexpected type!")(static_cast <bool> (cast<PointerType>(C->getType
())->isOpaqueOrPointeeTypeMatches(ElemTy) && "Computed GetElementPtr has unexpected type!"
) ? void (0) : __assert_fail ("cast<PointerType>(C->getType())->isOpaqueOrPointeeTypeMatches(ElemTy) && \"Computed GetElementPtr has unexpected type!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 1041, __extension__ __PRETTY_FUNCTION__))
;
1042
1043 // If we ended up indexing a member with a type that doesn't match
1044 // the type of what the original indices indexed, add a cast.
1045 if (C->getType() != ResTy)
1046 C = FoldBitCast(C, ResTy, DL);
1047
1048 return C;
1049}
1050
1051/// Attempt to constant fold an instruction with the
1052/// specified opcode and operands. If successful, the constant result is
1053/// returned, if not, null is returned. Note that this function can fail when
1054/// attempting to fold instructions like loads and stores, which have no
1055/// constant expression form.
1056Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode,
1057 ArrayRef<Constant *> Ops,
1058 const DataLayout &DL,
1059 const TargetLibraryInfo *TLI) {
1060 Type *DestTy = InstOrCE->getType();
1061
1062 if (Instruction::isUnaryOp(Opcode))
1063 return ConstantFoldUnaryOpOperand(Opcode, Ops[0], DL);
1064
1065 if (Instruction::isBinaryOp(Opcode))
1066 return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
1067
1068 if (Instruction::isCast(Opcode))
1069 return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
1070
1071 if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
1072 if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI,
1073 /*ForLoadOperand*/ false))
1074 return C;
1075
1076 return ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), Ops[0],
1077 Ops.slice(1), GEP->isInBounds(),
1078 GEP->getInRangeIndex());
1079 }
1080
1081 if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE))
1082 return CE->getWithOperands(Ops);
1083
1084 switch (Opcode) {
1085 default: return nullptr;
1086 case Instruction::ICmp:
1087 case Instruction::FCmp: llvm_unreachable("Invalid for compares")::llvm::llvm_unreachable_internal("Invalid for compares", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 1087)
;
1088 case Instruction::Freeze:
1089 return isGuaranteedNotToBeUndefOrPoison(Ops[0]) ? Ops[0] : nullptr;
1090 case Instruction::Call:
1091 if (auto *F = dyn_cast<Function>(Ops.back())) {
1092 const auto *Call = cast<CallBase>(InstOrCE);
1093 if (canConstantFoldCallTo(Call, F))
1094 return ConstantFoldCall(Call, F, Ops.slice(0, Ops.size() - 1), TLI);
1095 }
1096 return nullptr;
1097 case Instruction::Select:
1098 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1099 case Instruction::ExtractElement:
1100 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1101 case Instruction::ExtractValue:
1102 return ConstantExpr::getExtractValue(
1103 Ops[0], cast<ExtractValueInst>(InstOrCE)->getIndices());
1104 case Instruction::InsertElement:
1105 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1106 case Instruction::ShuffleVector:
1107 return ConstantExpr::getShuffleVector(
1108 Ops[0], Ops[1], cast<ShuffleVectorInst>(InstOrCE)->getShuffleMask());
1109 }
1110}
1111
1112} // end anonymous namespace
1113
1114//===----------------------------------------------------------------------===//
1115// Constant Folding public APIs
1116//===----------------------------------------------------------------------===//
1117
1118namespace {
1119
1120Constant *
1121ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL,
1122 const TargetLibraryInfo *TLI,
1123 SmallDenseMap<Constant *, Constant *> &FoldedOps) {
1124 if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C))
1125 return const_cast<Constant *>(C);
1126
1127 SmallVector<Constant *, 8> Ops;
1128 for (const Use &OldU : C->operands()) {
1129 Constant *OldC = cast<Constant>(&OldU);
1130 Constant *NewC = OldC;
1131 // Recursively fold the ConstantExpr's operands. If we have already folded
1132 // a ConstantExpr, we don't have to process it again.
1133 if (isa<ConstantVector>(OldC) || isa<ConstantExpr>(OldC)) {
1134 auto It = FoldedOps.find(OldC);
1135 if (It == FoldedOps.end()) {
1136 NewC = ConstantFoldConstantImpl(OldC, DL, TLI, FoldedOps);
1137 FoldedOps.insert({OldC, NewC});
1138 } else {
1139 NewC = It->second;
1140 }
1141 }
1142 Ops.push_back(NewC);
1143 }
1144
1145 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1146 if (CE->isCompare())
1147 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
1148 DL, TLI);
1149
1150 return ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI);
1151 }
1152
1153 assert(isa<ConstantVector>(C))(static_cast <bool> (isa<ConstantVector>(C)) ? void
(0) : __assert_fail ("isa<ConstantVector>(C)", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 1153, __extension__ __PRETTY_FUNCTION__))
;
1154 return ConstantVector::get(Ops);
1155}
1156
1157} // end anonymous namespace
1158
1159Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
1160 const TargetLibraryInfo *TLI) {
1161 // Handle PHI nodes quickly here...
1162 if (auto *PN = dyn_cast<PHINode>(I)) {
1163 Constant *CommonValue = nullptr;
1164
1165 SmallDenseMap<Constant *, Constant *> FoldedOps;
1166 for (Value *Incoming : PN->incoming_values()) {
1167 // If the incoming value is undef then skip it. Note that while we could
1168 // skip the value if it is equal to the phi node itself we choose not to
1169 // because that would break the rule that constant folding only applies if
1170 // all operands are constants.
1171 if (isa<UndefValue>(Incoming))
1172 continue;
1173 // If the incoming value is not a constant, then give up.
1174 auto *C = dyn_cast<Constant>(Incoming);
1175 if (!C)
1176 return nullptr;
1177 // Fold the PHI's operands.
1178 C = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
1179 // If the incoming value is a different constant to
1180 // the one we saw previously, then give up.
1181 if (CommonValue && C != CommonValue)
1182 return nullptr;
1183 CommonValue = C;
1184 }
1185
1186 // If we reach here, all incoming values are the same constant or undef.
1187 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
1188 }
1189
1190 // Scan the operand list, checking to see if they are all constants, if so,
1191 // hand off to ConstantFoldInstOperandsImpl.
1192 if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); }))
1193 return nullptr;
1194
1195 SmallDenseMap<Constant *, Constant *> FoldedOps;
1196 SmallVector<Constant *, 8> Ops;
1197 for (const Use &OpU : I->operands()) {
1198 auto *Op = cast<Constant>(&OpU);
1199 // Fold the Instruction's operands.
1200 Op = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps);
1201 Ops.push_back(Op);
1202 }
1203
1204 if (const auto *CI = dyn_cast<CmpInst>(I))
1205 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
1206 DL, TLI);
1207
1208 if (const auto *LI = dyn_cast<LoadInst>(I)) {
1209 if (LI->isVolatile())
1210 return nullptr;
1211 return ConstantFoldLoadFromConstPtr(Ops[0], LI->getType(), DL);
1212 }
1213
1214 if (auto *IVI = dyn_cast<InsertValueInst>(I))
1215 return ConstantExpr::getInsertValue(Ops[0], Ops[1], IVI->getIndices());
1216
1217 if (auto *EVI = dyn_cast<ExtractValueInst>(I))
1218 return ConstantExpr::getExtractValue(Ops[0], EVI->getIndices());
1219
1220 return ConstantFoldInstOperands(I, Ops, DL, TLI);
1221}
1222
1223Constant *llvm::ConstantFoldConstant(const Constant *C, const DataLayout &DL,
1224 const TargetLibraryInfo *TLI) {
1225 SmallDenseMap<Constant *, Constant *> FoldedOps;
1226 return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
1227}
1228
1229Constant *llvm::ConstantFoldInstOperands(Instruction *I,
1230 ArrayRef<Constant *> Ops,
1231 const DataLayout &DL,
1232 const TargetLibraryInfo *TLI) {
1233 return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI);
1234}
1235
1236Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
1237 Constant *Ops0, Constant *Ops1,
1238 const DataLayout &DL,
1239 const TargetLibraryInfo *TLI) {
1240 // fold: icmp (inttoptr x), null -> icmp x, 0
1241 // fold: icmp null, (inttoptr x) -> icmp 0, x
1242 // fold: icmp (ptrtoint x), 0 -> icmp x, null
1243 // fold: icmp 0, (ptrtoint x) -> icmp null, x
1244 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
1245 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1246 //
1247 // FIXME: The following comment is out of data and the DataLayout is here now.
1248 // ConstantExpr::getCompare cannot do this, because it doesn't have DL
1249 // around to know if bit truncation is happening.
1250 if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1251 if (Ops1->isNullValue()) {
1252 if (CE0->getOpcode() == Instruction::IntToPtr) {
1253 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1254 // Convert the integer value to the right size to ensure we get the
1255 // proper extension or truncation.
1256 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1257 IntPtrTy, false);
1258 Constant *Null = Constant::getNullValue(C->getType());
1259 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1260 }
1261
1262 // Only do this transformation if the int is intptrty in size, otherwise
1263 // there is a truncation or extension that we aren't modeling.
1264 if (CE0->getOpcode() == Instruction::PtrToInt) {
1265 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1266 if (CE0->getType() == IntPtrTy) {
1267 Constant *C = CE0->getOperand(0);
1268 Constant *Null = Constant::getNullValue(C->getType());
1269 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1270 }
1271 }
1272 }
1273
1274 if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
1275 if (CE0->getOpcode() == CE1->getOpcode()) {
1276 if (CE0->getOpcode() == Instruction::IntToPtr) {
1277 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1278
1279 // Convert the integer value to the right size to ensure we get the
1280 // proper extension or truncation.
1281 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1282 IntPtrTy, false);
1283 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
1284 IntPtrTy, false);
1285 return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
1286 }
1287
1288 // Only do this transformation if the int is intptrty in size, otherwise
1289 // there is a truncation or extension that we aren't modeling.
1290 if (CE0->getOpcode() == Instruction::PtrToInt) {
1291 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1292 if (CE0->getType() == IntPtrTy &&
1293 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1294 return ConstantFoldCompareInstOperands(
1295 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
1296 }
1297 }
1298 }
1299 }
1300
1301 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1302 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1303 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1304 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
1305 Constant *LHS = ConstantFoldCompareInstOperands(
1306 Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1307 Constant *RHS = ConstantFoldCompareInstOperands(
1308 Predicate, CE0->getOperand(1), Ops1, DL, TLI);
1309 unsigned OpC =
1310 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1311 return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL);
1312 }
1313 } else if (isa<ConstantExpr>(Ops1)) {
1314 // If RHS is a constant expression, but the left side isn't, swap the
1315 // operands and try again.
1316 Predicate = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)Predicate);
1317 return ConstantFoldCompareInstOperands(Predicate, Ops1, Ops0, DL, TLI);
1318 }
1319
1320 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
1321}
1322
1323Constant *llvm::ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op,
1324 const DataLayout &DL) {
1325 assert(Instruction::isUnaryOp(Opcode))(static_cast <bool> (Instruction::isUnaryOp(Opcode)) ? void
(0) : __assert_fail ("Instruction::isUnaryOp(Opcode)", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 1325, __extension__ __PRETTY_FUNCTION__))
;
1326
1327 return ConstantExpr::get(Opcode, Op);
1328}
1329
1330Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS,
1331 Constant *RHS,
1332 const DataLayout &DL) {
1333 assert(Instruction::isBinaryOp(Opcode))(static_cast <bool> (Instruction::isBinaryOp(Opcode)) ?
void (0) : __assert_fail ("Instruction::isBinaryOp(Opcode)",
"/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 1333, __extension__ __PRETTY_FUNCTION__))
;
1334 if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1335 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1336 return C;
1337
1338 return ConstantExpr::get(Opcode, LHS, RHS);
1339}
1340
1341Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1342 Type *DestTy, const DataLayout &DL) {
1343 assert(Instruction::isCast(Opcode))(static_cast <bool> (Instruction::isCast(Opcode)) ? void
(0) : __assert_fail ("Instruction::isCast(Opcode)", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 1343, __extension__ __PRETTY_FUNCTION__))
;
1344 switch (Opcode) {
1345 default:
1346 llvm_unreachable("Missing case")::llvm::llvm_unreachable_internal("Missing case", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 1346)
;
1347 case Instruction::PtrToInt:
1348 // If the input is a inttoptr, eliminate the pair. This requires knowing
1349 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
1350 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1351 if (CE->getOpcode() == Instruction::IntToPtr) {
1352 Constant *Input = CE->getOperand(0);
1353 unsigned InWidth = Input->getType()->getScalarSizeInBits();
1354 unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
1355 if (PtrWidth < InWidth) {
1356 Constant *Mask =
1357 ConstantInt::get(CE->getContext(),
1358 APInt::getLowBitsSet(InWidth, PtrWidth));
1359 Input = ConstantExpr::getAnd(Input, Mask);
1360 }
1361 // Do a zext or trunc to get to the dest size.
1362 return ConstantExpr::getIntegerCast(Input, DestTy, false);
1363 }
1364 }
1365 return ConstantExpr::getCast(Opcode, C, DestTy);
1366 case Instruction::IntToPtr:
1367 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1368 // the int size is >= the ptr size and the address spaces are the same.
1369 // This requires knowing the width of a pointer, so it can't be done in
1370 // ConstantExpr::getCast.
1371 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1372 if (CE->getOpcode() == Instruction::PtrToInt) {
1373 Constant *SrcPtr = CE->getOperand(0);
1374 unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1375 unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1376
1377 if (MidIntSize >= SrcPtrSize) {
1378 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1379 if (SrcAS == DestTy->getPointerAddressSpace())
1380 return FoldBitCast(CE->getOperand(0), DestTy, DL);
1381 }
1382 }
1383 }
1384
1385 return ConstantExpr::getCast(Opcode, C, DestTy);
1386 case Instruction::Trunc:
1387 case Instruction::ZExt:
1388 case Instruction::SExt:
1389 case Instruction::FPTrunc:
1390 case Instruction::FPExt:
1391 case Instruction::UIToFP:
1392 case Instruction::SIToFP:
1393 case Instruction::FPToUI:
1394 case Instruction::FPToSI:
1395 case Instruction::AddrSpaceCast:
1396 return ConstantExpr::getCast(Opcode, C, DestTy);
1397 case Instruction::BitCast:
1398 return FoldBitCast(C, DestTy, DL);
1399 }
1400}
1401
1402Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
1403 ConstantExpr *CE,
1404 Type *Ty,
1405 const DataLayout &DL) {
1406 if (!CE->getOperand(1)->isNullValue())
1407 return nullptr; // Do not allow stepping over the value!
1408
1409 // Loop over all of the operands, tracking down which value we are
1410 // addressing.
1411 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1412 C = C->getAggregateElement(CE->getOperand(i));
1413 if (!C)
1414 return nullptr;
1415 }
1416 return ConstantFoldLoadThroughBitcast(C, Ty, DL);
1417}
1418
1419Constant *
1420llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1421 ArrayRef<Constant *> Indices) {
1422 // Loop over all of the operands, tracking down which value we are
1423 // addressing.
1424 for (Constant *Index : Indices) {
1425 C = C->getAggregateElement(Index);
1426 if (!C)
1427 return nullptr;
1428 }
1429 return C;
1430}
1431
1432//===----------------------------------------------------------------------===//
1433// Constant Folding for Calls
1434//
1435
1436bool llvm::canConstantFoldCallTo(const CallBase *Call, const Function *F) {
1437 if (Call->isNoBuiltin())
1438 return false;
1439 switch (F->getIntrinsicID()) {
1440 // Operations that do not operate floating-point numbers and do not depend on
1441 // FP environment can be folded even in strictfp functions.
1442 case Intrinsic::bswap:
1443 case Intrinsic::ctpop:
1444 case Intrinsic::ctlz:
1445 case Intrinsic::cttz:
1446 case Intrinsic::fshl:
1447 case Intrinsic::fshr:
1448 case Intrinsic::launder_invariant_group:
1449 case Intrinsic::strip_invariant_group:
1450 case Intrinsic::masked_load:
1451 case Intrinsic::get_active_lane_mask:
1452 case Intrinsic::abs:
1453 case Intrinsic::smax:
1454 case Intrinsic::smin:
1455 case Intrinsic::umax:
1456 case Intrinsic::umin:
1457 case Intrinsic::sadd_with_overflow:
1458 case Intrinsic::uadd_with_overflow:
1459 case Intrinsic::ssub_with_overflow:
1460 case Intrinsic::usub_with_overflow:
1461 case Intrinsic::smul_with_overflow:
1462 case Intrinsic::umul_with_overflow:
1463 case Intrinsic::sadd_sat:
1464 case Intrinsic::uadd_sat:
1465 case Intrinsic::ssub_sat:
1466 case Intrinsic::usub_sat:
1467 case Intrinsic::smul_fix:
1468 case Intrinsic::smul_fix_sat:
1469 case Intrinsic::bitreverse:
1470 case Intrinsic::is_constant:
1471 case Intrinsic::vector_reduce_add:
1472 case Intrinsic::vector_reduce_mul:
1473 case Intrinsic::vector_reduce_and:
1474 case Intrinsic::vector_reduce_or:
1475 case Intrinsic::vector_reduce_xor:
1476 case Intrinsic::vector_reduce_smin:
1477 case Intrinsic::vector_reduce_smax:
1478 case Intrinsic::vector_reduce_umin:
1479 case Intrinsic::vector_reduce_umax:
1480 // Target intrinsics
1481 case Intrinsic::amdgcn_perm:
1482 case Intrinsic::arm_mve_vctp8:
1483 case Intrinsic::arm_mve_vctp16:
1484 case Intrinsic::arm_mve_vctp32:
1485 case Intrinsic::arm_mve_vctp64:
1486 case Intrinsic::aarch64_sve_convert_from_svbool:
1487 // WebAssembly float semantics are always known
1488 case Intrinsic::wasm_trunc_signed:
1489 case Intrinsic::wasm_trunc_unsigned:
1490 return true;
1491
1492 // Floating point operations cannot be folded in strictfp functions in
1493 // general case. They can be folded if FP environment is known to compiler.
1494 case Intrinsic::minnum:
1495 case Intrinsic::maxnum:
1496 case Intrinsic::minimum:
1497 case Intrinsic::maximum:
1498 case Intrinsic::log:
1499 case Intrinsic::log2:
1500 case Intrinsic::log10:
1501 case Intrinsic::exp:
1502 case Intrinsic::exp2:
1503 case Intrinsic::sqrt:
1504 case Intrinsic::sin:
1505 case Intrinsic::cos:
1506 case Intrinsic::pow:
1507 case Intrinsic::powi:
1508 case Intrinsic::fma:
1509 case Intrinsic::fmuladd:
1510 case Intrinsic::fptoui_sat:
1511 case Intrinsic::fptosi_sat:
1512 case Intrinsic::convert_from_fp16:
1513 case Intrinsic::convert_to_fp16:
1514 case Intrinsic::amdgcn_cos:
1515 case Intrinsic::amdgcn_cubeid:
1516 case Intrinsic::amdgcn_cubema:
1517 case Intrinsic::amdgcn_cubesc:
1518 case Intrinsic::amdgcn_cubetc:
1519 case Intrinsic::amdgcn_fmul_legacy:
1520 case Intrinsic::amdgcn_fma_legacy:
1521 case Intrinsic::amdgcn_fract:
1522 case Intrinsic::amdgcn_ldexp:
1523 case Intrinsic::amdgcn_sin:
1524 // The intrinsics below depend on rounding mode in MXCSR.
1525 case Intrinsic::x86_sse_cvtss2si:
1526 case Intrinsic::x86_sse_cvtss2si64:
1527 case Intrinsic::x86_sse_cvttss2si:
1528 case Intrinsic::x86_sse_cvttss2si64:
1529 case Intrinsic::x86_sse2_cvtsd2si:
1530 case Intrinsic::x86_sse2_cvtsd2si64:
1531 case Intrinsic::x86_sse2_cvttsd2si:
1532 case Intrinsic::x86_sse2_cvttsd2si64:
1533 case Intrinsic::x86_avx512_vcvtss2si32:
1534 case Intrinsic::x86_avx512_vcvtss2si64:
1535 case Intrinsic::x86_avx512_cvttss2si:
1536 case Intrinsic::x86_avx512_cvttss2si64:
1537 case Intrinsic::x86_avx512_vcvtsd2si32:
1538 case Intrinsic::x86_avx512_vcvtsd2si64:
1539 case Intrinsic::x86_avx512_cvttsd2si:
1540 case Intrinsic::x86_avx512_cvttsd2si64:
1541 case Intrinsic::x86_avx512_vcvtss2usi32:
1542 case Intrinsic::x86_avx512_vcvtss2usi64:
1543 case Intrinsic::x86_avx512_cvttss2usi:
1544 case Intrinsic::x86_avx512_cvttss2usi64:
1545 case Intrinsic::x86_avx512_vcvtsd2usi32:
1546 case Intrinsic::x86_avx512_vcvtsd2usi64:
1547 case Intrinsic::x86_avx512_cvttsd2usi:
1548 case Intrinsic::x86_avx512_cvttsd2usi64:
1549 return !Call->isStrictFP();
1550
1551 // Sign operations are actually bitwise operations, they do not raise
1552 // exceptions even for SNANs.
1553 case Intrinsic::fabs:
1554 case Intrinsic::copysign:
1555 // Non-constrained variants of rounding operations means default FP
1556 // environment, they can be folded in any case.
1557 case Intrinsic::ceil:
1558 case Intrinsic::floor:
1559 case Intrinsic::round:
1560 case Intrinsic::roundeven:
1561 case Intrinsic::trunc:
1562 case Intrinsic::nearbyint:
1563 case Intrinsic::rint:
1564 // Constrained intrinsics can be folded if FP environment is known
1565 // to compiler.
1566 case Intrinsic::experimental_constrained_fma:
1567 case Intrinsic::experimental_constrained_fmuladd:
1568 case Intrinsic::experimental_constrained_fadd:
1569 case Intrinsic::experimental_constrained_fsub:
1570 case Intrinsic::experimental_constrained_fmul:
1571 case Intrinsic::experimental_constrained_fdiv:
1572 case Intrinsic::experimental_constrained_frem:
1573 case Intrinsic::experimental_constrained_ceil:
1574 case Intrinsic::experimental_constrained_floor:
1575 case Intrinsic::experimental_constrained_round:
1576 case Intrinsic::experimental_constrained_roundeven:
1577 case Intrinsic::experimental_constrained_trunc:
1578 case Intrinsic::experimental_constrained_nearbyint:
1579 case Intrinsic::experimental_constrained_rint:
1580 return true;
1581 default:
1582 return false;
1583 case Intrinsic::not_intrinsic: break;
1584 }
1585
1586 if (!F->hasName() || Call->isStrictFP())
1587 return false;
1588
1589 // In these cases, the check of the length is required. We don't want to
1590 // return true for a name like "cos\0blah" which strcmp would return equal to
1591 // "cos", but has length 8.
1592 StringRef Name = F->getName();
1593 switch (Name[0]) {
1594 default:
1595 return false;
1596 case 'a':
1597 return Name == "acos" || Name == "acosf" ||
1598 Name == "asin" || Name == "asinf" ||
1599 Name == "atan" || Name == "atanf" ||
1600 Name == "atan2" || Name == "atan2f";
1601 case 'c':
1602 return Name == "ceil" || Name == "ceilf" ||
1603 Name == "cos" || Name == "cosf" ||
1604 Name == "cosh" || Name == "coshf";
1605 case 'e':
1606 return Name == "exp" || Name == "expf" ||
1607 Name == "exp2" || Name == "exp2f";
1608 case 'f':
1609 return Name == "fabs" || Name == "fabsf" ||
1610 Name == "floor" || Name == "floorf" ||
1611 Name == "fmod" || Name == "fmodf";
1612 case 'l':
1613 return Name == "log" || Name == "logf" ||
1614 Name == "log2" || Name == "log2f" ||
1615 Name == "log10" || Name == "log10f";
1616 case 'n':
1617 return Name == "nearbyint" || Name == "nearbyintf";
1618 case 'p':
1619 return Name == "pow" || Name == "powf";
1620 case 'r':
1621 return Name == "remainder" || Name == "remainderf" ||
1622 Name == "rint" || Name == "rintf" ||
1623 Name == "round" || Name == "roundf";
1624 case 's':
1625 return Name == "sin" || Name == "sinf" ||
1626 Name == "sinh" || Name == "sinhf" ||
1627 Name == "sqrt" || Name == "sqrtf";
1628 case 't':
1629 return Name == "tan" || Name == "tanf" ||
1630 Name == "tanh" || Name == "tanhf" ||
1631 Name == "trunc" || Name == "truncf";
1632 case '_':
1633 // Check for various function names that get used for the math functions
1634 // when the header files are preprocessed with the macro
1635 // __FINITE_MATH_ONLY__ enabled.
1636 // The '12' here is the length of the shortest name that can match.
1637 // We need to check the size before looking at Name[1] and Name[2]
1638 // so we may as well check a limit that will eliminate mismatches.
1639 if (Name.size() < 12 || Name[1] != '_')
1640 return false;
1641 switch (Name[2]) {
1642 default:
1643 return false;
1644 case 'a':
1645 return Name == "__acos_finite" || Name == "__acosf_finite" ||
1646 Name == "__asin_finite" || Name == "__asinf_finite" ||
1647 Name == "__atan2_finite" || Name == "__atan2f_finite";
1648 case 'c':
1649 return Name == "__cosh_finite" || Name == "__coshf_finite";
1650 case 'e':
1651 return Name == "__exp_finite" || Name == "__expf_finite" ||
1652 Name == "__exp2_finite" || Name == "__exp2f_finite";
1653 case 'l':
1654 return Name == "__log_finite" || Name == "__logf_finite" ||
1655 Name == "__log10_finite" || Name == "__log10f_finite";
1656 case 'p':
1657 return Name == "__pow_finite" || Name == "__powf_finite";
1658 case 's':
1659 return Name == "__sinh_finite" || Name == "__sinhf_finite";
1660 }
1661 }
1662}
1663
1664namespace {
1665
1666Constant *GetConstantFoldFPValue(double V, Type *Ty) {
1667 if (Ty->isHalfTy() || Ty->isFloatTy()) {
1668 APFloat APF(V);
1669 bool unused;
1670 APF.convert(Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &unused);
1671 return ConstantFP::get(Ty->getContext(), APF);
1672 }
1673 if (Ty->isDoubleTy())
1674 return ConstantFP::get(Ty->getContext(), APFloat(V));
1675 llvm_unreachable("Can only constant fold half/float/double")::llvm::llvm_unreachable_internal("Can only constant fold half/float/double"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 1675)
;
1676}
1677
1678/// Clear the floating-point exception state.
1679inline void llvm_fenv_clearexcept() {
1680#if defined(HAVE_FENV_H1) && HAVE_DECL_FE_ALL_EXCEPT1
1681 feclearexcept(FE_ALL_EXCEPT(0x20 | 0x04 | 0x10 | 0x08 | 0x01));
1682#endif
1683 errno(*__errno_location ()) = 0;
1684}
1685
1686/// Test if a floating-point exception was raised.
1687inline bool llvm_fenv_testexcept() {
1688 int errno_val = errno(*__errno_location ());
1689 if (errno_val == ERANGE34 || errno_val == EDOM33)
1690 return true;
1691#if defined(HAVE_FENV_H1) && HAVE_DECL_FE_ALL_EXCEPT1 && HAVE_DECL_FE_INEXACT1
1692 if (fetestexcept(FE_ALL_EXCEPT(0x20 | 0x04 | 0x10 | 0x08 | 0x01) & ~FE_INEXACT0x20))
1693 return true;
1694#endif
1695 return false;
1696}
1697
1698Constant *ConstantFoldFP(double (*NativeFP)(double), const APFloat &V,
1699 Type *Ty) {
1700 llvm_fenv_clearexcept();
1701 double Result = NativeFP(V.convertToDouble());
1702 if (llvm_fenv_testexcept()) {
1703 llvm_fenv_clearexcept();
1704 return nullptr;
1705 }
1706
1707 return GetConstantFoldFPValue(Result, Ty);
1708}
1709
1710Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
1711 const APFloat &V, const APFloat &W, Type *Ty) {
1712 llvm_fenv_clearexcept();
1713 double Result = NativeFP(V.convertToDouble(), W.convertToDouble());
1714 if (llvm_fenv_testexcept()) {
1715 llvm_fenv_clearexcept();
1716 return nullptr;
1717 }
1718
1719 return GetConstantFoldFPValue(Result, Ty);
1720}
1721
1722Constant *constantFoldVectorReduce(Intrinsic::ID IID, Constant *Op) {
1723 FixedVectorType *VT = dyn_cast<FixedVectorType>(Op->getType());
1724 if (!VT)
1725 return nullptr;
1726
1727 // This isn't strictly necessary, but handle the special/common case of zero:
1728 // all integer reductions of a zero input produce zero.
1729 if (isa<ConstantAggregateZero>(Op))
1730 return ConstantInt::get(VT->getElementType(), 0);
1731
1732 // This is the same as the underlying binops - poison propagates.
1733 if (isa<PoisonValue>(Op) || Op->containsPoisonElement())
1734 return PoisonValue::get(VT->getElementType());
1735
1736 // TODO: Handle undef.
1737 if (!isa<ConstantVector>(Op) && !isa<ConstantDataVector>(Op))
1738 return nullptr;
1739
1740 auto *EltC = dyn_cast<ConstantInt>(Op->getAggregateElement(0U));
1741 if (!EltC)
1742 return nullptr;
1743
1744 APInt Acc = EltC->getValue();
1745 for (unsigned I = 1, E = VT->getNumElements(); I != E; I++) {
1746 if (!(EltC = dyn_cast<ConstantInt>(Op->getAggregateElement(I))))
1747 return nullptr;
1748 const APInt &X = EltC->getValue();
1749 switch (IID) {
1750 case Intrinsic::vector_reduce_add:
1751 Acc = Acc + X;
1752 break;
1753 case Intrinsic::vector_reduce_mul:
1754 Acc = Acc * X;
1755 break;
1756 case Intrinsic::vector_reduce_and:
1757 Acc = Acc & X;
1758 break;
1759 case Intrinsic::vector_reduce_or:
1760 Acc = Acc | X;
1761 break;
1762 case Intrinsic::vector_reduce_xor:
1763 Acc = Acc ^ X;
1764 break;
1765 case Intrinsic::vector_reduce_smin:
1766 Acc = APIntOps::smin(Acc, X);
1767 break;
1768 case Intrinsic::vector_reduce_smax:
1769 Acc = APIntOps::smax(Acc, X);
1770 break;
1771 case Intrinsic::vector_reduce_umin:
1772 Acc = APIntOps::umin(Acc, X);
1773 break;
1774 case Intrinsic::vector_reduce_umax:
1775 Acc = APIntOps::umax(Acc, X);
1776 break;
1777 }
1778 }
1779
1780 return ConstantInt::get(Op->getContext(), Acc);
1781}
1782
1783/// Attempt to fold an SSE floating point to integer conversion of a constant
1784/// floating point. If roundTowardZero is false, the default IEEE rounding is
1785/// used (toward nearest, ties to even). This matches the behavior of the
1786/// non-truncating SSE instructions in the default rounding mode. The desired
1787/// integer type Ty is used to select how many bits are available for the
1788/// result. Returns null if the conversion cannot be performed, otherwise
1789/// returns the Constant value resulting from the conversion.
1790Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
1791 Type *Ty, bool IsSigned) {
1792 // All of these conversion intrinsics form an integer of at most 64bits.
1793 unsigned ResultWidth = Ty->getIntegerBitWidth();
1794 assert(ResultWidth <= 64 &&(static_cast <bool> (ResultWidth <= 64 && "Can only constant fold conversions to 64 and 32 bit ints"
) ? void (0) : __assert_fail ("ResultWidth <= 64 && \"Can only constant fold conversions to 64 and 32 bit ints\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 1795, __extension__ __PRETTY_FUNCTION__))
1795 "Can only constant fold conversions to 64 and 32 bit ints")(static_cast <bool> (ResultWidth <= 64 && "Can only constant fold conversions to 64 and 32 bit ints"
) ? void (0) : __assert_fail ("ResultWidth <= 64 && \"Can only constant fold conversions to 64 and 32 bit ints\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 1795, __extension__ __PRETTY_FUNCTION__))
;
1796
1797 uint64_t UIntVal;
1798 bool isExact = false;
1799 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1800 : APFloat::rmNearestTiesToEven;
1801 APFloat::opStatus status =
1802 Val.convertToInteger(makeMutableArrayRef(UIntVal), ResultWidth,
1803 IsSigned, mode, &isExact);
1804 if (status != APFloat::opOK &&
1805 (!roundTowardZero || status != APFloat::opInexact))
1806 return nullptr;
1807 return ConstantInt::get(Ty, UIntVal, IsSigned);
1808}
1809
1810double getValueAsDouble(ConstantFP *Op) {
1811 Type *Ty = Op->getType();
1812
1813 if (Ty->isBFloatTy() || Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())
1814 return Op->getValueAPF().convertToDouble();
1815
1816 bool unused;
1817 APFloat APF = Op->getValueAPF();
1818 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &unused);
1819 return APF.convertToDouble();
1820}
1821
1822static bool getConstIntOrUndef(Value *Op, const APInt *&C) {
1823 if (auto *CI
25.1
'CI' is null
33.1
'CI' is non-null
25.1
'CI' is null
33.1
'CI' is non-null
25.1
'CI' is null
33.1
'CI' is non-null
= dyn_cast<ConstantInt>(Op)) {
25
Assuming 'Op' is not a 'ConstantInt'
26
Taking false branch
33
Assuming 'Op' is a 'ConstantInt'
34
Taking true branch
1824 C = &CI->getValue();
1825 return true;
35
Returning the value 1, which participates in a condition later
1826 }
1827 if (isa<UndefValue>(Op)) {
27
Assuming 'Op' is a 'UndefValue'
28
Taking true branch
1828 C = nullptr;
29
Null pointer value stored to 'C0'
1829 return true;
30
Returning the value 1, which participates in a condition later
1830 }
1831 return false;
1832}
1833
1834/// Checks if the given intrinsic call, which evaluates to constant, is allowed
1835/// to be folded.
1836///
1837/// \param CI Constrained intrinsic call.
1838/// \param St Exception flags raised during constant evaluation.
1839static bool mayFoldConstrained(ConstrainedFPIntrinsic *CI,
1840 APFloat::opStatus St) {
1841 Optional<RoundingMode> ORM = CI->getRoundingMode();
1842 Optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
1843
1844 // If the operation does not change exception status flags, it is safe
1845 // to fold.
1846 if (St == APFloat::opStatus::opOK) {
1847 // When FP exceptions are not ignored, intrinsic call will not be
1848 // eliminated, because it is considered as having side effect. But we
1849 // know that its evaluation does not raise exceptions, so side effect
1850 // is absent. To allow removing the call, mark it as not accessing memory.
1851 if (EB && *EB != fp::ExceptionBehavior::ebIgnore)
1852 CI->addFnAttr(Attribute::ReadNone);
1853 return true;
1854 }
1855
1856 // If evaluation raised FP exception, the result can depend on rounding
1857 // mode. If the latter is unknown, folding is not possible.
1858 if (!ORM || *ORM == RoundingMode::Dynamic)
1859 return false;
1860
1861 // If FP exceptions are ignored, fold the call, even if such exception is
1862 // raised.
1863 if (!EB || *EB != fp::ExceptionBehavior::ebStrict)
1864 return true;
1865
1866 // Leave the calculation for runtime so that exception flags be correctly set
1867 // in hardware.
1868 return false;
1869}
1870
1871/// Returns the rounding mode that should be used for constant evaluation.
1872static RoundingMode
1873getEvaluationRoundingMode(const ConstrainedFPIntrinsic *CI) {
1874 Optional<RoundingMode> ORM = CI->getRoundingMode();
1875 if (!ORM || *ORM == RoundingMode::Dynamic)
1876 // Even if the rounding mode is unknown, try evaluating the operation.
1877 // If it does not raise inexact exception, rounding was not applied,
1878 // so the result is exact and does not depend on rounding mode. Whether
1879 // other FP exceptions are raised, it does not depend on rounding mode.
1880 return RoundingMode::NearestTiesToEven;
1881 return *ORM;
1882}
1883
1884static Constant *ConstantFoldScalarCall1(StringRef Name,
1885 Intrinsic::ID IntrinsicID,
1886 Type *Ty,
1887 ArrayRef<Constant *> Operands,
1888 const TargetLibraryInfo *TLI,
1889 const CallBase *Call) {
1890 assert(Operands.size() == 1 && "Wrong number of operands.")(static_cast <bool> (Operands.size() == 1 && "Wrong number of operands."
) ? void (0) : __assert_fail ("Operands.size() == 1 && \"Wrong number of operands.\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 1890, __extension__ __PRETTY_FUNCTION__))
;
1891
1892 if (IntrinsicID == Intrinsic::is_constant) {
1893 // We know we have a "Constant" argument. But we want to only
1894 // return true for manifest constants, not those that depend on
1895 // constants with unknowable values, e.g. GlobalValue or BlockAddress.
1896 if (Operands[0]->isManifestConstant())
1897 return ConstantInt::getTrue(Ty->getContext());
1898 return nullptr;
1899 }
1900 if (isa<UndefValue>(Operands[0])) {
1901 // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN.
1902 // ctpop() is between 0 and bitwidth, pick 0 for undef.
1903 // fptoui.sat and fptosi.sat can always fold to zero (for a zero input).
1904 if (IntrinsicID == Intrinsic::cos ||
1905 IntrinsicID == Intrinsic::ctpop ||
1906 IntrinsicID == Intrinsic::fptoui_sat ||
1907 IntrinsicID == Intrinsic::fptosi_sat)
1908 return Constant::getNullValue(Ty);
1909 if (IntrinsicID == Intrinsic::bswap ||
1910 IntrinsicID == Intrinsic::bitreverse ||
1911 IntrinsicID == Intrinsic::launder_invariant_group ||
1912 IntrinsicID == Intrinsic::strip_invariant_group)
1913 return Operands[0];
1914 }
1915
1916 if (isa<ConstantPointerNull>(Operands[0])) {
1917 // launder(null) == null == strip(null) iff in addrspace 0
1918 if (IntrinsicID == Intrinsic::launder_invariant_group ||
1919 IntrinsicID == Intrinsic::strip_invariant_group) {
1920 // If instruction is not yet put in a basic block (e.g. when cloning
1921 // a function during inlining), Call's caller may not be available.
1922 // So check Call's BB first before querying Call->getCaller.
1923 const Function *Caller =
1924 Call->getParent() ? Call->getCaller() : nullptr;
1925 if (Caller &&
1926 !NullPointerIsDefined(
1927 Caller, Operands[0]->getType()->getPointerAddressSpace())) {
1928 return Operands[0];
1929 }
1930 return nullptr;
1931 }
1932 }
1933
1934 if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
1935 if (IntrinsicID == Intrinsic::convert_to_fp16) {
1936 APFloat Val(Op->getValueAPF());
1937
1938 bool lost = false;
1939 Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &lost);
1940
1941 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
1942 }
1943
1944 APFloat U = Op->getValueAPF();
1945
1946 if (IntrinsicID == Intrinsic::wasm_trunc_signed ||
1947 IntrinsicID == Intrinsic::wasm_trunc_unsigned) {
1948 bool Signed = IntrinsicID == Intrinsic::wasm_trunc_signed;
1949
1950 if (U.isNaN())
1951 return nullptr;
1952
1953 unsigned Width = Ty->getIntegerBitWidth();
1954 APSInt Int(Width, !Signed);
1955 bool IsExact = false;
1956 APFloat::opStatus Status =
1957 U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact);
1958
1959 if (Status == APFloat::opOK || Status == APFloat::opInexact)
1960 return ConstantInt::get(Ty, Int);
1961
1962 return nullptr;
1963 }
1964
1965 if (IntrinsicID == Intrinsic::fptoui_sat ||
1966 IntrinsicID == Intrinsic::fptosi_sat) {
1967 // convertToInteger() already has the desired saturation semantics.
1968 APSInt Int(Ty->getIntegerBitWidth(),
1969 IntrinsicID == Intrinsic::fptoui_sat);
1970 bool IsExact;
1971 U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact);
1972 return ConstantInt::get(Ty, Int);
1973 }
1974
1975 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1976 return nullptr;
1977
1978 // Use internal versions of these intrinsics.
1979
1980 if (IntrinsicID == Intrinsic::nearbyint || IntrinsicID == Intrinsic::rint) {
1981 U.roundToIntegral(APFloat::rmNearestTiesToEven);
1982 return ConstantFP::get(Ty->getContext(), U);
1983 }
1984
1985 if (IntrinsicID == Intrinsic::round) {
1986 U.roundToIntegral(APFloat::rmNearestTiesToAway);
1987 return ConstantFP::get(Ty->getContext(), U);
1988 }
1989
1990 if (IntrinsicID == Intrinsic::roundeven) {
1991 U.roundToIntegral(APFloat::rmNearestTiesToEven);
1992 return ConstantFP::get(Ty->getContext(), U);
1993 }
1994
1995 if (IntrinsicID == Intrinsic::ceil) {
1996 U.roundToIntegral(APFloat::rmTowardPositive);
1997 return ConstantFP::get(Ty->getContext(), U);
1998 }
1999
2000 if (IntrinsicID == Intrinsic::floor) {
2001 U.roundToIntegral(APFloat::rmTowardNegative);
2002 return ConstantFP::get(Ty->getContext(), U);
2003 }
2004
2005 if (IntrinsicID == Intrinsic::trunc) {
2006 U.roundToIntegral(APFloat::rmTowardZero);
2007 return ConstantFP::get(Ty->getContext(), U);
2008 }
2009
2010 if (IntrinsicID == Intrinsic::fabs) {
2011 U.clearSign();
2012 return ConstantFP::get(Ty->getContext(), U);
2013 }
2014
2015 if (IntrinsicID == Intrinsic::amdgcn_fract) {
2016 // The v_fract instruction behaves like the OpenCL spec, which defines
2017 // fract(x) as fmin(x - floor(x), 0x1.fffffep-1f): "The min() operator is
2018 // there to prevent fract(-small) from returning 1.0. It returns the
2019 // largest positive floating-point number less than 1.0."
2020 APFloat FloorU(U);
2021 FloorU.roundToIntegral(APFloat::rmTowardNegative);
2022 APFloat FractU(U - FloorU);
2023 APFloat AlmostOne(U.getSemantics(), 1);
2024 AlmostOne.next(/*nextDown*/ true);
2025 return ConstantFP::get(Ty->getContext(), minimum(FractU, AlmostOne));
2026 }
2027
2028 // Rounding operations (floor, trunc, ceil, round and nearbyint) do not
2029 // raise FP exceptions, unless the argument is signaling NaN.
2030
2031 Optional<APFloat::roundingMode> RM;
2032 switch (IntrinsicID) {
2033 default:
2034 break;
2035 case Intrinsic::experimental_constrained_nearbyint:
2036 case Intrinsic::experimental_constrained_rint: {
2037 auto CI = cast<ConstrainedFPIntrinsic>(Call);
2038 RM = CI->getRoundingMode();
2039 if (!RM || RM.getValue() == RoundingMode::Dynamic)
2040 return nullptr;
2041 break;
2042 }
2043 case Intrinsic::experimental_constrained_round:
2044 RM = APFloat::rmNearestTiesToAway;
2045 break;
2046 case Intrinsic::experimental_constrained_ceil:
2047 RM = APFloat::rmTowardPositive;
2048 break;
2049 case Intrinsic::experimental_constrained_floor:
2050 RM = APFloat::rmTowardNegative;
2051 break;
2052 case Intrinsic::experimental_constrained_trunc:
2053 RM = APFloat::rmTowardZero;
2054 break;
2055 }
2056 if (RM) {
2057 auto CI = cast<ConstrainedFPIntrinsic>(Call);
2058 if (U.isFinite()) {
2059 APFloat::opStatus St = U.roundToIntegral(*RM);
2060 if (IntrinsicID == Intrinsic::experimental_constrained_rint &&
2061 St == APFloat::opInexact) {
2062 Optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
2063 if (EB && *EB == fp::ebStrict)
2064 return nullptr;
2065 }
2066 } else if (U.isSignaling()) {
2067 Optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
2068 if (EB && *EB != fp::ebIgnore)
2069 return nullptr;
2070 U = APFloat::getQNaN(U.getSemantics());
2071 }
2072 return ConstantFP::get(Ty->getContext(), U);
2073 }
2074
2075 /// We only fold functions with finite arguments. Folding NaN and inf is
2076 /// likely to be aborted with an exception anyway, and some host libms
2077 /// have known errors raising exceptions.
2078 if (!U.isFinite())
2079 return nullptr;
2080
2081 /// Currently APFloat versions of these functions do not exist, so we use
2082 /// the host native double versions. Float versions are not called
2083 /// directly but for all these it is true (float)(f((double)arg)) ==
2084 /// f(arg). Long double not supported yet.
2085 APFloat APF = Op->getValueAPF();
2086
2087 switch (IntrinsicID) {
2088 default: break;
2089 case Intrinsic::log:
2090 return ConstantFoldFP(log, APF, Ty);
2091 case Intrinsic::log2:
2092 // TODO: What about hosts that lack a C99 library?
2093 return ConstantFoldFP(Log2, APF, Ty);
2094 case Intrinsic::log10:
2095 // TODO: What about hosts that lack a C99 library?
2096 return ConstantFoldFP(log10, APF, Ty);
2097 case Intrinsic::exp:
2098 return ConstantFoldFP(exp, APF, Ty);
2099 case Intrinsic::exp2:
2100 // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
2101 return ConstantFoldBinaryFP(pow, APFloat(2.0), APF, Ty);
2102 case Intrinsic::sin:
2103 return ConstantFoldFP(sin, APF, Ty);
2104 case Intrinsic::cos:
2105 return ConstantFoldFP(cos, APF, Ty);
2106 case Intrinsic::sqrt:
2107 return ConstantFoldFP(sqrt, APF, Ty);
2108 case Intrinsic::amdgcn_cos:
2109 case Intrinsic::amdgcn_sin: {
2110 double V = getValueAsDouble(Op);
2111 if (V < -256.0 || V > 256.0)
2112 // The gfx8 and gfx9 architectures handle arguments outside the range
2113 // [-256, 256] differently. This should be a rare case so bail out
2114 // rather than trying to handle the difference.
2115 return nullptr;
2116 bool IsCos = IntrinsicID == Intrinsic::amdgcn_cos;
2117 double V4 = V * 4.0;
2118 if (V4 == floor(V4)) {
2119 // Force exact results for quarter-integer inputs.
2120 const double SinVals[4] = { 0.0, 1.0, 0.0, -1.0 };
2121 V = SinVals[((int)V4 + (IsCos ? 1 : 0)) & 3];
2122 } else {
2123 if (IsCos)
2124 V = cos(V * 2.0 * numbers::pi);
2125 else
2126 V = sin(V * 2.0 * numbers::pi);
2127 }
2128 return GetConstantFoldFPValue(V, Ty);
2129 }
2130 }
2131
2132 if (!TLI)
2133 return nullptr;
2134
2135 LibFunc Func = NotLibFunc;
2136 TLI->getLibFunc(Name, Func);
2137 switch (Func) {
2138 default:
2139 break;
2140 case LibFunc_acos:
2141 case LibFunc_acosf:
2142 case LibFunc_acos_finite:
2143 case LibFunc_acosf_finite:
2144 if (TLI->has(Func))
2145 return ConstantFoldFP(acos, APF, Ty);
2146 break;
2147 case LibFunc_asin:
2148 case LibFunc_asinf:
2149 case LibFunc_asin_finite:
2150 case LibFunc_asinf_finite:
2151 if (TLI->has(Func))
2152 return ConstantFoldFP(asin, APF, Ty);
2153 break;
2154 case LibFunc_atan:
2155 case LibFunc_atanf:
2156 if (TLI->has(Func))
2157 return ConstantFoldFP(atan, APF, Ty);
2158 break;
2159 case LibFunc_ceil:
2160 case LibFunc_ceilf:
2161 if (TLI->has(Func)) {
2162 U.roundToIntegral(APFloat::rmTowardPositive);
2163 return ConstantFP::get(Ty->getContext(), U);
2164 }
2165 break;
2166 case LibFunc_cos:
2167 case LibFunc_cosf:
2168 if (TLI->has(Func))
2169 return ConstantFoldFP(cos, APF, Ty);
2170 break;
2171 case LibFunc_cosh:
2172 case LibFunc_coshf:
2173 case LibFunc_cosh_finite:
2174 case LibFunc_coshf_finite:
2175 if (TLI->has(Func))
2176 return ConstantFoldFP(cosh, APF, Ty);
2177 break;
2178 case LibFunc_exp:
2179 case LibFunc_expf:
2180 case LibFunc_exp_finite:
2181 case LibFunc_expf_finite:
2182 if (TLI->has(Func))
2183 return ConstantFoldFP(exp, APF, Ty);
2184 break;
2185 case LibFunc_exp2:
2186 case LibFunc_exp2f:
2187 case LibFunc_exp2_finite:
2188 case LibFunc_exp2f_finite:
2189 if (TLI->has(Func))
2190 // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
2191 return ConstantFoldBinaryFP(pow, APFloat(2.0), APF, Ty);
2192 break;
2193 case LibFunc_fabs:
2194 case LibFunc_fabsf:
2195 if (TLI->has(Func)) {
2196 U.clearSign();
2197 return ConstantFP::get(Ty->getContext(), U);
2198 }
2199 break;
2200 case LibFunc_floor:
2201 case LibFunc_floorf:
2202 if (TLI->has(Func)) {
2203 U.roundToIntegral(APFloat::rmTowardNegative);
2204 return ConstantFP::get(Ty->getContext(), U);
2205 }
2206 break;
2207 case LibFunc_log:
2208 case LibFunc_logf:
2209 case LibFunc_log_finite:
2210 case LibFunc_logf_finite:
2211 if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
2212 return ConstantFoldFP(log, APF, Ty);
2213 break;
2214 case LibFunc_log2:
2215 case LibFunc_log2f:
2216 case LibFunc_log2_finite:
2217 case LibFunc_log2f_finite:
2218 if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
2219 // TODO: What about hosts that lack a C99 library?
2220 return ConstantFoldFP(Log2, APF, Ty);
2221 break;
2222 case LibFunc_log10:
2223 case LibFunc_log10f:
2224 case LibFunc_log10_finite:
2225 case LibFunc_log10f_finite:
2226 if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
2227 // TODO: What about hosts that lack a C99 library?
2228 return ConstantFoldFP(log10, APF, Ty);
2229 break;
2230 case LibFunc_nearbyint:
2231 case LibFunc_nearbyintf:
2232 case LibFunc_rint:
2233 case LibFunc_rintf:
2234 if (TLI->has(Func)) {
2235 U.roundToIntegral(APFloat::rmNearestTiesToEven);
2236 return ConstantFP::get(Ty->getContext(), U);
2237 }
2238 break;
2239 case LibFunc_round:
2240 case LibFunc_roundf:
2241 if (TLI->has(Func)) {
2242 U.roundToIntegral(APFloat::rmNearestTiesToAway);
2243 return ConstantFP::get(Ty->getContext(), U);
2244 }
2245 break;
2246 case LibFunc_sin:
2247 case LibFunc_sinf:
2248 if (TLI->has(Func))
2249 return ConstantFoldFP(sin, APF, Ty);
2250 break;
2251 case LibFunc_sinh:
2252 case LibFunc_sinhf:
2253 case LibFunc_sinh_finite:
2254 case LibFunc_sinhf_finite:
2255 if (TLI->has(Func))
2256 return ConstantFoldFP(sinh, APF, Ty);
2257 break;
2258 case LibFunc_sqrt:
2259 case LibFunc_sqrtf:
2260 if (!APF.isNegative() && TLI->has(Func))
2261 return ConstantFoldFP(sqrt, APF, Ty);
2262 break;
2263 case LibFunc_tan:
2264 case LibFunc_tanf:
2265 if (TLI->has(Func))
2266 return ConstantFoldFP(tan, APF, Ty);
2267 break;
2268 case LibFunc_tanh:
2269 case LibFunc_tanhf:
2270 if (TLI->has(Func))
2271 return ConstantFoldFP(tanh, APF, Ty);
2272 break;
2273 case LibFunc_trunc:
2274 case LibFunc_truncf:
2275 if (TLI->has(Func)) {
2276 U.roundToIntegral(APFloat::rmTowardZero);
2277 return ConstantFP::get(Ty->getContext(), U);
2278 }
2279 break;
2280 }
2281 return nullptr;
2282 }
2283
2284 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
2285 switch (IntrinsicID) {
2286 case Intrinsic::bswap:
2287 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
2288 case Intrinsic::ctpop:
2289 return ConstantInt::get(Ty, Op->getValue().countPopulation());
2290 case Intrinsic::bitreverse:
2291 return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
2292 case Intrinsic::convert_from_fp16: {
2293 APFloat Val(APFloat::IEEEhalf(), Op->getValue());
2294
2295 bool lost = false;
2296 APFloat::opStatus status = Val.convert(
2297 Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
2298
2299 // Conversion is always precise.
2300 (void)status;
2301 assert(status == APFloat::opOK && !lost &&(static_cast <bool> (status == APFloat::opOK &&
!lost && "Precision lost during fp16 constfolding") ?
void (0) : __assert_fail ("status == APFloat::opOK && !lost && \"Precision lost during fp16 constfolding\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 2302, __extension__ __PRETTY_FUNCTION__))
2302 "Precision lost during fp16 constfolding")(static_cast <bool> (status == APFloat::opOK &&
!lost && "Precision lost during fp16 constfolding") ?
void (0) : __assert_fail ("status == APFloat::opOK && !lost && \"Precision lost during fp16 constfolding\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 2302, __extension__ __PRETTY_FUNCTION__))
;
2303
2304 return ConstantFP::get(Ty->getContext(), Val);
2305 }
2306 default:
2307 return nullptr;
2308 }
2309 }
2310
2311 switch (IntrinsicID) {
2312 default: break;
2313 case Intrinsic::vector_reduce_add:
2314 case Intrinsic::vector_reduce_mul:
2315 case Intrinsic::vector_reduce_and:
2316 case Intrinsic::vector_reduce_or:
2317 case Intrinsic::vector_reduce_xor:
2318 case Intrinsic::vector_reduce_smin:
2319 case Intrinsic::vector_reduce_smax:
2320 case Intrinsic::vector_reduce_umin:
2321 case Intrinsic::vector_reduce_umax:
2322 if (Constant *C = constantFoldVectorReduce(IntrinsicID, Operands[0]))
2323 return C;
2324 break;
2325 }
2326
2327 // Support ConstantVector in case we have an Undef in the top.
2328 if (isa<ConstantVector>(Operands[0]) ||
2329 isa<ConstantDataVector>(Operands[0])) {
2330 auto *Op = cast<Constant>(Operands[0]);
2331 switch (IntrinsicID) {
2332 default: break;
2333 case Intrinsic::x86_sse_cvtss2si:
2334 case Intrinsic::x86_sse_cvtss2si64:
2335 case Intrinsic::x86_sse2_cvtsd2si:
2336 case Intrinsic::x86_sse2_cvtsd2si64:
2337 if (ConstantFP *FPOp =
2338 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2339 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2340 /*roundTowardZero=*/false, Ty,
2341 /*IsSigned*/true);
2342 break;
2343 case Intrinsic::x86_sse_cvttss2si:
2344 case Intrinsic::x86_sse_cvttss2si64:
2345 case Intrinsic::x86_sse2_cvttsd2si:
2346 case Intrinsic::x86_sse2_cvttsd2si64:
2347 if (ConstantFP *FPOp =
2348 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2349 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2350 /*roundTowardZero=*/true, Ty,
2351 /*IsSigned*/true);
2352 break;
2353 }
2354 }
2355
2356 return nullptr;
2357}
2358
2359static Constant *ConstantFoldScalarCall2(StringRef Name,
2360 Intrinsic::ID IntrinsicID,
2361 Type *Ty,
2362 ArrayRef<Constant *> Operands,
2363 const TargetLibraryInfo *TLI,
2364 const CallBase *Call) {
2365 assert(Operands.size() == 2 && "Wrong number of operands.")(static_cast <bool> (Operands.size() == 2 && "Wrong number of operands."
) ? void (0) : __assert_fail ("Operands.size() == 2 && \"Wrong number of operands.\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 2365, __extension__ __PRETTY_FUNCTION__))
;
1
Assuming the condition is true
2
'?' condition is true
2366
2367 if (Ty->isFloatingPointTy()) {
3
Calling 'Type::isFloatingPointTy'
12
Returning from 'Type::isFloatingPointTy'
13
Taking false branch
2368 // TODO: We should have undef handling for all of the FP intrinsics that
2369 // are attempted to be folded in this function.
2370 bool IsOp0Undef = isa<UndefValue>(Operands[0]);
2371 bool IsOp1Undef = isa<UndefValue>(Operands[1]);
2372 switch (IntrinsicID) {
2373 case Intrinsic::maxnum:
2374 case Intrinsic::minnum:
2375 case Intrinsic::maximum:
2376 case Intrinsic::minimum:
2377 // If one argument is undef, return the other argument.
2378 if (IsOp0Undef)
2379 return Operands[1];
2380 if (IsOp1Undef)
2381 return Operands[0];
2382 break;
2383 }
2384 }
2385
2386 if (const auto *Op1
14.1
'Op1' is null
14.1
'Op1' is null
14.1
'Op1' is null
= dyn_cast<ConstantFP>(Operands[0])) {
14
Assuming the object is not a 'ConstantFP'
2387 if (!Ty->isFloatingPointTy())
2388 return nullptr;
2389 APFloat Op1V = Op1->getValueAPF();
2390
2391 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2392 if (Op2->getType() != Op1->getType())
2393 return nullptr;
2394 APFloat Op2V = Op2->getValueAPF();
2395
2396 if (const auto *ConstrIntr = dyn_cast<ConstrainedFPIntrinsic>(Call)) {
2397 RoundingMode RM = getEvaluationRoundingMode(ConstrIntr);
2398 APFloat Res = Op1V;
2399 APFloat::opStatus St;
2400 switch (IntrinsicID) {
2401 default:
2402 return nullptr;
2403 case Intrinsic::experimental_constrained_fadd:
2404 St = Res.add(Op2V, RM);
2405 break;
2406 case Intrinsic::experimental_constrained_fsub:
2407 St = Res.subtract(Op2V, RM);
2408 break;
2409 case Intrinsic::experimental_constrained_fmul:
2410 St = Res.multiply(Op2V, RM);
2411 break;
2412 case Intrinsic::experimental_constrained_fdiv:
2413 St = Res.divide(Op2V, RM);
2414 break;
2415 case Intrinsic::experimental_constrained_frem:
2416 St = Res.mod(Op2V);
2417 break;
2418 }
2419 if (mayFoldConstrained(const_cast<ConstrainedFPIntrinsic *>(ConstrIntr),
2420 St))
2421 return ConstantFP::get(Ty->getContext(), Res);
2422 return nullptr;
2423 }
2424
2425 switch (IntrinsicID) {
2426 default:
2427 break;
2428 case Intrinsic::copysign:
2429 return ConstantFP::get(Ty->getContext(), APFloat::copySign(Op1V, Op2V));
2430 case Intrinsic::minnum:
2431 return ConstantFP::get(Ty->getContext(), minnum(Op1V, Op2V));
2432 case Intrinsic::maxnum:
2433 return ConstantFP::get(Ty->getContext(), maxnum(Op1V, Op2V));
2434 case Intrinsic::minimum:
2435 return ConstantFP::get(Ty->getContext(), minimum(Op1V, Op2V));
2436 case Intrinsic::maximum:
2437 return ConstantFP::get(Ty->getContext(), maximum(Op1V, Op2V));
2438 }
2439
2440 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
2441 return nullptr;
2442
2443 switch (IntrinsicID) {
2444 default:
2445 break;
2446 case Intrinsic::pow:
2447 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
2448 case Intrinsic::amdgcn_fmul_legacy:
2449 // The legacy behaviour is that multiplying +/- 0.0 by anything, even
2450 // NaN or infinity, gives +0.0.
2451 if (Op1V.isZero() || Op2V.isZero())
2452 return ConstantFP::getNullValue(Ty);
2453 return ConstantFP::get(Ty->getContext(), Op1V * Op2V);
2454 }
2455
2456 if (!TLI)
2457 return nullptr;
2458
2459 LibFunc Func = NotLibFunc;
2460 TLI->getLibFunc(Name, Func);
2461 switch (Func) {
2462 default:
2463 break;
2464 case LibFunc_pow:
2465 case LibFunc_powf:
2466 case LibFunc_pow_finite:
2467 case LibFunc_powf_finite:
2468 if (TLI->has(Func))
2469 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
2470 break;
2471 case LibFunc_fmod:
2472 case LibFunc_fmodf:
2473 if (TLI->has(Func)) {
2474 APFloat V = Op1->getValueAPF();
2475 if (APFloat::opStatus::opOK == V.mod(Op2->getValueAPF()))
2476 return ConstantFP::get(Ty->getContext(), V);
2477 }
2478 break;
2479 case LibFunc_remainder:
2480 case LibFunc_remainderf:
2481 if (TLI->has(Func)) {
2482 APFloat V = Op1->getValueAPF();
2483 if (APFloat::opStatus::opOK == V.remainder(Op2->getValueAPF()))
2484 return ConstantFP::get(Ty->getContext(), V);
2485 }
2486 break;
2487 case LibFunc_atan2:
2488 case LibFunc_atan2f:
2489 case LibFunc_atan2_finite:
2490 case LibFunc_atan2f_finite:
2491 if (TLI->has(Func))
2492 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
2493 break;
2494 }
2495 } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
2496 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
2497 return nullptr;
2498 if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
2499 return ConstantFP::get(
2500 Ty->getContext(),
2501 APFloat((float)std::pow((float)Op1V.convertToDouble(),
2502 (int)Op2C->getZExtValue())));
2503 if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
2504 return ConstantFP::get(
2505 Ty->getContext(),
2506 APFloat((float)std::pow((float)Op1V.convertToDouble(),
2507 (int)Op2C->getZExtValue())));
2508 if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
2509 return ConstantFP::get(
2510 Ty->getContext(),
2511 APFloat((double)std::pow(Op1V.convertToDouble(),
2512 (int)Op2C->getZExtValue())));
2513
2514 if (IntrinsicID == Intrinsic::amdgcn_ldexp) {
2515 // FIXME: Should flush denorms depending on FP mode, but that's ignored
2516 // everywhere else.
2517
2518 // scalbn is equivalent to ldexp with float radix 2
2519 APFloat Result = scalbn(Op1->getValueAPF(), Op2C->getSExtValue(),
2520 APFloat::rmNearestTiesToEven);
2521 return ConstantFP::get(Ty->getContext(), Result);
2522 }
2523 }
2524 return nullptr;
2525 }
2526
2527 if (Operands[0]->getType()->isIntegerTy() &&
15
Calling 'Type::isIntegerTy'
18
Returning from 'Type::isIntegerTy'
23
Taking true branch
2528 Operands[1]->getType()->isIntegerTy()) {
19
Calling 'Type::isIntegerTy'
22
Returning from 'Type::isIntegerTy'
2529 const APInt *C0, *C1;
2530 if (!getConstIntOrUndef(Operands[0], C0) ||
24
Calling 'getConstIntOrUndef'
31
Returning from 'getConstIntOrUndef'
37
Taking false branch
2531 !getConstIntOrUndef(Operands[1], C1))
32
Calling 'getConstIntOrUndef'
36
Returning from 'getConstIntOrUndef'
2532 return nullptr;
2533
2534 unsigned BitWidth = Ty->getScalarSizeInBits();
2535 switch (IntrinsicID) {
38
Control jumps to 'case abs:' at line 2653
2536 default: break;
2537 case Intrinsic::smax:
2538 if (!C0 && !C1)
2539 return UndefValue::get(Ty);
2540 if (!C0 || !C1)
2541 return ConstantInt::get(Ty, APInt::getSignedMaxValue(BitWidth));
2542 return ConstantInt::get(Ty, C0->sgt(*C1) ? *C0 : *C1);
2543
2544 case Intrinsic::smin:
2545 if (!C0 && !C1)
2546 return UndefValue::get(Ty);
2547 if (!C0 || !C1)
2548 return ConstantInt::get(Ty, APInt::getSignedMinValue(BitWidth));
2549 return ConstantInt::get(Ty, C0->slt(*C1) ? *C0 : *C1);
2550
2551 case Intrinsic::umax:
2552 if (!C0 && !C1)
2553 return UndefValue::get(Ty);
2554 if (!C0 || !C1)
2555 return ConstantInt::get(Ty, APInt::getMaxValue(BitWidth));
2556 return ConstantInt::get(Ty, C0->ugt(*C1) ? *C0 : *C1);
2557
2558 case Intrinsic::umin:
2559 if (!C0 && !C1)
2560 return UndefValue::get(Ty);
2561 if (!C0 || !C1)
2562 return ConstantInt::get(Ty, APInt::getMinValue(BitWidth));
2563 return ConstantInt::get(Ty, C0->ult(*C1) ? *C0 : *C1);
2564
2565 case Intrinsic::usub_with_overflow:
2566 case Intrinsic::ssub_with_overflow:
2567 // X - undef -> { 0, false }
2568 // undef - X -> { 0, false }
2569 if (!C0 || !C1)
2570 return Constant::getNullValue(Ty);
2571 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2572 case Intrinsic::uadd_with_overflow:
2573 case Intrinsic::sadd_with_overflow:
2574 // X + undef -> { -1, false }
2575 // undef + x -> { -1, false }
2576 if (!C0 || !C1) {
2577 return ConstantStruct::get(
2578 cast<StructType>(Ty),
2579 {Constant::getAllOnesValue(Ty->getStructElementType(0)),
2580 Constant::getNullValue(Ty->getStructElementType(1))});
2581 }
2582 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2583 case Intrinsic::smul_with_overflow:
2584 case Intrinsic::umul_with_overflow: {
2585 // undef * X -> { 0, false }
2586 // X * undef -> { 0, false }
2587 if (!C0 || !C1)
2588 return Constant::getNullValue(Ty);
2589
2590 APInt Res;
2591 bool Overflow;
2592 switch (IntrinsicID) {
2593 default: llvm_unreachable("Invalid case")::llvm::llvm_unreachable_internal("Invalid case", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 2593)
;
2594 case Intrinsic::sadd_with_overflow:
2595 Res = C0->sadd_ov(*C1, Overflow);
2596 break;
2597 case Intrinsic::uadd_with_overflow:
2598 Res = C0->uadd_ov(*C1, Overflow);
2599 break;
2600 case Intrinsic::ssub_with_overflow:
2601 Res = C0->ssub_ov(*C1, Overflow);
2602 break;
2603 case Intrinsic::usub_with_overflow:
2604 Res = C0->usub_ov(*C1, Overflow);
2605 break;
2606 case Intrinsic::smul_with_overflow:
2607 Res = C0->smul_ov(*C1, Overflow);
2608 break;
2609 case Intrinsic::umul_with_overflow:
2610 Res = C0->umul_ov(*C1, Overflow);
2611 break;
2612 }
2613 Constant *Ops[] = {
2614 ConstantInt::get(Ty->getContext(), Res),
2615 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
2616 };
2617 return ConstantStruct::get(cast<StructType>(Ty), Ops);
2618 }
2619 case Intrinsic::uadd_sat:
2620 case Intrinsic::sadd_sat:
2621 if (!C0 && !C1)
2622 return UndefValue::get(Ty);
2623 if (!C0 || !C1)
2624 return Constant::getAllOnesValue(Ty);
2625 if (IntrinsicID == Intrinsic::uadd_sat)
2626 return ConstantInt::get(Ty, C0->uadd_sat(*C1));
2627 else
2628 return ConstantInt::get(Ty, C0->sadd_sat(*C1));
2629 case Intrinsic::usub_sat:
2630 case Intrinsic::ssub_sat:
2631 if (!C0 && !C1)
2632 return UndefValue::get(Ty);
2633 if (!C0 || !C1)
2634 return Constant::getNullValue(Ty);
2635 if (IntrinsicID == Intrinsic::usub_sat)
2636 return ConstantInt::get(Ty, C0->usub_sat(*C1));
2637 else
2638 return ConstantInt::get(Ty, C0->ssub_sat(*C1));
2639 case Intrinsic::cttz:
2640 case Intrinsic::ctlz:
2641 assert(C1 && "Must be constant int")(static_cast <bool> (C1 && "Must be constant int"
) ? void (0) : __assert_fail ("C1 && \"Must be constant int\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 2641, __extension__ __PRETTY_FUNCTION__))
;
2642
2643 // cttz(0, 1) and ctlz(0, 1) are undef.
2644 if (C1->isOneValue() && (!C0 || C0->isNullValue()))
2645 return UndefValue::get(Ty);
2646 if (!C0)
2647 return Constant::getNullValue(Ty);
2648 if (IntrinsicID == Intrinsic::cttz)
2649 return ConstantInt::get(Ty, C0->countTrailingZeros());
2650 else
2651 return ConstantInt::get(Ty, C0->countLeadingZeros());
2652
2653 case Intrinsic::abs:
2654 // Undef or minimum val operand with poison min --> undef
2655 assert(C1 && "Must be constant int")(static_cast <bool> (C1 && "Must be constant int"
) ? void (0) : __assert_fail ("C1 && \"Must be constant int\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 2655, __extension__ __PRETTY_FUNCTION__))
;
39
'?' condition is true
2656 if (C1->isOneValue() && (!C0 || C0->isMinSignedValue()))
40
Calling 'APInt::isOneValue'
51
Returning from 'APInt::isOneValue'
2657 return UndefValue::get(Ty);
2658
2659 // Undef operand with no poison min --> 0 (sign bit must be clear)
2660 if (C1->isNullValue() && !C0)
52
Calling 'APInt::isNullValue'
62
Returning from 'APInt::isNullValue'
2661 return Constant::getNullValue(Ty);
2662
2663 return ConstantInt::get(Ty, C0->abs());
63
Called C++ object pointer is null
2664 }
2665
2666 return nullptr;
2667 }
2668
2669 // Support ConstantVector in case we have an Undef in the top.
2670 if ((isa<ConstantVector>(Operands[0]) ||
2671 isa<ConstantDataVector>(Operands[0])) &&
2672 // Check for default rounding mode.
2673 // FIXME: Support other rounding modes?
2674 isa<ConstantInt>(Operands[1]) &&
2675 cast<ConstantInt>(Operands[1])->getValue() == 4) {
2676 auto *Op = cast<Constant>(Operands[0]);
2677 switch (IntrinsicID) {
2678 default: break;
2679 case Intrinsic::x86_avx512_vcvtss2si32:
2680 case Intrinsic::x86_avx512_vcvtss2si64:
2681 case Intrinsic::x86_avx512_vcvtsd2si32:
2682 case Intrinsic::x86_avx512_vcvtsd2si64:
2683 if (ConstantFP *FPOp =
2684 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2685 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2686 /*roundTowardZero=*/false, Ty,
2687 /*IsSigned*/true);
2688 break;
2689 case Intrinsic::x86_avx512_vcvtss2usi32:
2690 case Intrinsic::x86_avx512_vcvtss2usi64:
2691 case Intrinsic::x86_avx512_vcvtsd2usi32:
2692 case Intrinsic::x86_avx512_vcvtsd2usi64:
2693 if (ConstantFP *FPOp =
2694 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2695 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2696 /*roundTowardZero=*/false, Ty,
2697 /*IsSigned*/false);
2698 break;
2699 case Intrinsic::x86_avx512_cvttss2si:
2700 case Intrinsic::x86_avx512_cvttss2si64:
2701 case Intrinsic::x86_avx512_cvttsd2si:
2702 case Intrinsic::x86_avx512_cvttsd2si64:
2703 if (ConstantFP *FPOp =
2704 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2705 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2706 /*roundTowardZero=*/true, Ty,
2707 /*IsSigned*/true);
2708 break;
2709 case Intrinsic::x86_avx512_cvttss2usi:
2710 case Intrinsic::x86_avx512_cvttss2usi64:
2711 case Intrinsic::x86_avx512_cvttsd2usi:
2712 case Intrinsic::x86_avx512_cvttsd2usi64:
2713 if (ConstantFP *FPOp =
2714 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2715 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2716 /*roundTowardZero=*/true, Ty,
2717 /*IsSigned*/false);
2718 break;
2719 }
2720 }
2721 return nullptr;
2722}
2723
2724static APFloat ConstantFoldAMDGCNCubeIntrinsic(Intrinsic::ID IntrinsicID,
2725 const APFloat &S0,
2726 const APFloat &S1,
2727 const APFloat &S2) {
2728 unsigned ID;
2729 const fltSemantics &Sem = S0.getSemantics();
2730 APFloat MA(Sem), SC(Sem), TC(Sem);
2731 if (abs(S2) >= abs(S0) && abs(S2) >= abs(S1)) {
2732 if (S2.isNegative() && S2.isNonZero() && !S2.isNaN()) {
2733 // S2 < 0
2734 ID = 5;
2735 SC = -S0;
2736 } else {
2737 ID = 4;
2738 SC = S0;
2739 }
2740 MA = S2;
2741 TC = -S1;
2742 } else if (abs(S1) >= abs(S0)) {
2743 if (S1.isNegative() && S1.isNonZero() && !S1.isNaN()) {
2744 // S1 < 0
2745 ID = 3;
2746 TC = -S2;
2747 } else {
2748 ID = 2;
2749 TC = S2;
2750 }
2751 MA = S1;
2752 SC = S0;
2753 } else {
2754 if (S0.isNegative() && S0.isNonZero() && !S0.isNaN()) {
2755 // S0 < 0
2756 ID = 1;
2757 SC = S2;
2758 } else {
2759 ID = 0;
2760 SC = -S2;
2761 }
2762 MA = S0;
2763 TC = -S1;
2764 }
2765 switch (IntrinsicID) {
2766 default:
2767 llvm_unreachable("unhandled amdgcn cube intrinsic")::llvm::llvm_unreachable_internal("unhandled amdgcn cube intrinsic"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 2767)
;
2768 case Intrinsic::amdgcn_cubeid:
2769 return APFloat(Sem, ID);
2770 case Intrinsic::amdgcn_cubema:
2771 return MA + MA;
2772 case Intrinsic::amdgcn_cubesc:
2773 return SC;
2774 case Intrinsic::amdgcn_cubetc:
2775 return TC;
2776 }
2777}
2778
2779static Constant *ConstantFoldAMDGCNPermIntrinsic(ArrayRef<Constant *> Operands,
2780 Type *Ty) {
2781 const APInt *C0, *C1, *C2;
2782 if (!getConstIntOrUndef(Operands[0], C0) ||
2783 !getConstIntOrUndef(Operands[1], C1) ||
2784 !getConstIntOrUndef(Operands[2], C2))
2785 return nullptr;
2786
2787 if (!C2)
2788 return UndefValue::get(Ty);
2789
2790 APInt Val(32, 0);
2791 unsigned NumUndefBytes = 0;
2792 for (unsigned I = 0; I < 32; I += 8) {
2793 unsigned Sel = C2->extractBitsAsZExtValue(8, I);
2794 unsigned B = 0;
2795
2796 if (Sel >= 13)
2797 B = 0xff;
2798 else if (Sel == 12)
2799 B = 0x00;
2800 else {
2801 const APInt *Src = ((Sel & 10) == 10 || (Sel & 12) == 4) ? C0 : C1;
2802 if (!Src)
2803 ++NumUndefBytes;
2804 else if (Sel < 8)
2805 B = Src->extractBitsAsZExtValue(8, (Sel & 3) * 8);
2806 else
2807 B = Src->extractBitsAsZExtValue(1, (Sel & 1) ? 31 : 15) * 0xff;
2808 }
2809
2810 Val.insertBits(B, I, 8);
2811 }
2812
2813 if (NumUndefBytes == 4)
2814 return UndefValue::get(Ty);
2815
2816 return ConstantInt::get(Ty, Val);
2817}
2818
2819static Constant *ConstantFoldScalarCall3(StringRef Name,
2820 Intrinsic::ID IntrinsicID,
2821 Type *Ty,
2822 ArrayRef<Constant *> Operands,
2823 const TargetLibraryInfo *TLI,
2824 const CallBase *Call) {
2825 assert(Operands.size() == 3 && "Wrong number of operands.")(static_cast <bool> (Operands.size() == 3 && "Wrong number of operands."
) ? void (0) : __assert_fail ("Operands.size() == 3 && \"Wrong number of operands.\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 2825, __extension__ __PRETTY_FUNCTION__))
;
2826
2827 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
2828 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2829 if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
2830 const APFloat &C1 = Op1->getValueAPF();
2831 const APFloat &C2 = Op2->getValueAPF();
2832 const APFloat &C3 = Op3->getValueAPF();
2833
2834 if (const auto *ConstrIntr = dyn_cast<ConstrainedFPIntrinsic>(Call)) {
2835 RoundingMode RM = getEvaluationRoundingMode(ConstrIntr);
2836 APFloat Res = C1;
2837 APFloat::opStatus St;
2838 switch (IntrinsicID) {
2839 default:
2840 return nullptr;
2841 case Intrinsic::experimental_constrained_fma:
2842 case Intrinsic::experimental_constrained_fmuladd:
2843 St = Res.fusedMultiplyAdd(C2, C3, RM);
2844 break;
2845 }
2846 if (mayFoldConstrained(
2847 const_cast<ConstrainedFPIntrinsic *>(ConstrIntr), St))
2848 return ConstantFP::get(Ty->getContext(), Res);
2849 return nullptr;
2850 }
2851
2852 switch (IntrinsicID) {
2853 default: break;
2854 case Intrinsic::amdgcn_fma_legacy: {
2855 // The legacy behaviour is that multiplying +/- 0.0 by anything, even
2856 // NaN or infinity, gives +0.0.
2857 if (C1.isZero() || C2.isZero()) {
2858 // It's tempting to just return C3 here, but that would give the
2859 // wrong result if C3 was -0.0.
2860 return ConstantFP::get(Ty->getContext(), APFloat(0.0f) + C3);
2861 }
2862 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2863 }
2864 case Intrinsic::fma:
2865 case Intrinsic::fmuladd: {
2866 APFloat V = C1;
2867 V.fusedMultiplyAdd(C2, C3, APFloat::rmNearestTiesToEven);
2868 return ConstantFP::get(Ty->getContext(), V);
2869 }
2870 case Intrinsic::amdgcn_cubeid:
2871 case Intrinsic::amdgcn_cubema:
2872 case Intrinsic::amdgcn_cubesc:
2873 case Intrinsic::amdgcn_cubetc: {
2874 APFloat V = ConstantFoldAMDGCNCubeIntrinsic(IntrinsicID, C1, C2, C3);
2875 return ConstantFP::get(Ty->getContext(), V);
2876 }
2877 }
2878 }
2879 }
2880 }
2881
2882 if (IntrinsicID == Intrinsic::smul_fix ||
2883 IntrinsicID == Intrinsic::smul_fix_sat) {
2884 // poison * C -> poison
2885 // C * poison -> poison
2886 if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1]))
2887 return PoisonValue::get(Ty);
2888
2889 const APInt *C0, *C1;
2890 if (!getConstIntOrUndef(Operands[0], C0) ||
2891 !getConstIntOrUndef(Operands[1], C1))
2892 return nullptr;
2893
2894 // undef * C -> 0
2895 // C * undef -> 0
2896 if (!C0 || !C1)
2897 return Constant::getNullValue(Ty);
2898
2899 // This code performs rounding towards negative infinity in case the result
2900 // cannot be represented exactly for the given scale. Targets that do care
2901 // about rounding should use a target hook for specifying how rounding
2902 // should be done, and provide their own folding to be consistent with
2903 // rounding. This is the same approach as used by
2904 // DAGTypeLegalizer::ExpandIntRes_MULFIX.
2905 unsigned Scale = cast<ConstantInt>(Operands[2])->getZExtValue();
2906 unsigned Width = C0->getBitWidth();
2907 assert(Scale < Width && "Illegal scale.")(static_cast <bool> (Scale < Width && "Illegal scale."
) ? void (0) : __assert_fail ("Scale < Width && \"Illegal scale.\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Analysis/ConstantFolding.cpp"
, 2907, __extension__ __PRETTY_FUNCTION__))
;
2908 unsigned ExtendedWidth = Width * 2;
2909 APInt Product = (C0->sextOrSelf(ExtendedWidth) *
2910 C1->sextOrSelf(ExtendedWidth)).ashr(Scale);
2911 if (IntrinsicID == Intrinsic::smul_fix_sat) {
2912 APInt Max = APInt::getSignedMaxValue(Width).sextOrSelf(ExtendedWidth);
2913 APInt Min = APInt::getSignedMinValue(Width).sextOrSelf(ExtendedWidth);
2914 Product = APIntOps::smin(Product, Max);
2915 Product = APIntOps::smax(Product, Min);
2916 }
2917 return ConstantInt::get(Ty->getContext(), Product.sextOrTrunc(Width));
2918 }
2919
2920 if (IntrinsicID == Intrinsic::fshl || IntrinsicID == Intrinsic::fshr) {
2921 const APInt *C0, *C1, *C2;
2922 if (!getConstIntOrUndef(Operands[0], C0) ||
2923 !getConstIntOrUndef(Operands[1], C1) ||
2924 !getConstIntOrUndef(Operands[2], C2))
2925 return nullptr;
2926
2927 bool IsRight = IntrinsicID == Intrinsic::fshr;
2928 if (!C2)
2929 return Operands[IsRight ? 1 : 0];
2930 if (!C0 && !C1)
2931 return UndefValue::get(Ty);
2932
2933 // The shift amount is interpreted as modulo the bitwidth. If the shift
2934 // amount is effectively 0, avoid UB due to oversized inverse shift below.
2935 unsigned BitWidth = C2->getBitWidth();
2936 unsigned ShAmt = C2->urem(BitWidth);
2937 if (!ShAmt)
2938 return Operands[IsRight ? 1 : 0];
2939
2940 // (C0 << ShlAmt) | (C1 >> LshrAmt)
2941 unsigned LshrAmt = IsRight ? ShAmt : BitWidth - ShAmt;
2942 unsigned ShlAmt = !IsRight ? ShAmt : BitWidth - ShAmt;
2943 if (!C0)
2944 return ConstantInt::get(Ty, C1->lshr(LshrAmt));
2945 if (!C1)
2946 return ConstantInt::get(Ty, C0->shl(ShlAmt));
2947 return ConstantInt::get(Ty, C0->shl(ShlAmt) | C1->lshr(LshrAmt));
2948 }
2949
2950 if (IntrinsicID == Intrinsic::amdgcn_perm)
2951 return ConstantFoldAMDGCNPermIntrinsic(Operands, Ty);
2952
2953 return nullptr;
2954}
2955
2956static Constant *ConstantFoldScalarCall(StringRef Name,
2957 Intrinsic::ID IntrinsicID,
2958 Type *Ty,
2959 ArrayRef<Constant *> Operands,
2960 const TargetLibraryInfo *TLI,
2961 const CallBase *Call) {
2962 if (Operands.size() == 1)
2963 return ConstantFoldScalarCall1(Name, IntrinsicID, Ty, Operands, TLI, Call);
2964
2965 if (Operands.size() == 2)
2966 return ConstantFoldScalarCall2(Name, IntrinsicID, Ty, Operands, TLI, Call);
2967
2968 if (Operands.size() == 3)
2969 return ConstantFoldScalarCall3(Name, IntrinsicID, Ty, Operands, TLI, Call);
2970
2971 return nullptr;
2972}
2973
2974static Constant *ConstantFoldFixedVectorCall(
2975 StringRef Name, Intrinsic::ID IntrinsicID, FixedVectorType *FVTy,
2976 ArrayRef<Constant *> Operands, const DataLayout &DL,
2977 const TargetLibraryInfo *TLI, const CallBase *Call) {
2978 SmallVector<Constant *, 4> Result(FVTy->getNumElements());
2979 SmallVector<Constant *, 4> Lane(Operands.size());
2980 Type *Ty = FVTy->getElementType();
2981
2982 switch (IntrinsicID) {
2983 case Intrinsic::masked_load: {
2984 auto *SrcPtr = Operands[0];
2985 auto *Mask = Operands[2];
2986 auto *Passthru = Operands[3];
2987
2988 Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, FVTy, DL);
2989
2990 SmallVector<Constant *, 32> NewElements;
2991 for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
2992 auto *MaskElt = Mask->getAggregateElement(I);
2993 if (!MaskElt)
2994 break;
2995 auto *PassthruElt = Passthru->getAggregateElement(I);
2996 auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
2997 if (isa<UndefValue>(MaskElt)) {
2998 if (PassthruElt)
2999 NewElements.push_back(PassthruElt);
3000 else if (VecElt)
3001 NewElements.push_back(VecElt);
3002 else
3003 return nullptr;
3004 }
3005 if (MaskElt->isNullValue()) {
3006 if (!PassthruElt)
3007 return nullptr;
3008 NewElements.push_back(PassthruElt);
3009 } else if (MaskElt->isOneValue()) {
3010 if (!VecElt)
3011 return nullptr;
3012 NewElements.push_back(VecElt);
3013 } else {
3014 return nullptr;
3015 }
3016 }
3017 if (NewElements.size() != FVTy->getNumElements())
3018 return nullptr;
3019 return ConstantVector::get(NewElements);
3020 }
3021 case Intrinsic::arm_mve_vctp8:
3022 case Intrinsic::arm_mve_vctp16:
3023 case Intrinsic::arm_mve_vctp32:
3024 case Intrinsic::arm_mve_vctp64: {
3025 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
3026 unsigned Lanes = FVTy->getNumElements();
3027 uint64_t Limit = Op->getZExtValue();
3028 // vctp64 are currently modelled as returning a v4i1, not a v2i1. Make
3029 // sure we get the limit right in that case and set all relevant lanes.
3030 if (IntrinsicID == Intrinsic::arm_mve_vctp64)
3031 Limit *= 2;
3032
3033 SmallVector<Constant *, 16> NCs;
3034 for (unsigned i = 0; i < Lanes; i++) {
3035 if (i < Limit)
3036 NCs.push_back(ConstantInt::getTrue(Ty));
3037 else
3038 NCs.push_back(ConstantInt::getFalse(Ty));
3039 }
3040 return ConstantVector::get(NCs);
3041 }
3042 break;
3043 }
3044 case Intrinsic::get_active_lane_mask: {
3045 auto *Op0 = dyn_cast<ConstantInt>(Operands[0]);
3046 auto *Op1 = dyn_cast<ConstantInt>(Operands[1]);
3047 if (Op0 && Op1) {
3048 unsigned Lanes = FVTy->getNumElements();
3049 uint64_t Base = Op0->getZExtValue();
3050 uint64_t Limit = Op1->getZExtValue();
3051
3052 SmallVector<Constant *, 16> NCs;
3053 for (unsigned i = 0; i < Lanes; i++) {
3054 if (Base + i < Limit)
3055 NCs.push_back(ConstantInt::getTrue(Ty));
3056 else
3057 NCs.push_back(ConstantInt::getFalse(Ty));
3058 }
3059 return ConstantVector::get(NCs);
3060 }
3061 break;
3062 }
3063 default:
3064 break;
3065 }
3066
3067 for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
3068 // Gather a column of constants.
3069 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
3070 // Some intrinsics use a scalar type for certain arguments.
3071 if (hasVectorInstrinsicScalarOpd(IntrinsicID, J)) {
3072 Lane[J] = Operands[J];
3073 continue;
3074 }
3075
3076 Constant *Agg = Operands[J]->getAggregateElement(I);
3077 if (!Agg)
3078 return nullptr;
3079
3080 Lane[J] = Agg;
3081 }
3082
3083 // Use the regular scalar folding to simplify this column.
3084 Constant *Folded =
3085 ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI, Call);
3086 if (!Folded)
3087 return nullptr;
3088 Result[I] = Folded;
3089 }
3090
3091 return ConstantVector::get(Result);
3092}
3093
3094static Constant *ConstantFoldScalableVectorCall(
3095 StringRef Name, Intrinsic::ID IntrinsicID, ScalableVectorType *SVTy,
3096 ArrayRef<Constant *> Operands, const DataLayout &DL,
3097 const TargetLibraryInfo *TLI, const CallBase *Call) {
3098 switch (IntrinsicID) {
3099 case Intrinsic::aarch64_sve_convert_from_svbool: {
3100 auto *Src = dyn_cast<Constant>(Operands[0]);
3101 if (!Src || !Src->isNullValue())
3102 break;
3103
3104 return ConstantInt::getFalse(SVTy);
3105 }
3106 default:
3107 break;
3108 }
3109 return nullptr;
3110}
3111
3112} // end anonymous namespace
3113
3114Constant *llvm::ConstantFoldCall(const CallBase *Call, Function *F,
3115 ArrayRef<Constant *> Operands,
3116 const TargetLibraryInfo *TLI) {
3117 if (Call->isNoBuiltin())
3118 return nullptr;
3119 if (!F->hasName())
3120 return nullptr;
3121
3122 // If this is not an intrinsic and not recognized as a library call, bail out.
3123 if (F->getIntrinsicID() == Intrinsic::not_intrinsic) {
3124 if (!TLI)
3125 return nullptr;
3126 LibFunc LibF;
3127 if (!TLI->getLibFunc(*F, LibF))
3128 return nullptr;
3129 }
3130
3131 StringRef Name = F->getName();
3132 Type *Ty = F->getReturnType();
3133 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty))
3134 return ConstantFoldFixedVectorCall(
3135 Name, F->getIntrinsicID(), FVTy, Operands,
3136 F->getParent()->getDataLayout(), TLI, Call);
3137
3138 if (auto *SVTy = dyn_cast<ScalableVectorType>(Ty))
3139 return ConstantFoldScalableVectorCall(
3140 Name, F->getIntrinsicID(), SVTy, Operands,
3141 F->getParent()->getDataLayout(), TLI, Call);
3142
3143 // TODO: If this is a library function, we already discovered that above,
3144 // so we should pass the LibFunc, not the name (and it might be better
3145 // still to separate intrinsic handling from libcalls).
3146 return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI,
3147 Call);
3148}
3149
3150bool llvm::isMathLibCallNoop(const CallBase *Call,
3151 const TargetLibraryInfo *TLI) {
3152 // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
3153 // (and to some extent ConstantFoldScalarCall).
3154 if (Call->isNoBuiltin() || Call->isStrictFP())
3155 return false;
3156 Function *F = Call->getCalledFunction();
3157 if (!F)
3158 return false;
3159
3160 LibFunc Func;
3161 if (!TLI || !TLI->getLibFunc(*F, Func))
3162 return false;
3163
3164 if (Call->getNumArgOperands() == 1) {
3165 if (ConstantFP *OpC = dyn_cast<ConstantFP>(Call->getArgOperand(0))) {
3166 const APFloat &Op = OpC->getValueAPF();
3167 switch (Func) {
3168 case LibFunc_logl:
3169 case LibFunc_log:
3170 case LibFunc_logf:
3171 case LibFunc_log2l:
3172 case LibFunc_log2:
3173 case LibFunc_log2f:
3174 case LibFunc_log10l:
3175 case LibFunc_log10:
3176 case LibFunc_log10f:
3177 return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
3178
3179 case LibFunc_expl:
3180 case LibFunc_exp:
3181 case LibFunc_expf:
3182 // FIXME: These boundaries are slightly conservative.
3183 if (OpC->getType()->isDoubleTy())
3184 return !(Op < APFloat(-745.0) || Op > APFloat(709.0));
3185 if (OpC->getType()->isFloatTy())
3186 return !(Op < APFloat(-103.0f) || Op > APFloat(88.0f));
3187 break;
3188
3189 case LibFunc_exp2l:
3190 case LibFunc_exp2:
3191 case LibFunc_exp2f:
3192 // FIXME: These boundaries are slightly conservative.
3193 if (OpC->getType()->isDoubleTy())
3194 return !(Op < APFloat(-1074.0) || Op > APFloat(1023.0));
3195 if (OpC->getType()->isFloatTy())
3196 return !(Op < APFloat(-149.0f) || Op > APFloat(127.0f));
3197 break;
3198
3199 case LibFunc_sinl:
3200 case LibFunc_sin:
3201 case LibFunc_sinf:
3202 case LibFunc_cosl:
3203 case LibFunc_cos:
3204 case LibFunc_cosf:
3205 return !Op.isInfinity();
3206
3207 case LibFunc_tanl:
3208 case LibFunc_tan:
3209 case LibFunc_tanf: {
3210 // FIXME: Stop using the host math library.
3211 // FIXME: The computation isn't done in the right precision.
3212 Type *Ty = OpC->getType();
3213 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy())
3214 return ConstantFoldFP(tan, OpC->getValueAPF(), Ty) != nullptr;
3215 break;
3216 }
3217
3218 case LibFunc_asinl:
3219 case LibFunc_asin:
3220 case LibFunc_asinf:
3221 case LibFunc_acosl:
3222 case LibFunc_acos:
3223 case LibFunc_acosf:
3224 return !(Op < APFloat(Op.getSemantics(), "-1") ||
3225 Op > APFloat(Op.getSemantics(), "1"));
3226
3227 case LibFunc_sinh:
3228 case LibFunc_cosh:
3229 case LibFunc_sinhf:
3230 case LibFunc_coshf:
3231 case LibFunc_sinhl:
3232 case LibFunc_coshl:
3233 // FIXME: These boundaries are slightly conservative.
3234 if (OpC->getType()->isDoubleTy())
3235 return !(Op < APFloat(-710.0) || Op > APFloat(710.0));
3236 if (OpC->getType()->isFloatTy())
3237 return !(Op < APFloat(-89.0f) || Op > APFloat(89.0f));
3238 break;
3239
3240 case LibFunc_sqrtl:
3241 case LibFunc_sqrt:
3242 case LibFunc_sqrtf:
3243 return Op.isNaN() || Op.isZero() || !Op.isNegative();
3244
3245 // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
3246 // maybe others?
3247 default:
3248 break;
3249 }
3250 }
3251 }
3252
3253 if (Call->getNumArgOperands() == 2) {
3254 ConstantFP *Op0C = dyn_cast<ConstantFP>(Call->getArgOperand(0));
3255 ConstantFP *Op1C = dyn_cast<ConstantFP>(Call->getArgOperand(1));
3256 if (Op0C && Op1C) {
3257 const APFloat &Op0 = Op0C->getValueAPF();
3258 const APFloat &Op1 = Op1C->getValueAPF();
3259
3260 switch (Func) {
3261 case LibFunc_powl:
3262 case LibFunc_pow:
3263 case LibFunc_powf: {
3264 // FIXME: Stop using the host math library.
3265 // FIXME: The computation isn't done in the right precision.
3266 Type *Ty = Op0C->getType();
3267 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
3268 if (Ty == Op1C->getType())
3269 return ConstantFoldBinaryFP(pow, Op0, Op1, Ty) != nullptr;
3270 }
3271 break;
3272 }
3273
3274 case LibFunc_fmodl:
3275 case LibFunc_fmod:
3276 case LibFunc_fmodf:
3277 case LibFunc_remainderl:
3278 case LibFunc_remainder:
3279 case LibFunc_remainderf:
3280 return Op0.isNaN() || Op1.isNaN() ||
3281 (!Op0.isInfinity() && !Op1.isZero());
3282
3283 default:
3284 break;
3285 }
3286 }
3287 }
3288
3289 return false;
3290}
3291
3292void TargetFolder::anchor() {}

/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/IR/Type.h

1//===- llvm/Type.h - Classes for handling data types ------------*- C++ -*-===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the declaration of the Type class. For more "Type"
10// stuff, look in DerivedTypes.h.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_IR_TYPE_H
15#define LLVM_IR_TYPE_H
16
17#include "llvm/ADT/APFloat.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/Support/CBindingWrapping.h"
21#include "llvm/Support/Casting.h"
22#include "llvm/Support/Compiler.h"
23#include "llvm/Support/ErrorHandling.h"
24#include "llvm/Support/TypeSize.h"
25#include <cassert>
26#include <cstdint>
27#include <iterator>
28
29namespace llvm {
30
31class IntegerType;
32class LLVMContext;
33class PointerType;
34class raw_ostream;
35class StringRef;
36
37/// The instances of the Type class are immutable: once they are created,
38/// they are never changed. Also note that only one instance of a particular
39/// type is ever created. Thus seeing if two types are equal is a matter of
40/// doing a trivial pointer comparison. To enforce that no two equal instances
41/// are created, Type instances can only be created via static factory methods
42/// in class Type and in derived classes. Once allocated, Types are never
43/// free'd.
44///
45class Type {
46public:
47 //===--------------------------------------------------------------------===//
48 /// Definitions of all of the base types for the Type system. Based on this
49 /// value, you can cast to a class defined in DerivedTypes.h.
50 /// Note: If you add an element to this, you need to add an element to the
51 /// Type::getPrimitiveType function, or else things will break!
52 /// Also update LLVMTypeKind and LLVMGetTypeKind () in the C binding.
53 ///
54 enum TypeID {
55 // PrimitiveTypes
56 HalfTyID = 0, ///< 16-bit floating point type
57 BFloatTyID, ///< 16-bit floating point type (7-bit significand)
58 FloatTyID, ///< 32-bit floating point type
59 DoubleTyID, ///< 64-bit floating point type
60 X86_FP80TyID, ///< 80-bit floating point type (X87)
61 FP128TyID, ///< 128-bit floating point type (112-bit significand)
62 PPC_FP128TyID, ///< 128-bit floating point type (two 64-bits, PowerPC)
63 VoidTyID, ///< type with no size
64 LabelTyID, ///< Labels
65 MetadataTyID, ///< Metadata
66 X86_MMXTyID, ///< MMX vectors (64 bits, X86 specific)
67 X86_AMXTyID, ///< AMX vectors (8192 bits, X86 specific)
68 TokenTyID, ///< Tokens
69
70 // Derived types... see DerivedTypes.h file.
71 IntegerTyID, ///< Arbitrary bit width integers
72 FunctionTyID, ///< Functions
73 PointerTyID, ///< Pointers
74 StructTyID, ///< Structures
75 ArrayTyID, ///< Arrays
76 FixedVectorTyID, ///< Fixed width SIMD vector type
77 ScalableVectorTyID ///< Scalable SIMD vector type
78 };
79
80private:
81 /// This refers to the LLVMContext in which this type was uniqued.
82 LLVMContext &Context;
83
84 TypeID ID : 8; // The current base type of this type.
85 unsigned SubclassData : 24; // Space for subclasses to store data.
86 // Note that this should be synchronized with
87 // MAX_INT_BITS value in IntegerType class.
88
89protected:
90 friend class LLVMContextImpl;
91
92 explicit Type(LLVMContext &C, TypeID tid)
93 : Context(C), ID(tid), SubclassData(0) {}
94 ~Type() = default;
95
96 unsigned getSubclassData() const { return SubclassData; }
97
98 void setSubclassData(unsigned val) {
99 SubclassData = val;
100 // Ensure we don't have any accidental truncation.
101 assert(getSubclassData() == val && "Subclass data too large for field")(static_cast <bool> (getSubclassData() == val &&
"Subclass data too large for field") ? void (0) : __assert_fail
("getSubclassData() == val && \"Subclass data too large for field\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/IR/Type.h"
, 101, __extension__ __PRETTY_FUNCTION__))
;
102 }
103
104 /// Keeps track of how many Type*'s there are in the ContainedTys list.
105 unsigned NumContainedTys = 0;
106
107 /// A pointer to the array of Types contained by this Type. For example, this
108 /// includes the arguments of a function type, the elements of a structure,
109 /// the pointee of a pointer, the element type of an array, etc. This pointer
110 /// may be 0 for types that don't contain other types (Integer, Double,
111 /// Float).
112 Type * const *ContainedTys = nullptr;
113
114public:
115 /// Print the current type.
116 /// Omit the type details if \p NoDetails == true.
117 /// E.g., let %st = type { i32, i16 }
118 /// When \p NoDetails is true, we only print %st.
119 /// Put differently, \p NoDetails prints the type as if
120 /// inlined with the operands when printing an instruction.
121 void print(raw_ostream &O, bool IsForDebug = false,
122 bool NoDetails = false) const;
123
124 void dump() const;
125
126 /// Return the LLVMContext in which this type was uniqued.
127 LLVMContext &getContext() const { return Context; }
128
129 //===--------------------------------------------------------------------===//
130 // Accessors for working with types.
131 //
132
133 /// Return the type id for the type. This will return one of the TypeID enum
134 /// elements defined above.
135 TypeID getTypeID() const { return ID; }
136
137 /// Return true if this is 'void'.
138 bool isVoidTy() const { return getTypeID() == VoidTyID; }
139
140 /// Return true if this is 'half', a 16-bit IEEE fp type.
141 bool isHalfTy() const { return getTypeID() == HalfTyID; }
142
143 /// Return true if this is 'bfloat', a 16-bit bfloat type.
144 bool isBFloatTy() const { return getTypeID() == BFloatTyID; }
145
146 /// Return true if this is 'float', a 32-bit IEEE fp type.
147 bool isFloatTy() const { return getTypeID() == FloatTyID; }
148
149 /// Return true if this is 'double', a 64-bit IEEE fp type.
150 bool isDoubleTy() const { return getTypeID() == DoubleTyID; }
151
152 /// Return true if this is x86 long double.
153 bool isX86_FP80Ty() const { return getTypeID() == X86_FP80TyID; }
154
155 /// Return true if this is 'fp128'.
156 bool isFP128Ty() const { return getTypeID() == FP128TyID; }
157
158 /// Return true if this is powerpc long double.
159 bool isPPC_FP128Ty() const { return getTypeID() == PPC_FP128TyID; }
160
161 /// Return true if this is one of the six floating-point types
162 bool isFloatingPointTy() const {
163 return getTypeID() == HalfTyID || getTypeID() == BFloatTyID ||
4
Assuming the condition is false
5
Assuming the condition is false
11
Returning zero, which participates in a condition later
164 getTypeID() == FloatTyID || getTypeID() == DoubleTyID ||
6
Assuming the condition is false
7
Assuming the condition is false
165 getTypeID() == X86_FP80TyID || getTypeID() == FP128TyID ||
8
Assuming the condition is false
9
Assuming the condition is false
166 getTypeID() == PPC_FP128TyID;
10
Assuming the condition is false
167 }
168
169 const fltSemantics &getFltSemantics() const {
170 switch (getTypeID()) {
171 case HalfTyID: return APFloat::IEEEhalf();
172 case BFloatTyID: return APFloat::BFloat();
173 case FloatTyID: return APFloat::IEEEsingle();
174 case DoubleTyID: return APFloat::IEEEdouble();
175 case X86_FP80TyID: return APFloat::x87DoubleExtended();
176 case FP128TyID: return APFloat::IEEEquad();
177 case PPC_FP128TyID: return APFloat::PPCDoubleDouble();
178 default: llvm_unreachable("Invalid floating type")::llvm::llvm_unreachable_internal("Invalid floating type", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/IR/Type.h"
, 178)
;
179 }
180 }
181
182 /// Return true if this is X86 MMX.
183 bool isX86_MMXTy() const { return getTypeID() == X86_MMXTyID; }
184
185 /// Return true if this is X86 AMX.
186 bool isX86_AMXTy() const { return getTypeID() == X86_AMXTyID; }
187
188 /// Return true if this is a FP type or a vector of FP.
189 bool isFPOrFPVectorTy() const { return getScalarType()->isFloatingPointTy(); }
190
191 /// Return true if this is 'label'.
192 bool isLabelTy() const { return getTypeID() == LabelTyID; }
193
194 /// Return true if this is 'metadata'.
195 bool isMetadataTy() const { return getTypeID() == MetadataTyID; }
196
197 /// Return true if this is 'token'.
198 bool isTokenTy() const { return getTypeID() == TokenTyID; }
199
200 /// True if this is an instance of IntegerType.
201 bool isIntegerTy() const { return getTypeID() == IntegerTyID; }
16
Assuming the condition is true
17
Returning the value 1, which participates in a condition later
20
Assuming the condition is true
21
Returning the value 1, which participates in a condition later
202
203 /// Return true if this is an IntegerType of the given width.
204 bool isIntegerTy(unsigned Bitwidth) const;
205
206 /// Return true if this is an integer type or a vector of integer types.
207 bool isIntOrIntVectorTy() const { return getScalarType()->isIntegerTy(); }
208
209 /// Return true if this is an integer type or a vector of integer types of
210 /// the given width.
211 bool isIntOrIntVectorTy(unsigned BitWidth) const {
212 return getScalarType()->isIntegerTy(BitWidth);
213 }
214
215 /// Return true if this is an integer type or a pointer type.
216 bool isIntOrPtrTy() const { return isIntegerTy() || isPointerTy(); }
217
218 /// True if this is an instance of FunctionType.
219 bool isFunctionTy() const { return getTypeID() == FunctionTyID; }
220
221 /// True if this is an instance of StructType.
222 bool isStructTy() const { return getTypeID() == StructTyID; }
223
224 /// True if this is an instance of ArrayType.
225 bool isArrayTy() const { return getTypeID() == ArrayTyID; }
226
227 /// True if this is an instance of PointerType.
228 bool isPointerTy() const { return getTypeID() == PointerTyID; }
229
230 /// True if this is an instance of an opaque PointerType.
231 bool isOpaquePointerTy() const;
232
233 /// Return true if this is a pointer type or a vector of pointer types.
234 bool isPtrOrPtrVectorTy() const { return getScalarType()->isPointerTy(); }
235
236 /// True if this is an instance of VectorType.
237 inline bool isVectorTy() const {
238 return getTypeID() == ScalableVectorTyID || getTypeID() == FixedVectorTyID;
239 }
240
241 /// Return true if this type could be converted with a lossless BitCast to
242 /// type 'Ty'. For example, i8* to i32*. BitCasts are valid for types of the
243 /// same size only where no re-interpretation of the bits is done.
244 /// Determine if this type could be losslessly bitcast to Ty
245 bool canLosslesslyBitCastTo(Type *Ty) const;
246
247 /// Return true if this type is empty, that is, it has no elements or all of
248 /// its elements are empty.
249 bool isEmptyTy() const;
250
251 /// Return true if the type is "first class", meaning it is a valid type for a
252 /// Value.
253 bool isFirstClassType() const {
254 return getTypeID() != FunctionTyID && getTypeID() != VoidTyID;
255 }
256
257 /// Return true if the type is a valid type for a register in codegen. This
258 /// includes all first-class types except struct and array types.
259 bool isSingleValueType() const {
260 return isFloatingPointTy() || isX86_MMXTy() || isIntegerTy() ||
261 isPointerTy() || isVectorTy() || isX86_AMXTy();
262 }
263
264 /// Return true if the type is an aggregate type. This means it is valid as
265 /// the first operand of an insertvalue or extractvalue instruction. This
266 /// includes struct and array types, but does not include vector types.
267 bool isAggregateType() const {
268 return getTypeID() == StructTyID || getTypeID() == ArrayTyID;
269 }
270
271 /// Return true if it makes sense to take the size of this type. To get the
272 /// actual size for a particular target, it is reasonable to use the
273 /// DataLayout subsystem to do this.
274 bool isSized(SmallPtrSetImpl<Type*> *Visited = nullptr) const {
275 // If it's a primitive, it is always sized.
276 if (getTypeID() == IntegerTyID || isFloatingPointTy() ||
277 getTypeID() == PointerTyID || getTypeID() == X86_MMXTyID ||
278 getTypeID() == X86_AMXTyID)
279 return true;
280 // If it is not something that can have a size (e.g. a function or label),
281 // it doesn't have a size.
282 if (getTypeID() != StructTyID && getTypeID() != ArrayTyID && !isVectorTy())
283 return false;
284 // Otherwise we have to try harder to decide.
285 return isSizedDerivedType(Visited);
286 }
287
288 /// Return the basic size of this type if it is a primitive type. These are
289 /// fixed by LLVM and are not target-dependent.
290 /// This will return zero if the type does not have a size or is not a
291 /// primitive type.
292 ///
293 /// If this is a scalable vector type, the scalable property will be set and
294 /// the runtime size will be a positive integer multiple of the base size.
295 ///
296 /// Note that this may not reflect the size of memory allocated for an
297 /// instance of the type or the number of bytes that are written when an
298 /// instance of the type is stored to memory. The DataLayout class provides
299 /// additional query functions to provide this information.
300 ///
301 TypeSize getPrimitiveSizeInBits() const LLVM_READONLY__attribute__((__pure__));
302
303 /// If this is a vector type, return the getPrimitiveSizeInBits value for the
304 /// element type. Otherwise return the getPrimitiveSizeInBits value for this
305 /// type.
306 unsigned getScalarSizeInBits() const LLVM_READONLY__attribute__((__pure__));
307
308 /// Return the width of the mantissa of this type. This is only valid on
309 /// floating-point types. If the FP type does not have a stable mantissa (e.g.
310 /// ppc long double), this method returns -1.
311 int getFPMantissaWidth() const;
312
313 /// Return whether the type is IEEE compatible, as defined by the eponymous
314 /// method in APFloat.
315 bool isIEEE() const { return APFloat::getZero(getFltSemantics()).isIEEE(); }
316
317 /// If this is a vector type, return the element type, otherwise return
318 /// 'this'.
319 inline Type *getScalarType() const {
320 if (isVectorTy())
321 return getContainedType(0);
322 return const_cast<Type *>(this);
323 }
324
325 //===--------------------------------------------------------------------===//
326 // Type Iteration support.
327 //
328 using subtype_iterator = Type * const *;
329
330 subtype_iterator subtype_begin() const { return ContainedTys; }
331 subtype_iterator subtype_end() const { return &ContainedTys[NumContainedTys];}
332 ArrayRef<Type*> subtypes() const {
333 return makeArrayRef(subtype_begin(), subtype_end());
334 }
335
336 using subtype_reverse_iterator = std::reverse_iterator<subtype_iterator>;
337
338 subtype_reverse_iterator subtype_rbegin() const {
339 return subtype_reverse_iterator(subtype_end());
340 }
341 subtype_reverse_iterator subtype_rend() const {
342 return subtype_reverse_iterator(subtype_begin());
343 }
344
345 /// This method is used to implement the type iterator (defined at the end of
346 /// the file). For derived types, this returns the types 'contained' in the
347 /// derived type.
348 Type *getContainedType(unsigned i) const {
349 assert(i < NumContainedTys && "Index out of range!")(static_cast <bool> (i < NumContainedTys && "Index out of range!"
) ? void (0) : __assert_fail ("i < NumContainedTys && \"Index out of range!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/IR/Type.h"
, 349, __extension__ __PRETTY_FUNCTION__))
;
350 return ContainedTys[i];
351 }
352
353 /// Return the number of types in the derived type.
354 unsigned getNumContainedTypes() const { return NumContainedTys; }
355
356 //===--------------------------------------------------------------------===//
357 // Helper methods corresponding to subclass methods. This forces a cast to
358 // the specified subclass and calls its accessor. "getArrayNumElements" (for
359 // example) is shorthand for cast<ArrayType>(Ty)->getNumElements(). This is
360 // only intended to cover the core methods that are frequently used, helper
361 // methods should not be added here.
362
363 inline unsigned getIntegerBitWidth() const;
364
365 inline Type *getFunctionParamType(unsigned i) const;
366 inline unsigned getFunctionNumParams() const;
367 inline bool isFunctionVarArg() const;
368
369 inline StringRef getStructName() const;
370 inline unsigned getStructNumElements() const;
371 inline Type *getStructElementType(unsigned N) const;
372
373 inline uint64_t getArrayNumElements() const;
374
375 Type *getArrayElementType() const {
376 assert(getTypeID() == ArrayTyID)(static_cast <bool> (getTypeID() == ArrayTyID) ? void (
0) : __assert_fail ("getTypeID() == ArrayTyID", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/IR/Type.h"
, 376, __extension__ __PRETTY_FUNCTION__))
;
377 return ContainedTys[0];
378 }
379
380 Type *getPointerElementType() const {
381 assert(getTypeID() == PointerTyID)(static_cast <bool> (getTypeID() == PointerTyID) ? void
(0) : __assert_fail ("getTypeID() == PointerTyID", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/IR/Type.h"
, 381, __extension__ __PRETTY_FUNCTION__))
;
382 return ContainedTys[0];
383 }
384
385 /// Given vector type, change the element type,
386 /// whilst keeping the old number of elements.
387 /// For non-vectors simply returns \p EltTy.
388 inline Type *getWithNewType(Type *EltTy) const;
389
390 /// Given an integer or vector type, change the lane bitwidth to NewBitwidth,
391 /// whilst keeping the old number of lanes.
392 inline Type *getWithNewBitWidth(unsigned NewBitWidth) const;
393
394 /// Given scalar/vector integer type, returns a type with elements twice as
395 /// wide as in the original type. For vectors, preserves element count.
396 inline Type *getExtendedType() const;
397
398 /// Get the address space of this pointer or pointer vector type.
399 inline unsigned getPointerAddressSpace() const;
400
401 //===--------------------------------------------------------------------===//
402 // Static members exported by the Type class itself. Useful for getting
403 // instances of Type.
404 //
405
406 /// Return a type based on an identifier.
407 static Type *getPrimitiveType(LLVMContext &C, TypeID IDNumber);
408
409 //===--------------------------------------------------------------------===//
410 // These are the builtin types that are always available.
411 //
412 static Type *getVoidTy(LLVMContext &C);
413 static Type *getLabelTy(LLVMContext &C);
414 static Type *getHalfTy(LLVMContext &C);
415 static Type *getBFloatTy(LLVMContext &C);
416 static Type *getFloatTy(LLVMContext &C);
417 static Type *getDoubleTy(LLVMContext &C);
418 static Type *getMetadataTy(LLVMContext &C);
419 static Type *getX86_FP80Ty(LLVMContext &C);
420 static Type *getFP128Ty(LLVMContext &C);
421 static Type *getPPC_FP128Ty(LLVMContext &C);
422 static Type *getX86_MMXTy(LLVMContext &C);
423 static Type *getX86_AMXTy(LLVMContext &C);
424 static Type *getTokenTy(LLVMContext &C);
425 static IntegerType *getIntNTy(LLVMContext &C, unsigned N);
426 static IntegerType *getInt1Ty(LLVMContext &C);
427 static IntegerType *getInt8Ty(LLVMContext &C);
428 static IntegerType *getInt16Ty(LLVMContext &C);
429 static IntegerType *getInt32Ty(LLVMContext &C);
430 static IntegerType *getInt64Ty(LLVMContext &C);
431 static IntegerType *getInt128Ty(LLVMContext &C);
432 template <typename ScalarTy> static Type *getScalarTy(LLVMContext &C) {
433 int noOfBits = sizeof(ScalarTy) * CHAR_BIT8;
434 if (std::is_integral<ScalarTy>::value) {
435 return (Type*) Type::getIntNTy(C, noOfBits);
436 } else if (std::is_floating_point<ScalarTy>::value) {
437 switch (noOfBits) {
438 case 32:
439 return Type::getFloatTy(C);
440 case 64:
441 return Type::getDoubleTy(C);
442 }
443 }
444 llvm_unreachable("Unsupported type in Type::getScalarTy")::llvm::llvm_unreachable_internal("Unsupported type in Type::getScalarTy"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/IR/Type.h"
, 444)
;
445 }
446 static Type *getFloatingPointTy(LLVMContext &C, const fltSemantics &S) {
447 Type *Ty;
448 if (&S == &APFloat::IEEEhalf())
449 Ty = Type::getHalfTy(C);
450 else if (&S == &APFloat::BFloat())
451 Ty = Type::getBFloatTy(C);
452 else if (&S == &APFloat::IEEEsingle())
453 Ty = Type::getFloatTy(C);
454 else if (&S == &APFloat::IEEEdouble())
455 Ty = Type::getDoubleTy(C);
456 else if (&S == &APFloat::x87DoubleExtended())
457 Ty = Type::getX86_FP80Ty(C);
458 else if (&S == &APFloat::IEEEquad())
459 Ty = Type::getFP128Ty(C);
460 else {
461 assert(&S == &APFloat::PPCDoubleDouble() && "Unknown FP format")(static_cast <bool> (&S == &APFloat::PPCDoubleDouble
() && "Unknown FP format") ? void (0) : __assert_fail
("&S == &APFloat::PPCDoubleDouble() && \"Unknown FP format\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/IR/Type.h"
, 461, __extension__ __PRETTY_FUNCTION__))
;
462 Ty = Type::getPPC_FP128Ty(C);
463 }
464 return Ty;
465 }
466
467 //===--------------------------------------------------------------------===//
468 // Convenience methods for getting pointer types with one of the above builtin
469 // types as pointee.
470 //
471 static PointerType *getHalfPtrTy(LLVMContext &C, unsigned AS = 0);
472 static PointerType *getBFloatPtrTy(LLVMContext &C, unsigned AS = 0);
473 static PointerType *getFloatPtrTy(LLVMContext &C, unsigned AS = 0);
474 static PointerType *getDoublePtrTy(LLVMContext &C, unsigned AS = 0);
475 static PointerType *getX86_FP80PtrTy(LLVMContext &C, unsigned AS = 0);
476 static PointerType *getFP128PtrTy(LLVMContext &C, unsigned AS = 0);
477 static PointerType *getPPC_FP128PtrTy(LLVMContext &C, unsigned AS = 0);
478 static PointerType *getX86_MMXPtrTy(LLVMContext &C, unsigned AS = 0);
479 static PointerType *getX86_AMXPtrTy(LLVMContext &C, unsigned AS = 0);
480 static PointerType *getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS = 0);
481 static PointerType *getInt1PtrTy(LLVMContext &C, unsigned AS = 0);
482 static PointerType *getInt8PtrTy(LLVMContext &C, unsigned AS = 0);
483 static PointerType *getInt16PtrTy(LLVMContext &C, unsigned AS = 0);
484 static PointerType *getInt32PtrTy(LLVMContext &C, unsigned AS = 0);
485 static PointerType *getInt64PtrTy(LLVMContext &C, unsigned AS = 0);
486
487 /// Return a pointer to the current type. This is equivalent to
488 /// PointerType::get(Foo, AddrSpace).
489 /// TODO: Remove this after opaque pointer transition is complete.
490 PointerType *getPointerTo(unsigned AddrSpace = 0) const;
491
492private:
493 /// Derived types like structures and arrays are sized iff all of the members
494 /// of the type are sized as well. Since asking for their size is relatively
495 /// uncommon, move this operation out-of-line.
496 bool isSizedDerivedType(SmallPtrSetImpl<Type*> *Visited = nullptr) const;
497};
498
499// Printing of types.
500inline raw_ostream &operator<<(raw_ostream &OS, const Type &T) {
501 T.print(OS);
502 return OS;
503}
504
505// allow isa<PointerType>(x) to work without DerivedTypes.h included.
506template <> struct isa_impl<PointerType, Type> {
507 static inline bool doit(const Type &Ty) {
508 return Ty.getTypeID() == Type::PointerTyID;
509 }
510};
511
512// Create wrappers for C Binding types (see CBindingWrapping.h).
513DEFINE_ISA_CONVERSION_FUNCTIONS(Type, LLVMTypeRef)inline Type *unwrap(LLVMTypeRef P) { return reinterpret_cast<
Type*>(P); } inline LLVMTypeRef wrap(const Type *P) { return
reinterpret_cast<LLVMTypeRef>(const_cast<Type*>(
P)); } template<typename T> inline T *unwrap(LLVMTypeRef
P) { return cast<T>(unwrap(P)); }
514
515/* Specialized opaque type conversions.
516 */
517inline Type **unwrap(LLVMTypeRef* Tys) {
518 return reinterpret_cast<Type**>(Tys);
519}
520
521inline LLVMTypeRef *wrap(Type **Tys) {
522 return reinterpret_cast<LLVMTypeRef*>(const_cast<Type**>(Tys));
523}
524
525} // end namespace llvm
526
527#endif // LLVM_IR_TYPE_H

/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h

1//===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file implements a class to represent arbitrary precision
11/// integral constant values and operations on them.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ADT_APINT_H
16#define LLVM_ADT_APINT_H
17
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/MathExtras.h"
20#include <cassert>
21#include <climits>
22#include <cstring>
23#include <utility>
24
25namespace llvm {
26class FoldingSetNodeID;
27class StringRef;
28class hash_code;
29class raw_ostream;
30
31template <typename T> class SmallVectorImpl;
32template <typename T> class ArrayRef;
33template <typename T> class Optional;
34template <typename T> struct DenseMapInfo;
35
36class APInt;
37
38inline APInt operator-(APInt);
39
40//===----------------------------------------------------------------------===//
41// APInt Class
42//===----------------------------------------------------------------------===//
43
44/// Class for arbitrary precision integers.
45///
46/// APInt is a functional replacement for common case unsigned integer type like
47/// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
48/// integer sizes and large integer value types such as 3-bits, 15-bits, or more
49/// than 64-bits of precision. APInt provides a variety of arithmetic operators
50/// and methods to manipulate integer values of any bit-width. It supports both
51/// the typical integer arithmetic and comparison operations as well as bitwise
52/// manipulation.
53///
54/// The class has several invariants worth noting:
55/// * All bit, byte, and word positions are zero-based.
56/// * Once the bit width is set, it doesn't change except by the Truncate,
57/// SignExtend, or ZeroExtend operations.
58/// * All binary operators must be on APInt instances of the same bit width.
59/// Attempting to use these operators on instances with different bit
60/// widths will yield an assertion.
61/// * The value is stored canonically as an unsigned value. For operations
62/// where it makes a difference, there are both signed and unsigned variants
63/// of the operation. For example, sdiv and udiv. However, because the bit
64/// widths must be the same, operations such as Mul and Add produce the same
65/// results regardless of whether the values are interpreted as signed or
66/// not.
67/// * In general, the class tries to follow the style of computation that LLVM
68/// uses in its IR. This simplifies its use for LLVM.
69/// * APInt supports zero-bit-width values, but operations that require bits
70/// are not defined on it (e.g. you cannot ask for the sign of a zero-bit
71/// integer). This means that operations like zero extension and logical
72/// shifts are defined, but sign extension and ashr is not. Zero bit values
73/// compare and hash equal to themselves, and countLeadingZeros returns 0.
74///
75class LLVM_NODISCARD[[clang::warn_unused_result]] APInt {
76public:
77 typedef uint64_t WordType;
78
79 /// This enum is used to hold the constants we needed for APInt.
80 enum : unsigned {
81 /// Byte size of a word.
82 APINT_WORD_SIZE = sizeof(WordType),
83 /// Bits in a word.
84 APINT_BITS_PER_WORD = APINT_WORD_SIZE * CHAR_BIT8
85 };
86
87 enum class Rounding {
88 DOWN,
89 TOWARD_ZERO,
90 UP,
91 };
92
93 static constexpr WordType WORDTYPE_MAX = ~WordType(0);
94
95 /// \name Constructors
96 /// @{
97
98 /// Create a new APInt of numBits width, initialized as val.
99 ///
100 /// If isSigned is true then val is treated as if it were a signed value
101 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
102 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
103 /// the range of val are zero filled).
104 ///
105 /// \param numBits the bit width of the constructed APInt
106 /// \param val the initial value of the APInt
107 /// \param isSigned how to treat signedness of val
108 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
109 : BitWidth(numBits) {
110 if (isSingleWord()) {
111 U.VAL = val;
112 clearUnusedBits();
113 } else {
114 initSlowCase(val, isSigned);
115 }
116 }
117
118 /// Construct an APInt of numBits width, initialized as bigVal[].
119 ///
120 /// Note that bigVal.size() can be smaller or larger than the corresponding
121 /// bit width but any extraneous bits will be dropped.
122 ///
123 /// \param numBits the bit width of the constructed APInt
124 /// \param bigVal a sequence of words to form the initial value of the APInt
125 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
126
127 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
128 /// deprecated because this constructor is prone to ambiguity with the
129 /// APInt(unsigned, uint64_t, bool) constructor.
130 ///
131 /// If this overload is ever deleted, care should be taken to prevent calls
132 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
133 /// constructor.
134 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
135
136 /// Construct an APInt from a string representation.
137 ///
138 /// This constructor interprets the string \p str in the given radix. The
139 /// interpretation stops when the first character that is not suitable for the
140 /// radix is encountered, or the end of the string. Acceptable radix values
141 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
142 /// string to require more bits than numBits.
143 ///
144 /// \param numBits the bit width of the constructed APInt
145 /// \param str the string to be interpreted
146 /// \param radix the radix to use for the conversion
147 APInt(unsigned numBits, StringRef str, uint8_t radix);
148
149 /// Default constructor that creates an APInt with a 1-bit zero value.
150 explicit APInt() : BitWidth(1) { U.VAL = 0; }
151
152 /// Copy Constructor.
153 APInt(const APInt &that) : BitWidth(that.BitWidth) {
154 if (isSingleWord())
155 U.VAL = that.U.VAL;
156 else
157 initSlowCase(that);
158 }
159
160 /// Move Constructor.
161 APInt(APInt &&that) : BitWidth(that.BitWidth) {
162 memcpy(&U, &that.U, sizeof(U));
163 that.BitWidth = 0;
164 }
165
166 /// Destructor.
167 ~APInt() {
168 if (needsCleanup())
169 delete[] U.pVal;
170 }
171
172 /// @}
173 /// \name Value Generators
174 /// @{
175
176 /// Get the '0' value for the specified bit-width.
177 static APInt getZero(unsigned numBits) { return APInt(numBits, 0); }
178
179 /// NOTE: This is soft-deprecated. Please use `getZero()` instead.
180 static APInt getNullValue(unsigned numBits) { return getZero(numBits); }
181
182 /// Return an APInt zero bits wide.
183 static APInt getZeroWidth() { return getZero(0); }
184
185 /// Gets maximum unsigned value of APInt for specific bit width.
186 static APInt getMaxValue(unsigned numBits) {
187 return getAllOnesValue(numBits);
188 }
189
190 /// Gets maximum signed value of APInt for a specific bit width.
191 static APInt getSignedMaxValue(unsigned numBits) {
192 APInt API = getAllOnesValue(numBits);
193 API.clearBit(numBits - 1);
194 return API;
195 }
196
197 /// Gets minimum unsigned value of APInt for a specific bit width.
198 static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); }
199
200 /// Gets minimum signed value of APInt for a specific bit width.
201 static APInt getSignedMinValue(unsigned numBits) {
202 APInt API(numBits, 0);
203 API.setBit(numBits - 1);
204 return API;
205 }
206
207 /// Get the SignMask for a specific bit width.
208 ///
209 /// This is just a wrapper function of getSignedMinValue(), and it helps code
210 /// readability when we want to get a SignMask.
211 static APInt getSignMask(unsigned BitWidth) {
212 return getSignedMinValue(BitWidth);
213 }
214
215 /// Return an APInt of a specified width with all bits set.
216 static APInt getAllOnes(unsigned numBits) {
217 return APInt(numBits, WORDTYPE_MAX, true);
218 }
219
220 /// NOTE: This is soft-deprecated. Please use `getAllOnes()` instead.
221 static APInt getAllOnesValue(unsigned numBits) { return getAllOnes(numBits); }
222
223 /// Return an APInt with exactly one bit set in the result.
224 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
225 APInt Res(numBits, 0);
226 Res.setBit(BitNo);
227 return Res;
228 }
229
230 /// Get a value with a block of bits set.
231 ///
232 /// Constructs an APInt value that has a contiguous range of bits set. The
233 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
234 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
235 /// 0x0000FFFF. Please call getBitsSetWithWrap if \p loBit may be greater than
236 /// \p hiBit.
237 ///
238 /// \param numBits the intended bit width of the result
239 /// \param loBit the index of the lowest bit set.
240 /// \param hiBit the index of the highest bit set.
241 ///
242 /// \returns An APInt value with the requested bits set.
243 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
244 APInt Res(numBits, 0);
245 Res.setBits(loBit, hiBit);
246 return Res;
247 }
248
249 /// Wrap version of getBitsSet.
250 /// If \p hiBit is bigger than \p loBit, this is same with getBitsSet.
251 /// If \p hiBit is not bigger than \p loBit, the set bits "wrap". For example,
252 /// with parameters (32, 28, 4), you would get 0xF000000F.
253 /// If \p hiBit is equal to \p loBit, you would get a result with all bits
254 /// set.
255 static APInt getBitsSetWithWrap(unsigned numBits, unsigned loBit,
256 unsigned hiBit) {
257 APInt Res(numBits, 0);
258 Res.setBitsWithWrap(loBit, hiBit);
259 return Res;
260 }
261
262 /// Constructs an APInt value that has a contiguous range of bits set. The
263 /// bits from loBit (inclusive) to numBits (exclusive) will be set. All other
264 /// bits will be zero. For example, with parameters(32, 12) you would get
265 /// 0xFFFFF000.
266 ///
267 /// \param numBits the intended bit width of the result
268 /// \param loBit the index of the lowest bit to set.
269 ///
270 /// \returns An APInt value with the requested bits set.
271 static APInt getBitsSetFrom(unsigned numBits, unsigned loBit) {
272 APInt Res(numBits, 0);
273 Res.setBitsFrom(loBit);
274 return Res;
275 }
276
277 /// Constructs an APInt value that has the top hiBitsSet bits set.
278 ///
279 /// \param numBits the bitwidth of the result
280 /// \param hiBitsSet the number of high-order bits set in the result.
281 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
282 APInt Res(numBits, 0);
283 Res.setHighBits(hiBitsSet);
284 return Res;
285 }
286
287 /// Constructs an APInt value that has the bottom loBitsSet bits set.
288 ///
289 /// \param numBits the bitwidth of the result
290 /// \param loBitsSet the number of low-order bits set in the result.
291 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
292 APInt Res(numBits, 0);
293 Res.setLowBits(loBitsSet);
294 return Res;
295 }
296
297 /// Return a value containing V broadcasted over NewLen bits.
298 static APInt getSplat(unsigned NewLen, const APInt &V);
299
300 /// @}
301 /// \name Value Tests
302 /// @{
303
304 /// Determine if this APInt just has one word to store value.
305 ///
306 /// \returns true if the number of bits <= 64, false otherwise.
307 bool isSingleWord() const { return BitWidth
54.1
Field 'BitWidth' is > APINT_BITS_PER_WORD
54.1
Field 'BitWidth' is > APINT_BITS_PER_WORD
54.1
Field 'BitWidth' is > APINT_BITS_PER_WORD
<= APINT_BITS_PER_WORD
; }
43
Assuming field 'BitWidth' is > APINT_BITS_PER_WORD
44
Returning zero, which participates in a condition later
55
Returning zero, which participates in a condition later
308
309 /// Determine sign of this APInt.
310 ///
311 /// This tests the high bit of this APInt to determine if it is set.
312 ///
313 /// \returns true if this APInt is negative, false otherwise
314 bool isNegative() const { return (*this)[BitWidth - 1]; }
315
316 /// Determine if this APInt Value is non-negative (>= 0)
317 ///
318 /// This tests the high bit of the APInt to determine if it is unset.
319 bool isNonNegative() const { return !isNegative(); }
320
321 /// Determine if sign bit of this APInt is set.
322 ///
323 /// This tests the high bit of this APInt to determine if it is set.
324 ///
325 /// \returns true if this APInt has its sign bit set, false otherwise.
326 bool isSignBitSet() const { return (*this)[BitWidth - 1]; }
327
328 /// Determine if sign bit of this APInt is clear.
329 ///
330 /// This tests the high bit of this APInt to determine if it is clear.
331 ///
332 /// \returns true if this APInt has its sign bit clear, false otherwise.
333 bool isSignBitClear() const { return !isSignBitSet(); }
334
335 /// Determine if this APInt Value is positive.
336 ///
337 /// This tests if the value of this APInt is positive (> 0). Note
338 /// that 0 is not a positive value.
339 ///
340 /// \returns true if this APInt is positive.
341 bool isStrictlyPositive() const { return isNonNegative() && !isZero(); }
342
343 /// Determine if this APInt Value is non-positive (<= 0).
344 ///
345 /// \returns true if this APInt is non-positive.
346 bool isNonPositive() const { return !isStrictlyPositive(); }
347
348 /// Determine if all bits are set.
349 bool isAllOnes() const {
350 if (isSingleWord()) {
351 // Calculate the shift amount, handling the zero-bit wide case without UB.
352 unsigned ShiftAmt =
353 (APINT_BITS_PER_WORD - BitWidth) % APINT_BITS_PER_WORD;
354 return U.VAL == WORDTYPE_MAX >> ShiftAmt;
355 }
356 return countTrailingOnesSlowCase() == BitWidth;
357 }
358
359 /// NOTE: This is soft-deprecated. Please use `isAllOnes()` instead.
360 bool isAllOnesValue() const { return isAllOnes(); }
361
362 /// Determine if this value is zero, i.e. all bits are clear.
363 bool isZero() const {
364 if (isSingleWord())
54
Calling 'APInt::isSingleWord'
56
Returning from 'APInt::isSingleWord'
57
Taking false branch
365 return U.VAL == 0;
366 return countLeadingZerosSlowCase() == BitWidth;
58
Assuming the condition is false
59
Returning zero, which participates in a condition later
367 }
368
369 /// NOTE: This is soft-deprecated. Please use `isZero()` instead.
370 bool isNullValue() const { return isZero(); }
53
Calling 'APInt::isZero'
60
Returning from 'APInt::isZero'
61
Returning zero, which participates in a condition later
371
372 /// Determine if this is a value of 1.
373 ///
374 /// This checks to see if the value of this APInt is one.
375 bool isOne() const {
376 if (isSingleWord())
42
Calling 'APInt::isSingleWord'
45
Returning from 'APInt::isSingleWord'
46
Taking false branch
377 return U.VAL == 1;
378 return countLeadingZerosSlowCase() == BitWidth - 1;
47
Assuming the condition is false
48
Returning zero, which participates in a condition later
379 }
380
381 /// NOTE: This is soft-deprecated. Please use `isOne()` instead.
382 bool isOneValue() const { return isOne(); }
41
Calling 'APInt::isOne'
49
Returning from 'APInt::isOne'
50
Returning zero, which participates in a condition later
383
384 /// Determine if this is the largest unsigned value.
385 ///
386 /// This checks to see if the value of this APInt is the maximum unsigned
387 /// value for the APInt's bit width.
388 bool isMaxValue() const { return isAllOnes(); }
389
390 /// Determine if this is the largest signed value.
391 ///
392 /// This checks to see if the value of this APInt is the maximum signed
393 /// value for the APInt's bit width.
394 bool isMaxSignedValue() const {
395 if (isSingleWord()) {
396 assert(BitWidth && "zero width values not allowed")(static_cast <bool> (BitWidth && "zero width values not allowed"
) ? void (0) : __assert_fail ("BitWidth && \"zero width values not allowed\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 396, __extension__ __PRETTY_FUNCTION__))
;
397 return U.VAL == ((WordType(1) << (BitWidth - 1)) - 1);
398 }
399 return !isNegative() && countTrailingOnesSlowCase() == BitWidth - 1;
400 }
401
402 /// Determine if this is the smallest unsigned value.
403 ///
404 /// This checks to see if the value of this APInt is the minimum unsigned
405 /// value for the APInt's bit width.
406 bool isMinValue() const { return isZero(); }
407
408 /// Determine if this is the smallest signed value.
409 ///
410 /// This checks to see if the value of this APInt is the minimum signed
411 /// value for the APInt's bit width.
412 bool isMinSignedValue() const {
413 if (isSingleWord()) {
414 assert(BitWidth && "zero width values not allowed")(static_cast <bool> (BitWidth && "zero width values not allowed"
) ? void (0) : __assert_fail ("BitWidth && \"zero width values not allowed\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 414, __extension__ __PRETTY_FUNCTION__))
;
415 return U.VAL == (WordType(1) << (BitWidth - 1));
416 }
417 return isNegative() && countTrailingZerosSlowCase() == BitWidth - 1;
418 }
419
420 /// Check if this APInt has an N-bits unsigned integer value.
421 bool isIntN(unsigned N) const { return getActiveBits() <= N; }
422
423 /// Check if this APInt has an N-bits signed integer value.
424 bool isSignedIntN(unsigned N) const { return getMinSignedBits() <= N; }
425
426 /// Check if this APInt's value is a power of two greater than zero.
427 ///
428 /// \returns true if the argument APInt value is a power of two > 0.
429 bool isPowerOf2() const {
430 if (isSingleWord()) {
431 assert(BitWidth && "zero width values not allowed")(static_cast <bool> (BitWidth && "zero width values not allowed"
) ? void (0) : __assert_fail ("BitWidth && \"zero width values not allowed\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 431, __extension__ __PRETTY_FUNCTION__))
;
432 return isPowerOf2_64(U.VAL);
433 }
434 return countPopulationSlowCase() == 1;
435 }
436
437 /// Check if the APInt's value is returned by getSignMask.
438 ///
439 /// \returns true if this is the value returned by getSignMask.
440 bool isSignMask() const { return isMinSignedValue(); }
441
442 /// Convert APInt to a boolean value.
443 ///
444 /// This converts the APInt to a boolean value as a test against zero.
445 bool getBoolValue() const { return !isZero(); }
446
447 /// If this value is smaller than the specified limit, return it, otherwise
448 /// return the limit value. This causes the value to saturate to the limit.
449 uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX(18446744073709551615UL)) const {
450 return ugt(Limit) ? Limit : getZExtValue();
451 }
452
453 /// Check if the APInt consists of a repeated bit pattern.
454 ///
455 /// e.g. 0x01010101 satisfies isSplat(8).
456 /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit
457 /// width without remainder.
458 bool isSplat(unsigned SplatSizeInBits) const;
459
460 /// \returns true if this APInt value is a sequence of \param numBits ones
461 /// starting at the least significant bit with the remainder zero.
462 bool isMask(unsigned numBits) const {
463 assert(numBits != 0 && "numBits must be non-zero")(static_cast <bool> (numBits != 0 && "numBits must be non-zero"
) ? void (0) : __assert_fail ("numBits != 0 && \"numBits must be non-zero\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 463, __extension__ __PRETTY_FUNCTION__))
;
464 assert(numBits <= BitWidth && "numBits out of range")(static_cast <bool> (numBits <= BitWidth && "numBits out of range"
) ? void (0) : __assert_fail ("numBits <= BitWidth && \"numBits out of range\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 464, __extension__ __PRETTY_FUNCTION__))
;
465 if (isSingleWord())
466 return U.VAL == (WORDTYPE_MAX >> (APINT_BITS_PER_WORD - numBits));
467 unsigned Ones = countTrailingOnesSlowCase();
468 return (numBits == Ones) &&
469 ((Ones + countLeadingZerosSlowCase()) == BitWidth);
470 }
471
472 /// \returns true if this APInt is a non-empty sequence of ones starting at
473 /// the least significant bit with the remainder zero.
474 /// Ex. isMask(0x0000FFFFU) == true.
475 bool isMask() const {
476 if (isSingleWord())
477 return isMask_64(U.VAL);
478 unsigned Ones = countTrailingOnesSlowCase();
479 return (Ones > 0) && ((Ones + countLeadingZerosSlowCase()) == BitWidth);
480 }
481
482 /// Return true if this APInt value contains a sequence of ones with
483 /// the remainder zero.
484 bool isShiftedMask() const {
485 if (isSingleWord())
486 return isShiftedMask_64(U.VAL);
487 unsigned Ones = countPopulationSlowCase();
488 unsigned LeadZ = countLeadingZerosSlowCase();
489 return (Ones + LeadZ + countTrailingZeros()) == BitWidth;
490 }
491
492 /// Compute an APInt containing numBits highbits from this APInt.
493 ///
494 /// Get an APInt with the same BitWidth as this APInt, just zero mask the low
495 /// bits and right shift to the least significant bit.
496 ///
497 /// \returns the high "numBits" bits of this APInt.
498 APInt getHiBits(unsigned numBits) const;
499
500 /// Compute an APInt containing numBits lowbits from this APInt.
501 ///
502 /// Get an APInt with the same BitWidth as this APInt, just zero mask the high
503 /// bits.
504 ///
505 /// \returns the low "numBits" bits of this APInt.
506 APInt getLoBits(unsigned numBits) const;
507
508 /// Determine if two APInts have the same value, after zero-extending
509 /// one of them (if needed!) to ensure that the bit-widths match.
510 static bool isSameValue(const APInt &I1, const APInt &I2) {
511 if (I1.getBitWidth() == I2.getBitWidth())
512 return I1 == I2;
513
514 if (I1.getBitWidth() > I2.getBitWidth())
515 return I1 == I2.zext(I1.getBitWidth());
516
517 return I1.zext(I2.getBitWidth()) == I2;
518 }
519
520 /// Overload to compute a hash_code for an APInt value.
521 friend hash_code hash_value(const APInt &Arg);
522
523 /// This function returns a pointer to the internal storage of the APInt.
524 /// This is useful for writing out the APInt in binary form without any
525 /// conversions.
526 const uint64_t *getRawData() const {
527 if (isSingleWord())
528 return &U.VAL;
529 return &U.pVal[0];
530 }
531
532 /// @}
533 /// \name Unary Operators
534 /// @{
535
536 /// Postfix increment operator. Increment *this by 1.
537 ///
538 /// \returns a new APInt value representing the original value of *this.
539 APInt operator++(int) {
540 APInt API(*this);
541 ++(*this);
542 return API;
543 }
544
545 /// Prefix increment operator.
546 ///
547 /// \returns *this incremented by one
548 APInt &operator++();
549
550 /// Postfix decrement operator. Decrement *this by 1.
551 ///
552 /// \returns a new APInt value representing the original value of *this.
553 APInt operator--(int) {
554 APInt API(*this);
555 --(*this);
556 return API;
557 }
558
559 /// Prefix decrement operator.
560 ///
561 /// \returns *this decremented by one.
562 APInt &operator--();
563
564 /// Logical negation operation on this APInt returns true if zero, like normal
565 /// integers.
566 bool operator!() const { return isZero(); }
567
568 /// @}
569 /// \name Assignment Operators
570 /// @{
571
572 /// Copy assignment operator.
573 ///
574 /// \returns *this after assignment of RHS.
575 APInt &operator=(const APInt &RHS) {
576 // The common case (both source or dest being inline) doesn't require
577 // allocation or deallocation.
578 if (isSingleWord() && RHS.isSingleWord()) {
579 U.VAL = RHS.U.VAL;
580 BitWidth = RHS.BitWidth;
581 return *this;
582 }
583
584 assignSlowCase(RHS);
585 return *this;
586 }
587
588 /// Move assignment operator.
589 APInt &operator=(APInt &&that) {
590#ifdef EXPENSIVE_CHECKS
591 // Some std::shuffle implementations still do self-assignment.
592 if (this == &that)
593 return *this;
594#endif
595 assert(this != &that && "Self-move not supported")(static_cast <bool> (this != &that && "Self-move not supported"
) ? void (0) : __assert_fail ("this != &that && \"Self-move not supported\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 595, __extension__ __PRETTY_FUNCTION__))
;
596 if (!isSingleWord())
597 delete[] U.pVal;
598
599 // Use memcpy so that type based alias analysis sees both VAL and pVal
600 // as modified.
601 memcpy(&U, &that.U, sizeof(U));
602
603 BitWidth = that.BitWidth;
604 that.BitWidth = 0;
605 return *this;
606 }
607
608 /// Assignment operator.
609 ///
610 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
611 /// the bit width, the excess bits are truncated. If the bit width is larger
612 /// than 64, the value is zero filled in the unspecified high order bits.
613 ///
614 /// \returns *this after assignment of RHS value.
615 APInt &operator=(uint64_t RHS) {
616 if (isSingleWord()) {
617 U.VAL = RHS;
618 return clearUnusedBits();
619 }
620 U.pVal[0] = RHS;
621 memset(U.pVal + 1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
622 return *this;
623 }
624
625 /// Bitwise AND assignment operator.
626 ///
627 /// Performs a bitwise AND operation on this APInt and RHS. The result is
628 /// assigned to *this.
629 ///
630 /// \returns *this after ANDing with RHS.
631 APInt &operator&=(const APInt &RHS) {
632 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Bit widths must be the same") ? void (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 632, __extension__ __PRETTY_FUNCTION__))
;
633 if (isSingleWord())
634 U.VAL &= RHS.U.VAL;
635 else
636 andAssignSlowCase(RHS);
637 return *this;
638 }
639
640 /// Bitwise AND assignment operator.
641 ///
642 /// Performs a bitwise AND operation on this APInt and RHS. RHS is
643 /// logically zero-extended or truncated to match the bit-width of
644 /// the LHS.
645 APInt &operator&=(uint64_t RHS) {
646 if (isSingleWord()) {
647 U.VAL &= RHS;
648 return *this;
649 }
650 U.pVal[0] &= RHS;
651 memset(U.pVal + 1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
652 return *this;
653 }
654
655 /// Bitwise OR assignment operator.
656 ///
657 /// Performs a bitwise OR operation on this APInt and RHS. The result is
658 /// assigned *this;
659 ///
660 /// \returns *this after ORing with RHS.
661 APInt &operator|=(const APInt &RHS) {
662 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Bit widths must be the same") ? void (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 662, __extension__ __PRETTY_FUNCTION__))
;
663 if (isSingleWord())
664 U.VAL |= RHS.U.VAL;
665 else
666 orAssignSlowCase(RHS);
667 return *this;
668 }
669
670 /// Bitwise OR assignment operator.
671 ///
672 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
673 /// logically zero-extended or truncated to match the bit-width of
674 /// the LHS.
675 APInt &operator|=(uint64_t RHS) {
676 if (isSingleWord()) {
677 U.VAL |= RHS;
678 return clearUnusedBits();
679 }
680 U.pVal[0] |= RHS;
681 return *this;
682 }
683
684 /// Bitwise XOR assignment operator.
685 ///
686 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
687 /// assigned to *this.
688 ///
689 /// \returns *this after XORing with RHS.
690 APInt &operator^=(const APInt &RHS) {
691 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Bit widths must be the same") ? void (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 691, __extension__ __PRETTY_FUNCTION__))
;
692 if (isSingleWord())
693 U.VAL ^= RHS.U.VAL;
694 else
695 xorAssignSlowCase(RHS);
696 return *this;
697 }
698
699 /// Bitwise XOR assignment operator.
700 ///
701 /// Performs a bitwise XOR operation on this APInt and RHS. RHS is
702 /// logically zero-extended or truncated to match the bit-width of
703 /// the LHS.
704 APInt &operator^=(uint64_t RHS) {
705 if (isSingleWord()) {
706 U.VAL ^= RHS;
707 return clearUnusedBits();
708 }
709 U.pVal[0] ^= RHS;
710 return *this;
711 }
712
713 /// Multiplication assignment operator.
714 ///
715 /// Multiplies this APInt by RHS and assigns the result to *this.
716 ///
717 /// \returns *this
718 APInt &operator*=(const APInt &RHS);
719 APInt &operator*=(uint64_t RHS);
720
721 /// Addition assignment operator.
722 ///
723 /// Adds RHS to *this and assigns the result to *this.
724 ///
725 /// \returns *this
726 APInt &operator+=(const APInt &RHS);
727 APInt &operator+=(uint64_t RHS);
728
729 /// Subtraction assignment operator.
730 ///
731 /// Subtracts RHS from *this and assigns the result to *this.
732 ///
733 /// \returns *this
734 APInt &operator-=(const APInt &RHS);
735 APInt &operator-=(uint64_t RHS);
736
737 /// Left-shift assignment function.
738 ///
739 /// Shifts *this left by shiftAmt and assigns the result to *this.
740 ///
741 /// \returns *this after shifting left by ShiftAmt
742 APInt &operator<<=(unsigned ShiftAmt) {
743 assert(ShiftAmt <= BitWidth && "Invalid shift amount")(static_cast <bool> (ShiftAmt <= BitWidth &&
"Invalid shift amount") ? void (0) : __assert_fail ("ShiftAmt <= BitWidth && \"Invalid shift amount\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 743, __extension__ __PRETTY_FUNCTION__))
;
744 if (isSingleWord()) {
745 if (ShiftAmt == BitWidth)
746 U.VAL = 0;
747 else
748 U.VAL <<= ShiftAmt;
749 return clearUnusedBits();
750 }
751 shlSlowCase(ShiftAmt);
752 return *this;
753 }
754
755 /// Left-shift assignment function.
756 ///
757 /// Shifts *this left by shiftAmt and assigns the result to *this.
758 ///
759 /// \returns *this after shifting left by ShiftAmt
760 APInt &operator<<=(const APInt &ShiftAmt);
761
762 /// @}
763 /// \name Binary Operators
764 /// @{
765
766 /// Multiplication operator.
767 ///
768 /// Multiplies this APInt by RHS and returns the result.
769 APInt operator*(const APInt &RHS) const;
770
771 /// Left logical shift operator.
772 ///
773 /// Shifts this APInt left by \p Bits and returns the result.
774 APInt operator<<(unsigned Bits) const { return shl(Bits); }
775
776 /// Left logical shift operator.
777 ///
778 /// Shifts this APInt left by \p Bits and returns the result.
779 APInt operator<<(const APInt &Bits) const { return shl(Bits); }
780
781 /// Arithmetic right-shift function.
782 ///
783 /// Arithmetic right-shift this APInt by shiftAmt.
784 APInt ashr(unsigned ShiftAmt) const {
785 APInt R(*this);
786 R.ashrInPlace(ShiftAmt);
787 return R;
788 }
789
790 /// Arithmetic right-shift this APInt by ShiftAmt in place.
791 void ashrInPlace(unsigned ShiftAmt) {
792 assert(ShiftAmt <= BitWidth && "Invalid shift amount")(static_cast <bool> (ShiftAmt <= BitWidth &&
"Invalid shift amount") ? void (0) : __assert_fail ("ShiftAmt <= BitWidth && \"Invalid shift amount\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 792, __extension__ __PRETTY_FUNCTION__))
;
793 if (isSingleWord()) {
794 int64_t SExtVAL = SignExtend64(U.VAL, BitWidth);
795 if (ShiftAmt == BitWidth)
796 U.VAL = SExtVAL >> (APINT_BITS_PER_WORD - 1); // Fill with sign bit.
797 else
798 U.VAL = SExtVAL >> ShiftAmt;
799 clearUnusedBits();
800 return;
801 }
802 ashrSlowCase(ShiftAmt);
803 }
804
805 /// Logical right-shift function.
806 ///
807 /// Logical right-shift this APInt by shiftAmt.
808 APInt lshr(unsigned shiftAmt) const {
809 APInt R(*this);
810 R.lshrInPlace(shiftAmt);
811 return R;
812 }
813
814 /// Logical right-shift this APInt by ShiftAmt in place.
815 void lshrInPlace(unsigned ShiftAmt) {
816 assert(ShiftAmt <= BitWidth && "Invalid shift amount")(static_cast <bool> (ShiftAmt <= BitWidth &&
"Invalid shift amount") ? void (0) : __assert_fail ("ShiftAmt <= BitWidth && \"Invalid shift amount\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 816, __extension__ __PRETTY_FUNCTION__))
;
817 if (isSingleWord()) {
818 if (ShiftAmt == BitWidth)
819 U.VAL = 0;
820 else
821 U.VAL >>= ShiftAmt;
822 return;
823 }
824 lshrSlowCase(ShiftAmt);
825 }
826
827 /// Left-shift function.
828 ///
829 /// Left-shift this APInt by shiftAmt.
830 APInt shl(unsigned shiftAmt) const {
831 APInt R(*this);
832 R <<= shiftAmt;
833 return R;
834 }
835
836 /// Rotate left by rotateAmt.
837 APInt rotl(unsigned rotateAmt) const;
838
839 /// Rotate right by rotateAmt.
840 APInt rotr(unsigned rotateAmt) const;
841
842 /// Arithmetic right-shift function.
843 ///
844 /// Arithmetic right-shift this APInt by shiftAmt.
845 APInt ashr(const APInt &ShiftAmt) const {
846 APInt R(*this);
847 R.ashrInPlace(ShiftAmt);
848 return R;
849 }
850
851 /// Arithmetic right-shift this APInt by shiftAmt in place.
852 void ashrInPlace(const APInt &shiftAmt);
853
854 /// Logical right-shift function.
855 ///
856 /// Logical right-shift this APInt by shiftAmt.
857 APInt lshr(const APInt &ShiftAmt) const {
858 APInt R(*this);
859 R.lshrInPlace(ShiftAmt);
860 return R;
861 }
862
863 /// Logical right-shift this APInt by ShiftAmt in place.
864 void lshrInPlace(const APInt &ShiftAmt);
865
866 /// Left-shift function.
867 ///
868 /// Left-shift this APInt by shiftAmt.
869 APInt shl(const APInt &ShiftAmt) const {
870 APInt R(*this);
871 R <<= ShiftAmt;
872 return R;
873 }
874
875 /// Rotate left by rotateAmt.
876 APInt rotl(const APInt &rotateAmt) const;
877
878 /// Rotate right by rotateAmt.
879 APInt rotr(const APInt &rotateAmt) const;
880
881 /// Concatenate the bits from "NewLSB" onto the bottom of *this. This is
882 /// equivalent to:
883 /// (this->zext(NewWidth) << NewLSB.getBitWidth()) | NewLSB.zext(NewWidth)
884 APInt concat(const APInt &NewLSB) const {
885 /// If the result will be small, then both the merged values are small.
886 unsigned NewWidth = getBitWidth() + NewLSB.getBitWidth();
887 if (NewWidth <= APINT_BITS_PER_WORD)
888 return APInt(NewWidth, (U.VAL << NewLSB.getBitWidth()) | NewLSB.U.VAL);
889 return concatSlowCase(NewLSB);
890 }
891
892 /// Unsigned division operation.
893 ///
894 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
895 /// RHS are treated as unsigned quantities for purposes of this division.
896 ///
897 /// \returns a new APInt value containing the division result, rounded towards
898 /// zero.
899 APInt udiv(const APInt &RHS) const;
900 APInt udiv(uint64_t RHS) const;
901
902 /// Signed division function for APInt.
903 ///
904 /// Signed divide this APInt by APInt RHS.
905 ///
906 /// The result is rounded towards zero.
907 APInt sdiv(const APInt &RHS) const;
908 APInt sdiv(int64_t RHS) const;
909
910 /// Unsigned remainder operation.
911 ///
912 /// Perform an unsigned remainder operation on this APInt with RHS being the
913 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
914 /// of this operation. Note that this is a true remainder operation and not a
915 /// modulo operation because the sign follows the sign of the dividend which
916 /// is *this.
917 ///
918 /// \returns a new APInt value containing the remainder result
919 APInt urem(const APInt &RHS) const;
920 uint64_t urem(uint64_t RHS) const;
921
922 /// Function for signed remainder operation.
923 ///
924 /// Signed remainder operation on APInt.
925 APInt srem(const APInt &RHS) const;
926 int64_t srem(int64_t RHS) const;
927
928 /// Dual division/remainder interface.
929 ///
930 /// Sometimes it is convenient to divide two APInt values and obtain both the
931 /// quotient and remainder. This function does both operations in the same
932 /// computation making it a little more efficient. The pair of input arguments
933 /// may overlap with the pair of output arguments. It is safe to call
934 /// udivrem(X, Y, X, Y), for example.
935 static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
936 APInt &Remainder);
937 static void udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
938 uint64_t &Remainder);
939
940 static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
941 APInt &Remainder);
942 static void sdivrem(const APInt &LHS, int64_t RHS, APInt &Quotient,
943 int64_t &Remainder);
944
945 // Operations that return overflow indicators.
946 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
947 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
948 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
949 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
950 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
951 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
952 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
953 APInt sshl_ov(const APInt &Amt, bool &Overflow) const;
954 APInt ushl_ov(const APInt &Amt, bool &Overflow) const;
955
956 // Operations that saturate
957 APInt sadd_sat(const APInt &RHS) const;
958 APInt uadd_sat(const APInt &RHS) const;
959 APInt ssub_sat(const APInt &RHS) const;
960 APInt usub_sat(const APInt &RHS) const;
961 APInt smul_sat(const APInt &RHS) const;
962 APInt umul_sat(const APInt &RHS) const;
963 APInt sshl_sat(const APInt &RHS) const;
964 APInt ushl_sat(const APInt &RHS) const;
965
966 /// Array-indexing support.
967 ///
968 /// \returns the bit value at bitPosition
969 bool operator[](unsigned bitPosition) const {
970 assert(bitPosition < getBitWidth() && "Bit position out of bounds!")(static_cast <bool> (bitPosition < getBitWidth() &&
"Bit position out of bounds!") ? void (0) : __assert_fail ("bitPosition < getBitWidth() && \"Bit position out of bounds!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 970, __extension__ __PRETTY_FUNCTION__))
;
971 return (maskBit(bitPosition) & getWord(bitPosition)) != 0;
972 }
973
974 /// @}
975 /// \name Comparison Operators
976 /// @{
977
978 /// Equality operator.
979 ///
980 /// Compares this APInt with RHS for the validity of the equality
981 /// relationship.
982 bool operator==(const APInt &RHS) const {
983 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Comparison requires equal bit widths") ? void (0) : __assert_fail
("BitWidth == RHS.BitWidth && \"Comparison requires equal bit widths\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 983, __extension__ __PRETTY_FUNCTION__))
;
984 if (isSingleWord())
985 return U.VAL == RHS.U.VAL;
986 return equalSlowCase(RHS);
987 }
988
989 /// Equality operator.
990 ///
991 /// Compares this APInt with a uint64_t for the validity of the equality
992 /// relationship.
993 ///
994 /// \returns true if *this == Val
995 bool operator==(uint64_t Val) const {
996 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() == Val;
997 }
998
999 /// Equality comparison.
1000 ///
1001 /// Compares this APInt with RHS for the validity of the equality
1002 /// relationship.
1003 ///
1004 /// \returns true if *this == Val
1005 bool eq(const APInt &RHS) const { return (*this) == RHS; }
1006
1007 /// Inequality operator.
1008 ///
1009 /// Compares this APInt with RHS for the validity of the inequality
1010 /// relationship.
1011 ///
1012 /// \returns true if *this != Val
1013 bool operator!=(const APInt &RHS) const { return !((*this) == RHS); }
1014
1015 /// Inequality operator.
1016 ///
1017 /// Compares this APInt with a uint64_t for the validity of the inequality
1018 /// relationship.
1019 ///
1020 /// \returns true if *this != Val
1021 bool operator!=(uint64_t Val) const { return !((*this) == Val); }
1022
1023 /// Inequality comparison
1024 ///
1025 /// Compares this APInt with RHS for the validity of the inequality
1026 /// relationship.
1027 ///
1028 /// \returns true if *this != Val
1029 bool ne(const APInt &RHS) const { return !((*this) == RHS); }
1030
1031 /// Unsigned less than comparison
1032 ///
1033 /// Regards both *this and RHS as unsigned quantities and compares them for
1034 /// the validity of the less-than relationship.
1035 ///
1036 /// \returns true if *this < RHS when both are considered unsigned.
1037 bool ult(const APInt &RHS) const { return compare(RHS) < 0; }
1038
1039 /// Unsigned less than comparison
1040 ///
1041 /// Regards both *this as an unsigned quantity and compares it with RHS for
1042 /// the validity of the less-than relationship.
1043 ///
1044 /// \returns true if *this < RHS when considered unsigned.
1045 bool ult(uint64_t RHS) const {
1046 // Only need to check active bits if not a single word.
1047 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() < RHS;
1048 }
1049
1050 /// Signed less than comparison
1051 ///
1052 /// Regards both *this and RHS as signed quantities and compares them for
1053 /// validity of the less-than relationship.
1054 ///
1055 /// \returns true if *this < RHS when both are considered signed.
1056 bool slt(const APInt &RHS) const { return compareSigned(RHS) < 0; }
1057
1058 /// Signed less than comparison
1059 ///
1060 /// Regards both *this as a signed quantity and compares it with RHS for
1061 /// the validity of the less-than relationship.
1062 ///
1063 /// \returns true if *this < RHS when considered signed.
1064 bool slt(int64_t RHS) const {
1065 return (!isSingleWord() && getMinSignedBits() > 64) ? isNegative()
1066 : getSExtValue() < RHS;
1067 }
1068
1069 /// Unsigned less or equal comparison
1070 ///
1071 /// Regards both *this and RHS as unsigned quantities and compares them for
1072 /// validity of the less-or-equal relationship.
1073 ///
1074 /// \returns true if *this <= RHS when both are considered unsigned.
1075 bool ule(const APInt &RHS) const { return compare(RHS) <= 0; }
1076
1077 /// Unsigned less or equal comparison
1078 ///
1079 /// Regards both *this as an unsigned quantity and compares it with RHS for
1080 /// the validity of the less-or-equal relationship.
1081 ///
1082 /// \returns true if *this <= RHS when considered unsigned.
1083 bool ule(uint64_t RHS) const { return !ugt(RHS); }
1084
1085 /// Signed less or equal comparison
1086 ///
1087 /// Regards both *this and RHS as signed quantities and compares them for
1088 /// validity of the less-or-equal relationship.
1089 ///
1090 /// \returns true if *this <= RHS when both are considered signed.
1091 bool sle(const APInt &RHS) const { return compareSigned(RHS) <= 0; }
1092
1093 /// Signed less or equal comparison
1094 ///
1095 /// Regards both *this as a signed quantity and compares it with RHS for the
1096 /// validity of the less-or-equal relationship.
1097 ///
1098 /// \returns true if *this <= RHS when considered signed.
1099 bool sle(uint64_t RHS) const { return !sgt(RHS); }
1100
1101 /// Unsigned greater than comparison
1102 ///
1103 /// Regards both *this and RHS as unsigned quantities and compares them for
1104 /// the validity of the greater-than relationship.
1105 ///
1106 /// \returns true if *this > RHS when both are considered unsigned.
1107 bool ugt(const APInt &RHS) const { return !ule(RHS); }
1108
1109 /// Unsigned greater than comparison
1110 ///
1111 /// Regards both *this as an unsigned quantity and compares it with RHS for
1112 /// the validity of the greater-than relationship.
1113 ///
1114 /// \returns true if *this > RHS when considered unsigned.
1115 bool ugt(uint64_t RHS) const {
1116 // Only need to check active bits if not a single word.
1117 return (!isSingleWord() && getActiveBits() > 64) || getZExtValue() > RHS;
1118 }
1119
1120 /// Signed greater than comparison
1121 ///
1122 /// Regards both *this and RHS as signed quantities and compares them for the
1123 /// validity of the greater-than relationship.
1124 ///
1125 /// \returns true if *this > RHS when both are considered signed.
1126 bool sgt(const APInt &RHS) const { return !sle(RHS); }
1127
1128 /// Signed greater than comparison
1129 ///
1130 /// Regards both *this as a signed quantity and compares it with RHS for
1131 /// the validity of the greater-than relationship.
1132 ///
1133 /// \returns true if *this > RHS when considered signed.
1134 bool sgt(int64_t RHS) const {
1135 return (!isSingleWord() && getMinSignedBits() > 64) ? !isNegative()
1136 : getSExtValue() > RHS;
1137 }
1138
1139 /// Unsigned greater or equal comparison
1140 ///
1141 /// Regards both *this and RHS as unsigned quantities and compares them for
1142 /// validity of the greater-or-equal relationship.
1143 ///
1144 /// \returns true if *this >= RHS when both are considered unsigned.
1145 bool uge(const APInt &RHS) const { return !ult(RHS); }
1146
1147 /// Unsigned greater or equal comparison
1148 ///
1149 /// Regards both *this as an unsigned quantity and compares it with RHS for
1150 /// the validity of the greater-or-equal relationship.
1151 ///
1152 /// \returns true if *this >= RHS when considered unsigned.
1153 bool uge(uint64_t RHS) const { return !ult(RHS); }
1154
1155 /// Signed greater or equal comparison
1156 ///
1157 /// Regards both *this and RHS as signed quantities and compares them for
1158 /// validity of the greater-or-equal relationship.
1159 ///
1160 /// \returns true if *this >= RHS when both are considered signed.
1161 bool sge(const APInt &RHS) const { return !slt(RHS); }
1162
1163 /// Signed greater or equal comparison
1164 ///
1165 /// Regards both *this as a signed quantity and compares it with RHS for
1166 /// the validity of the greater-or-equal relationship.
1167 ///
1168 /// \returns true if *this >= RHS when considered signed.
1169 bool sge(int64_t RHS) const { return !slt(RHS); }
1170
1171 /// This operation tests if there are any pairs of corresponding bits
1172 /// between this APInt and RHS that are both set.
1173 bool intersects(const APInt &RHS) const {
1174 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Bit widths must be the same") ? void (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 1174, __extension__ __PRETTY_FUNCTION__))
;
1175 if (isSingleWord())
1176 return (U.VAL & RHS.U.VAL) != 0;
1177 return intersectsSlowCase(RHS);
1178 }
1179
1180 /// This operation checks that all bits set in this APInt are also set in RHS.
1181 bool isSubsetOf(const APInt &RHS) const {
1182 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Bit widths must be the same") ? void (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 1182, __extension__ __PRETTY_FUNCTION__))
;
1183 if (isSingleWord())
1184 return (U.VAL & ~RHS.U.VAL) == 0;
1185 return isSubsetOfSlowCase(RHS);
1186 }
1187
1188 /// @}
1189 /// \name Resizing Operators
1190 /// @{
1191
1192 /// Truncate to new width.
1193 ///
1194 /// Truncate the APInt to a specified width. It is an error to specify a width
1195 /// that is greater than or equal to the current width.
1196 APInt trunc(unsigned width) const;
1197
1198 /// Truncate to new width with unsigned saturation.
1199 ///
1200 /// If the APInt, treated as unsigned integer, can be losslessly truncated to
1201 /// the new bitwidth, then return truncated APInt. Else, return max value.
1202 APInt truncUSat(unsigned width) const;
1203
1204 /// Truncate to new width with signed saturation.
1205 ///
1206 /// If this APInt, treated as signed integer, can be losslessly truncated to
1207 /// the new bitwidth, then return truncated APInt. Else, return either
1208 /// signed min value if the APInt was negative, or signed max value.
1209 APInt truncSSat(unsigned width) const;
1210
1211 /// Sign extend to a new width.
1212 ///
1213 /// This operation sign extends the APInt to a new width. If the high order
1214 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1215 /// It is an error to specify a width that is less than or equal to the
1216 /// current width.
1217 APInt sext(unsigned width) const;
1218
1219 /// Zero extend to a new width.
1220 ///
1221 /// This operation zero extends the APInt to a new width. The high order bits
1222 /// are filled with 0 bits. It is an error to specify a width that is less
1223 /// than or equal to the current width.
1224 APInt zext(unsigned width) const;
1225
1226 /// Sign extend or truncate to width
1227 ///
1228 /// Make this APInt have the bit width given by \p width. The value is sign
1229 /// extended, truncated, or left alone to make it that width.
1230 APInt sextOrTrunc(unsigned width) const;
1231
1232 /// Zero extend or truncate to width
1233 ///
1234 /// Make this APInt have the bit width given by \p width. The value is zero
1235 /// extended, truncated, or left alone to make it that width.
1236 APInt zextOrTrunc(unsigned width) const;
1237
1238 /// Truncate to width
1239 ///
1240 /// Make this APInt have the bit width given by \p width. The value is
1241 /// truncated or left alone to make it that width.
1242 APInt truncOrSelf(unsigned width) const;
1243
1244 /// Sign extend or truncate to width
1245 ///
1246 /// Make this APInt have the bit width given by \p width. The value is sign
1247 /// extended, or left alone to make it that width.
1248 APInt sextOrSelf(unsigned width) const;
1249
1250 /// Zero extend or truncate to width
1251 ///
1252 /// Make this APInt have the bit width given by \p width. The value is zero
1253 /// extended, or left alone to make it that width.
1254 APInt zextOrSelf(unsigned width) const;
1255
1256 /// @}
1257 /// \name Bit Manipulation Operators
1258 /// @{
1259
1260 /// Set every bit to 1.
1261 void setAllBits() {
1262 if (isSingleWord())
1263 U.VAL = WORDTYPE_MAX;
1264 else
1265 // Set all the bits in all the words.
1266 memset(U.pVal, -1, getNumWords() * APINT_WORD_SIZE);
1267 // Clear the unused ones
1268 clearUnusedBits();
1269 }
1270
1271 /// Set the given bit to 1 whose position is given as "bitPosition".
1272 void setBit(unsigned BitPosition) {
1273 assert(BitPosition < BitWidth && "BitPosition out of range")(static_cast <bool> (BitPosition < BitWidth &&
"BitPosition out of range") ? void (0) : __assert_fail ("BitPosition < BitWidth && \"BitPosition out of range\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 1273, __extension__ __PRETTY_FUNCTION__))
;
1274 WordType Mask = maskBit(BitPosition);
1275 if (isSingleWord())
1276 U.VAL |= Mask;
1277 else
1278 U.pVal[whichWord(BitPosition)] |= Mask;
1279 }
1280
1281 /// Set the sign bit to 1.
1282 void setSignBit() { setBit(BitWidth - 1); }
1283
1284 /// Set a given bit to a given value.
1285 void setBitVal(unsigned BitPosition, bool BitValue) {
1286 if (BitValue)
1287 setBit(BitPosition);
1288 else
1289 clearBit(BitPosition);
1290 }
1291
1292 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1293 /// This function handles "wrap" case when \p loBit >= \p hiBit, and calls
1294 /// setBits when \p loBit < \p hiBit.
1295 /// For \p loBit == \p hiBit wrap case, set every bit to 1.
1296 void setBitsWithWrap(unsigned loBit, unsigned hiBit) {
1297 assert(hiBit <= BitWidth && "hiBit out of range")(static_cast <bool> (hiBit <= BitWidth && "hiBit out of range"
) ? void (0) : __assert_fail ("hiBit <= BitWidth && \"hiBit out of range\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 1297, __extension__ __PRETTY_FUNCTION__))
;
1298 assert(loBit <= BitWidth && "loBit out of range")(static_cast <bool> (loBit <= BitWidth && "loBit out of range"
) ? void (0) : __assert_fail ("loBit <= BitWidth && \"loBit out of range\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 1298, __extension__ __PRETTY_FUNCTION__))
;
1299 if (loBit < hiBit) {
1300 setBits(loBit, hiBit);
1301 return;
1302 }
1303 setLowBits(hiBit);
1304 setHighBits(BitWidth - loBit);
1305 }
1306
1307 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1308 /// This function handles case when \p loBit <= \p hiBit.
1309 void setBits(unsigned loBit, unsigned hiBit) {
1310 assert(hiBit <= BitWidth && "hiBit out of range")(static_cast <bool> (hiBit <= BitWidth && "hiBit out of range"
) ? void (0) : __assert_fail ("hiBit <= BitWidth && \"hiBit out of range\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 1310, __extension__ __PRETTY_FUNCTION__))
;
1311 assert(loBit <= BitWidth && "loBit out of range")(static_cast <bool> (loBit <= BitWidth && "loBit out of range"
) ? void (0) : __assert_fail ("loBit <= BitWidth && \"loBit out of range\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 1311, __extension__ __PRETTY_FUNCTION__))
;
1312 assert(loBit <= hiBit && "loBit greater than hiBit")(static_cast <bool> (loBit <= hiBit && "loBit greater than hiBit"
) ? void (0) : __assert_fail ("loBit <= hiBit && \"loBit greater than hiBit\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 1312, __extension__ __PRETTY_FUNCTION__))
;
1313 if (loBit == hiBit)
1314 return;
1315 if (loBit < APINT_BITS_PER_WORD && hiBit <= APINT_BITS_PER_WORD) {
1316 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - (hiBit - loBit));
1317 mask <<= loBit;
1318 if (isSingleWord())
1319 U.VAL |= mask;
1320 else
1321 U.pVal[0] |= mask;
1322 } else {
1323 setBitsSlowCase(loBit, hiBit);
1324 }
1325 }
1326
1327 /// Set the top bits starting from loBit.
1328 void setBitsFrom(unsigned loBit) { return setBits(loBit, BitWidth); }
1329
1330 /// Set the bottom loBits bits.
1331 void setLowBits(unsigned loBits) { return setBits(0, loBits); }
1332
1333 /// Set the top hiBits bits.
1334 void setHighBits(unsigned hiBits) {
1335 return setBits(BitWidth - hiBits, BitWidth);
1336 }
1337
1338 /// Set every bit to 0.
1339 void clearAllBits() {
1340 if (isSingleWord())
1341 U.VAL = 0;
1342 else
1343 memset(U.pVal, 0, getNumWords() * APINT_WORD_SIZE);
1344 }
1345
1346 /// Set a given bit to 0.
1347 ///
1348 /// Set the given bit to 0 whose position is given as "bitPosition".
1349 void clearBit(unsigned BitPosition) {
1350 assert(BitPosition < BitWidth && "BitPosition out of range")(static_cast <bool> (BitPosition < BitWidth &&
"BitPosition out of range") ? void (0) : __assert_fail ("BitPosition < BitWidth && \"BitPosition out of range\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 1350, __extension__ __PRETTY_FUNCTION__))
;
1351 WordType Mask = ~maskBit(BitPosition);
1352 if (isSingleWord())
1353 U.VAL &= Mask;
1354 else
1355 U.pVal[whichWord(BitPosition)] &= Mask;
1356 }
1357
1358 /// Set bottom loBits bits to 0.
1359 void clearLowBits(unsigned loBits) {
1360 assert(loBits <= BitWidth && "More bits than bitwidth")(static_cast <bool> (loBits <= BitWidth && "More bits than bitwidth"
) ? void (0) : __assert_fail ("loBits <= BitWidth && \"More bits than bitwidth\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 1360, __extension__ __PRETTY_FUNCTION__))
;
1361 APInt Keep = getHighBitsSet(BitWidth, BitWidth - loBits);
1362 *this &= Keep;
1363 }
1364
1365 /// Set the sign bit to 0.
1366 void clearSignBit() { clearBit(BitWidth - 1); }
1367
1368 /// Toggle every bit to its opposite value.
1369 void flipAllBits() {
1370 if (isSingleWord()) {
1371 U.VAL ^= WORDTYPE_MAX;
1372 clearUnusedBits();
1373 } else {
1374 flipAllBitsSlowCase();
1375 }
1376 }
1377
1378 /// Toggles a given bit to its opposite value.
1379 ///
1380 /// Toggle a given bit to its opposite value whose position is given
1381 /// as "bitPosition".
1382 void flipBit(unsigned bitPosition);
1383
1384 /// Negate this APInt in place.
1385 void negate() {
1386 flipAllBits();
1387 ++(*this);
1388 }
1389
1390 /// Insert the bits from a smaller APInt starting at bitPosition.
1391 void insertBits(const APInt &SubBits, unsigned bitPosition);
1392 void insertBits(uint64_t SubBits, unsigned bitPosition, unsigned numBits);
1393
1394 /// Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
1395 APInt extractBits(unsigned numBits, unsigned bitPosition) const;
1396 uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const;
1397
1398 /// @}
1399 /// \name Value Characterization Functions
1400 /// @{
1401
1402 /// Return the number of bits in the APInt.
1403 unsigned getBitWidth() const { return BitWidth; }
1404
1405 /// Get the number of words.
1406 ///
1407 /// Here one word's bitwidth equals to that of uint64_t.
1408 ///
1409 /// \returns the number of words to hold the integer value of this APInt.
1410 unsigned getNumWords() const { return getNumWords(BitWidth); }
1411
1412 /// Get the number of words.
1413 ///
1414 /// *NOTE* Here one word's bitwidth equals to that of uint64_t.
1415 ///
1416 /// \returns the number of words to hold the integer value with a given bit
1417 /// width.
1418 static unsigned getNumWords(unsigned BitWidth) {
1419 return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1420 }
1421
1422 /// Compute the number of active bits in the value
1423 ///
1424 /// This function returns the number of active bits which is defined as the
1425 /// bit width minus the number of leading zeros. This is used in several
1426 /// computations to see how "wide" the value is.
1427 unsigned getActiveBits() const { return BitWidth - countLeadingZeros(); }
1428
1429 /// Compute the number of active words in the value of this APInt.
1430 ///
1431 /// This is used in conjunction with getActiveData to extract the raw value of
1432 /// the APInt.
1433 unsigned getActiveWords() const {
1434 unsigned numActiveBits = getActiveBits();
1435 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
1436 }
1437
1438 /// Get the minimum bit size for this signed APInt
1439 ///
1440 /// Computes the minimum bit width for this APInt while considering it to be a
1441 /// signed (and probably negative) value. If the value is not negative, this
1442 /// function returns the same value as getActiveBits()+1. Otherwise, it
1443 /// returns the smallest bit width that will retain the negative value. For
1444 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1445 /// for -1, this function will always return 1.
1446 unsigned getMinSignedBits() const { return BitWidth - getNumSignBits() + 1; }
1447
1448 /// Get zero extended value
1449 ///
1450 /// This method attempts to return the value of this APInt as a zero extended
1451 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1452 /// uint64_t. Otherwise an assertion will result.
1453 uint64_t getZExtValue() const {
1454 if (isSingleWord()) {
1455 assert(BitWidth && "zero width values not allowed")(static_cast <bool> (BitWidth && "zero width values not allowed"
) ? void (0) : __assert_fail ("BitWidth && \"zero width values not allowed\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 1455, __extension__ __PRETTY_FUNCTION__))
;
1456 return U.VAL;
1457 }
1458 assert(getActiveBits() <= 64 && "Too many bits for uint64_t")(static_cast <bool> (getActiveBits() <= 64 &&
"Too many bits for uint64_t") ? void (0) : __assert_fail ("getActiveBits() <= 64 && \"Too many bits for uint64_t\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 1458, __extension__ __PRETTY_FUNCTION__))
;
1459 return U.pVal[0];
1460 }
1461
1462 /// Get sign extended value
1463 ///
1464 /// This method attempts to return the value of this APInt as a sign extended
1465 /// int64_t. The bit width must be <= 64 or the value must fit within an
1466 /// int64_t. Otherwise an assertion will result.
1467 int64_t getSExtValue() const {
1468 if (isSingleWord())
1469 return SignExtend64(U.VAL, BitWidth);
1470 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t")(static_cast <bool> (getMinSignedBits() <= 64 &&
"Too many bits for int64_t") ? void (0) : __assert_fail ("getMinSignedBits() <= 64 && \"Too many bits for int64_t\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include/llvm/ADT/APInt.h"
, 1470, __extension__ __PRETTY_FUNCTION__))
;
1471 return int64_t(U.pVal[0]);
1472 }
1473
1474 /// Get bits required for string value.
1475 ///
1476 /// This method determines how many bits are required to hold the APInt
1477 /// equivalent of the string given by \p str.
1478 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1479
1480 /// The APInt version of the countLeadingZeros functions in
1481 /// MathExtras.h.
1482 ///
1483 /// It counts the number of zeros from the most significant bit to the first
1484 /// one bit.
1485 ///
1486 /// \returns BitWidth if the value is zero, otherwise returns the number of
1487 /// zeros from the most significant bit to the first one bits.
1488 unsigned countLeadingZeros() const {
1489 if (isSingleWord()) {
1490 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1491 return llvm::countLeadingZeros(U.VAL) - unusedBits;
1492 }
1493 return countLeadingZerosSlowCase();
1494 }
1495
1496 /// Count the number of leading one bits.
1497 ///
1498 /// This function is an APInt version of the countLeadingOnes
1499 /// functions in MathExtras.h. It counts the number of ones from the most
1500 /// significant bit to the first zero bit.
1501 ///
1502 /// \returns 0 if the high order bit is not set, otherwise returns the number
1503 /// of 1 bits from the most significant to the least
1504 unsigned countLeadingOnes() const {
1505 if (isSingleWord()) {
1506 if (LLVM_UNLIKELY(BitWidth == 0)__builtin_expect((bool)(BitWidth == 0), false))
1507 return 0;
1508 return llvm::countLeadingOnes(U.VAL << (APINT_BITS_PER_WORD - BitWidth));
1509 }
1510 return countLeadingOnesSlowCase();
1511 }
1512
1513 /// Computes the number of leading bits of this APInt that are equal to its
1514 /// sign bit.
1515 unsigned getNumSignBits() const {
1516 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1517 }
1518
1519 /// Count the number of trailing zero bits.
1520 ///
1521 /// This function is an APInt version of the countTrailingZeros
1522 /// functions in MathExtras.h. It counts the number of zeros from the least
1523 /// significant bit to the first set bit.
1524 ///
1525 /// \returns BitWidth if the value is zero, otherwise returns the number of
1526 /// zeros from the least significant bit to the first one bit.
1527 unsigned countTrailingZeros() const {
1528 if (isSingleWord()) {
1529 unsigned TrailingZeros = llvm::countTrailingZeros(U.VAL);
1530 return (TrailingZeros > BitWidth ? BitWidth : TrailingZeros);
1531 }
1532 return countTrailingZerosSlowCase();
1533 }
1534
1535 /// Count the number of trailing one bits.
1536 ///
1537 /// This function is an APInt version of the countTrailingOnes
1538 /// functions in MathExtras.h. It counts the number of ones from the least
1539 /// significant bit to the first zero bit.
1540 ///
1541 /// \returns BitWidth if the value is all ones, otherwise returns the number
1542 /// of ones from the least significant bit to the first zero bit.
1543 unsigned countTrailingOnes() const {
1544 if (isSingleWord())
1545 return llvm::countTrailingOnes(U.VAL);
1546 return countTrailingOnesSlowCase();
1547 }
1548
1549 /// Count the number of bits set.
1550 ///
1551 /// This function is an APInt version of the countPopulation functions
1552 /// in MathExtras.h. It counts the number of 1 bits in the APInt value.
1553 ///
1554 /// \returns 0 if the value is zero, otherwise returns the number of set bits.
1555 unsigned countPopulation() const {
1556 if (isSingleWord())
1557 return llvm::countPopulation(U.VAL);
1558 return countPopulationSlowCase();
1559 }
1560
1561 /// @}
1562 /// \name Conversion Functions
1563 /// @{
1564 void print(raw_ostream &OS, bool isSigned) const;
1565
1566 /// Converts an APInt to a string and append it to Str. Str is commonly a
1567 /// SmallString.
1568 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1569 bool formatAsCLiteral = false) const;
1570
1571 /// Considers the APInt to be unsigned and converts it into a string in the
1572 /// radix given. The radix can be 2, 8, 10 16, or 36.
1573 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1574 toString(Str, Radix, false, false);
1575 }
1576
1577 /// Considers the APInt to be signed and converts it into a string in the
1578 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1579 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1580 toString(Str, Radix, true, false);
1581 }
1582
1583 /// \returns a byte-swapped representation of this APInt Value.
1584 APInt byteSwap() const;
1585
1586 /// \returns the value with the bit representation reversed of this APInt
1587 /// Value.
1588 APInt reverseBits() const;
1589
1590 /// Converts this APInt to a double value.
1591 double roundToDouble(bool isSigned) const;
1592
1593 /// Converts this unsigned APInt to a double value.
1594 double roundToDouble() const { return roundToDouble(false); }
1595
1596 /// Converts this signed APInt to a double value.
1597 double signedRoundToDouble() const { return roundToDouble(true); }
1598
1599 /// Converts APInt bits to a double
1600 ///
1601 /// The conversion does not do a translation from integer to double, it just
1602 /// re-interprets the bits as a double. Note that it is valid to do this on
1603 /// any bit width. Exactly 64 bits will be translated.
1604 double bitsToDouble() const { return BitsToDouble(getWord(0)); }
1605
1606 /// Converts APInt bits to a float
1607 ///
1608 /// The conversion does not do a translation from integer to float, it just
1609 /// re-interprets the bits as a float. Note that it is valid to do this on
1610 /// any bit width. Exactly 32 bits will be translated.
1611 float bitsToFloat() const {
1612 return BitsToFloat(static_cast<uint32_t>(getWord(0)));
1613 }
1614
1615 /// Converts a double to APInt bits.
1616 ///
1617 /// The conversion does not do a translation from double to integer, it just
1618 /// re-interprets the bits of the double.
1619 static APInt doubleToBits(double V) {
1620 return APInt(sizeof(double) * CHAR_BIT8, DoubleToBits(V));
1621 }
1622
1623 /// Converts a float to APInt bits.
1624 ///
1625 /// The conversion does not do a translation from float to integer, it just
1626 /// re-interprets the bits of the float.
1627 static APInt floatToBits(float V) {
1628 return APInt(sizeof(float) * CHAR_BIT8, FloatToBits(V));
1629 }
1630
1631 /// @}
1632 /// \name Mathematics Operations
1633 /// @{
1634
1635 /// \returns the floor log base 2 of this APInt.
1636 unsigned logBase2() const { return getActiveBits() - 1; }
1637
1638 /// \returns the ceil log base 2 of this APInt.
1639 unsigned ceilLogBase2() const {
1640 APInt temp(*this);
1641 --temp;
1642 return temp.getActiveBits();
1643 }
1644
1645 /// \returns the nearest log base 2 of this APInt. Ties round up.
1646 ///
1647 /// NOTE: When we have a BitWidth of 1, we define:
1648 ///
1649 /// log2(0) = UINT32_MAX
1650 /// log2(1) = 0
1651 ///
1652 /// to get around any mathematical concerns resulting from
1653 /// referencing 2 in a space where 2 does no exist.
1654 unsigned nearestLogBase2() const;
1655
1656 /// \returns the log base 2 of this APInt if its an exact power of two, -1
1657 /// otherwise
1658 int32_t exactLogBase2() const {
1659 if (!isPowerOf2())
1660 return -1;
1661 return logBase2();
1662 }
1663
1664 /// Compute the square root.
1665 APInt sqrt() const;
1666
1667 /// Get the absolute value. If *this is < 0 then return -(*this), otherwise
1668 /// *this. Note that the "most negative" signed number (e.g. -128 for 8 bit
1669 /// wide APInt) is unchanged due to how negation works.
1670 APInt abs() const {
1671 if (isNegative())
1672 return -(*this);
1673 return *this;
1674 }
1675
1676 /// \returns the multiplicative inverse for a given modulo.
1677 APInt multiplicativeInverse(const APInt &modulo) const;
1678
1679 /// @}
1680 /// \name Building-block Operations for APInt and APFloat
1681 /// @{
1682
1683 // These building block operations operate on a representation of arbitrary
1684 // precision, two's-complement, bignum integer values. They should be
1685 // sufficient to implement APInt and APFloat bignum requirements. Inputs are
1686 // generally a pointer to the base of an array of integer parts, representing
1687 // an unsigned bignum, and a count of how many parts there are.
1688
1689 /// Sets the least significant part of a bignum to the input value, and zeroes
1690 /// out higher parts.
1691 static void tcSet(WordType *, WordType, unsigned);
1692
1693 /// Assign one bignum to another.
1694 static void tcAssign(WordType *, const WordType *, unsigned);
1695
1696 /// Returns true if a bignum is zero, false otherwise.
1697 static bool tcIsZero(const WordType *, unsigned);
1698
1699 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1700 static int tcExtractBit(const WordType *, unsigned bit);
1701
1702 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
1703 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
1704 /// significant bit of DST. All high bits above srcBITS in DST are
1705 /// zero-filled.
1706 static void tcExtract(WordType *, unsigned dstCount, const WordType *,
1707 unsigned srcBits, unsigned srcLSB);
1708
1709 /// Set the given bit of a bignum. Zero-based.
1710 static void tcSetBit(WordType *, unsigned bit);
1711
1712 /// Clear the given bit of a bignum. Zero-based.
1713 static void tcClearBit(WordType *, unsigned bit);
1714
1715 /// Returns the bit number of the least or most significant set bit of a
1716 /// number. If the input number has no bits set -1U is returned.
1717 static unsigned tcLSB(const WordType *, unsigned n);
1718 static unsigned tcMSB(const WordType *parts, unsigned n);
1719
1720 /// Negate a bignum in-place.
1721 static void tcNegate(WordType *, unsigned);
1722
1723 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1724 static WordType tcAdd(WordType *, const WordType *, WordType carry, unsigned);
1725 /// DST += RHS. Returns the carry flag.
1726 static WordType tcAddPart(WordType *, WordType, unsigned);
1727
1728 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1729 static WordType tcSubtract(WordType *, const WordType *, WordType carry,
1730 unsigned);
1731 /// DST -= RHS. Returns the carry flag.
1732 static WordType tcSubtractPart(WordType *, WordType, unsigned);
1733
1734 /// DST += SRC * MULTIPLIER + PART if add is true
1735 /// DST = SRC * MULTIPLIER + PART if add is false
1736 ///
1737 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must
1738 /// start at the same point, i.e. DST == SRC.
1739 ///
1740 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned.
1741 /// Otherwise DST is filled with the least significant DSTPARTS parts of the
1742 /// result, and if all of the omitted higher parts were zero return zero,
1743 /// otherwise overflow occurred and return one.
1744 static int tcMultiplyPart(WordType *dst, const WordType *src,
1745 WordType multiplier, WordType carry,
1746 unsigned srcParts, unsigned dstParts, bool add);
1747
1748 /// DST = LHS * RHS, where DST has the same width as the operands and is
1749 /// filled with the least significant parts of the result. Returns one if
1750 /// overflow occurred, otherwise zero. DST must be disjoint from both
1751 /// operands.
1752 static int tcMultiply(WordType *, const WordType *, const WordType *,
1753 unsigned);
1754
1755 /// DST = LHS * RHS, where DST has width the sum of the widths of the
1756 /// operands. No overflow occurs. DST must be disjoint from both operands.
1757 static void tcFullMultiply(WordType *, const WordType *, const WordType *,
1758 unsigned, unsigned);
1759
1760 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1761 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set
1762 /// REMAINDER to the remainder, return zero. i.e.
1763 ///
1764 /// OLD_LHS = RHS * LHS + REMAINDER
1765 ///
1766 /// SCRATCH is a bignum of the same size as the operands and result for use by
1767 /// the routine; its contents need not be initialized and are destroyed. LHS,
1768 /// REMAINDER and SCRATCH must be distinct.
1769 static int tcDivide(WordType *lhs, const WordType *rhs, WordType *remainder,
1770 WordType *scratch, unsigned parts);
1771
1772 /// Shift a bignum left Count bits. Shifted in bits are zero. There are no
1773 /// restrictions on Count.
1774 static void tcShiftLeft(WordType *, unsigned Words, unsigned Count);
1775
1776 /// Shift a bignum right Count bits. Shifted in bits are zero. There are no
1777 /// restrictions on Count.
1778 static void tcShiftRight(WordType *, unsigned Words, unsigned Count);
1779
1780 /// Comparison (unsigned) of two bignums.
1781 static int tcCompare(const WordType *, const WordType *, unsigned);
1782
1783 /// Increment a bignum in-place. Return the carry flag.
1784 static WordType tcIncrement(WordType *dst, unsigned parts) {
1785 return tcAddPart(dst, 1, parts);
1786 }
1787
1788 /// Decrement a bignum in-place. Return the borrow flag.
1789 static WordType tcDecrement(WordType *dst, unsigned parts) {
1790 return tcSubtractPart(dst, 1, parts);
1791 }
1792
1793 /// Used to insert APInt objects, or objects that contain APInt objects, into
1794 /// FoldingSets.
1795 void Profile(FoldingSetNodeID &id) const;
1796
1797 /// debug method
1798 void dump() const;
1799
1800 /// Returns whether this instance allocated memory.
1801 bool needsCleanup() const { return !isSingleWord(); }
1802
1803private:
1804 /// This union is used to store the integer value. When the
1805 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
1806 union {
1807 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1808 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1809 } U;
1810
1811 unsigned BitWidth; ///< The number of bits in this APInt.