Bug Summary

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