Bug Summary

File:clang/lib/Sema/SemaChecking.cpp
Warning:line 10534, column 7
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 SemaChecking.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 -relaxed-aliasing -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-13~++20210621111111+acefe0eaaf82/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/include -I /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/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-13/lib/clang/13.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-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-13~++20210621111111+acefe0eaaf82/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -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-06-21-164211-33944-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp
1//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
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 implements extra semantic analysis beyond what is enforced
10// by the C type system.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Attr.h"
17#include "clang/AST/AttrIterator.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/EvaluatedExprVisitor.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/ExprOpenMP.h"
29#include "clang/AST/FormatString.h"
30#include "clang/AST/NSAPI.h"
31#include "clang/AST/NonTrivialTypeVisitor.h"
32#include "clang/AST/OperationKinds.h"
33#include "clang/AST/RecordLayout.h"
34#include "clang/AST/Stmt.h"
35#include "clang/AST/TemplateBase.h"
36#include "clang/AST/Type.h"
37#include "clang/AST/TypeLoc.h"
38#include "clang/AST/UnresolvedSet.h"
39#include "clang/Basic/AddressSpaces.h"
40#include "clang/Basic/CharInfo.h"
41#include "clang/Basic/Diagnostic.h"
42#include "clang/Basic/IdentifierTable.h"
43#include "clang/Basic/LLVM.h"
44#include "clang/Basic/LangOptions.h"
45#include "clang/Basic/OpenCLOptions.h"
46#include "clang/Basic/OperatorKinds.h"
47#include "clang/Basic/PartialDiagnostic.h"
48#include "clang/Basic/SourceLocation.h"
49#include "clang/Basic/SourceManager.h"
50#include "clang/Basic/Specifiers.h"
51#include "clang/Basic/SyncScope.h"
52#include "clang/Basic/TargetBuiltins.h"
53#include "clang/Basic/TargetCXXABI.h"
54#include "clang/Basic/TargetInfo.h"
55#include "clang/Basic/TypeTraits.h"
56#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57#include "clang/Sema/Initialization.h"
58#include "clang/Sema/Lookup.h"
59#include "clang/Sema/Ownership.h"
60#include "clang/Sema/Scope.h"
61#include "clang/Sema/ScopeInfo.h"
62#include "clang/Sema/Sema.h"
63#include "clang/Sema/SemaInternal.h"
64#include "llvm/ADT/APFloat.h"
65#include "llvm/ADT/APInt.h"
66#include "llvm/ADT/APSInt.h"
67#include "llvm/ADT/ArrayRef.h"
68#include "llvm/ADT/DenseMap.h"
69#include "llvm/ADT/FoldingSet.h"
70#include "llvm/ADT/None.h"
71#include "llvm/ADT/Optional.h"
72#include "llvm/ADT/STLExtras.h"
73#include "llvm/ADT/SmallBitVector.h"
74#include "llvm/ADT/SmallPtrSet.h"
75#include "llvm/ADT/SmallString.h"
76#include "llvm/ADT/SmallVector.h"
77#include "llvm/ADT/StringRef.h"
78#include "llvm/ADT/StringSet.h"
79#include "llvm/ADT/StringSwitch.h"
80#include "llvm/ADT/Triple.h"
81#include "llvm/Support/AtomicOrdering.h"
82#include "llvm/Support/Casting.h"
83#include "llvm/Support/Compiler.h"
84#include "llvm/Support/ConvertUTF.h"
85#include "llvm/Support/ErrorHandling.h"
86#include "llvm/Support/Format.h"
87#include "llvm/Support/Locale.h"
88#include "llvm/Support/MathExtras.h"
89#include "llvm/Support/SaveAndRestore.h"
90#include "llvm/Support/raw_ostream.h"
91#include <algorithm>
92#include <bitset>
93#include <cassert>
94#include <cctype>
95#include <cstddef>
96#include <cstdint>
97#include <functional>
98#include <limits>
99#include <string>
100#include <tuple>
101#include <utility>
102
103using namespace clang;
104using namespace sema;
105
106SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
107 unsigned ByteNo) const {
108 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
109 Context.getTargetInfo());
110}
111
112/// Checks that a call expression's argument count is the desired number.
113/// This is useful when doing custom type-checking. Returns true on error.
114static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
115 unsigned argCount = call->getNumArgs();
116 if (argCount == desiredArgCount) return false;
117
118 if (argCount < desiredArgCount)
119 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
120 << 0 /*function call*/ << desiredArgCount << argCount
121 << call->getSourceRange();
122
123 // Highlight all the excess arguments.
124 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
125 call->getArg(argCount - 1)->getEndLoc());
126
127 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
128 << 0 /*function call*/ << desiredArgCount << argCount
129 << call->getArg(1)->getSourceRange();
130}
131
132/// Check that the first argument to __builtin_annotation is an integer
133/// and the second argument is a non-wide string literal.
134static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
135 if (checkArgCount(S, TheCall, 2))
136 return true;
137
138 // First argument should be an integer.
139 Expr *ValArg = TheCall->getArg(0);
140 QualType Ty = ValArg->getType();
141 if (!Ty->isIntegerType()) {
142 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
143 << ValArg->getSourceRange();
144 return true;
145 }
146
147 // Second argument should be a constant string.
148 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
149 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
150 if (!Literal || !Literal->isAscii()) {
151 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
152 << StrArg->getSourceRange();
153 return true;
154 }
155
156 TheCall->setType(Ty);
157 return false;
158}
159
160static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
161 // We need at least one argument.
162 if (TheCall->getNumArgs() < 1) {
163 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
164 << 0 << 1 << TheCall->getNumArgs()
165 << TheCall->getCallee()->getSourceRange();
166 return true;
167 }
168
169 // All arguments should be wide string literals.
170 for (Expr *Arg : TheCall->arguments()) {
171 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
172 if (!Literal || !Literal->isWide()) {
173 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
174 << Arg->getSourceRange();
175 return true;
176 }
177 }
178
179 return false;
180}
181
182/// Check that the argument to __builtin_addressof is a glvalue, and set the
183/// result type to the corresponding pointer type.
184static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
185 if (checkArgCount(S, TheCall, 1))
186 return true;
187
188 ExprResult Arg(TheCall->getArg(0));
189 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
190 if (ResultType.isNull())
191 return true;
192
193 TheCall->setArg(0, Arg.get());
194 TheCall->setType(ResultType);
195 return false;
196}
197
198/// Check the number of arguments and set the result type to
199/// the argument type.
200static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
201 if (checkArgCount(S, TheCall, 1))
202 return true;
203
204 TheCall->setType(TheCall->getArg(0)->getType());
205 return false;
206}
207
208/// Check that the value argument for __builtin_is_aligned(value, alignment) and
209/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
210/// type (but not a function pointer) and that the alignment is a power-of-two.
211static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
212 if (checkArgCount(S, TheCall, 2))
213 return true;
214
215 clang::Expr *Source = TheCall->getArg(0);
216 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
217
218 auto IsValidIntegerType = [](QualType Ty) {
219 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
220 };
221 QualType SrcTy = Source->getType();
222 // We should also be able to use it with arrays (but not functions!).
223 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
224 SrcTy = S.Context.getDecayedType(SrcTy);
225 }
226 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
227 SrcTy->isFunctionPointerType()) {
228 // FIXME: this is not quite the right error message since we don't allow
229 // floating point types, or member pointers.
230 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
231 << SrcTy;
232 return true;
233 }
234
235 clang::Expr *AlignOp = TheCall->getArg(1);
236 if (!IsValidIntegerType(AlignOp->getType())) {
237 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
238 << AlignOp->getType();
239 return true;
240 }
241 Expr::EvalResult AlignResult;
242 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
243 // We can't check validity of alignment if it is value dependent.
244 if (!AlignOp->isValueDependent() &&
245 AlignOp->EvaluateAsInt(AlignResult, S.Context,
246 Expr::SE_AllowSideEffects)) {
247 llvm::APSInt AlignValue = AlignResult.Val.getInt();
248 llvm::APSInt MaxValue(
249 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
250 if (AlignValue < 1) {
251 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
252 return true;
253 }
254 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
255 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
256 << toString(MaxValue, 10);
257 return true;
258 }
259 if (!AlignValue.isPowerOf2()) {
260 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
261 return true;
262 }
263 if (AlignValue == 1) {
264 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
265 << IsBooleanAlignBuiltin;
266 }
267 }
268
269 ExprResult SrcArg = S.PerformCopyInitialization(
270 InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
271 SourceLocation(), Source);
272 if (SrcArg.isInvalid())
273 return true;
274 TheCall->setArg(0, SrcArg.get());
275 ExprResult AlignArg =
276 S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
277 S.Context, AlignOp->getType(), false),
278 SourceLocation(), AlignOp);
279 if (AlignArg.isInvalid())
280 return true;
281 TheCall->setArg(1, AlignArg.get());
282 // For align_up/align_down, the return type is the same as the (potentially
283 // decayed) argument type including qualifiers. For is_aligned(), the result
284 // is always bool.
285 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
286 return false;
287}
288
289static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
290 unsigned BuiltinID) {
291 if (checkArgCount(S, TheCall, 3))
292 return true;
293
294 // First two arguments should be integers.
295 for (unsigned I = 0; I < 2; ++I) {
296 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
297 if (Arg.isInvalid()) return true;
298 TheCall->setArg(I, Arg.get());
299
300 QualType Ty = Arg.get()->getType();
301 if (!Ty->isIntegerType()) {
302 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
303 << Ty << Arg.get()->getSourceRange();
304 return true;
305 }
306 }
307
308 // Third argument should be a pointer to a non-const integer.
309 // IRGen correctly handles volatile, restrict, and address spaces, and
310 // the other qualifiers aren't possible.
311 {
312 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
313 if (Arg.isInvalid()) return true;
314 TheCall->setArg(2, Arg.get());
315
316 QualType Ty = Arg.get()->getType();
317 const auto *PtrTy = Ty->getAs<PointerType>();
318 if (!PtrTy ||
319 !PtrTy->getPointeeType()->isIntegerType() ||
320 PtrTy->getPointeeType().isConstQualified()) {
321 S.Diag(Arg.get()->getBeginLoc(),
322 diag::err_overflow_builtin_must_be_ptr_int)
323 << Ty << Arg.get()->getSourceRange();
324 return true;
325 }
326 }
327
328 // Disallow signed ExtIntType args larger than 128 bits to mul function until
329 // we improve backend support.
330 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
331 for (unsigned I = 0; I < 3; ++I) {
332 const auto Arg = TheCall->getArg(I);
333 // Third argument will be a pointer.
334 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
335 if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
336 S.getASTContext().getIntWidth(Ty) > 128)
337 return S.Diag(Arg->getBeginLoc(),
338 diag::err_overflow_builtin_ext_int_max_size)
339 << 128;
340 }
341 }
342
343 return false;
344}
345
346static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
347 if (checkArgCount(S, BuiltinCall, 2))
348 return true;
349
350 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
351 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
352 Expr *Call = BuiltinCall->getArg(0);
353 Expr *Chain = BuiltinCall->getArg(1);
354
355 if (Call->getStmtClass() != Stmt::CallExprClass) {
356 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
357 << Call->getSourceRange();
358 return true;
359 }
360
361 auto CE = cast<CallExpr>(Call);
362 if (CE->getCallee()->getType()->isBlockPointerType()) {
363 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
364 << Call->getSourceRange();
365 return true;
366 }
367
368 const Decl *TargetDecl = CE->getCalleeDecl();
369 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
370 if (FD->getBuiltinID()) {
371 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
372 << Call->getSourceRange();
373 return true;
374 }
375
376 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
377 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
378 << Call->getSourceRange();
379 return true;
380 }
381
382 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
383 if (ChainResult.isInvalid())
384 return true;
385 if (!ChainResult.get()->getType()->isPointerType()) {
386 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
387 << Chain->getSourceRange();
388 return true;
389 }
390
391 QualType ReturnTy = CE->getCallReturnType(S.Context);
392 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
393 QualType BuiltinTy = S.Context.getFunctionType(
394 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
395 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
396
397 Builtin =
398 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
399
400 BuiltinCall->setType(CE->getType());
401 BuiltinCall->setValueKind(CE->getValueKind());
402 BuiltinCall->setObjectKind(CE->getObjectKind());
403 BuiltinCall->setCallee(Builtin);
404 BuiltinCall->setArg(1, ChainResult.get());
405
406 return false;
407}
408
409namespace {
410
411class EstimateSizeFormatHandler
412 : public analyze_format_string::FormatStringHandler {
413 size_t Size;
414
415public:
416 EstimateSizeFormatHandler(StringRef Format)
417 : Size(std::min(Format.find(0), Format.size()) +
418 1 /* null byte always written by sprintf */) {}
419
420 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
421 const char *, unsigned SpecifierLen) override {
422
423 const size_t FieldWidth = computeFieldWidth(FS);
424 const size_t Precision = computePrecision(FS);
425
426 // The actual format.
427 switch (FS.getConversionSpecifier().getKind()) {
428 // Just a char.
429 case analyze_format_string::ConversionSpecifier::cArg:
430 case analyze_format_string::ConversionSpecifier::CArg:
431 Size += std::max(FieldWidth, (size_t)1);
432 break;
433 // Just an integer.
434 case analyze_format_string::ConversionSpecifier::dArg:
435 case analyze_format_string::ConversionSpecifier::DArg:
436 case analyze_format_string::ConversionSpecifier::iArg:
437 case analyze_format_string::ConversionSpecifier::oArg:
438 case analyze_format_string::ConversionSpecifier::OArg:
439 case analyze_format_string::ConversionSpecifier::uArg:
440 case analyze_format_string::ConversionSpecifier::UArg:
441 case analyze_format_string::ConversionSpecifier::xArg:
442 case analyze_format_string::ConversionSpecifier::XArg:
443 Size += std::max(FieldWidth, Precision);
444 break;
445
446 // %g style conversion switches between %f or %e style dynamically.
447 // %f always takes less space, so default to it.
448 case analyze_format_string::ConversionSpecifier::gArg:
449 case analyze_format_string::ConversionSpecifier::GArg:
450
451 // Floating point number in the form '[+]ddd.ddd'.
452 case analyze_format_string::ConversionSpecifier::fArg:
453 case analyze_format_string::ConversionSpecifier::FArg:
454 Size += std::max(FieldWidth, 1 /* integer part */ +
455 (Precision ? 1 + Precision
456 : 0) /* period + decimal */);
457 break;
458
459 // Floating point number in the form '[-]d.ddde[+-]dd'.
460 case analyze_format_string::ConversionSpecifier::eArg:
461 case analyze_format_string::ConversionSpecifier::EArg:
462 Size +=
463 std::max(FieldWidth,
464 1 /* integer part */ +
465 (Precision ? 1 + Precision : 0) /* period + decimal */ +
466 1 /* e or E letter */ + 2 /* exponent */);
467 break;
468
469 // Floating point number in the form '[-]0xh.hhhhp±dd'.
470 case analyze_format_string::ConversionSpecifier::aArg:
471 case analyze_format_string::ConversionSpecifier::AArg:
472 Size +=
473 std::max(FieldWidth,
474 2 /* 0x */ + 1 /* integer part */ +
475 (Precision ? 1 + Precision : 0) /* period + decimal */ +
476 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
477 break;
478
479 // Just a string.
480 case analyze_format_string::ConversionSpecifier::sArg:
481 case analyze_format_string::ConversionSpecifier::SArg:
482 Size += FieldWidth;
483 break;
484
485 // Just a pointer in the form '0xddd'.
486 case analyze_format_string::ConversionSpecifier::pArg:
487 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
488 break;
489
490 // A plain percent.
491 case analyze_format_string::ConversionSpecifier::PercentArg:
492 Size += 1;
493 break;
494
495 default:
496 break;
497 }
498
499 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
500
501 if (FS.hasAlternativeForm()) {
502 switch (FS.getConversionSpecifier().getKind()) {
503 default:
504 break;
505 // Force a leading '0'.
506 case analyze_format_string::ConversionSpecifier::oArg:
507 Size += 1;
508 break;
509 // Force a leading '0x'.
510 case analyze_format_string::ConversionSpecifier::xArg:
511 case analyze_format_string::ConversionSpecifier::XArg:
512 Size += 2;
513 break;
514 // Force a period '.' before decimal, even if precision is 0.
515 case analyze_format_string::ConversionSpecifier::aArg:
516 case analyze_format_string::ConversionSpecifier::AArg:
517 case analyze_format_string::ConversionSpecifier::eArg:
518 case analyze_format_string::ConversionSpecifier::EArg:
519 case analyze_format_string::ConversionSpecifier::fArg:
520 case analyze_format_string::ConversionSpecifier::FArg:
521 case analyze_format_string::ConversionSpecifier::gArg:
522 case analyze_format_string::ConversionSpecifier::GArg:
523 Size += (Precision ? 0 : 1);
524 break;
525 }
526 }
527 assert(SpecifierLen <= Size && "no underflow")(static_cast <bool> (SpecifierLen <= Size &&
"no underflow") ? void (0) : __assert_fail ("SpecifierLen <= Size && \"no underflow\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 527, __extension__ __PRETTY_FUNCTION__))
;
528 Size -= SpecifierLen;
529 return true;
530 }
531
532 size_t getSizeLowerBound() const { return Size; }
533
534private:
535 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
536 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
537 size_t FieldWidth = 0;
538 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
539 FieldWidth = FW.getConstantAmount();
540 return FieldWidth;
541 }
542
543 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
544 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
545 size_t Precision = 0;
546
547 // See man 3 printf for default precision value based on the specifier.
548 switch (FW.getHowSpecified()) {
549 case analyze_format_string::OptionalAmount::NotSpecified:
550 switch (FS.getConversionSpecifier().getKind()) {
551 default:
552 break;
553 case analyze_format_string::ConversionSpecifier::dArg: // %d
554 case analyze_format_string::ConversionSpecifier::DArg: // %D
555 case analyze_format_string::ConversionSpecifier::iArg: // %i
556 Precision = 1;
557 break;
558 case analyze_format_string::ConversionSpecifier::oArg: // %d
559 case analyze_format_string::ConversionSpecifier::OArg: // %D
560 case analyze_format_string::ConversionSpecifier::uArg: // %d
561 case analyze_format_string::ConversionSpecifier::UArg: // %D
562 case analyze_format_string::ConversionSpecifier::xArg: // %d
563 case analyze_format_string::ConversionSpecifier::XArg: // %D
564 Precision = 1;
565 break;
566 case analyze_format_string::ConversionSpecifier::fArg: // %f
567 case analyze_format_string::ConversionSpecifier::FArg: // %F
568 case analyze_format_string::ConversionSpecifier::eArg: // %e
569 case analyze_format_string::ConversionSpecifier::EArg: // %E
570 case analyze_format_string::ConversionSpecifier::gArg: // %g
571 case analyze_format_string::ConversionSpecifier::GArg: // %G
572 Precision = 6;
573 break;
574 case analyze_format_string::ConversionSpecifier::pArg: // %d
575 Precision = 1;
576 break;
577 }
578 break;
579 case analyze_format_string::OptionalAmount::Constant:
580 Precision = FW.getConstantAmount();
581 break;
582 default:
583 break;
584 }
585 return Precision;
586 }
587};
588
589} // namespace
590
591/// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
592/// __builtin_*_chk function, then use the object size argument specified in the
593/// source. Otherwise, infer the object size using __builtin_object_size.
594void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
595 CallExpr *TheCall) {
596 // FIXME: There are some more useful checks we could be doing here:
597 // - Evaluate strlen of strcpy arguments, use as object size.
598
599 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
600 isConstantEvaluated())
601 return;
602
603 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
604 if (!BuiltinID)
605 return;
606
607 const TargetInfo &TI = getASTContext().getTargetInfo();
608 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
609
610 unsigned DiagID = 0;
611 bool IsChkVariant = false;
612 Optional<llvm::APSInt> UsedSize;
613 unsigned SizeIndex, ObjectIndex;
614 switch (BuiltinID) {
615 default:
616 return;
617 case Builtin::BIsprintf:
618 case Builtin::BI__builtin___sprintf_chk: {
619 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
620 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
621
622 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
623
624 if (!Format->isAscii() && !Format->isUTF8())
625 return;
626
627 StringRef FormatStrRef = Format->getString();
628 EstimateSizeFormatHandler H(FormatStrRef);
629 const char *FormatBytes = FormatStrRef.data();
630 const ConstantArrayType *T =
631 Context.getAsConstantArrayType(Format->getType());
632 assert(T && "String literal not of constant array type!")(static_cast <bool> (T && "String literal not of constant array type!"
) ? void (0) : __assert_fail ("T && \"String literal not of constant array type!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 632, __extension__ __PRETTY_FUNCTION__))
;
633 size_t TypeSize = T->getSize().getZExtValue();
634
635 // In case there's a null byte somewhere.
636 size_t StrLen =
637 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
638 if (!analyze_format_string::ParsePrintfString(
639 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
640 Context.getTargetInfo(), false)) {
641 DiagID = diag::warn_fortify_source_format_overflow;
642 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
643 .extOrTrunc(SizeTypeWidth);
644 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
645 IsChkVariant = true;
646 ObjectIndex = 2;
647 } else {
648 IsChkVariant = false;
649 ObjectIndex = 0;
650 }
651 break;
652 }
653 }
654 return;
655 }
656 case Builtin::BI__builtin___memcpy_chk:
657 case Builtin::BI__builtin___memmove_chk:
658 case Builtin::BI__builtin___memset_chk:
659// case Builtin::BI__builtin___strlcat_chk:
660// case Builtin::BI__builtin___strlcpy_chk:
661 case Builtin::BI__builtin___strncat_chk:
662 case Builtin::BI__builtin___strncpy_chk:
663 case Builtin::BI__builtin___stpncpy_chk:
664 case Builtin::BI__builtin___memccpy_chk:
665 case Builtin::BI__builtin___mempcpy_chk: {
666 DiagID = diag::warn_builtin_chk_overflow;
667 IsChkVariant = true;
668 SizeIndex = TheCall->getNumArgs() - 2;
669 ObjectIndex = TheCall->getNumArgs() - 1;
670 break;
671 }
672
673 case Builtin::BI__builtin___snprintf_chk:
674 case Builtin::BI__builtin___vsnprintf_chk: {
675 DiagID = diag::warn_builtin_chk_overflow;
676 IsChkVariant = true;
677 SizeIndex = 1;
678 ObjectIndex = 3;
679 break;
680 }
681
682 case Builtin::BIstrncat:
683 case Builtin::BI__builtin_strncat:
684 case Builtin::BIstrncpy:
685 case Builtin::BI__builtin_strncpy:
686 case Builtin::BIstpncpy:
687 case Builtin::BI__builtin_stpncpy: {
688 // Whether these functions overflow depends on the runtime strlen of the
689 // string, not just the buffer size, so emitting the "always overflow"
690 // diagnostic isn't quite right. We should still diagnose passing a buffer
691 // size larger than the destination buffer though; this is a runtime abort
692 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
693 DiagID = diag::warn_fortify_source_size_mismatch;
694 SizeIndex = TheCall->getNumArgs() - 1;
695 ObjectIndex = 0;
696 break;
697 }
698
699 case Builtin::BImemcpy:
700 case Builtin::BI__builtin_memcpy:
701 case Builtin::BImemmove:
702 case Builtin::BI__builtin_memmove:
703 case Builtin::BImemset:
704 case Builtin::BI__builtin_memset:
705 case Builtin::BImempcpy:
706 case Builtin::BI__builtin_mempcpy: {
707 DiagID = diag::warn_fortify_source_overflow;
708 SizeIndex = TheCall->getNumArgs() - 1;
709 ObjectIndex = 0;
710 break;
711 }
712 case Builtin::BIsnprintf:
713 case Builtin::BI__builtin_snprintf:
714 case Builtin::BIvsnprintf:
715 case Builtin::BI__builtin_vsnprintf: {
716 DiagID = diag::warn_fortify_source_size_mismatch;
717 SizeIndex = 1;
718 ObjectIndex = 0;
719 break;
720 }
721 }
722
723 llvm::APSInt ObjectSize;
724 // For __builtin___*_chk, the object size is explicitly provided by the caller
725 // (usually using __builtin_object_size). Use that value to check this call.
726 if (IsChkVariant) {
727 Expr::EvalResult Result;
728 Expr *SizeArg = TheCall->getArg(ObjectIndex);
729 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
730 return;
731 ObjectSize = Result.Val.getInt();
732
733 // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
734 } else {
735 // If the parameter has a pass_object_size attribute, then we should use its
736 // (potentially) more strict checking mode. Otherwise, conservatively assume
737 // type 0.
738 int BOSType = 0;
739 if (const auto *POS =
740 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
741 BOSType = POS->getType();
742
743 Expr *ObjArg = TheCall->getArg(ObjectIndex);
744 uint64_t Result;
745 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
746 return;
747 // Get the object size in the target's size_t width.
748 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
749 }
750
751 // Evaluate the number of bytes of the object that this call will use.
752 if (!UsedSize) {
753 Expr::EvalResult Result;
754 Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
755 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
756 return;
757 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
758 }
759
760 if (UsedSize.getValue().ule(ObjectSize))
761 return;
762
763 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
764 // Skim off the details of whichever builtin was called to produce a better
765 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
766 if (IsChkVariant) {
767 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
768 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
769 } else if (FunctionName.startswith("__builtin_")) {
770 FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
771 }
772
773 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
774 PDiag(DiagID)
775 << FunctionName << toString(ObjectSize, /*Radix=*/10)
776 << toString(UsedSize.getValue(), /*Radix=*/10));
777}
778
779static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
780 Scope::ScopeFlags NeededScopeFlags,
781 unsigned DiagID) {
782 // Scopes aren't available during instantiation. Fortunately, builtin
783 // functions cannot be template args so they cannot be formed through template
784 // instantiation. Therefore checking once during the parse is sufficient.
785 if (SemaRef.inTemplateInstantiation())
786 return false;
787
788 Scope *S = SemaRef.getCurScope();
789 while (S && !S->isSEHExceptScope())
790 S = S->getParent();
791 if (!S || !(S->getFlags() & NeededScopeFlags)) {
792 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
793 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
794 << DRE->getDecl()->getIdentifier();
795 return true;
796 }
797
798 return false;
799}
800
801static inline bool isBlockPointer(Expr *Arg) {
802 return Arg->getType()->isBlockPointerType();
803}
804
805/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
806/// void*, which is a requirement of device side enqueue.
807static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
808 const BlockPointerType *BPT =
809 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
810 ArrayRef<QualType> Params =
811 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
812 unsigned ArgCounter = 0;
813 bool IllegalParams = false;
814 // Iterate through the block parameters until either one is found that is not
815 // a local void*, or the block is valid.
816 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
817 I != E; ++I, ++ArgCounter) {
818 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
819 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
820 LangAS::opencl_local) {
821 // Get the location of the error. If a block literal has been passed
822 // (BlockExpr) then we can point straight to the offending argument,
823 // else we just point to the variable reference.
824 SourceLocation ErrorLoc;
825 if (isa<BlockExpr>(BlockArg)) {
826 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
827 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
828 } else if (isa<DeclRefExpr>(BlockArg)) {
829 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
830 }
831 S.Diag(ErrorLoc,
832 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
833 IllegalParams = true;
834 }
835 }
836
837 return IllegalParams;
838}
839
840static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
841 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
842 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
843 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
844 return true;
845 }
846 return false;
847}
848
849static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
850 if (checkArgCount(S, TheCall, 2))
851 return true;
852
853 if (checkOpenCLSubgroupExt(S, TheCall))
854 return true;
855
856 // First argument is an ndrange_t type.
857 Expr *NDRangeArg = TheCall->getArg(0);
858 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
859 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
860 << TheCall->getDirectCallee() << "'ndrange_t'";
861 return true;
862 }
863
864 Expr *BlockArg = TheCall->getArg(1);
865 if (!isBlockPointer(BlockArg)) {
866 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
867 << TheCall->getDirectCallee() << "block";
868 return true;
869 }
870 return checkOpenCLBlockArgs(S, BlockArg);
871}
872
873/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
874/// get_kernel_work_group_size
875/// and get_kernel_preferred_work_group_size_multiple builtin functions.
876static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
877 if (checkArgCount(S, TheCall, 1))
878 return true;
879
880 Expr *BlockArg = TheCall->getArg(0);
881 if (!isBlockPointer(BlockArg)) {
882 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
883 << TheCall->getDirectCallee() << "block";
884 return true;
885 }
886 return checkOpenCLBlockArgs(S, BlockArg);
887}
888
889/// Diagnose integer type and any valid implicit conversion to it.
890static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
891 const QualType &IntType);
892
893static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
894 unsigned Start, unsigned End) {
895 bool IllegalParams = false;
896 for (unsigned I = Start; I <= End; ++I)
897 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
898 S.Context.getSizeType());
899 return IllegalParams;
900}
901
902/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
903/// 'local void*' parameter of passed block.
904static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
905 Expr *BlockArg,
906 unsigned NumNonVarArgs) {
907 const BlockPointerType *BPT =
908 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
909 unsigned NumBlockParams =
910 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
911 unsigned TotalNumArgs = TheCall->getNumArgs();
912
913 // For each argument passed to the block, a corresponding uint needs to
914 // be passed to describe the size of the local memory.
915 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
916 S.Diag(TheCall->getBeginLoc(),
917 diag::err_opencl_enqueue_kernel_local_size_args);
918 return true;
919 }
920
921 // Check that the sizes of the local memory are specified by integers.
922 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
923 TotalNumArgs - 1);
924}
925
926/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
927/// overload formats specified in Table 6.13.17.1.
928/// int enqueue_kernel(queue_t queue,
929/// kernel_enqueue_flags_t flags,
930/// const ndrange_t ndrange,
931/// void (^block)(void))
932/// int enqueue_kernel(queue_t queue,
933/// kernel_enqueue_flags_t flags,
934/// const ndrange_t ndrange,
935/// uint num_events_in_wait_list,
936/// clk_event_t *event_wait_list,
937/// clk_event_t *event_ret,
938/// void (^block)(void))
939/// int enqueue_kernel(queue_t queue,
940/// kernel_enqueue_flags_t flags,
941/// const ndrange_t ndrange,
942/// void (^block)(local void*, ...),
943/// uint size0, ...)
944/// int enqueue_kernel(queue_t queue,
945/// kernel_enqueue_flags_t flags,
946/// const ndrange_t ndrange,
947/// uint num_events_in_wait_list,
948/// clk_event_t *event_wait_list,
949/// clk_event_t *event_ret,
950/// void (^block)(local void*, ...),
951/// uint size0, ...)
952static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
953 unsigned NumArgs = TheCall->getNumArgs();
954
955 if (NumArgs < 4) {
956 S.Diag(TheCall->getBeginLoc(),
957 diag::err_typecheck_call_too_few_args_at_least)
958 << 0 << 4 << NumArgs;
959 return true;
960 }
961
962 Expr *Arg0 = TheCall->getArg(0);
963 Expr *Arg1 = TheCall->getArg(1);
964 Expr *Arg2 = TheCall->getArg(2);
965 Expr *Arg3 = TheCall->getArg(3);
966
967 // First argument always needs to be a queue_t type.
968 if (!Arg0->getType()->isQueueT()) {
969 S.Diag(TheCall->getArg(0)->getBeginLoc(),
970 diag::err_opencl_builtin_expected_type)
971 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
972 return true;
973 }
974
975 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
976 if (!Arg1->getType()->isIntegerType()) {
977 S.Diag(TheCall->getArg(1)->getBeginLoc(),
978 diag::err_opencl_builtin_expected_type)
979 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
980 return true;
981 }
982
983 // Third argument is always an ndrange_t type.
984 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
985 S.Diag(TheCall->getArg(2)->getBeginLoc(),
986 diag::err_opencl_builtin_expected_type)
987 << TheCall->getDirectCallee() << "'ndrange_t'";
988 return true;
989 }
990
991 // With four arguments, there is only one form that the function could be
992 // called in: no events and no variable arguments.
993 if (NumArgs == 4) {
994 // check that the last argument is the right block type.
995 if (!isBlockPointer(Arg3)) {
996 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
997 << TheCall->getDirectCallee() << "block";
998 return true;
999 }
1000 // we have a block type, check the prototype
1001 const BlockPointerType *BPT =
1002 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1003 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1004 S.Diag(Arg3->getBeginLoc(),
1005 diag::err_opencl_enqueue_kernel_blocks_no_args);
1006 return true;
1007 }
1008 return false;
1009 }
1010 // we can have block + varargs.
1011 if (isBlockPointer(Arg3))
1012 return (checkOpenCLBlockArgs(S, Arg3) ||
1013 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1014 // last two cases with either exactly 7 args or 7 args and varargs.
1015 if (NumArgs >= 7) {
1016 // check common block argument.
1017 Expr *Arg6 = TheCall->getArg(6);
1018 if (!isBlockPointer(Arg6)) {
1019 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1020 << TheCall->getDirectCallee() << "block";
1021 return true;
1022 }
1023 if (checkOpenCLBlockArgs(S, Arg6))
1024 return true;
1025
1026 // Forth argument has to be any integer type.
1027 if (!Arg3->getType()->isIntegerType()) {
1028 S.Diag(TheCall->getArg(3)->getBeginLoc(),
1029 diag::err_opencl_builtin_expected_type)
1030 << TheCall->getDirectCallee() << "integer";
1031 return true;
1032 }
1033 // check remaining common arguments.
1034 Expr *Arg4 = TheCall->getArg(4);
1035 Expr *Arg5 = TheCall->getArg(5);
1036
1037 // Fifth argument is always passed as a pointer to clk_event_t.
1038 if (!Arg4->isNullPointerConstant(S.Context,
1039 Expr::NPC_ValueDependentIsNotNull) &&
1040 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1041 S.Diag(TheCall->getArg(4)->getBeginLoc(),
1042 diag::err_opencl_builtin_expected_type)
1043 << TheCall->getDirectCallee()
1044 << S.Context.getPointerType(S.Context.OCLClkEventTy);
1045 return true;
1046 }
1047
1048 // Sixth argument is always passed as a pointer to clk_event_t.
1049 if (!Arg5->isNullPointerConstant(S.Context,
1050 Expr::NPC_ValueDependentIsNotNull) &&
1051 !(Arg5->getType()->isPointerType() &&
1052 Arg5->getType()->getPointeeType()->isClkEventT())) {
1053 S.Diag(TheCall->getArg(5)->getBeginLoc(),
1054 diag::err_opencl_builtin_expected_type)
1055 << TheCall->getDirectCallee()
1056 << S.Context.getPointerType(S.Context.OCLClkEventTy);
1057 return true;
1058 }
1059
1060 if (NumArgs == 7)
1061 return false;
1062
1063 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1064 }
1065
1066 // None of the specific case has been detected, give generic error
1067 S.Diag(TheCall->getBeginLoc(),
1068 diag::err_opencl_enqueue_kernel_incorrect_args);
1069 return true;
1070}
1071
1072/// Returns OpenCL access qual.
1073static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1074 return D->getAttr<OpenCLAccessAttr>();
1075}
1076
1077/// Returns true if pipe element type is different from the pointer.
1078static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1079 const Expr *Arg0 = Call->getArg(0);
1080 // First argument type should always be pipe.
1081 if (!Arg0->getType()->isPipeType()) {
1082 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1083 << Call->getDirectCallee() << Arg0->getSourceRange();
1084 return true;
1085 }
1086 OpenCLAccessAttr *AccessQual =
1087 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1088 // Validates the access qualifier is compatible with the call.
1089 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1090 // read_only and write_only, and assumed to be read_only if no qualifier is
1091 // specified.
1092 switch (Call->getDirectCallee()->getBuiltinID()) {
1093 case Builtin::BIread_pipe:
1094 case Builtin::BIreserve_read_pipe:
1095 case Builtin::BIcommit_read_pipe:
1096 case Builtin::BIwork_group_reserve_read_pipe:
1097 case Builtin::BIsub_group_reserve_read_pipe:
1098 case Builtin::BIwork_group_commit_read_pipe:
1099 case Builtin::BIsub_group_commit_read_pipe:
1100 if (!(!AccessQual || AccessQual->isReadOnly())) {
1101 S.Diag(Arg0->getBeginLoc(),
1102 diag::err_opencl_builtin_pipe_invalid_access_modifier)
1103 << "read_only" << Arg0->getSourceRange();
1104 return true;
1105 }
1106 break;
1107 case Builtin::BIwrite_pipe:
1108 case Builtin::BIreserve_write_pipe:
1109 case Builtin::BIcommit_write_pipe:
1110 case Builtin::BIwork_group_reserve_write_pipe:
1111 case Builtin::BIsub_group_reserve_write_pipe:
1112 case Builtin::BIwork_group_commit_write_pipe:
1113 case Builtin::BIsub_group_commit_write_pipe:
1114 if (!(AccessQual && AccessQual->isWriteOnly())) {
1115 S.Diag(Arg0->getBeginLoc(),
1116 diag::err_opencl_builtin_pipe_invalid_access_modifier)
1117 << "write_only" << Arg0->getSourceRange();
1118 return true;
1119 }
1120 break;
1121 default:
1122 break;
1123 }
1124 return false;
1125}
1126
1127/// Returns true if pipe element type is different from the pointer.
1128static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1129 const Expr *Arg0 = Call->getArg(0);
1130 const Expr *ArgIdx = Call->getArg(Idx);
1131 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1132 const QualType EltTy = PipeTy->getElementType();
1133 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1134 // The Idx argument should be a pointer and the type of the pointer and
1135 // the type of pipe element should also be the same.
1136 if (!ArgTy ||
1137 !S.Context.hasSameType(
1138 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1139 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1140 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1141 << ArgIdx->getType() << ArgIdx->getSourceRange();
1142 return true;
1143 }
1144 return false;
1145}
1146
1147// Performs semantic analysis for the read/write_pipe call.
1148// \param S Reference to the semantic analyzer.
1149// \param Call A pointer to the builtin call.
1150// \return True if a semantic error has been found, false otherwise.
1151static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1152 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1153 // functions have two forms.
1154 switch (Call->getNumArgs()) {
1155 case 2:
1156 if (checkOpenCLPipeArg(S, Call))
1157 return true;
1158 // The call with 2 arguments should be
1159 // read/write_pipe(pipe T, T*).
1160 // Check packet type T.
1161 if (checkOpenCLPipePacketType(S, Call, 1))
1162 return true;
1163 break;
1164
1165 case 4: {
1166 if (checkOpenCLPipeArg(S, Call))
1167 return true;
1168 // The call with 4 arguments should be
1169 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1170 // Check reserve_id_t.
1171 if (!Call->getArg(1)->getType()->isReserveIDT()) {
1172 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1173 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1174 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1175 return true;
1176 }
1177
1178 // Check the index.
1179 const Expr *Arg2 = Call->getArg(2);
1180 if (!Arg2->getType()->isIntegerType() &&
1181 !Arg2->getType()->isUnsignedIntegerType()) {
1182 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1183 << Call->getDirectCallee() << S.Context.UnsignedIntTy
1184 << Arg2->getType() << Arg2->getSourceRange();
1185 return true;
1186 }
1187
1188 // Check packet type T.
1189 if (checkOpenCLPipePacketType(S, Call, 3))
1190 return true;
1191 } break;
1192 default:
1193 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1194 << Call->getDirectCallee() << Call->getSourceRange();
1195 return true;
1196 }
1197
1198 return false;
1199}
1200
1201// Performs a semantic analysis on the {work_group_/sub_group_
1202// /_}reserve_{read/write}_pipe
1203// \param S Reference to the semantic analyzer.
1204// \param Call The call to the builtin function to be analyzed.
1205// \return True if a semantic error was found, false otherwise.
1206static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1207 if (checkArgCount(S, Call, 2))
1208 return true;
1209
1210 if (checkOpenCLPipeArg(S, Call))
1211 return true;
1212
1213 // Check the reserve size.
1214 if (!Call->getArg(1)->getType()->isIntegerType() &&
1215 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1216 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1217 << Call->getDirectCallee() << S.Context.UnsignedIntTy
1218 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1219 return true;
1220 }
1221
1222 // Since return type of reserve_read/write_pipe built-in function is
1223 // reserve_id_t, which is not defined in the builtin def file , we used int
1224 // as return type and need to override the return type of these functions.
1225 Call->setType(S.Context.OCLReserveIDTy);
1226
1227 return false;
1228}
1229
1230// Performs a semantic analysis on {work_group_/sub_group_
1231// /_}commit_{read/write}_pipe
1232// \param S Reference to the semantic analyzer.
1233// \param Call The call to the builtin function to be analyzed.
1234// \return True if a semantic error was found, false otherwise.
1235static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1236 if (checkArgCount(S, Call, 2))
1237 return true;
1238
1239 if (checkOpenCLPipeArg(S, Call))
1240 return true;
1241
1242 // Check reserve_id_t.
1243 if (!Call->getArg(1)->getType()->isReserveIDT()) {
1244 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1245 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1246 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1247 return true;
1248 }
1249
1250 return false;
1251}
1252
1253// Performs a semantic analysis on the call to built-in Pipe
1254// Query Functions.
1255// \param S Reference to the semantic analyzer.
1256// \param Call The call to the builtin function to be analyzed.
1257// \return True if a semantic error was found, false otherwise.
1258static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1259 if (checkArgCount(S, Call, 1))
1260 return true;
1261
1262 if (!Call->getArg(0)->getType()->isPipeType()) {
1263 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1264 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1265 return true;
1266 }
1267
1268 return false;
1269}
1270
1271// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1272// Performs semantic analysis for the to_global/local/private call.
1273// \param S Reference to the semantic analyzer.
1274// \param BuiltinID ID of the builtin function.
1275// \param Call A pointer to the builtin call.
1276// \return True if a semantic error has been found, false otherwise.
1277static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1278 CallExpr *Call) {
1279 if (checkArgCount(S, Call, 1))
1280 return true;
1281
1282 auto RT = Call->getArg(0)->getType();
1283 if (!RT->isPointerType() || RT->getPointeeType()
1284 .getAddressSpace() == LangAS::opencl_constant) {
1285 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1286 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1287 return true;
1288 }
1289
1290 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1291 S.Diag(Call->getArg(0)->getBeginLoc(),
1292 diag::warn_opencl_generic_address_space_arg)
1293 << Call->getDirectCallee()->getNameInfo().getAsString()
1294 << Call->getArg(0)->getSourceRange();
1295 }
1296
1297 RT = RT->getPointeeType();
1298 auto Qual = RT.getQualifiers();
1299 switch (BuiltinID) {
1300 case Builtin::BIto_global:
1301 Qual.setAddressSpace(LangAS::opencl_global);
1302 break;
1303 case Builtin::BIto_local:
1304 Qual.setAddressSpace(LangAS::opencl_local);
1305 break;
1306 case Builtin::BIto_private:
1307 Qual.setAddressSpace(LangAS::opencl_private);
1308 break;
1309 default:
1310 llvm_unreachable("Invalid builtin function")::llvm::llvm_unreachable_internal("Invalid builtin function",
"/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 1310)
;
1311 }
1312 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1313 RT.getUnqualifiedType(), Qual)));
1314
1315 return false;
1316}
1317
1318static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1319 if (checkArgCount(S, TheCall, 1))
1320 return ExprError();
1321
1322 // Compute __builtin_launder's parameter type from the argument.
1323 // The parameter type is:
1324 // * The type of the argument if it's not an array or function type,
1325 // Otherwise,
1326 // * The decayed argument type.
1327 QualType ParamTy = [&]() {
1328 QualType ArgTy = TheCall->getArg(0)->getType();
1329 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1330 return S.Context.getPointerType(Ty->getElementType());
1331 if (ArgTy->isFunctionType()) {
1332 return S.Context.getPointerType(ArgTy);
1333 }
1334 return ArgTy;
1335 }();
1336
1337 TheCall->setType(ParamTy);
1338
1339 auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1340 if (!ParamTy->isPointerType())
1341 return 0;
1342 if (ParamTy->isFunctionPointerType())
1343 return 1;
1344 if (ParamTy->isVoidPointerType())
1345 return 2;
1346 return llvm::Optional<unsigned>{};
1347 }();
1348 if (DiagSelect.hasValue()) {
1349 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1350 << DiagSelect.getValue() << TheCall->getSourceRange();
1351 return ExprError();
1352 }
1353
1354 // We either have an incomplete class type, or we have a class template
1355 // whose instantiation has not been forced. Example:
1356 //
1357 // template <class T> struct Foo { T value; };
1358 // Foo<int> *p = nullptr;
1359 // auto *d = __builtin_launder(p);
1360 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1361 diag::err_incomplete_type))
1362 return ExprError();
1363
1364 assert(ParamTy->getPointeeType()->isObjectType() &&(static_cast <bool> (ParamTy->getPointeeType()->isObjectType
() && "Unhandled non-object pointer case") ? void (0)
: __assert_fail ("ParamTy->getPointeeType()->isObjectType() && \"Unhandled non-object pointer case\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 1365, __extension__ __PRETTY_FUNCTION__))
1365 "Unhandled non-object pointer case")(static_cast <bool> (ParamTy->getPointeeType()->isObjectType
() && "Unhandled non-object pointer case") ? void (0)
: __assert_fail ("ParamTy->getPointeeType()->isObjectType() && \"Unhandled non-object pointer case\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 1365, __extension__ __PRETTY_FUNCTION__))
;
1366
1367 InitializedEntity Entity =
1368 InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1369 ExprResult Arg =
1370 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1371 if (Arg.isInvalid())
1372 return ExprError();
1373 TheCall->setArg(0, Arg.get());
1374
1375 return TheCall;
1376}
1377
1378// Emit an error and return true if the current architecture is not in the list
1379// of supported architectures.
1380static bool
1381CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1382 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1383 llvm::Triple::ArchType CurArch =
1384 S.getASTContext().getTargetInfo().getTriple().getArch();
1385 if (llvm::is_contained(SupportedArchs, CurArch))
1386 return false;
1387 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1388 << TheCall->getSourceRange();
1389 return true;
1390}
1391
1392static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1393 SourceLocation CallSiteLoc);
1394
1395bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1396 CallExpr *TheCall) {
1397 switch (TI.getTriple().getArch()) {
1398 default:
1399 // Some builtins don't require additional checking, so just consider these
1400 // acceptable.
1401 return false;
1402 case llvm::Triple::arm:
1403 case llvm::Triple::armeb:
1404 case llvm::Triple::thumb:
1405 case llvm::Triple::thumbeb:
1406 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1407 case llvm::Triple::aarch64:
1408 case llvm::Triple::aarch64_32:
1409 case llvm::Triple::aarch64_be:
1410 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1411 case llvm::Triple::bpfeb:
1412 case llvm::Triple::bpfel:
1413 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1414 case llvm::Triple::hexagon:
1415 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1416 case llvm::Triple::mips:
1417 case llvm::Triple::mipsel:
1418 case llvm::Triple::mips64:
1419 case llvm::Triple::mips64el:
1420 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1421 case llvm::Triple::systemz:
1422 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1423 case llvm::Triple::x86:
1424 case llvm::Triple::x86_64:
1425 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1426 case llvm::Triple::ppc:
1427 case llvm::Triple::ppcle:
1428 case llvm::Triple::ppc64:
1429 case llvm::Triple::ppc64le:
1430 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1431 case llvm::Triple::amdgcn:
1432 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1433 case llvm::Triple::riscv32:
1434 case llvm::Triple::riscv64:
1435 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1436 }
1437}
1438
1439ExprResult
1440Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1441 CallExpr *TheCall) {
1442 ExprResult TheCallResult(TheCall);
1443
1444 // Find out if any arguments are required to be integer constant expressions.
1445 unsigned ICEArguments = 0;
1446 ASTContext::GetBuiltinTypeError Error;
1447 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1448 if (Error != ASTContext::GE_None)
1449 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
1450
1451 // If any arguments are required to be ICE's, check and diagnose.
1452 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1453 // Skip arguments not required to be ICE's.
1454 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1455
1456 llvm::APSInt Result;
1457 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1458 return true;
1459 ICEArguments &= ~(1 << ArgNo);
1460 }
1461
1462 switch (BuiltinID) {
1463 case Builtin::BI__builtin___CFStringMakeConstantString:
1464 assert(TheCall->getNumArgs() == 1 &&(static_cast <bool> (TheCall->getNumArgs() == 1 &&
"Wrong # arguments to builtin CFStringMakeConstantString") ?
void (0) : __assert_fail ("TheCall->getNumArgs() == 1 && \"Wrong # arguments to builtin CFStringMakeConstantString\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 1465, __extension__ __PRETTY_FUNCTION__))
1465 "Wrong # arguments to builtin CFStringMakeConstantString")(static_cast <bool> (TheCall->getNumArgs() == 1 &&
"Wrong # arguments to builtin CFStringMakeConstantString") ?
void (0) : __assert_fail ("TheCall->getNumArgs() == 1 && \"Wrong # arguments to builtin CFStringMakeConstantString\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 1465, __extension__ __PRETTY_FUNCTION__))
;
1466 if (CheckObjCString(TheCall->getArg(0)))
1467 return ExprError();
1468 break;
1469 case Builtin::BI__builtin_ms_va_start:
1470 case Builtin::BI__builtin_stdarg_start:
1471 case Builtin::BI__builtin_va_start:
1472 if (SemaBuiltinVAStart(BuiltinID, TheCall))
1473 return ExprError();
1474 break;
1475 case Builtin::BI__va_start: {
1476 switch (Context.getTargetInfo().getTriple().getArch()) {
1477 case llvm::Triple::aarch64:
1478 case llvm::Triple::arm:
1479 case llvm::Triple::thumb:
1480 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1481 return ExprError();
1482 break;
1483 default:
1484 if (SemaBuiltinVAStart(BuiltinID, TheCall))
1485 return ExprError();
1486 break;
1487 }
1488 break;
1489 }
1490
1491 // The acquire, release, and no fence variants are ARM and AArch64 only.
1492 case Builtin::BI_interlockedbittestandset_acq:
1493 case Builtin::BI_interlockedbittestandset_rel:
1494 case Builtin::BI_interlockedbittestandset_nf:
1495 case Builtin::BI_interlockedbittestandreset_acq:
1496 case Builtin::BI_interlockedbittestandreset_rel:
1497 case Builtin::BI_interlockedbittestandreset_nf:
1498 if (CheckBuiltinTargetSupport(
1499 *this, BuiltinID, TheCall,
1500 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1501 return ExprError();
1502 break;
1503
1504 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1505 case Builtin::BI_bittest64:
1506 case Builtin::BI_bittestandcomplement64:
1507 case Builtin::BI_bittestandreset64:
1508 case Builtin::BI_bittestandset64:
1509 case Builtin::BI_interlockedbittestandreset64:
1510 case Builtin::BI_interlockedbittestandset64:
1511 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1512 {llvm::Triple::x86_64, llvm::Triple::arm,
1513 llvm::Triple::thumb, llvm::Triple::aarch64}))
1514 return ExprError();
1515 break;
1516
1517 case Builtin::BI__builtin_isgreater:
1518 case Builtin::BI__builtin_isgreaterequal:
1519 case Builtin::BI__builtin_isless:
1520 case Builtin::BI__builtin_islessequal:
1521 case Builtin::BI__builtin_islessgreater:
1522 case Builtin::BI__builtin_isunordered:
1523 if (SemaBuiltinUnorderedCompare(TheCall))
1524 return ExprError();
1525 break;
1526 case Builtin::BI__builtin_fpclassify:
1527 if (SemaBuiltinFPClassification(TheCall, 6))
1528 return ExprError();
1529 break;
1530 case Builtin::BI__builtin_isfinite:
1531 case Builtin::BI__builtin_isinf:
1532 case Builtin::BI__builtin_isinf_sign:
1533 case Builtin::BI__builtin_isnan:
1534 case Builtin::BI__builtin_isnormal:
1535 case Builtin::BI__builtin_signbit:
1536 case Builtin::BI__builtin_signbitf:
1537 case Builtin::BI__builtin_signbitl:
1538 if (SemaBuiltinFPClassification(TheCall, 1))
1539 return ExprError();
1540 break;
1541 case Builtin::BI__builtin_shufflevector:
1542 return SemaBuiltinShuffleVector(TheCall);
1543 // TheCall will be freed by the smart pointer here, but that's fine, since
1544 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1545 case Builtin::BI__builtin_prefetch:
1546 if (SemaBuiltinPrefetch(TheCall))
1547 return ExprError();
1548 break;
1549 case Builtin::BI__builtin_alloca_with_align:
1550 if (SemaBuiltinAllocaWithAlign(TheCall))
1551 return ExprError();
1552 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1553 case Builtin::BI__builtin_alloca:
1554 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1555 << TheCall->getDirectCallee();
1556 break;
1557 case Builtin::BI__assume:
1558 case Builtin::BI__builtin_assume:
1559 if (SemaBuiltinAssume(TheCall))
1560 return ExprError();
1561 break;
1562 case Builtin::BI__builtin_assume_aligned:
1563 if (SemaBuiltinAssumeAligned(TheCall))
1564 return ExprError();
1565 break;
1566 case Builtin::BI__builtin_dynamic_object_size:
1567 case Builtin::BI__builtin_object_size:
1568 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1569 return ExprError();
1570 break;
1571 case Builtin::BI__builtin_longjmp:
1572 if (SemaBuiltinLongjmp(TheCall))
1573 return ExprError();
1574 break;
1575 case Builtin::BI__builtin_setjmp:
1576 if (SemaBuiltinSetjmp(TheCall))
1577 return ExprError();
1578 break;
1579 case Builtin::BI__builtin_classify_type:
1580 if (checkArgCount(*this, TheCall, 1)) return true;
1581 TheCall->setType(Context.IntTy);
1582 break;
1583 case Builtin::BI__builtin_complex:
1584 if (SemaBuiltinComplex(TheCall))
1585 return ExprError();
1586 break;
1587 case Builtin::BI__builtin_constant_p: {
1588 if (checkArgCount(*this, TheCall, 1)) return true;
1589 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1590 if (Arg.isInvalid()) return true;
1591 TheCall->setArg(0, Arg.get());
1592 TheCall->setType(Context.IntTy);
1593 break;
1594 }
1595 case Builtin::BI__builtin_launder:
1596 return SemaBuiltinLaunder(*this, TheCall);
1597 case Builtin::BI__sync_fetch_and_add:
1598 case Builtin::BI__sync_fetch_and_add_1:
1599 case Builtin::BI__sync_fetch_and_add_2:
1600 case Builtin::BI__sync_fetch_and_add_4:
1601 case Builtin::BI__sync_fetch_and_add_8:
1602 case Builtin::BI__sync_fetch_and_add_16:
1603 case Builtin::BI__sync_fetch_and_sub:
1604 case Builtin::BI__sync_fetch_and_sub_1:
1605 case Builtin::BI__sync_fetch_and_sub_2:
1606 case Builtin::BI__sync_fetch_and_sub_4:
1607 case Builtin::BI__sync_fetch_and_sub_8:
1608 case Builtin::BI__sync_fetch_and_sub_16:
1609 case Builtin::BI__sync_fetch_and_or:
1610 case Builtin::BI__sync_fetch_and_or_1:
1611 case Builtin::BI__sync_fetch_and_or_2:
1612 case Builtin::BI__sync_fetch_and_or_4:
1613 case Builtin::BI__sync_fetch_and_or_8:
1614 case Builtin::BI__sync_fetch_and_or_16:
1615 case Builtin::BI__sync_fetch_and_and:
1616 case Builtin::BI__sync_fetch_and_and_1:
1617 case Builtin::BI__sync_fetch_and_and_2:
1618 case Builtin::BI__sync_fetch_and_and_4:
1619 case Builtin::BI__sync_fetch_and_and_8:
1620 case Builtin::BI__sync_fetch_and_and_16:
1621 case Builtin::BI__sync_fetch_and_xor:
1622 case Builtin::BI__sync_fetch_and_xor_1:
1623 case Builtin::BI__sync_fetch_and_xor_2:
1624 case Builtin::BI__sync_fetch_and_xor_4:
1625 case Builtin::BI__sync_fetch_and_xor_8:
1626 case Builtin::BI__sync_fetch_and_xor_16:
1627 case Builtin::BI__sync_fetch_and_nand:
1628 case Builtin::BI__sync_fetch_and_nand_1:
1629 case Builtin::BI__sync_fetch_and_nand_2:
1630 case Builtin::BI__sync_fetch_and_nand_4:
1631 case Builtin::BI__sync_fetch_and_nand_8:
1632 case Builtin::BI__sync_fetch_and_nand_16:
1633 case Builtin::BI__sync_add_and_fetch:
1634 case Builtin::BI__sync_add_and_fetch_1:
1635 case Builtin::BI__sync_add_and_fetch_2:
1636 case Builtin::BI__sync_add_and_fetch_4:
1637 case Builtin::BI__sync_add_and_fetch_8:
1638 case Builtin::BI__sync_add_and_fetch_16:
1639 case Builtin::BI__sync_sub_and_fetch:
1640 case Builtin::BI__sync_sub_and_fetch_1:
1641 case Builtin::BI__sync_sub_and_fetch_2:
1642 case Builtin::BI__sync_sub_and_fetch_4:
1643 case Builtin::BI__sync_sub_and_fetch_8:
1644 case Builtin::BI__sync_sub_and_fetch_16:
1645 case Builtin::BI__sync_and_and_fetch:
1646 case Builtin::BI__sync_and_and_fetch_1:
1647 case Builtin::BI__sync_and_and_fetch_2:
1648 case Builtin::BI__sync_and_and_fetch_4:
1649 case Builtin::BI__sync_and_and_fetch_8:
1650 case Builtin::BI__sync_and_and_fetch_16:
1651 case Builtin::BI__sync_or_and_fetch:
1652 case Builtin::BI__sync_or_and_fetch_1:
1653 case Builtin::BI__sync_or_and_fetch_2:
1654 case Builtin::BI__sync_or_and_fetch_4:
1655 case Builtin::BI__sync_or_and_fetch_8:
1656 case Builtin::BI__sync_or_and_fetch_16:
1657 case Builtin::BI__sync_xor_and_fetch:
1658 case Builtin::BI__sync_xor_and_fetch_1:
1659 case Builtin::BI__sync_xor_and_fetch_2:
1660 case Builtin::BI__sync_xor_and_fetch_4:
1661 case Builtin::BI__sync_xor_and_fetch_8:
1662 case Builtin::BI__sync_xor_and_fetch_16:
1663 case Builtin::BI__sync_nand_and_fetch:
1664 case Builtin::BI__sync_nand_and_fetch_1:
1665 case Builtin::BI__sync_nand_and_fetch_2:
1666 case Builtin::BI__sync_nand_and_fetch_4:
1667 case Builtin::BI__sync_nand_and_fetch_8:
1668 case Builtin::BI__sync_nand_and_fetch_16:
1669 case Builtin::BI__sync_val_compare_and_swap:
1670 case Builtin::BI__sync_val_compare_and_swap_1:
1671 case Builtin::BI__sync_val_compare_and_swap_2:
1672 case Builtin::BI__sync_val_compare_and_swap_4:
1673 case Builtin::BI__sync_val_compare_and_swap_8:
1674 case Builtin::BI__sync_val_compare_and_swap_16:
1675 case Builtin::BI__sync_bool_compare_and_swap:
1676 case Builtin::BI__sync_bool_compare_and_swap_1:
1677 case Builtin::BI__sync_bool_compare_and_swap_2:
1678 case Builtin::BI__sync_bool_compare_and_swap_4:
1679 case Builtin::BI__sync_bool_compare_and_swap_8:
1680 case Builtin::BI__sync_bool_compare_and_swap_16:
1681 case Builtin::BI__sync_lock_test_and_set:
1682 case Builtin::BI__sync_lock_test_and_set_1:
1683 case Builtin::BI__sync_lock_test_and_set_2:
1684 case Builtin::BI__sync_lock_test_and_set_4:
1685 case Builtin::BI__sync_lock_test_and_set_8:
1686 case Builtin::BI__sync_lock_test_and_set_16:
1687 case Builtin::BI__sync_lock_release:
1688 case Builtin::BI__sync_lock_release_1:
1689 case Builtin::BI__sync_lock_release_2:
1690 case Builtin::BI__sync_lock_release_4:
1691 case Builtin::BI__sync_lock_release_8:
1692 case Builtin::BI__sync_lock_release_16:
1693 case Builtin::BI__sync_swap:
1694 case Builtin::BI__sync_swap_1:
1695 case Builtin::BI__sync_swap_2:
1696 case Builtin::BI__sync_swap_4:
1697 case Builtin::BI__sync_swap_8:
1698 case Builtin::BI__sync_swap_16:
1699 return SemaBuiltinAtomicOverloaded(TheCallResult);
1700 case Builtin::BI__sync_synchronize:
1701 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1702 << TheCall->getCallee()->getSourceRange();
1703 break;
1704 case Builtin::BI__builtin_nontemporal_load:
1705 case Builtin::BI__builtin_nontemporal_store:
1706 return SemaBuiltinNontemporalOverloaded(TheCallResult);
1707 case Builtin::BI__builtin_memcpy_inline: {
1708 clang::Expr *SizeOp = TheCall->getArg(2);
1709 // We warn about copying to or from `nullptr` pointers when `size` is
1710 // greater than 0. When `size` is value dependent we cannot evaluate its
1711 // value so we bail out.
1712 if (SizeOp->isValueDependent())
1713 break;
1714 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1715 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1716 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1717 }
1718 break;
1719 }
1720#define BUILTIN(ID, TYPE, ATTRS)
1721#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1722 case Builtin::BI##ID: \
1723 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1724#include "clang/Basic/Builtins.def"
1725 case Builtin::BI__annotation:
1726 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1727 return ExprError();
1728 break;
1729 case Builtin::BI__builtin_annotation:
1730 if (SemaBuiltinAnnotation(*this, TheCall))
1731 return ExprError();
1732 break;
1733 case Builtin::BI__builtin_addressof:
1734 if (SemaBuiltinAddressof(*this, TheCall))
1735 return ExprError();
1736 break;
1737 case Builtin::BI__builtin_is_aligned:
1738 case Builtin::BI__builtin_align_up:
1739 case Builtin::BI__builtin_align_down:
1740 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1741 return ExprError();
1742 break;
1743 case Builtin::BI__builtin_add_overflow:
1744 case Builtin::BI__builtin_sub_overflow:
1745 case Builtin::BI__builtin_mul_overflow:
1746 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1747 return ExprError();
1748 break;
1749 case Builtin::BI__builtin_operator_new:
1750 case Builtin::BI__builtin_operator_delete: {
1751 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1752 ExprResult Res =
1753 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1754 if (Res.isInvalid())
1755 CorrectDelayedTyposInExpr(TheCallResult.get());
1756 return Res;
1757 }
1758 case Builtin::BI__builtin_dump_struct: {
1759 // We first want to ensure we are called with 2 arguments
1760 if (checkArgCount(*this, TheCall, 2))
1761 return ExprError();
1762 // Ensure that the first argument is of type 'struct XX *'
1763 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1764 const QualType PtrArgType = PtrArg->getType();
1765 if (!PtrArgType->isPointerType() ||
1766 !PtrArgType->getPointeeType()->isRecordType()) {
1767 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1768 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1769 << "structure pointer";
1770 return ExprError();
1771 }
1772
1773 // Ensure that the second argument is of type 'FunctionType'
1774 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1775 const QualType FnPtrArgType = FnPtrArg->getType();
1776 if (!FnPtrArgType->isPointerType()) {
1777 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1778 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1779 << FnPtrArgType << "'int (*)(const char *, ...)'";
1780 return ExprError();
1781 }
1782
1783 const auto *FuncType =
1784 FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1785
1786 if (!FuncType) {
1787 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1788 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1789 << FnPtrArgType << "'int (*)(const char *, ...)'";
1790 return ExprError();
1791 }
1792
1793 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1794 if (!FT->getNumParams()) {
1795 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1796 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1797 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1798 return ExprError();
1799 }
1800 QualType PT = FT->getParamType(0);
1801 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1802 !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1803 !PT->getPointeeType().isConstQualified()) {
1804 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1805 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1806 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1807 return ExprError();
1808 }
1809 }
1810
1811 TheCall->setType(Context.IntTy);
1812 break;
1813 }
1814 case Builtin::BI__builtin_expect_with_probability: {
1815 // We first want to ensure we are called with 3 arguments
1816 if (checkArgCount(*this, TheCall, 3))
1817 return ExprError();
1818 // then check probability is constant float in range [0.0, 1.0]
1819 const Expr *ProbArg = TheCall->getArg(2);
1820 SmallVector<PartialDiagnosticAt, 8> Notes;
1821 Expr::EvalResult Eval;
1822 Eval.Diag = &Notes;
1823 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1824 !Eval.Val.isFloat()) {
1825 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1826 << ProbArg->getSourceRange();
1827 for (const PartialDiagnosticAt &PDiag : Notes)
1828 Diag(PDiag.first, PDiag.second);
1829 return ExprError();
1830 }
1831 llvm::APFloat Probability = Eval.Val.getFloat();
1832 bool LoseInfo = false;
1833 Probability.convert(llvm::APFloat::IEEEdouble(),
1834 llvm::RoundingMode::Dynamic, &LoseInfo);
1835 if (!(Probability >= llvm::APFloat(0.0) &&
1836 Probability <= llvm::APFloat(1.0))) {
1837 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1838 << ProbArg->getSourceRange();
1839 return ExprError();
1840 }
1841 break;
1842 }
1843 case Builtin::BI__builtin_preserve_access_index:
1844 if (SemaBuiltinPreserveAI(*this, TheCall))
1845 return ExprError();
1846 break;
1847 case Builtin::BI__builtin_call_with_static_chain:
1848 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1849 return ExprError();
1850 break;
1851 case Builtin::BI__exception_code:
1852 case Builtin::BI_exception_code:
1853 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1854 diag::err_seh___except_block))
1855 return ExprError();
1856 break;
1857 case Builtin::BI__exception_info:
1858 case Builtin::BI_exception_info:
1859 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1860 diag::err_seh___except_filter))
1861 return ExprError();
1862 break;
1863 case Builtin::BI__GetExceptionInfo:
1864 if (checkArgCount(*this, TheCall, 1))
1865 return ExprError();
1866
1867 if (CheckCXXThrowOperand(
1868 TheCall->getBeginLoc(),
1869 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1870 TheCall))
1871 return ExprError();
1872
1873 TheCall->setType(Context.VoidPtrTy);
1874 break;
1875 // OpenCL v2.0, s6.13.16 - Pipe functions
1876 case Builtin::BIread_pipe:
1877 case Builtin::BIwrite_pipe:
1878 // Since those two functions are declared with var args, we need a semantic
1879 // check for the argument.
1880 if (SemaBuiltinRWPipe(*this, TheCall))
1881 return ExprError();
1882 break;
1883 case Builtin::BIreserve_read_pipe:
1884 case Builtin::BIreserve_write_pipe:
1885 case Builtin::BIwork_group_reserve_read_pipe:
1886 case Builtin::BIwork_group_reserve_write_pipe:
1887 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1888 return ExprError();
1889 break;
1890 case Builtin::BIsub_group_reserve_read_pipe:
1891 case Builtin::BIsub_group_reserve_write_pipe:
1892 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1893 SemaBuiltinReserveRWPipe(*this, TheCall))
1894 return ExprError();
1895 break;
1896 case Builtin::BIcommit_read_pipe:
1897 case Builtin::BIcommit_write_pipe:
1898 case Builtin::BIwork_group_commit_read_pipe:
1899 case Builtin::BIwork_group_commit_write_pipe:
1900 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1901 return ExprError();
1902 break;
1903 case Builtin::BIsub_group_commit_read_pipe:
1904 case Builtin::BIsub_group_commit_write_pipe:
1905 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1906 SemaBuiltinCommitRWPipe(*this, TheCall))
1907 return ExprError();
1908 break;
1909 case Builtin::BIget_pipe_num_packets:
1910 case Builtin::BIget_pipe_max_packets:
1911 if (SemaBuiltinPipePackets(*this, TheCall))
1912 return ExprError();
1913 break;
1914 case Builtin::BIto_global:
1915 case Builtin::BIto_local:
1916 case Builtin::BIto_private:
1917 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1918 return ExprError();
1919 break;
1920 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1921 case Builtin::BIenqueue_kernel:
1922 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1923 return ExprError();
1924 break;
1925 case Builtin::BIget_kernel_work_group_size:
1926 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1927 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1928 return ExprError();
1929 break;
1930 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1931 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1932 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1933 return ExprError();
1934 break;
1935 case Builtin::BI__builtin_os_log_format:
1936 Cleanup.setExprNeedsCleanups(true);
1937 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1938 case Builtin::BI__builtin_os_log_format_buffer_size:
1939 if (SemaBuiltinOSLogFormat(TheCall))
1940 return ExprError();
1941 break;
1942 case Builtin::BI__builtin_frame_address:
1943 case Builtin::BI__builtin_return_address: {
1944 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1945 return ExprError();
1946
1947 // -Wframe-address warning if non-zero passed to builtin
1948 // return/frame address.
1949 Expr::EvalResult Result;
1950 if (!TheCall->getArg(0)->isValueDependent() &&
1951 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1952 Result.Val.getInt() != 0)
1953 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1954 << ((BuiltinID == Builtin::BI__builtin_return_address)
1955 ? "__builtin_return_address"
1956 : "__builtin_frame_address")
1957 << TheCall->getSourceRange();
1958 break;
1959 }
1960
1961 case Builtin::BI__builtin_matrix_transpose:
1962 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1963
1964 case Builtin::BI__builtin_matrix_column_major_load:
1965 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1966
1967 case Builtin::BI__builtin_matrix_column_major_store:
1968 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1969
1970 case Builtin::BI__builtin_get_device_side_mangled_name: {
1971 auto Check = [](CallExpr *TheCall) {
1972 if (TheCall->getNumArgs() != 1)
1973 return false;
1974 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
1975 if (!DRE)
1976 return false;
1977 auto *D = DRE->getDecl();
1978 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
1979 return false;
1980 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
1981 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
1982 };
1983 if (!Check(TheCall)) {
1984 Diag(TheCall->getBeginLoc(),
1985 diag::err_hip_invalid_args_builtin_mangled_name);
1986 return ExprError();
1987 }
1988 }
1989 }
1990
1991 // Since the target specific builtins for each arch overlap, only check those
1992 // of the arch we are compiling for.
1993 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1994 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1995 assert(Context.getAuxTargetInfo() &&(static_cast <bool> (Context.getAuxTargetInfo() &&
"Aux Target Builtin, but not an aux target?") ? void (0) : __assert_fail
("Context.getAuxTargetInfo() && \"Aux Target Builtin, but not an aux target?\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 1996, __extension__ __PRETTY_FUNCTION__))
1996 "Aux Target Builtin, but not an aux target?")(static_cast <bool> (Context.getAuxTargetInfo() &&
"Aux Target Builtin, but not an aux target?") ? void (0) : __assert_fail
("Context.getAuxTargetInfo() && \"Aux Target Builtin, but not an aux target?\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 1996, __extension__ __PRETTY_FUNCTION__))
;
1997
1998 if (CheckTSBuiltinFunctionCall(
1999 *Context.getAuxTargetInfo(),
2000 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2001 return ExprError();
2002 } else {
2003 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2004 TheCall))
2005 return ExprError();
2006 }
2007 }
2008
2009 return TheCallResult;
2010}
2011
2012// Get the valid immediate range for the specified NEON type code.
2013static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2014 NeonTypeFlags Type(t);
2015 int IsQuad = ForceQuad ? true : Type.isQuad();
2016 switch (Type.getEltType()) {
2017 case NeonTypeFlags::Int8:
2018 case NeonTypeFlags::Poly8:
2019 return shift ? 7 : (8 << IsQuad) - 1;
2020 case NeonTypeFlags::Int16:
2021 case NeonTypeFlags::Poly16:
2022 return shift ? 15 : (4 << IsQuad) - 1;
2023 case NeonTypeFlags::Int32:
2024 return shift ? 31 : (2 << IsQuad) - 1;
2025 case NeonTypeFlags::Int64:
2026 case NeonTypeFlags::Poly64:
2027 return shift ? 63 : (1 << IsQuad) - 1;
2028 case NeonTypeFlags::Poly128:
2029 return shift ? 127 : (1 << IsQuad) - 1;
2030 case NeonTypeFlags::Float16:
2031 assert(!shift && "cannot shift float types!")(static_cast <bool> (!shift && "cannot shift float types!"
) ? void (0) : __assert_fail ("!shift && \"cannot shift float types!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2031, __extension__ __PRETTY_FUNCTION__))
;
2032 return (4 << IsQuad) - 1;
2033 case NeonTypeFlags::Float32:
2034 assert(!shift && "cannot shift float types!")(static_cast <bool> (!shift && "cannot shift float types!"
) ? void (0) : __assert_fail ("!shift && \"cannot shift float types!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2034, __extension__ __PRETTY_FUNCTION__))
;
2035 return (2 << IsQuad) - 1;
2036 case NeonTypeFlags::Float64:
2037 assert(!shift && "cannot shift float types!")(static_cast <bool> (!shift && "cannot shift float types!"
) ? void (0) : __assert_fail ("!shift && \"cannot shift float types!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2037, __extension__ __PRETTY_FUNCTION__))
;
2038 return (1 << IsQuad) - 1;
2039 case NeonTypeFlags::BFloat16:
2040 assert(!shift && "cannot shift float types!")(static_cast <bool> (!shift && "cannot shift float types!"
) ? void (0) : __assert_fail ("!shift && \"cannot shift float types!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2040, __extension__ __PRETTY_FUNCTION__))
;
2041 return (4 << IsQuad) - 1;
2042 }
2043 llvm_unreachable("Invalid NeonTypeFlag!")::llvm::llvm_unreachable_internal("Invalid NeonTypeFlag!", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2043)
;
2044}
2045
2046/// getNeonEltType - Return the QualType corresponding to the elements of
2047/// the vector type specified by the NeonTypeFlags. This is used to check
2048/// the pointer arguments for Neon load/store intrinsics.
2049static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2050 bool IsPolyUnsigned, bool IsInt64Long) {
2051 switch (Flags.getEltType()) {
2052 case NeonTypeFlags::Int8:
2053 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2054 case NeonTypeFlags::Int16:
2055 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2056 case NeonTypeFlags::Int32:
2057 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2058 case NeonTypeFlags::Int64:
2059 if (IsInt64Long)
2060 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2061 else
2062 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2063 : Context.LongLongTy;
2064 case NeonTypeFlags::Poly8:
2065 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2066 case NeonTypeFlags::Poly16:
2067 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2068 case NeonTypeFlags::Poly64:
2069 if (IsInt64Long)
2070 return Context.UnsignedLongTy;
2071 else
2072 return Context.UnsignedLongLongTy;
2073 case NeonTypeFlags::Poly128:
2074 break;
2075 case NeonTypeFlags::Float16:
2076 return Context.HalfTy;
2077 case NeonTypeFlags::Float32:
2078 return Context.FloatTy;
2079 case NeonTypeFlags::Float64:
2080 return Context.DoubleTy;
2081 case NeonTypeFlags::BFloat16:
2082 return Context.BFloat16Ty;
2083 }
2084 llvm_unreachable("Invalid NeonTypeFlag!")::llvm::llvm_unreachable_internal("Invalid NeonTypeFlag!", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2084)
;
2085}
2086
2087bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2088 // Range check SVE intrinsics that take immediate values.
2089 SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2090
2091 switch (BuiltinID) {
2092 default:
2093 return false;
2094#define GET_SVE_IMMEDIATE_CHECK
2095#include "clang/Basic/arm_sve_sema_rangechecks.inc"
2096#undef GET_SVE_IMMEDIATE_CHECK
2097 }
2098
2099 // Perform all the immediate checks for this builtin call.
2100 bool HasError = false;
2101 for (auto &I : ImmChecks) {
2102 int ArgNum, CheckTy, ElementSizeInBits;
2103 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2104
2105 typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2106
2107 // Function that checks whether the operand (ArgNum) is an immediate
2108 // that is one of the predefined values.
2109 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2110 int ErrDiag) -> bool {
2111 // We can't check the value of a dependent argument.
2112 Expr *Arg = TheCall->getArg(ArgNum);
2113 if (Arg->isTypeDependent() || Arg->isValueDependent())
2114 return false;
2115
2116 // Check constant-ness first.
2117 llvm::APSInt Imm;
2118 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2119 return true;
2120
2121 if (!CheckImm(Imm.getSExtValue()))
2122 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2123 return false;
2124 };
2125
2126 switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2127 case SVETypeFlags::ImmCheck0_31:
2128 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2129 HasError = true;
2130 break;
2131 case SVETypeFlags::ImmCheck0_13:
2132 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2133 HasError = true;
2134 break;
2135 case SVETypeFlags::ImmCheck1_16:
2136 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2137 HasError = true;
2138 break;
2139 case SVETypeFlags::ImmCheck0_7:
2140 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2141 HasError = true;
2142 break;
2143 case SVETypeFlags::ImmCheckExtract:
2144 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2145 (2048 / ElementSizeInBits) - 1))
2146 HasError = true;
2147 break;
2148 case SVETypeFlags::ImmCheckShiftRight:
2149 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2150 HasError = true;
2151 break;
2152 case SVETypeFlags::ImmCheckShiftRightNarrow:
2153 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2154 ElementSizeInBits / 2))
2155 HasError = true;
2156 break;
2157 case SVETypeFlags::ImmCheckShiftLeft:
2158 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2159 ElementSizeInBits - 1))
2160 HasError = true;
2161 break;
2162 case SVETypeFlags::ImmCheckLaneIndex:
2163 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2164 (128 / (1 * ElementSizeInBits)) - 1))
2165 HasError = true;
2166 break;
2167 case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2168 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2169 (128 / (2 * ElementSizeInBits)) - 1))
2170 HasError = true;
2171 break;
2172 case SVETypeFlags::ImmCheckLaneIndexDot:
2173 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2174 (128 / (4 * ElementSizeInBits)) - 1))
2175 HasError = true;
2176 break;
2177 case SVETypeFlags::ImmCheckComplexRot90_270:
2178 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2179 diag::err_rotation_argument_to_cadd))
2180 HasError = true;
2181 break;
2182 case SVETypeFlags::ImmCheckComplexRotAll90:
2183 if (CheckImmediateInSet(
2184 [](int64_t V) {
2185 return V == 0 || V == 90 || V == 180 || V == 270;
2186 },
2187 diag::err_rotation_argument_to_cmla))
2188 HasError = true;
2189 break;
2190 case SVETypeFlags::ImmCheck0_1:
2191 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2192 HasError = true;
2193 break;
2194 case SVETypeFlags::ImmCheck0_2:
2195 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2196 HasError = true;
2197 break;
2198 case SVETypeFlags::ImmCheck0_3:
2199 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2200 HasError = true;
2201 break;
2202 }
2203 }
2204
2205 return HasError;
2206}
2207
2208bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2209 unsigned BuiltinID, CallExpr *TheCall) {
2210 llvm::APSInt Result;
2211 uint64_t mask = 0;
2212 unsigned TV = 0;
2213 int PtrArgNum = -1;
2214 bool HasConstPtr = false;
2215 switch (BuiltinID) {
2216#define GET_NEON_OVERLOAD_CHECK
2217#include "clang/Basic/arm_neon.inc"
2218#include "clang/Basic/arm_fp16.inc"
2219#undef GET_NEON_OVERLOAD_CHECK
2220 }
2221
2222 // For NEON intrinsics which are overloaded on vector element type, validate
2223 // the immediate which specifies which variant to emit.
2224 unsigned ImmArg = TheCall->getNumArgs()-1;
2225 if (mask) {
2226 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2227 return true;
2228
2229 TV = Result.getLimitedValue(64);
2230 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2231 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2232 << TheCall->getArg(ImmArg)->getSourceRange();
2233 }
2234
2235 if (PtrArgNum >= 0) {
2236 // Check that pointer arguments have the specified type.
2237 Expr *Arg = TheCall->getArg(PtrArgNum);
2238 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2239 Arg = ICE->getSubExpr();
2240 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2241 QualType RHSTy = RHS.get()->getType();
2242
2243 llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2244 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2245 Arch == llvm::Triple::aarch64_32 ||
2246 Arch == llvm::Triple::aarch64_be;
2247 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2248 QualType EltTy =
2249 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2250 if (HasConstPtr)
2251 EltTy = EltTy.withConst();
2252 QualType LHSTy = Context.getPointerType(EltTy);
2253 AssignConvertType ConvTy;
2254 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2255 if (RHS.isInvalid())
2256 return true;
2257 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2258 RHS.get(), AA_Assigning))
2259 return true;
2260 }
2261
2262 // For NEON intrinsics which take an immediate value as part of the
2263 // instruction, range check them here.
2264 unsigned i = 0, l = 0, u = 0;
2265 switch (BuiltinID) {
2266 default:
2267 return false;
2268 #define GET_NEON_IMMEDIATE_CHECK
2269 #include "clang/Basic/arm_neon.inc"
2270 #include "clang/Basic/arm_fp16.inc"
2271 #undef GET_NEON_IMMEDIATE_CHECK
2272 }
2273
2274 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2275}
2276
2277bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2278 switch (BuiltinID) {
2279 default:
2280 return false;
2281 #include "clang/Basic/arm_mve_builtin_sema.inc"
2282 }
2283}
2284
2285bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2286 CallExpr *TheCall) {
2287 bool Err = false;
2288 switch (BuiltinID) {
2289 default:
2290 return false;
2291#include "clang/Basic/arm_cde_builtin_sema.inc"
2292 }
2293
2294 if (Err)
2295 return true;
2296
2297 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2298}
2299
2300bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2301 const Expr *CoprocArg, bool WantCDE) {
2302 if (isConstantEvaluated())
2303 return false;
2304
2305 // We can't check the value of a dependent argument.
2306 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2307 return false;
2308
2309 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2310 int64_t CoprocNo = CoprocNoAP.getExtValue();
2311 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative")(static_cast <bool> (CoprocNo >= 0 && "Coprocessor immediate must be non-negative"
) ? void (0) : __assert_fail ("CoprocNo >= 0 && \"Coprocessor immediate must be non-negative\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2311, __extension__ __PRETTY_FUNCTION__))
;
2312
2313 uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2314 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2315
2316 if (IsCDECoproc != WantCDE)
2317 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2318 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2319
2320 return false;
2321}
2322
2323bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2324 unsigned MaxWidth) {
2325 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||(static_cast <bool> ((BuiltinID == ARM::BI__builtin_arm_ldrex
|| BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM
::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex
|| BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID ==
AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex
|| BuiltinID == AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? void (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2333, __extension__ __PRETTY_FUNCTION__))
2326 BuiltinID == ARM::BI__builtin_arm_ldaex ||(static_cast <bool> ((BuiltinID == ARM::BI__builtin_arm_ldrex
|| BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM
::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex
|| BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID ==
AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex
|| BuiltinID == AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? void (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2333, __extension__ __PRETTY_FUNCTION__))
2327 BuiltinID == ARM::BI__builtin_arm_strex ||(static_cast <bool> ((BuiltinID == ARM::BI__builtin_arm_ldrex
|| BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM
::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex
|| BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID ==
AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex
|| BuiltinID == AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? void (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2333, __extension__ __PRETTY_FUNCTION__))
2328 BuiltinID == ARM::BI__builtin_arm_stlex ||(static_cast <bool> ((BuiltinID == ARM::BI__builtin_arm_ldrex
|| BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM
::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex
|| BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID ==
AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex
|| BuiltinID == AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? void (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2333, __extension__ __PRETTY_FUNCTION__))
2329 BuiltinID == AArch64::BI__builtin_arm_ldrex ||(static_cast <bool> ((BuiltinID == ARM::BI__builtin_arm_ldrex
|| BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM
::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex
|| BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID ==
AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex
|| BuiltinID == AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? void (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2333, __extension__ __PRETTY_FUNCTION__))
2330 BuiltinID == AArch64::BI__builtin_arm_ldaex ||(static_cast <bool> ((BuiltinID == ARM::BI__builtin_arm_ldrex
|| BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM
::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex
|| BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID ==
AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex
|| BuiltinID == AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? void (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2333, __extension__ __PRETTY_FUNCTION__))
2331 BuiltinID == AArch64::BI__builtin_arm_strex ||(static_cast <bool> ((BuiltinID == ARM::BI__builtin_arm_ldrex
|| BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM
::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex
|| BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID ==
AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex
|| BuiltinID == AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? void (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2333, __extension__ __PRETTY_FUNCTION__))
2332 BuiltinID == AArch64::BI__builtin_arm_stlex) &&(static_cast <bool> ((BuiltinID == ARM::BI__builtin_arm_ldrex
|| BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM
::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex
|| BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID ==
AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex
|| BuiltinID == AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? void (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2333, __extension__ __PRETTY_FUNCTION__))
2333 "unexpected ARM builtin")(static_cast <bool> ((BuiltinID == ARM::BI__builtin_arm_ldrex
|| BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM
::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex
|| BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID ==
AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex
|| BuiltinID == AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? void (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2333, __extension__ __PRETTY_FUNCTION__))
;
2334 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2335 BuiltinID == ARM::BI__builtin_arm_ldaex ||
2336 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2337 BuiltinID == AArch64::BI__builtin_arm_ldaex;
2338
2339 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2340
2341 // Ensure that we have the proper number of arguments.
2342 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2343 return true;
2344
2345 // Inspect the pointer argument of the atomic builtin. This should always be
2346 // a pointer type, whose element is an integral scalar or pointer type.
2347 // Because it is a pointer type, we don't have to worry about any implicit
2348 // casts here.
2349 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2350 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2351 if (PointerArgRes.isInvalid())
2352 return true;
2353 PointerArg = PointerArgRes.get();
2354
2355 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2356 if (!pointerType) {
2357 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2358 << PointerArg->getType() << PointerArg->getSourceRange();
2359 return true;
2360 }
2361
2362 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2363 // task is to insert the appropriate casts into the AST. First work out just
2364 // what the appropriate type is.
2365 QualType ValType = pointerType->getPointeeType();
2366 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2367 if (IsLdrex)
2368 AddrType.addConst();
2369
2370 // Issue a warning if the cast is dodgy.
2371 CastKind CastNeeded = CK_NoOp;
2372 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2373 CastNeeded = CK_BitCast;
2374 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2375 << PointerArg->getType() << Context.getPointerType(AddrType)
2376 << AA_Passing << PointerArg->getSourceRange();
2377 }
2378
2379 // Finally, do the cast and replace the argument with the corrected version.
2380 AddrType = Context.getPointerType(AddrType);
2381 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2382 if (PointerArgRes.isInvalid())
2383 return true;
2384 PointerArg = PointerArgRes.get();
2385
2386 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2387
2388 // In general, we allow ints, floats and pointers to be loaded and stored.
2389 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2390 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2391 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2392 << PointerArg->getType() << PointerArg->getSourceRange();
2393 return true;
2394 }
2395
2396 // But ARM doesn't have instructions to deal with 128-bit versions.
2397 if (Context.getTypeSize(ValType) > MaxWidth) {
2398 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate")(static_cast <bool> (MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"
) ? void (0) : __assert_fail ("MaxWidth == 64 && \"Diagnostic unexpectedly inaccurate\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2398, __extension__ __PRETTY_FUNCTION__))
;
2399 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2400 << PointerArg->getType() << PointerArg->getSourceRange();
2401 return true;
2402 }
2403
2404 switch (ValType.getObjCLifetime()) {
2405 case Qualifiers::OCL_None:
2406 case Qualifiers::OCL_ExplicitNone:
2407 // okay
2408 break;
2409
2410 case Qualifiers::OCL_Weak:
2411 case Qualifiers::OCL_Strong:
2412 case Qualifiers::OCL_Autoreleasing:
2413 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2414 << ValType << PointerArg->getSourceRange();
2415 return true;
2416 }
2417
2418 if (IsLdrex) {
2419 TheCall->setType(ValType);
2420 return false;
2421 }
2422
2423 // Initialize the argument to be stored.
2424 ExprResult ValArg = TheCall->getArg(0);
2425 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2426 Context, ValType, /*consume*/ false);
2427 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2428 if (ValArg.isInvalid())
2429 return true;
2430 TheCall->setArg(0, ValArg.get());
2431
2432 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2433 // but the custom checker bypasses all default analysis.
2434 TheCall->setType(Context.IntTy);
2435 return false;
2436}
2437
2438bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2439 CallExpr *TheCall) {
2440 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2441 BuiltinID == ARM::BI__builtin_arm_ldaex ||
2442 BuiltinID == ARM::BI__builtin_arm_strex ||
2443 BuiltinID == ARM::BI__builtin_arm_stlex) {
2444 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2445 }
2446
2447 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2448 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2449 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2450 }
2451
2452 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2453 BuiltinID == ARM::BI__builtin_arm_wsr64)
2454 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2455
2456 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2457 BuiltinID == ARM::BI__builtin_arm_rsrp ||
2458 BuiltinID == ARM::BI__builtin_arm_wsr ||
2459 BuiltinID == ARM::BI__builtin_arm_wsrp)
2460 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2461
2462 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2463 return true;
2464 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2465 return true;
2466 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2467 return true;
2468
2469 // For intrinsics which take an immediate value as part of the instruction,
2470 // range check them here.
2471 // FIXME: VFP Intrinsics should error if VFP not present.
2472 switch (BuiltinID) {
2473 default: return false;
2474 case ARM::BI__builtin_arm_ssat:
2475 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2476 case ARM::BI__builtin_arm_usat:
2477 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2478 case ARM::BI__builtin_arm_ssat16:
2479 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2480 case ARM::BI__builtin_arm_usat16:
2481 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2482 case ARM::BI__builtin_arm_vcvtr_f:
2483 case ARM::BI__builtin_arm_vcvtr_d:
2484 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2485 case ARM::BI__builtin_arm_dmb:
2486 case ARM::BI__builtin_arm_dsb:
2487 case ARM::BI__builtin_arm_isb:
2488 case ARM::BI__builtin_arm_dbg:
2489 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2490 case ARM::BI__builtin_arm_cdp:
2491 case ARM::BI__builtin_arm_cdp2:
2492 case ARM::BI__builtin_arm_mcr:
2493 case ARM::BI__builtin_arm_mcr2:
2494 case ARM::BI__builtin_arm_mrc:
2495 case ARM::BI__builtin_arm_mrc2:
2496 case ARM::BI__builtin_arm_mcrr:
2497 case ARM::BI__builtin_arm_mcrr2:
2498 case ARM::BI__builtin_arm_mrrc:
2499 case ARM::BI__builtin_arm_mrrc2:
2500 case ARM::BI__builtin_arm_ldc:
2501 case ARM::BI__builtin_arm_ldcl:
2502 case ARM::BI__builtin_arm_ldc2:
2503 case ARM::BI__builtin_arm_ldc2l:
2504 case ARM::BI__builtin_arm_stc:
2505 case ARM::BI__builtin_arm_stcl:
2506 case ARM::BI__builtin_arm_stc2:
2507 case ARM::BI__builtin_arm_stc2l:
2508 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2509 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2510 /*WantCDE*/ false);
2511 }
2512}
2513
2514bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2515 unsigned BuiltinID,
2516 CallExpr *TheCall) {
2517 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2518 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2519 BuiltinID == AArch64::BI__builtin_arm_strex ||
2520 BuiltinID == AArch64::BI__builtin_arm_stlex) {
2521 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2522 }
2523
2524 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2525 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2526 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2527 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2528 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2529 }
2530
2531 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2532 BuiltinID == AArch64::BI__builtin_arm_wsr64)
2533 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2534
2535 // Memory Tagging Extensions (MTE) Intrinsics
2536 if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2537 BuiltinID == AArch64::BI__builtin_arm_addg ||
2538 BuiltinID == AArch64::BI__builtin_arm_gmi ||
2539 BuiltinID == AArch64::BI__builtin_arm_ldg ||
2540 BuiltinID == AArch64::BI__builtin_arm_stg ||
2541 BuiltinID == AArch64::BI__builtin_arm_subp) {
2542 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2543 }
2544
2545 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2546 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2547 BuiltinID == AArch64::BI__builtin_arm_wsr ||
2548 BuiltinID == AArch64::BI__builtin_arm_wsrp)
2549 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2550
2551 // Only check the valid encoding range. Any constant in this range would be
2552 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2553 // an exception for incorrect registers. This matches MSVC behavior.
2554 if (BuiltinID == AArch64::BI_ReadStatusReg ||
2555 BuiltinID == AArch64::BI_WriteStatusReg)
2556 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2557
2558 if (BuiltinID == AArch64::BI__getReg)
2559 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2560
2561 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2562 return true;
2563
2564 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2565 return true;
2566
2567 // For intrinsics which take an immediate value as part of the instruction,
2568 // range check them here.
2569 unsigned i = 0, l = 0, u = 0;
2570 switch (BuiltinID) {
2571 default: return false;
2572 case AArch64::BI__builtin_arm_dmb:
2573 case AArch64::BI__builtin_arm_dsb:
2574 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2575 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2576 }
2577
2578 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2579}
2580
2581static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2582 if (Arg->getType()->getAsPlaceholderType())
2583 return false;
2584
2585 // The first argument needs to be a record field access.
2586 // If it is an array element access, we delay decision
2587 // to BPF backend to check whether the access is a
2588 // field access or not.
2589 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2590 dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2591 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2592}
2593
2594static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2595 QualType VectorTy, QualType EltTy) {
2596 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2597 if (!Context.hasSameType(VectorEltTy, EltTy)) {
2598 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2599 << Call->getSourceRange() << VectorEltTy << EltTy;
2600 return false;
2601 }
2602 return true;
2603}
2604
2605static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2606 QualType ArgType = Arg->getType();
2607 if (ArgType->getAsPlaceholderType())
2608 return false;
2609
2610 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2611 // format:
2612 // 1. __builtin_preserve_type_info(*(<type> *)0, flag);
2613 // 2. <type> var;
2614 // __builtin_preserve_type_info(var, flag);
2615 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2616 !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2617 return false;
2618
2619 // Typedef type.
2620 if (ArgType->getAs<TypedefType>())
2621 return true;
2622
2623 // Record type or Enum type.
2624 const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2625 if (const auto *RT = Ty->getAs<RecordType>()) {
2626 if (!RT->getDecl()->getDeclName().isEmpty())
2627 return true;
2628 } else if (const auto *ET = Ty->getAs<EnumType>()) {
2629 if (!ET->getDecl()->getDeclName().isEmpty())
2630 return true;
2631 }
2632
2633 return false;
2634}
2635
2636static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2637 QualType ArgType = Arg->getType();
2638 if (ArgType->getAsPlaceholderType())
2639 return false;
2640
2641 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2642 // format:
2643 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2644 // flag);
2645 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2646 if (!UO)
2647 return false;
2648
2649 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2650 if (!CE)
2651 return false;
2652 if (CE->getCastKind() != CK_IntegralToPointer &&
2653 CE->getCastKind() != CK_NullToPointer)
2654 return false;
2655
2656 // The integer must be from an EnumConstantDecl.
2657 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2658 if (!DR)
2659 return false;
2660
2661 const EnumConstantDecl *Enumerator =
2662 dyn_cast<EnumConstantDecl>(DR->getDecl());
2663 if (!Enumerator)
2664 return false;
2665
2666 // The type must be EnumType.
2667 const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2668 const auto *ET = Ty->getAs<EnumType>();
2669 if (!ET)
2670 return false;
2671
2672 // The enum value must be supported.
2673 for (auto *EDI : ET->getDecl()->enumerators()) {
2674 if (EDI == Enumerator)
2675 return true;
2676 }
2677
2678 return false;
2679}
2680
2681bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2682 CallExpr *TheCall) {
2683 assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||(static_cast <bool> ((BuiltinID == BPF::BI__builtin_preserve_field_info
|| BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID ==
BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value
) && "unexpected BPF builtin") ? void (0) : __assert_fail
("(BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && \"unexpected BPF builtin\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2687, __extension__ __PRETTY_FUNCTION__))
2684 BuiltinID == BPF::BI__builtin_btf_type_id ||(static_cast <bool> ((BuiltinID == BPF::BI__builtin_preserve_field_info
|| BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID ==
BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value
) && "unexpected BPF builtin") ? void (0) : __assert_fail
("(BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && \"unexpected BPF builtin\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2687, __extension__ __PRETTY_FUNCTION__))
2685 BuiltinID == BPF::BI__builtin_preserve_type_info ||(static_cast <bool> ((BuiltinID == BPF::BI__builtin_preserve_field_info
|| BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID ==
BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value
) && "unexpected BPF builtin") ? void (0) : __assert_fail
("(BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && \"unexpected BPF builtin\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2687, __extension__ __PRETTY_FUNCTION__))
2686 BuiltinID == BPF::BI__builtin_preserve_enum_value) &&(static_cast <bool> ((BuiltinID == BPF::BI__builtin_preserve_field_info
|| BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID ==
BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value
) && "unexpected BPF builtin") ? void (0) : __assert_fail
("(BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && \"unexpected BPF builtin\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2687, __extension__ __PRETTY_FUNCTION__))
2687 "unexpected BPF builtin")(static_cast <bool> ((BuiltinID == BPF::BI__builtin_preserve_field_info
|| BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID ==
BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value
) && "unexpected BPF builtin") ? void (0) : __assert_fail
("(BuiltinID == BPF::BI__builtin_preserve_field_info || BuiltinID == BPF::BI__builtin_btf_type_id || BuiltinID == BPF::BI__builtin_preserve_type_info || BuiltinID == BPF::BI__builtin_preserve_enum_value) && \"unexpected BPF builtin\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 2687, __extension__ __PRETTY_FUNCTION__))
;
2688
2689 if (checkArgCount(*this, TheCall, 2))
2690 return true;
2691
2692 // The second argument needs to be a constant int
2693 Expr *Arg = TheCall->getArg(1);
2694 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2695 diag::kind kind;
2696 if (!Value) {
2697 if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2698 kind = diag::err_preserve_field_info_not_const;
2699 else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2700 kind = diag::err_btf_type_id_not_const;
2701 else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2702 kind = diag::err_preserve_type_info_not_const;
2703 else
2704 kind = diag::err_preserve_enum_value_not_const;
2705 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2706 return true;
2707 }
2708
2709 // The first argument
2710 Arg = TheCall->getArg(0);
2711 bool InvalidArg = false;
2712 bool ReturnUnsignedInt = true;
2713 if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2714 if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2715 InvalidArg = true;
2716 kind = diag::err_preserve_field_info_not_field;
2717 }
2718 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2719 if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2720 InvalidArg = true;
2721 kind = diag::err_preserve_type_info_invalid;
2722 }
2723 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2724 if (!isValidBPFPreserveEnumValueArg(Arg)) {
2725 InvalidArg = true;
2726 kind = diag::err_preserve_enum_value_invalid;
2727 }
2728 ReturnUnsignedInt = false;
2729 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2730 ReturnUnsignedInt = false;
2731 }
2732
2733 if (InvalidArg) {
2734 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2735 return true;
2736 }
2737
2738 if (ReturnUnsignedInt)
2739 TheCall->setType(Context.UnsignedIntTy);
2740 else
2741 TheCall->setType(Context.UnsignedLongTy);
2742 return false;
2743}
2744
2745bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2746 struct ArgInfo {
2747 uint8_t OpNum;
2748 bool IsSigned;
2749 uint8_t BitWidth;
2750 uint8_t Align;
2751 };
2752 struct BuiltinInfo {
2753 unsigned BuiltinID;
2754 ArgInfo Infos[2];
2755 };
2756
2757 static BuiltinInfo Infos[] = {
2758 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
2759 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
2760 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
2761 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} },
2762 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
2763 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
2764 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
2765 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
2766 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
2767 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
2768 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
2769
2770 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
2771 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
2772 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
2773 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
2774 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
2775 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
2776 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
2777 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
2778 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
2779 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
2780 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
2781
2782 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
2783 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
2784 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
2785 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
2786 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
2787 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
2788 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
2789 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
2790 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
2791 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
2792 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
2793 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
2794 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
2795 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
2796 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
2797 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
2798 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
2799 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
2800 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
2801 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
2802 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
2803 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
2804 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
2805 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
2806 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
2807 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
2808 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
2809 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
2810 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
2811 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
2812 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
2813 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
2814 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
2815 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
2816 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
2817 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
2818 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
2819 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
2820 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
2821 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
2822 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
2823 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
2824 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
2825 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
2826 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
2827 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
2828 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
2829 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
2830 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
2831 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
2832 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
2833 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2834 {{ 1, false, 6, 0 }} },
2835 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
2836 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
2837 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
2838 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
2839 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
2840 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
2841 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2842 {{ 1, false, 5, 0 }} },
2843 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
2844 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
2845 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
2846 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
2847 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
2848 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
2849 { 2, false, 5, 0 }} },
2850 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
2851 { 2, false, 6, 0 }} },
2852 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
2853 { 3, false, 5, 0 }} },
2854 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
2855 { 3, false, 6, 0 }} },
2856 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
2857 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
2858 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
2859 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
2860 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
2861 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
2862 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
2863 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
2864 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
2865 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
2866 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
2867 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
2868 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
2869 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
2870 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
2871 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2872 {{ 2, false, 4, 0 },
2873 { 3, false, 5, 0 }} },
2874 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2875 {{ 2, false, 4, 0 },
2876 { 3, false, 5, 0 }} },
2877 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2878 {{ 2, false, 4, 0 },
2879 { 3, false, 5, 0 }} },
2880 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2881 {{ 2, false, 4, 0 },
2882 { 3, false, 5, 0 }} },
2883 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
2884 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
2885 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
2886 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
2887 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
2888 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
2889 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
2890 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
2891 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
2892 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
2893 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
2894 { 2, false, 5, 0 }} },
2895 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
2896 { 2, false, 6, 0 }} },
2897 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
2898 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
2899 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
2900 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
2901 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
2902 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
2903 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
2904 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
2905 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2906 {{ 1, false, 4, 0 }} },
2907 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
2908 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2909 {{ 1, false, 4, 0 }} },
2910 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
2911 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
2912 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
2913 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
2914 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
2915 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
2916 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
2917 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
2918 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
2919 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
2920 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
2921 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
2922 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
2923 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
2924 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
2925 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
2926 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
2927 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
2928 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
2929 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2930 {{ 3, false, 1, 0 }} },
2931 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
2932 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
2933 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
2934 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2935 {{ 3, false, 1, 0 }} },
2936 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
2937 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
2938 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
2939 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2940 {{ 3, false, 1, 0 }} },
2941 };
2942
2943 // Use a dynamically initialized static to sort the table exactly once on
2944 // first run.
2945 static const bool SortOnce =
2946 (llvm::sort(Infos,
2947 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2948 return LHS.BuiltinID < RHS.BuiltinID;
2949 }),
2950 true);
2951 (void)SortOnce;
2952
2953 const BuiltinInfo *F = llvm::partition_point(
2954 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2955 if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2956 return false;
2957
2958 bool Error = false;
2959
2960 for (const ArgInfo &A : F->Infos) {
2961 // Ignore empty ArgInfo elements.
2962 if (A.BitWidth == 0)
2963 continue;
2964
2965 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2966 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2967 if (!A.Align) {
2968 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2969 } else {
2970 unsigned M = 1 << A.Align;
2971 Min *= M;
2972 Max *= M;
2973 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2974 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2975 }
2976 }
2977 return Error;
2978}
2979
2980bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2981 CallExpr *TheCall) {
2982 return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2983}
2984
2985bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2986 unsigned BuiltinID, CallExpr *TheCall) {
2987 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2988 CheckMipsBuiltinArgument(BuiltinID, TheCall);
2989}
2990
2991bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2992 CallExpr *TheCall) {
2993
2994 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2995 BuiltinID <= Mips::BI__builtin_mips_lwx) {
2996 if (!TI.hasFeature("dsp"))
2997 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2998 }
2999
3000 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3001 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3002 if (!TI.hasFeature("dspr2"))
3003 return Diag(TheCall->getBeginLoc(),
3004 diag::err_mips_builtin_requires_dspr2);
3005 }
3006
3007 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3008 BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3009 if (!TI.hasFeature("msa"))
3010 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3011 }
3012
3013 return false;
3014}
3015
3016// CheckMipsBuiltinArgument - Checks the constant value passed to the
3017// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3018// ordering for DSP is unspecified. MSA is ordered by the data format used
3019// by the underlying instruction i.e., df/m, df/n and then by size.
3020//
3021// FIXME: The size tests here should instead be tablegen'd along with the
3022// definitions from include/clang/Basic/BuiltinsMips.def.
3023// FIXME: GCC is strict on signedness for some of these intrinsics, we should
3024// be too.
3025bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3026 unsigned i = 0, l = 0, u = 0, m = 0;
3027 switch (BuiltinID) {
3028 default: return false;
3029 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3030 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3031 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3032 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3033 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3034 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3035 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3036 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3037 // df/m field.
3038 // These intrinsics take an unsigned 3 bit immediate.
3039 case Mips::BI__builtin_msa_bclri_b:
3040 case Mips::BI__builtin_msa_bnegi_b:
3041 case Mips::BI__builtin_msa_bseti_b:
3042 case Mips::BI__builtin_msa_sat_s_b:
3043 case Mips::BI__builtin_msa_sat_u_b:
3044 case Mips::BI__builtin_msa_slli_b:
3045 case Mips::BI__builtin_msa_srai_b:
3046 case Mips::BI__builtin_msa_srari_b:
3047 case Mips::BI__builtin_msa_srli_b:
3048 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3049 case Mips::BI__builtin_msa_binsli_b:
3050 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3051 // These intrinsics take an unsigned 4 bit immediate.
3052 case Mips::BI__builtin_msa_bclri_h:
3053 case Mips::BI__builtin_msa_bnegi_h:
3054 case Mips::BI__builtin_msa_bseti_h:
3055 case Mips::BI__builtin_msa_sat_s_h:
3056 case Mips::BI__builtin_msa_sat_u_h:
3057 case Mips::BI__builtin_msa_slli_h:
3058 case Mips::BI__builtin_msa_srai_h:
3059 case Mips::BI__builtin_msa_srari_h:
3060 case Mips::BI__builtin_msa_srli_h:
3061 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3062 case Mips::BI__builtin_msa_binsli_h:
3063 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3064 // These intrinsics take an unsigned 5 bit immediate.
3065 // The first block of intrinsics actually have an unsigned 5 bit field,
3066 // not a df/n field.
3067 case Mips::BI__builtin_msa_cfcmsa:
3068 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3069 case Mips::BI__builtin_msa_clei_u_b:
3070 case Mips::BI__builtin_msa_clei_u_h:
3071 case Mips::BI__builtin_msa_clei_u_w:
3072 case Mips::BI__builtin_msa_clei_u_d:
3073 case Mips::BI__builtin_msa_clti_u_b:
3074 case Mips::BI__builtin_msa_clti_u_h:
3075 case Mips::BI__builtin_msa_clti_u_w:
3076 case Mips::BI__builtin_msa_clti_u_d:
3077 case Mips::BI__builtin_msa_maxi_u_b:
3078 case Mips::BI__builtin_msa_maxi_u_h:
3079 case Mips::BI__builtin_msa_maxi_u_w:
3080 case Mips::BI__builtin_msa_maxi_u_d:
3081 case Mips::BI__builtin_msa_mini_u_b:
3082 case Mips::BI__builtin_msa_mini_u_h:
3083 case Mips::BI__builtin_msa_mini_u_w:
3084 case Mips::BI__builtin_msa_mini_u_d:
3085 case Mips::BI__builtin_msa_addvi_b:
3086 case Mips::BI__builtin_msa_addvi_h:
3087 case Mips::BI__builtin_msa_addvi_w:
3088 case Mips::BI__builtin_msa_addvi_d:
3089 case Mips::BI__builtin_msa_bclri_w:
3090 case Mips::BI__builtin_msa_bnegi_w:
3091 case Mips::BI__builtin_msa_bseti_w:
3092 case Mips::BI__builtin_msa_sat_s_w:
3093 case Mips::BI__builtin_msa_sat_u_w:
3094 case Mips::BI__builtin_msa_slli_w:
3095 case Mips::BI__builtin_msa_srai_w:
3096 case Mips::BI__builtin_msa_srari_w:
3097 case Mips::BI__builtin_msa_srli_w:
3098 case Mips::BI__builtin_msa_srlri_w:
3099 case Mips::BI__builtin_msa_subvi_b:
3100 case Mips::BI__builtin_msa_subvi_h:
3101 case Mips::BI__builtin_msa_subvi_w:
3102 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3103 case Mips::BI__builtin_msa_binsli_w:
3104 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3105 // These intrinsics take an unsigned 6 bit immediate.
3106 case Mips::BI__builtin_msa_bclri_d:
3107 case Mips::BI__builtin_msa_bnegi_d:
3108 case Mips::BI__builtin_msa_bseti_d:
3109 case Mips::BI__builtin_msa_sat_s_d:
3110 case Mips::BI__builtin_msa_sat_u_d:
3111 case Mips::BI__builtin_msa_slli_d:
3112 case Mips::BI__builtin_msa_srai_d:
3113 case Mips::BI__builtin_msa_srari_d:
3114 case Mips::BI__builtin_msa_srli_d:
3115 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3116 case Mips::BI__builtin_msa_binsli_d:
3117 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3118 // These intrinsics take a signed 5 bit immediate.
3119 case Mips::BI__builtin_msa_ceqi_b:
3120 case Mips::BI__builtin_msa_ceqi_h:
3121 case Mips::BI__builtin_msa_ceqi_w:
3122 case Mips::BI__builtin_msa_ceqi_d:
3123 case Mips::BI__builtin_msa_clti_s_b:
3124 case Mips::BI__builtin_msa_clti_s_h:
3125 case Mips::BI__builtin_msa_clti_s_w:
3126 case Mips::BI__builtin_msa_clti_s_d:
3127 case Mips::BI__builtin_msa_clei_s_b:
3128 case Mips::BI__builtin_msa_clei_s_h:
3129 case Mips::BI__builtin_msa_clei_s_w:
3130 case Mips::BI__builtin_msa_clei_s_d:
3131 case Mips::BI__builtin_msa_maxi_s_b:
3132 case Mips::BI__builtin_msa_maxi_s_h:
3133 case Mips::BI__builtin_msa_maxi_s_w:
3134 case Mips::BI__builtin_msa_maxi_s_d:
3135 case Mips::BI__builtin_msa_mini_s_b:
3136 case Mips::BI__builtin_msa_mini_s_h:
3137 case Mips::BI__builtin_msa_mini_s_w:
3138 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3139 // These intrinsics take an unsigned 8 bit immediate.
3140 case Mips::BI__builtin_msa_andi_b:
3141 case Mips::BI__builtin_msa_nori_b:
3142 case Mips::BI__builtin_msa_ori_b:
3143 case Mips::BI__builtin_msa_shf_b:
3144 case Mips::BI__builtin_msa_shf_h:
3145 case Mips::BI__builtin_msa_shf_w:
3146 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3147 case Mips::BI__builtin_msa_bseli_b:
3148 case Mips::BI__builtin_msa_bmnzi_b:
3149 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3150 // df/n format
3151 // These intrinsics take an unsigned 4 bit immediate.
3152 case Mips::BI__builtin_msa_copy_s_b:
3153 case Mips::BI__builtin_msa_copy_u_b:
3154 case Mips::BI__builtin_msa_insve_b:
3155 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3156 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3157 // These intrinsics take an unsigned 3 bit immediate.
3158 case Mips::BI__builtin_msa_copy_s_h:
3159 case Mips::BI__builtin_msa_copy_u_h:
3160 case Mips::BI__builtin_msa_insve_h:
3161 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3162 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3163 // These intrinsics take an unsigned 2 bit immediate.
3164 case Mips::BI__builtin_msa_copy_s_w:
3165 case Mips::BI__builtin_msa_copy_u_w:
3166 case Mips::BI__builtin_msa_insve_w:
3167 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3168 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3169 // These intrinsics take an unsigned 1 bit immediate.
3170 case Mips::BI__builtin_msa_copy_s_d:
3171 case Mips::BI__builtin_msa_copy_u_d:
3172 case Mips::BI__builtin_msa_insve_d:
3173 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3174 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3175 // Memory offsets and immediate loads.
3176 // These intrinsics take a signed 10 bit immediate.
3177 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3178 case Mips::BI__builtin_msa_ldi_h:
3179 case Mips::BI__builtin_msa_ldi_w:
3180 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3181 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3182 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3183 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3184 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3185 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3186 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3187 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3188 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3189 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3190 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3191 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3192 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3193 }
3194
3195 if (!m)
3196 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3197
3198 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3199 SemaBuiltinConstantArgMultiple(TheCall, i, m);
3200}
3201
3202/// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3203/// advancing the pointer over the consumed characters. The decoded type is
3204/// returned. If the decoded type represents a constant integer with a
3205/// constraint on its value then Mask is set to that value. The type descriptors
3206/// used in Str are specific to PPC MMA builtins and are documented in the file
3207/// defining the PPC builtins.
3208static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3209 unsigned &Mask) {
3210 bool RequireICE = false;
3211 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3212 switch (*Str++) {
3213 case 'V':
3214 return Context.getVectorType(Context.UnsignedCharTy, 16,
3215 VectorType::VectorKind::AltiVecVector);
3216 case 'i': {
3217 char *End;
3218 unsigned size = strtoul(Str, &End, 10);
3219 assert(End != Str && "Missing constant parameter constraint")(static_cast <bool> (End != Str && "Missing constant parameter constraint"
) ? void (0) : __assert_fail ("End != Str && \"Missing constant parameter constraint\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 3219, __extension__ __PRETTY_FUNCTION__))
;
3220 Str = End;
3221 Mask = size;
3222 return Context.IntTy;
3223 }
3224 case 'W': {
3225 char *End;
3226 unsigned size = strtoul(Str, &End, 10);
3227 assert(End != Str && "Missing PowerPC MMA type size")(static_cast <bool> (End != Str && "Missing PowerPC MMA type size"
) ? void (0) : __assert_fail ("End != Str && \"Missing PowerPC MMA type size\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 3227, __extension__ __PRETTY_FUNCTION__))
;
3228 Str = End;
3229 QualType Type;
3230 switch (size) {
3231 #define PPC_VECTOR_TYPE(typeName, Id, size) \
3232 case size: Type = Context.Id##Ty; break;
3233 #include "clang/Basic/PPCTypes.def"
3234 default: llvm_unreachable("Invalid PowerPC MMA vector type")::llvm::llvm_unreachable_internal("Invalid PowerPC MMA vector type"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 3234)
;
3235 }
3236 bool CheckVectorArgs = false;
3237 while (!CheckVectorArgs) {
3238 switch (*Str++) {
3239 case '*':
3240 Type = Context.getPointerType(Type);
3241 break;
3242 case 'C':
3243 Type = Type.withConst();
3244 break;
3245 default:
3246 CheckVectorArgs = true;
3247 --Str;
3248 break;
3249 }
3250 }
3251 return Type;
3252 }
3253 default:
3254 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3255 }
3256}
3257
3258bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3259 CallExpr *TheCall) {
3260 unsigned i = 0, l = 0, u = 0;
3261 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3262 BuiltinID == PPC::BI__builtin_divdeu ||
3263 BuiltinID == PPC::BI__builtin_bpermd;
3264 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3265 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3266 BuiltinID == PPC::BI__builtin_divweu ||
3267 BuiltinID == PPC::BI__builtin_divde ||
3268 BuiltinID == PPC::BI__builtin_divdeu;
3269
3270 if (Is64BitBltin && !IsTarget64Bit)
3271 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3272 << TheCall->getSourceRange();
3273
3274 if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3275 (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3276 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3277 << TheCall->getSourceRange();
3278
3279 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3280 if (!TI.hasFeature("vsx"))
3281 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3282 << TheCall->getSourceRange();
3283 return false;
3284 };
3285
3286 switch (BuiltinID) {
3287 default: return false;
3288 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3289 case PPC::BI__builtin_altivec_crypto_vshasigmad:
3290 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3291 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3292 case PPC::BI__builtin_altivec_dss:
3293 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3294 case PPC::BI__builtin_tbegin:
3295 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3296 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3297 case PPC::BI__builtin_tabortwc:
3298 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3299 case PPC::BI__builtin_tabortwci:
3300 case PPC::BI__builtin_tabortdci:
3301 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3302 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3303 case PPC::BI__builtin_altivec_dst:
3304 case PPC::BI__builtin_altivec_dstt:
3305 case PPC::BI__builtin_altivec_dstst:
3306 case PPC::BI__builtin_altivec_dststt:
3307 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3308 case PPC::BI__builtin_vsx_xxpermdi:
3309 case PPC::BI__builtin_vsx_xxsldwi:
3310 return SemaBuiltinVSX(TheCall);
3311 case PPC::BI__builtin_unpack_vector_int128:
3312 return SemaVSXCheck(TheCall) ||
3313 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3314 case PPC::BI__builtin_pack_vector_int128:
3315 return SemaVSXCheck(TheCall);
3316 case PPC::BI__builtin_altivec_vgnb:
3317 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3318 case PPC::BI__builtin_altivec_vec_replace_elt:
3319 case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3320 QualType VecTy = TheCall->getArg(0)->getType();
3321 QualType EltTy = TheCall->getArg(1)->getType();
3322 unsigned Width = Context.getIntWidth(EltTy);
3323 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3324 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3325 }
3326 case PPC::BI__builtin_vsx_xxeval:
3327 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3328 case PPC::BI__builtin_altivec_vsldbi:
3329 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3330 case PPC::BI__builtin_altivec_vsrdbi:
3331 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3332 case PPC::BI__builtin_vsx_xxpermx:
3333 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3334#define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \
3335 case PPC::BI__builtin_##Name: \
3336 return SemaBuiltinPPCMMACall(TheCall, Types);
3337#include "clang/Basic/BuiltinsPPC.def"
3338 }
3339 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3340}
3341
3342// Check if the given type is a non-pointer PPC MMA type. This function is used
3343// in Sema to prevent invalid uses of restricted PPC MMA types.
3344bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3345 if (Type->isPointerType() || Type->isArrayType())
3346 return false;
3347
3348 QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3349#define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3350 if (false
3351#include "clang/Basic/PPCTypes.def"
3352 ) {
3353 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3354 return true;
3355 }
3356 return false;
3357}
3358
3359bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3360 CallExpr *TheCall) {
3361 // position of memory order and scope arguments in the builtin
3362 unsigned OrderIndex, ScopeIndex;
3363 switch (BuiltinID) {
3364 case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3365 case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3366 case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3367 case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3368 OrderIndex = 2;
3369 ScopeIndex = 3;
3370 break;
3371 case AMDGPU::BI__builtin_amdgcn_fence:
3372 OrderIndex = 0;
3373 ScopeIndex = 1;
3374 break;
3375 default:
3376 return false;
3377 }
3378
3379 ExprResult Arg = TheCall->getArg(OrderIndex);
3380 auto ArgExpr = Arg.get();
3381 Expr::EvalResult ArgResult;
3382
3383 if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3384 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3385 << ArgExpr->getType();
3386 auto Ord = ArgResult.Val.getInt().getZExtValue();
3387
3388 // Check valididty of memory ordering as per C11 / C++11's memody model.
3389 // Only fence needs check. Atomic dec/inc allow all memory orders.
3390 if (!llvm::isValidAtomicOrderingCABI(Ord))
3391 return Diag(ArgExpr->getBeginLoc(),
3392 diag::warn_atomic_op_has_invalid_memory_order)
3393 << ArgExpr->getSourceRange();
3394 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3395 case llvm::AtomicOrderingCABI::relaxed:
3396 case llvm::AtomicOrderingCABI::consume:
3397 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3398 return Diag(ArgExpr->getBeginLoc(),
3399 diag::warn_atomic_op_has_invalid_memory_order)
3400 << ArgExpr->getSourceRange();
3401 break;
3402 case llvm::AtomicOrderingCABI::acquire:
3403 case llvm::AtomicOrderingCABI::release:
3404 case llvm::AtomicOrderingCABI::acq_rel:
3405 case llvm::AtomicOrderingCABI::seq_cst:
3406 break;
3407 }
3408
3409 Arg = TheCall->getArg(ScopeIndex);
3410 ArgExpr = Arg.get();
3411 Expr::EvalResult ArgResult1;
3412 // Check that sync scope is a constant literal
3413 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3414 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3415 << ArgExpr->getType();
3416
3417 return false;
3418}
3419
3420bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3421 llvm::APSInt Result;
3422
3423 // We can't check the value of a dependent argument.
3424 Expr *Arg = TheCall->getArg(ArgNum);
3425 if (Arg->isTypeDependent() || Arg->isValueDependent())
3426 return false;
3427
3428 // Check constant-ness first.
3429 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3430 return true;
3431
3432 int64_t Val = Result.getSExtValue();
3433 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3434 return false;
3435
3436 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3437 << Arg->getSourceRange();
3438}
3439
3440bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3441 unsigned BuiltinID,
3442 CallExpr *TheCall) {
3443 // CodeGenFunction can also detect this, but this gives a better error
3444 // message.
3445 bool FeatureMissing = false;
3446 SmallVector<StringRef> ReqFeatures;
3447 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3448 Features.split(ReqFeatures, ',');
3449
3450 // Check if each required feature is included
3451 for (StringRef F : ReqFeatures) {
3452 if (TI.hasFeature(F))
3453 continue;
3454
3455 // If the feature is 64bit, alter the string so it will print better in
3456 // the diagnostic.
3457 if (F == "64bit")
3458 F = "RV64";
3459
3460 // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3461 F.consume_front("experimental-");
3462 std::string FeatureStr = F.str();
3463 FeatureStr[0] = std::toupper(FeatureStr[0]);
3464
3465 // Error message
3466 FeatureMissing = true;
3467 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3468 << TheCall->getSourceRange() << StringRef(FeatureStr);
3469 }
3470
3471 if (FeatureMissing)
3472 return true;
3473
3474 switch (BuiltinID) {
3475 case RISCV::BI__builtin_rvv_vsetvli:
3476 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3477 CheckRISCVLMUL(TheCall, 2);
3478 case RISCV::BI__builtin_rvv_vsetvlimax:
3479 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3480 CheckRISCVLMUL(TheCall, 1);
3481 }
3482
3483 return false;
3484}
3485
3486bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3487 CallExpr *TheCall) {
3488 if (BuiltinID == SystemZ::BI__builtin_tabort) {
3489 Expr *Arg = TheCall->getArg(0);
3490 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3491 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3492 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3493 << Arg->getSourceRange();
3494 }
3495
3496 // For intrinsics which take an immediate value as part of the instruction,
3497 // range check them here.
3498 unsigned i = 0, l = 0, u = 0;
3499 switch (BuiltinID) {
3500 default: return false;
3501 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3502 case SystemZ::BI__builtin_s390_verimb:
3503 case SystemZ::BI__builtin_s390_verimh:
3504 case SystemZ::BI__builtin_s390_verimf:
3505 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3506 case SystemZ::BI__builtin_s390_vfaeb:
3507 case SystemZ::BI__builtin_s390_vfaeh:
3508 case SystemZ::BI__builtin_s390_vfaef:
3509 case SystemZ::BI__builtin_s390_vfaebs:
3510 case SystemZ::BI__builtin_s390_vfaehs:
3511 case SystemZ::BI__builtin_s390_vfaefs:
3512 case SystemZ::BI__builtin_s390_vfaezb:
3513 case SystemZ::BI__builtin_s390_vfaezh:
3514 case SystemZ::BI__builtin_s390_vfaezf:
3515 case SystemZ::BI__builtin_s390_vfaezbs:
3516 case SystemZ::BI__builtin_s390_vfaezhs:
3517 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3518 case SystemZ::BI__builtin_s390_vfisb:
3519 case SystemZ::BI__builtin_s390_vfidb:
3520 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3521 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3522 case SystemZ::BI__builtin_s390_vftcisb:
3523 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3524 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3525 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3526 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3527 case SystemZ::BI__builtin_s390_vstrcb:
3528 case SystemZ::BI__builtin_s390_vstrch:
3529 case SystemZ::BI__builtin_s390_vstrcf:
3530 case SystemZ::BI__builtin_s390_vstrczb:
3531 case SystemZ::BI__builtin_s390_vstrczh:
3532 case SystemZ::BI__builtin_s390_vstrczf:
3533 case SystemZ::BI__builtin_s390_vstrcbs:
3534 case SystemZ::BI__builtin_s390_vstrchs:
3535 case SystemZ::BI__builtin_s390_vstrcfs:
3536 case SystemZ::BI__builtin_s390_vstrczbs:
3537 case SystemZ::BI__builtin_s390_vstrczhs:
3538 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3539 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3540 case SystemZ::BI__builtin_s390_vfminsb:
3541 case SystemZ::BI__builtin_s390_vfmaxsb:
3542 case SystemZ::BI__builtin_s390_vfmindb:
3543 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3544 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3545 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3546 }
3547 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3548}
3549
3550/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3551/// This checks that the target supports __builtin_cpu_supports and
3552/// that the string argument is constant and valid.
3553static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3554 CallExpr *TheCall) {
3555 Expr *Arg = TheCall->getArg(0);
3556
3557 // Check if the argument is a string literal.
3558 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3559 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3560 << Arg->getSourceRange();
3561
3562 // Check the contents of the string.
3563 StringRef Feature =
3564 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3565 if (!TI.validateCpuSupports(Feature))
3566 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3567 << Arg->getSourceRange();
3568 return false;
3569}
3570
3571/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3572/// This checks that the target supports __builtin_cpu_is and
3573/// that the string argument is constant and valid.
3574static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3575 Expr *Arg = TheCall->getArg(0);
3576
3577 // Check if the argument is a string literal.
3578 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3579 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3580 << Arg->getSourceRange();
3581
3582 // Check the contents of the string.
3583 StringRef Feature =
3584 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3585 if (!TI.validateCpuIs(Feature))
3586 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3587 << Arg->getSourceRange();
3588 return false;
3589}
3590
3591// Check if the rounding mode is legal.
3592bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3593 // Indicates if this instruction has rounding control or just SAE.
3594 bool HasRC = false;
3595
3596 unsigned ArgNum = 0;
3597 switch (BuiltinID) {
3598 default:
3599 return false;
3600 case X86::BI__builtin_ia32_vcvttsd2si32:
3601 case X86::BI__builtin_ia32_vcvttsd2si64:
3602 case X86::BI__builtin_ia32_vcvttsd2usi32:
3603 case X86::BI__builtin_ia32_vcvttsd2usi64:
3604 case X86::BI__builtin_ia32_vcvttss2si32:
3605 case X86::BI__builtin_ia32_vcvttss2si64:
3606 case X86::BI__builtin_ia32_vcvttss2usi32:
3607 case X86::BI__builtin_ia32_vcvttss2usi64:
3608 ArgNum = 1;
3609 break;
3610 case X86::BI__builtin_ia32_maxpd512:
3611 case X86::BI__builtin_ia32_maxps512:
3612 case X86::BI__builtin_ia32_minpd512:
3613 case X86::BI__builtin_ia32_minps512:
3614 ArgNum = 2;
3615 break;
3616 case X86::BI__builtin_ia32_cvtps2pd512_mask:
3617 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3618 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3619 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3620 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3621 case X86::BI__builtin_ia32_cvttps2dq512_mask:
3622 case X86::BI__builtin_ia32_cvttps2qq512_mask:
3623 case X86::BI__builtin_ia32_cvttps2udq512_mask:
3624 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3625 case X86::BI__builtin_ia32_exp2pd_mask:
3626 case X86::BI__builtin_ia32_exp2ps_mask:
3627 case X86::BI__builtin_ia32_getexppd512_mask:
3628 case X86::BI__builtin_ia32_getexpps512_mask:
3629 case X86::BI__builtin_ia32_rcp28pd_mask:
3630 case X86::BI__builtin_ia32_rcp28ps_mask:
3631 case X86::BI__builtin_ia32_rsqrt28pd_mask:
3632 case X86::BI__builtin_ia32_rsqrt28ps_mask:
3633 case X86::BI__builtin_ia32_vcomisd:
3634 case X86::BI__builtin_ia32_vcomiss:
3635 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3636 ArgNum = 3;
3637 break;
3638 case X86::BI__builtin_ia32_cmppd512_mask:
3639 case X86::BI__builtin_ia32_cmpps512_mask:
3640 case X86::BI__builtin_ia32_cmpsd_mask:
3641 case X86::BI__builtin_ia32_cmpss_mask:
3642 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3643 case X86::BI__builtin_ia32_getexpsd128_round_mask:
3644 case X86::BI__builtin_ia32_getexpss128_round_mask:
3645 case X86::BI__builtin_ia32_getmantpd512_mask:
3646 case X86::BI__builtin_ia32_getmantps512_mask:
3647 case X86::BI__builtin_ia32_maxsd_round_mask:
3648 case X86::BI__builtin_ia32_maxss_round_mask:
3649 case X86::BI__builtin_ia32_minsd_round_mask:
3650 case X86::BI__builtin_ia32_minss_round_mask:
3651 case X86::BI__builtin_ia32_rcp28sd_round_mask:
3652 case X86::BI__builtin_ia32_rcp28ss_round_mask:
3653 case X86::BI__builtin_ia32_reducepd512_mask:
3654 case X86::BI__builtin_ia32_reduceps512_mask:
3655 case X86::BI__builtin_ia32_rndscalepd_mask:
3656 case X86::BI__builtin_ia32_rndscaleps_mask:
3657 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3658 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3659 ArgNum = 4;
3660 break;
3661 case X86::BI__builtin_ia32_fixupimmpd512_mask:
3662 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3663 case X86::BI__builtin_ia32_fixupimmps512_mask:
3664 case X86::BI__builtin_ia32_fixupimmps512_maskz:
3665 case X86::BI__builtin_ia32_fixupimmsd_mask:
3666 case X86::BI__builtin_ia32_fixupimmsd_maskz:
3667 case X86::BI__builtin_ia32_fixupimmss_mask:
3668 case X86::BI__builtin_ia32_fixupimmss_maskz:
3669 case X86::BI__builtin_ia32_getmantsd_round_mask:
3670 case X86::BI__builtin_ia32_getmantss_round_mask:
3671 case X86::BI__builtin_ia32_rangepd512_mask:
3672 case X86::BI__builtin_ia32_rangeps512_mask:
3673 case X86::BI__builtin_ia32_rangesd128_round_mask:
3674 case X86::BI__builtin_ia32_rangess128_round_mask:
3675 case X86::BI__builtin_ia32_reducesd_mask:
3676 case X86::BI__builtin_ia32_reducess_mask:
3677 case X86::BI__builtin_ia32_rndscalesd_round_mask:
3678 case X86::BI__builtin_ia32_rndscaless_round_mask:
3679 ArgNum = 5;
3680 break;
3681 case X86::BI__builtin_ia32_vcvtsd2si64:
3682 case X86::BI__builtin_ia32_vcvtsd2si32:
3683 case X86::BI__builtin_ia32_vcvtsd2usi32:
3684 case X86::BI__builtin_ia32_vcvtsd2usi64:
3685 case X86::BI__builtin_ia32_vcvtss2si32:
3686 case X86::BI__builtin_ia32_vcvtss2si64:
3687 case X86::BI__builtin_ia32_vcvtss2usi32:
3688 case X86::BI__builtin_ia32_vcvtss2usi64:
3689 case X86::BI__builtin_ia32_sqrtpd512:
3690 case X86::BI__builtin_ia32_sqrtps512:
3691 ArgNum = 1;
3692 HasRC = true;
3693 break;
3694 case X86::BI__builtin_ia32_addpd512:
3695 case X86::BI__builtin_ia32_addps512:
3696 case X86::BI__builtin_ia32_divpd512:
3697 case X86::BI__builtin_ia32_divps512:
3698 case X86::BI__builtin_ia32_mulpd512:
3699 case X86::BI__builtin_ia32_mulps512:
3700 case X86::BI__builtin_ia32_subpd512:
3701 case X86::BI__builtin_ia32_subps512:
3702 case X86::BI__builtin_ia32_cvtsi2sd64:
3703 case X86::BI__builtin_ia32_cvtsi2ss32:
3704 case X86::BI__builtin_ia32_cvtsi2ss64:
3705 case X86::BI__builtin_ia32_cvtusi2sd64:
3706 case X86::BI__builtin_ia32_cvtusi2ss32:
3707 case X86::BI__builtin_ia32_cvtusi2ss64:
3708 ArgNum = 2;
3709 HasRC = true;
3710 break;
3711 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3712 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3713 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3714 case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3715 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3716 case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3717 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3718 case X86::BI__builtin_ia32_cvtps2dq512_mask:
3719 case X86::BI__builtin_ia32_cvtps2qq512_mask:
3720 case X86::BI__builtin_ia32_cvtps2udq512_mask:
3721 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3722 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3723 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3724 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3725 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3726 ArgNum = 3;
3727 HasRC = true;
3728 break;
3729 case X86::BI__builtin_ia32_addss_round_mask:
3730 case X86::BI__builtin_ia32_addsd_round_mask:
3731 case X86::BI__builtin_ia32_divss_round_mask:
3732 case X86::BI__builtin_ia32_divsd_round_mask:
3733 case X86::BI__builtin_ia32_mulss_round_mask:
3734 case X86::BI__builtin_ia32_mulsd_round_mask:
3735 case X86::BI__builtin_ia32_subss_round_mask:
3736 case X86::BI__builtin_ia32_subsd_round_mask:
3737 case X86::BI__builtin_ia32_scalefpd512_mask:
3738 case X86::BI__builtin_ia32_scalefps512_mask:
3739 case X86::BI__builtin_ia32_scalefsd_round_mask:
3740 case X86::BI__builtin_ia32_scalefss_round_mask:
3741 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3742 case X86::BI__builtin_ia32_sqrtsd_round_mask:
3743 case X86::BI__builtin_ia32_sqrtss_round_mask:
3744 case X86::BI__builtin_ia32_vfmaddsd3_mask:
3745 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3746 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3747 case X86::BI__builtin_ia32_vfmaddss3_mask:
3748 case X86::BI__builtin_ia32_vfmaddss3_maskz:
3749 case X86::BI__builtin_ia32_vfmaddss3_mask3:
3750 case X86::BI__builtin_ia32_vfmaddpd512_mask:
3751 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3752 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3753 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3754 case X86::BI__builtin_ia32_vfmaddps512_mask:
3755 case X86::BI__builtin_ia32_vfmaddps512_maskz:
3756 case X86::BI__builtin_ia32_vfmaddps512_mask3:
3757 case X86::BI__builtin_ia32_vfmsubps512_mask3:
3758 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3759 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3760 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3761 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3762 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3763 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3764 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3765 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3766 ArgNum = 4;
3767 HasRC = true;
3768 break;
3769 }
3770
3771 llvm::APSInt Result;
3772
3773 // We can't check the value of a dependent argument.
3774 Expr *Arg = TheCall->getArg(ArgNum);
3775 if (Arg->isTypeDependent() || Arg->isValueDependent())
3776 return false;
3777
3778 // Check constant-ness first.
3779 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3780 return true;
3781
3782 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3783 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3784 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3785 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3786 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3787 Result == 8/*ROUND_NO_EXC*/ ||
3788 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3789 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3790 return false;
3791
3792 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3793 << Arg->getSourceRange();
3794}
3795
3796// Check if the gather/scatter scale is legal.
3797bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3798 CallExpr *TheCall) {
3799 unsigned ArgNum = 0;
3800 switch (BuiltinID) {
3801 default:
3802 return false;
3803 case X86::BI__builtin_ia32_gatherpfdpd:
3804 case X86::BI__builtin_ia32_gatherpfdps:
3805 case X86::BI__builtin_ia32_gatherpfqpd:
3806 case X86::BI__builtin_ia32_gatherpfqps:
3807 case X86::BI__builtin_ia32_scatterpfdpd:
3808 case X86::BI__builtin_ia32_scatterpfdps:
3809 case X86::BI__builtin_ia32_scatterpfqpd:
3810 case X86::BI__builtin_ia32_scatterpfqps:
3811 ArgNum = 3;
3812 break;
3813 case X86::BI__builtin_ia32_gatherd_pd:
3814 case X86::BI__builtin_ia32_gatherd_pd256:
3815 case X86::BI__builtin_ia32_gatherq_pd:
3816 case X86::BI__builtin_ia32_gatherq_pd256:
3817 case X86::BI__builtin_ia32_gatherd_ps:
3818 case X86::BI__builtin_ia32_gatherd_ps256:
3819 case X86::BI__builtin_ia32_gatherq_ps:
3820 case X86::BI__builtin_ia32_gatherq_ps256:
3821 case X86::BI__builtin_ia32_gatherd_q:
3822 case X86::BI__builtin_ia32_gatherd_q256:
3823 case X86::BI__builtin_ia32_gatherq_q:
3824 case X86::BI__builtin_ia32_gatherq_q256:
3825 case X86::BI__builtin_ia32_gatherd_d:
3826 case X86::BI__builtin_ia32_gatherd_d256:
3827 case X86::BI__builtin_ia32_gatherq_d:
3828 case X86::BI__builtin_ia32_gatherq_d256:
3829 case X86::BI__builtin_ia32_gather3div2df:
3830 case X86::BI__builtin_ia32_gather3div2di:
3831 case X86::BI__builtin_ia32_gather3div4df:
3832 case X86::BI__builtin_ia32_gather3div4di:
3833 case X86::BI__builtin_ia32_gather3div4sf:
3834 case X86::BI__builtin_ia32_gather3div4si:
3835 case X86::BI__builtin_ia32_gather3div8sf:
3836 case X86::BI__builtin_ia32_gather3div8si:
3837 case X86::BI__builtin_ia32_gather3siv2df:
3838 case X86::BI__builtin_ia32_gather3siv2di:
3839 case X86::BI__builtin_ia32_gather3siv4df:
3840 case X86::BI__builtin_ia32_gather3siv4di:
3841 case X86::BI__builtin_ia32_gather3siv4sf:
3842 case X86::BI__builtin_ia32_gather3siv4si:
3843 case X86::BI__builtin_ia32_gather3siv8sf:
3844 case X86::BI__builtin_ia32_gather3siv8si:
3845 case X86::BI__builtin_ia32_gathersiv8df:
3846 case X86::BI__builtin_ia32_gathersiv16sf:
3847 case X86::BI__builtin_ia32_gatherdiv8df:
3848 case X86::BI__builtin_ia32_gatherdiv16sf:
3849 case X86::BI__builtin_ia32_gathersiv8di:
3850 case X86::BI__builtin_ia32_gathersiv16si:
3851 case X86::BI__builtin_ia32_gatherdiv8di:
3852 case X86::BI__builtin_ia32_gatherdiv16si:
3853 case X86::BI__builtin_ia32_scatterdiv2df:
3854 case X86::BI__builtin_ia32_scatterdiv2di:
3855 case X86::BI__builtin_ia32_scatterdiv4df:
3856 case X86::BI__builtin_ia32_scatterdiv4di:
3857 case X86::BI__builtin_ia32_scatterdiv4sf:
3858 case X86::BI__builtin_ia32_scatterdiv4si:
3859 case X86::BI__builtin_ia32_scatterdiv8sf:
3860 case X86::BI__builtin_ia32_scatterdiv8si:
3861 case X86::BI__builtin_ia32_scattersiv2df:
3862 case X86::BI__builtin_ia32_scattersiv2di:
3863 case X86::BI__builtin_ia32_scattersiv4df:
3864 case X86::BI__builtin_ia32_scattersiv4di:
3865 case X86::BI__builtin_ia32_scattersiv4sf:
3866 case X86::BI__builtin_ia32_scattersiv4si:
3867 case X86::BI__builtin_ia32_scattersiv8sf:
3868 case X86::BI__builtin_ia32_scattersiv8si:
3869 case X86::BI__builtin_ia32_scattersiv8df:
3870 case X86::BI__builtin_ia32_scattersiv16sf:
3871 case X86::BI__builtin_ia32_scatterdiv8df:
3872 case X86::BI__builtin_ia32_scatterdiv16sf:
3873 case X86::BI__builtin_ia32_scattersiv8di:
3874 case X86::BI__builtin_ia32_scattersiv16si:
3875 case X86::BI__builtin_ia32_scatterdiv8di:
3876 case X86::BI__builtin_ia32_scatterdiv16si:
3877 ArgNum = 4;
3878 break;
3879 }
3880
3881 llvm::APSInt Result;
3882
3883 // We can't check the value of a dependent argument.
3884 Expr *Arg = TheCall->getArg(ArgNum);
3885 if (Arg->isTypeDependent() || Arg->isValueDependent())
3886 return false;
3887
3888 // Check constant-ness first.
3889 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3890 return true;
3891
3892 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3893 return false;
3894
3895 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3896 << Arg->getSourceRange();
3897}
3898
3899enum { TileRegLow = 0, TileRegHigh = 7 };
3900
3901bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
3902 ArrayRef<int> ArgNums) {
3903 for (int ArgNum : ArgNums) {
3904 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
3905 return true;
3906 }
3907 return false;
3908}
3909
3910bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
3911 ArrayRef<int> ArgNums) {
3912 // Because the max number of tile register is TileRegHigh + 1, so here we use
3913 // each bit to represent the usage of them in bitset.
3914 std::bitset<TileRegHigh + 1> ArgValues;
3915 for (int ArgNum : ArgNums) {
3916 Expr *Arg = TheCall->getArg(ArgNum);
3917 if (Arg->isTypeDependent() || Arg->isValueDependent())
3918 continue;
3919
3920 llvm::APSInt Result;
3921 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3922 return true;
3923 int ArgExtValue = Result.getExtValue();
3924 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&(static_cast <bool> ((ArgExtValue >= TileRegLow || ArgExtValue
<= TileRegHigh) && "Incorrect tile register num."
) ? void (0) : __assert_fail ("(ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && \"Incorrect tile register num.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 3925, __extension__ __PRETTY_FUNCTION__))
3925 "Incorrect tile register num.")(static_cast <bool> ((ArgExtValue >= TileRegLow || ArgExtValue
<= TileRegHigh) && "Incorrect tile register num."
) ? void (0) : __assert_fail ("(ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && \"Incorrect tile register num.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 3925, __extension__ __PRETTY_FUNCTION__))
;
3926 if (ArgValues.test(ArgExtValue))
3927 return Diag(TheCall->getBeginLoc(),
3928 diag::err_x86_builtin_tile_arg_duplicate)
3929 << TheCall->getArg(ArgNum)->getSourceRange();
3930 ArgValues.set(ArgExtValue);
3931 }
3932 return false;
3933}
3934
3935bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
3936 ArrayRef<int> ArgNums) {
3937 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
3938 CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
3939}
3940
3941bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
3942 switch (BuiltinID) {
3943 default:
3944 return false;
3945 case X86::BI__builtin_ia32_tileloadd64:
3946 case X86::BI__builtin_ia32_tileloaddt164:
3947 case X86::BI__builtin_ia32_tilestored64:
3948 case X86::BI__builtin_ia32_tilezero:
3949 return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
3950 case X86::BI__builtin_ia32_tdpbssd:
3951 case X86::BI__builtin_ia32_tdpbsud:
3952 case X86::BI__builtin_ia32_tdpbusd:
3953 case X86::BI__builtin_ia32_tdpbuud:
3954 case X86::BI__builtin_ia32_tdpbf16ps:
3955 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
3956 }
3957}
3958static bool isX86_32Builtin(unsigned BuiltinID) {
3959 // These builtins only work on x86-32 targets.
3960 switch (BuiltinID) {
3961 case X86::BI__builtin_ia32_readeflags_u32:
3962 case X86::BI__builtin_ia32_writeeflags_u32:
3963 return true;
3964 }
3965
3966 return false;
3967}
3968
3969bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3970 CallExpr *TheCall) {
3971 if (BuiltinID == X86::BI__builtin_cpu_supports)
3972 return SemaBuiltinCpuSupports(*this, TI, TheCall);
3973
3974 if (BuiltinID == X86::BI__builtin_cpu_is)
3975 return SemaBuiltinCpuIs(*this, TI, TheCall);
3976
3977 // Check for 32-bit only builtins on a 64-bit target.
3978 const llvm::Triple &TT = TI.getTriple();
3979 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3980 return Diag(TheCall->getCallee()->getBeginLoc(),
3981 diag::err_32_bit_builtin_64_bit_tgt);
3982
3983 // If the intrinsic has rounding or SAE make sure its valid.
3984 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3985 return true;
3986
3987 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3988 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3989 return true;
3990
3991 // If the intrinsic has a tile arguments, make sure they are valid.
3992 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
3993 return true;
3994
3995 // For intrinsics which take an immediate value as part of the instruction,
3996 // range check them here.
3997 int i = 0, l = 0, u = 0;
3998 switch (BuiltinID) {
3999 default:
4000 return false;
4001 case X86::BI__builtin_ia32_vec_ext_v2si:
4002 case X86::BI__builtin_ia32_vec_ext_v2di:
4003 case X86::BI__builtin_ia32_vextractf128_pd256:
4004 case X86::BI__builtin_ia32_vextractf128_ps256:
4005 case X86::BI__builtin_ia32_vextractf128_si256:
4006 case X86::BI__builtin_ia32_extract128i256:
4007 case X86::BI__builtin_ia32_extractf64x4_mask:
4008 case X86::BI__builtin_ia32_extracti64x4_mask:
4009 case X86::BI__builtin_ia32_extractf32x8_mask:
4010 case X86::BI__builtin_ia32_extracti32x8_mask:
4011 case X86::BI__builtin_ia32_extractf64x2_256_mask:
4012 case X86::BI__builtin_ia32_extracti64x2_256_mask:
4013 case X86::BI__builtin_ia32_extractf32x4_256_mask:
4014 case X86::BI__builtin_ia32_extracti32x4_256_mask:
4015 i = 1; l = 0; u = 1;
4016 break;
4017 case X86::BI__builtin_ia32_vec_set_v2di:
4018 case X86::BI__builtin_ia32_vinsertf128_pd256:
4019 case X86::BI__builtin_ia32_vinsertf128_ps256:
4020 case X86::BI__builtin_ia32_vinsertf128_si256:
4021 case X86::BI__builtin_ia32_insert128i256:
4022 case X86::BI__builtin_ia32_insertf32x8:
4023 case X86::BI__builtin_ia32_inserti32x8:
4024 case X86::BI__builtin_ia32_insertf64x4:
4025 case X86::BI__builtin_ia32_inserti64x4:
4026 case X86::BI__builtin_ia32_insertf64x2_256:
4027 case X86::BI__builtin_ia32_inserti64x2_256:
4028 case X86::BI__builtin_ia32_insertf32x4_256:
4029 case X86::BI__builtin_ia32_inserti32x4_256:
4030 i = 2; l = 0; u = 1;
4031 break;
4032 case X86::BI__builtin_ia32_vpermilpd:
4033 case X86::BI__builtin_ia32_vec_ext_v4hi:
4034 case X86::BI__builtin_ia32_vec_ext_v4si:
4035 case X86::BI__builtin_ia32_vec_ext_v4sf:
4036 case X86::BI__builtin_ia32_vec_ext_v4di:
4037 case X86::BI__builtin_ia32_extractf32x4_mask:
4038 case X86::BI__builtin_ia32_extracti32x4_mask:
4039 case X86::BI__builtin_ia32_extractf64x2_512_mask:
4040 case X86::BI__builtin_ia32_extracti64x2_512_mask:
4041 i = 1; l = 0; u = 3;
4042 break;
4043 case X86::BI_mm_prefetch:
4044 case X86::BI__builtin_ia32_vec_ext_v8hi:
4045 case X86::BI__builtin_ia32_vec_ext_v8si:
4046 i = 1; l = 0; u = 7;
4047 break;
4048 case X86::BI__builtin_ia32_sha1rnds4:
4049 case X86::BI__builtin_ia32_blendpd:
4050 case X86::BI__builtin_ia32_shufpd:
4051 case X86::BI__builtin_ia32_vec_set_v4hi:
4052 case X86::BI__builtin_ia32_vec_set_v4si:
4053 case X86::BI__builtin_ia32_vec_set_v4di:
4054 case X86::BI__builtin_ia32_shuf_f32x4_256:
4055 case X86::BI__builtin_ia32_shuf_f64x2_256:
4056 case X86::BI__builtin_ia32_shuf_i32x4_256:
4057 case X86::BI__builtin_ia32_shuf_i64x2_256:
4058 case X86::BI__builtin_ia32_insertf64x2_512:
4059 case X86::BI__builtin_ia32_inserti64x2_512:
4060 case X86::BI__builtin_ia32_insertf32x4:
4061 case X86::BI__builtin_ia32_inserti32x4:
4062 i = 2; l = 0; u = 3;
4063 break;
4064 case X86::BI__builtin_ia32_vpermil2pd:
4065 case X86::BI__builtin_ia32_vpermil2pd256:
4066 case X86::BI__builtin_ia32_vpermil2ps:
4067 case X86::BI__builtin_ia32_vpermil2ps256:
4068 i = 3; l = 0; u = 3;
4069 break;
4070 case X86::BI__builtin_ia32_cmpb128_mask:
4071 case X86::BI__builtin_ia32_cmpw128_mask:
4072 case X86::BI__builtin_ia32_cmpd128_mask:
4073 case X86::BI__builtin_ia32_cmpq128_mask:
4074 case X86::BI__builtin_ia32_cmpb256_mask:
4075 case X86::BI__builtin_ia32_cmpw256_mask:
4076 case X86::BI__builtin_ia32_cmpd256_mask:
4077 case X86::BI__builtin_ia32_cmpq256_mask:
4078 case X86::BI__builtin_ia32_cmpb512_mask:
4079 case X86::BI__builtin_ia32_cmpw512_mask:
4080 case X86::BI__builtin_ia32_cmpd512_mask:
4081 case X86::BI__builtin_ia32_cmpq512_mask:
4082 case X86::BI__builtin_ia32_ucmpb128_mask:
4083 case X86::BI__builtin_ia32_ucmpw128_mask:
4084 case X86::BI__builtin_ia32_ucmpd128_mask:
4085 case X86::BI__builtin_ia32_ucmpq128_mask:
4086 case X86::BI__builtin_ia32_ucmpb256_mask:
4087 case X86::BI__builtin_ia32_ucmpw256_mask:
4088 case X86::BI__builtin_ia32_ucmpd256_mask:
4089 case X86::BI__builtin_ia32_ucmpq256_mask:
4090 case X86::BI__builtin_ia32_ucmpb512_mask:
4091 case X86::BI__builtin_ia32_ucmpw512_mask:
4092 case X86::BI__builtin_ia32_ucmpd512_mask:
4093 case X86::BI__builtin_ia32_ucmpq512_mask:
4094 case X86::BI__builtin_ia32_vpcomub:
4095 case X86::BI__builtin_ia32_vpcomuw:
4096 case X86::BI__builtin_ia32_vpcomud:
4097 case X86::BI__builtin_ia32_vpcomuq:
4098 case X86::BI__builtin_ia32_vpcomb:
4099 case X86::BI__builtin_ia32_vpcomw:
4100 case X86::BI__builtin_ia32_vpcomd:
4101 case X86::BI__builtin_ia32_vpcomq:
4102 case X86::BI__builtin_ia32_vec_set_v8hi:
4103 case X86::BI__builtin_ia32_vec_set_v8si:
4104 i = 2; l = 0; u = 7;
4105 break;
4106 case X86::BI__builtin_ia32_vpermilpd256:
4107 case X86::BI__builtin_ia32_roundps:
4108 case X86::BI__builtin_ia32_roundpd:
4109 case X86::BI__builtin_ia32_roundps256:
4110 case X86::BI__builtin_ia32_roundpd256:
4111 case X86::BI__builtin_ia32_getmantpd128_mask:
4112 case X86::BI__builtin_ia32_getmantpd256_mask:
4113 case X86::BI__builtin_ia32_getmantps128_mask:
4114 case X86::BI__builtin_ia32_getmantps256_mask:
4115 case X86::BI__builtin_ia32_getmantpd512_mask:
4116 case X86::BI__builtin_ia32_getmantps512_mask:
4117 case X86::BI__builtin_ia32_vec_ext_v16qi:
4118 case X86::BI__builtin_ia32_vec_ext_v16hi:
4119 i = 1; l = 0; u = 15;
4120 break;
4121 case X86::BI__builtin_ia32_pblendd128:
4122 case X86::BI__builtin_ia32_blendps:
4123 case X86::BI__builtin_ia32_blendpd256:
4124 case X86::BI__builtin_ia32_shufpd256:
4125 case X86::BI__builtin_ia32_roundss:
4126 case X86::BI__builtin_ia32_roundsd:
4127 case X86::BI__builtin_ia32_rangepd128_mask:
4128 case X86::BI__builtin_ia32_rangepd256_mask:
4129 case X86::BI__builtin_ia32_rangepd512_mask:
4130 case X86::BI__builtin_ia32_rangeps128_mask:
4131 case X86::BI__builtin_ia32_rangeps256_mask:
4132 case X86::BI__builtin_ia32_rangeps512_mask:
4133 case X86::BI__builtin_ia32_getmantsd_round_mask:
4134 case X86::BI__builtin_ia32_getmantss_round_mask:
4135 case X86::BI__builtin_ia32_vec_set_v16qi:
4136 case X86::BI__builtin_ia32_vec_set_v16hi:
4137 i = 2; l = 0; u = 15;
4138 break;
4139 case X86::BI__builtin_ia32_vec_ext_v32qi:
4140 i = 1; l = 0; u = 31;
4141 break;
4142 case X86::BI__builtin_ia32_cmpps:
4143 case X86::BI__builtin_ia32_cmpss:
4144 case X86::BI__builtin_ia32_cmppd:
4145 case X86::BI__builtin_ia32_cmpsd:
4146 case X86::BI__builtin_ia32_cmpps256:
4147 case X86::BI__builtin_ia32_cmppd256:
4148 case X86::BI__builtin_ia32_cmpps128_mask:
4149 case X86::BI__builtin_ia32_cmppd128_mask:
4150 case X86::BI__builtin_ia32_cmpps256_mask:
4151 case X86::BI__builtin_ia32_cmppd256_mask:
4152 case X86::BI__builtin_ia32_cmpps512_mask:
4153 case X86::BI__builtin_ia32_cmppd512_mask:
4154 case X86::BI__builtin_ia32_cmpsd_mask:
4155 case X86::BI__builtin_ia32_cmpss_mask:
4156 case X86::BI__builtin_ia32_vec_set_v32qi:
4157 i = 2; l = 0; u = 31;
4158 break;
4159 case X86::BI__builtin_ia32_permdf256:
4160 case X86::BI__builtin_ia32_permdi256:
4161 case X86::BI__builtin_ia32_permdf512:
4162 case X86::BI__builtin_ia32_permdi512:
4163 case X86::BI__builtin_ia32_vpermilps:
4164 case X86::BI__builtin_ia32_vpermilps256:
4165 case X86::BI__builtin_ia32_vpermilpd512:
4166 case X86::BI__builtin_ia32_vpermilps512:
4167 case X86::BI__builtin_ia32_pshufd:
4168 case X86::BI__builtin_ia32_pshufd256:
4169 case X86::BI__builtin_ia32_pshufd512:
4170 case X86::BI__builtin_ia32_pshufhw:
4171 case X86::BI__builtin_ia32_pshufhw256:
4172 case X86::BI__builtin_ia32_pshufhw512:
4173 case X86::BI__builtin_ia32_pshuflw:
4174 case X86::BI__builtin_ia32_pshuflw256:
4175 case X86::BI__builtin_ia32_pshuflw512:
4176 case X86::BI__builtin_ia32_vcvtps2ph:
4177 case X86::BI__builtin_ia32_vcvtps2ph_mask:
4178 case X86::BI__builtin_ia32_vcvtps2ph256:
4179 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4180 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4181 case X86::BI__builtin_ia32_rndscaleps_128_mask:
4182 case X86::BI__builtin_ia32_rndscalepd_128_mask:
4183 case X86::BI__builtin_ia32_rndscaleps_256_mask:
4184 case X86::BI__builtin_ia32_rndscalepd_256_mask:
4185 case X86::BI__builtin_ia32_rndscaleps_mask:
4186 case X86::BI__builtin_ia32_rndscalepd_mask:
4187 case X86::BI__builtin_ia32_reducepd128_mask:
4188 case X86::BI__builtin_ia32_reducepd256_mask:
4189 case X86::BI__builtin_ia32_reducepd512_mask:
4190 case X86::BI__builtin_ia32_reduceps128_mask:
4191 case X86::BI__builtin_ia32_reduceps256_mask:
4192 case X86::BI__builtin_ia32_reduceps512_mask:
4193 case X86::BI__builtin_ia32_prold512:
4194 case X86::BI__builtin_ia32_prolq512:
4195 case X86::BI__builtin_ia32_prold128:
4196 case X86::BI__builtin_ia32_prold256:
4197 case X86::BI__builtin_ia32_prolq128:
4198 case X86::BI__builtin_ia32_prolq256:
4199 case X86::BI__builtin_ia32_prord512:
4200 case X86::BI__builtin_ia32_prorq512:
4201 case X86::BI__builtin_ia32_prord128:
4202 case X86::BI__builtin_ia32_prord256:
4203 case X86::BI__builtin_ia32_prorq128:
4204 case X86::BI__builtin_ia32_prorq256:
4205 case X86::BI__builtin_ia32_fpclasspd128_mask:
4206 case X86::BI__builtin_ia32_fpclasspd256_mask:
4207 case X86::BI__builtin_ia32_fpclassps128_mask:
4208 case X86::BI__builtin_ia32_fpclassps256_mask:
4209 case X86::BI__builtin_ia32_fpclassps512_mask:
4210 case X86::BI__builtin_ia32_fpclasspd512_mask:
4211 case X86::BI__builtin_ia32_fpclasssd_mask:
4212 case X86::BI__builtin_ia32_fpclassss_mask:
4213 case X86::BI__builtin_ia32_pslldqi128_byteshift:
4214 case X86::BI__builtin_ia32_pslldqi256_byteshift:
4215 case X86::BI__builtin_ia32_pslldqi512_byteshift:
4216 case X86::BI__builtin_ia32_psrldqi128_byteshift:
4217 case X86::BI__builtin_ia32_psrldqi256_byteshift:
4218 case X86::BI__builtin_ia32_psrldqi512_byteshift:
4219 case X86::BI__builtin_ia32_kshiftliqi:
4220 case X86::BI__builtin_ia32_kshiftlihi:
4221 case X86::BI__builtin_ia32_kshiftlisi:
4222 case X86::BI__builtin_ia32_kshiftlidi:
4223 case X86::BI__builtin_ia32_kshiftriqi:
4224 case X86::BI__builtin_ia32_kshiftrihi:
4225 case X86::BI__builtin_ia32_kshiftrisi:
4226 case X86::BI__builtin_ia32_kshiftridi:
4227 i = 1; l = 0; u = 255;
4228 break;
4229 case X86::BI__builtin_ia32_vperm2f128_pd256:
4230 case X86::BI__builtin_ia32_vperm2f128_ps256:
4231 case X86::BI__builtin_ia32_vperm2f128_si256:
4232 case X86::BI__builtin_ia32_permti256:
4233 case X86::BI__builtin_ia32_pblendw128:
4234 case X86::BI__builtin_ia32_pblendw256:
4235 case X86::BI__builtin_ia32_blendps256:
4236 case X86::BI__builtin_ia32_pblendd256:
4237 case X86::BI__builtin_ia32_palignr128:
4238 case X86::BI__builtin_ia32_palignr256:
4239 case X86::BI__builtin_ia32_palignr512:
4240 case X86::BI__builtin_ia32_alignq512:
4241 case X86::BI__builtin_ia32_alignd512:
4242 case X86::BI__builtin_ia32_alignd128:
4243 case X86::BI__builtin_ia32_alignd256:
4244 case X86::BI__builtin_ia32_alignq128:
4245 case X86::BI__builtin_ia32_alignq256:
4246 case X86::BI__builtin_ia32_vcomisd:
4247 case X86::BI__builtin_ia32_vcomiss:
4248 case X86::BI__builtin_ia32_shuf_f32x4:
4249 case X86::BI__builtin_ia32_shuf_f64x2:
4250 case X86::BI__builtin_ia32_shuf_i32x4:
4251 case X86::BI__builtin_ia32_shuf_i64x2:
4252 case X86::BI__builtin_ia32_shufpd512:
4253 case X86::BI__builtin_ia32_shufps:
4254 case X86::BI__builtin_ia32_shufps256:
4255 case X86::BI__builtin_ia32_shufps512:
4256 case X86::BI__builtin_ia32_dbpsadbw128:
4257 case X86::BI__builtin_ia32_dbpsadbw256:
4258 case X86::BI__builtin_ia32_dbpsadbw512:
4259 case X86::BI__builtin_ia32_vpshldd128:
4260 case X86::BI__builtin_ia32_vpshldd256:
4261 case X86::BI__builtin_ia32_vpshldd512:
4262 case X86::BI__builtin_ia32_vpshldq128:
4263 case X86::BI__builtin_ia32_vpshldq256:
4264 case X86::BI__builtin_ia32_vpshldq512:
4265 case X86::BI__builtin_ia32_vpshldw128:
4266 case X86::BI__builtin_ia32_vpshldw256:
4267 case X86::BI__builtin_ia32_vpshldw512:
4268 case X86::BI__builtin_ia32_vpshrdd128:
4269 case X86::BI__builtin_ia32_vpshrdd256:
4270 case X86::BI__builtin_ia32_vpshrdd512:
4271 case X86::BI__builtin_ia32_vpshrdq128:
4272 case X86::BI__builtin_ia32_vpshrdq256:
4273 case X86::BI__builtin_ia32_vpshrdq512:
4274 case X86::BI__builtin_ia32_vpshrdw128:
4275 case X86::BI__builtin_ia32_vpshrdw256:
4276 case X86::BI__builtin_ia32_vpshrdw512:
4277 i = 2; l = 0; u = 255;
4278 break;
4279 case X86::BI__builtin_ia32_fixupimmpd512_mask:
4280 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4281 case X86::BI__builtin_ia32_fixupimmps512_mask:
4282 case X86::BI__builtin_ia32_fixupimmps512_maskz:
4283 case X86::BI__builtin_ia32_fixupimmsd_mask:
4284 case X86::BI__builtin_ia32_fixupimmsd_maskz:
4285 case X86::BI__builtin_ia32_fixupimmss_mask:
4286 case X86::BI__builtin_ia32_fixupimmss_maskz:
4287 case X86::BI__builtin_ia32_fixupimmpd128_mask:
4288 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4289 case X86::BI__builtin_ia32_fixupimmpd256_mask:
4290 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4291 case X86::BI__builtin_ia32_fixupimmps128_mask:
4292 case X86::BI__builtin_ia32_fixupimmps128_maskz:
4293 case X86::BI__builtin_ia32_fixupimmps256_mask:
4294 case X86::BI__builtin_ia32_fixupimmps256_maskz:
4295 case X86::BI__builtin_ia32_pternlogd512_mask:
4296 case X86::BI__builtin_ia32_pternlogd512_maskz:
4297 case X86::BI__builtin_ia32_pternlogq512_mask:
4298 case X86::BI__builtin_ia32_pternlogq512_maskz:
4299 case X86::BI__builtin_ia32_pternlogd128_mask:
4300 case X86::BI__builtin_ia32_pternlogd128_maskz:
4301 case X86::BI__builtin_ia32_pternlogd256_mask:
4302 case X86::BI__builtin_ia32_pternlogd256_maskz:
4303 case X86::BI__builtin_ia32_pternlogq128_mask:
4304 case X86::BI__builtin_ia32_pternlogq128_maskz:
4305 case X86::BI__builtin_ia32_pternlogq256_mask:
4306 case X86::BI__builtin_ia32_pternlogq256_maskz:
4307 i = 3; l = 0; u = 255;
4308 break;
4309 case X86::BI__builtin_ia32_gatherpfdpd:
4310 case X86::BI__builtin_ia32_gatherpfdps:
4311 case X86::BI__builtin_ia32_gatherpfqpd:
4312 case X86::BI__builtin_ia32_gatherpfqps:
4313 case X86::BI__builtin_ia32_scatterpfdpd:
4314 case X86::BI__builtin_ia32_scatterpfdps:
4315 case X86::BI__builtin_ia32_scatterpfqpd:
4316 case X86::BI__builtin_ia32_scatterpfqps:
4317 i = 4; l = 2; u = 3;
4318 break;
4319 case X86::BI__builtin_ia32_reducesd_mask:
4320 case X86::BI__builtin_ia32_reducess_mask:
4321 case X86::BI__builtin_ia32_rndscalesd_round_mask:
4322 case X86::BI__builtin_ia32_rndscaless_round_mask:
4323 i = 4; l = 0; u = 255;
4324 break;
4325 }
4326
4327 // Note that we don't force a hard error on the range check here, allowing
4328 // template-generated or macro-generated dead code to potentially have out-of-
4329 // range values. These need to code generate, but don't need to necessarily
4330 // make any sense. We use a warning that defaults to an error.
4331 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4332}
4333
4334/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4335/// parameter with the FormatAttr's correct format_idx and firstDataArg.
4336/// Returns true when the format fits the function and the FormatStringInfo has
4337/// been populated.
4338bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4339 FormatStringInfo *FSI) {
4340 FSI->HasVAListArg = Format->getFirstArg() == 0;
4341 FSI->FormatIdx = Format->getFormatIdx() - 1;
4342 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4343
4344 // The way the format attribute works in GCC, the implicit this argument
4345 // of member functions is counted. However, it doesn't appear in our own
4346 // lists, so decrement format_idx in that case.
4347 if (IsCXXMember) {
4348 if(FSI->FormatIdx == 0)
4349 return false;
4350 --FSI->FormatIdx;
4351 if (FSI->FirstDataArg != 0)
4352 --FSI->FirstDataArg;
4353 }
4354 return true;
4355}
4356
4357/// Checks if a the given expression evaluates to null.
4358///
4359/// Returns true if the value evaluates to null.
4360static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4361 // If the expression has non-null type, it doesn't evaluate to null.
4362 if (auto nullability
4363 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4364 if (*nullability == NullabilityKind::NonNull)
4365 return false;
4366 }
4367
4368 // As a special case, transparent unions initialized with zero are
4369 // considered null for the purposes of the nonnull attribute.
4370 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4371 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4372 if (const CompoundLiteralExpr *CLE =
4373 dyn_cast<CompoundLiteralExpr>(Expr))
4374 if (const InitListExpr *ILE =
4375 dyn_cast<InitListExpr>(CLE->getInitializer()))
4376 Expr = ILE->getInit(0);
4377 }
4378
4379 bool Result;
4380 return (!Expr->isValueDependent() &&
4381 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4382 !Result);
4383}
4384
4385static void CheckNonNullArgument(Sema &S,
4386 const Expr *ArgExpr,
4387 SourceLocation CallSiteLoc) {
4388 if (CheckNonNullExpr(S, ArgExpr))
4389 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4390 S.PDiag(diag::warn_null_arg)
4391 << ArgExpr->getSourceRange());
4392}
4393
4394bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4395 FormatStringInfo FSI;
4396 if ((GetFormatStringType(Format) == FST_NSString) &&
4397 getFormatStringInfo(Format, false, &FSI)) {
4398 Idx = FSI.FormatIdx;
4399 return true;
4400 }
4401 return false;
4402}
4403
4404/// Diagnose use of %s directive in an NSString which is being passed
4405/// as formatting string to formatting method.
4406static void
4407DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4408 const NamedDecl *FDecl,
4409 Expr **Args,
4410 unsigned NumArgs) {
4411 unsigned Idx = 0;
4412 bool Format = false;
4413 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4414 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4415 Idx = 2;
4416 Format = true;
4417 }
4418 else
4419 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4420 if (S.GetFormatNSStringIdx(I, Idx)) {
4421 Format = true;
4422 break;
4423 }
4424 }
4425 if (!Format || NumArgs <= Idx)
4426 return;
4427 const Expr *FormatExpr = Args[Idx];
4428 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4429 FormatExpr = CSCE->getSubExpr();
4430 const StringLiteral *FormatString;
4431 if (const ObjCStringLiteral *OSL =
4432 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4433 FormatString = OSL->getString();
4434 else
4435 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4436 if (!FormatString)
4437 return;
4438 if (S.FormatStringHasSArg(FormatString)) {
4439 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4440 << "%s" << 1 << 1;
4441 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4442 << FDecl->getDeclName();
4443 }
4444}
4445
4446/// Determine whether the given type has a non-null nullability annotation.
4447static bool isNonNullType(ASTContext &ctx, QualType type) {
4448 if (auto nullability = type->getNullability(ctx))
4449 return *nullability == NullabilityKind::NonNull;
4450
4451 return false;
4452}
4453
4454static void CheckNonNullArguments(Sema &S,
4455 const NamedDecl *FDecl,
4456 const FunctionProtoType *Proto,
4457 ArrayRef<const Expr *> Args,
4458 SourceLocation CallSiteLoc) {
4459 assert((FDecl || Proto) && "Need a function declaration or prototype")(static_cast <bool> ((FDecl || Proto) && "Need a function declaration or prototype"
) ? void (0) : __assert_fail ("(FDecl || Proto) && \"Need a function declaration or prototype\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 4459, __extension__ __PRETTY_FUNCTION__))
;
4460
4461 // Already checked by by constant evaluator.
4462 if (S.isConstantEvaluated())
4463 return;
4464 // Check the attributes attached to the method/function itself.
4465 llvm::SmallBitVector NonNullArgs;
4466 if (FDecl) {
4467 // Handle the nonnull attribute on the function/method declaration itself.
4468 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4469 if (!NonNull->args_size()) {
4470 // Easy case: all pointer arguments are nonnull.
4471 for (const auto *Arg : Args)
4472 if (S.isValidPointerAttrType(Arg->getType()))
4473 CheckNonNullArgument(S, Arg, CallSiteLoc);
4474 return;
4475 }
4476
4477 for (const ParamIdx &Idx : NonNull->args()) {
4478 unsigned IdxAST = Idx.getASTIndex();
4479 if (IdxAST >= Args.size())
4480 continue;
4481 if (NonNullArgs.empty())
4482 NonNullArgs.resize(Args.size());
4483 NonNullArgs.set(IdxAST);
4484 }
4485 }
4486 }
4487
4488 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4489 // Handle the nonnull attribute on the parameters of the
4490 // function/method.
4491 ArrayRef<ParmVarDecl*> parms;
4492 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4493 parms = FD->parameters();
4494 else
4495 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4496
4497 unsigned ParamIndex = 0;
4498 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4499 I != E; ++I, ++ParamIndex) {
4500 const ParmVarDecl *PVD = *I;
4501 if (PVD->hasAttr<NonNullAttr>() ||
4502 isNonNullType(S.Context, PVD->getType())) {
4503 if (NonNullArgs.empty())
4504 NonNullArgs.resize(Args.size());
4505
4506 NonNullArgs.set(ParamIndex);
4507 }
4508 }
4509 } else {
4510 // If we have a non-function, non-method declaration but no
4511 // function prototype, try to dig out the function prototype.
4512 if (!Proto) {
4513 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4514 QualType type = VD->getType().getNonReferenceType();
4515 if (auto pointerType = type->getAs<PointerType>())
4516 type = pointerType->getPointeeType();
4517 else if (auto blockType = type->getAs<BlockPointerType>())
4518 type = blockType->getPointeeType();
4519 // FIXME: data member pointers?
4520
4521 // Dig out the function prototype, if there is one.
4522 Proto = type->getAs<FunctionProtoType>();
4523 }
4524 }
4525
4526 // Fill in non-null argument information from the nullability
4527 // information on the parameter types (if we have them).
4528 if (Proto) {
4529 unsigned Index = 0;
4530 for (auto paramType : Proto->getParamTypes()) {
4531 if (isNonNullType(S.Context, paramType)) {
4532 if (NonNullArgs.empty())
4533 NonNullArgs.resize(Args.size());
4534
4535 NonNullArgs.set(Index);
4536 }
4537
4538 ++Index;
4539 }
4540 }
4541 }
4542
4543 // Check for non-null arguments.
4544 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4545 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4546 if (NonNullArgs[ArgIndex])
4547 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4548 }
4549}
4550
4551/// Warn if a pointer or reference argument passed to a function points to an
4552/// object that is less aligned than the parameter. This can happen when
4553/// creating a typedef with a lower alignment than the original type and then
4554/// calling functions defined in terms of the original type.
4555void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4556 StringRef ParamName, QualType ArgTy,
4557 QualType ParamTy) {
4558
4559 // If a function accepts a pointer or reference type
4560 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4561 return;
4562
4563 // If the parameter is a pointer type, get the pointee type for the
4564 // argument too. If the parameter is a reference type, don't try to get
4565 // the pointee type for the argument.
4566 if (ParamTy->isPointerType())
4567 ArgTy = ArgTy->getPointeeType();
4568
4569 // Remove reference or pointer
4570 ParamTy = ParamTy->getPointeeType();
4571
4572 // Find expected alignment, and the actual alignment of the passed object.
4573 // getTypeAlignInChars requires complete types
4574 if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
4575 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
4576 ArgTy->isUndeducedType())
4577 return;
4578
4579 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4580 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4581
4582 // If the argument is less aligned than the parameter, there is a
4583 // potential alignment issue.
4584 if (ArgAlign < ParamAlign)
4585 Diag(Loc, diag::warn_param_mismatched_alignment)
4586 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4587 << ParamName << FDecl;
4588}
4589
4590/// Handles the checks for format strings, non-POD arguments to vararg
4591/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4592/// attributes.
4593void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4594 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4595 bool IsMemberFunction, SourceLocation Loc,
4596 SourceRange Range, VariadicCallType CallType) {
4597 // FIXME: We should check as much as we can in the template definition.
4598 if (CurContext->isDependentContext())
4599 return;
4600
4601 // Printf and scanf checking.
4602 llvm::SmallBitVector CheckedVarArgs;
4603 if (FDecl) {
4604 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4605 // Only create vector if there are format attributes.
4606 CheckedVarArgs.resize(Args.size());
4607
4608 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4609 CheckedVarArgs);
4610 }
4611 }
4612
4613 // Refuse POD arguments that weren't caught by the format string
4614 // checks above.
4615 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4616 if (CallType != VariadicDoesNotApply &&
4617 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4618 unsigned NumParams = Proto ? Proto->getNumParams()
4619 : FDecl && isa<FunctionDecl>(FDecl)
4620 ? cast<FunctionDecl>(FDecl)->getNumParams()
4621 : FDecl && isa<ObjCMethodDecl>(FDecl)
4622 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4623 : 0;
4624
4625 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4626 // Args[ArgIdx] can be null in malformed code.
4627 if (const Expr *Arg = Args[ArgIdx]) {
4628 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4629 checkVariadicArgument(Arg, CallType);
4630 }
4631 }
4632 }
4633
4634 if (FDecl || Proto) {
4635 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4636
4637 // Type safety checking.
4638 if (FDecl) {
4639 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4640 CheckArgumentWithTypeTag(I, Args, Loc);
4641 }
4642 }
4643
4644 // Check that passed arguments match the alignment of original arguments.
4645 // Try to get the missing prototype from the declaration.
4646 if (!Proto && FDecl) {
4647 const auto *FT = FDecl->getFunctionType();
4648 if (isa_and_nonnull<FunctionProtoType>(FT))
4649 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4650 }
4651 if (Proto) {
4652 // For variadic functions, we may have more args than parameters.
4653 // For some K&R functions, we may have less args than parameters.
4654 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4655 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4656 // Args[ArgIdx] can be null in malformed code.
4657 if (const Expr *Arg = Args[ArgIdx]) {
4658 if (Arg->containsErrors())
4659 continue;
4660
4661 QualType ParamTy = Proto->getParamType(ArgIdx);
4662 QualType ArgTy = Arg->getType();
4663 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4664 ArgTy, ParamTy);
4665 }
4666 }
4667 }
4668
4669 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4670 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4671 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4672 if (!Arg->isValueDependent()) {
4673 Expr::EvalResult Align;
4674 if (Arg->EvaluateAsInt(Align, Context)) {
4675 const llvm::APSInt &I = Align.Val.getInt();
4676 if (!I.isPowerOf2())
4677 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4678 << Arg->getSourceRange();
4679
4680 if (I > Sema::MaximumAlignment)
4681 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4682 << Arg->getSourceRange() << Sema::MaximumAlignment;
4683 }
4684 }
4685 }
4686
4687 if (FD)
4688 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4689}
4690
4691/// CheckConstructorCall - Check a constructor call for correctness and safety
4692/// properties not enforced by the C type system.
4693void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4694 ArrayRef<const Expr *> Args,
4695 const FunctionProtoType *Proto,
4696 SourceLocation Loc) {
4697 VariadicCallType CallType =
4698 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4699
4700 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4701 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4702 Context.getPointerType(Ctor->getThisObjectType()));
4703
4704 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4705 Loc, SourceRange(), CallType);
4706}
4707
4708/// CheckFunctionCall - Check a direct function call for various correctness
4709/// and safety properties not strictly enforced by the C type system.
4710bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4711 const FunctionProtoType *Proto) {
4712 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1
Assuming 'TheCall' is not a 'CXXOperatorCallExpr'
4713 isa<CXXMethodDecl>(FDecl);
4714 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2
Assuming 'TheCall' is not a 'CXXMemberCallExpr'
4715 IsMemberOperatorCall;
4716 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4717 TheCall->getCallee());
4718 Expr** Args = TheCall->getArgs();
4719 unsigned NumArgs = TheCall->getNumArgs();
4720
4721 Expr *ImplicitThis = nullptr;
4722 if (IsMemberOperatorCall
2.1
'IsMemberOperatorCall' is false
) {
3
Taking false branch
4723 // If this is a call to a member operator, hide the first argument
4724 // from checkCall.
4725 // FIXME: Our choice of AST representation here is less than ideal.
4726 ImplicitThis = Args[0];
4727 ++Args;
4728 --NumArgs;
4729 } else if (IsMemberFunction
3.1
'IsMemberFunction' is false
)
4
Taking false branch
4730 ImplicitThis =
4731 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4732
4733 if (ImplicitThis
4.1
'ImplicitThis' is null
) {
5
Taking false branch
4734 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4735 // used.
4736 QualType ThisType = ImplicitThis->getType();
4737 if (!ThisType->isPointerType()) {
4738 assert(!ThisType->isReferenceType())(static_cast <bool> (!ThisType->isReferenceType()) ?
void (0) : __assert_fail ("!ThisType->isReferenceType()",
"/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 4738, __extension__ __PRETTY_FUNCTION__))
;
4739 ThisType = Context.getPointerType(ThisType);
4740 }
4741
4742 QualType ThisTypeFromDecl =
4743 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
4744
4745 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4746 ThisTypeFromDecl);
4747 }
4748
4749 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4750 IsMemberFunction, TheCall->getRParenLoc(),
4751 TheCall->getCallee()->getSourceRange(), CallType);
4752
4753 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4754 // None of the checks below are needed for functions that don't have
4755 // simple names (e.g., C++ conversion functions).
4756 if (!FnInfo)
6
Assuming 'FnInfo' is non-null
7
Taking false branch
4757 return false;
4758
4759 CheckTCBEnforcement(TheCall, FDecl);
4760
4761 CheckAbsoluteValueFunction(TheCall, FDecl);
4762 CheckMaxUnsignedZero(TheCall, FDecl);
4763
4764 if (getLangOpts().ObjC)
8
Assuming field 'ObjC' is 0
9
Taking false branch
4765 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4766
4767 unsigned CMId = FDecl->getMemoryFunctionKind();
4768
4769 // Handle memory setting and copying functions.
4770 switch (CMId) {
10
Control jumps to 'case BIfree:' at line 4780
4771 case 0:
4772 return false;
4773/* case Builtin::BIstrlcpy: // fallthrough
4774 case Builtin::BIstrlcat:
4775 CheckStrlcpycatArguments(TheCall, FnInfo);
4776 break;*/
4777 case Builtin::BIstrncat:
4778 CheckStrncatArguments(TheCall, FnInfo);
4779 break;
4780 case Builtin::BIfree:
4781 CheckFreeArguments(TheCall);
11
Calling 'Sema::CheckFreeArguments'
4782 break;
4783 default:
4784 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4785 }
4786
4787 return false;
4788}
4789
4790bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4791 ArrayRef<const Expr *> Args) {
4792 VariadicCallType CallType =
4793 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4794
4795 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4796 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4797 CallType);
4798
4799 return false;
4800}
4801
4802bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4803 const FunctionProtoType *Proto) {
4804 QualType Ty;
4805 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4806 Ty = V->getType().getNonReferenceType();
4807 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4808 Ty = F->getType().getNonReferenceType();
4809 else
4810 return false;
4811
4812 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4813 !Ty->isFunctionProtoType())
4814 return false;
4815
4816 VariadicCallType CallType;
4817 if (!Proto || !Proto->isVariadic()) {
4818 CallType = VariadicDoesNotApply;
4819 } else if (Ty->isBlockPointerType()) {
4820 CallType = VariadicBlock;
4821 } else { // Ty->isFunctionPointerType()
4822 CallType = VariadicFunction;
4823 }
4824
4825 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4826 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4827 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4828 TheCall->getCallee()->getSourceRange(), CallType);
4829
4830 return false;
4831}
4832
4833/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4834/// such as function pointers returned from functions.
4835bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4836 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4837 TheCall->getCallee());
4838 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4839 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4840 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4841 TheCall->getCallee()->getSourceRange(), CallType);
4842
4843 return false;
4844}
4845
4846static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4847 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4848 return false;
4849
4850 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4851 switch (Op) {
4852 case AtomicExpr::AO__c11_atomic_init:
4853 case AtomicExpr::AO__opencl_atomic_init:
4854 llvm_unreachable("There is no ordering argument for an init")::llvm::llvm_unreachable_internal("There is no ordering argument for an init"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 4854)
;
4855
4856 case AtomicExpr::AO__c11_atomic_load:
4857 case AtomicExpr::AO__opencl_atomic_load:
4858 case AtomicExpr::AO__atomic_load_n:
4859 case AtomicExpr::AO__atomic_load:
4860 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4861 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4862
4863 case AtomicExpr::AO__c11_atomic_store:
4864 case AtomicExpr::AO__opencl_atomic_store:
4865 case AtomicExpr::AO__atomic_store:
4866 case AtomicExpr::AO__atomic_store_n:
4867 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4868 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4869 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4870
4871 default:
4872 return true;
4873 }
4874}
4875
4876ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4877 AtomicExpr::AtomicOp Op) {
4878 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4879 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4880 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4881 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4882 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4883 Op);
4884}
4885
4886ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4887 SourceLocation RParenLoc, MultiExprArg Args,
4888 AtomicExpr::AtomicOp Op,
4889 AtomicArgumentOrder ArgOrder) {
4890 // All the non-OpenCL operations take one of the following forms.
4891 // The OpenCL operations take the __c11 forms with one extra argument for
4892 // synchronization scope.
4893 enum {
4894 // C __c11_atomic_init(A *, C)
4895 Init,
4896
4897 // C __c11_atomic_load(A *, int)
4898 Load,
4899
4900 // void __atomic_load(A *, CP, int)
4901 LoadCopy,
4902
4903 // void __atomic_store(A *, CP, int)
4904 Copy,
4905
4906 // C __c11_atomic_add(A *, M, int)
4907 Arithmetic,
4908
4909 // C __atomic_exchange_n(A *, CP, int)
4910 Xchg,
4911
4912 // void __atomic_exchange(A *, C *, CP, int)
4913 GNUXchg,
4914
4915 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4916 C11CmpXchg,
4917
4918 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4919 GNUCmpXchg
4920 } Form = Init;
4921
4922 const unsigned NumForm = GNUCmpXchg + 1;
4923 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4924 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4925 // where:
4926 // C is an appropriate type,
4927 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4928 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4929 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4930 // the int parameters are for orderings.
4931
4932 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4933 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4934 "need to update code for modified forms");
4935 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4936 AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4937 AtomicExpr::AO__atomic_load,
4938 "need to update code for modified C11 atomics");
4939 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4940 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4941 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4942 Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4943 IsOpenCL;
4944 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4945 Op == AtomicExpr::AO__atomic_store_n ||
4946 Op == AtomicExpr::AO__atomic_exchange_n ||
4947 Op == AtomicExpr::AO__atomic_compare_exchange_n;
4948 bool IsAddSub = false;
4949
4950 switch (Op) {
4951 case AtomicExpr::AO__c11_atomic_init:
4952 case AtomicExpr::AO__opencl_atomic_init:
4953 Form = Init;
4954 break;
4955
4956 case AtomicExpr::AO__c11_atomic_load:
4957 case AtomicExpr::AO__opencl_atomic_load:
4958 case AtomicExpr::AO__atomic_load_n:
4959 Form = Load;
4960 break;
4961
4962 case AtomicExpr::AO__atomic_load:
4963 Form = LoadCopy;
4964 break;
4965
4966 case AtomicExpr::AO__c11_atomic_store:
4967 case AtomicExpr::AO__opencl_atomic_store:
4968 case AtomicExpr::AO__atomic_store:
4969 case AtomicExpr::AO__atomic_store_n:
4970 Form = Copy;
4971 break;
4972
4973 case AtomicExpr::AO__c11_atomic_fetch_add:
4974 case AtomicExpr::AO__c11_atomic_fetch_sub:
4975 case AtomicExpr::AO__opencl_atomic_fetch_add:
4976 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4977 case AtomicExpr::AO__atomic_fetch_add:
4978 case AtomicExpr::AO__atomic_fetch_sub:
4979 case AtomicExpr::AO__atomic_add_fetch:
4980 case AtomicExpr::AO__atomic_sub_fetch:
4981 IsAddSub = true;
4982 Form = Arithmetic;
4983 break;
4984 case AtomicExpr::AO__c11_atomic_fetch_and:
4985 case AtomicExpr::AO__c11_atomic_fetch_or:
4986 case AtomicExpr::AO__c11_atomic_fetch_xor:
4987 case AtomicExpr::AO__opencl_atomic_fetch_and:
4988 case AtomicExpr::AO__opencl_atomic_fetch_or:
4989 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4990 case AtomicExpr::AO__atomic_fetch_and:
4991 case AtomicExpr::AO__atomic_fetch_or:
4992 case AtomicExpr::AO__atomic_fetch_xor:
4993 case AtomicExpr::AO__atomic_fetch_nand:
4994 case AtomicExpr::AO__atomic_and_fetch:
4995 case AtomicExpr::AO__atomic_or_fetch:
4996 case AtomicExpr::AO__atomic_xor_fetch:
4997 case AtomicExpr::AO__atomic_nand_fetch:
4998 Form = Arithmetic;
4999 break;
5000 case AtomicExpr::AO__c11_atomic_fetch_min:
5001 case AtomicExpr::AO__c11_atomic_fetch_max:
5002 case AtomicExpr::AO__opencl_atomic_fetch_min:
5003 case AtomicExpr::AO__opencl_atomic_fetch_max:
5004 case AtomicExpr::AO__atomic_min_fetch:
5005 case AtomicExpr::AO__atomic_max_fetch:
5006 case AtomicExpr::AO__atomic_fetch_min:
5007 case AtomicExpr::AO__atomic_fetch_max:
5008 Form = Arithmetic;
5009 break;
5010
5011 case AtomicExpr::AO__c11_atomic_exchange:
5012 case AtomicExpr::AO__opencl_atomic_exchange:
5013 case AtomicExpr::AO__atomic_exchange_n:
5014 Form = Xchg;
5015 break;
5016
5017 case AtomicExpr::AO__atomic_exchange:
5018 Form = GNUXchg;
5019 break;
5020
5021 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5022 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5023 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5024 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5025 Form = C11CmpXchg;
5026 break;
5027
5028 case AtomicExpr::AO__atomic_compare_exchange:
5029 case AtomicExpr::AO__atomic_compare_exchange_n:
5030 Form = GNUCmpXchg;
5031 break;
5032 }
5033
5034 unsigned AdjustedNumArgs = NumArgs[Form];
5035 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5036 ++AdjustedNumArgs;
5037 // Check we have the right number of arguments.
5038 if (Args.size() < AdjustedNumArgs) {
5039 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5040 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5041 << ExprRange;
5042 return ExprError();
5043 } else if (Args.size() > AdjustedNumArgs) {
5044 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5045 diag::err_typecheck_call_too_many_args)
5046 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5047 << ExprRange;
5048 return ExprError();
5049 }
5050
5051 // Inspect the first argument of the atomic operation.
5052 Expr *Ptr = Args[0];
5053 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5054 if (ConvertedPtr.isInvalid())
5055 return ExprError();
5056
5057 Ptr = ConvertedPtr.get();
5058 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5059 if (!pointerType) {
5060 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5061 << Ptr->getType() << Ptr->getSourceRange();
5062 return ExprError();
5063 }
5064
5065 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5066 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5067 QualType ValType = AtomTy; // 'C'
5068 if (IsC11) {
5069 if (!AtomTy->isAtomicType()) {
5070 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5071 << Ptr->getType() << Ptr->getSourceRange();
5072 return ExprError();
5073 }
5074 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5075 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5076 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5077 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5078 << Ptr->getSourceRange();
5079 return ExprError();
5080 }
5081 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5082 } else if (Form != Load && Form != LoadCopy) {
5083 if (ValType.isConstQualified()) {
5084 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5085 << Ptr->getType() << Ptr->getSourceRange();
5086 return ExprError();
5087 }
5088 }
5089
5090 // For an arithmetic operation, the implied arithmetic must be well-formed.
5091 if (Form == Arithmetic) {
5092 // gcc does not enforce these rules for GNU atomics, but we do so for
5093 // sanity.
5094 auto IsAllowedValueType = [&](QualType ValType) {
5095 if (ValType->isIntegerType())
5096 return true;
5097 if (ValType->isPointerType())
5098 return true;
5099 if (!ValType->isFloatingType())
5100 return false;
5101 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5102 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5103 &Context.getTargetInfo().getLongDoubleFormat() ==
5104 &llvm::APFloat::x87DoubleExtended())
5105 return false;
5106 return true;
5107 };
5108 if (IsAddSub && !IsAllowedValueType(ValType)) {
5109 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5110 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5111 return ExprError();
5112 }
5113 if (!IsAddSub && !ValType->isIntegerType()) {
5114 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5115 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5116 return ExprError();
5117 }
5118 if (IsC11 && ValType->isPointerType() &&
5119 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5120 diag::err_incomplete_type)) {
5121 return ExprError();
5122 }
5123 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5124 // For __atomic_*_n operations, the value type must be a scalar integral or
5125 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5126 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5127 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5128 return ExprError();
5129 }
5130
5131 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5132 !AtomTy->isScalarType()) {
5133 // For GNU atomics, require a trivially-copyable type. This is not part of
5134 // the GNU atomics specification, but we enforce it for sanity.
5135 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5136 << Ptr->getType() << Ptr->getSourceRange();
5137 return ExprError();
5138 }
5139
5140 switch (ValType.getObjCLifetime()) {
5141 case Qualifiers::OCL_None:
5142 case Qualifiers::OCL_ExplicitNone:
5143 // okay
5144 break;
5145
5146 case Qualifiers::OCL_Weak:
5147 case Qualifiers::OCL_Strong:
5148 case Qualifiers::OCL_Autoreleasing:
5149 // FIXME: Can this happen? By this point, ValType should be known
5150 // to be trivially copyable.
5151 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5152 << ValType << Ptr->getSourceRange();
5153 return ExprError();
5154 }
5155
5156 // All atomic operations have an overload which takes a pointer to a volatile
5157 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
5158 // into the result or the other operands. Similarly atomic_load takes a
5159 // pointer to a const 'A'.
5160 ValType.removeLocalVolatile();
5161 ValType.removeLocalConst();
5162 QualType ResultType = ValType;
5163 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5164 Form == Init)
5165 ResultType = Context.VoidTy;
5166 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5167 ResultType = Context.BoolTy;
5168
5169 // The type of a parameter passed 'by value'. In the GNU atomics, such
5170 // arguments are actually passed as pointers.
5171 QualType ByValType = ValType; // 'CP'
5172 bool IsPassedByAddress = false;
5173 if (!IsC11 && !IsN) {
5174 ByValType = Ptr->getType();
5175 IsPassedByAddress = true;
5176 }
5177
5178 SmallVector<Expr *, 5> APIOrderedArgs;
5179 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5180 APIOrderedArgs.push_back(Args[0]);
5181 switch (Form) {
5182 case Init:
5183 case Load:
5184 APIOrderedArgs.push_back(Args[1]); // Val1/Order
5185 break;
5186 case LoadCopy:
5187 case Copy:
5188 case Arithmetic:
5189 case Xchg:
5190 APIOrderedArgs.push_back(Args[2]); // Val1
5191 APIOrderedArgs.push_back(Args[1]); // Order
5192 break;
5193 case GNUXchg:
5194 APIOrderedArgs.push_back(Args[2]); // Val1
5195 APIOrderedArgs.push_back(Args[3]); // Val2
5196 APIOrderedArgs.push_back(Args[1]); // Order
5197 break;
5198 case C11CmpXchg:
5199 APIOrderedArgs.push_back(Args[2]); // Val1
5200 APIOrderedArgs.push_back(Args[4]); // Val2
5201 APIOrderedArgs.push_back(Args[1]); // Order
5202 APIOrderedArgs.push_back(Args[3]); // OrderFail
5203 break;
5204 case GNUCmpXchg:
5205 APIOrderedArgs.push_back(Args[2]); // Val1
5206 APIOrderedArgs.push_back(Args[4]); // Val2
5207 APIOrderedArgs.push_back(Args[5]); // Weak
5208 APIOrderedArgs.push_back(Args[1]); // Order
5209 APIOrderedArgs.push_back(Args[3]); // OrderFail
5210 break;
5211 }
5212 } else
5213 APIOrderedArgs.append(Args.begin(), Args.end());
5214
5215 // The first argument's non-CV pointer type is used to deduce the type of
5216 // subsequent arguments, except for:
5217 // - weak flag (always converted to bool)
5218 // - memory order (always converted to int)
5219 // - scope (always converted to int)
5220 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5221 QualType Ty;
5222 if (i < NumVals[Form] + 1) {
5223 switch (i) {
5224 case 0:
5225 // The first argument is always a pointer. It has a fixed type.
5226 // It is always dereferenced, a nullptr is undefined.
5227 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5228 // Nothing else to do: we already know all we want about this pointer.
5229 continue;
5230 case 1:
5231 // The second argument is the non-atomic operand. For arithmetic, this
5232 // is always passed by value, and for a compare_exchange it is always
5233 // passed by address. For the rest, GNU uses by-address and C11 uses
5234 // by-value.
5235 assert(Form != Load)(static_cast <bool> (Form != Load) ? void (0) : __assert_fail
("Form != Load", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 5235, __extension__ __PRETTY_FUNCTION__))
;
5236 if (Form == Arithmetic && ValType->isPointerType())
5237 Ty = Context.getPointerDiffType();
5238 else if (Form == Init || Form == Arithmetic)
5239 Ty = ValType;
5240 else if (Form == Copy || Form == Xchg) {
5241 if (IsPassedByAddress) {
5242 // The value pointer is always dereferenced, a nullptr is undefined.
5243 CheckNonNullArgument(*this, APIOrderedArgs[i],
5244 ExprRange.getBegin());
5245 }
5246 Ty = ByValType;
5247 } else {
5248 Expr *ValArg = APIOrderedArgs[i];
5249 // The value pointer is always dereferenced, a nullptr is undefined.
5250 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5251 LangAS AS = LangAS::Default;
5252 // Keep address space of non-atomic pointer type.
5253 if (const PointerType *PtrTy =
5254 ValArg->getType()->getAs<PointerType>()) {
5255 AS = PtrTy->getPointeeType().getAddressSpace();
5256 }
5257 Ty = Context.getPointerType(
5258 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5259 }
5260 break;
5261 case 2:
5262 // The third argument to compare_exchange / GNU exchange is the desired
5263 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5264 if (IsPassedByAddress)
5265 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5266 Ty = ByValType;
5267 break;
5268 case 3:
5269 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5270 Ty = Context.BoolTy;
5271 break;
5272 }
5273 } else {
5274 // The order(s) and scope are always converted to int.
5275 Ty = Context.IntTy;
5276 }
5277
5278 InitializedEntity Entity =
5279 InitializedEntity::InitializeParameter(Context, Ty, false);
5280 ExprResult Arg = APIOrderedArgs[i];
5281 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5282 if (Arg.isInvalid())
5283 return true;
5284 APIOrderedArgs[i] = Arg.get();
5285 }
5286
5287 // Permute the arguments into a 'consistent' order.
5288 SmallVector<Expr*, 5> SubExprs;
5289 SubExprs.push_back(Ptr);
5290 switch (Form) {
5291 case Init:
5292 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5293 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5294 break;
5295 case Load:
5296 SubExprs.push_back(APIOrderedArgs[1]); // Order
5297 break;
5298 case LoadCopy:
5299 case Copy:
5300 case Arithmetic:
5301 case Xchg:
5302 SubExprs.push_back(APIOrderedArgs[2]); // Order
5303 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5304 break;
5305 case GNUXchg:
5306 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5307 SubExprs.push_back(APIOrderedArgs[3]); // Order
5308 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5309 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5310 break;
5311 case C11CmpXchg:
5312 SubExprs.push_back(APIOrderedArgs[3]); // Order
5313 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5314 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5315 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5316 break;
5317 case GNUCmpXchg:
5318 SubExprs.push_back(APIOrderedArgs[4]); // Order
5319 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5320 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5321 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5322 SubExprs.push_back(APIOrderedArgs[3]); // Weak
5323 break;
5324 }
5325
5326 if (SubExprs.size() >= 2 && Form != Init) {
5327 if (Optional<llvm::APSInt> Result =
5328 SubExprs[1]->getIntegerConstantExpr(Context))
5329 if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5330 Diag(SubExprs[1]->getBeginLoc(),
5331 diag::warn_atomic_op_has_invalid_memory_order)
5332 << SubExprs[1]->getSourceRange();
5333 }
5334
5335 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5336 auto *Scope = Args[Args.size() - 1];
5337 if (Optional<llvm::APSInt> Result =
5338 Scope->getIntegerConstantExpr(Context)) {
5339 if (!ScopeModel->isValid(Result->getZExtValue()))
5340 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5341 << Scope->getSourceRange();
5342 }
5343 SubExprs.push_back(Scope);
5344 }
5345
5346 AtomicExpr *AE = new (Context)
5347 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5348
5349 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5350 Op == AtomicExpr::AO__c11_atomic_store ||
5351 Op == AtomicExpr::AO__opencl_atomic_load ||
5352 Op == AtomicExpr::AO__opencl_atomic_store ) &&
5353 Context.AtomicUsesUnsupportedLibcall(AE))
5354 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5355 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5356 Op == AtomicExpr::AO__opencl_atomic_load)
5357 ? 0
5358 : 1);
5359
5360 if (ValType->isExtIntType()) {
5361 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5362 return ExprError();
5363 }
5364
5365 return AE;
5366}
5367
5368/// checkBuiltinArgument - Given a call to a builtin function, perform
5369/// normal type-checking on the given argument, updating the call in
5370/// place. This is useful when a builtin function requires custom
5371/// type-checking for some of its arguments but not necessarily all of
5372/// them.
5373///
5374/// Returns true on error.
5375static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5376 FunctionDecl *Fn = E->getDirectCallee();
5377 assert(Fn && "builtin call without direct callee!")(static_cast <bool> (Fn && "builtin call without direct callee!"
) ? void (0) : __assert_fail ("Fn && \"builtin call without direct callee!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 5377, __extension__ __PRETTY_FUNCTION__))
;
5378
5379 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5380 InitializedEntity Entity =
5381 InitializedEntity::InitializeParameter(S.Context, Param);
5382
5383 ExprResult Arg = E->getArg(0);
5384 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5385 if (Arg.isInvalid())
5386 return true;
5387
5388 E->setArg(ArgIndex, Arg.get());
5389 return false;
5390}
5391
5392/// We have a call to a function like __sync_fetch_and_add, which is an
5393/// overloaded function based on the pointer type of its first argument.
5394/// The main BuildCallExpr routines have already promoted the types of
5395/// arguments because all of these calls are prototyped as void(...).
5396///
5397/// This function goes through and does final semantic checking for these
5398/// builtins, as well as generating any warnings.
5399ExprResult
5400Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5401 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5402 Expr *Callee = TheCall->getCallee();
5403 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5404 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5405
5406 // Ensure that we have at least one argument to do type inference from.
5407 if (TheCall->getNumArgs() < 1) {
5408 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5409 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5410 return ExprError();
5411 }
5412
5413 // Inspect the first argument of the atomic builtin. This should always be
5414 // a pointer type, whose element is an integral scalar or pointer type.
5415 // Because it is a pointer type, we don't have to worry about any implicit
5416 // casts here.
5417 // FIXME: We don't allow floating point scalars as input.
5418 Expr *FirstArg = TheCall->getArg(0);
5419 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5420 if (FirstArgResult.isInvalid())
5421 return ExprError();
5422 FirstArg = FirstArgResult.get();
5423 TheCall->setArg(0, FirstArg);
5424
5425 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5426 if (!pointerType) {
5427 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5428 << FirstArg->getType() << FirstArg->getSourceRange();
5429 return ExprError();
5430 }
5431
5432 QualType ValType = pointerType->getPointeeType();
5433 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5434 !ValType->isBlockPointerType()) {
5435 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5436 << FirstArg->getType() << FirstArg->getSourceRange();
5437 return ExprError();
5438 }
5439
5440 if (ValType.isConstQualified()) {
5441 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5442 << FirstArg->getType() << FirstArg->getSourceRange();
5443 return ExprError();
5444 }
5445
5446 switch (ValType.getObjCLifetime()) {
5447 case Qualifiers::OCL_None:
5448 case Qualifiers::OCL_ExplicitNone:
5449 // okay
5450 break;
5451
5452 case Qualifiers::OCL_Weak:
5453 case Qualifiers::OCL_Strong:
5454 case Qualifiers::OCL_Autoreleasing:
5455 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5456 << ValType << FirstArg->getSourceRange();
5457 return ExprError();
5458 }
5459
5460 // Strip any qualifiers off ValType.
5461 ValType = ValType.getUnqualifiedType();
5462
5463 // The majority of builtins return a value, but a few have special return
5464 // types, so allow them to override appropriately below.
5465 QualType ResultType = ValType;
5466
5467 // We need to figure out which concrete builtin this maps onto. For example,
5468 // __sync_fetch_and_add with a 2 byte object turns into
5469 // __sync_fetch_and_add_2.
5470#define BUILTIN_ROW(x) \
5471 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5472 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5473
5474 static const unsigned BuiltinIndices[][5] = {
5475 BUILTIN_ROW(__sync_fetch_and_add),
5476 BUILTIN_ROW(__sync_fetch_and_sub),
5477 BUILTIN_ROW(__sync_fetch_and_or),
5478 BUILTIN_ROW(__sync_fetch_and_and),
5479 BUILTIN_ROW(__sync_fetch_and_xor),
5480 BUILTIN_ROW(__sync_fetch_and_nand),
5481
5482 BUILTIN_ROW(__sync_add_and_fetch),
5483 BUILTIN_ROW(__sync_sub_and_fetch),
5484 BUILTIN_ROW(__sync_and_and_fetch),
5485 BUILTIN_ROW(__sync_or_and_fetch),
5486 BUILTIN_ROW(__sync_xor_and_fetch),
5487 BUILTIN_ROW(__sync_nand_and_fetch),
5488
5489 BUILTIN_ROW(__sync_val_compare_and_swap),
5490 BUILTIN_ROW(__sync_bool_compare_and_swap),
5491 BUILTIN_ROW(__sync_lock_test_and_set),
5492 BUILTIN_ROW(__sync_lock_release),
5493 BUILTIN_ROW(__sync_swap)
5494 };
5495#undef BUILTIN_ROW
5496
5497 // Determine the index of the size.
5498 unsigned SizeIndex;
5499 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5500 case 1: SizeIndex = 0; break;
5501 case 2: SizeIndex = 1; break;
5502 case 4: SizeIndex = 2; break;
5503 case 8: SizeIndex = 3; break;
5504 case 16: SizeIndex = 4; break;
5505 default:
5506 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5507 << FirstArg->getType() << FirstArg->getSourceRange();
5508 return ExprError();
5509 }
5510
5511 // Each of these builtins has one pointer argument, followed by some number of
5512 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5513 // that we ignore. Find out which row of BuiltinIndices to read from as well
5514 // as the number of fixed args.
5515 unsigned BuiltinID = FDecl->getBuiltinID();
5516 unsigned BuiltinIndex, NumFixed = 1;
5517 bool WarnAboutSemanticsChange = false;
5518 switch (BuiltinID) {
5519 default: llvm_unreachable("Unknown overloaded atomic builtin!")::llvm::llvm_unreachable_internal("Unknown overloaded atomic builtin!"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 5519)
;
5520 case Builtin::BI__sync_fetch_and_add:
5521 case Builtin::BI__sync_fetch_and_add_1:
5522 case Builtin::BI__sync_fetch_and_add_2:
5523 case Builtin::BI__sync_fetch_and_add_4:
5524 case Builtin::BI__sync_fetch_and_add_8:
5525 case Builtin::BI__sync_fetch_and_add_16:
5526 BuiltinIndex = 0;
5527 break;
5528
5529 case Builtin::BI__sync_fetch_and_sub:
5530 case Builtin::BI__sync_fetch_and_sub_1:
5531 case Builtin::BI__sync_fetch_and_sub_2:
5532 case Builtin::BI__sync_fetch_and_sub_4:
5533 case Builtin::BI__sync_fetch_and_sub_8:
5534 case Builtin::BI__sync_fetch_and_sub_16:
5535 BuiltinIndex = 1;
5536 break;
5537
5538 case Builtin::BI__sync_fetch_and_or:
5539 case Builtin::BI__sync_fetch_and_or_1:
5540 case Builtin::BI__sync_fetch_and_or_2:
5541 case Builtin::BI__sync_fetch_and_or_4:
5542 case Builtin::BI__sync_fetch_and_or_8:
5543 case Builtin::BI__sync_fetch_and_or_16:
5544 BuiltinIndex = 2;
5545 break;
5546
5547 case Builtin::BI__sync_fetch_and_and:
5548 case Builtin::BI__sync_fetch_and_and_1:
5549 case Builtin::BI__sync_fetch_and_and_2:
5550 case Builtin::BI__sync_fetch_and_and_4:
5551 case Builtin::BI__sync_fetch_and_and_8:
5552 case Builtin::BI__sync_fetch_and_and_16:
5553 BuiltinIndex = 3;
5554 break;
5555
5556 case Builtin::BI__sync_fetch_and_xor:
5557 case Builtin::BI__sync_fetch_and_xor_1:
5558 case Builtin::BI__sync_fetch_and_xor_2:
5559 case Builtin::BI__sync_fetch_and_xor_4:
5560 case Builtin::BI__sync_fetch_and_xor_8:
5561 case Builtin::BI__sync_fetch_and_xor_16:
5562 BuiltinIndex = 4;
5563 break;
5564
5565 case Builtin::BI__sync_fetch_and_nand:
5566 case Builtin::BI__sync_fetch_and_nand_1:
5567 case Builtin::BI__sync_fetch_and_nand_2:
5568 case Builtin::BI__sync_fetch_and_nand_4:
5569 case Builtin::BI__sync_fetch_and_nand_8:
5570 case Builtin::BI__sync_fetch_and_nand_16:
5571 BuiltinIndex = 5;
5572 WarnAboutSemanticsChange = true;
5573 break;
5574
5575 case Builtin::BI__sync_add_and_fetch:
5576 case Builtin::BI__sync_add_and_fetch_1:
5577 case Builtin::BI__sync_add_and_fetch_2:
5578 case Builtin::BI__sync_add_and_fetch_4:
5579 case Builtin::BI__sync_add_and_fetch_8:
5580 case Builtin::BI__sync_add_and_fetch_16:
5581 BuiltinIndex = 6;
5582 break;
5583
5584 case Builtin::BI__sync_sub_and_fetch:
5585 case Builtin::BI__sync_sub_and_fetch_1:
5586 case Builtin::BI__sync_sub_and_fetch_2:
5587 case Builtin::BI__sync_sub_and_fetch_4:
5588 case Builtin::BI__sync_sub_and_fetch_8:
5589 case Builtin::BI__sync_sub_and_fetch_16:
5590 BuiltinIndex = 7;
5591 break;
5592
5593 case Builtin::BI__sync_and_and_fetch:
5594 case Builtin::BI__sync_and_and_fetch_1:
5595 case Builtin::BI__sync_and_and_fetch_2:
5596 case Builtin::BI__sync_and_and_fetch_4:
5597 case Builtin::BI__sync_and_and_fetch_8:
5598 case Builtin::BI__sync_and_and_fetch_16:
5599 BuiltinIndex = 8;
5600 break;
5601
5602 case Builtin::BI__sync_or_and_fetch:
5603 case Builtin::BI__sync_or_and_fetch_1:
5604 case Builtin::BI__sync_or_and_fetch_2:
5605 case Builtin::BI__sync_or_and_fetch_4:
5606 case Builtin::BI__sync_or_and_fetch_8:
5607 case Builtin::BI__sync_or_and_fetch_16:
5608 BuiltinIndex = 9;
5609 break;
5610
5611 case Builtin::BI__sync_xor_and_fetch:
5612 case Builtin::BI__sync_xor_and_fetch_1:
5613 case Builtin::BI__sync_xor_and_fetch_2:
5614 case Builtin::BI__sync_xor_and_fetch_4:
5615 case Builtin::BI__sync_xor_and_fetch_8:
5616 case Builtin::BI__sync_xor_and_fetch_16:
5617 BuiltinIndex = 10;
5618 break;
5619
5620 case Builtin::BI__sync_nand_and_fetch:
5621 case Builtin::BI__sync_nand_and_fetch_1:
5622 case Builtin::BI__sync_nand_and_fetch_2:
5623 case Builtin::BI__sync_nand_and_fetch_4:
5624 case Builtin::BI__sync_nand_and_fetch_8:
5625 case Builtin::BI__sync_nand_and_fetch_16:
5626 BuiltinIndex = 11;
5627 WarnAboutSemanticsChange = true;
5628 break;
5629
5630 case Builtin::BI__sync_val_compare_and_swap:
5631 case Builtin::BI__sync_val_compare_and_swap_1:
5632 case Builtin::BI__sync_val_compare_and_swap_2:
5633 case Builtin::BI__sync_val_compare_and_swap_4:
5634 case Builtin::BI__sync_val_compare_and_swap_8:
5635 case Builtin::BI__sync_val_compare_and_swap_16:
5636 BuiltinIndex = 12;
5637 NumFixed = 2;
5638 break;
5639
5640 case Builtin::BI__sync_bool_compare_and_swap:
5641 case Builtin::BI__sync_bool_compare_and_swap_1:
5642 case Builtin::BI__sync_bool_compare_and_swap_2:
5643 case Builtin::BI__sync_bool_compare_and_swap_4:
5644 case Builtin::BI__sync_bool_compare_and_swap_8:
5645 case Builtin::BI__sync_bool_compare_and_swap_16:
5646 BuiltinIndex = 13;
5647 NumFixed = 2;
5648 ResultType = Context.BoolTy;
5649 break;
5650
5651 case Builtin::BI__sync_lock_test_and_set:
5652 case Builtin::BI__sync_lock_test_and_set_1:
5653 case Builtin::BI__sync_lock_test_and_set_2:
5654 case Builtin::BI__sync_lock_test_and_set_4:
5655 case Builtin::BI__sync_lock_test_and_set_8:
5656 case Builtin::BI__sync_lock_test_and_set_16:
5657 BuiltinIndex = 14;
5658 break;
5659
5660 case Builtin::BI__sync_lock_release:
5661 case Builtin::BI__sync_lock_release_1:
5662 case Builtin::BI__sync_lock_release_2:
5663 case Builtin::BI__sync_lock_release_4:
5664 case Builtin::BI__sync_lock_release_8:
5665 case Builtin::BI__sync_lock_release_16:
5666 BuiltinIndex = 15;
5667 NumFixed = 0;
5668 ResultType = Context.VoidTy;
5669 break;
5670
5671 case Builtin::BI__sync_swap:
5672 case Builtin::BI__sync_swap_1:
5673 case Builtin::BI__sync_swap_2:
5674 case Builtin::BI__sync_swap_4:
5675 case Builtin::BI__sync_swap_8:
5676 case Builtin::BI__sync_swap_16:
5677 BuiltinIndex = 16;
5678 break;
5679 }
5680
5681 // Now that we know how many fixed arguments we expect, first check that we
5682 // have at least that many.
5683 if (TheCall->getNumArgs() < 1+NumFixed) {
5684 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5685 << 0 << 1 + NumFixed << TheCall->getNumArgs()
5686 << Callee->getSourceRange();
5687 return ExprError();
5688 }
5689
5690 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5691 << Callee->getSourceRange();
5692
5693 if (WarnAboutSemanticsChange) {
5694 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5695 << Callee->getSourceRange();
5696 }
5697
5698 // Get the decl for the concrete builtin from this, we can tell what the
5699 // concrete integer type we should convert to is.
5700 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5701 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5702 FunctionDecl *NewBuiltinDecl;
5703 if (NewBuiltinID == BuiltinID)
5704 NewBuiltinDecl = FDecl;
5705 else {
5706 // Perform builtin lookup to avoid redeclaring it.
5707 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5708 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5709 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5710 assert(Res.getFoundDecl())(static_cast <bool> (Res.getFoundDecl()) ? void (0) : __assert_fail
("Res.getFoundDecl()", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 5710, __extension__ __PRETTY_FUNCTION__))
;
5711 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5712 if (!NewBuiltinDecl)
5713 return ExprError();
5714 }
5715
5716 // The first argument --- the pointer --- has a fixed type; we
5717 // deduce the types of the rest of the arguments accordingly. Walk
5718 // the remaining arguments, converting them to the deduced value type.
5719 for (unsigned i = 0; i != NumFixed; ++i) {
5720 ExprResult Arg = TheCall->getArg(i+1);
5721
5722 // GCC does an implicit conversion to the pointer or integer ValType. This
5723 // can fail in some cases (1i -> int**), check for this error case now.
5724 // Initialize the argument.
5725 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5726 ValType, /*consume*/ false);
5727 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5728 if (Arg.isInvalid())
5729 return ExprError();
5730
5731 // Okay, we have something that *can* be converted to the right type. Check
5732 // to see if there is a potentially weird extension going on here. This can
5733 // happen when you do an atomic operation on something like an char* and
5734 // pass in 42. The 42 gets converted to char. This is even more strange
5735 // for things like 45.123 -> char, etc.
5736 // FIXME: Do this check.
5737 TheCall->setArg(i+1, Arg.get());
5738 }
5739
5740 // Create a new DeclRefExpr to refer to the new decl.
5741 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5742 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5743 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5744 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5745
5746 // Set the callee in the CallExpr.
5747 // FIXME: This loses syntactic information.
5748 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5749 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5750 CK_BuiltinFnToFnPtr);
5751 TheCall->setCallee(PromotedCall.get());
5752
5753 // Change the result type of the call to match the original value type. This
5754 // is arbitrary, but the codegen for these builtins ins design to handle it
5755 // gracefully.
5756 TheCall->setType(ResultType);
5757
5758 // Prohibit use of _ExtInt with atomic builtins.
5759 // The arguments would have already been converted to the first argument's
5760 // type, so only need to check the first argument.
5761 const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5762 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5763 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5764 return ExprError();
5765 }
5766
5767 return TheCallResult;
5768}
5769
5770/// SemaBuiltinNontemporalOverloaded - We have a call to
5771/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5772/// overloaded function based on the pointer type of its last argument.
5773///
5774/// This function goes through and does final semantic checking for these
5775/// builtins.
5776ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5777 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5778 DeclRefExpr *DRE =
5779 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5780 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5781 unsigned BuiltinID = FDecl->getBuiltinID();
5782 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||(static_cast <bool> ((BuiltinID == Builtin::BI__builtin_nontemporal_store
|| BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
"Unexpected nontemporal load/store builtin!") ? void (0) : __assert_fail
("(BuiltinID == Builtin::BI__builtin_nontemporal_store || BuiltinID == Builtin::BI__builtin_nontemporal_load) && \"Unexpected nontemporal load/store builtin!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 5784, __extension__ __PRETTY_FUNCTION__))
5783 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&(static_cast <bool> ((BuiltinID == Builtin::BI__builtin_nontemporal_store
|| BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
"Unexpected nontemporal load/store builtin!") ? void (0) : __assert_fail
("(BuiltinID == Builtin::BI__builtin_nontemporal_store || BuiltinID == Builtin::BI__builtin_nontemporal_load) && \"Unexpected nontemporal load/store builtin!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 5784, __extension__ __PRETTY_FUNCTION__))
5784 "Unexpected nontemporal load/store builtin!")(static_cast <bool> ((BuiltinID == Builtin::BI__builtin_nontemporal_store
|| BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
"Unexpected nontemporal load/store builtin!") ? void (0) : __assert_fail
("(BuiltinID == Builtin::BI__builtin_nontemporal_store || BuiltinID == Builtin::BI__builtin_nontemporal_load) && \"Unexpected nontemporal load/store builtin!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaChecking.cpp"
, 5784, __extension__ __PRETTY_FUNCTION__))
;
5785 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5786 unsigned numArgs = isStore ? 2 : 1;
5787
5788 // Ensure that we have the proper number of arguments.
5789 if (checkArgCount(*this, TheCall, numArgs))
5790 return ExprError();
5791
5792 // Inspect the last argument of the nontemporal builtin. This should always
5793 // be a pointer type, from which we imply the type of the memory access.
5794 // Because it is a pointer type, we don't have to worry about any implicit
5795 // casts here.
5796 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5797 ExprResult PointerArgResult =
5798 DefaultFunctionArrayLvalueConversion(PointerArg);
5799
5800 if (PointerArgResult.isInvalid())
5801 return ExprError();
5802 PointerArg = PointerArgResult.get();
5803 TheCall->setArg(numArgs - 1, PointerArg);
5804
5805 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5806 if (!pointerType) {
5807 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5808 << PointerArg->getType() << PointerArg->getSourceRange();
5809 return ExprError();
5810 }
5811
5812 QualType ValType = pointerType->getPointeeType();
5813
5814 // Strip any qualifiers off ValType.
5815 ValType = ValType.getUnqualifiedType();
5816 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5817 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5818 !ValType->isVectorType()) {
5819 Diag(DRE->getBeginLoc(),
5820 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5821 << PointerArg->getType() << PointerArg->getSourceRange();
5822 return ExprError();
5823 }
5824
5825 if (!isStore) {
5826 TheCall->setType(ValType);
5827 return TheCallResult;
5828 }
5829
5830 ExprResult ValArg = TheCall->getArg(0);
5831 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5832 Context, ValType, /*consume*/ false);
5833 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5834 if (ValArg.isInvalid())
5835 return ExprError();
5836
5837 TheCall->setArg(0, ValArg.get());
5838 TheCall->setType(Context.VoidTy);
5839 return TheCallResult;
5840}
5841
5842/// CheckObjCString - Checks that the argument to the builtin
5843/// CFString constructor is correct
5844/// Note: It might also make sense to do the UTF-16 conversion here (would
5845/// simplify the backend).
5846bool Sema::CheckObjCString(Expr *Arg) {
5847 Arg = Arg->IgnoreParenCasts();
5848 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5849
5850 if (!Literal || !Literal->isAscii()) {
5851 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5852 << Arg->getSourceRange();
5853 return true;
5854 }
5855
5856 if (Literal->containsNonAsciiOrNull()) {
5857 StringRef String = Literal->getString();
5858 unsigned NumBytes = String.size();
5859 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5860 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5861 llvm::UTF16 *ToPtr = &ToBuf[0];
5862
5863 llvm::ConversionResult Result =
5864 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5865 ToPtr + NumBytes, llvm::strictConversion);
5866 // Check for conversion failure.
5867 if (Result != llvm::conversionOK)
5868 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5869 << Arg->getSourceRange();
5870 }
5871 return false;
5872}
5873
5874/// CheckObjCString - Checks that the format string argument to the os_log()
5875/// and os_trace() functions is correct, and converts it to const char *.
5876ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5877 Arg = Arg->IgnoreParenCasts();
5878 auto *Literal = dyn_cast<StringLiteral>(Arg);
5879 if (!Literal) {
5880 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5881 Literal = ObjcLiteral->getString();
5882 }
5883 }
5884
5885 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5886 return ExprError(
5887 Diag(Arg->getBe