clang 19.0.0git
SemaChecking.cpp
Go to the documentation of this file.
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"
16#include "clang/AST/Attr.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"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
30#include "clang/AST/NSAPI.h"
34#include "clang/AST/Stmt.h"
36#include "clang/AST/Type.h"
37#include "clang/AST/TypeLoc.h"
43#include "clang/Basic/LLVM.h"
56#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
58#include "clang/Sema/Lookup.h"
60#include "clang/Sema/Scope.h"
62#include "clang/Sema/Sema.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/STLExtras.h"
71#include "llvm/ADT/SmallBitVector.h"
72#include "llvm/ADT/SmallPtrSet.h"
73#include "llvm/ADT/SmallString.h"
74#include "llvm/ADT/SmallVector.h"
75#include "llvm/ADT/StringExtras.h"
76#include "llvm/ADT/StringRef.h"
77#include "llvm/ADT/StringSet.h"
78#include "llvm/ADT/StringSwitch.h"
79#include "llvm/Support/AtomicOrdering.h"
80#include "llvm/Support/Casting.h"
81#include "llvm/Support/Compiler.h"
82#include "llvm/Support/ConvertUTF.h"
83#include "llvm/Support/ErrorHandling.h"
84#include "llvm/Support/Format.h"
85#include "llvm/Support/Locale.h"
86#include "llvm/Support/MathExtras.h"
87#include "llvm/Support/SaveAndRestore.h"
88#include "llvm/Support/raw_ostream.h"
89#include "llvm/TargetParser/RISCVTargetParser.h"
90#include "llvm/TargetParser/Triple.h"
91#include <algorithm>
92#include <bitset>
93#include <cassert>
94#include <cctype>
95#include <cstddef>
96#include <cstdint>
97#include <functional>
98#include <limits>
99#include <optional>
100#include <string>
101#include <tuple>
102#include <utility>
103
104using namespace clang;
105using namespace sema;
106
108 unsigned ByteNo) const {
109 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
111}
112
113static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
115 return (A << 8) | B;
116}
117
118/// Checks that a call expression's argument count is at least the desired
119/// number. This is useful when doing custom type-checking on a variadic
120/// function. Returns true on error.
122 unsigned MinArgCount) {
123 unsigned ArgCount = Call->getNumArgs();
124 if (ArgCount >= MinArgCount)
125 return false;
126
127 return S.Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
128 << 0 /*function call*/ << MinArgCount << ArgCount
129 << /*is non object*/ 0 << Call->getSourceRange();
130}
131
132/// Checks that a call expression's argument count is at most the desired
133/// number. This is useful when doing custom type-checking on a variadic
134/// function. Returns true on error.
135static bool checkArgCountAtMost(Sema &S, CallExpr *Call, unsigned MaxArgCount) {
136 unsigned ArgCount = Call->getNumArgs();
137 if (ArgCount <= MaxArgCount)
138 return false;
139 return S.Diag(Call->getEndLoc(),
140 diag::err_typecheck_call_too_many_args_at_most)
141 << 0 /*function call*/ << MaxArgCount << ArgCount
142 << /*is non object*/ 0 << Call->getSourceRange();
143}
144
145/// Checks that a call expression's argument count is in the desired range. This
146/// is useful when doing custom type-checking on a variadic function. Returns
147/// true on error.
148static bool checkArgCountRange(Sema &S, CallExpr *Call, unsigned MinArgCount,
149 unsigned MaxArgCount) {
150 return checkArgCountAtLeast(S, Call, MinArgCount) ||
151 checkArgCountAtMost(S, Call, MaxArgCount);
152}
153
154/// Checks that a call expression's argument count is the desired number.
155/// This is useful when doing custom type-checking. Returns true on error.
156static bool checkArgCount(Sema &S, CallExpr *Call, unsigned DesiredArgCount) {
157 unsigned ArgCount = Call->getNumArgs();
158 if (ArgCount == DesiredArgCount)
159 return false;
160
161 if (checkArgCountAtLeast(S, Call, DesiredArgCount))
162 return true;
163 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
164
165 // Highlight all the excess arguments.
166 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
167 Call->getArg(ArgCount - 1)->getEndLoc());
168
169 return S.Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
170 << 0 /*function call*/ << DesiredArgCount << ArgCount
171 << /*is non object*/ 0 << Call->getArg(1)->getSourceRange();
172}
173
175 if (Value->isTypeDependent())
176 return false;
177
178 InitializedEntity Entity =
182 if (Result.isInvalid())
183 return true;
184 Value = Result.get();
185 return false;
186}
187
188/// Check that the first argument to __builtin_annotation is an integer
189/// and the second argument is a non-wide string literal.
190static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
191 if (checkArgCount(S, TheCall, 2))
192 return true;
193
194 // First argument should be an integer.
195 Expr *ValArg = TheCall->getArg(0);
196 QualType Ty = ValArg->getType();
197 if (!Ty->isIntegerType()) {
198 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
199 << ValArg->getSourceRange();
200 return true;
201 }
202
203 // Second argument should be a constant string.
204 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
205 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
206 if (!Literal || !Literal->isOrdinary()) {
207 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
208 << StrArg->getSourceRange();
209 return true;
210 }
211
212 TheCall->setType(Ty);
213 return false;
214}
215
216static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
217 // We need at least one argument.
218 if (TheCall->getNumArgs() < 1) {
219 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
220 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
221 << TheCall->getCallee()->getSourceRange();
222 return true;
223 }
224
225 // All arguments should be wide string literals.
226 for (Expr *Arg : TheCall->arguments()) {
227 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
228 if (!Literal || !Literal->isWide()) {
229 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
230 << Arg->getSourceRange();
231 return true;
232 }
233 }
234
235 return false;
236}
237
238/// Check that the argument to __builtin_addressof is a glvalue, and set the
239/// result type to the corresponding pointer type.
240static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
241 if (checkArgCount(S, TheCall, 1))
242 return true;
243
244 ExprResult Arg(TheCall->getArg(0));
245 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
246 if (ResultType.isNull())
247 return true;
248
249 TheCall->setArg(0, Arg.get());
250 TheCall->setType(ResultType);
251 return false;
252}
253
254/// Check that the argument to __builtin_function_start is a function.
255static bool SemaBuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
256 if (checkArgCount(S, TheCall, 1))
257 return true;
258
260 if (Arg.isInvalid())
261 return true;
262
263 TheCall->setArg(0, Arg.get());
264 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
266
267 if (!FD) {
268 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
269 << TheCall->getSourceRange();
270 return true;
271 }
272
273 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
274 TheCall->getBeginLoc());
275}
276
277/// Check the number of arguments and set the result type to
278/// the argument type.
279static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
280 if (checkArgCount(S, TheCall, 1))
281 return true;
282
283 TheCall->setType(TheCall->getArg(0)->getType());
284 return false;
285}
286
287/// Check that the value argument for __builtin_is_aligned(value, alignment) and
288/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
289/// type (but not a function pointer) and that the alignment is a power-of-two.
290static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
291 if (checkArgCount(S, TheCall, 2))
292 return true;
293
294 clang::Expr *Source = TheCall->getArg(0);
295 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
296
297 auto IsValidIntegerType = [](QualType Ty) {
298 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
299 };
300 QualType SrcTy = Source->getType();
301 // We should also be able to use it with arrays (but not functions!).
302 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
303 SrcTy = S.Context.getDecayedType(SrcTy);
304 }
305 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
306 SrcTy->isFunctionPointerType()) {
307 // FIXME: this is not quite the right error message since we don't allow
308 // floating point types, or member pointers.
309 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
310 << SrcTy;
311 return true;
312 }
313
314 clang::Expr *AlignOp = TheCall->getArg(1);
315 if (!IsValidIntegerType(AlignOp->getType())) {
316 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
317 << AlignOp->getType();
318 return true;
319 }
320 Expr::EvalResult AlignResult;
321 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
322 // We can't check validity of alignment if it is value dependent.
323 if (!AlignOp->isValueDependent() &&
324 AlignOp->EvaluateAsInt(AlignResult, S.Context,
326 llvm::APSInt AlignValue = AlignResult.Val.getInt();
327 llvm::APSInt MaxValue(
328 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
329 if (AlignValue < 1) {
330 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
331 return true;
332 }
333 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
334 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
335 << toString(MaxValue, 10);
336 return true;
337 }
338 if (!AlignValue.isPowerOf2()) {
339 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
340 return true;
341 }
342 if (AlignValue == 1) {
343 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
344 << IsBooleanAlignBuiltin;
345 }
346 }
347
350 SourceLocation(), Source);
351 if (SrcArg.isInvalid())
352 return true;
353 TheCall->setArg(0, SrcArg.get());
354 ExprResult AlignArg =
356 S.Context, AlignOp->getType(), false),
357 SourceLocation(), AlignOp);
358 if (AlignArg.isInvalid())
359 return true;
360 TheCall->setArg(1, AlignArg.get());
361 // For align_up/align_down, the return type is the same as the (potentially
362 // decayed) argument type including qualifiers. For is_aligned(), the result
363 // is always bool.
364 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
365 return false;
366}
367
368static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
369 unsigned BuiltinID) {
370 if (checkArgCount(S, TheCall, 3))
371 return true;
372
373 std::pair<unsigned, const char *> Builtins[] = {
374 { Builtin::BI__builtin_add_overflow, "ckd_add" },
375 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
376 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
377 };
378
379 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
380 const char *> &P) {
381 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
383 S.getSourceManager(), S.getLangOpts()) == P.second;
384 });
385
386 auto ValidCkdIntType = [](QualType QT) {
387 // A valid checked integer type is an integer type other than a plain char,
388 // bool, a bit-precise type, or an enumeration type.
389 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
390 return (BT->getKind() >= BuiltinType::Short &&
391 BT->getKind() <= BuiltinType::Int128) || (
392 BT->getKind() >= BuiltinType::UShort &&
393 BT->getKind() <= BuiltinType::UInt128) ||
394 BT->getKind() == BuiltinType::UChar ||
395 BT->getKind() == BuiltinType::SChar;
396 return false;
397 };
398
399 // First two arguments should be integers.
400 for (unsigned I = 0; I < 2; ++I) {
402 if (Arg.isInvalid()) return true;
403 TheCall->setArg(I, Arg.get());
404
405 QualType Ty = Arg.get()->getType();
406 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
407 if (!IsValid) {
408 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
409 << CkdOperation << Ty << Arg.get()->getSourceRange();
410 return true;
411 }
412 }
413
414 // Third argument should be a pointer to a non-const integer.
415 // IRGen correctly handles volatile, restrict, and address spaces, and
416 // the other qualifiers aren't possible.
417 {
419 if (Arg.isInvalid()) return true;
420 TheCall->setArg(2, Arg.get());
421
422 QualType Ty = Arg.get()->getType();
423 const auto *PtrTy = Ty->getAs<PointerType>();
424 if (!PtrTy ||
425 !PtrTy->getPointeeType()->isIntegerType() ||
426 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
427 PtrTy->getPointeeType().isConstQualified()) {
428 S.Diag(Arg.get()->getBeginLoc(),
429 diag::err_overflow_builtin_must_be_ptr_int)
430 << CkdOperation << Ty << Arg.get()->getSourceRange();
431 return true;
432 }
433 }
434
435 // Disallow signed bit-precise integer args larger than 128 bits to mul
436 // function until we improve backend support.
437 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
438 for (unsigned I = 0; I < 3; ++I) {
439 const auto Arg = TheCall->getArg(I);
440 // Third argument will be a pointer.
441 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
442 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
443 S.getASTContext().getIntWidth(Ty) > 128)
444 return S.Diag(Arg->getBeginLoc(),
445 diag::err_overflow_builtin_bit_int_max_size)
446 << 128;
447 }
448 }
449
450 return false;
451}
452
453namespace {
454struct BuiltinDumpStructGenerator {
455 Sema &S;
456 CallExpr *TheCall;
457 SourceLocation Loc = TheCall->getBeginLoc();
459 DiagnosticErrorTrap ErrorTracker;
460 PrintingPolicy Policy;
461
462 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
463 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
464 Policy(S.Context.getPrintingPolicy()) {
465 Policy.AnonymousTagLocations = false;
466 }
467
468 Expr *makeOpaqueValueExpr(Expr *Inner) {
469 auto *OVE = new (S.Context)
470 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
471 Inner->getObjectKind(), Inner);
472 Actions.push_back(OVE);
473 return OVE;
474 }
475
476 Expr *getStringLiteral(llvm::StringRef Str) {
478 // Wrap the literal in parentheses to attach a source location.
479 return new (S.Context) ParenExpr(Loc, Loc, Lit);
480 }
481
482 bool callPrintFunction(llvm::StringRef Format,
483 llvm::ArrayRef<Expr *> Exprs = {}) {
485 assert(TheCall->getNumArgs() >= 2);
486 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
487 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
488 Args.push_back(getStringLiteral(Format));
489 Args.insert(Args.end(), Exprs.begin(), Exprs.end());
490
491 // Register a note to explain why we're performing the call.
494 Ctx.PointOfInstantiation = Loc;
495 Ctx.CallArgs = Args.data();
496 Ctx.NumCallArgs = Args.size();
498
499 ExprResult RealCall =
500 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
501 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
502
504 if (!RealCall.isInvalid())
505 Actions.push_back(RealCall.get());
506 // Bail out if we've hit any errors, even if we managed to build the
507 // call. We don't want to produce more than one error.
508 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
509 }
510
511 Expr *getIndentString(unsigned Depth) {
512 if (!Depth)
513 return nullptr;
514
516 Indent.resize(Depth * Policy.Indentation, ' ');
517 return getStringLiteral(Indent);
518 }
519
521 return getStringLiteral(T.getAsString(Policy));
522 }
523
524 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
525 llvm::raw_svector_ostream OS(Str);
526
527 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
528 // than trying to print a single character.
529 if (auto *BT = T->getAs<BuiltinType>()) {
530 switch (BT->getKind()) {
531 case BuiltinType::Bool:
532 OS << "%d";
533 return true;
534 case BuiltinType::Char_U:
535 case BuiltinType::UChar:
536 OS << "%hhu";
537 return true;
538 case BuiltinType::Char_S:
539 case BuiltinType::SChar:
540 OS << "%hhd";
541 return true;
542 default:
543 break;
544 }
545 }
546
548 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
549 // We were able to guess how to format this.
550 if (Specifier.getConversionSpecifier().getKind() ==
551 analyze_printf::PrintfConversionSpecifier::sArg) {
552 // Wrap double-quotes around a '%s' specifier and limit its maximum
553 // length. Ideally we'd also somehow escape special characters in the
554 // contents but printf doesn't support that.
555 // FIXME: '%s' formatting is not safe in general.
556 OS << '"';
557 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
558 Specifier.toString(OS);
559 OS << '"';
560 // FIXME: It would be nice to include a '...' if the string doesn't fit
561 // in the length limit.
562 } else {
563 Specifier.toString(OS);
564 }
565 return true;
566 }
567
568 if (T->isPointerType()) {
569 // Format all pointers with '%p'.
570 OS << "%p";
571 return true;
572 }
573
574 return false;
575 }
576
577 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
578 Expr *IndentLit = getIndentString(Depth);
579 Expr *TypeLit = getTypeString(S.Context.getRecordType(RD));
580 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
581 : callPrintFunction("%s", {TypeLit}))
582 return true;
583
584 return dumpRecordValue(RD, E, IndentLit, Depth);
585 }
586
587 // Dump a record value. E should be a pointer or lvalue referring to an RD.
588 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
589 unsigned Depth) {
590 // FIXME: Decide what to do if RD is a union. At least we should probably
591 // turn off printing `const char*` members with `%s`, because that is very
592 // likely to crash if that's not the active member. Whatever we decide, we
593 // should document it.
594
595 // Build an OpaqueValueExpr so we can refer to E more than once without
596 // triggering re-evaluation.
597 Expr *RecordArg = makeOpaqueValueExpr(E);
598 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
599
600 if (callPrintFunction(" {\n"))
601 return true;
602
603 // Dump each base class, regardless of whether they're aggregates.
604 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
605 for (const auto &Base : CXXRD->bases()) {
606 QualType BaseType =
607 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
608 : S.Context.getLValueReferenceType(Base.getType());
610 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
611 RecordArg);
612 if (BasePtr.isInvalid() ||
613 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
614 Depth + 1))
615 return true;
616 }
617 }
618
619 Expr *FieldIndentArg = getIndentString(Depth + 1);
620
621 // Dump each field.
622 for (auto *D : RD->decls()) {
623 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
624 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
625 if (!FD || FD->isUnnamedBitfield() || FD->isAnonymousStructOrUnion())
626 continue;
627
628 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
629 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
630 getTypeString(FD->getType()),
631 getStringLiteral(FD->getName())};
632
633 if (FD->isBitField()) {
634 Format += ": %zu ";
636 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
637 FD->getBitWidthValue(S.Context));
638 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
639 }
640
641 Format += "=";
642
645 CXXScopeSpec(), Loc, IFD,
646 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
648 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
650 DeclarationNameInfo(FD->getDeclName(), Loc));
651 if (Field.isInvalid())
652 return true;
653
654 auto *InnerRD = FD->getType()->getAsRecordDecl();
655 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
656 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
657 // Recursively print the values of members of aggregate record type.
658 if (callPrintFunction(Format, Args) ||
659 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
660 return true;
661 } else {
662 Format += " ";
663 if (appendFormatSpecifier(FD->getType(), Format)) {
664 // We know how to print this field.
665 Args.push_back(Field.get());
666 } else {
667 // We don't know how to print this field. Print out its address
668 // with a format specifier that a smart tool will be able to
669 // recognize and treat specially.
670 Format += "*%p";
671 ExprResult FieldAddr =
672 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
673 if (FieldAddr.isInvalid())
674 return true;
675 Args.push_back(FieldAddr.get());
676 }
677 Format += "\n";
678 if (callPrintFunction(Format, Args))
679 return true;
680 }
681 }
682
683 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
684 : callPrintFunction("}\n");
685 }
686
687 Expr *buildWrapper() {
688 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
690 TheCall->setType(Wrapper->getType());
691 TheCall->setValueKind(Wrapper->getValueKind());
692 return Wrapper;
693 }
694};
695} // namespace
696
698 if (checkArgCountAtLeast(S, TheCall, 2))
699 return ExprError();
700
701 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
702 if (PtrArgResult.isInvalid())
703 return ExprError();
704 TheCall->setArg(0, PtrArgResult.get());
705
706 // First argument should be a pointer to a struct.
707 QualType PtrArgType = PtrArgResult.get()->getType();
708 if (!PtrArgType->isPointerType() ||
709 !PtrArgType->getPointeeType()->isRecordType()) {
710 S.Diag(PtrArgResult.get()->getBeginLoc(),
711 diag::err_expected_struct_pointer_argument)
712 << 1 << TheCall->getDirectCallee() << PtrArgType;
713 return ExprError();
714 }
715 QualType Pointee = PtrArgType->getPointeeType();
716 const RecordDecl *RD = Pointee->getAsRecordDecl();
717 // Try to instantiate the class template as appropriate; otherwise, access to
718 // its data() may lead to a crash.
719 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
720 diag::err_incomplete_type))
721 return ExprError();
722 // Second argument is a callable, but we can't fully validate it until we try
723 // calling it.
724 QualType FnArgType = TheCall->getArg(1)->getType();
725 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
726 !FnArgType->isBlockPointerType() &&
727 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
728 auto *BT = FnArgType->getAs<BuiltinType>();
729 switch (BT ? BT->getKind() : BuiltinType::Void) {
730 case BuiltinType::Dependent:
731 case BuiltinType::Overload:
732 case BuiltinType::BoundMember:
733 case BuiltinType::PseudoObject:
734 case BuiltinType::UnknownAny:
735 case BuiltinType::BuiltinFn:
736 // This might be a callable.
737 break;
738
739 default:
740 S.Diag(TheCall->getArg(1)->getBeginLoc(),
741 diag::err_expected_callable_argument)
742 << 2 << TheCall->getDirectCallee() << FnArgType;
743 return ExprError();
744 }
745 }
746
747 BuiltinDumpStructGenerator Generator(S, TheCall);
748
749 // Wrap parentheses around the given pointer. This is not necessary for
750 // correct code generation, but it means that when we pretty-print the call
751 // arguments in our diagnostics we will produce '(&s)->n' instead of the
752 // incorrect '&s->n'.
753 Expr *PtrArg = PtrArgResult.get();
754 PtrArg = new (S.Context)
755 ParenExpr(PtrArg->getBeginLoc(),
756 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
757 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
758 return ExprError();
759
760 return Generator.buildWrapper();
761}
762
763static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
764 if (checkArgCount(S, BuiltinCall, 2))
765 return true;
766
767 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
768 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
769 Expr *Call = BuiltinCall->getArg(0);
770 Expr *Chain = BuiltinCall->getArg(1);
771
772 if (Call->getStmtClass() != Stmt::CallExprClass) {
773 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
774 << Call->getSourceRange();
775 return true;
776 }
777
778 auto CE = cast<CallExpr>(Call);
779 if (CE->getCallee()->getType()->isBlockPointerType()) {
780 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
781 << Call->getSourceRange();
782 return true;
783 }
784
785 const Decl *TargetDecl = CE->getCalleeDecl();
786 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
787 if (FD->getBuiltinID()) {
788 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
789 << Call->getSourceRange();
790 return true;
791 }
792
793 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
794 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
795 << Call->getSourceRange();
796 return true;
797 }
798
799 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
800 if (ChainResult.isInvalid())
801 return true;
802 if (!ChainResult.get()->getType()->isPointerType()) {
803 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
804 << Chain->getSourceRange();
805 return true;
806 }
807
808 QualType ReturnTy = CE->getCallReturnType(S.Context);
809 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
810 QualType BuiltinTy = S.Context.getFunctionType(
811 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
812 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
813
814 Builtin =
815 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
816
817 BuiltinCall->setType(CE->getType());
818 BuiltinCall->setValueKind(CE->getValueKind());
819 BuiltinCall->setObjectKind(CE->getObjectKind());
820 BuiltinCall->setCallee(Builtin);
821 BuiltinCall->setArg(1, ChainResult.get());
822
823 return false;
824}
825
826namespace {
827
828class ScanfDiagnosticFormatHandler
830 // Accepts the argument index (relative to the first destination index) of the
831 // argument whose size we want.
832 using ComputeSizeFunction =
833 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
834
835 // Accepts the argument index (relative to the first destination index), the
836 // destination size, and the source size).
837 using DiagnoseFunction =
838 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
839
840 ComputeSizeFunction ComputeSizeArgument;
841 DiagnoseFunction Diagnose;
842
843public:
844 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
845 DiagnoseFunction Diagnose)
846 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
847
848 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
849 const char *StartSpecifier,
850 unsigned specifierLen) override {
851 if (!FS.consumesDataArgument())
852 return true;
853
854 unsigned NulByte = 0;
855 switch ((FS.getConversionSpecifier().getKind())) {
856 default:
857 return true;
860 NulByte = 1;
861 break;
863 break;
864 }
865
866 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
867 if (FW.getHowSpecified() !=
868 analyze_format_string::OptionalAmount::HowSpecified::Constant)
869 return true;
870
871 unsigned SourceSize = FW.getConstantAmount() + NulByte;
872
873 std::optional<llvm::APSInt> DestSizeAPS =
874 ComputeSizeArgument(FS.getArgIndex());
875 if (!DestSizeAPS)
876 return true;
877
878 unsigned DestSize = DestSizeAPS->getZExtValue();
879
880 if (DestSize < SourceSize)
881 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
882
883 return true;
884 }
885};
886
887class EstimateSizeFormatHandler
889 size_t Size;
890 /// Whether the format string contains Linux kernel's format specifier
891 /// extension.
892 bool IsKernelCompatible = true;
893
894public:
895 EstimateSizeFormatHandler(StringRef Format)
896 : Size(std::min(Format.find(0), Format.size()) +
897 1 /* null byte always written by sprintf */) {}
898
899 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
900 const char *, unsigned SpecifierLen,
901 const TargetInfo &) override {
902
903 const size_t FieldWidth = computeFieldWidth(FS);
904 const size_t Precision = computePrecision(FS);
905
906 // The actual format.
907 switch (FS.getConversionSpecifier().getKind()) {
908 // Just a char.
911 Size += std::max(FieldWidth, (size_t)1);
912 break;
913 // Just an integer.
923 Size += std::max(FieldWidth, Precision);
924 break;
925
926 // %g style conversion switches between %f or %e style dynamically.
927 // %g removes trailing zeros, and does not print decimal point if there are
928 // no digits that follow it. Thus %g can print a single digit.
929 // FIXME: If it is alternative form:
930 // For g and G conversions, trailing zeros are not removed from the result.
933 Size += 1;
934 break;
935
936 // Floating point number in the form '[+]ddd.ddd'.
939 Size += std::max(FieldWidth, 1 /* integer part */ +
940 (Precision ? 1 + Precision
941 : 0) /* period + decimal */);
942 break;
943
944 // Floating point number in the form '[-]d.ddde[+-]dd'.
947 Size +=
948 std::max(FieldWidth,
949 1 /* integer part */ +
950 (Precision ? 1 + Precision : 0) /* period + decimal */ +
951 1 /* e or E letter */ + 2 /* exponent */);
952 break;
953
954 // Floating point number in the form '[-]0xh.hhhhp±dd'.
957 Size +=
958 std::max(FieldWidth,
959 2 /* 0x */ + 1 /* integer part */ +
960 (Precision ? 1 + Precision : 0) /* period + decimal */ +
961 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
962 break;
963
964 // Just a string.
967 Size += FieldWidth;
968 break;
969
970 // Just a pointer in the form '0xddd'.
972 // Linux kernel has its own extesion for `%p` specifier.
973 // Kernel Document:
974 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
975 IsKernelCompatible = false;
976 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
977 break;
978
979 // A plain percent.
981 Size += 1;
982 break;
983
984 default:
985 break;
986 }
987
988 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
989
990 if (FS.hasAlternativeForm()) {
991 switch (FS.getConversionSpecifier().getKind()) {
992 // For o conversion, it increases the precision, if and only if necessary,
993 // to force the first digit of the result to be a zero
994 // (if the value and precision are both 0, a single 0 is printed)
996 // For b conversion, a nonzero result has 0b prefixed to it.
998 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
999 // it.
1002 // Note: even when the prefix is added, if
1003 // (prefix_width <= FieldWidth - formatted_length) holds,
1004 // the prefix does not increase the format
1005 // size. e.g.(("%#3x", 0xf) is "0xf")
1006
1007 // If the result is zero, o, b, x, X adds nothing.
1008 break;
1009 // For a, A, e, E, f, F, g, and G conversions,
1010 // the result of converting a floating-point number always contains a
1011 // decimal-point
1020 Size += (Precision ? 0 : 1);
1021 break;
1022 // For other conversions, the behavior is undefined.
1023 default:
1024 break;
1025 }
1026 }
1027 assert(SpecifierLen <= Size && "no underflow");
1028 Size -= SpecifierLen;
1029 return true;
1030 }
1031
1032 size_t getSizeLowerBound() const { return Size; }
1033 bool isKernelCompatible() const { return IsKernelCompatible; }
1034
1035private:
1036 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1037 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1038 size_t FieldWidth = 0;
1040 FieldWidth = FW.getConstantAmount();
1041 return FieldWidth;
1042 }
1043
1044 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1045 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1046 size_t Precision = 0;
1047
1048 // See man 3 printf for default precision value based on the specifier.
1049 switch (FW.getHowSpecified()) {
1051 switch (FS.getConversionSpecifier().getKind()) {
1052 default:
1053 break;
1057 Precision = 1;
1058 break;
1065 Precision = 1;
1066 break;
1073 Precision = 6;
1074 break;
1076 Precision = 1;
1077 break;
1078 }
1079 break;
1081 Precision = FW.getConstantAmount();
1082 break;
1083 default:
1084 break;
1085 }
1086 return Precision;
1087 }
1088};
1089
1090} // namespace
1091
1092static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1093 StringRef &FormatStrRef, size_t &StrLen,
1094 ASTContext &Context) {
1095 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1096 Format && (Format->isOrdinary() || Format->isUTF8())) {
1097 FormatStrRef = Format->getString();
1098 const ConstantArrayType *T =
1099 Context.getAsConstantArrayType(Format->getType());
1100 assert(T && "String literal not of constant array type!");
1101 size_t TypeSize = T->getSize().getZExtValue();
1102 // In case there's a null byte somewhere.
1103 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1104 return true;
1105 }
1106 return false;
1107}
1108
1109void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1110 CallExpr *TheCall) {
1111 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1113 return;
1114
1115 bool UseDABAttr = false;
1116 const FunctionDecl *UseDecl = FD;
1117
1118 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1119 if (DABAttr) {
1120 UseDecl = DABAttr->getFunction();
1121 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1122 UseDABAttr = true;
1123 }
1124
1125 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1126
1127 if (!BuiltinID)
1128 return;
1129
1130 const TargetInfo &TI = getASTContext().getTargetInfo();
1131 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1132
1133 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1134 // If we refer to a diagnose_as_builtin attribute, we need to change the
1135 // argument index to refer to the arguments of the called function. Unless
1136 // the index is out of bounds, which presumably means it's a variadic
1137 // function.
1138 if (!UseDABAttr)
1139 return Index;
1140 unsigned DABIndices = DABAttr->argIndices_size();
1141 unsigned NewIndex = Index < DABIndices
1142 ? DABAttr->argIndices_begin()[Index]
1143 : Index - DABIndices + FD->getNumParams();
1144 if (NewIndex >= TheCall->getNumArgs())
1145 return std::nullopt;
1146 return NewIndex;
1147 };
1148
1149 auto ComputeExplicitObjectSizeArgument =
1150 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1151 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1152 if (!IndexOptional)
1153 return std::nullopt;
1154 unsigned NewIndex = *IndexOptional;
1156 Expr *SizeArg = TheCall->getArg(NewIndex);
1157 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1158 return std::nullopt;
1159 llvm::APSInt Integer = Result.Val.getInt();
1160 Integer.setIsUnsigned(true);
1161 return Integer;
1162 };
1163
1164 auto ComputeSizeArgument =
1165 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1166 // If the parameter has a pass_object_size attribute, then we should use its
1167 // (potentially) more strict checking mode. Otherwise, conservatively assume
1168 // type 0.
1169 int BOSType = 0;
1170 // This check can fail for variadic functions.
1171 if (Index < FD->getNumParams()) {
1172 if (const auto *POS =
1173 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1174 BOSType = POS->getType();
1175 }
1176
1177 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1178 if (!IndexOptional)
1179 return std::nullopt;
1180 unsigned NewIndex = *IndexOptional;
1181
1182 if (NewIndex >= TheCall->getNumArgs())
1183 return std::nullopt;
1184
1185 const Expr *ObjArg = TheCall->getArg(NewIndex);
1187 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
1188 return std::nullopt;
1189
1190 // Get the object size in the target's size_t width.
1191 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
1192 };
1193
1194 auto ComputeStrLenArgument =
1195 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1196 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1197 if (!IndexOptional)
1198 return std::nullopt;
1199 unsigned NewIndex = *IndexOptional;
1200
1201 const Expr *ObjArg = TheCall->getArg(NewIndex);
1203 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
1204 return std::nullopt;
1205 // Add 1 for null byte.
1206 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
1207 };
1208
1209 std::optional<llvm::APSInt> SourceSize;
1210 std::optional<llvm::APSInt> DestinationSize;
1211 unsigned DiagID = 0;
1212 bool IsChkVariant = false;
1213
1214 auto GetFunctionName = [&]() {
1215 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
1216 // Skim off the details of whichever builtin was called to produce a better
1217 // diagnostic, as it's unlikely that the user wrote the __builtin
1218 // explicitly.
1219 if (IsChkVariant) {
1220 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1221 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1222 } else {
1223 FunctionName.consume_front("__builtin_");
1224 }
1225 return FunctionName;
1226 };
1227
1228 switch (BuiltinID) {
1229 default:
1230 return;
1231 case Builtin::BI__builtin_strcpy:
1232 case Builtin::BIstrcpy: {
1233 DiagID = diag::warn_fortify_strlen_overflow;
1234 SourceSize = ComputeStrLenArgument(1);
1235 DestinationSize = ComputeSizeArgument(0);
1236 break;
1237 }
1238
1239 case Builtin::BI__builtin___strcpy_chk: {
1240 DiagID = diag::warn_fortify_strlen_overflow;
1241 SourceSize = ComputeStrLenArgument(1);
1242 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1243 IsChkVariant = true;
1244 break;
1245 }
1246
1247 case Builtin::BIscanf:
1248 case Builtin::BIfscanf:
1249 case Builtin::BIsscanf: {
1250 unsigned FormatIndex = 1;
1251 unsigned DataIndex = 2;
1252 if (BuiltinID == Builtin::BIscanf) {
1253 FormatIndex = 0;
1254 DataIndex = 1;
1255 }
1256
1257 const auto *FormatExpr =
1258 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1259
1260 StringRef FormatStrRef;
1261 size_t StrLen;
1262 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1263 return;
1264
1265 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1266 unsigned SourceSize) {
1267 DiagID = diag::warn_fortify_scanf_overflow;
1268 unsigned Index = ArgIndex + DataIndex;
1269 StringRef FunctionName = GetFunctionName();
1270 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1271 PDiag(DiagID) << FunctionName << (Index + 1)
1272 << DestSize << SourceSize);
1273 };
1274
1275 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1276 return ComputeSizeArgument(Index + DataIndex);
1277 };
1278 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1279 const char *FormatBytes = FormatStrRef.data();
1281 FormatBytes + StrLen, getLangOpts(),
1283
1284 // Unlike the other cases, in this one we have already issued the diagnostic
1285 // here, so no need to continue (because unlike the other cases, here the
1286 // diagnostic refers to the argument number).
1287 return;
1288 }
1289
1290 case Builtin::BIsprintf:
1291 case Builtin::BI__builtin___sprintf_chk: {
1292 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1293 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1294
1295 StringRef FormatStrRef;
1296 size_t StrLen;
1297 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1298 EstimateSizeFormatHandler H(FormatStrRef);
1299 const char *FormatBytes = FormatStrRef.data();
1301 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1302 Context.getTargetInfo(), false)) {
1303 DiagID = H.isKernelCompatible()
1304 ? diag::warn_format_overflow
1305 : diag::warn_format_overflow_non_kprintf;
1306 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1307 .extOrTrunc(SizeTypeWidth);
1308 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1309 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1310 IsChkVariant = true;
1311 } else {
1312 DestinationSize = ComputeSizeArgument(0);
1313 }
1314 break;
1315 }
1316 }
1317 return;
1318 }
1319 case Builtin::BI__builtin___memcpy_chk:
1320 case Builtin::BI__builtin___memmove_chk:
1321 case Builtin::BI__builtin___memset_chk:
1322 case Builtin::BI__builtin___strlcat_chk:
1323 case Builtin::BI__builtin___strlcpy_chk:
1324 case Builtin::BI__builtin___strncat_chk:
1325 case Builtin::BI__builtin___strncpy_chk:
1326 case Builtin::BI__builtin___stpncpy_chk:
1327 case Builtin::BI__builtin___memccpy_chk:
1328 case Builtin::BI__builtin___mempcpy_chk: {
1329 DiagID = diag::warn_builtin_chk_overflow;
1330 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1331 DestinationSize =
1332 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1333 IsChkVariant = true;
1334 break;
1335 }
1336
1337 case Builtin::BI__builtin___snprintf_chk:
1338 case Builtin::BI__builtin___vsnprintf_chk: {
1339 DiagID = diag::warn_builtin_chk_overflow;
1340 SourceSize = ComputeExplicitObjectSizeArgument(1);
1341 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1342 IsChkVariant = true;
1343 break;
1344 }
1345
1346 case Builtin::BIstrncat:
1347 case Builtin::BI__builtin_strncat:
1348 case Builtin::BIstrncpy:
1349 case Builtin::BI__builtin_strncpy:
1350 case Builtin::BIstpncpy:
1351 case Builtin::BI__builtin_stpncpy: {
1352 // Whether these functions overflow depends on the runtime strlen of the
1353 // string, not just the buffer size, so emitting the "always overflow"
1354 // diagnostic isn't quite right. We should still diagnose passing a buffer
1355 // size larger than the destination buffer though; this is a runtime abort
1356 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1357 DiagID = diag::warn_fortify_source_size_mismatch;
1358 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1359 DestinationSize = ComputeSizeArgument(0);
1360 break;
1361 }
1362
1363 case Builtin::BImemcpy:
1364 case Builtin::BI__builtin_memcpy:
1365 case Builtin::BImemmove:
1366 case Builtin::BI__builtin_memmove:
1367 case Builtin::BImemset:
1368 case Builtin::BI__builtin_memset:
1369 case Builtin::BImempcpy:
1370 case Builtin::BI__builtin_mempcpy: {
1371 DiagID = diag::warn_fortify_source_overflow;
1372 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1373 DestinationSize = ComputeSizeArgument(0);
1374 break;
1375 }
1376 case Builtin::BIsnprintf:
1377 case Builtin::BI__builtin_snprintf:
1378 case Builtin::BIvsnprintf:
1379 case Builtin::BI__builtin_vsnprintf: {
1380 DiagID = diag::warn_fortify_source_size_mismatch;
1381 SourceSize = ComputeExplicitObjectSizeArgument(1);
1382 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1383 StringRef FormatStrRef;
1384 size_t StrLen;
1385 if (SourceSize &&
1386 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1387 EstimateSizeFormatHandler H(FormatStrRef);
1388 const char *FormatBytes = FormatStrRef.data();
1390 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1391 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1392 llvm::APSInt FormatSize =
1393 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1394 .extOrTrunc(SizeTypeWidth);
1395 if (FormatSize > *SourceSize && *SourceSize != 0) {
1396 unsigned TruncationDiagID =
1397 H.isKernelCompatible() ? diag::warn_format_truncation
1398 : diag::warn_format_truncation_non_kprintf;
1399 SmallString<16> SpecifiedSizeStr;
1400 SmallString<16> FormatSizeStr;
1401 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1402 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1403 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1404 PDiag(TruncationDiagID)
1405 << GetFunctionName() << SpecifiedSizeStr
1406 << FormatSizeStr);
1407 }
1408 }
1409 }
1410 DestinationSize = ComputeSizeArgument(0);
1411 }
1412 }
1413
1414 if (!SourceSize || !DestinationSize ||
1415 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1416 return;
1417
1418 StringRef FunctionName = GetFunctionName();
1419
1420 SmallString<16> DestinationStr;
1421 SmallString<16> SourceStr;
1422 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1423 SourceSize->toString(SourceStr, /*Radix=*/10);
1424 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1425 PDiag(DiagID)
1426 << FunctionName << DestinationStr << SourceStr);
1427}
1428
1429static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1430 Scope::ScopeFlags NeededScopeFlags,
1431 unsigned DiagID) {
1432 // Scopes aren't available during instantiation. Fortunately, builtin
1433 // functions cannot be template args so they cannot be formed through template
1434 // instantiation. Therefore checking once during the parse is sufficient.
1435 if (SemaRef.inTemplateInstantiation())
1436 return false;
1437
1438 Scope *S = SemaRef.getCurScope();
1439 while (S && !S->isSEHExceptScope())
1440 S = S->getParent();
1441 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1442 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1443 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1444 << DRE->getDecl()->getIdentifier();
1445 return true;
1446 }
1447
1448 return false;
1449}
1450
1451static inline bool isBlockPointer(Expr *Arg) {
1452 return Arg->getType()->isBlockPointerType();
1453}
1454
1455/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
1456/// void*, which is a requirement of device side enqueue.
1457static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
1458 const BlockPointerType *BPT =
1459 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1460 ArrayRef<QualType> Params =
1461 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
1462 unsigned ArgCounter = 0;
1463 bool IllegalParams = false;
1464 // Iterate through the block parameters until either one is found that is not
1465 // a local void*, or the block is valid.
1466 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
1467 I != E; ++I, ++ArgCounter) {
1468 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
1469 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
1471 // Get the location of the error. If a block literal has been passed
1472 // (BlockExpr) then we can point straight to the offending argument,
1473 // else we just point to the variable reference.
1474 SourceLocation ErrorLoc;
1475 if (isa<BlockExpr>(BlockArg)) {
1476 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
1477 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
1478 } else if (isa<DeclRefExpr>(BlockArg)) {
1479 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
1480 }
1481 S.Diag(ErrorLoc,
1482 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
1483 IllegalParams = true;
1484 }
1485 }
1486
1487 return IllegalParams;
1488}
1489
1491 // OpenCL device can support extension but not the feature as extension
1492 // requires subgroup independent forward progress, but subgroup independent
1493 // forward progress is optional in OpenCL C 3.0 __opencl_c_subgroups feature.
1494 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts()) &&
1495 !S.getOpenCLOptions().isSupported("__opencl_c_subgroups",
1496 S.getLangOpts())) {
1497 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
1498 << 1 << Call->getDirectCallee()
1499 << "cl_khr_subgroups or __opencl_c_subgroups";
1500 return true;
1501 }
1502 return false;
1503}
1504
1506 if (checkArgCount(S, TheCall, 2))
1507 return true;
1508
1509 if (checkOpenCLSubgroupExt(S, TheCall))
1510 return true;
1511
1512 // First argument is an ndrange_t type.
1513 Expr *NDRangeArg = TheCall->getArg(0);
1514 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1515 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1516 << TheCall->getDirectCallee() << "'ndrange_t'";
1517 return true;
1518 }
1519
1520 Expr *BlockArg = TheCall->getArg(1);
1521 if (!isBlockPointer(BlockArg)) {
1522 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1523 << TheCall->getDirectCallee() << "block";
1524 return true;
1525 }
1526 return checkOpenCLBlockArgs(S, BlockArg);
1527}
1528
1529/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
1530/// get_kernel_work_group_size
1531/// and get_kernel_preferred_work_group_size_multiple builtin functions.
1533 if (checkArgCount(S, TheCall, 1))
1534 return true;
1535
1536 Expr *BlockArg = TheCall->getArg(0);
1537 if (!isBlockPointer(BlockArg)) {
1538 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1539 << TheCall->getDirectCallee() << "block";
1540 return true;
1541 }
1542 return checkOpenCLBlockArgs(S, BlockArg);
1543}
1544
1545/// Diagnose integer type and any valid implicit conversion to it.
1546static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
1547 const QualType &IntType);
1548
1550 unsigned Start, unsigned End) {
1551 bool IllegalParams = false;
1552 for (unsigned I = Start; I <= End; ++I)
1553 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
1554 S.Context.getSizeType());
1555 return IllegalParams;
1556}
1557
1558/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
1559/// 'local void*' parameter of passed block.
1561 Expr *BlockArg,
1562 unsigned NumNonVarArgs) {
1563 const BlockPointerType *BPT =
1564 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1565 unsigned NumBlockParams =
1566 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
1567 unsigned TotalNumArgs = TheCall->getNumArgs();
1568
1569 // For each argument passed to the block, a corresponding uint needs to
1570 // be passed to describe the size of the local memory.
1571 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
1572 S.Diag(TheCall->getBeginLoc(),
1573 diag::err_opencl_enqueue_kernel_local_size_args);
1574 return true;
1575 }
1576
1577 // Check that the sizes of the local memory are specified by integers.
1578 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
1579 TotalNumArgs - 1);
1580}
1581
1582/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
1583/// overload formats specified in Table 6.13.17.1.
1584/// int enqueue_kernel(queue_t queue,
1585/// kernel_enqueue_flags_t flags,
1586/// const ndrange_t ndrange,
1587/// void (^block)(void))
1588/// int enqueue_kernel(queue_t queue,
1589/// kernel_enqueue_flags_t flags,
1590/// const ndrange_t ndrange,
1591/// uint num_events_in_wait_list,
1592/// clk_event_t *event_wait_list,
1593/// clk_event_t *event_ret,
1594/// void (^block)(void))
1595/// int enqueue_kernel(queue_t queue,
1596/// kernel_enqueue_flags_t flags,
1597/// const ndrange_t ndrange,
1598/// void (^block)(local void*, ...),
1599/// uint size0, ...)
1600/// int enqueue_kernel(queue_t queue,
1601/// kernel_enqueue_flags_t flags,
1602/// const ndrange_t ndrange,
1603/// uint num_events_in_wait_list,
1604/// clk_event_t *event_wait_list,
1605/// clk_event_t *event_ret,
1606/// void (^block)(local void*, ...),
1607/// uint size0, ...)
1609 unsigned NumArgs = TheCall->getNumArgs();
1610
1611 if (NumArgs < 4) {
1612 S.Diag(TheCall->getBeginLoc(),
1613 diag::err_typecheck_call_too_few_args_at_least)
1614 << 0 << 4 << NumArgs << /*is non object*/ 0;
1615 return true;
1616 }
1617
1618 Expr *Arg0 = TheCall->getArg(0);
1619 Expr *Arg1 = TheCall->getArg(1);
1620 Expr *Arg2 = TheCall->getArg(2);
1621 Expr *Arg3 = TheCall->getArg(3);
1622
1623 // First argument always needs to be a queue_t type.
1624 if (!Arg0->getType()->isQueueT()) {
1625 S.Diag(TheCall->getArg(0)->getBeginLoc(),
1626 diag::err_opencl_builtin_expected_type)
1627 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
1628 return true;
1629 }
1630
1631 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
1632 if (!Arg1->getType()->isIntegerType()) {
1633 S.Diag(TheCall->getArg(1)->getBeginLoc(),
1634 diag::err_opencl_builtin_expected_type)
1635 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
1636 return true;
1637 }
1638
1639 // Third argument is always an ndrange_t type.
1640 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1641 S.Diag(TheCall->getArg(2)->getBeginLoc(),
1642 diag::err_opencl_builtin_expected_type)
1643 << TheCall->getDirectCallee() << "'ndrange_t'";
1644 return true;
1645 }
1646
1647 // With four arguments, there is only one form that the function could be
1648 // called in: no events and no variable arguments.
1649 if (NumArgs == 4) {
1650 // check that the last argument is the right block type.
1651 if (!isBlockPointer(Arg3)) {
1652 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1653 << TheCall->getDirectCallee() << "block";
1654 return true;
1655 }
1656 // we have a block type, check the prototype
1657 const BlockPointerType *BPT =
1658 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1659 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1660 S.Diag(Arg3->getBeginLoc(),
1661 diag::err_opencl_enqueue_kernel_blocks_no_args);
1662 return true;
1663 }
1664 return false;
1665 }
1666 // we can have block + varargs.
1667 if (isBlockPointer(Arg3))
1668 return (checkOpenCLBlockArgs(S, Arg3) ||
1669 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1670 // last two cases with either exactly 7 args or 7 args and varargs.
1671 if (NumArgs >= 7) {
1672 // check common block argument.
1673 Expr *Arg6 = TheCall->getArg(6);
1674 if (!isBlockPointer(Arg6)) {
1675 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1676 << TheCall->getDirectCallee() << "block";
1677 return true;
1678 }
1679 if (checkOpenCLBlockArgs(S, Arg6))
1680 return true;
1681
1682 // Forth argument has to be any integer type.
1683 if (!Arg3->getType()->isIntegerType()) {
1684 S.Diag(TheCall->getArg(3)->getBeginLoc(),
1685 diag::err_opencl_builtin_expected_type)
1686 << TheCall->getDirectCallee() << "integer";
1687 return true;
1688 }
1689 // check remaining common arguments.
1690 Expr *Arg4 = TheCall->getArg(4);
1691 Expr *Arg5 = TheCall->getArg(5);
1692
1693 // Fifth argument is always passed as a pointer to clk_event_t.
1694 if (!Arg4->isNullPointerConstant(S.Context,
1697 S.Diag(TheCall->getArg(4)->getBeginLoc(),
1698 diag::err_opencl_builtin_expected_type)
1699 << TheCall->getDirectCallee()
1701 return true;
1702 }
1703
1704 // Sixth argument is always passed as a pointer to clk_event_t.
1705 if (!Arg5->isNullPointerConstant(S.Context,
1707 !(Arg5->getType()->isPointerType() &&
1708 Arg5->getType()->getPointeeType()->isClkEventT())) {
1709 S.Diag(TheCall->getArg(5)->getBeginLoc(),
1710 diag::err_opencl_builtin_expected_type)
1711 << TheCall->getDirectCallee()
1713 return true;
1714 }
1715
1716 if (NumArgs == 7)
1717 return false;
1718
1719 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1720 }
1721
1722 // None of the specific case has been detected, give generic error
1723 S.Diag(TheCall->getBeginLoc(),
1724 diag::err_opencl_enqueue_kernel_incorrect_args);
1725 return true;
1726}
1727
1728/// Returns OpenCL access qual.
1729static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1730 return D->getAttr<OpenCLAccessAttr>();
1731}
1732
1733/// Returns true if pipe element type is different from the pointer.
1735 const Expr *Arg0 = Call->getArg(0);
1736 // First argument type should always be pipe.
1737 if (!Arg0->getType()->isPipeType()) {
1738 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1739 << Call->getDirectCallee() << Arg0->getSourceRange();
1740 return true;
1741 }
1742 OpenCLAccessAttr *AccessQual =
1743 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1744 // Validates the access qualifier is compatible with the call.
1745 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1746 // read_only and write_only, and assumed to be read_only if no qualifier is
1747 // specified.
1748 switch (Call->getDirectCallee()->getBuiltinID()) {
1749 case Builtin::BIread_pipe:
1750 case Builtin::BIreserve_read_pipe:
1751 case Builtin::BIcommit_read_pipe:
1752 case Builtin::BIwork_group_reserve_read_pipe:
1753 case Builtin::BIsub_group_reserve_read_pipe:
1754 case Builtin::BIwork_group_commit_read_pipe:
1755 case Builtin::BIsub_group_commit_read_pipe:
1756 if (!(!AccessQual || AccessQual->isReadOnly())) {
1757 S.Diag(Arg0->getBeginLoc(),
1758 diag::err_opencl_builtin_pipe_invalid_access_modifier)
1759 << "read_only" << Arg0->getSourceRange();
1760 return true;
1761 }
1762 break;
1763 case Builtin::BIwrite_pipe:
1764 case Builtin::BIreserve_write_pipe:
1765 case Builtin::BIcommit_write_pipe:
1766 case Builtin::BIwork_group_reserve_write_pipe:
1767 case Builtin::BIsub_group_reserve_write_pipe:
1768 case Builtin::BIwork_group_commit_write_pipe:
1769 case Builtin::BIsub_group_commit_write_pipe:
1770 if (!(AccessQual && AccessQual->isWriteOnly())) {
1771 S.Diag(Arg0->getBeginLoc(),
1772 diag::err_opencl_builtin_pipe_invalid_access_modifier)
1773 << "write_only" << Arg0->getSourceRange();
1774 return true;
1775 }
1776 break;
1777 default:
1778 break;
1779 }
1780 return false;
1781}
1782
1783/// Returns true if pipe element type is different from the pointer.
1784static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1785 const Expr *Arg0 = Call->getArg(0);
1786 const Expr *ArgIdx = Call->getArg(Idx);
1787 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1788 const QualType EltTy = PipeTy->getElementType();
1789 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1790 // The Idx argument should be a pointer and the type of the pointer and
1791 // the type of pipe element should also be the same.
1792 if (!ArgTy ||
1794 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1795 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1796 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1797 << ArgIdx->getType() << ArgIdx->getSourceRange();
1798 return true;
1799 }
1800 return false;
1801}
1802
1803// Performs semantic analysis for the read/write_pipe call.
1804// \param S Reference to the semantic analyzer.
1805// \param Call A pointer to the builtin call.
1806// \return True if a semantic error has been found, false otherwise.
1808 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1809 // functions have two forms.
1810 switch (Call->getNumArgs()) {
1811 case 2:
1812 if (checkOpenCLPipeArg(S, Call))
1813 return true;
1814 // The call with 2 arguments should be
1815 // read/write_pipe(pipe T, T*).
1816 // Check packet type T.
1818 return true;
1819 break;
1820
1821 case 4: {
1822 if (checkOpenCLPipeArg(S, Call))
1823 return true;
1824 // The call with 4 arguments should be
1825 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1826 // Check reserve_id_t.
1827 if (!Call->getArg(1)->getType()->isReserveIDT()) {
1828 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1829 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1830 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1831 return true;
1832 }
1833
1834 // Check the index.
1835 const Expr *Arg2 = Call->getArg(2);
1836 if (!Arg2->getType()->isIntegerType() &&
1837 !Arg2->getType()->isUnsignedIntegerType()) {
1838 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1839 << Call->getDirectCallee() << S.Context.UnsignedIntTy
1840 << Arg2->getType() << Arg2->getSourceRange();
1841 return true;
1842 }
1843
1844 // Check packet type T.
1846 return true;
1847 } break;
1848 default:
1849 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1850 << Call->getDirectCallee() << Call->getSourceRange();
1851 return true;
1852 }
1853
1854 return false;
1855}
1856
1857// Performs a semantic analysis on the {work_group_/sub_group_
1858// /_}reserve_{read/write}_pipe
1859// \param S Reference to the semantic analyzer.
1860// \param Call The call to the builtin function to be analyzed.
1861// \return True if a semantic error was found, false otherwise.
1863 if (checkArgCount(S, Call, 2))
1864 return true;
1865
1866 if (checkOpenCLPipeArg(S, Call))
1867 return true;
1868
1869 // Check the reserve size.
1870 if (!Call->getArg(1)->getType()->isIntegerType() &&
1871 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1872 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1873 << Call->getDirectCallee() << S.Context.UnsignedIntTy
1874 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1875 return true;
1876 }
1877
1878 // Since return type of reserve_read/write_pipe built-in function is
1879 // reserve_id_t, which is not defined in the builtin def file , we used int
1880 // as return type and need to override the return type of these functions.
1881 Call->setType(S.Context.OCLReserveIDTy);
1882
1883 return false;
1884}
1885
1886// Performs a semantic analysis on {work_group_/sub_group_
1887// /_}commit_{read/write}_pipe
1888// \param S Reference to the semantic analyzer.
1889// \param Call The call to the builtin function to be analyzed.
1890// \return True if a semantic error was found, false otherwise.
1892 if (checkArgCount(S, Call, 2))
1893 return true;
1894
1895 if (checkOpenCLPipeArg(S, Call))
1896 return true;
1897
1898 // Check reserve_id_t.
1899 if (!Call->getArg(1)->getType()->isReserveIDT()) {
1900 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1901 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1902 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1903 return true;
1904 }
1905
1906 return false;
1907}
1908
1909// Performs a semantic analysis on the call to built-in Pipe
1910// Query Functions.
1911// \param S Reference to the semantic analyzer.
1912// \param Call The call to the builtin function to be analyzed.
1913// \return True if a semantic error was found, false otherwise.
1915 if (checkArgCount(S, Call, 1))
1916 return true;
1917
1918 if (!Call->getArg(0)->getType()->isPipeType()) {
1919 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1920 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1921 return true;
1922 }
1923
1924 return false;
1925}
1926
1927// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1928// Performs semantic analysis for the to_global/local/private call.
1929// \param S Reference to the semantic analyzer.
1930// \param BuiltinID ID of the builtin function.
1931// \param Call A pointer to the builtin call.
1932// \return True if a semantic error has been found, false otherwise.
1933static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1934 CallExpr *Call) {
1935 if (checkArgCount(S, Call, 1))
1936 return true;
1937
1938 auto RT = Call->getArg(0)->getType();
1939 if (!RT->isPointerType() || RT->getPointeeType()
1940 .getAddressSpace() == LangAS::opencl_constant) {
1941 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1942 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1943 return true;
1944 }
1945
1946 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1947 S.Diag(Call->getArg(0)->getBeginLoc(),
1948 diag::warn_opencl_generic_address_space_arg)
1949 << Call->getDirectCallee()->getNameInfo().getAsString()
1950 << Call->getArg(0)->getSourceRange();
1951 }
1952
1953 RT = RT->getPointeeType();
1954 auto Qual = RT.getQualifiers();
1955 switch (BuiltinID) {
1956 case Builtin::BIto_global:
1957 Qual.setAddressSpace(LangAS::opencl_global);
1958 break;
1959 case Builtin::BIto_local:
1960 Qual.setAddressSpace(LangAS::opencl_local);
1961 break;
1962 case Builtin::BIto_private:
1963 Qual.setAddressSpace(LangAS::opencl_private);
1964 break;
1965 default:
1966 llvm_unreachable("Invalid builtin function");
1967 }
1969 RT.getUnqualifiedType(), Qual)));
1970
1971 return false;
1972}
1973
1975 if (checkArgCount(S, TheCall, 1))
1976 return ExprError();
1977
1978 // Compute __builtin_launder's parameter type from the argument.
1979 // The parameter type is:
1980 // * The type of the argument if it's not an array or function type,
1981 // Otherwise,
1982 // * The decayed argument type.
1983 QualType ParamTy = [&]() {
1984 QualType ArgTy = TheCall->getArg(0)->getType();
1985 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1986 return S.Context.getPointerType(Ty->getElementType());
1987 if (ArgTy->isFunctionType()) {
1988 return S.Context.getPointerType(ArgTy);
1989 }
1990 return ArgTy;
1991 }();
1992
1993 TheCall->setType(ParamTy);
1994
1995 auto DiagSelect = [&]() -> std::optional<unsigned> {
1996 if (!ParamTy->isPointerType())
1997 return 0;
1998 if (ParamTy->isFunctionPointerType())
1999 return 1;
2000 if (ParamTy->isVoidPointerType())
2001 return 2;
2002 return std::optional<unsigned>{};
2003 }();
2004 if (DiagSelect) {
2005 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
2006 << *DiagSelect << TheCall->getSourceRange();
2007 return ExprError();
2008 }
2009
2010 // We either have an incomplete class type, or we have a class template
2011 // whose instantiation has not been forced. Example:
2012 //
2013 // template <class T> struct Foo { T value; };
2014 // Foo<int> *p = nullptr;
2015 // auto *d = __builtin_launder(p);
2016 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
2017 diag::err_incomplete_type))
2018 return ExprError();
2019
2020 assert(ParamTy->getPointeeType()->isObjectType() &&
2021 "Unhandled non-object pointer case");
2022
2023 InitializedEntity Entity =
2025 ExprResult Arg =
2026 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
2027 if (Arg.isInvalid())
2028 return ExprError();
2029 TheCall->setArg(0, Arg.get());
2030
2031 return TheCall;
2032}
2033
2034// Emit an error and return true if the current object format type is in the
2035// list of unsupported types.
2037 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2038 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2039 llvm::Triple::ObjectFormatType CurObjFormat =
2040 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2041 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2042 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2043 << TheCall->getSourceRange();
2044 return true;
2045 }
2046 return false;
2047}
2048
2049// Emit an error and return true if the current architecture is not in the list
2050// of supported architectures.
2051static bool
2052CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2053 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2054 llvm::Triple::ArchType CurArch =
2055 S.getASTContext().getTargetInfo().getTriple().getArch();
2056 if (llvm::is_contained(SupportedArchs, CurArch))
2057 return false;
2058 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2059 << TheCall->getSourceRange();
2060 return true;
2061}
2062
2063static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2064 SourceLocation CallSiteLoc);
2065
2066bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2067 CallExpr *TheCall) {
2068 switch (TI.getTriple().getArch()) {
2069 default:
2070 // Some builtins don't require additional checking, so just consider these
2071 // acceptable.
2072 return false;
2073 case llvm::Triple::arm:
2074 case llvm::Triple::armeb:
2075 case llvm::Triple::thumb:
2076 case llvm::Triple::thumbeb:
2077 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2078 case llvm::Triple::aarch64:
2079 case llvm::Triple::aarch64_32:
2080 case llvm::Triple::aarch64_be:
2081 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2082 case llvm::Triple::bpfeb:
2083 case llvm::Triple::bpfel:
2084 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2085 case llvm::Triple::hexagon:
2086 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2087 case llvm::Triple::mips:
2088 case llvm::Triple::mipsel:
2089 case llvm::Triple::mips64:
2090 case llvm::Triple::mips64el:
2091 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2092 case llvm::Triple::systemz:
2093 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2094 case llvm::Triple::x86:
2095 case llvm::Triple::x86_64:
2096 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
2097 case llvm::Triple::ppc:
2098 case llvm::Triple::ppcle:
2099 case llvm::Triple::ppc64:
2100 case llvm::Triple::ppc64le:
2101 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2102 case llvm::Triple::amdgcn:
2103 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2104 case llvm::Triple::riscv32:
2105 case llvm::Triple::riscv64:
2106 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2107 case llvm::Triple::loongarch32:
2108 case llvm::Triple::loongarch64:
2109 return CheckLoongArchBuiltinFunctionCall(TI, BuiltinID, TheCall);
2110 case llvm::Triple::wasm32:
2111 case llvm::Triple::wasm64:
2112 return CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2113 case llvm::Triple::nvptx:
2114 case llvm::Triple::nvptx64:
2115 return CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2116 }
2117}
2118
2119// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2120// not a valid type, emit an error message and return true. Otherwise return
2121// false.
2123 QualType Ty) {
2125 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2126 << 1 << /* vector, integer or float ty*/ 0 << Ty;
2127 }
2128
2129 return false;
2130}
2131
2133 QualType ArgTy, int ArgIndex) {
2134 QualType EltTy = ArgTy;
2135 if (auto *VecTy = EltTy->getAs<VectorType>())
2136 EltTy = VecTy->getElementType();
2137
2138 if (!EltTy->isRealFloatingType()) {
2139 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2140 << ArgIndex << /* vector or float ty*/ 5 << ArgTy;
2141 }
2142
2143 return false;
2144}
2145
2146/// SemaBuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2147/// This checks that the target supports the builtin and that the string
2148/// argument is constant and valid.
2149static bool SemaBuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2150 const TargetInfo *AuxTI, unsigned BuiltinID) {
2151 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2152 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2153 "Expecting __builtin_cpu_...");
2154
2155 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2156 const TargetInfo *TheTI = &TI;
2157 auto SupportsBI = [=](const TargetInfo *TInfo) {
2158 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2159 (!IsCPUSupports && TInfo->supportsCpuIs()));
2160 };
2161 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2162 TheTI = AuxTI;
2163
2164 if (IsCPUSupports && !TheTI->supportsCpuSupports())
2165 return S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2166 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2167 if (!IsCPUSupports && !TheTI->supportsCpuIs())
2168 return S.Diag(TheCall->getBeginLoc(),
2169 TI.getTriple().isOSAIX()
2170 ? diag::err_builtin_aix_os_unsupported
2171 : diag::err_builtin_target_unsupported)
2172 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2173
2174 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2175 // Check if the argument is a string literal.
2176 if (!isa<StringLiteral>(Arg))
2177 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2178 << Arg->getSourceRange();
2179
2180 // Check the contents of the string.
2181 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2182 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature))
2183 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
2184 << Arg->getSourceRange();
2185 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2186 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2187 << Arg->getSourceRange();
2188 return false;
2189}
2190
2192Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2193 CallExpr *TheCall) {
2194 ExprResult TheCallResult(TheCall);
2195
2196 // Find out if any arguments are required to be integer constant expressions.
2197 unsigned ICEArguments = 0;
2199 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2200 if (Error != ASTContext::GE_None)
2201 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2202
2203 // If any arguments are required to be ICE's, check and diagnose.
2204 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2205 // Skip arguments not required to be ICE's.
2206 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2207
2208 llvm::APSInt Result;
2209 // If we don't have enough arguments, continue so we can issue better
2210 // diagnostic in checkArgCount(...)
2211 if (ArgNo < TheCall->getNumArgs() &&
2212 SemaBuiltinConstantArg(TheCall, ArgNo, Result))
2213 return true;
2214 ICEArguments &= ~(1 << ArgNo);
2215 }
2216
2217 FPOptions FPO;
2218 switch (BuiltinID) {
2219 case Builtin::BI__builtin_cpu_supports:
2220 case Builtin::BI__builtin_cpu_is:
2221 if (SemaBuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2222 Context.getAuxTargetInfo(), BuiltinID))
2223 return ExprError();
2224 break;
2225 case Builtin::BI__builtin_cpu_init:
2227 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2228 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2229 return ExprError();
2230 }
2231 break;
2232 case Builtin::BI__builtin___CFStringMakeConstantString:
2233 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2234 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2236 *this, BuiltinID, TheCall,
2237 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2238 return ExprError();
2239 assert(TheCall->getNumArgs() == 1 &&
2240 "Wrong # arguments to builtin CFStringMakeConstantString");
2241 if (CheckObjCString(TheCall->getArg(0)))
2242 return ExprError();
2243 break;
2244 case Builtin::BI__builtin_ms_va_start:
2245 case Builtin::BI__builtin_stdarg_start:
2246 case Builtin::BI__builtin_va_start:
2247 if (SemaBuiltinVAStart(BuiltinID, TheCall))
2248 return ExprError();
2249 break;
2250 case Builtin::BI__va_start: {
2251 switch (Context.getTargetInfo().getTriple().getArch()) {
2252 case llvm::Triple::aarch64:
2253 case llvm::Triple::arm:
2254 case llvm::Triple::thumb:
2255 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
2256 return ExprError();
2257 break;
2258 default:
2259 if (SemaBuiltinVAStart(BuiltinID, TheCall))
2260 return ExprError();
2261 break;
2262 }
2263 break;
2264 }
2265
2266 // The acquire, release, and no fence variants are ARM and AArch64 only.
2267 case Builtin::BI_interlockedbittestandset_acq:
2268 case Builtin::BI_interlockedbittestandset_rel:
2269 case Builtin::BI_interlockedbittestandset_nf:
2270 case Builtin::BI_interlockedbittestandreset_acq:
2271 case Builtin::BI_interlockedbittestandreset_rel:
2272 case Builtin::BI_interlockedbittestandreset_nf:
2274 *this, BuiltinID, TheCall,
2275 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2276 return ExprError();
2277 break;
2278
2279 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2280 case Builtin::BI_bittest64:
2281 case Builtin::BI_bittestandcomplement64:
2282 case Builtin::BI_bittestandreset64:
2283 case Builtin::BI_bittestandset64:
2284 case Builtin::BI_interlockedbittestandreset64:
2285 case Builtin::BI_interlockedbittestandset64:
2286 if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall,
2287 {llvm::Triple::x86_64, llvm::Triple::arm,
2288 llvm::Triple::thumb,
2289 llvm::Triple::aarch64}))
2290 return ExprError();
2291 break;
2292
2293 case Builtin::BI__builtin_set_flt_rounds:
2294 if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall,
2295 {llvm::Triple::x86, llvm::Triple::x86_64,
2296 llvm::Triple::arm, llvm::Triple::thumb,
2297 llvm::Triple::aarch64}))
2298 return ExprError();
2299 break;
2300
2301 case Builtin::BI__builtin_isgreater:
2302 case Builtin::BI__builtin_isgreaterequal:
2303 case Builtin::BI__builtin_isless:
2304 case Builtin::BI__builtin_islessequal:
2305 case Builtin::BI__builtin_islessgreater:
2306 case Builtin::BI__builtin_isunordered:
2307 if (SemaBuiltinUnorderedCompare(TheCall, BuiltinID))
2308 return ExprError();
2309 break;
2310 case Builtin::BI__builtin_fpclassify:
2311 if (SemaBuiltinFPClassification(TheCall, 6, BuiltinID))
2312 return ExprError();
2313 break;
2314 case Builtin::BI__builtin_isfpclass:
2315 if (SemaBuiltinFPClassification(TheCall, 2, BuiltinID))
2316 return ExprError();
2317 break;
2318 case Builtin::BI__builtin_isfinite:
2319 case Builtin::BI__builtin_isinf:
2320 case Builtin::BI__builtin_isinf_sign:
2321 case Builtin::BI__builtin_isnan:
2322 case Builtin::BI__builtin_issignaling:
2323 case Builtin::BI__builtin_isnormal:
2324 case Builtin::BI__builtin_issubnormal:
2325 case Builtin::BI__builtin_iszero:
2326 case Builtin::BI__builtin_signbit:
2327 case Builtin::BI__builtin_signbitf:
2328 case Builtin::BI__builtin_signbitl:
2329 if (SemaBuiltinFPClassification(TheCall, 1, BuiltinID))
2330 return ExprError();
2331 break;
2332 case Builtin::BI__builtin_shufflevector:
2333 return SemaBuiltinShuffleVector(TheCall);
2334 // TheCall will be freed by the smart pointer here, but that's fine, since
2335 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
2336 case Builtin::BI__builtin_prefetch:
2337 if (SemaBuiltinPrefetch(TheCall))
2338 return ExprError();
2339 break;
2340 case Builtin::BI__builtin_alloca_with_align:
2341 case Builtin::BI__builtin_alloca_with_align_uninitialized:
2342 if (SemaBuiltinAllocaWithAlign(TheCall))
2343 return ExprError();
2344 [[fallthrough]];
2345 case Builtin::BI__builtin_alloca:
2346 case Builtin::BI__builtin_alloca_uninitialized:
2347 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
2348 << TheCall->getDirectCallee();
2349 break;
2350 case Builtin::BI__arithmetic_fence:
2351 if (SemaBuiltinArithmeticFence(TheCall))
2352 return ExprError();
2353 break;
2354 case Builtin::BI__assume:
2355 case Builtin::BI__builtin_assume:
2356 if (SemaBuiltinAssume(TheCall))
2357 return ExprError();
2358 break;
2359 case Builtin::BI__builtin_assume_aligned:
2360 if (SemaBuiltinAssumeAligned(TheCall))
2361 return ExprError();
2362 break;
2363 case Builtin::BI__builtin_dynamic_object_size:
2364 case Builtin::BI__builtin_object_size:
2365 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
2366 return ExprError();
2367 break;
2368 case Builtin::BI__builtin_longjmp:
2369 if (SemaBuiltinLongjmp(TheCall))
2370 return ExprError();
2371 break;
2372 case Builtin::BI__builtin_setjmp:
2373 if (SemaBuiltinSetjmp(TheCall))
2374 return ExprError();
2375 break;
2376 case Builtin::BI__builtin_classify_type:
2377 if (checkArgCount(*this, TheCall, 1)) return true;
2378 TheCall->setType(Context.IntTy);
2379 break;
2380 case Builtin::BI__builtin_complex:
2381 if (SemaBuiltinComplex(TheCall))
2382 return ExprError();
2383 break;
2384 case Builtin::BI__builtin_constant_p: {
2385 if (checkArgCount(*this, TheCall, 1)) return true;
2387 if (Arg.isInvalid()) return true;
2388 TheCall->setArg(0, Arg.get());
2389 TheCall->setType(Context.IntTy);
2390 break;
2391 }
2392 case Builtin::BI__builtin_launder:
2393 return SemaBuiltinLaunder(*this, TheCall);
2394 case Builtin::BI__sync_fetch_and_add:
2395 case Builtin::BI__sync_fetch_and_add_1:
2396 case Builtin::BI__sync_fetch_and_add_2:
2397 case Builtin::BI__sync_fetch_and_add_4:
2398 case Builtin::BI__sync_fetch_and_add_8:
2399 case Builtin::BI__sync_fetch_and_add_16:
2400 case Builtin::BI__sync_fetch_and_sub:
2401 case Builtin::BI__sync_fetch_and_sub_1:
2402 case Builtin::BI__sync_fetch_and_sub_2:
2403 case Builtin::BI__sync_fetch_and_sub_4:
2404 case Builtin::BI__sync_fetch_and_sub_8:
2405 case Builtin::BI__sync_fetch_and_sub_16:
2406 case Builtin::BI__sync_fetch_and_or:
2407 case Builtin::BI__sync_fetch_and_or_1:
2408 case Builtin::BI__sync_fetch_and_or_2:
2409 case Builtin::BI__sync_fetch_and_or_4:
2410 case Builtin::BI__sync_fetch_and_or_8:
2411 case Builtin::BI__sync_fetch_and_or_16:
2412 case Builtin::BI__sync_fetch_and_and:
2413 case Builtin::BI__sync_fetch_and_and_1:
2414 case Builtin::BI__sync_fetch_and_and_2:
2415 case Builtin::BI__sync_fetch_and_and_4:
2416 case Builtin::BI__sync_fetch_and_and_8:
2417 case Builtin::BI__sync_fetch_and_and_16:
2418 case Builtin::BI__sync_fetch_and_xor:
2419 case Builtin::BI__sync_fetch_and_xor_1:
2420 case Builtin::BI__sync_fetch_and_xor_2:
2421 case Builtin::BI__sync_fetch_and_xor_4:
2422 case Builtin::BI__sync_fetch_and_xor_8:
2423 case Builtin::BI__sync_fetch_and_xor_16:
2424 case Builtin::BI__sync_fetch_and_nand:
2425 case Builtin::BI__sync_fetch_and_nand_1:
2426 case Builtin::BI__sync_fetch_and_nand_2:
2427 case Builtin::BI__sync_fetch_and_nand_4:
2428 case Builtin::BI__sync_fetch_and_nand_8:
2429 case Builtin::BI__sync_fetch_and_nand_16:
2430 case Builtin::BI__sync_add_and_fetch:
2431 case Builtin::BI__sync_add_and_fetch_1:
2432 case Builtin::BI__sync_add_and_fetch_2:
2433 case Builtin::BI__sync_add_and_fetch_4:
2434 case Builtin::BI__sync_add_and_fetch_8:
2435 case Builtin::BI__sync_add_and_fetch_16:
2436 case Builtin::BI__sync_sub_and_fetch:
2437 case Builtin::BI__sync_sub_and_fetch_1:
2438 case Builtin::BI__sync_sub_and_fetch_2:
2439 case Builtin::BI__sync_sub_and_fetch_4:
2440 case Builtin::BI__sync_sub_and_fetch_8:
2441 case Builtin::BI__sync_sub_and_fetch_16:
2442 case Builtin::BI__sync_and_and_fetch:
2443 case Builtin::BI__sync_and_and_fetch_1:
2444 case Builtin::BI__sync_and_and_fetch_2:
2445 case Builtin::BI__sync_and_and_fetch_4:
2446 case Builtin::BI__sync_and_and_fetch_8:
2447 case Builtin::BI__sync_and_and_fetch_16:
2448 case Builtin::BI__sync_or_and_fetch:
2449 case Builtin::BI__sync_or_and_fetch_1:
2450 case Builtin::BI__sync_or_and_fetch_2:
2451 case Builtin::BI__sync_or_and_fetch_4:
2452 case Builtin::BI__sync_or_and_fetch_8:
2453 case Builtin::BI__sync_or_and_fetch_16:
2454 case Builtin::BI__sync_xor_and_fetch:
2455 case Builtin::BI__sync_xor_and_fetch_1:
2456 case Builtin::BI__sync_xor_and_fetch_2:
2457 case Builtin::BI__sync_xor_and_fetch_4:
2458 case Builtin::BI__sync_xor_and_fetch_8:
2459 case Builtin::BI__sync_xor_and_fetch_16:
2460 case Builtin::BI__sync_nand_and_fetch:
2461 case Builtin::BI__sync_nand_and_fetch_1:
2462 case Builtin::BI__sync_nand_and_fetch_2:
2463 case Builtin::BI__sync_nand_and_fetch_4:
2464 case Builtin::BI__sync_nand_and_fetch_8:
2465 case Builtin::BI__sync_nand_and_fetch_16:
2466 case Builtin::BI__sync_val_compare_and_swap:
2467 case Builtin::BI__sync_val_compare_and_swap_1:
2468 case Builtin::BI__sync_val_compare_and_swap_2:
2469 case Builtin::BI__sync_val_compare_and_swap_4:
2470 case Builtin::BI__sync_val_compare_and_swap_8:
2471 case Builtin::BI__sync_val_compare_and_swap_16:
2472 case Builtin::BI__sync_bool_compare_and_swap:
2473 case Builtin::BI__sync_bool_compare_and_swap_1:
2474 case Builtin::BI__sync_bool_compare_and_swap_2:
2475 case Builtin::BI__sync_bool_compare_and_swap_4:
2476 case Builtin::BI__sync_bool_compare_and_swap_8:
2477 case Builtin::BI__sync_bool_compare_and_swap_16:
2478 case Builtin::BI__sync_lock_test_and_set:
2479 case Builtin::BI__sync_lock_test_and_set_1:
2480 case Builtin::BI__sync_lock_test_and_set_2:
2481 case Builtin::BI__sync_lock_test_and_set_4:
2482 case Builtin::BI__sync_lock_test_and_set_8:
2483 case Builtin::BI__sync_lock_test_and_set_16:
2484 case Builtin::BI__sync_lock_release:
2485 case Builtin::BI__sync_lock_release_1:
2486 case Builtin::BI__sync_lock_release_2:
2487 case Builtin::BI__sync_lock_release_4:
2488 case Builtin::BI__sync_lock_release_8:
2489 case Builtin::BI__sync_lock_release_16:
2490 case Builtin::BI__sync_swap:
2491 case Builtin::BI__sync_swap_1:
2492 case Builtin::BI__sync_swap_2:
2493 case Builtin::BI__sync_swap_4:
2494 case Builtin::BI__sync_swap_8:
2495 case Builtin::BI__sync_swap_16:
2496 return SemaBuiltinAtomicOverloaded(TheCallResult);
2497 case Builtin::BI__sync_synchronize:
2498 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
2499 << TheCall->getCallee()->getSourceRange();
2500 break;
2501 case Builtin::BI__builtin_nontemporal_load:
2502 case Builtin::BI__builtin_nontemporal_store:
2503 return SemaBuiltinNontemporalOverloaded(TheCallResult);
2504 case Builtin::BI__builtin_memcpy_inline: {
2505 clang::Expr *SizeOp = TheCall->getArg(2);
2506 // We warn about copying to or from `nullptr` pointers when `size` is
2507 // greater than 0. When `size` is value dependent we cannot evaluate its
2508 // value so we bail out.
2509 if (SizeOp->isValueDependent())
2510 break;
2511 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
2512 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2513 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
2514 }
2515 break;
2516 }
2517 case Builtin::BI__builtin_memset_inline: {
2518 clang::Expr *SizeOp = TheCall->getArg(2);
2519 // We warn about filling to `nullptr` pointers when `size` is greater than
2520 // 0. When `size` is value dependent we cannot evaluate its value so we bail
2521 // out.
2522 if (SizeOp->isValueDependent())
2523 break;
2524 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
2525 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2526 break;
2527 }
2528#define BUILTIN(ID, TYPE, ATTRS)
2529#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
2530 case Builtin::BI##ID: \
2531 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
2532#include "clang/Basic/Builtins.inc"
2533 case Builtin::BI__annotation:
2534 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
2535 return ExprError();
2536 break;
2537 case Builtin::BI__builtin_annotation:
2538 if (SemaBuiltinAnnotation(*this, TheCall))
2539 return ExprError();
2540 break;
2541 case Builtin::BI__builtin_addressof:
2542 if (SemaBuiltinAddressof(*this, TheCall))
2543 return ExprError();
2544 break;
2545 case Builtin::BI__builtin_function_start:
2546 if (SemaBuiltinFunctionStart(*this, TheCall))
2547 return ExprError();
2548 break;
2549 case Builtin::BI__builtin_is_aligned:
2550 case Builtin::BI__builtin_align_up:
2551 case Builtin::BI__builtin_align_down:
2552 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
2553 return ExprError();
2554 break;
2555 case Builtin::BI__builtin_add_overflow:
2556 case Builtin::BI__builtin_sub_overflow:
2557 case Builtin::BI__builtin_mul_overflow:
2558 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
2559 return ExprError();
2560 break;
2561 case Builtin::BI__builtin_operator_new:
2562 case Builtin::BI__builtin_operator_delete: {
2563 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
2564 ExprResult Res =
2565 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
2566 if (Res.isInvalid())
2567 CorrectDelayedTyposInExpr(TheCallResult.get());
2568 return Res;
2569 }
2570 case Builtin::BI__builtin_dump_struct:
2571 return SemaBuiltinDumpStruct(*this, TheCall);
2572 case Builtin::BI__builtin_expect_with_probability: {
2573 // We first want to ensure we are called with 3 arguments
2574 if (checkArgCount(*this, TheCall, 3))
2575 return ExprError();
2576 // then check probability is constant float in range [0.0, 1.0]
2577 const Expr *ProbArg = TheCall->getArg(2);
2579 Expr::EvalResult Eval;
2580 Eval.Diag = &Notes;
2581 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2582 !Eval.Val.isFloat()) {
2583 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2584 << ProbArg->getSourceRange();
2585 for (const PartialDiagnosticAt &PDiag : Notes)
2586 Diag(PDiag.first, PDiag.second);
2587 return ExprError();
2588 }
2589 llvm::APFloat Probability = Eval.Val.getFloat();
2590 bool LoseInfo = false;
2591 Probability.convert(llvm::APFloat::IEEEdouble(),
2592 llvm::RoundingMode::Dynamic, &LoseInfo);
2593 if (!(Probability >= llvm::APFloat(0.0) &&
2594 Probability <= llvm::APFloat(1.0))) {
2595 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2596 << ProbArg->getSourceRange();
2597 return ExprError();
2598 }
2599 break;
2600 }
2601 case Builtin::BI__builtin_preserve_access_index:
2602 if (SemaBuiltinPreserveAI(*this, TheCall))
2603 return ExprError();
2604 break;
2605 case Builtin::BI__builtin_call_with_static_chain:
2606 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
2607 return ExprError();
2608 break;
2609 case Builtin::BI__exception_code:
2610 case Builtin::BI_exception_code:
2612 diag::err_seh___except_block))
2613 return ExprError();
2614 break;
2615 case Builtin::BI__exception_info:
2616 case Builtin::BI_exception_info:
2618 diag::err_seh___except_filter))
2619 return ExprError();
2620 break;
2621 case Builtin::BI__GetExceptionInfo:
2622 if (checkArgCount(*this, TheCall, 1))
2623 return ExprError();
2624
2626 TheCall->getBeginLoc(),
2628 TheCall))
2629 return ExprError();
2630
2631 TheCall->setType(Context.VoidPtrTy);
2632 break;
2633 case Builtin::BIaddressof:
2634 case Builtin::BI__addressof:
2635 case Builtin::BIforward:
2636 case Builtin::BIforward_like:
2637 case Builtin::BImove:
2638 case Builtin::BImove_if_noexcept:
2639 case Builtin::BIas_const: {
2640 // These are all expected to be of the form
2641 // T &/&&/* f(U &/&&)
2642 // where T and U only differ in qualification.
2643 if (checkArgCount(*this, TheCall, 1))
2644 return ExprError();
2645 QualType Param = FDecl->getParamDecl(0)->getType();
2646 QualType Result = FDecl->getReturnType();
2647 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
2648 BuiltinID == Builtin::BI__addressof;
2649 if (!(Param->isReferenceType() &&
2650 (ReturnsPointer ? Result->isAnyPointerType()
2651 : Result->isReferenceType()) &&
2653 Result->getPointeeType()))) {
2654 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
2655 << FDecl;
2656 return ExprError();
2657 }
2658 break;
2659 }
2660 // OpenCL v2.0, s6.13.16 - Pipe functions
2661 case Builtin::BIread_pipe:
2662 case Builtin::BIwrite_pipe:
2663 // Since those two functions are declared with var args, we need a semantic
2664 // check for the argument.
2665 if (SemaBuiltinRWPipe(*this, TheCall))
2666 return ExprError();
2667 break;
2668 case Builtin::BIreserve_read_pipe:
2669 case Builtin::BIreserve_write_pipe:
2670 case Builtin::BIwork_group_reserve_read_pipe:
2671 case Builtin::BIwork_group_reserve_write_pipe:
2672 if (SemaBuiltinReserveRWPipe(*this, TheCall))
2673 return ExprError();
2674 break;
2675 case Builtin::BIsub_group_reserve_read_pipe:
2676 case Builtin::BIsub_group_reserve_write_pipe:
2677 if (checkOpenCLSubgroupExt(*this, TheCall) ||
2678 SemaBuiltinReserveRWPipe(*this, TheCall))
2679 return ExprError();
2680 break;
2681 case Builtin::BIcommit_read_pipe:
2682 case Builtin::BIcommit_write_pipe:
2683 case Builtin::BIwork_group_commit_read_pipe:
2684 case Builtin::BIwork_group_commit_write_pipe:
2685 if (SemaBuiltinCommitRWPipe(*this, TheCall))
2686 return ExprError();
2687 break;
2688 case Builtin::BIsub_group_commit_read_pipe:
2689 case Builtin::BIsub_group_commit_write_pipe:
2690 if (checkOpenCLSubgroupExt(*this, TheCall) ||
2691 SemaBuiltinCommitRWPipe(*this, TheCall))
2692 return ExprError();
2693 break;
2694 case Builtin::BIget_pipe_num_packets:
2695 case Builtin::BIget_pipe_max_packets:
2696 if (SemaBuiltinPipePackets(*this, TheCall))
2697 return ExprError();
2698 break;
2699 case Builtin::BIto_global:
2700 case Builtin::BIto_local:
2701 case Builtin::BIto_private:
2702 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2703 return ExprError();
2704 break;
2705 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2706 case Builtin::BIenqueue_kernel:
2707 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
2708 return ExprError();
2709 break;
2710 case Builtin::BIget_kernel_work_group_size:
2711 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2712 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2713 return ExprError();
2714 break;
2715 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2716 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2717 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2718 return ExprError();
2719 break;
2720 case Builtin::BI__builtin_os_log_format:
2722 [[fallthrough]];
2723 case Builtin::BI__builtin_os_log_format_buffer_size:
2724 if (SemaBuiltinOSLogFormat(TheCall))
2725 return ExprError();
2726 break;
2727 case Builtin::BI__builtin_frame_address:
2728 case Builtin::BI__builtin_return_address: {
2729 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2730 return ExprError();
2731
2732 // -Wframe-address warning if non-zero passed to builtin
2733 // return/frame address.
2735 if (!TheCall->getArg(0)->isValueDependent() &&
2736 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2737 Result.Val.getInt() != 0)
2738 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2739 << ((BuiltinID == Builtin::BI__builtin_return_address)
2740 ? "__builtin_return_address"
2741 : "__builtin_frame_address")
2742 << TheCall->getSourceRange();
2743 break;
2744 }
2745
2746 case Builtin::BI__builtin_nondeterministic_value: {
2747 if (SemaBuiltinNonDeterministicValue(TheCall))
2748 return ExprError();
2749 break;
2750 }
2751
2752 // __builtin_elementwise_abs restricts the element type to signed integers or
2753 // floating point types only.
2754 case Builtin::BI__builtin_elementwise_abs: {
2755 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2756 return ExprError();
2757
2758 QualType ArgTy = TheCall->getArg(0)->getType();
2759 QualType EltTy = ArgTy;
2760
2761 if (auto *VecTy = EltTy->getAs<VectorType>())
2762 EltTy = VecTy->getElementType();
2763 if (EltTy->isUnsignedIntegerType()) {
2764 Diag(TheCall->getArg(0)->getBeginLoc(),
2765 diag::err_builtin_invalid_arg_type)
2766 << 1 << /* signed integer or float ty*/ 3 << ArgTy;
2767 return ExprError();
2768 }
2769 break;
2770 }
2771
2772 // These builtins restrict the element type to floating point
2773 // types only.
2774 case Builtin::BI__builtin_elementwise_ceil:
2775 case Builtin::BI__builtin_elementwise_cos:
2776 case Builtin::BI__builtin_elementwise_exp:
2777 case Builtin::BI__builtin_elementwise_exp2:
2778 case Builtin::BI__builtin_elementwise_floor:
2779 case Builtin::BI__builtin_elementwise_log:
2780 case Builtin::BI__builtin_elementwise_log2:
2781 case Builtin::BI__builtin_elementwise_log10:
2782 case Builtin::BI__builtin_elementwise_roundeven:
2783 case Builtin::BI__builtin_elementwise_round:
2784 case Builtin::BI__builtin_elementwise_rint:
2785 case Builtin::BI__builtin_elementwise_nearbyint:
2786 case Builtin::BI__builtin_elementwise_sin:
2787 case Builtin::BI__builtin_elementwise_sqrt:
2788 case Builtin::BI__builtin_elementwise_trunc:
2789 case Builtin::BI__builtin_elementwise_canonicalize: {
2790 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2791 return ExprError();
2792
2793 QualType ArgTy = TheCall->getArg(0)->getType();
2794 if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
2795 ArgTy, 1))
2796 return ExprError();
2797 break;
2798 }
2799 case Builtin::BI__builtin_elementwise_fma: {
2800 if (SemaBuiltinElementwiseTernaryMath(TheCall))
2801 return ExprError();
2802 break;
2803 }
2804
2805 // These builtins restrict the element type to floating point
2806 // types only, and take in two arguments.
2807 case Builtin::BI__builtin_elementwise_pow: {
2808 if (SemaBuiltinElementwiseMath(TheCall))
2809 return ExprError();
2810
2811 QualType ArgTy = TheCall->getArg(0)->getType();
2812 if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
2813 ArgTy, 1) ||
2814 checkFPMathBuiltinElementType(*this, TheCall->getArg(1)->getBeginLoc(),
2815 ArgTy, 2))
2816 return ExprError();
2817 break;
2818 }
2819
2820 // These builtins restrict the element type to integer
2821 // types only.
2822 case Builtin::BI__builtin_elementwise_add_sat:
2823 case Builtin::BI__builtin_elementwise_sub_sat: {
2824 if (SemaBuiltinElementwiseMath(TheCall))
2825 return ExprError();
2826
2827 const Expr *Arg = TheCall->getArg(0);
2828 QualType ArgTy = Arg->getType();
2829 QualType EltTy = ArgTy;
2830
2831 if (auto *VecTy = EltTy->getAs<VectorType>())
2832 EltTy = VecTy->getElementType();
2833
2834 if (!EltTy->isIntegerType()) {
2835 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2836 << 1 << /* integer ty */ 6 << ArgTy;
2837 return ExprError();
2838 }
2839 break;
2840 }
2841
2842 case Builtin::BI__builtin_elementwise_min:
2843 case Builtin::BI__builtin_elementwise_max:
2844 if (SemaBuiltinElementwiseMath(TheCall))
2845 return ExprError();
2846 break;
2847
2848 case Builtin::BI__builtin_elementwise_bitreverse: {
2849 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
2850 return ExprError();
2851
2852 const Expr *Arg = TheCall->getArg(0);
2853 QualType ArgTy = Arg->getType();
2854 QualType EltTy = ArgTy;
2855
2856 if (auto *VecTy = EltTy->getAs<VectorType>())
2857 EltTy = VecTy->getElementType();
2858
2859 if (!EltTy->isIntegerType()) {
2860 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2861 << 1 << /* integer ty */ 6 << ArgTy;
2862 return ExprError();
2863 }
2864 break;
2865 }
2866
2867 case Builtin::BI__builtin_elementwise_copysign: {
2868 if (checkArgCount(*this, TheCall, 2))
2869 return ExprError();
2870
2871 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
2872 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
2873 if (Magnitude.isInvalid() || Sign.isInvalid())
2874 return ExprError();
2875
2876 QualType MagnitudeTy = Magnitude.get()->getType();
2877 QualType SignTy = Sign.get()->getType();
2878 if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
2879 MagnitudeTy, 1) ||
2880 checkFPMathBuiltinElementType(*this, TheCall->getArg(1)->getBeginLoc(),
2881 SignTy, 2)) {
2882 return ExprError();
2883 }
2884
2885 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
2886 return Diag(Sign.get()->getBeginLoc(),
2887 diag::err_typecheck_call_different_arg_types)
2888 << MagnitudeTy << SignTy;
2889 }
2890
2891 TheCall->setArg(0, Magnitude.get());
2892 TheCall->setArg(1, Sign.get());
2893 TheCall->setType(Magnitude.get()->getType());
2894 break;
2895 }
2896 case Builtin::BI__builtin_reduce_max:
2897 case Builtin::BI__builtin_reduce_min: {
2898 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2899 return ExprError();
2900
2901 const Expr *Arg = TheCall->getArg(0);
2902 const auto *TyA = Arg->getType()->getAs<VectorType>();
2903 if (!TyA) {
2904 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2905 << 1 << /* vector ty*/ 4 << Arg->getType();
2906 return ExprError();
2907 }
2908
2909 TheCall->setType(TyA->getElementType());
2910 break;
2911 }
2912
2913 // These builtins support vectors of integers only.
2914 // TODO: ADD/MUL should support floating-point types.
2915 case Builtin::BI__builtin_reduce_add:
2916 case Builtin::BI__builtin_reduce_mul:
2917 case Builtin::BI__builtin_reduce_xor:
2918 case Builtin::BI__builtin_reduce_or:
2919 case Builtin::BI__builtin_reduce_and: {
2920 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2921 return ExprError();
2922
2923 const Expr *Arg = TheCall->getArg(0);
2924 const auto *TyA = Arg->getType()->getAs<VectorType>();
2925 if (!TyA || !TyA->getElementType()->isIntegerType()) {
2926 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2927 << 1 << /* vector of integers */ 6 << Arg->getType();
2928 return ExprError();
2929 }
2930 TheCall->setType(TyA->getElementType());
2931 break;
2932 }
2933
2934 case Builtin::BI__builtin_matrix_transpose:
2935 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
2936
2937 case Builtin::BI__builtin_matrix_column_major_load:
2938 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2939
2940 case Builtin::BI__builtin_matrix_column_major_store:
2941 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2942
2943 case Builtin::BI__builtin_get_device_side_mangled_name: {
2944 auto Check = [](CallExpr *TheCall) {
2945 if (TheCall->getNumArgs() != 1)
2946 return false;
2947 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2948 if (!DRE)
2949 return false;
2950 auto *D = DRE->getDecl();
2951 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2952 return false;
2953 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2954 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2955 };
2956 if (!Check(TheCall)) {
2957 Diag(TheCall->getBeginLoc(),
2958 diag::err_hip_invalid_args_builtin_mangled_name);
2959 return ExprError();
2960 }
2961 }
2962 }
2963
2964 // Since the target specific builtins for each arch overlap, only check those
2965 // of the arch we are compiling for.
2966 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2967 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2968 assert(Context.getAuxTargetInfo() &&
2969 "Aux Target Builtin, but not an aux target?");
2970
2971 if (CheckTSBuiltinFunctionCall(
2973 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2974 return ExprError();
2975 } else {
2976 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2977 TheCall))
2978 return ExprError();
2979 }
2980 }
2981
2982 return TheCallResult;
2983}
2984
2985// Get the valid immediate range for the specified NEON type code.
2986static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2988 int IsQuad = ForceQuad ? true : Type.isQuad();
2989 switch (Type.getEltType()) {
2992 return shift ? 7 : (8 << IsQuad) - 1;
2995 return shift ? 15 : (4 << IsQuad) - 1;
2997 return shift ? 31 : (2 << IsQuad) - 1;
3000 return shift ? 63 : (1 << IsQuad) - 1;
3002 return shift ? 127 : (1 << IsQuad) - 1;
3004 assert(!shift && "cannot shift float types!");
3005 return (4 << IsQuad) - 1;
3007 assert(!shift && "cannot shift float types!");
3008 return (2 << IsQuad) - 1;
3010 assert(!shift && "cannot shift float types!");
3011 return (1 << IsQuad) - 1;
3013 assert(!shift && "cannot shift float types!");
3014 return (4 << IsQuad) - 1;
3015 }
3016 llvm_unreachable("Invalid NeonTypeFlag!");
3017}
3018
3019/// getNeonEltType - Return the QualType corresponding to the elements of
3020/// the vector type specified by the NeonTypeFlags. This is used to check
3021/// the pointer arguments for Neon load/store intrinsics.
3023 bool IsPolyUnsigned, bool IsInt64Long) {
3024 switch (Flags.getEltType()) {
3026 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
3028 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
3030 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
3032 if (IsInt64Long)
3033 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
3034 else
3035 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
3036 : Context.LongLongTy;
3038 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
3040 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
3042 if (IsInt64Long)
3043 return Context.UnsignedLongTy;
3044 else
3045 return Context.UnsignedLongLongTy;
3047 break;
3049 return Context.HalfTy;
3051 return Context.FloatTy;
3053 return Context.DoubleTy;
3055 return Context.BFloat16Ty;
3056 }
3057 llvm_unreachable("Invalid NeonTypeFlag!");
3058}
3059
3066
3067enum ArmSMEState : unsigned {
3069
3070 ArmInZA = 0b01,
3071 ArmOutZA = 0b10,
3074
3075 ArmInZT0 = 0b01 << 2,
3076 ArmOutZT0 = 0b10 << 2,
3077 ArmInOutZT0 = 0b11 << 2,
3078 ArmZT0Mask = 0b11 << 2
3080
3081bool Sema::ParseSVEImmChecks(
3082 CallExpr *TheCall, SmallVector<std::tuple<int, int, int>, 3> &ImmChecks) {
3083 // Perform all the immediate checks for this builtin call.
3084 bool HasError = false;
3085 for (auto &I : ImmChecks) {
3086 int ArgNum, CheckTy, ElementSizeInBits;
3087 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
3088
3089 typedef bool (*OptionSetCheckFnTy)(int64_t Value);
3090
3091 // Function that checks whether the operand (ArgNum) is an immediate
3092 // that is one of the predefined values.
3093 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
3094 int ErrDiag) -> bool {
3095 // We can't check the value of a dependent argument.
3096 Expr *Arg = TheCall->getArg(ArgNum);
3097 if (Arg->isTypeDependent() || Arg->isValueDependent())
3098 return false;
3099
3100 // Check constant-ness first.
3101 llvm::APSInt Imm;
3102 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
3103 return true;
3104
3105 if (!CheckImm(Imm.getSExtValue()))
3106 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
3107 return false;
3108 };
3109
3110 switch ((SVETypeFlags::ImmCheckType)CheckTy) {
3111 case SVETypeFlags::ImmCheck0_31:
3112 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
3113 HasError = true;
3114 break;
3115 case SVETypeFlags::ImmCheck0_13:
3116 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
3117 HasError = true;
3118 break;
3119 case SVETypeFlags::ImmCheck1_16:
3120 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
3121 HasError = true;
3122 break;
3123 case SVETypeFlags::ImmCheck0_7:
3124 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
3125 HasError = true;
3126 break;
3127 case SVETypeFlags::ImmCheck1_1:
3128 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 1))
3129 HasError = true;
3130 break;
3131 case SVETypeFlags::ImmCheck1_3:
3132 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 3))
3133 HasError = true;
3134 break;
3135 case SVETypeFlags::ImmCheck1_7:
3136 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 7))
3137 HasError = true;
3138 break;
3139 case SVETypeFlags::ImmCheckExtract:
3140 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
3141 (2048 / ElementSizeInBits) - 1))
3142 HasError = true;
3143 break;
3144 case SVETypeFlags::ImmCheckShiftRight:
3145 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
3146 HasError = true;
3147 break;
3148 case SVETypeFlags::ImmCheckShiftRightNarrow:
3149 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
3150 ElementSizeInBits / 2))
3151 HasError = true;
3152 break;
3153 case SVETypeFlags::ImmCheckShiftLeft:
3154 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
3155 ElementSizeInBits - 1))
3156 HasError = true;
3157 break;
3158 case SVETypeFlags::ImmCheckLaneIndex:
3159 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
3160 (128 / (1 * ElementSizeInBits)) - 1))
3161 HasError = true;
3162 break;
3163 case SVETypeFlags::ImmCheckLaneIndexCompRotate:
3164 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
3165 (128 / (2 * ElementSizeInBits)) - 1))
3166 HasError = true;
3167 break;
3168 case SVETypeFlags::ImmCheckLaneIndexDot:
3169 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
3170 (128 / (4 * ElementSizeInBits)) - 1))
3171 HasError = true;
3172 break;
3173 case SVETypeFlags::ImmCheckComplexRot90_270:
3174 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
3175 diag::err_rotation_argument_to_cadd))
3176 HasError = true;
3177 break;
3178 case SVETypeFlags::ImmCheckComplexRotAll90:
3179 if (CheckImmediateInSet(
3180 [](int64_t V) {
3181 return V == 0 || V == 90 || V == 180 || V == 270;
3182 },
3183 diag::err_rotation_argument_to_cmla))
3184 HasError = true;
3185 break;
3186 case SVETypeFlags::ImmCheck0_1:
3187 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
3188 HasError = true;
3189 break;
3190 case SVETypeFlags::ImmCheck0_2:
3191 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
3192 HasError = true;
3193 break;
3194 case SVETypeFlags::ImmCheck0_3:
3195 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
3196 HasError = true;
3197 break;
3198 case SVETypeFlags::ImmCheck0_0:
3199 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 0))
3200 HasError = true;
3201 break;
3202 case SVETypeFlags::ImmCheck0_15:
3203 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 15))
3204 HasError = true;
3205 break;
3206 case SVETypeFlags::ImmCheck0_255:
3207 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 255))
3208 HasError = true;
3209 break;
3210 case SVETypeFlags::ImmCheck2_4_Mul2:
3211 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 2, 4) ||
3212 SemaBuiltinConstantArgMultiple(TheCall, ArgNum, 2))
3213 HasError = true;
3214 break;
3215 }
3216 }
3217
3218 return HasError;
3219}
3220
3222 if (FD->hasAttr<ArmLocallyStreamingAttr>())
3223 return ArmStreaming;
3224 if (const auto *T = FD->getType()->getAs<FunctionProtoType>()) {
3225 if (T->getAArch64SMEAttributes() & FunctionType::SME_PStateSMEnabledMask)
3226 return ArmStreaming;
3227 if (T->getAArch64SMEAttributes() & FunctionType::SME_PStateSMCompatibleMask)
3229 }
3230 return ArmNonStreaming;
3231}
3232
3233static void checkArmStreamingBuiltin(Sema &S, CallExpr *TheCall,
3234 const FunctionDecl *FD,
3238 // Check intrinsics that are available in [sve2p1 or sme/sme2].
3239 llvm::StringMap<bool> CallerFeatureMap;
3240 S.Context.getFunctionFeatureMap(CallerFeatureMap, FD);
3241 if (Builtin::evaluateRequiredTargetFeatures("sve2p1", CallerFeatureMap))
3243 else
3245 }
3246
3247 if (FnType == ArmStreaming && BuiltinType == ArmNonStreaming) {
3248 S.Diag(TheCall->getBeginLoc(), diag::warn_attribute_arm_sm_incompat_builtin)
3249 << TheCall->getSourceRange() << "streaming";
3250 }
3251
3252 if (FnType == ArmStreamingCompatible &&
3254 S.Diag(TheCall->getBeginLoc(), diag::warn_attribute_arm_sm_incompat_builtin)
3255 << TheCall->getSourceRange() << "streaming compatible";
3256 return;
3257 }
3258
3259 if (FnType == ArmNonStreaming && BuiltinType == ArmStreaming) {
3260 S.Diag(TheCall->getBeginLoc(), diag::warn_attribute_arm_sm_incompat_builtin)
3261 << TheCall->getSourceRange() << "non-streaming";
3262 }
3263}
3264
3265static bool hasArmZAState(const FunctionDecl *FD) {
3266 const auto *T = FD->getType()->getAs<FunctionProtoType>();
3267 return (T && FunctionType::getArmZAState(T->getAArch64SMEAttributes()) !=
3269 (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZA());
3270}
3271
3272static bool hasArmZT0State(const FunctionDecl *FD) {
3273 const auto *T = FD->getType()->getAs<FunctionProtoType>();
3274 return (T && FunctionType::getArmZT0State(T->getAArch64SMEAttributes()) !=
3276 (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZT0());
3277}
3278
3279static ArmSMEState getSMEState(unsigned BuiltinID) {
3280 switch (BuiltinID) {
3281 default:
3282 return ArmNoState;
3283#define GET_SME_BUILTIN_GET_STATE
3284#include "clang/Basic/arm_sme_builtins_za_state.inc"
3285#undef GET_SME_BUILTIN_GET_STATE
3286 }
3287}
3288
3289bool Sema::CheckSMEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3290 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3291 std::optional<ArmStreamingType> BuiltinType;
3292
3293 switch (BuiltinID) {
3294#define GET_SME_STREAMING_ATTRS
3295#include "clang/Basic/arm_sme_streaming_attrs.inc"
3296#undef GET_SME_STREAMING_ATTRS
3297 }
3298
3299 if (BuiltinType)
3300 checkArmStreamingBuiltin(*this, TheCall, FD, *BuiltinType);
3301
3302 if ((getSMEState(BuiltinID) & ArmZAMask) && !hasArmZAState(FD))
3303 Diag(TheCall->getBeginLoc(),
3304 diag::warn_attribute_arm_za_builtin_no_za_state)
3305 << TheCall->getSourceRange();
3306
3307 if ((getSMEState(BuiltinID) & ArmZT0Mask) && !hasArmZT0State(FD))
3308 Diag(TheCall->getBeginLoc(),
3309 diag::warn_attribute_arm_zt0_builtin_no_zt0_state)
3310 << TheCall->getSourceRange();
3311 }
3312
3313 // Range check SME intrinsics that take immediate values.
3315
3316 switch (BuiltinID) {
3317 default:
3318 return false;
3319#define GET_SME_IMMEDIATE_CHECK
3320#include "clang/Basic/arm_sme_sema_rangechecks.inc"
3321#undef GET_SME_IMMEDIATE_CHECK
3322 }
3323
3324 return ParseSVEImmChecks(TheCall, ImmChecks);
3325}
3326
3327bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3328 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3329 std::optional<ArmStreamingType> BuiltinType;
3330
3331 switch (BuiltinID) {
3332#define GET_SVE_STREAMING_ATTRS
3333#include "clang/Basic/arm_sve_streaming_attrs.inc"
3334#undef GET_SVE_STREAMING_ATTRS
3335 }
3336 if (BuiltinType)
3337 checkArmStreamingBuiltin(*this, TheCall, FD, *BuiltinType);
3338 }
3339 // Range check SVE intrinsics that take immediate values.
3341
3342 switch (BuiltinID) {
3343 default:
3344 return false;
3345#define GET_SVE_IMMEDIATE_CHECK
3346#include "clang/Basic/arm_sve_sema_rangechecks.inc"
3347#undef GET_SVE_IMMEDIATE_CHECK
3348 }
3349
3350 return ParseSVEImmChecks(TheCall, ImmChecks);
3351}
3352
3353bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
3354 unsigned BuiltinID, CallExpr *TheCall) {
3355 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3356
3357 switch (BuiltinID) {
3358 default:
3359 break;
3360#define GET_NEON_BUILTINS
3361#define TARGET_BUILTIN(id, ...) case NEON::BI##id:
3362#define BUILTIN(id, ...) case NEON::BI##id:
3363#include "clang/Basic/arm_neon.inc"
3364 checkArmStreamingBuiltin(*this, TheCall, FD, ArmNonStreaming);
3365 break;
3366#undef TARGET_BUILTIN
3367#undef BUILTIN
3368#undef GET_NEON_BUILTINS
3369 }
3370 }
3371
3372 llvm::APSInt Result;
3373 uint64_t mask = 0;
3374 unsigned TV = 0;
3375 int PtrArgNum = -1;
3376 bool HasConstPtr = false;
3377 switch (BuiltinID) {
3378#define GET_NEON_OVERLOAD_CHECK
3379#include "clang/Basic/arm_neon.inc"
3380#include "clang/Basic/arm_fp16.inc"
3381#undef GET_NEON_OVERLOAD_CHECK
3382 }
3383
3384 // For NEON intrinsics which are overloaded on vector element type, validate
3385 // the immediate which specifies which variant to emit.
3386 unsigned ImmArg = TheCall->getNumArgs()-1;
3387 if (mask) {
3388 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
3389 return true;
3390
3391 TV = Result.getLimitedValue(64);
3392 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
3393 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
3394 << TheCall->getArg(ImmArg)->getSourceRange();
3395 }
3396
3397 if (PtrArgNum >= 0) {
3398 // Check that pointer arguments have the specified type.
3399 Expr *Arg = TheCall->getArg(PtrArgNum);
3400 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
3401 Arg = ICE->getSubExpr();
3403 QualType RHSTy = RHS.get()->getType();
3404
3405 llvm::Triple::ArchType Arch = TI.getTriple().getArch();
3406 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
3407 Arch == llvm::Triple::aarch64_32 ||
3408 Arch == llvm::Triple::aarch64_be;
3409 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
3410 QualType EltTy =
3411 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
3412 if (HasConstPtr)
3413 EltTy = EltTy.withConst();
3414 QualType LHSTy = Context.getPointerType(EltTy);
3415 AssignConvertType ConvTy;
3416 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
3417 if (RHS.isInvalid())
3418 return true;
3419 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
3420 RHS.get(), AA_Assigning))
3421 return true;
3422 }
3423
3424 // For NEON intrinsics which take an immediate value as part of the
3425 // instruction, range check them here.
3426 unsigned i = 0, l = 0, u = 0;
3427 switch (BuiltinID) {
3428 default:
3429 return false;
3430 #define GET_NEON_IMMEDIATE_CHECK
3431 #include "clang/Basic/arm_neon.inc"
3432 #include "clang/Basic/arm_fp16.inc"
3433 #undef GET_NEON_IMMEDIATE_CHECK
3434 }
3435
3436 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
3437}
3438
3439bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3440 switch (BuiltinID) {
3441 default:
3442 return false;
3443 #include "clang/Basic/arm_mve_builtin_sema.inc"
3444 }
3445}
3446
3447bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3448 CallExpr *TheCall) {
3449 bool Err = false;
3450 switch (BuiltinID) {
3451 default:
3452 return false;
3453#include "clang/Basic/arm_cde_builtin_sema.inc"
3454 }
3455
3456 if (Err)
3457 return true;
3458
3459 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
3460}
3461
3462bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
3463 const Expr *CoprocArg, bool WantCDE) {
3465 return false;
3466
3467 // We can't check the value of a dependent argument.
3468 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
3469 return false;
3470
3471 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
3472 int64_t CoprocNo = CoprocNoAP.getExtValue();
3473 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
3474
3475 uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
3476 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
3477
3478 if (IsCDECoproc != WantCDE)
3479 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
3480 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
3481
3482 return false;
3483}
3484
3485bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
3486 unsigned MaxWidth) {
3487 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
3488 BuiltinID == ARM::BI__builtin_arm_ldaex ||
3489 BuiltinID == ARM::BI__builtin_arm_strex ||
3490 BuiltinID == ARM::BI__builtin_arm_stlex ||
3491 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
3492 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
3493 BuiltinID == AArch64::BI__builtin_arm_strex ||
3494 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
3495 "unexpected ARM builtin");
3496 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
3497 BuiltinID == ARM::BI__builtin_arm_ldaex ||
3498 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
3499 BuiltinID == AArch64::BI__builtin_arm_ldaex;
3500
3501 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3502
3503 // Ensure that we have the proper number of arguments.
3504 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
3505 return true;
3506
3507 // Inspect the pointer argument of the atomic builtin. This should always be
3508 // a pointer type, whose element is an integral scalar or pointer type.
3509 // Because it is a pointer type, we don't have to worry about any implicit
3510 // casts here.
3511 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
3512 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
3513 if (PointerArgRes.isInvalid())
3514 return true;
3515 PointerArg = PointerArgRes.get();
3516
3517 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3518 if (!pointerType) {
3519 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
3520 << PointerArg->getType() << PointerArg->getSourceRange();
3521 return true;
3522 }
3523
3524 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
3525 // task is to insert the appropriate casts into the AST. First work out just
3526 // what the appropriate type is.
3527 QualType ValType = pointerType->getPointeeType();
3528 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
3529 if (IsLdrex)
3530 AddrType.addConst();
3531
3532 // Issue a warning if the cast is dodgy.
3533 CastKind CastNeeded = CK_NoOp;
3534 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
3535 CastNeeded = CK_BitCast;
3536 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
3537 << PointerArg->getType() << Context.getPointerType(AddrType)
3538 << AA_Passing << PointerArg->getSourceRange();
3539 }
3540
3541 // Finally, do the cast and replace the argument with the corrected version.
3542 AddrType = Context.getPointerType(AddrType);
3543 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
3544 if (PointerArgRes.isInvalid())
3545 return true;
3546 PointerArg = PointerArgRes.get();
3547
3548 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
3549
3550 // In general, we allow ints, floats and pointers to be loaded and stored.
3551 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3552 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
3553 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
3554 << PointerArg->getType() << PointerArg->getSourceRange();
3555 return true;
3556 }
3557
3558 // But ARM doesn't have instructions to deal with 128-bit versions.
3559 if (Context.getTypeSize(ValType) > MaxWidth) {
3560 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
3561 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
3562 << PointerArg->getType() << PointerArg->getSourceRange();
3563 return true;
3564 }
3565
3566 switch (ValType.getObjCLifetime()) {
3569 // okay
3570 break;
3571
3575 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
3576 << ValType << PointerArg->getSourceRange();
3577 return true;
3578 }
3579
3580 if (IsLdrex) {
3581 TheCall->setType(ValType);
3582 return false;
3583 }
3584
3585 // Initialize the argument to be stored.
3586 ExprResult ValArg = TheCall->getArg(0);
3588 Context, ValType, /*consume*/ false);
3589 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3590 if (ValArg.isInvalid())
3591 return true;
3592 TheCall->setArg(0, ValArg.get());
3593
3594 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
3595 // but the custom checker bypasses all default analysis.
3596 TheCall->setType(Context.IntTy);
3597 return false;
3598}
3599
3600bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3601 CallExpr *TheCall) {
3602 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
3603 BuiltinID == ARM::BI__builtin_arm_ldaex ||
3604 BuiltinID == ARM::BI__builtin_arm_strex ||
3605 BuiltinID == ARM::BI__builtin_arm_stlex) {
3606 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
3607 }
3608
3609 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
3610 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3611 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
3612 }
3613
3614 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3615 BuiltinID == ARM::BI__builtin_arm_wsr64)
3616 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
3617
3618 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
3619 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3620 BuiltinID == ARM::BI__builtin_arm_wsr ||
3621 BuiltinID == ARM::BI__builtin_arm_wsrp)
3622 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
3623
3624 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
3625 return true;
3626 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
3627 return true;
3628 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
3629 return true;
3630
3631 // For intrinsics which take an immediate value as part of the instruction,
3632 // range check them here.
3633 // FIXME: VFP Intrinsics should error if VFP not present.
3634 switch (BuiltinID) {
3635 default: return false;
3636 case ARM::BI__builtin_arm_ssat:
3637 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
3638 case ARM::BI__builtin_arm_usat:
3639 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
3640 case ARM::BI__builtin_arm_ssat16:
3641 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3642 case ARM::BI__builtin_arm_usat16:
3643 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3644 case ARM::BI__builtin_arm_vcvtr_f:
3645 case ARM::BI__builtin_arm_vcvtr_d:
3646 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3647 case ARM::BI__builtin_arm_dmb:
3648 case ARM::BI__builtin_arm_dsb:
3649 case ARM::BI__builtin_arm_isb:
3650 case ARM::BI__builtin_arm_dbg:
3651 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
3652 case ARM::BI__builtin_arm_cdp:
3653 case ARM::BI__builtin_arm_cdp2:
3654 case ARM::BI__builtin_arm_mcr:
3655 case ARM::BI__builtin_arm_mcr2:
3656 case ARM::BI__builtin_arm_mrc:
3657 case ARM::BI__builtin_arm_mrc2:
3658 case ARM::BI__builtin_arm_mcrr:
3659 case ARM::BI__builtin_arm_mcrr2:
3660 case ARM::BI__builtin_arm_mrrc:
3661 case ARM::BI__builtin_arm_mrrc2:
3662 case ARM::BI__builtin_arm_ldc:
3663 case ARM::BI__builtin_arm_ldcl:
3664 case ARM::BI__builtin_arm_ldc2:
3665 case ARM::BI__builtin_arm_ldc2l:
3666 case ARM::BI__builtin_arm_stc:
3667 case ARM::BI__builtin_arm_stcl:
3668 case ARM::BI__builtin_arm_stc2:
3669 case ARM::BI__builtin_arm_stc2l:
3670 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
3671 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
3672 /*WantCDE*/ false);
3673 }
3674}
3675
3676bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
3677 unsigned BuiltinID,
3678 CallExpr *TheCall) {
3679 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
3680 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
3681 BuiltinID == AArch64::BI__builtin_arm_strex ||
3682 BuiltinID == AArch64::BI__builtin_arm_stlex) {
3683 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
3684 }
3685
3686 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
3687 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3688 SemaBuiltinConstantArgRange(TheCall, 2, 0, 3) ||
3689 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
3690 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
3691 }
3692
3693 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3694 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3695 BuiltinID == AArch64::BI__builtin_arm_rsr128 ||
3696 BuiltinID == AArch64::BI__builtin_arm_wsr128)
3697 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
3698
3699 // Memory Tagging Extensions (MTE) Intrinsics
3700 if (BuiltinID == AArch64::BI__builtin_arm_irg ||
3701 BuiltinID == AArch64::BI__builtin_arm_addg ||
3702 BuiltinID == AArch64::BI__builtin_arm_gmi ||
3703 BuiltinID == AArch64::BI__builtin_arm_ldg ||
3704 BuiltinID == AArch64::BI__builtin_arm_stg ||
3705 BuiltinID == AArch64::BI__builtin_arm_subp) {
3706 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
3707 }
3708
3709 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
3710 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3711 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3712 BuiltinID == AArch64::BI__builtin_arm_wsrp)
3713 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
3714
3715 // Only check the valid encoding range. Any constant in this range would be
3716 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
3717 // an exception for incorrect registers. This matches MSVC behavior.
3718 if (BuiltinID == AArch64::BI_ReadStatusReg ||
3719 BuiltinID == AArch64::BI_WriteStatusReg)
3720 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
3721
3722 if (BuiltinID == AArch64::BI__getReg)
3723 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3724
3725 if (BuiltinID == AArch64::BI__break)
3726 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xffff);
3727
3728 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
3729 return true;
3730
3731 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
3732 return true;
3733
3734 if (CheckSMEBuiltinFunctionCall(BuiltinID, TheCall))
3735 return true;
3736
3737 // For intrinsics which take an immediate value as part of the instruction,
3738 // range check them here.
3739 unsigned i = 0, l = 0, u = 0;
3740 switch (BuiltinID) {
3741 default: return false;
3742 case AArch64::BI__builtin_arm_dmb:
3743 case AArch64::BI__builtin_arm_dsb:
3744 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
3745 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
3746 }
3747
3748 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
3749}
3750
3752 if (Arg->getType()->getAsPlaceholderType())
3753 return false;
3754
3755 // The first argument needs to be a record field access.
3756 // If it is an array element access, we delay decision
3757 // to BPF backend to check whether the access is a
3758 // field access or not.
3759 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
3760 isa<MemberExpr>(Arg->IgnoreParens()) ||
3761 isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
3762}
3763
3765 QualType ArgType = Arg->getType();
3766 if (ArgType->getAsPlaceholderType())
3767 return false;
3768
3769 // for TYPE_EXISTENCE/TYPE_MATCH/TYPE_SIZEOF reloc type
3770 // format:
3771 // 1. __builtin_preserve_type_info(*(<type> *)0, flag);
3772 // 2. <type> var;
3773 // __builtin_preserve_type_info(var, flag);
3774 if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
3775 !isa<UnaryOperator>(Arg->IgnoreParens()))
3776 return false;
3777
3778 // Typedef type.
3779 if (ArgType->getAs<TypedefType>())
3780 return true;
3781
3782 // Record type or Enum type.
3783 const Type *Ty = ArgType->getUnqualifiedDesugaredType();
3784 if (const auto *RT = Ty->getAs<RecordType>()) {
3785 if (!RT->getDecl()->getDeclName().isEmpty())
3786 return true;
3787 } else if (const auto *ET = Ty->getAs<EnumType>()) {
3788 if (!ET->getDecl()->getDeclName().isEmpty())
3789 return true;
3790 }
3791
3792 return false;
3793}
3794
3796 QualType ArgType = Arg->getType();
3797 if (ArgType->getAsPlaceholderType())
3798 return false;
3799
3800 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
3801 // format:
3802 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
3803 // flag);
3804 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
3805 if (!UO)
3806 return false;
3807
3808 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
3809 if (!CE)
3810 return false;
3811 if (CE->getCastKind() != CK_IntegralToPointer &&
3812 CE->getCastKind() != CK_NullToPointer)
3813 return false;
3814
3815 // The integer must be from an EnumConstantDecl.
3816 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
3817 if (!DR)
3818 return false;
3819
3820 const EnumConstantDecl *Enumerator =
3821 dyn_cast<EnumConstantDecl>(DR->getDecl());
3822 if (!Enumerator)
3823 return false;
3824
3825 // The type must be EnumType.
3826 const Type *Ty = ArgType->getUnqualifiedDesugaredType();
3827 const auto *ET = Ty->getAs<EnumType>();
3828 if (!ET)
3829 return false;
3830
3831 // The enum value must be supported.
3832 return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
3833}
3834
3835bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
3836 CallExpr *TheCall) {
3837 assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
3838 BuiltinID == BPF::BI__builtin_btf_type_id ||
3839 BuiltinID == BPF::BI__builtin_preserve_type_info ||
3840 BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
3841 "unexpected BPF builtin");
3842
3843 if (checkArgCount(*this, TheCall, 2))
3844 return true;
3845
3846 // The second argument needs to be a constant int
3847 Expr *Arg = TheCall->getArg(1);
3848 std::optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
3850 if (!Value) {
3851 if (BuiltinID == BPF::BI__builtin_preserve_field_info)
3852 kind = diag::err_preserve_field_info_not_const;
3853 else if (BuiltinID == BPF::BI__builtin_btf_type_id)
3854 kind = diag::err_btf_type_id_not_const;
3855 else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
3856 kind = diag::err_preserve_type_info_not_const;
3857 else
3858 kind = diag::err_preserve_enum_value_not_const;
3859 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
3860 return true;
3861 }
3862
3863 // The first argument
3864 Arg = TheCall->getArg(0);
3865 bool InvalidArg = false;
3866 bool ReturnUnsignedInt = true;
3867 if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
3869 InvalidArg = true;
3870 kind = diag::err_preserve_field_info_not_field;
3871 }
3872 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
3874 InvalidArg = true;
3875 kind = diag::err_preserve_type_info_invalid;
3876 }
3877 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
3879 InvalidArg = true;
3880 kind = diag::err_preserve_enum_value_invalid;
3881 }
3882 ReturnUnsignedInt = false;
3883 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
3884 ReturnUnsignedInt = false;
3885 }
3886
3887 if (InvalidArg) {
3888 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
3889 return true;
3890 }
3891
3892 if (ReturnUnsignedInt)
3893 TheCall->setType(Context.UnsignedIntTy);
3894 else
3895 TheCall->setType(Context.UnsignedLongTy);
3896 return false;
3897}
3898
3899bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3900 struct ArgInfo {
3901 uint8_t OpNum;
3902 bool IsSigned;
3903 uint8_t BitWidth;
3904 uint8_t Align;
3905 };
3906 struct BuiltinInfo {
3907 unsigned BuiltinID;
3908 ArgInfo Infos[2];
3909 };
3910
3911 static BuiltinInfo Infos[] = {
3912 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
3913 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
3914 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
3915 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} },
3916 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
3917 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
3918 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
3919 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
3920 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
3921 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
3922 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
3923
3924 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
3925 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
3926 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
3927 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
3928 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
3929 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
3930 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
3931 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
3932 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
3933 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
3934 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
3935
3936 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
3937 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
3938 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
3939 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
3940 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
3941 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
3942 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
3943 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
3944 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
3945 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
3946 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
3947 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
3948 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
3949 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
3950 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
3951 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
3952 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
3953 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
3954 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
3955 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
3956 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
3957 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
3958 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
3959 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
3960 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
3961 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
3962 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
3963 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
3964 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
3965 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
3966 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
3967 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
3968 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
3969 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
3970 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
3971 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
3972 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
3973 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
3974 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
3975 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
3976 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
3977 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
3978 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
3979 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
3980 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
3981 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
3982 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
3983 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
3984 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
3985 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
3986 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
3987 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
3988 {{ 1, false, 6, 0 }} },
3989 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
3990 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
3991 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
3992 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
3993 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
3994 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
3995 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
3996 {{ 1, false, 5, 0 }} },
3997 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
3998 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
3999 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
4000 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
4001 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
4002 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
4003 { 2, false, 5, 0 }} },
4004 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
4005 { 2, false, 6, 0 }} },
4006 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
4007 { 3, false, 5, 0 }} },
4008 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
4009 { 3, false, 6, 0 }} },
4010 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
4011 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
4012 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
4013 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
4014 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
4015 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
4016 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
4017 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
4018 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
4019 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
4020 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
4021 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
4022 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
4023 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
4024 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
4025 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
4026 {{ 2, false, 4, 0 },
4027 { 3, false, 5, 0 }} },
4028 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
4029 {{ 2, false, 4, 0 },
4030 { 3, false, 5, 0 }} },
4031 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
4032 {{ 2, false, 4, 0 },
4033 { 3, false, 5, 0 }} },
4034 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
4035 {{ 2, false, 4, 0 },
4036 { 3, false, 5, 0 }} },
4037 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
4038 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
4039 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
4040 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
4041 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
4042 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
4043 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
4044 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
4045 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
4046 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
4047 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
4048 { 2, false, 5, 0 }} },
4049 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
4050 { 2, false, 6, 0 }} },
4051 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
4052 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
4053 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
4054 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
4055 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
4056 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
4057 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
4058 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
4059 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
4060 {{ 1, false, 4, 0 }} },
4061 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
4062 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
4063 {{ 1, false, 4, 0 }} },
4064 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
4065 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
4066 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
4067 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
4068 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
4069 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
4070 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
4071 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
4072 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
4073 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
4074 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
4075 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
4076 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
4077 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
4078 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
4079 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
4080 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
4081 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
4082 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
4083 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
4084 {{ 3, false, 1, 0 }} },
4085 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
4086 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
4087 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
4088 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
4089 {{ 3, false, 1, 0 }} },
4090 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
4091 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
4092 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
4093 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
4094 {{ 3, false, 1, 0 }} },
4095
4096 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10, {{ 2, false, 2, 0 }} },
4097 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10_128B,
4098 {{ 2, false, 2, 0 }} },
4099 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10_vxx,
4100 {{ 3, false, 2, 0 }} },
4101 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10_vxx_128B,
4102 {{ 3, false, 2, 0 }} },
4103 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10, {{ 2, false, 2, 0 }} },
4104 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10_128B,
4105 {{ 2, false, 2, 0 }} },
4106 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10_vxx,
4107 {{ 3, false, 2, 0 }} },
4108 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10_vxx_128B,
4109 {{ 3, false, 2, 0 }} },
4110 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, {{ 2, false, 3, 0 }} },
4111 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, {{ 2, false, 3, 0 }} },
4112 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, {{ 3, false, 3, 0 }} },
4113 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B,
4114 {{ 3, false, 3, 0 }} },
4115 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, {{ 2, false, 3, 0 }} },
4116 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, {{ 2, false, 3, 0 }} },
4117 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, {{ 3, false, 3, 0 }} },
4118 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B,
4119 {{ 3, false, 3, 0 }} },
4120 };
4121
4122 // Use a dynamically initialized static to sort the table exactly once on
4123 // first run.
4124 static const bool SortOnce =
4125 (llvm::sort(Infos,
4126 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
4127 return LHS.BuiltinID < RHS.BuiltinID;
4128 }),
4129 true);
4130 (void)SortOnce;
4131
4132 const BuiltinInfo *F = llvm::partition_point(
4133 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
4134 if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
4135 return false;
4136
4137 bool Error = false;
4138
4139 for (const ArgInfo &A : F->Infos) {
4140 // Ignore empty ArgInfo elements.
4141 if (A.BitWidth == 0)
4142 continue;
4143
4144 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
4145 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
4146 if (!A.Align) {
4147 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
4148 } else {
4149 unsigned M = 1 << A.Align;
4150 Min *= M;
4151 Max *= M;
4152 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
4153 Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
4154 }
4155 }
4156 return Error;
4157}
4158
4159bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
4160 CallExpr *TheCall) {
4161 return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
4162}
4163
4164bool Sema::CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI,
4165 unsigned BuiltinID,
4166 CallExpr *TheCall) {
4167 switch (BuiltinID) {
4168 default:
4169 break;
4170 // Basic intrinsics.
4171 case LoongArch::BI__builtin_loongarch_cacop_d:
4172 case LoongArch::BI__builtin_loongarch_cacop_w: {
4173 SemaBuiltinConstantArgRange(TheCall, 0, 0, llvm::maxUIntN(5));
4174 SemaBuiltinConstantArgRange(TheCall, 2, llvm::minIntN(12),
4175 llvm::maxIntN(12));
4176 break;
4177 }
4178 case LoongArch::BI__builtin_loongarch_break:
4179 case LoongArch::BI__builtin_loongarch_dbar:
4180 case LoongArch::BI__builtin_loongarch_ibar:
4181 case LoongArch::BI__builtin_loongarch_syscall:
4182 // Check if immediate is in [0, 32767].
4183 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 32767);
4184 case LoongArch::BI__builtin_loongarch_csrrd_w:
4185 case LoongArch::BI__builtin_loongarch_csrrd_d:
4186 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 16383);
4187 case LoongArch::BI__builtin_loongarch_csrwr_w:
4188 case LoongArch::BI__builtin_loongarch_csrwr_d:
4189 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 16383);
4190 case LoongArch::BI__builtin_loongarch_csrxchg_w:
4191 case LoongArch::BI__builtin_loongarch_csrxchg_d:
4192 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 16383);
4193 case LoongArch::BI__builtin_loongarch_lddir_d:
4194 case LoongArch::BI__builtin_loongarch_ldpte_d:
4195 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
4196 case LoongArch::BI__builtin_loongarch_movfcsr2gr:
4197 case LoongArch::BI__builtin_loongarch_movgr2fcsr:
4198 return SemaBuiltinConstantArgRange(TheCall, 0, 0, llvm::maxUIntN(2));
4199
4200 // LSX intrinsics.
4201 case LoongArch::BI__builtin_lsx_vbitclri_b:
4202 case LoongArch::BI__builtin_lsx_vbitrevi_b:
4203 case LoongArch::BI__builtin_lsx_vbitseti_b:
4204 case LoongArch::BI__builtin_lsx_vsat_b:
4205 case LoongArch::BI__builtin_lsx_vsat_bu:
4206 case LoongArch::BI__builtin_lsx_vslli_b:
4207 case LoongArch::BI__builtin_lsx_vsrai_b:
4208 case LoongArch::BI__builtin_lsx_vsrari_b:
4209 case LoongArch::BI__builtin_lsx_vsrli_b:
4210 case LoongArch::BI__builtin_lsx_vsllwil_h_b:
4211 case LoongArch::BI__builtin_lsx_vsllwil_hu_bu:
4212 case LoongArch::BI__builtin_lsx_vrotri_b:
4213 case LoongArch::BI__builtin_lsx_vsrlri_b:
4214 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
4215 case LoongArch::BI__builtin_lsx_vbitclri_h:
4216 case LoongArch::BI__builtin_lsx_vbitrevi_h:
4217 case LoongArch::BI__builtin_lsx_vbitseti_h:
4218 case LoongArch::BI__builtin_lsx_vsat_h:
4219 case LoongArch::BI__builtin_lsx_vsat_hu:
4220 case LoongArch::BI__builtin_lsx_vslli_h:
4221 case LoongArch::BI__builtin_lsx_vsrai_h:
4222 case LoongArch::BI__builtin_lsx_vsrari_h:
4223 case LoongArch::BI__builtin_lsx_vsrli_h:
4224 case LoongArch::BI__builtin_lsx_vsllwil_w_h:
4225 case LoongArch::BI__builtin_lsx_vsllwil_wu_hu:
4226 case LoongArch::BI__builtin_lsx_vrotri_h:
4227 case LoongArch::BI__builtin_lsx_vsrlri_h:
4228 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4229 case LoongArch::BI__builtin_lsx_vssrarni_b_h:
4230 case LoongArch::BI__builtin_lsx_vssrarni_bu_h:
4231 case LoongArch::BI__builtin_lsx_vssrani_b_h:
4232 case LoongArch::BI__builtin_lsx_vssrani_bu_h:
4233 case LoongArch::BI__builtin_lsx_vsrarni_b_h:
4234 case LoongArch::BI__builtin_lsx_vsrlni_b_h:
4235 case LoongArch::BI__builtin_lsx_vsrlrni_b_h:
4236 case LoongArch::BI__builtin_lsx_vssrlni_b_h:
4237 case LoongArch::BI__builtin_lsx_vssrlni_bu_h:
4238 case LoongArch::BI__builtin_lsx_vssrlrni_b_h:
4239 case LoongArch::BI__builtin_lsx_vssrlrni_bu_h:
4240 case LoongArch::BI__builtin_lsx_vsrani_b_h:
4241 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
4242 case LoongArch::BI__builtin_lsx_vslei_bu:
4243 case LoongArch::BI__builtin_lsx_vslei_hu:
4244 case LoongArch::BI__builtin_lsx_vslei_wu:
4245 case LoongArch::BI__builtin_lsx_vslei_du:
4246 case LoongArch::BI__builtin_lsx_vslti_bu:
4247 case LoongArch::BI__builtin_lsx_vslti_hu:
4248 case LoongArch::BI__builtin_lsx_vslti_wu:
4249 case LoongArch::BI__builtin_lsx_vslti_du:
4250 case LoongArch::BI__builtin_lsx_vmaxi_bu:
4251 case LoongArch::BI__builtin_lsx_vmaxi_hu:
4252 case LoongArch::BI__builtin_lsx_vmaxi_wu:
4253 case LoongArch::BI__builtin_lsx_vmaxi_du:
4254 case LoongArch::BI__builtin_lsx_vmini_bu:
4255 case LoongArch::BI__builtin_lsx_vmini_hu:
4256 case LoongArch::BI__builtin_lsx_vmini_wu:
4257 case LoongArch::BI__builtin_lsx_vmini_du:
4258 case LoongArch::BI__builtin_lsx_vaddi_bu:
4259 case LoongArch::BI__builtin_lsx_vaddi_hu:
4260 case LoongArch::BI__builtin_lsx_vaddi_wu:
4261 case LoongArch::BI__builtin_lsx_vaddi_du:
4262 case LoongArch::BI__builtin_lsx_vbitclri_w:
4263 case LoongArch::BI__builtin_lsx_vbitrevi_w:
4264 case LoongArch::BI__builtin_lsx_vbitseti_w:
4265 case LoongArch::BI__builtin_lsx_vsat_w:
4266 case LoongArch::BI__builtin_lsx_vsat_wu:
4267 case LoongArch::BI__builtin_lsx_vslli_w:
4268 case LoongArch::BI__builtin_lsx_vsrai_w:
4269 case LoongArch::BI__builtin_lsx_vsrari_w:
4270 case LoongArch::BI__builtin_lsx_vsrli_w:
4271 case LoongArch::BI__builtin_lsx_vsllwil_d_w:
4272 case LoongArch::BI__builtin_lsx_vsllwil_du_wu:
4273 case LoongArch::BI__builtin_lsx_vsrlri_w:
4274 case LoongArch::BI__builtin_lsx_vrotri_w:
4275 case LoongArch::BI__builtin_lsx_vsubi_bu:
4276 case LoongArch::BI__builtin_lsx_vsubi_hu:
4277 case LoongArch::BI__builtin_lsx_vbsrl_v:
4278 case LoongArch::BI__builtin_lsx_vbsll_v:
4279 case LoongArch::BI__builtin_lsx_vsubi_wu:
4280 case LoongArch::BI__builtin_lsx_vsubi_du:
4281 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
4282 case LoongArch::BI__builtin_lsx_vssrarni_h_w:
4283 case LoongArch::BI__builtin_lsx_vssrarni_hu_w:
4284 case LoongArch::BI__builtin_lsx_vssrani_h_w:
4285 case LoongArch::BI__builtin_lsx_vssrani_hu_w:
4286 case LoongArch::BI__builtin_lsx_vsrarni_h_w:
4287 case LoongArch::BI__builtin_lsx_vsrani_h_w:
4288 case LoongArch::BI__builtin_lsx_vfrstpi_b:
4289 case LoongArch::BI__builtin_lsx_vfrstpi_h:
4290 case LoongArch::BI__builtin_lsx_vsrlni_h_w:
4291 case LoongArch::BI__builtin_lsx_vsrlrni_h_w:
4292 case LoongArch::BI__builtin_lsx_vssrlni_h_w:
4293 case LoongArch::BI__builtin_lsx_vssrlni_hu_w:
4294 case LoongArch::BI__builtin_lsx_vssrlrni_h_w:
4295 case LoongArch::BI__builtin_lsx_vssrlrni_hu_w:
4296 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
4297 case LoongArch::BI__builtin_lsx_vbitclri_d:
4298 case LoongArch::BI__builtin_lsx_vbitrevi_d:
4299 case LoongArch::BI__builtin_lsx_vbitseti_d:
4300 case LoongArch::BI__builtin_lsx_vsat_d:
4301 case LoongArch::BI__builtin_lsx_vsat_du:
4302 case LoongArch::BI__builtin_lsx_vslli_d:
4303 case LoongArch::BI__builtin_lsx_vsrai_d:
4304 case LoongArch::BI__builtin_lsx_vsrli_d:
4305 case LoongArch::BI__builtin_lsx_vsrari_d:
4306 case LoongArch::BI__builtin_lsx_vrotri_d:
4307 case LoongArch::BI__builtin_lsx_vsrlri_d:
4308 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 63);
4309 case LoongArch::BI__builtin_lsx_vssrarni_w_d:
4310 case LoongArch::BI__builtin_lsx_vssrarni_wu_d:
4311 case LoongArch::BI__builtin_lsx_vssrani_w_d:
4312 case LoongArch::BI__builtin_lsx_vssrani_wu_d:
4313 case LoongArch::BI__builtin_lsx_vsrarni_w_d:
4314 case LoongArch::BI__builtin_lsx_vsrlni_w_d:
4315 case LoongArch::BI__builtin_lsx_vsrlrni_w_d:
4316 case LoongArch::BI__builtin_lsx_vssrlni_w_d:
4317 case LoongArch::BI__builtin_lsx_vssrlni_wu_d:
4318 case LoongArch::BI__builtin_lsx_vssrlrni_w_d:
4319 case LoongArch::BI__builtin_lsx_vssrlrni_wu_d:
4320 case LoongArch::BI__builtin_lsx_vsrani_w_d:
4321 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 63);
4322 case LoongArch::BI__builtin_lsx_vssrarni_d_q:
4323 case LoongArch::BI__builtin_lsx_vssrarni_du_q:
4324 case LoongArch::BI__builtin_lsx_vssrani_d_q:
4325 case LoongArch::BI__builtin_lsx_vssrani_du_q:
4326 case LoongArch::BI__builtin_lsx_vsrarni_d_q:
4327 case LoongArch::BI__builtin_lsx_vssrlni_d_q:
4328 case LoongArch::BI__builtin_lsx_vssrlni_du_q:
4329 case LoongArch::BI__builtin_lsx_vssrlrni_d_q:
4330 case LoongArch::BI__builtin_lsx_vssrlrni_du_q:
4331 case LoongArch::BI__builtin_lsx_vsrani_d_q:
4332 case LoongArch::BI__builtin_lsx_vsrlrni_d_q:
4333 case LoongArch::BI__builtin_lsx_vsrlni_d_q:
4334 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 127);
4335 case LoongArch::BI__builtin_lsx_vseqi_b:
4336 case LoongArch::BI__builtin_lsx_vseqi_h:
4337 case LoongArch::BI__builtin_lsx_vseqi_w:
4338 case LoongArch::BI__builtin_lsx_vseqi_d:
4339 case LoongArch::BI__builtin_lsx_vslti_b:
4340 case LoongArch::BI__builtin_lsx_vslti_h:
4341 case LoongArch::BI__builtin_lsx_vslti_w:
4342 case LoongArch::BI__builtin_lsx_vslti_d:
4343 case LoongArch::BI__builtin_lsx_vslei_b:
4344 case LoongArch::BI__builtin_lsx_vslei_h:
4345 case LoongArch::BI__builtin_lsx_vslei_w:
4346 case LoongArch::BI__builtin_lsx_vslei_d:
4347 case LoongArch::BI__builtin_lsx_vmaxi_b:
4348 case LoongArch::BI__builtin_lsx_vmaxi_h:
4349 case LoongArch::BI__builtin_lsx_vmaxi_w:
4350 case LoongArch::BI__builtin_lsx_vmaxi_d:
4351 case LoongArch::BI__builtin_lsx_vmini_b:
4352 case LoongArch::BI__builtin_lsx_vmini_h:
4353 case LoongArch::BI__builtin_lsx_vmini_w:
4354 case LoongArch::BI__builtin_lsx_vmini_d:
4355 return SemaBuiltinConstantArgRange(TheCall, 1, -16, 15);
4356 case LoongArch::BI__builtin_lsx_vandi_b:
4357 case LoongArch::BI__builtin_lsx_vnori_b:
4358 case LoongArch::BI__builtin_lsx_vori_b:
4359 case LoongArch::BI__builtin_lsx_vshuf4i_b:
4360 case LoongArch::BI__builtin_lsx_vshuf4i_h:
4361 case LoongArch::BI__builtin_lsx_vshuf4i_w:
4362 case LoongArch::BI__builtin_lsx_vxori_b:
4363 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 255);
4364 case LoongArch::BI__builtin_lsx_vbitseli_b:
4365 case LoongArch::BI__builtin_lsx_vshuf4i_d:
4366 case LoongArch::BI__builtin_lsx_vextrins_b:
4367 case LoongArch::BI__builtin_lsx_vextrins_h:
4368 case LoongArch::BI__builtin_lsx_vextrins_w:
4369 case LoongArch::BI__builtin_lsx_vextrins_d:
4370 case LoongArch::BI__builtin_lsx_vpermi_w:
4371 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 255);
4372 case LoongArch::BI__builtin_lsx_vpickve2gr_b:
4373 case LoongArch::BI__builtin_lsx_vpickve2gr_bu:
4374 case LoongArch::BI__builtin_lsx_vreplvei_b:
4375 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4376 case LoongArch::BI__builtin_lsx_vinsgr2vr_b:
4377 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
4378 case LoongArch::BI__builtin_lsx_vpickve2gr_h:
4379 case LoongArch::BI__builtin_lsx_vpickve2gr_hu:
4380 case LoongArch::BI__builtin_lsx_vreplvei_h:
4381 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
4382 case LoongArch::BI__builtin_lsx_vinsgr2vr_h:
4383 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
4384 case LoongArch::BI__builtin_lsx_vpickve2gr_w:
4385 case LoongArch::BI__builtin_lsx_vpickve2gr_wu:
4386 case LoongArch::BI__builtin_lsx_vreplvei_w:
4387 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
4388 case LoongArch::BI__builtin_lsx_vinsgr2vr_w:
4389 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
4390 case LoongArch::BI__builtin_lsx_vpickve2gr_d:
4391 case LoongArch::BI__builtin_lsx_vpickve2gr_du:
4392 case LoongArch::BI__builtin_lsx_vreplvei_d:
4393 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
4394 case LoongArch::BI__builtin_lsx_vinsgr2vr_d:
4395 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
4396 case LoongArch::BI__builtin_lsx_vstelm_b:
4397 return SemaBuiltinConstantArgRange(TheCall, 2, -128, 127) ||
4398 SemaBuiltinConstantArgRange(TheCall, 3, 0, 15);
4399 case LoongArch::BI__builtin_lsx_vstelm_h:
4400 return SemaBuiltinConstantArgRange(TheCall, 2, -256, 254) ||
4401 SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
4402 case LoongArch::BI__builtin_lsx_vstelm_w:
4403 return SemaBuiltinConstantArgRange(TheCall, 2, -512, 508) ||
4404 SemaBuiltinConstantArgRange(TheCall, 3, 0, 3);
4405 case LoongArch::BI__builtin_lsx_vstelm_d:
4406 return SemaBuiltinConstantArgRange(TheCall, 2, -1024, 1016) ||
4407 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1);
4408 case LoongArch::BI__builtin_lsx_vldrepl_b:
4409 case LoongArch::BI__builtin_lsx_vld:
4410 return SemaBuiltinConstantArgRange(TheCall, 1, -2048, 2047);
4411 case LoongArch::BI__builtin_lsx_vldrepl_h:
4412 return SemaBuiltinConstantArgRange(TheCall, 1, -2048, 2046);
4413 case LoongArch::BI__builtin_lsx_vldrepl_w:
4414 return SemaBuiltinConstantArgRange(TheCall, 1, -2048, 2044);
4415 case LoongArch::BI__builtin_lsx_vldrepl_d:
4416 return SemaBuiltinConstantArgRange(TheCall, 1, -2048, 2040);
4417 case LoongArch::BI__builtin_lsx_vst:
4418 return SemaBuiltinConstantArgRange(TheCall, 2, -2048, 2047);
4419 case LoongArch::BI__builtin_lsx_vldi:
4420 return SemaBuiltinConstantArgRange(TheCall, 0, -4096, 4095);
4421 case LoongArch::BI__builtin_lsx_vrepli_b:
4422 case LoongArch::BI__builtin_lsx_vrepli_h:
4423 case LoongArch::BI__builtin_lsx_vrepli_w:
4424 case LoongArch::BI__builtin_lsx_vrepli_d:
4425 return SemaBuiltinConstantArgRange(TheCall, 0, -512, 511);
4426
4427 // LASX intrinsics.
4428 case LoongArch::BI__builtin_lasx_xvbitclri_b:
4429 case LoongArch::BI__builtin_lasx_xvbitrevi_b:
4430 case LoongArch::BI__builtin_lasx_xvbitseti_b:
4431 case LoongArch::BI__builtin_lasx_xvsat_b:
4432 case LoongArch::BI__builtin_lasx_xvsat_bu:
4433 case LoongArch::BI__builtin_lasx_xvslli_b:
4434 case LoongArch::BI__builtin_lasx_xvsrai_b:
4435 case LoongArch::BI__builtin_lasx_xvsrari_b:
4436 case LoongArch::BI__builtin_lasx_xvsrli_b:
4437 case LoongArch::BI__builtin_lasx_xvsllwil_h_b:
4438 case LoongArch::BI__builtin_lasx_xvsllwil_hu_bu:
4439 case LoongArch::BI__builtin_lasx_xvrotri_b:
4440 case LoongArch::BI__builtin_lasx_xvsrlri_b:
4441 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
4442 case LoongArch::BI__builtin_lasx_xvbitclri_h:
4443 case LoongArch::BI__builtin_lasx_xvbitrevi_h:
4444 case LoongArch::BI__builtin_lasx_xvbitseti_h:
4445 case LoongArch::BI__builtin_lasx_xvsat_h:
4446 case LoongArch::BI__builtin_lasx_xvsat_hu:
4447 case LoongArch::BI__builtin_lasx_xvslli_h:
4448 case LoongArch::BI__builtin_lasx_xvsrai_h:
4449 case LoongArch::BI__builtin_lasx_xvsrari_h:
4450 case LoongArch::BI__builtin_lasx_xvsrli_h:
4451 case LoongArch::BI__builtin_lasx_xvsllwil_w_h:
4452 case LoongArch::BI__builtin_lasx_xvsllwil_wu_hu:
4453 case LoongArch::BI__builtin_lasx_xvrotri_h:
4454 case LoongArch::BI__builtin_lasx_xvsrlri_h:
4455 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4456 case LoongArch::BI__builtin_lasx_xvssrarni_b_h:
4457 case LoongArch::BI__builtin_lasx_xvssrarni_bu_h:
4458 case LoongArch::BI__builtin_lasx_xvssrani_b_h:
4459 case LoongArch::BI__builtin_lasx_xvssrani_bu_h:
4460 case LoongArch::BI__builtin_lasx_xvsrarni_b_h:
4461 case LoongArch::BI__builtin_lasx_xvsrlni_b_h:
4462 case LoongArch::BI__builtin_lasx_xvsrlrni_b_h:
4463 case LoongArch::BI__builtin_lasx_xvssrlni_b_h:
4464 case LoongArch::BI__builtin_lasx_xvssrlni_bu_h:
4465 case LoongArch::BI__builtin_lasx_xvssrlrni_b_h:
4466 case LoongArch::BI__builtin_lasx_xvssrlrni_bu_h:
4467 case LoongArch::BI__builtin_lasx_xvsrani_b_h:
4468 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
4469 case LoongArch::BI__builtin_lasx_xvslei_bu:
4470 case LoongArch::BI__builtin_lasx_xvslei_hu:
4471 case LoongArch::BI__builtin_lasx_xvslei_wu:
4472 case LoongArch::BI__builtin_lasx_xvslei_du:
4473 case LoongArch::BI__builtin_lasx_xvslti_bu:
4474 case LoongArch::BI__builtin_lasx_xvslti_hu:
4475 case LoongArch::BI__builtin_lasx_xvslti_wu:
4476 case LoongArch::BI__builtin_lasx_xvslti_du:
4477 case LoongArch::BI__builtin_lasx_xvmaxi_bu:
4478 case LoongArch::BI__builtin_lasx_xvmaxi_hu:
4479 case LoongArch::BI__builtin_lasx_xvmaxi_wu:
4480 case LoongArch::BI__builtin_lasx_xvmaxi_du:
4481 case LoongArch::BI__builtin_lasx_xvmini_bu:
4482 case LoongArch::BI__builtin_lasx_xvmini_hu:
4483 case LoongArch::BI__builtin_lasx_xvmini_wu:
4484 case LoongArch::BI__builtin_lasx_xvmini_du:
4485 case LoongArch::BI__builtin_lasx_xvaddi_bu:
4486 case LoongArch::BI__builtin_lasx_xvaddi_hu:
4487 case LoongArch::BI__builtin_lasx_xvaddi_wu:
4488 case LoongArch::BI__builtin_lasx_xvaddi_du:
4489 case LoongArch::BI__builtin_lasx_xvbitclri_w:
4490 case LoongArch::BI__builtin_lasx_xvbitrevi_w:
4491 case LoongArch::BI__builtin_lasx_xvbitseti_w:
4492 case LoongArch::BI__builtin_lasx_xvsat_w:
4493 case LoongArch::BI__builtin_lasx_xvsat_wu:
4494 case LoongArch::BI__builtin_lasx_xvslli_w:
4495 case LoongArch::BI__builtin_lasx_xvsrai_w:
4496 case LoongArch::BI__builtin_lasx_xvsrari_w:
4497 case LoongArch::BI__builtin_lasx_xvsrli_w:
4498 case LoongArch::BI__builtin_lasx_xvsllwil_d_w:
4499 case LoongArch::BI__builtin_lasx_xvsllwil_du_wu:
4500 case LoongArch::BI__builtin_lasx_xvsrlri_w:
4501 case LoongArch::BI__builtin_lasx_xvrotri_w:
4502 case LoongArch::BI__builtin_lasx_xvsubi_bu:
4503 case LoongArch::BI__builtin_lasx_xvsubi_hu:
4504 case LoongArch::BI__builtin_lasx_xvsubi_wu:
4505 case LoongArch::BI__builtin_lasx_xvsubi_du:
4506 case LoongArch::BI__builtin_lasx_xvbsrl_v:
4507 case LoongArch::BI__builtin_lasx_xvbsll_v:
4508 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
4509 case LoongArch::BI__builtin_lasx_xvssrarni_h_w:
4510 case LoongArch::BI__builtin_lasx_xvssrarni_hu_w:
4511 case LoongArch::BI__builtin_lasx_xvssrani_h_w:
4512 case LoongArch::BI__builtin_lasx_xvssrani_hu_w:
4513 case LoongArch::BI__builtin_lasx_xvsrarni_h_w:
4514 case LoongArch::BI__builtin_lasx_xvsrani_h_w:
4515 case LoongArch::BI__builtin_lasx_xvfrstpi_b:
4516 case LoongArch::BI__builtin_lasx_xvfrstpi_h:
4517 case LoongArch::BI__builtin_lasx_xvsrlni_h_w:
4518 case LoongArch::BI__builtin_lasx_xvsrlrni_h_w:
4519 case LoongArch::BI__builtin_lasx_xvssrlni_h_w:
4520 case LoongArch::BI__builtin_lasx_xvssrlni_hu_w:
4521 case LoongArch::BI__builtin_lasx_xvssrlrni_h_w:
4522 case LoongArch::BI__builtin_lasx_xvssrlrni_hu_w:
4523 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
4524 case LoongArch::BI__builtin_lasx_xvbitclri_d:
4525 case LoongArch::BI__builtin_lasx_xvbitrevi_d:
4526 case LoongArch::BI__builtin_lasx_xvbitseti_d:
4527 case LoongArch::BI__builtin_lasx_xvsat_d:
4528 case LoongArch::BI__builtin_lasx_xvsat_du:
4529 case LoongArch::BI__builtin_lasx_xvslli_d:
4530 case LoongArch::BI__builtin_lasx_xvsrai_d:
4531 case LoongArch::BI__builtin_lasx_xvsrli_d:
4532 case LoongArch::BI__builtin_lasx_xvsrari_d:
4533 case LoongArch::BI__builtin_lasx_xvrotri_d:
4534 case LoongArch::BI__builtin_lasx_xvsrlri_d:
4535 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 63);
4536 case LoongArch::BI__builtin_lasx_xvssrarni_w_d:
4537 case LoongArch::BI__builtin_lasx_xvssrarni_wu_d:
4538 case LoongArch::BI__builtin_lasx_xvssrani_w_d:
4539 case LoongArch::BI__builtin_lasx_xvssrani_wu_d:
4540 case LoongArch::BI__builtin_lasx_xvsrarni_w_d:
4541 case LoongArch::BI__builtin_lasx_xvsrlni_w_d:
4542 case LoongArch::BI__builtin_lasx_xvsrlrni_w_d:
4543 case LoongArch::BI__builtin_lasx_xvssrlni_w_d:
4544 case LoongArch::BI__builtin_lasx_xvssrlni_wu_d:
4545 case LoongArch::BI__builtin_lasx_xvssrlrni_w_d:
4546 case LoongArch::BI__builtin_lasx_xvssrlrni_wu_d:
4547 case LoongArch::BI__builtin_lasx_xvsrani_w_d:
4548 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 63);
4549 case LoongArch::BI__builtin_lasx_xvssrarni_d_q:
4550 case LoongArch::BI__builtin_lasx_xvssrarni_du_q:
4551 case LoongArch::BI__builtin_lasx_xvssrani_d_q:
4552 case LoongArch::BI__builtin_lasx_xvssrani_du_q:
4553 case LoongArch::BI__builtin_lasx_xvsrarni_d_q:
4554 case LoongArch::BI__builtin_lasx_xvssrlni_d_q:
4555 case LoongArch::BI__builtin_lasx_xvssrlni_du_q:
4556 case LoongArch::BI__builtin_lasx_xvssrlrni_d_q:
4557 case LoongArch::BI__builtin_lasx_xvssrlrni_du_q:
4558 case LoongArch::BI__builtin_lasx_xvsrani_d_q:
4559 case LoongArch::BI__builtin_lasx_xvsrlni_d_q:
4560 case LoongArch::BI__builtin_lasx_xvsrlrni_d_q:
4561 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 127);
4562 case LoongArch::BI__builtin_lasx_xvseqi_b:
4563 case LoongArch::BI__builtin_lasx_xvseqi_h:
4564 case LoongArch::BI__builtin_lasx_xvseqi_w:
4565 case LoongArch::BI__builtin_lasx_xvseqi_d:
4566 case LoongArch::BI__builtin_lasx_xvslti_b:
4567 case LoongArch::BI__builtin_lasx_xvslti_h:
4568 case LoongArch::BI__builtin_lasx_xvslti_w:
4569 case LoongArch::BI__builtin_lasx_xvslti_d:
4570 case LoongArch::BI__builtin_lasx_xvslei_b:
4571 case LoongArch::BI__builtin_lasx_xvslei_h:
4572 case LoongArch::BI__builtin_lasx_xvslei_w:
4573 case LoongArch::BI__builtin_lasx_xvslei_d:
4574 case LoongArch::BI__builtin_lasx_xvmaxi_b:
4575 case LoongArch::BI__builtin_lasx_xvmaxi_h:
4576 case LoongArch::BI__builtin_lasx_xvmaxi_w:
4577 case LoongArch::BI__builtin_lasx_xvmaxi_d:
4578 case LoongArch::BI__builtin_lasx_xvmini_b:
4579 case LoongArch::BI__builtin_lasx_xvmini_h:
4580 case LoongArch::BI__builtin_lasx_xvmini_w:
4581 case LoongArch::BI__builtin_lasx_xvmini_d:
4582 return SemaBuiltinConstantArgRange(TheCall, 1, -16, 15);
4583 case LoongArch::BI__builtin_lasx_xvandi_b:
4584 case LoongArch::BI__builtin_lasx_xvnori_b:
4585 case LoongArch::BI__builtin_lasx_xvori_b:
4586 case LoongArch::BI__builtin_lasx_xvshuf4i_b:
4587 case LoongArch::BI__builtin_lasx_xvshuf4i_h:
4588 case LoongArch::BI__builtin_lasx_xvshuf4i_w:
4589 case LoongArch::BI__builtin_lasx_xvxori_b:
4590 case LoongArch::BI__builtin_lasx_xvpermi_d:
4591 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 255);
4592 case LoongArch::BI__builtin_lasx_xvbitseli_b:
4593 case LoongArch::BI__builtin_lasx_xvshuf4i_d:
4594 case LoongArch::BI__builtin_lasx_xvextrins_b:
4595 case LoongArch::BI__builtin_lasx_xvextrins_h:
4596 case LoongArch::BI__builtin_lasx_xvextrins_w:
4597 case LoongArch::BI__builtin_lasx_xvextrins_d:
4598 case LoongArch::BI__builtin_lasx_xvpermi_q:
4599 case LoongArch::BI__builtin_lasx_xvpermi_w:
4600 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 255);
4601 case LoongArch::BI__builtin_lasx_xvrepl128vei_b:
4602 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4603 case LoongArch::BI__builtin_lasx_xvrepl128vei_h:
4604 case LoongArch::BI__builtin_lasx_xvpickve2gr_w:
4605 case LoongArch::BI__builtin_lasx_xvpickve2gr_wu:
4606 case LoongArch::BI__builtin_lasx_xvpickve_w_f:
4607 case LoongArch::BI__builtin_lasx_xvpickve_w:
4608 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
4609 case LoongArch::BI__builtin_lasx_xvinsgr2vr_w:
4610 case LoongArch::BI__builtin_lasx_xvinsve0_w:
4611 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
4612 case LoongArch::BI__builtin_lasx_xvrepl128vei_w:
4613 case LoongArch::BI__builtin_lasx_xvpickve2gr_d:
4614 case LoongArch::BI__builtin_lasx_xvpickve2gr_du:
4615 case LoongArch::BI__builtin_lasx_xvpickve_d_f:
4616 case LoongArch::BI__builtin_lasx_xvpickve_d:
4617 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
4618 case LoongArch::BI__builtin_lasx_xvinsve0_d:
4619 case LoongArch::BI__builtin_lasx_xvinsgr2vr_d:
4620 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
4621 case LoongArch::BI__builtin_lasx_xvstelm_b:
4622 return SemaBuiltinConstantArgRange(TheCall, 2, -128, 127) ||
4623 SemaBuiltinConstantArgRange(TheCall, 3, 0, 31);
4624 case LoongArch::BI__builtin_lasx_xvstelm_h:
4625 return SemaBuiltinConstantArgRange(TheCall, 2, -256, 254) ||
4626 SemaBuiltinConstantArgRange(TheCall, 3, 0, 15);
4627 case LoongArch::BI__builtin_lasx_xvstelm_w:
4628 return SemaBuiltinConstantArgRange(TheCall, 2, -512, 508) ||
4629 SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
4630 case LoongArch::BI__builtin_lasx_xvstelm_d:
4631 return SemaBuiltinConstantArgRange(TheCall, 2, -1024, 1016) ||
4632 SemaBuiltinConstantArgRange(TheCall, 3, 0, 3);
4633 case LoongArch::BI__builtin_lasx_xvrepl128vei_d:
4634 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
4635 case LoongArch::BI__builtin_lasx_xvldrepl_b:
4636 case LoongArch::BI__builtin_lasx_xvld:
4637 return SemaBuiltinConstantArgRange(TheCall, 1, -2048, 2047);
4638 case LoongArch::BI__builtin_lasx_xvldrepl_h:
4639 return SemaBuiltinConstantArgRange(TheCall, 1, -2048, 2046);
4640 case LoongArch::BI__builtin_lasx_xvldrepl_w:
4641 return SemaBuiltinConstantArgRange(TheCall, 1, -2048, 2044);
4642 case LoongArch::BI__builtin_lasx_xvldrepl_d:
4643 return SemaBuiltinConstantArgRange(TheCall, 1, -2048, 2040);
4644 case LoongArch::BI__builtin_lasx_xvst:
4645 return SemaBuiltinConstantArgRange(TheCall, 2, -2048, 2047);
4646 case LoongArch::BI__builtin_lasx_xvldi:
4647 return SemaBuiltinConstantArgRange(TheCall, 0, -4096, 4095);
4648 case LoongArch::BI__builtin_lasx_xvrepli_b:
4649 case LoongArch::BI__builtin_lasx_xvrepli_h:
4650 case LoongArch::BI__builtin_lasx_xvrepli_w:
4651 case LoongArch::BI__builtin_lasx_xvrepli_d:
4652 return SemaBuiltinConstantArgRange(TheCall, 0, -512, 511);
4653 }
4654 return false;
4655}
4656
4657bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
4658 unsigned BuiltinID, CallExpr *TheCall) {
4659 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
4660 CheckMipsBuiltinArgument(BuiltinID, TheCall);
4661}
4662
4663bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
4664 CallExpr *TheCall) {
4665
4666 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
4667 BuiltinID <= Mips::BI__builtin_mips_lwx) {
4668 if (!TI.hasFeature("dsp"))
4669 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
4670 }
4671
4672 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
4673 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
4674 if (!TI.hasFeature("dspr2"))
4675 return Diag(TheCall->getBeginLoc(),
4676 diag::err_mips_builtin_requires_dspr2);
4677 }
4678
4679 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
4680 BuiltinID <= Mips::BI__builtin_msa_xori_b) {
4681 if (!TI.hasFeature("msa"))
4682 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
4683 }
4684
4685 return false;
4686}
4687
4688// CheckMipsBuiltinArgument - Checks the constant value passed to the
4689// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
4690// ordering for DSP is unspecified. MSA is ordered by the data format used
4691// by the underlying instruction i.e., df/m, df/n and then by size.
4692//
4693// FIXME: The size tests here should instead be tablegen'd along with the
4694// definitions from include/clang/Basic/BuiltinsMips.def.
4695// FIXME: GCC is strict on signedness for some of these intrinsics, we should
4696// be too.
4697bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
4698 unsigned i = 0, l = 0, u = 0, m = 0;
4699 switch (BuiltinID) {
4700 default: return false;
4701 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
4702 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
4703 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
4704 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
4705 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
4706 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
4707 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
4708 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
4709 // df/m field.
4710 // These intrinsics take an unsigned 3 bit immediate.
4711 case Mips::BI__builtin_msa_bclri_b:
4712 case Mips::BI__builtin_msa_bnegi_b:
4713 case Mips::BI__builtin_msa_bseti_b:
4714 case Mips::BI__builtin_msa_sat_s_b:
4715 case Mips::BI__builtin_msa_sat_u_b:
4716 case Mips::BI__builtin_msa_slli_b:
4717 case Mips::BI__builtin_msa_srai_b:
4718 case Mips::BI__builtin_msa_srari_b:
4719 case Mips::BI__builtin_msa_srli_b:
4720 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
4721 case Mips::BI__builtin_msa_binsli_b:
4722 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
4723 // These intrinsics take an unsigned 4 bit immediate.
4724 case Mips::BI__builtin_msa_bclri_h:
4725 case Mips::BI__builtin_msa_bnegi_h:
4726 case Mips::BI__builtin_msa_bseti_h:
4727 case Mips::BI__builtin_msa_sat_s_h:
4728 case Mips::BI__builtin_msa_sat_u_h:
4729 case Mips::BI__builtin_msa_slli_h:
4730 case Mips::BI__builtin_msa_srai_h:
4731 case Mips::BI__builtin_msa_srari_h:
4732 case Mips::BI__builtin_msa_srli_h:
4733 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
4734 case Mips::BI__builtin_msa_binsli_h:
4735 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
4736 // These intrinsics take an unsigned 5 bit immediate.
4737 // The first block of intrinsics actually have an unsigned 5 bit field,
4738 // not a df/n field.
4739 case Mips::BI__builtin_msa_cfcmsa:
4740 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
4741 case Mips::BI__builtin_msa_clei_u_b:
4742 case Mips::BI__builtin_msa_clei_u_h:
4743 case Mips::BI__builtin_msa_clei_u_w:
4744 case Mips::BI__builtin_msa_clei_u_d:
4745 case Mips::BI__builtin_msa_clti_u_b:
4746 case Mips::BI__builtin_msa_clti_u_h:
4747 case Mips::BI__builtin_msa_clti_u_w:
4748 case Mips::BI__builtin_msa_clti_u_d:
4749 case Mips::BI__builtin_msa_maxi_u_b:
4750 case Mips::BI__builtin_msa_maxi_u_h:
4751 case Mips::BI__builtin_msa_maxi_u_w:
4752 case Mips::BI__builtin_msa_maxi_u_d:
4753 case Mips::BI__builtin_msa_mini_u_b:
4754 case Mips::BI__builtin_msa_mini_u_h:
4755 case Mips::BI__builtin_msa_mini_u_w:
4756 case Mips::BI__builtin_msa_mini_u_d:
4757 case Mips::BI__builtin_msa_addvi_b:
4758 case Mips::BI__builtin_msa_addvi_h:
4759 case Mips::BI__builtin_msa_addvi_w:
4760 case Mips::BI__builtin_msa_addvi_d:
4761 case Mips::BI__builtin_msa_bclri_w:
4762 case Mips::BI__builtin_msa_bnegi_w:
4763 case Mips::BI__builtin_msa_bseti_w:
4764 case Mips::BI__builtin_msa_sat_s_w:
4765 case Mips::BI__builtin_msa_sat_u_w:
4766 case Mips::BI__builtin_msa_slli_w:
4767 case Mips::BI__builtin_msa_srai_w:
4768 case Mips::BI__builtin_msa_srari_w:
4769 case Mips::BI__builtin_msa_srli_w:
4770 case Mips::BI__builtin_msa_srlri_w:
4771 case Mips::BI__builtin_msa_subvi_b:
4772 case Mips::BI__builtin_msa_subvi_h:
4773 case Mips::BI__builtin_msa_subvi_w:
4774 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
4775 case Mips::BI__builtin_msa_binsli_w:
4776 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
4777 // These intrinsics take an unsigned 6 bit immediate.
4778 case Mips::BI__builtin_msa_bclri_d:
4779 case Mips::BI__builtin_msa_bnegi_d:
4780 case Mips::BI__builtin_msa_bseti_d:
4781 case Mips::BI__builtin_msa_sat_s_d:
4782 case Mips::BI__builtin_msa_sat_u_d:
4783 case Mips::BI__builtin_msa_slli_d:
4784 case Mips::BI__builtin_msa_srai_d:
4785 case Mips::BI__builtin_msa_srari_d:
4786 case Mips::BI__builtin_msa_srli_d:
4787 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
4788 case Mips::BI__builtin_msa_binsli_d:
4789 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
4790 // These intrinsics take a signed 5 bit immediate.
4791 case Mips::BI__builtin_msa_ceqi_b:
4792 case Mips::BI__builtin_msa_ceqi_h:
4793 case Mips::BI__builtin_msa_ceqi_w:
4794 case Mips::BI__builtin_msa_ceqi_d:
4795 case Mips::BI__builtin_msa_clti_s_b:
4796 case Mips::BI__builtin_msa_clti_s_h:
4797 case Mips::BI__builtin_msa_clti_s_w:
4798 case Mips::BI__builtin_msa_clti_s_d:
4799 case Mips::BI__builtin_msa_clei_s_b:
4800 case Mips::BI__builtin_msa_clei_s_h:
4801 case Mips::BI__builtin_msa_clei_s_w:
4802 case Mips::BI__builtin_msa_clei_s_d:
4803 case Mips::BI__builtin_msa_maxi_s_b:
4804 case Mips::BI__builtin_msa_maxi_s_h:
4805 case Mips::BI__builtin_msa_maxi_s_w:
4806 case Mips::BI__builtin_msa_maxi_s_d:
4807 case Mips::BI__builtin_msa_mini_s_b:
4808 case Mips::BI__builtin_msa_mini_s_h:
4809 case Mips::BI__builtin_msa_mini_s_w:
4810 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
4811 // These intrinsics take an unsigned 8 bit immediate.
4812 case Mips::BI__builtin_msa_andi_b:
4813 case Mips::BI__builtin_msa_nori_b:
4814 case Mips::BI__builtin_msa_ori_b:
4815 case Mips::BI__builtin_msa_shf_b:
4816 case Mips::BI__builtin_msa_shf_h:
4817 case Mips::BI__builtin_msa_shf_w:
4818 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
4819 case Mips::BI__builtin_msa_bseli_b:
4820 case Mips::BI__builtin_msa_bmnzi_b:
4821 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
4822 // df/n format
4823 // These intrinsics take an unsigned 4 bit immediate.
4824 case Mips::BI__builtin_msa_copy_s_b:
4825 case Mips::BI__builtin_msa_copy_u_b:
4826 case Mips::BI__builtin_msa_insve_b:
4827 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
4828 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
4829 // These intrinsics take an unsigned 3 bit immediate.
4830 case Mips::BI__builtin_msa_copy_s_h:
4831 case Mips::BI__builtin_msa_copy_u_h:
4832 case Mips::BI__builtin_msa_insve_h:
4833 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
4834 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
4835 // These intrinsics take an unsigned 2 bit immediate.
4836 case Mips::BI__builtin_msa_copy_s_w:
4837 case Mips::BI__builtin_msa_copy_u_w:
4838 case Mips::BI__builtin_msa_insve_w:
4839 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
4840 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
4841 // These intrinsics take an unsigned 1 bit immediate.
4842 case Mips::BI__builtin_msa_copy_s_d:
4843 case Mips::BI__builtin_msa_copy_u_d:
4844 case Mips::BI__builtin_msa_insve_d:
4845 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
4846 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
4847 // Memory offsets and immediate loads.
4848 // These intrinsics take a signed 10 bit immediate.
4849 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
4850 case Mips::BI__builtin_msa_ldi_h:
4851 case Mips::BI__builtin_msa_ldi_w:
4852 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
4853 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
4854 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
4855 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
4856 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
4857 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
4858 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
4859 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
4860 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
4861 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
4862 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
4863 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
4864 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
4865 }
4866
4867 if (!m)
4868 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
4869
4870 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
4871 SemaBuiltinConstantArgMultiple(TheCall, i, m);
4872}
4873
4874/// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
4875/// advancing the pointer over the consumed characters. The decoded type is
4876/// returned. If the decoded type represents a constant integer with a
4877/// constraint on its value then Mask is set to that value. The type descriptors
4878/// used in Str are specific to PPC MMA builtins and are documented in the file
4879/// defining the PPC builtins.
4880static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
4881 unsigned &Mask) {
4882 bool RequireICE = false;
4884 switch (*Str++) {
4885 case 'V':
4886 return Context.getVectorType(Context.UnsignedCharTy, 16,
4888 case 'i': {
4889 char *End;
4890 unsigned size = strtoul(Str, &End, 10);
4891 assert(End != Str && "Missing constant parameter constraint");
4892 Str = End;
4893 Mask = size;
4894 return Context.IntTy;
4895 }
4896 case 'W': {
4897 char *End;
4898 unsigned size = strtoul(Str, &End, 10);
4899 assert(End != Str && "Missing PowerPC MMA type size");
4900 Str = End;
4901 QualType Type;
4902 switch (size) {
4903 #define PPC_VECTOR_TYPE(typeName, Id, size) \
4904 case size: Type = Context.Id##Ty; break;
4905 #include "clang/Basic/PPCTypes.def"
4906 default: llvm_unreachable("Invalid PowerPC MMA vector type");
4907 }
4908 bool CheckVectorArgs = false;
4909 while (!CheckVectorArgs) {
4910 switch (*Str++) {
4911 case '*':
4912 Type = Context.getPointerType(Type);
4913 break;
4914 case 'C':
4915 Type = Type.withConst();
4916 break;
4917 default:
4918 CheckVectorArgs = true;
4919 --Str;
4920 break;
4921 }
4922 }
4923 return Type;
4924 }
4925 default:
4926 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
4927 }
4928}
4929
4930static bool isPPC_64Builtin(unsigned BuiltinID) {
4931 // These builtins only work on PPC 64bit targets.
4932 switch (BuiltinID) {
4933 case PPC::BI__builtin_divde:
4934 case PPC::BI__builtin_divdeu:
4935 case PPC::BI__builtin_bpermd:
4936 case PPC::BI__builtin_pdepd:
4937 case PPC::BI__builtin_pextd:
4938 case PPC::BI__builtin_ppc_ldarx:
4939 case PPC::BI__builtin_ppc_stdcx:
4940 case PPC::BI__builtin_ppc_tdw:
4941 case PPC::BI__builtin_ppc_trapd:
4942 case PPC::BI__builtin_ppc_cmpeqb:
4943 case PPC::BI__builtin_ppc_setb:
4944 case PPC::BI__builtin_ppc_mulhd:
4945 case PPC::BI__builtin_ppc_mulhdu:
4946 case PPC::BI__builtin_ppc_maddhd:
4947 case PPC::BI__builtin_ppc_maddhdu:
4948 case PPC::BI__builtin_ppc_maddld:
4949 case PPC::BI__builtin_ppc_load8r:
4950 case PPC::BI__builtin_ppc_store8r:
4951 case PPC::BI__builtin_ppc_insert_exp:
4952 case PPC::BI__builtin_ppc_extract_sig:
4953 case PPC::BI__builtin_ppc_addex:
4954 case PPC::BI__builtin_darn:
4955 case PPC::BI__builtin_darn_raw:
4956 case PPC::BI__builtin_ppc_compare_and_swaplp:
4957 case PPC::BI__builtin_ppc_fetch_and_addlp:
4958 case PPC::BI__builtin_ppc_fetch_and_andlp:
4959 case PPC::BI__builtin_ppc_fetch_and_orlp:
4960 case PPC::BI__builtin_ppc_fetch_and_swaplp:
4961 return true;
4962 }
4963 return false;
4964}
4965
4966/// Returns true if the argument consists of one contiguous run of 1s with any
4967/// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
4968/// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
4969/// since all 1s are not contiguous.
4970bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
4971 llvm::APSInt Result;
4972 // We can't check the value of a dependent argument.
4973 Expr *Arg = TheCall->getArg(ArgNum);
4974 if (Arg->isTypeDependent() || Arg->isValueDependent())
4975 return false;
4976
4977 // Check constant-ness first.
4978 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4979 return true;
4980
4981 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
4982 if (Result.isShiftedMask() || (~Result).isShiftedMask())
4983 return false;
4984
4985 return Diag(TheCall->getBeginLoc(),
4986 diag::err_argument_not_contiguous_bit_field)
4987 << ArgNum << Arg->getSourceRange();
4988}
4989
4990bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4991 CallExpr *TheCall) {
4992 unsigned i = 0, l = 0, u = 0;
4993 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
4994 llvm::APSInt Result;
4995
4996 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
4997 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
4998 << TheCall->getSourceRange();
4999
5000 switch (BuiltinID) {
5001 default: return false;
5002 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
5003 case PPC::BI__builtin_altivec_crypto_vshasigmad:
5004 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
5005 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
5006 case PPC::BI__builtin_altivec_dss:
5007 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
5008 case PPC::BI__builtin_tbegin:
5009 case PPC::BI__builtin_tend:
5010 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
5011 case PPC::BI__builtin_tsr:
5012 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7);
5013 case PPC::BI__builtin_tabortwc:
5014 case PPC::BI__builtin_tabortdc:
5015 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
5016 case PPC::BI__builtin_tabortwci:
5017 case PPC::BI__builtin_tabortdci:
5018 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
5019 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
5020 // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
5021 // __builtin_(un)pack_longdouble are available only if long double uses IBM
5022 // extended double representation.
5023 case PPC::BI__builtin_unpack_longdouble:
5024 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
5025 return true;
5026 [[fallthrough]];
5027 case PPC::BI__builtin_pack_longdouble:
5028 if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
5029 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
5030 << "ibmlongdouble";
5031 return false;
5032 case PPC::BI__builtin_altivec_dst:
5033 case PPC::BI__builtin_altivec_dstt:
5034 case PPC::BI__builtin_altivec_dstst:
5035 case PPC::BI__builtin_altivec_dststt:
5036 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
5037 case PPC::BI__builtin_vsx_xxpermdi:
5038 case PPC::BI__builtin_vsx_xxsldwi:
5039 return SemaBuiltinVSX(TheCall);
5040 case PPC::BI__builtin_unpack_vector_int128:
5041 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
5042 case PPC::BI__builtin_altivec_vgnb:
5043 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
5044 case PPC::BI__builtin_vsx_xxeval:
5045 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
5046 case PPC::BI__builtin_altivec_vsldbi:
5047 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
5048 case PPC::BI__builtin_altivec_vsrdbi:
5049 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
5050 case PPC::BI__builtin_vsx_xxpermx:
5051 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
5052 case PPC::BI__builtin_ppc_tw:
5053 case PPC::BI__builtin_ppc_tdw:
5054 return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
5055 case PPC::BI__builtin_ppc_cmprb:
5056 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
5057 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
5058 // be a constant that represents a contiguous bit field.
5059 case PPC::BI__builtin_ppc_rlwnm:
5060 return SemaValueIsRunOfOnes(TheCall, 2);
5061 case PPC::BI__builtin_ppc_rlwimi:
5062 case PPC::BI__builtin_ppc_rldimi:
5063 return SemaBuiltinConstantArg(TheCall, 2, Result) ||
5064 SemaValueIsRunOfOnes(TheCall, 3);
5065 case PPC::BI__builtin_ppc_addex: {
5066 if (SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
5067 return true;
5068 // Output warning for reserved values 1 to 3.
5069 int ArgValue =
5070 TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
5071 if (ArgValue != 0)
5072 Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
5073 << ArgValue;
5074 return false;
5075 }
5076 case PPC::BI__builtin_ppc_mtfsb0:
5077 case PPC::BI__builtin_ppc_mtfsb1:
5078 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
5079 case PPC::BI__builtin_ppc_mtfsf:
5080 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
5081 case PPC::BI__builtin_ppc_mtfsfi:
5082 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
5083 SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
5084 case PPC::BI__builtin_ppc_alignx:
5085 return SemaBuiltinConstantArgPower2(TheCall, 0);
5086 case PPC::BI__builtin_ppc_rdlam:
5087 return SemaValueIsRunOfOnes(TheCall, 2);
5088 case PPC::BI__builtin_vsx_ldrmb:
5089 case PPC::BI__builtin_vsx_strmb:
5090 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
5091 case PPC::BI__builtin_altivec_vcntmbb:
5092 case PPC::BI__builtin_altivec_vcntmbh:
5093 case PPC::BI__builtin_altivec_vcntmbw:
5094 case PPC::BI__builtin_altivec_vcntmbd:
5095 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
5096 case PPC::BI__builtin_vsx_xxgenpcvbm:
5097 case PPC::BI__builtin_vsx_xxgenpcvhm:
5098 case PPC::BI__builtin_vsx_xxgenpcvwm:
5099 case PPC::BI__builtin_vsx_xxgenpcvdm:
5100 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
5101 case PPC::BI__builtin_ppc_test_data_class: {
5102 // Check if the first argument of the __builtin_ppc_test_data_class call is
5103 // valid. The argument must be 'float' or 'double' or '__float128'.
5104 QualType ArgType = TheCall->getArg(0)->getType();
5105 if (ArgType != QualType(Context.FloatTy) &&
5106 ArgType != QualType(Context.DoubleTy) &&
5107 ArgType != QualType(Context.Float128Ty))
5108 return Diag(TheCall->getBeginLoc(),
5109 diag::err_ppc_invalid_test_data_class_type);
5110 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
5111 }
5112 case PPC::BI__builtin_ppc_maxfe:
5113 case PPC::BI__builtin_ppc_minfe:
5114 case PPC::BI__builtin_ppc_maxfl:
5115 case PPC::BI__builtin_ppc_minfl:
5116 case PPC::BI__builtin_ppc_maxfs:
5117 case PPC::BI__builtin_ppc_minfs: {
5118 if (Context.getTargetInfo().getTriple().isOSAIX() &&
5119 (BuiltinID == PPC::BI__builtin_ppc_maxfe ||
5120 BuiltinID == PPC::BI__builtin_ppc_minfe))
5121 return Diag(TheCall->getBeginLoc(), diag::err_target_unsupported_type)
5122 << "builtin" << true << 128 << QualType(Context.LongDoubleTy)
5123 << false << Context.getTargetInfo().getTriple().str();
5124 // Argument type should be exact.
5126 if (BuiltinID == PPC::BI__builtin_ppc_maxfl ||
5127 BuiltinID == PPC::BI__builtin_ppc_minfl)
5128 ArgType = QualType(Context.DoubleTy);
5129 else if (BuiltinID == PPC::BI__builtin_ppc_maxfs ||
5130 BuiltinID == PPC::BI__builtin_ppc_minfs)
5131 ArgType = QualType(Context.FloatTy);
5132 for (unsigned I = 0, E = TheCall->getNumArgs(); I < E; ++I)
5133 if (TheCall->getArg(I)->getType() != ArgType)
5134 return Diag(TheCall->getBeginLoc(),
5135 diag::err_typecheck_convert_incompatible)
5136 << TheCall->getArg(I)->getType() << ArgType << 1 << 0 << 0;
5137 return false;
5138 }
5139#define CUSTOM_BUILTIN(Name, Intr, Types, Acc, Feature) \
5140 case PPC::BI__builtin_##Name: \
5141 return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
5142#include "clang/Basic/BuiltinsPPC.def"
5143 }
5144 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
5145}
5146
5147// Check if the given type is a non-pointer PPC MMA type. This function is used
5148// in Sema to prevent invalid uses of restricted PPC MMA types.
5149bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
5150 if (Type->isPointerType() || Type->isArrayType())
5151 return false;
5152
5153 QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
5154#define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
5155 if (false
5156#include "clang/Basic/PPCTypes.def"
5157 ) {
5158 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
5159 return true;
5160 }
5161 return false;
5162}
5163
5164bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
5165 CallExpr *TheCall) {
5166 // position of memory order and scope arguments in the builtin
5167 unsigned OrderIndex, ScopeIndex;
5168 switch (BuiltinID) {
5169 case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
5170 case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
5171 case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
5172 case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
5173 OrderIndex = 2;
5174 ScopeIndex = 3;
5175 break;
5176 case AMDGPU::BI__builtin_amdgcn_fence:
5177 OrderIndex = 0;
5178 ScopeIndex = 1;
5179 break;
5180 default:
5181 return false;
5182 }
5183
5184 ExprResult Arg = TheCall->getArg(OrderIndex);
5185 auto ArgExpr = Arg.get();
5186 Expr::EvalResult ArgResult;
5187
5188 if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
5189 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
5190 << ArgExpr->getType();
5191 auto Ord = ArgResult.Val.getInt().getZExtValue();
5192
5193 // Check validity of memory ordering as per C11 / C++11's memody model.
5194 // Only fence needs check. Atomic dec/inc allow all memory orders.
5195 if (!llvm::isValidAtomicOrderingCABI(Ord))
5196 return Diag(ArgExpr->getBeginLoc(),
5197 diag::warn_atomic_op_has_invalid_memory_order)
5198 << 0 << ArgExpr->getSourceRange();
5199 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
5200 case llvm::AtomicOrderingCABI::relaxed:
5201 case llvm::AtomicOrderingCABI::consume:
5202 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
5203 return Diag(ArgExpr->getBeginLoc(),
5204 diag::warn_atomic_op_has_invalid_memory_order)
5205 << 0 << ArgExpr->getSourceRange();
5206 break;
5207 case llvm::AtomicOrderingCABI::acquire:
5208 case llvm::AtomicOrderingCABI::release:
5209 case llvm::AtomicOrderingCABI::acq_rel:
5210 case llvm::AtomicOrderingCABI::seq_cst:
5211 break;
5212 }
5213
5214 Arg = TheCall->getArg(ScopeIndex);
5215 ArgExpr = Arg.get();
5216 Expr::EvalResult ArgResult1;
5217 // Check that sync scope is a constant literal
5218 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
5219 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
5220 << ArgExpr->getType();
5221
5222 return false;
5223}
5224
5225bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
5226 llvm::APSInt Result;
5227
5228 // We can't check the value of a dependent argument.
5229 Expr *Arg = TheCall->getArg(ArgNum);
5230 if (Arg->isTypeDependent() || Arg->isValueDependent())
5231 return false;
5232
5233 // Check constant-ness first.
5234 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5235 return true;
5236
5237 int64_t Val = Result.getSExtValue();
5238 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
5239 return false;
5240
5241 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
5242 << Arg->getSourceRange();
5243}
5244
5245static bool CheckInvalidVLENandLMUL(const TargetInfo &TI, CallExpr *TheCall,
5246 Sema &S, QualType Type, int EGW) {
5247 assert((EGW == 128 || EGW == 256) && "EGW can only be 128 or 256 bits");
5248
5249 // LMUL * VLEN >= EGW
5252 unsigned ElemSize = S.Context.getTypeSize(Info.ElementType);
5253 unsigned MinElemCount = Info.EC.getKnownMinValue();
5254
5255 unsigned EGS = EGW / ElemSize;
5256 // If EGS is less than or equal to the minimum number of elements, then the
5257 // type is valid.
5258 if (EGS <= MinElemCount)
5259 return false;
5260
5261 // Otherwise, we need vscale to be at least EGS / MinElemCont.
5262 assert(EGS % MinElemCount == 0);
5263 unsigned VScaleFactor = EGS / MinElemCount;
5264 // Vscale is VLEN/RVVBitsPerBlock.
5265 unsigned MinRequiredVLEN = VScaleFactor * llvm::RISCV::RVVBitsPerBlock;
5266 std::string RequiredExt = "zvl" + std::to_string(MinRequiredVLEN) + "b";
5267 if (!TI.hasFeature(RequiredExt))
5268 return S.Diag(TheCall->getBeginLoc(),
5269 diag::err_riscv_type_requires_extension) << Type << RequiredExt;
5270
5271 return false;
5272}
5273
5274bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
5275 unsigned BuiltinID,
5276 CallExpr *TheCall) {
5277 // CodeGenFunction can also detect this, but this gives a better error
5278 // message.
5279 bool FeatureMissing = false;
5280 SmallVector<StringRef> ReqFeatures;
5281 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
5282 Features.split(ReqFeatures, ',', -1, false);
5283
5284 // Check if each required feature is included
5285 for (StringRef F : ReqFeatures) {
5286 SmallVector<StringRef> ReqOpFeatures;
5287 F.split(ReqOpFeatures, '|');
5288
5289 if (llvm::none_of(ReqOpFeatures,
5290 [&TI](StringRef OF) { return TI.hasFeature(OF); })) {
5291 std::string FeatureStrs;