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"
31#include "clang/AST/NSAPI.h"
35#include "clang/AST/Stmt.h"
37#include "clang/AST/Type.h"
38#include "clang/AST/TypeLoc.h"
44#include "clang/Basic/LLVM.h"
57#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
59#include "clang/Sema/Lookup.h"
61#include "clang/Sema/Scope.h"
63#include "clang/Sema/Sema.h"
65#include "clang/Sema/SemaObjC.h"
66#include "llvm/ADT/APFloat.h"
67#include "llvm/ADT/APInt.h"
68#include "llvm/ADT/APSInt.h"
69#include "llvm/ADT/ArrayRef.h"
70#include "llvm/ADT/DenseMap.h"
71#include "llvm/ADT/FoldingSet.h"
72#include "llvm/ADT/STLExtras.h"
73#include "llvm/ADT/SmallBitVector.h"
74#include "llvm/ADT/SmallPtrSet.h"
75#include "llvm/ADT/SmallString.h"
76#include "llvm/ADT/SmallVector.h"
77#include "llvm/ADT/StringExtras.h"
78#include "llvm/ADT/StringRef.h"
79#include "llvm/ADT/StringSet.h"
80#include "llvm/ADT/StringSwitch.h"
81#include "llvm/Support/AtomicOrdering.h"
82#include "llvm/Support/Casting.h"
83#include "llvm/Support/Compiler.h"
84#include "llvm/Support/ConvertUTF.h"
85#include "llvm/Support/ErrorHandling.h"
86#include "llvm/Support/Format.h"
87#include "llvm/Support/Locale.h"
88#include "llvm/Support/MathExtras.h"
89#include "llvm/Support/SaveAndRestore.h"
90#include "llvm/Support/raw_ostream.h"
91#include "llvm/TargetParser/RISCVTargetParser.h"
92#include "llvm/TargetParser/Triple.h"
93#include <algorithm>
94#include <bitset>
95#include <cassert>
96#include <cctype>
97#include <cstddef>
98#include <cstdint>
99#include <functional>
100#include <limits>
101#include <optional>
102#include <string>
103#include <tuple>
104#include <utility>
105
106using namespace clang;
107using namespace sema;
108
110 unsigned ByteNo) const {
111 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
113}
114
115static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
117 return (A << 8) | B;
118}
119
120/// Checks that a call expression's argument count is at least the desired
121/// number. This is useful when doing custom type-checking on a variadic
122/// function. Returns true on error.
124 unsigned MinArgCount) {
125 unsigned ArgCount = Call->getNumArgs();
126 if (ArgCount >= MinArgCount)
127 return false;
128
129 return S.Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
130 << 0 /*function call*/ << MinArgCount << ArgCount
131 << /*is non object*/ 0 << Call->getSourceRange();
132}
133
134/// Checks that a call expression's argument count is at most the desired
135/// number. This is useful when doing custom type-checking on a variadic
136/// function. Returns true on error.
137static bool checkArgCountAtMost(Sema &S, CallExpr *Call, unsigned MaxArgCount) {
138 unsigned ArgCount = Call->getNumArgs();
139 if (ArgCount <= MaxArgCount)
140 return false;
141 return S.Diag(Call->getEndLoc(),
142 diag::err_typecheck_call_too_many_args_at_most)
143 << 0 /*function call*/ << MaxArgCount << ArgCount
144 << /*is non object*/ 0 << Call->getSourceRange();
145}
146
147/// Checks that a call expression's argument count is in the desired range. This
148/// is useful when doing custom type-checking on a variadic function. Returns
149/// true on error.
150static bool checkArgCountRange(Sema &S, CallExpr *Call, unsigned MinArgCount,
151 unsigned MaxArgCount) {
152 return checkArgCountAtLeast(S, Call, MinArgCount) ||
153 checkArgCountAtMost(S, Call, MaxArgCount);
154}
155
156/// Checks that a call expression's argument count is the desired number.
157/// This is useful when doing custom type-checking. Returns true on error.
158static bool checkArgCount(Sema &S, CallExpr *Call, unsigned DesiredArgCount) {
159 unsigned ArgCount = Call->getNumArgs();
160 if (ArgCount == DesiredArgCount)
161 return false;
162
163 if (checkArgCountAtLeast(S, Call, DesiredArgCount))
164 return true;
165 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
166
167 // Highlight all the excess arguments.
168 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
169 Call->getArg(ArgCount - 1)->getEndLoc());
170
171 return S.Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
172 << 0 /*function call*/ << DesiredArgCount << ArgCount
173 << /*is non object*/ 0 << Call->getArg(1)->getSourceRange();
174}
175
177 if (Value->isTypeDependent())
178 return false;
179
180 InitializedEntity Entity =
184 if (Result.isInvalid())
185 return true;
186 Value = Result.get();
187 return false;
188}
189
190/// Check that the first argument to __builtin_annotation is an integer
191/// and the second argument is a non-wide string literal.
192static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
193 if (checkArgCount(S, TheCall, 2))
194 return true;
195
196 // First argument should be an integer.
197 Expr *ValArg = TheCall->getArg(0);
198 QualType Ty = ValArg->getType();
199 if (!Ty->isIntegerType()) {
200 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
201 << ValArg->getSourceRange();
202 return true;
203 }
204
205 // Second argument should be a constant string.
206 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
207 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
208 if (!Literal || !Literal->isOrdinary()) {
209 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
210 << StrArg->getSourceRange();
211 return true;
212 }
213
214 TheCall->setType(Ty);
215 return false;
216}
217
218static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
219 // We need at least one argument.
220 if (TheCall->getNumArgs() < 1) {
221 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
222 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
223 << TheCall->getCallee()->getSourceRange();
224 return true;
225 }
226
227 // All arguments should be wide string literals.
228 for (Expr *Arg : TheCall->arguments()) {
229 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
230 if (!Literal || !Literal->isWide()) {
231 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
232 << Arg->getSourceRange();
233 return true;
234 }
235 }
236
237 return false;
238}
239
240/// Check that the argument to __builtin_addressof is a glvalue, and set the
241/// result type to the corresponding pointer type.
242static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
243 if (checkArgCount(S, TheCall, 1))
244 return true;
245
246 ExprResult Arg(TheCall->getArg(0));
247 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
248 if (ResultType.isNull())
249 return true;
250
251 TheCall->setArg(0, Arg.get());
252 TheCall->setType(ResultType);
253 return false;
254}
255
256/// Check that the argument to __builtin_function_start is a function.
257static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
258 if (checkArgCount(S, TheCall, 1))
259 return true;
260
262 if (Arg.isInvalid())
263 return true;
264
265 TheCall->setArg(0, Arg.get());
266 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
268
269 if (!FD) {
270 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
271 << TheCall->getSourceRange();
272 return true;
273 }
274
275 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
276 TheCall->getBeginLoc());
277}
278
279/// Check the number of arguments and set the result type to
280/// the argument type.
281static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
282 if (checkArgCount(S, TheCall, 1))
283 return true;
284
285 TheCall->setType(TheCall->getArg(0)->getType());
286 return false;
287}
288
289/// Check that the value argument for __builtin_is_aligned(value, alignment) and
290/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
291/// type (but not a function pointer) and that the alignment is a power-of-two.
292static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
293 if (checkArgCount(S, TheCall, 2))
294 return true;
295
296 clang::Expr *Source = TheCall->getArg(0);
297 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
298
299 auto IsValidIntegerType = [](QualType Ty) {
300 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
301 };
302 QualType SrcTy = Source->getType();
303 // We should also be able to use it with arrays (but not functions!).
304 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
305 SrcTy = S.Context.getDecayedType(SrcTy);
306 }
307 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
308 SrcTy->isFunctionPointerType()) {
309 // FIXME: this is not quite the right error message since we don't allow
310 // floating point types, or member pointers.
311 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
312 << SrcTy;
313 return true;
314 }
315
316 clang::Expr *AlignOp = TheCall->getArg(1);
317 if (!IsValidIntegerType(AlignOp->getType())) {
318 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
319 << AlignOp->getType();
320 return true;
321 }
322 Expr::EvalResult AlignResult;
323 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
324 // We can't check validity of alignment if it is value dependent.
325 if (!AlignOp->isValueDependent() &&
326 AlignOp->EvaluateAsInt(AlignResult, S.Context,
328 llvm::APSInt AlignValue = AlignResult.Val.getInt();
329 llvm::APSInt MaxValue(
330 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
331 if (AlignValue < 1) {
332 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
333 return true;
334 }
335 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
336 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
337 << toString(MaxValue, 10);
338 return true;
339 }
340 if (!AlignValue.isPowerOf2()) {
341 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
342 return true;
343 }
344 if (AlignValue == 1) {
345 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
346 << IsBooleanAlignBuiltin;
347 }
348 }
349
352 SourceLocation(), Source);
353 if (SrcArg.isInvalid())
354 return true;
355 TheCall->setArg(0, SrcArg.get());
356 ExprResult AlignArg =
358 S.Context, AlignOp->getType(), false),
359 SourceLocation(), AlignOp);
360 if (AlignArg.isInvalid())
361 return true;
362 TheCall->setArg(1, AlignArg.get());
363 // For align_up/align_down, the return type is the same as the (potentially
364 // decayed) argument type including qualifiers. For is_aligned(), the result
365 // is always bool.
366 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
367 return false;
368}
369
370static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
371 if (checkArgCount(S, TheCall, 3))
372 return true;
373
374 std::pair<unsigned, const char *> Builtins[] = {
375 { Builtin::BI__builtin_add_overflow, "ckd_add" },
376 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
377 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
378 };
379
380 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
381 const char *> &P) {
382 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
384 S.getSourceManager(), S.getLangOpts()) == P.second;
385 });
386
387 auto ValidCkdIntType = [](QualType QT) {
388 // A valid checked integer type is an integer type other than a plain char,
389 // bool, a bit-precise type, or an enumeration type.
390 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
391 return (BT->getKind() >= BuiltinType::Short &&
392 BT->getKind() <= BuiltinType::Int128) || (
393 BT->getKind() >= BuiltinType::UShort &&
394 BT->getKind() <= BuiltinType::UInt128) ||
395 BT->getKind() == BuiltinType::UChar ||
396 BT->getKind() == BuiltinType::SChar;
397 return false;
398 };
399
400 // First two arguments should be integers.
401 for (unsigned I = 0; I < 2; ++I) {
403 if (Arg.isInvalid()) return true;
404 TheCall->setArg(I, Arg.get());
405
406 QualType Ty = Arg.get()->getType();
407 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
408 if (!IsValid) {
409 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
410 << CkdOperation << Ty << Arg.get()->getSourceRange();
411 return true;
412 }
413 }
414
415 // Third argument should be a pointer to a non-const integer.
416 // IRGen correctly handles volatile, restrict, and address spaces, and
417 // the other qualifiers aren't possible.
418 {
420 if (Arg.isInvalid()) return true;
421 TheCall->setArg(2, Arg.get());
422
423 QualType Ty = Arg.get()->getType();
424 const auto *PtrTy = Ty->getAs<PointerType>();
425 if (!PtrTy ||
426 !PtrTy->getPointeeType()->isIntegerType() ||
427 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
428 PtrTy->getPointeeType().isConstQualified()) {
429 S.Diag(Arg.get()->getBeginLoc(),
430 diag::err_overflow_builtin_must_be_ptr_int)
431 << CkdOperation << Ty << Arg.get()->getSourceRange();
432 return true;
433 }
434 }
435
436 // Disallow signed bit-precise integer args larger than 128 bits to mul
437 // function until we improve backend support.
438 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
439 for (unsigned I = 0; I < 3; ++I) {
440 const auto Arg = TheCall->getArg(I);
441 // Third argument will be a pointer.
442 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
443 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
444 S.getASTContext().getIntWidth(Ty) > 128)
445 return S.Diag(Arg->getBeginLoc(),
446 diag::err_overflow_builtin_bit_int_max_size)
447 << 128;
448 }
449 }
450
451 return false;
452}
453
454namespace {
455struct BuiltinDumpStructGenerator {
456 Sema &S;
457 CallExpr *TheCall;
458 SourceLocation Loc = TheCall->getBeginLoc();
460 DiagnosticErrorTrap ErrorTracker;
461 PrintingPolicy Policy;
462
463 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
464 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
465 Policy(S.Context.getPrintingPolicy()) {
466 Policy.AnonymousTagLocations = false;
467 }
468
469 Expr *makeOpaqueValueExpr(Expr *Inner) {
470 auto *OVE = new (S.Context)
471 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
472 Inner->getObjectKind(), Inner);
473 Actions.push_back(OVE);
474 return OVE;
475 }
476
477 Expr *getStringLiteral(llvm::StringRef Str) {
479 // Wrap the literal in parentheses to attach a source location.
480 return new (S.Context) ParenExpr(Loc, Loc, Lit);
481 }
482
483 bool callPrintFunction(llvm::StringRef Format,
484 llvm::ArrayRef<Expr *> Exprs = {}) {
486 assert(TheCall->getNumArgs() >= 2);
487 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
488 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
489 Args.push_back(getStringLiteral(Format));
490 Args.insert(Args.end(), Exprs.begin(), Exprs.end());
491
492 // Register a note to explain why we're performing the call.
496 Ctx.CallArgs = Args.data();
497 Ctx.NumCallArgs = Args.size();
499
500 ExprResult RealCall =
501 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
502 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
503
505 if (!RealCall.isInvalid())
506 Actions.push_back(RealCall.get());
507 // Bail out if we've hit any errors, even if we managed to build the
508 // call. We don't want to produce more than one error.
509 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
510 }
511
512 Expr *getIndentString(unsigned Depth) {
513 if (!Depth)
514 return nullptr;
515
517 Indent.resize(Depth * Policy.Indentation, ' ');
518 return getStringLiteral(Indent);
519 }
520
522 return getStringLiteral(T.getAsString(Policy));
523 }
524
525 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
526 llvm::raw_svector_ostream OS(Str);
527
528 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
529 // than trying to print a single character.
530 if (auto *BT = T->getAs<BuiltinType>()) {
531 switch (BT->getKind()) {
532 case BuiltinType::Bool:
533 OS << "%d";
534 return true;
535 case BuiltinType::Char_U:
536 case BuiltinType::UChar:
537 OS << "%hhu";
538 return true;
539 case BuiltinType::Char_S:
540 case BuiltinType::SChar:
541 OS << "%hhd";
542 return true;
543 default:
544 break;
545 }
546 }
547
549 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
550 // We were able to guess how to format this.
551 if (Specifier.getConversionSpecifier().getKind() ==
552 analyze_printf::PrintfConversionSpecifier::sArg) {
553 // Wrap double-quotes around a '%s' specifier and limit its maximum
554 // length. Ideally we'd also somehow escape special characters in the
555 // contents but printf doesn't support that.
556 // FIXME: '%s' formatting is not safe in general.
557 OS << '"';
558 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
559 Specifier.toString(OS);
560 OS << '"';
561 // FIXME: It would be nice to include a '...' if the string doesn't fit
562 // in the length limit.
563 } else {
564 Specifier.toString(OS);
565 }
566 return true;
567 }
568
569 if (T->isPointerType()) {
570 // Format all pointers with '%p'.
571 OS << "%p";
572 return true;
573 }
574
575 return false;
576 }
577
578 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
579 Expr *IndentLit = getIndentString(Depth);
580 Expr *TypeLit = getTypeString(S.Context.getRecordType(RD));
581 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
582 : callPrintFunction("%s", {TypeLit}))
583 return true;
584
585 return dumpRecordValue(RD, E, IndentLit, Depth);
586 }
587
588 // Dump a record value. E should be a pointer or lvalue referring to an RD.
589 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
590 unsigned Depth) {
591 // FIXME: Decide what to do if RD is a union. At least we should probably
592 // turn off printing `const char*` members with `%s`, because that is very
593 // likely to crash if that's not the active member. Whatever we decide, we
594 // should document it.
595
596 // Build an OpaqueValueExpr so we can refer to E more than once without
597 // triggering re-evaluation.
598 Expr *RecordArg = makeOpaqueValueExpr(E);
599 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
600
601 if (callPrintFunction(" {\n"))
602 return true;
603
604 // Dump each base class, regardless of whether they're aggregates.
605 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
606 for (const auto &Base : CXXRD->bases()) {
607 QualType BaseType =
608 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
609 : S.Context.getLValueReferenceType(Base.getType());
612 RecordArg);
613 if (BasePtr.isInvalid() ||
614 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
615 Depth + 1))
616 return true;
617 }
618 }
619
620 Expr *FieldIndentArg = getIndentString(Depth + 1);
621
622 // Dump each field.
623 for (auto *D : RD->decls()) {
624 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
625 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
626 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
627 continue;
628
629 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
630 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
631 getTypeString(FD->getType()),
632 getStringLiteral(FD->getName())};
633
634 if (FD->isBitField()) {
635 Format += ": %zu ";
637 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
638 FD->getBitWidthValue(S.Context));
639 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
640 }
641
642 Format += "=";
643
646 CXXScopeSpec(), Loc, IFD,
647 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
649 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
651 DeclarationNameInfo(FD->getDeclName(), Loc));
652 if (Field.isInvalid())
653 return true;
654
655 auto *InnerRD = FD->getType()->getAsRecordDecl();
656 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
657 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
658 // Recursively print the values of members of aggregate record type.
659 if (callPrintFunction(Format, Args) ||
660 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
661 return true;
662 } else {
663 Format += " ";
664 if (appendFormatSpecifier(FD->getType(), Format)) {
665 // We know how to print this field.
666 Args.push_back(Field.get());
667 } else {
668 // We don't know how to print this field. Print out its address
669 // with a format specifier that a smart tool will be able to
670 // recognize and treat specially.
671 Format += "*%p";
672 ExprResult FieldAddr =
673 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
674 if (FieldAddr.isInvalid())
675 return true;
676 Args.push_back(FieldAddr.get());
677 }
678 Format += "\n";
679 if (callPrintFunction(Format, Args))
680 return true;
681 }
682 }
683
684 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
685 : callPrintFunction("}\n");
686 }
687
688 Expr *buildWrapper() {
689 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
691 TheCall->setType(Wrapper->getType());
692 TheCall->setValueKind(Wrapper->getValueKind());
693 return Wrapper;
694 }
695};
696} // namespace
697
699 if (checkArgCountAtLeast(S, TheCall, 2))
700 return ExprError();
701
702 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
703 if (PtrArgResult.isInvalid())
704 return ExprError();
705 TheCall->setArg(0, PtrArgResult.get());
706
707 // First argument should be a pointer to a struct.
708 QualType PtrArgType = PtrArgResult.get()->getType();
709 if (!PtrArgType->isPointerType() ||
710 !PtrArgType->getPointeeType()->isRecordType()) {
711 S.Diag(PtrArgResult.get()->getBeginLoc(),
712 diag::err_expected_struct_pointer_argument)
713 << 1 << TheCall->getDirectCallee() << PtrArgType;
714 return ExprError();
715 }
716 QualType Pointee = PtrArgType->getPointeeType();
717 const RecordDecl *RD = Pointee->getAsRecordDecl();
718 // Try to instantiate the class template as appropriate; otherwise, access to
719 // its data() may lead to a crash.
720 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
721 diag::err_incomplete_type))
722 return ExprError();
723 // Second argument is a callable, but we can't fully validate it until we try
724 // calling it.
725 QualType FnArgType = TheCall->getArg(1)->getType();
726 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
727 !FnArgType->isBlockPointerType() &&
728 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
729 auto *BT = FnArgType->getAs<BuiltinType>();
730 switch (BT ? BT->getKind() : BuiltinType::Void) {
731 case BuiltinType::Dependent:
732 case BuiltinType::Overload:
733 case BuiltinType::BoundMember:
734 case BuiltinType::PseudoObject:
735 case BuiltinType::UnknownAny:
736 case BuiltinType::BuiltinFn:
737 // This might be a callable.
738 break;
739
740 default:
741 S.Diag(TheCall->getArg(1)->getBeginLoc(),
742 diag::err_expected_callable_argument)
743 << 2 << TheCall->getDirectCallee() << FnArgType;
744 return ExprError();
745 }
746 }
747
748 BuiltinDumpStructGenerator Generator(S, TheCall);
749
750 // Wrap parentheses around the given pointer. This is not necessary for
751 // correct code generation, but it means that when we pretty-print the call
752 // arguments in our diagnostics we will produce '(&s)->n' instead of the
753 // incorrect '&s->n'.
754 Expr *PtrArg = PtrArgResult.get();
755 PtrArg = new (S.Context)
756 ParenExpr(PtrArg->getBeginLoc(),
757 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
758 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
759 return ExprError();
760
761 return Generator.buildWrapper();
762}
763
764static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
765 if (checkArgCount(S, BuiltinCall, 2))
766 return true;
767
768 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
769 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
770 Expr *Call = BuiltinCall->getArg(0);
771 Expr *Chain = BuiltinCall->getArg(1);
772
773 if (Call->getStmtClass() != Stmt::CallExprClass) {
774 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
775 << Call->getSourceRange();
776 return true;
777 }
778
779 auto CE = cast<CallExpr>(Call);
780 if (CE->getCallee()->getType()->isBlockPointerType()) {
781 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
782 << Call->getSourceRange();
783 return true;
784 }
785
786 const Decl *TargetDecl = CE->getCalleeDecl();
787 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
788 if (FD->getBuiltinID()) {
789 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
790 << Call->getSourceRange();
791 return true;
792 }
793
794 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
795 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
796 << Call->getSourceRange();
797 return true;
798 }
799
800 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
801 if (ChainResult.isInvalid())
802 return true;
803 if (!ChainResult.get()->getType()->isPointerType()) {
804 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
805 << Chain->getSourceRange();
806 return true;
807 }
808
809 QualType ReturnTy = CE->getCallReturnType(S.Context);
810 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
811 QualType BuiltinTy = S.Context.getFunctionType(
812 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
813 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
814
815 Builtin =
816 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
817
818 BuiltinCall->setType(CE->getType());
819 BuiltinCall->setValueKind(CE->getValueKind());
820 BuiltinCall->setObjectKind(CE->getObjectKind());
821 BuiltinCall->setCallee(Builtin);
822 BuiltinCall->setArg(1, ChainResult.get());
823
824 return false;
825}
826
827namespace {
828
829class ScanfDiagnosticFormatHandler
831 // Accepts the argument index (relative to the first destination index) of the
832 // argument whose size we want.
833 using ComputeSizeFunction =
834 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
835
836 // Accepts the argument index (relative to the first destination index), the
837 // destination size, and the source size).
838 using DiagnoseFunction =
839 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
840
841 ComputeSizeFunction ComputeSizeArgument;
842 DiagnoseFunction Diagnose;
843
844public:
845 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
846 DiagnoseFunction Diagnose)
847 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
848
849 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
850 const char *StartSpecifier,
851 unsigned specifierLen) override {
852 if (!FS.consumesDataArgument())
853 return true;
854
855 unsigned NulByte = 0;
856 switch ((FS.getConversionSpecifier().getKind())) {
857 default:
858 return true;
861 NulByte = 1;
862 break;
864 break;
865 }
866
867 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
868 if (FW.getHowSpecified() !=
869 analyze_format_string::OptionalAmount::HowSpecified::Constant)
870 return true;
871
872 unsigned SourceSize = FW.getConstantAmount() + NulByte;
873
874 std::optional<llvm::APSInt> DestSizeAPS =
875 ComputeSizeArgument(FS.getArgIndex());
876 if (!DestSizeAPS)
877 return true;
878
879 unsigned DestSize = DestSizeAPS->getZExtValue();
880
881 if (DestSize < SourceSize)
882 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
883
884 return true;
885 }
886};
887
888class EstimateSizeFormatHandler
890 size_t Size;
891 /// Whether the format string contains Linux kernel's format specifier
892 /// extension.
893 bool IsKernelCompatible = true;
894
895public:
896 EstimateSizeFormatHandler(StringRef Format)
897 : Size(std::min(Format.find(0), Format.size()) +
898 1 /* null byte always written by sprintf */) {}
899
900 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
901 const char *, unsigned SpecifierLen,
902 const TargetInfo &) override {
903
904 const size_t FieldWidth = computeFieldWidth(FS);
905 const size_t Precision = computePrecision(FS);
906
907 // The actual format.
908 switch (FS.getConversionSpecifier().getKind()) {
909 // Just a char.
912 Size += std::max(FieldWidth, (size_t)1);
913 break;
914 // Just an integer.
924 Size += std::max(FieldWidth, Precision);
925 break;
926
927 // %g style conversion switches between %f or %e style dynamically.
928 // %g removes trailing zeros, and does not print decimal point if there are
929 // no digits that follow it. Thus %g can print a single digit.
930 // FIXME: If it is alternative form:
931 // For g and G conversions, trailing zeros are not removed from the result.
934 Size += 1;
935 break;
936
937 // Floating point number in the form '[+]ddd.ddd'.
940 Size += std::max(FieldWidth, 1 /* integer part */ +
941 (Precision ? 1 + Precision
942 : 0) /* period + decimal */);
943 break;
944
945 // Floating point number in the form '[-]d.ddde[+-]dd'.
948 Size +=
949 std::max(FieldWidth,
950 1 /* integer part */ +
951 (Precision ? 1 + Precision : 0) /* period + decimal */ +
952 1 /* e or E letter */ + 2 /* exponent */);
953 break;
954
955 // Floating point number in the form '[-]0xh.hhhhp±dd'.
958 Size +=
959 std::max(FieldWidth,
960 2 /* 0x */ + 1 /* integer part */ +
961 (Precision ? 1 + Precision : 0) /* period + decimal */ +
962 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
963 break;
964
965 // Just a string.
968 Size += FieldWidth;
969 break;
970
971 // Just a pointer in the form '0xddd'.
973 // Linux kernel has its own extesion for `%p` specifier.
974 // Kernel Document:
975 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
976 IsKernelCompatible = false;
977 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
978 break;
979
980 // A plain percent.
982 Size += 1;
983 break;
984
985 default:
986 break;
987 }
988
989 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
990
991 if (FS.hasAlternativeForm()) {
992 switch (FS.getConversionSpecifier().getKind()) {
993 // For o conversion, it increases the precision, if and only if necessary,
994 // to force the first digit of the result to be a zero
995 // (if the value and precision are both 0, a single 0 is printed)
997 // For b conversion, a nonzero result has 0b prefixed to it.
999 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1000 // it.
1003 // Note: even when the prefix is added, if
1004 // (prefix_width <= FieldWidth - formatted_length) holds,
1005 // the prefix does not increase the format
1006 // size. e.g.(("%#3x", 0xf) is "0xf")
1007
1008 // If the result is zero, o, b, x, X adds nothing.
1009 break;
1010 // For a, A, e, E, f, F, g, and G conversions,
1011 // the result of converting a floating-point number always contains a
1012 // decimal-point
1021 Size += (Precision ? 0 : 1);
1022 break;
1023 // For other conversions, the behavior is undefined.
1024 default:
1025 break;
1026 }
1027 }
1028 assert(SpecifierLen <= Size && "no underflow");
1029 Size -= SpecifierLen;
1030 return true;
1031 }
1032
1033 size_t getSizeLowerBound() const { return Size; }
1034 bool isKernelCompatible() const { return IsKernelCompatible; }
1035
1036private:
1037 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1038 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1039 size_t FieldWidth = 0;
1041 FieldWidth = FW.getConstantAmount();
1042 return FieldWidth;
1043 }
1044
1045 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1046 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1047 size_t Precision = 0;
1048
1049 // See man 3 printf for default precision value based on the specifier.
1050 switch (FW.getHowSpecified()) {
1052 switch (FS.getConversionSpecifier().getKind()) {
1053 default:
1054 break;
1058 Precision = 1;
1059 break;
1066 Precision = 1;
1067 break;
1074 Precision = 6;
1075 break;
1077 Precision = 1;
1078 break;
1079 }
1080 break;
1082 Precision = FW.getConstantAmount();
1083 break;
1084 default:
1085 break;
1086 }
1087 return Precision;
1088 }
1089};
1090
1091} // namespace
1092
1093static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1094 StringRef &FormatStrRef, size_t &StrLen,
1095 ASTContext &Context) {
1096 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1097 Format && (Format->isOrdinary() || Format->isUTF8())) {
1098 FormatStrRef = Format->getString();
1099 const ConstantArrayType *T =
1100 Context.getAsConstantArrayType(Format->getType());
1101 assert(T && "String literal not of constant array type!");
1102 size_t TypeSize = T->getZExtSize();
1103 // In case there's a null byte somewhere.
1104 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1105 return true;
1106 }
1107 return false;
1108}
1109
1110void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1111 CallExpr *TheCall) {
1112 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1114 return;
1115
1116 bool UseDABAttr = false;
1117 const FunctionDecl *UseDecl = FD;
1118
1119 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1120 if (DABAttr) {
1121 UseDecl = DABAttr->getFunction();
1122 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1123 UseDABAttr = true;
1124 }
1125
1126 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1127
1128 if (!BuiltinID)
1129 return;
1130
1131 const TargetInfo &TI = getASTContext().getTargetInfo();
1132 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1133
1134 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1135 // If we refer to a diagnose_as_builtin attribute, we need to change the
1136 // argument index to refer to the arguments of the called function. Unless
1137 // the index is out of bounds, which presumably means it's a variadic
1138 // function.
1139 if (!UseDABAttr)
1140 return Index;
1141 unsigned DABIndices = DABAttr->argIndices_size();
1142 unsigned NewIndex = Index < DABIndices
1143 ? DABAttr->argIndices_begin()[Index]
1144 : Index - DABIndices + FD->getNumParams();
1145 if (NewIndex >= TheCall->getNumArgs())
1146 return std::nullopt;
1147 return NewIndex;
1148 };
1149
1150 auto ComputeExplicitObjectSizeArgument =
1151 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1152 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1153 if (!IndexOptional)
1154 return std::nullopt;
1155 unsigned NewIndex = *IndexOptional;
1157 Expr *SizeArg = TheCall->getArg(NewIndex);
1158 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1159 return std::nullopt;
1160 llvm::APSInt Integer = Result.Val.getInt();
1161 Integer.setIsUnsigned(true);
1162 return Integer;
1163 };
1164
1165 auto ComputeSizeArgument =
1166 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1167 // If the parameter has a pass_object_size attribute, then we should use its
1168 // (potentially) more strict checking mode. Otherwise, conservatively assume
1169 // type 0.
1170 int BOSType = 0;
1171 // This check can fail for variadic functions.
1172 if (Index < FD->getNumParams()) {
1173 if (const auto *POS =
1174 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1175 BOSType = POS->getType();
1176 }
1177
1178 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1179 if (!IndexOptional)
1180 return std::nullopt;
1181 unsigned NewIndex = *IndexOptional;
1182
1183 if (NewIndex >= TheCall->getNumArgs())
1184 return std::nullopt;
1185
1186 const Expr *ObjArg = TheCall->getArg(NewIndex);
1188 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
1189 return std::nullopt;
1190
1191 // Get the object size in the target's size_t width.
1192 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
1193 };
1194
1195 auto ComputeStrLenArgument =
1196 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1197 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1198 if (!IndexOptional)
1199 return std::nullopt;
1200 unsigned NewIndex = *IndexOptional;
1201
1202 const Expr *ObjArg = TheCall->getArg(NewIndex);
1204 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
1205 return std::nullopt;
1206 // Add 1 for null byte.
1207 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
1208 };
1209
1210 std::optional<llvm::APSInt> SourceSize;
1211 std::optional<llvm::APSInt> DestinationSize;
1212 unsigned DiagID = 0;
1213 bool IsChkVariant = false;
1214
1215 auto GetFunctionName = [&]() {
1216 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
1217 // Skim off the details of whichever builtin was called to produce a better
1218 // diagnostic, as it's unlikely that the user wrote the __builtin
1219 // explicitly.
1220 if (IsChkVariant) {
1221 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1222 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1223 } else {
1224 FunctionName.consume_front("__builtin_");
1225 }
1226 return FunctionName;
1227 };
1228
1229 switch (BuiltinID) {
1230 default:
1231 return;
1232 case Builtin::BI__builtin_strcpy:
1233 case Builtin::BIstrcpy: {
1234 DiagID = diag::warn_fortify_strlen_overflow;
1235 SourceSize = ComputeStrLenArgument(1);
1236 DestinationSize = ComputeSizeArgument(0);
1237 break;
1238 }
1239
1240 case Builtin::BI__builtin___strcpy_chk: {
1241 DiagID = diag::warn_fortify_strlen_overflow;
1242 SourceSize = ComputeStrLenArgument(1);
1243 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1244 IsChkVariant = true;
1245 break;
1246 }
1247
1248 case Builtin::BIscanf:
1249 case Builtin::BIfscanf:
1250 case Builtin::BIsscanf: {
1251 unsigned FormatIndex = 1;
1252 unsigned DataIndex = 2;
1253 if (BuiltinID == Builtin::BIscanf) {
1254 FormatIndex = 0;
1255 DataIndex = 1;
1256 }
1257
1258 const auto *FormatExpr =
1259 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1260
1261 StringRef FormatStrRef;
1262 size_t StrLen;
1263 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1264 return;
1265
1266 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1267 unsigned SourceSize) {
1268 DiagID = diag::warn_fortify_scanf_overflow;
1269 unsigned Index = ArgIndex + DataIndex;
1270 StringRef FunctionName = GetFunctionName();
1271 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1272 PDiag(DiagID) << FunctionName << (Index + 1)
1273 << DestSize << SourceSize);
1274 };
1275
1276 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1277 return ComputeSizeArgument(Index + DataIndex);
1278 };
1279 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1280 const char *FormatBytes = FormatStrRef.data();
1282 FormatBytes + StrLen, getLangOpts(),
1284
1285 // Unlike the other cases, in this one we have already issued the diagnostic
1286 // here, so no need to continue (because unlike the other cases, here the
1287 // diagnostic refers to the argument number).
1288 return;
1289 }
1290
1291 case Builtin::BIsprintf:
1292 case Builtin::BI__builtin___sprintf_chk: {
1293 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1294 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1295
1296 StringRef FormatStrRef;
1297 size_t StrLen;
1298 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1299 EstimateSizeFormatHandler H(FormatStrRef);
1300 const char *FormatBytes = FormatStrRef.data();
1302 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1303 Context.getTargetInfo(), false)) {
1304 DiagID = H.isKernelCompatible()
1305 ? diag::warn_format_overflow
1306 : diag::warn_format_overflow_non_kprintf;
1307 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1308 .extOrTrunc(SizeTypeWidth);
1309 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1310 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1311 IsChkVariant = true;
1312 } else {
1313 DestinationSize = ComputeSizeArgument(0);
1314 }
1315 break;
1316 }
1317 }
1318 return;
1319 }
1320 case Builtin::BI__builtin___memcpy_chk:
1321 case Builtin::BI__builtin___memmove_chk:
1322 case Builtin::BI__builtin___memset_chk:
1323 case Builtin::BI__builtin___strlcat_chk:
1324 case Builtin::BI__builtin___strlcpy_chk:
1325 case Builtin::BI__builtin___strncat_chk:
1326 case Builtin::BI__builtin___strncpy_chk:
1327 case Builtin::BI__builtin___stpncpy_chk:
1328 case Builtin::BI__builtin___memccpy_chk:
1329 case Builtin::BI__builtin___mempcpy_chk: {
1330 DiagID = diag::warn_builtin_chk_overflow;
1331 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1332 DestinationSize =
1333 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1334 IsChkVariant = true;
1335 break;
1336 }
1337
1338 case Builtin::BI__builtin___snprintf_chk:
1339 case Builtin::BI__builtin___vsnprintf_chk: {
1340 DiagID = diag::warn_builtin_chk_overflow;
1341 SourceSize = ComputeExplicitObjectSizeArgument(1);
1342 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1343 IsChkVariant = true;
1344 break;
1345 }
1346
1347 case Builtin::BIstrncat:
1348 case Builtin::BI__builtin_strncat:
1349 case Builtin::BIstrncpy:
1350 case Builtin::BI__builtin_strncpy:
1351 case Builtin::BIstpncpy:
1352 case Builtin::BI__builtin_stpncpy: {
1353 // Whether these functions overflow depends on the runtime strlen of the
1354 // string, not just the buffer size, so emitting the "always overflow"
1355 // diagnostic isn't quite right. We should still diagnose passing a buffer
1356 // size larger than the destination buffer though; this is a runtime abort
1357 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1358 DiagID = diag::warn_fortify_source_size_mismatch;
1359 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1360 DestinationSize = ComputeSizeArgument(0);
1361 break;
1362 }
1363
1364 case Builtin::BImemcpy:
1365 case Builtin::BI__builtin_memcpy:
1366 case Builtin::BImemmove:
1367 case Builtin::BI__builtin_memmove:
1368 case Builtin::BImemset:
1369 case Builtin::BI__builtin_memset:
1370 case Builtin::BImempcpy:
1371 case Builtin::BI__builtin_mempcpy: {
1372 DiagID = diag::warn_fortify_source_overflow;
1373 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1374 DestinationSize = ComputeSizeArgument(0);
1375 break;
1376 }
1377 case Builtin::BIsnprintf:
1378 case Builtin::BI__builtin_snprintf:
1379 case Builtin::BIvsnprintf:
1380 case Builtin::BI__builtin_vsnprintf: {
1381 DiagID = diag::warn_fortify_source_size_mismatch;
1382 SourceSize = ComputeExplicitObjectSizeArgument(1);
1383 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1384 StringRef FormatStrRef;
1385 size_t StrLen;
1386 if (SourceSize &&
1387 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1388 EstimateSizeFormatHandler H(FormatStrRef);
1389 const char *FormatBytes = FormatStrRef.data();
1391 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1392 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1393 llvm::APSInt FormatSize =
1394 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1395 .extOrTrunc(SizeTypeWidth);
1396 if (FormatSize > *SourceSize && *SourceSize != 0) {
1397 unsigned TruncationDiagID =
1398 H.isKernelCompatible() ? diag::warn_format_truncation
1399 : diag::warn_format_truncation_non_kprintf;
1400 SmallString<16> SpecifiedSizeStr;
1401 SmallString<16> FormatSizeStr;
1402 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1403 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1404 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1405 PDiag(TruncationDiagID)
1406 << GetFunctionName() << SpecifiedSizeStr
1407 << FormatSizeStr);
1408 }
1409 }
1410 }
1411 DestinationSize = ComputeSizeArgument(0);
1412 }
1413 }
1414
1415 if (!SourceSize || !DestinationSize ||
1416 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1417 return;
1418
1419 StringRef FunctionName = GetFunctionName();
1420
1421 SmallString<16> DestinationStr;
1422 SmallString<16> SourceStr;
1423 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1424 SourceSize->toString(SourceStr, /*Radix=*/10);
1425 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1426 PDiag(DiagID)
1427 << FunctionName << DestinationStr << SourceStr);
1428}
1429
1430static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1431 Scope::ScopeFlags NeededScopeFlags,
1432 unsigned DiagID) {
1433 // Scopes aren't available during instantiation. Fortunately, builtin
1434 // functions cannot be template args so they cannot be formed through template
1435 // instantiation. Therefore checking once during the parse is sufficient.
1436 if (SemaRef.inTemplateInstantiation())
1437 return false;
1438
1439 Scope *S = SemaRef.getCurScope();
1440 while (S && !S->isSEHExceptScope())
1441 S = S->getParent();
1442 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1443 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1444 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1445 << DRE->getDecl()->getIdentifier();
1446 return true;
1447 }
1448
1449 return false;
1450}
1451
1452static inline bool isBlockPointer(Expr *Arg) {
1453 return Arg->getType()->isBlockPointerType();
1454}
1455
1456/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
1457/// void*, which is a requirement of device side enqueue.
1458static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
1459 const BlockPointerType *BPT =
1460 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1461 ArrayRef<QualType> Params =
1462 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
1463 unsigned ArgCounter = 0;
1464 bool IllegalParams = false;
1465 // Iterate through the block parameters until either one is found that is not
1466 // a local void*, or the block is valid.
1467 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
1468 I != E; ++I, ++ArgCounter) {
1469 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
1470 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
1472 // Get the location of the error. If a block literal has been passed
1473 // (BlockExpr) then we can point straight to the offending argument,
1474 // else we just point to the variable reference.
1475 SourceLocation ErrorLoc;
1476 if (isa<BlockExpr>(BlockArg)) {
1477 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
1478 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
1479 } else if (isa<DeclRefExpr>(BlockArg)) {
1480 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
1481 }
1482 S.Diag(ErrorLoc,
1483 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
1484 IllegalParams = true;
1485 }
1486 }
1487
1488 return IllegalParams;
1489}
1490
1492 // OpenCL device can support extension but not the feature as extension
1493 // requires subgroup independent forward progress, but subgroup independent
1494 // forward progress is optional in OpenCL C 3.0 __opencl_c_subgroups feature.
1495 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts()) &&
1496 !S.getOpenCLOptions().isSupported("__opencl_c_subgroups",
1497 S.getLangOpts())) {
1498 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
1499 << 1 << Call->getDirectCallee()
1500 << "cl_khr_subgroups or __opencl_c_subgroups";
1501 return true;
1502 }
1503 return false;
1504}
1505
1506static bool OpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
1507 if (checkArgCount(S, TheCall, 2))
1508 return true;
1509
1510 if (checkOpenCLSubgroupExt(S, TheCall))
1511 return true;
1512
1513 // First argument is an ndrange_t type.
1514 Expr *NDRangeArg = TheCall->getArg(0);
1515 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1516 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1517 << TheCall->getDirectCallee() << "'ndrange_t'";
1518 return true;
1519 }
1520
1521 Expr *BlockArg = TheCall->getArg(1);
1522 if (!isBlockPointer(BlockArg)) {
1523 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1524 << TheCall->getDirectCallee() << "block";
1525 return true;
1526 }
1527 return checkOpenCLBlockArgs(S, BlockArg);
1528}
1529
1530/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
1531/// get_kernel_work_group_size
1532/// and get_kernel_preferred_work_group_size_multiple builtin functions.
1534 if (checkArgCount(S, TheCall, 1))
1535 return true;
1536
1537 Expr *BlockArg = TheCall->getArg(0);
1538 if (!isBlockPointer(BlockArg)) {
1539 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1540 << TheCall->getDirectCallee() << "block";
1541 return true;
1542 }
1543 return checkOpenCLBlockArgs(S, BlockArg);
1544}
1545
1546/// Diagnose integer type and any valid implicit conversion to it.
1547static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
1548 const QualType &IntType);
1549
1551 unsigned Start, unsigned End) {
1552 bool IllegalParams = false;
1553 for (unsigned I = Start; I <= End; ++I)
1554 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
1555 S.Context.getSizeType());
1556 return IllegalParams;
1557}
1558
1559/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
1560/// 'local void*' parameter of passed block.
1562 Expr *BlockArg,
1563 unsigned NumNonVarArgs) {
1564 const BlockPointerType *BPT =
1565 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1566 unsigned NumBlockParams =
1567 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
1568 unsigned TotalNumArgs = TheCall->getNumArgs();
1569
1570 // For each argument passed to the block, a corresponding uint needs to
1571 // be passed to describe the size of the local memory.
1572 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
1573 S.Diag(TheCall->getBeginLoc(),
1574 diag::err_opencl_enqueue_kernel_local_size_args);
1575 return true;
1576 }
1577
1578 // Check that the sizes of the local memory are specified by integers.
1579 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
1580 TotalNumArgs - 1);
1581}
1582
1583/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
1584/// overload formats specified in Table 6.13.17.1.
1585/// int enqueue_kernel(queue_t queue,
1586/// kernel_enqueue_flags_t flags,
1587/// const ndrange_t ndrange,
1588/// void (^block)(void))
1589/// int enqueue_kernel(queue_t queue,
1590/// kernel_enqueue_flags_t flags,
1591/// const ndrange_t ndrange,
1592/// uint num_events_in_wait_list,
1593/// clk_event_t *event_wait_list,
1594/// clk_event_t *event_ret,
1595/// void (^block)(void))
1596/// int enqueue_kernel(queue_t queue,
1597/// kernel_enqueue_flags_t flags,
1598/// const ndrange_t ndrange,
1599/// void (^block)(local void*, ...),
1600/// uint size0, ...)
1601/// int enqueue_kernel(queue_t queue,
1602/// kernel_enqueue_flags_t flags,
1603/// const ndrange_t ndrange,
1604/// uint num_events_in_wait_list,
1605/// clk_event_t *event_wait_list,
1606/// clk_event_t *event_ret,
1607/// void (^block)(local void*, ...),
1608/// uint size0, ...)
1609static bool OpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
1610 unsigned NumArgs = TheCall->getNumArgs();
1611
1612 if (NumArgs < 4) {
1613 S.Diag(TheCall->getBeginLoc(),
1614 diag::err_typecheck_call_too_few_args_at_least)
1615 << 0 << 4 << NumArgs << /*is non object*/ 0;
1616 return true;
1617 }
1618
1619 Expr *Arg0 = TheCall->getArg(0);
1620 Expr *Arg1 = TheCall->getArg(1);
1621 Expr *Arg2 = TheCall->getArg(2);
1622 Expr *Arg3 = TheCall->getArg(3);
1623
1624 // First argument always needs to be a queue_t type.
1625 if (!Arg0->getType()->isQueueT()) {
1626 S.Diag(TheCall->getArg(0)->getBeginLoc(),
1627 diag::err_opencl_builtin_expected_type)
1628 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
1629 return true;
1630 }
1631
1632 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
1633 if (!Arg1->getType()->isIntegerType()) {
1634 S.Diag(TheCall->getArg(1)->getBeginLoc(),
1635 diag::err_opencl_builtin_expected_type)
1636 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
1637 return true;
1638 }
1639
1640 // Third argument is always an ndrange_t type.
1641 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1642 S.Diag(TheCall->getArg(2)->getBeginLoc(),
1643 diag::err_opencl_builtin_expected_type)
1644 << TheCall->getDirectCallee() << "'ndrange_t'";
1645 return true;
1646 }
1647
1648 // With four arguments, there is only one form that the function could be
1649 // called in: no events and no variable arguments.
1650 if (NumArgs == 4) {
1651 // check that the last argument is the right block type.
1652 if (!isBlockPointer(Arg3)) {
1653 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1654 << TheCall->getDirectCallee() << "block";
1655 return true;
1656 }
1657 // we have a block type, check the prototype
1658 const BlockPointerType *BPT =
1659 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1660 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1661 S.Diag(Arg3->getBeginLoc(),
1662 diag::err_opencl_enqueue_kernel_blocks_no_args);
1663 return true;
1664 }
1665 return false;
1666 }
1667 // we can have block + varargs.
1668 if (isBlockPointer(Arg3))
1669 return (checkOpenCLBlockArgs(S, Arg3) ||
1670 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1671 // last two cases with either exactly 7 args or 7 args and varargs.
1672 if (NumArgs >= 7) {
1673 // check common block argument.
1674 Expr *Arg6 = TheCall->getArg(6);
1675 if (!isBlockPointer(Arg6)) {
1676 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1677 << TheCall->getDirectCallee() << "block";
1678 return true;
1679 }
1680 if (checkOpenCLBlockArgs(S, Arg6))
1681 return true;
1682
1683 // Forth argument has to be any integer type.
1684 if (!Arg3->getType()->isIntegerType()) {
1685 S.Diag(TheCall->getArg(3)->getBeginLoc(),
1686 diag::err_opencl_builtin_expected_type)
1687 << TheCall->getDirectCallee() << "integer";
1688 return true;
1689 }
1690 // check remaining common arguments.
1691 Expr *Arg4 = TheCall->getArg(4);
1692 Expr *Arg5 = TheCall->getArg(5);
1693
1694 // Fifth argument is always passed as a pointer to clk_event_t.
1695 if (!Arg4->isNullPointerConstant(S.Context,
1698 S.Diag(TheCall->getArg(4)->getBeginLoc(),
1699 diag::err_opencl_builtin_expected_type)
1700 << TheCall->getDirectCallee()
1702 return true;
1703 }
1704
1705 // Sixth argument is always passed as a pointer to clk_event_t.
1706 if (!Arg5->isNullPointerConstant(S.Context,
1708 !(Arg5->getType()->isPointerType() &&
1709 Arg5->getType()->getPointeeType()->isClkEventT())) {
1710 S.Diag(TheCall->getArg(5)->getBeginLoc(),
1711 diag::err_opencl_builtin_expected_type)
1712 << TheCall->getDirectCallee()
1714 return true;
1715 }
1716
1717 if (NumArgs == 7)
1718 return false;
1719
1720 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1721 }
1722
1723 // None of the specific case has been detected, give generic error
1724 S.Diag(TheCall->getBeginLoc(),
1725 diag::err_opencl_enqueue_kernel_incorrect_args);
1726 return true;
1727}
1728
1729/// Returns OpenCL access qual.
1730static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1731 return D->getAttr<OpenCLAccessAttr>();
1732}
1733
1734/// Returns true if pipe element type is different from the pointer.
1736 const Expr *Arg0 = Call->getArg(0);
1737 // First argument type should always be pipe.
1738 if (!Arg0->getType()->isPipeType()) {
1739 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1740 << Call->getDirectCallee() << Arg0->getSourceRange();
1741 return true;
1742 }
1743 OpenCLAccessAttr *AccessQual =
1744 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1745 // Validates the access qualifier is compatible with the call.
1746 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1747 // read_only and write_only, and assumed to be read_only if no qualifier is
1748 // specified.
1749 switch (Call->getDirectCallee()->getBuiltinID()) {
1750 case Builtin::BIread_pipe:
1751 case Builtin::BIreserve_read_pipe:
1752 case Builtin::BIcommit_read_pipe:
1753 case Builtin::BIwork_group_reserve_read_pipe:
1754 case Builtin::BIsub_group_reserve_read_pipe:
1755 case Builtin::BIwork_group_commit_read_pipe:
1756 case Builtin::BIsub_group_commit_read_pipe:
1757 if (!(!AccessQual || AccessQual->isReadOnly())) {
1758 S.Diag(Arg0->getBeginLoc(),
1759 diag::err_opencl_builtin_pipe_invalid_access_modifier)
1760 << "read_only" << Arg0->getSourceRange();
1761 return true;
1762 }
1763 break;
1764 case Builtin::BIwrite_pipe:
1765 case Builtin::BIreserve_write_pipe:
1766 case Builtin::BIcommit_write_pipe:
1767 case Builtin::BIwork_group_reserve_write_pipe:
1768 case Builtin::BIsub_group_reserve_write_pipe:
1769 case Builtin::BIwork_group_commit_write_pipe:
1770 case Builtin::BIsub_group_commit_write_pipe:
1771 if (!(AccessQual && AccessQual->isWriteOnly())) {
1772 S.Diag(Arg0->getBeginLoc(),
1773 diag::err_opencl_builtin_pipe_invalid_access_modifier)
1774 << "write_only" << Arg0->getSourceRange();
1775 return true;
1776 }
1777 break;
1778 default:
1779 break;
1780 }
1781 return false;
1782}
1783
1784/// Returns true if pipe element type is different from the pointer.
1785static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1786 const Expr *Arg0 = Call->getArg(0);
1787 const Expr *ArgIdx = Call->getArg(Idx);
1788 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1789 const QualType EltTy = PipeTy->getElementType();
1790 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1791 // The Idx argument should be a pointer and the type of the pointer and
1792 // the type of pipe element should also be the same.
1793 if (!ArgTy ||
1795 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1796 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1797 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1798 << ArgIdx->getType() << ArgIdx->getSourceRange();
1799 return true;
1800 }
1801 return false;
1802}
1803
1804// Performs semantic analysis for the read/write_pipe call.
1805// \param S Reference to the semantic analyzer.
1806// \param Call A pointer to the builtin call.
1807// \return True if a semantic error has been found, false otherwise.
1808static bool BuiltinRWPipe(Sema &S, CallExpr *Call) {
1809 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1810 // functions have two forms.
1811 switch (Call->getNumArgs()) {
1812 case 2:
1813 if (checkOpenCLPipeArg(S, Call))
1814 return true;
1815 // The call with 2 arguments should be
1816 // read/write_pipe(pipe T, T*).
1817 // Check packet type T.
1819 return true;
1820 break;
1821
1822 case 4: {
1823 if (checkOpenCLPipeArg(S, Call))
1824 return true;
1825 // The call with 4 arguments should be
1826 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1827 // Check reserve_id_t.
1828 if (!Call->getArg(1)->getType()->isReserveIDT()) {
1829 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1830 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1831 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1832 return true;
1833 }
1834
1835 // Check the index.
1836 const Expr *Arg2 = Call->getArg(2);
1837 if (!Arg2->getType()->isIntegerType() &&
1838 !Arg2->getType()->isUnsignedIntegerType()) {
1839 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1840 << Call->getDirectCallee() << S.Context.UnsignedIntTy
1841 << Arg2->getType() << Arg2->getSourceRange();
1842 return true;
1843 }
1844
1845 // Check packet type T.
1847 return true;
1848 } break;
1849 default:
1850 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1851 << Call->getDirectCallee() << Call->getSourceRange();
1852 return true;
1853 }
1854
1855 return false;
1856}
1857
1858// Performs a semantic analysis on the {work_group_/sub_group_
1859// /_}reserve_{read/write}_pipe
1860// \param S Reference to the semantic analyzer.
1861// \param Call The call to the builtin function to be analyzed.
1862// \return True if a semantic error was found, false otherwise.
1864 if (checkArgCount(S, Call, 2))
1865 return true;
1866
1867 if (checkOpenCLPipeArg(S, Call))
1868 return true;
1869
1870 // Check the reserve size.
1871 if (!Call->getArg(1)->getType()->isIntegerType() &&
1872 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1873 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1874 << Call->getDirectCallee() << S.Context.UnsignedIntTy
1875 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1876 return true;
1877 }
1878
1879 // Since return type of reserve_read/write_pipe built-in function is
1880 // reserve_id_t, which is not defined in the builtin def file , we used int
1881 // as return type and need to override the return type of these functions.
1882 Call->setType(S.Context.OCLReserveIDTy);
1883
1884 return false;
1885}
1886
1887// Performs a semantic analysis on {work_group_/sub_group_
1888// /_}commit_{read/write}_pipe
1889// \param S Reference to the semantic analyzer.
1890// \param Call The call to the builtin function to be analyzed.
1891// \return True if a semantic error was found, false otherwise.
1893 if (checkArgCount(S, Call, 2))
1894 return true;
1895
1896 if (checkOpenCLPipeArg(S, Call))
1897 return true;
1898
1899 // Check reserve_id_t.
1900 if (!Call->getArg(1)->getType()->isReserveIDT()) {
1901 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1902 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1903 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1904 return true;
1905 }
1906
1907 return false;
1908}
1909
1910// Performs a semantic analysis on the call to built-in Pipe
1911// Query Functions.
1912// \param S Reference to the semantic analyzer.
1913// \param Call The call to the builtin function to be analyzed.
1914// \return True if a semantic error was found, false otherwise.
1916 if (checkArgCount(S, Call, 1))
1917 return true;
1918
1919 if (!Call->getArg(0)->getType()->isPipeType()) {
1920 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1921 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1922 return true;
1923 }
1924
1925 return false;
1926}
1927
1928// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1929// Performs semantic analysis for the to_global/local/private call.
1930// \param S Reference to the semantic analyzer.
1931// \param BuiltinID ID of the builtin function.
1932// \param Call A pointer to the builtin call.
1933// \return True if a semantic error has been found, false otherwise.
1934static bool OpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 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
1974namespace {
1975enum PointerAuthOpKind {
1976 PAO_Strip,
1977 PAO_Sign,
1978 PAO_Auth,
1979 PAO_SignGeneric,
1980 PAO_Discriminator,
1981 PAO_BlendPointer,
1982 PAO_BlendInteger
1983};
1984}
1985
1986static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1987 if (S.getLangOpts().PointerAuthIntrinsics)
1988 return false;
1989
1990 S.Diag(E->getExprLoc(), diag::err_ptrauth_disabled) << E->getSourceRange();
1991 return true;
1992}
1993
1994static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1995 // Convert it to type 'int'.
1996 if (convertArgumentToType(S, Arg, S.Context.IntTy))
1997 return true;
1998
1999 // Value-dependent expressions are okay; wait for template instantiation.
2000 if (Arg->isValueDependent())
2001 return false;
2002
2003 unsigned KeyValue;
2004 return S.checkConstantPointerAuthKey(Arg, KeyValue);
2005}
2006
2008 // Attempt to constant-evaluate the expression.
2009 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
2010 if (!KeyValue) {
2011 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
2012 << 0 << Arg->getSourceRange();
2013 return true;
2014 }
2015
2016 // Ask the target to validate the key parameter.
2017 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
2019 {
2020 llvm::raw_svector_ostream Str(Value);
2021 Str << *KeyValue;
2022 }
2023
2024 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
2025 << Value << Arg->getSourceRange();
2026 return true;
2027 }
2028
2029 Result = KeyValue->getZExtValue();
2030 return false;
2031}
2032
2033static bool checkPointerAuthValue(Sema &S, Expr *&Arg,
2034 PointerAuthOpKind OpKind) {
2035 if (Arg->hasPlaceholderType()) {
2037 if (R.isInvalid())
2038 return true;
2039 Arg = R.get();
2040 }
2041
2042 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
2043 return OpKind != PAO_BlendInteger;
2044 };
2045 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
2046 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
2047 OpKind == PAO_SignGeneric;
2048 };
2049
2050 // Require the value to have the right range of type.
2051 QualType ExpectedTy;
2052 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
2053 ExpectedTy = Arg->getType().getUnqualifiedType();
2054 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
2055 ExpectedTy = S.Context.VoidPtrTy;
2056 } else if (AllowsInteger(OpKind) &&
2058 ExpectedTy = S.Context.getUIntPtrType();
2059
2060 } else {
2061 // Diagnose the failures.
2062 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
2063 << unsigned(OpKind == PAO_Discriminator ? 1
2064 : OpKind == PAO_BlendPointer ? 2
2065 : OpKind == PAO_BlendInteger ? 3
2066 : 0)
2067 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
2068 << Arg->getType() << Arg->getSourceRange();
2069 return true;
2070 }
2071
2072 // Convert to that type. This should just be an lvalue-to-rvalue
2073 // conversion.
2074 if (convertArgumentToType(S, Arg, ExpectedTy))
2075 return true;
2076
2077 // Warn about null pointers for non-generic sign and auth operations.
2078 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
2080 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
2081 ? diag::warn_ptrauth_sign_null_pointer
2082 : diag::warn_ptrauth_auth_null_pointer)
2083 << Arg->getSourceRange();
2084 }
2085
2086 return false;
2087}
2088
2090 if (checkArgCount(S, Call, 2))
2091 return ExprError();
2093 return ExprError();
2094 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
2095 checkPointerAuthKey(S, Call->getArgs()[1]))
2096 return ExprError();
2097
2098 Call->setType(Call->getArgs()[0]->getType());
2099 return Call;
2100}
2101
2103 if (checkArgCount(S, Call, 2))
2104 return ExprError();
2106 return ExprError();
2107 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
2108 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
2109 return ExprError();
2110
2111 Call->setType(S.Context.getUIntPtrType());
2112 return Call;
2113}
2114
2116 if (checkArgCount(S, Call, 2))
2117 return ExprError();
2119 return ExprError();
2120 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
2121 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
2122 return ExprError();
2123
2124 Call->setType(S.Context.getUIntPtrType());
2125 return Call;
2126}
2127
2129 PointerAuthOpKind OpKind) {
2130 if (checkArgCount(S, Call, 3))
2131 return ExprError();
2133 return ExprError();
2134 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind) ||
2135 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2136 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator))
2137 return ExprError();
2138
2139 Call->setType(Call->getArgs()[0]->getType());
2140 return Call;
2141}
2142
2144 if (checkArgCount(S, Call, 5))
2145 return ExprError();
2147 return ExprError();
2148 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
2149 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2150 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
2151 checkPointerAuthKey(S, Call->getArgs()[3]) ||
2152 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
2153 return ExprError();
2154
2155 Call->setType(Call->getArgs()[0]->getType());
2156 return Call;
2157}
2158
2160 if (checkArgCount(S, TheCall, 1))
2161 return ExprError();
2162
2163 // Compute __builtin_launder's parameter type from the argument.
2164 // The parameter type is:
2165 // * The type of the argument if it's not an array or function type,
2166 // Otherwise,
2167 // * The decayed argument type.
2168 QualType ParamTy = [&]() {
2169 QualType ArgTy = TheCall->getArg(0)->getType();
2170 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
2171 return S.Context.getPointerType(Ty->getElementType());
2172 if (ArgTy->isFunctionType()) {
2173 return S.Context.getPointerType(ArgTy);
2174 }
2175 return ArgTy;
2176 }();
2177
2178 TheCall->setType(ParamTy);
2179
2180 auto DiagSelect = [&]() -> std::optional<unsigned> {
2181 if (!ParamTy->isPointerType())
2182 return 0;
2183 if (ParamTy->isFunctionPointerType())
2184 return 1;
2185 if (ParamTy->isVoidPointerType())
2186 return 2;
2187 return std::optional<unsigned>{};
2188 }();
2189 if (DiagSelect) {
2190 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
2191 << *DiagSelect << TheCall->getSourceRange();
2192 return ExprError();
2193 }
2194
2195 // We either have an incomplete class type, or we have a class template
2196 // whose instantiation has not been forced. Example:
2197 //
2198 // template <class T> struct Foo { T value; };
2199 // Foo<int> *p = nullptr;
2200 // auto *d = __builtin_launder(p);
2201 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
2202 diag::err_incomplete_type))
2203 return ExprError();
2204
2205 assert(ParamTy->getPointeeType()->isObjectType() &&
2206 "Unhandled non-object pointer case");
2207
2208 InitializedEntity Entity =
2210 ExprResult Arg =
2211 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
2212 if (Arg.isInvalid())
2213 return ExprError();
2214 TheCall->setArg(0, Arg.get());
2215
2216 return TheCall;
2217}
2218
2219// Emit an error and return true if the current object format type is in the
2220// list of unsupported types.
2222 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2223 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2224 llvm::Triple::ObjectFormatType CurObjFormat =
2225 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2226 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2227 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2228 << TheCall->getSourceRange();
2229 return true;
2230 }
2231 return false;
2232}
2233
2234// Emit an error and return true if the current architecture is not in the list
2235// of supported architectures.
2236static bool
2237CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2238 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2239 llvm::Triple::ArchType CurArch =
2240 S.getASTContext().getTargetInfo().getTriple().getArch();
2241 if (llvm::is_contained(SupportedArchs, CurArch))
2242 return false;
2243 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2244 << TheCall->getSourceRange();
2245 return true;
2246}
2247
2248static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2249 SourceLocation CallSiteLoc);
2250
2251bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2252 CallExpr *TheCall) {
2253 switch (TI.getTriple().getArch()) {
2254 default:
2255 // Some builtins don't require additional checking, so just consider these
2256 // acceptable.
2257 return false;
2258 case llvm::Triple::arm:
2259 case llvm::Triple::armeb:
2260 case llvm::Triple::thumb:
2261 case llvm::Triple::thumbeb:
2262 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2263 case llvm::Triple::aarch64:
2264 case llvm::Triple::aarch64_32:
2265 case llvm::Triple::aarch64_be:
2266 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2267 case llvm::Triple::bpfeb:
2268 case llvm::Triple::bpfel:
2269 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2270 case llvm::Triple::hexagon:
2271 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2272 case llvm::Triple::mips:
2273 case llvm::Triple::mipsel:
2274 case llvm::Triple::mips64:
2275 case llvm::Triple::mips64el:
2276 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2277 case llvm::Triple::systemz:
2278 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2279 case llvm::Triple::x86:
2280 case llvm::Triple::x86_64:
2281 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
2282 case llvm::Triple::ppc:
2283 case llvm::Triple::ppcle:
2284 case llvm::Triple::ppc64:
2285 case llvm::Triple::ppc64le:
2286 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2287 case llvm::Triple::amdgcn:
2288 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2289 case llvm::Triple::riscv32:
2290 case llvm::Triple::riscv64:
2291 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2292 case llvm::Triple::loongarch32:
2293 case llvm::Triple::loongarch64:
2294 return CheckLoongArchBuiltinFunctionCall(TI, BuiltinID, TheCall);
2295 case llvm::Triple::wasm32:
2296 case llvm::Triple::wasm64:
2297 return CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2298 case llvm::Triple::nvptx:
2299 case llvm::Triple::nvptx64:
2300 return CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2301 }
2302}
2303
2304// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2305// not a valid type, emit an error message and return true. Otherwise return
2306// false.
2308 QualType ArgTy, int ArgIndex) {
2309 if (!ArgTy->getAs<VectorType>() &&
2311 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2312 << ArgIndex << /* vector, integer or float ty*/ 0 << ArgTy;
2313 }
2314
2315 return false;
2316}
2317
2319 QualType ArgTy, int ArgIndex) {
2320 QualType EltTy = ArgTy;
2321 if (auto *VecTy = EltTy->getAs<VectorType>())
2322 EltTy = VecTy->getElementType();
2323
2324 if (!EltTy->isRealFloatingType()) {
2325 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2326 << ArgIndex << /* vector or float ty*/ 5 << ArgTy;
2327 }
2328
2329 return false;
2330}
2331
2332/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2333/// This checks that the target supports the builtin and that the string
2334/// argument is constant and valid.
2335static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2336 const TargetInfo *AuxTI, unsigned BuiltinID) {
2337 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2338 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2339 "Expecting __builtin_cpu_...");
2340
2341 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2342 const TargetInfo *TheTI = &TI;
2343 auto SupportsBI = [=](const TargetInfo *TInfo) {
2344 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2345 (!IsCPUSupports && TInfo->supportsCpuIs()));
2346 };
2347 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2348 TheTI = AuxTI;
2349
2350 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2351 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2352 return S.Diag(TheCall->getBeginLoc(),
2353 TI.getTriple().isOSAIX()
2354 ? diag::err_builtin_aix_os_unsupported
2355 : diag::err_builtin_target_unsupported)
2356 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2357
2358 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2359 // Check if the argument is a string literal.
2360 if (!isa<StringLiteral>(Arg))
2361 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2362 << Arg->getSourceRange();
2363
2364 // Check the contents of the string.
2365 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2366 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2367 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2368 << Arg->getSourceRange();
2369 return false;
2370 }
2371 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2372 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2373 << Arg->getSourceRange();
2374 return false;
2375}
2376
2377/// Checks that __builtin_popcountg was called with a single argument, which is
2378/// an unsigned integer.
2379static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2380 if (checkArgCount(S, TheCall, 1))
2381 return true;
2382
2383 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2384 if (ArgRes.isInvalid())
2385 return true;
2386
2387 Expr *Arg = ArgRes.get();
2388 TheCall->setArg(0, Arg);
2389
2390 QualType ArgTy = Arg->getType();
2391
2392 if (!ArgTy->isUnsignedIntegerType()) {
2393 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2394 << 1 << /*unsigned integer ty*/ 7 << ArgTy;
2395 return true;
2396 }
2397 return false;
2398}
2399
2400/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2401/// an unsigned integer, and an optional second argument, which is promoted to
2402/// an 'int'.
2403static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2404 if (checkArgCountRange(S, TheCall, 1, 2))
2405 return true;
2406
2407 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2408 if (Arg0Res.isInvalid())
2409 return true;
2410
2411 Expr *Arg0 = Arg0Res.get();
2412 TheCall->setArg(0, Arg0);
2413
2414 QualType Arg0Ty = Arg0->getType();
2415
2416 if (!Arg0Ty->isUnsignedIntegerType()) {
2417 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2418 << 1 << /*unsigned integer ty*/ 7 << Arg0Ty;
2419 return true;
2420 }
2421
2422 if (TheCall->getNumArgs() > 1) {
2423 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2424 if (Arg1Res.isInvalid())
2425 return true;
2426
2427 Expr *Arg1 = Arg1Res.get();
2428 TheCall->setArg(1, Arg1);
2429
2430 QualType Arg1Ty = Arg1->getType();
2431
2432 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2433 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2434 << 2 << /*'int' ty*/ 8 << Arg1Ty;
2435 return true;
2436 }
2437 }
2438
2439 return false;
2440}
2441
2443Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2444 CallExpr *TheCall) {
2445 ExprResult TheCallResult(TheCall);
2446
2447 // Find out if any arguments are required to be integer constant expressions.
2448 unsigned ICEArguments = 0;
2450 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2451 if (Error != ASTContext::GE_None)
2452 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2453
2454 // If any arguments are required to be ICE's, check and diagnose.
2455 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2456 // Skip arguments not required to be ICE's.
2457 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2458
2459 llvm::APSInt Result;
2460 // If we don't have enough arguments, continue so we can issue better
2461 // diagnostic in checkArgCount(...)
2462 if (ArgNo < TheCall->getNumArgs() &&
2463 BuiltinConstantArg(TheCall, ArgNo, Result))
2464 return true;
2465 ICEArguments &= ~(1 << ArgNo);
2466 }
2467
2468 FPOptions FPO;
2469 switch (BuiltinID) {
2470 case Builtin::BI__builtin_cpu_supports:
2471 case Builtin::BI__builtin_cpu_is:
2472 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2473 Context.getAuxTargetInfo(), BuiltinID))
2474 return ExprError();
2475 break;
2476 case Builtin::BI__builtin_cpu_init:
2478 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2479 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2480 return ExprError();
2481 }
2482 break;
2483 case Builtin::BI__builtin___CFStringMakeConstantString:
2484 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2485 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2487 *this, BuiltinID, TheCall,
2488 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2489 return ExprError();
2490 assert(TheCall->getNumArgs() == 1 &&
2491 "Wrong # arguments to builtin CFStringMakeConstantString");
2492 if (ObjC().CheckObjCString(TheCall->getArg(0)))
2493 return ExprError();
2494 break;
2495 case Builtin::BI__builtin_ms_va_start:
2496 case Builtin::BI__builtin_stdarg_start:
2497 case Builtin::BI__builtin_va_start:
2498 if (BuiltinVAStart(BuiltinID, TheCall))
2499 return ExprError();
2500 break;
2501 case Builtin::BI__va_start: {
2502 switch (Context.getTargetInfo().getTriple().getArch()) {
2503 case llvm::Triple::aarch64:
2504 case llvm::Triple::arm:
2505 case llvm::Triple::thumb:
2506 if (BuiltinVAStartARMMicrosoft(TheCall))
2507 return ExprError();
2508 break;
2509 default:
2510 if (BuiltinVAStart(BuiltinID, TheCall))
2511 return ExprError();
2512 break;
2513 }
2514 break;
2515 }
2516
2517 // The acquire, release, and no fence variants are ARM and AArch64 only.
2518 case Builtin::BI_interlockedbittestandset_acq:
2519 case Builtin::BI_interlockedbittestandset_rel:
2520 case Builtin::BI_interlockedbittestandset_nf:
2521 case Builtin::BI_interlockedbittestandreset_acq:
2522 case Builtin::BI_interlockedbittestandreset_rel:
2523 case Builtin::BI_interlockedbittestandreset_nf:
2525 *this, BuiltinID, TheCall,
2526 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2527 return ExprError();
2528 break;
2529
2530 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2531 case Builtin::BI_bittest64:
2532 case Builtin::BI_bittestandcomplement64:
2533 case Builtin::BI_bittestandreset64:
2534 case Builtin::BI_bittestandset64:
2535 case Builtin::BI_interlockedbittestandreset64:
2536 case Builtin::BI_interlockedbittestandset64:
2538 *this, BuiltinID, TheCall,
2539 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2540 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2541 return ExprError();
2542 break;
2543
2544 case Builtin::BI__builtin_set_flt_rounds:
2546 *this, BuiltinID, TheCall,
2547 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
2548 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2549 return ExprError();
2550 break;
2551
2552 case Builtin::BI__builtin_isgreater:
2553 case Builtin::BI__builtin_isgreaterequal:
2554 case Builtin::BI__builtin_isless:
2555 case Builtin::BI__builtin_islessequal:
2556 case Builtin::BI__builtin_islessgreater:
2557 case Builtin::BI__builtin_isunordered:
2558 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2559 return ExprError();
2560 break;
2561 case Builtin::BI__builtin_fpclassify:
2562 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
2563 return ExprError();
2564 break;
2565 case Builtin::BI__builtin_isfpclass:
2566 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
2567 return ExprError();
2568 break;
2569 case Builtin::BI__builtin_isfinite:
2570 case Builtin::BI__builtin_isinf:
2571 case Builtin::BI__builtin_isinf_sign:
2572 case Builtin::BI__builtin_isnan:
2573 case Builtin::BI__builtin_issignaling:
2574 case Builtin::BI__builtin_isnormal:
2575 case Builtin::BI__builtin_issubnormal:
2576 case Builtin::BI__builtin_iszero:
2577 case Builtin::BI__builtin_signbit:
2578 case Builtin::BI__builtin_signbitf:
2579 case Builtin::BI__builtin_signbitl:
2580 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
2581 return ExprError();
2582 break;
2583 case Builtin::BI__builtin_shufflevector:
2584 return BuiltinShuffleVector(TheCall);
2585 // TheCall will be freed by the smart pointer here, but that's fine, since
2586 // BuiltinShuffleVector guts it, but then doesn't release it.
2587 case Builtin::BI__builtin_prefetch:
2588 if (BuiltinPrefetch(TheCall))
2589 return ExprError();
2590 break;
2591 case Builtin::BI__builtin_alloca_with_align:
2592 case Builtin::BI__builtin_alloca_with_align_uninitialized:
2593 if (BuiltinAllocaWithAlign(TheCall))
2594 return ExprError();
2595 [[fallthrough]];
2596 case Builtin::BI__builtin_alloca:
2597 case Builtin::BI__builtin_alloca_uninitialized:
2598 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
2599 << TheCall->getDirectCallee();
2600 break;
2601 case Builtin::BI__arithmetic_fence:
2602 if (BuiltinArithmeticFence(TheCall))
2603 return ExprError();
2604 break;
2605 case Builtin::BI__assume:
2606 case Builtin::BI__builtin_assume:
2607 if (BuiltinAssume(TheCall))
2608 return ExprError();
2609 break;
2610 case Builtin::BI__builtin_assume_aligned:
2611 if (BuiltinAssumeAligned(TheCall))
2612 return ExprError();
2613 break;
2614 case Builtin::BI__builtin_dynamic_object_size:
2615 case Builtin::BI__builtin_object_size:
2616 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
2617 return ExprError();
2618 break;
2619 case Builtin::BI__builtin_longjmp:
2620 if (BuiltinLongjmp(TheCall))
2621 return ExprError();
2622 break;
2623 case Builtin::BI__builtin_setjmp:
2624 if (BuiltinSetjmp(TheCall))
2625 return ExprError();
2626 break;
2627 case Builtin::BI__builtin_classify_type:
2628 if (checkArgCount(*this, TheCall, 1)) return true;
2629 TheCall->setType(Context.IntTy);
2630 break;
2631 case Builtin::BI__builtin_complex:
2632 if (BuiltinComplex(TheCall))
2633 return ExprError();
2634 break;
2635 case Builtin::BI__builtin_constant_p: {
2636 if (checkArgCount(*this, TheCall, 1)) return true;
2638 if (Arg.isInvalid()) return true;
2639 TheCall->setArg(0, Arg.get());
2640 TheCall->setType(Context.IntTy);
2641 break;
2642 }
2643 case Builtin::BI__builtin_launder:
2644 return BuiltinLaunder(*this, TheCall);
2645 case Builtin::BI__sync_fetch_and_add:
2646 case Builtin::BI__sync_fetch_and_add_1:
2647 case Builtin::BI__sync_fetch_and_add_2:
2648 case Builtin::BI__sync_fetch_and_add_4:
2649 case Builtin::BI__sync_fetch_and_add_8:
2650 case Builtin::BI__sync_fetch_and_add_16:
2651 case Builtin::BI__sync_fetch_and_sub:
2652 case Builtin::BI__sync_fetch_and_sub_1:
2653 case Builtin::BI__sync_fetch_and_sub_2:
2654 case Builtin::BI__sync_fetch_and_sub_4:
2655 case Builtin::BI__sync_fetch_and_sub_8:
2656 case Builtin::BI__sync_fetch_and_sub_16:
2657 case Builtin::BI__sync_fetch_and_or:
2658 case Builtin::BI__sync_fetch_and_or_1:
2659 case Builtin::BI__sync_fetch_and_or_2:
2660 case Builtin::BI__sync_fetch_and_or_4:
2661 case Builtin::BI__sync_fetch_and_or_8:
2662 case Builtin::BI__sync_fetch_and_or_16:
2663 case Builtin::BI__sync_fetch_and_and:
2664 case Builtin::BI__sync_fetch_and_and_1:
2665 case Builtin::BI__sync_fetch_and_and_2:
2666 case Builtin::BI__sync_fetch_and_and_4:
2667 case Builtin::BI__sync_fetch_and_and_8:
2668 case Builtin::BI__sync_fetch_and_and_16:
2669 case Builtin::BI__sync_fetch_and_xor:
2670 case Builtin::BI__sync_fetch_and_xor_1:
2671 case Builtin::BI__sync_fetch_and_xor_2:
2672 case Builtin::BI__sync_fetch_and_xor_4:
2673 case Builtin::BI__sync_fetch_and_xor_8:
2674 case Builtin::BI__sync_fetch_and_xor_16:
2675 case Builtin::BI__sync_fetch_and_nand:
2676 case Builtin::BI__sync_fetch_and_nand_1:
2677 case Builtin::BI__sync_fetch_and_nand_2:
2678 case Builtin::BI__sync_fetch_and_nand_4:
2679 case Builtin::BI__sync_fetch_and_nand_8:
2680 case Builtin::BI__sync_fetch_and_nand_16:
2681 case Builtin::BI__sync_add_and_fetch:
2682 case Builtin::BI__sync_add_and_fetch_1:
2683 case Builtin::BI__sync_add_and_fetch_2:
2684 case Builtin::BI__sync_add_and_fetch_4:
2685 case Builtin::BI__sync_add_and_fetch_8:
2686 case Builtin::BI__sync_add_and_fetch_16:
2687 case Builtin::BI__sync_sub_and_fetch:
2688 case Builtin::BI__sync_sub_and_fetch_1:
2689 case Builtin::BI__sync_sub_and_fetch_2:
2690 case Builtin::BI__sync_sub_and_fetch_4:
2691 case Builtin::BI__sync_sub_and_fetch_8:
2692 case Builtin::BI__sync_sub_and_fetch_16:
2693 case Builtin::BI__sync_and_and_fetch:
2694 case Builtin::BI__sync_and_and_fetch_1:
2695 case Builtin::BI__sync_and_and_fetch_2:
2696 case Builtin::BI__sync_and_and_fetch_4:
2697 case Builtin::BI__sync_and_and_fetch_8:
2698 case Builtin::BI__sync_and_and_fetch_16:
2699 case Builtin::BI__sync_or_and_fetch:
2700 case Builtin::BI__sync_or_and_fetch_1:
2701 case Builtin::BI__sync_or_and_fetch_2:
2702 case Builtin::BI__sync_or_and_fetch_4:
2703 case Builtin::BI__sync_or_and_fetch_8:
2704 case Builtin::BI__sync_or_and_fetch_16:
2705 case Builtin::BI__sync_xor_and_fetch:
2706 case Builtin::BI__sync_xor_and_fetch_1:
2707 case Builtin::BI__sync_xor_and_fetch_2:
2708 case Builtin::BI__sync_xor_and_fetch_4:
2709 case Builtin::BI__sync_xor_and_fetch_8:
2710 case Builtin::BI__sync_xor_and_fetch_16:
2711 case Builtin::BI__sync_nand_and_fetch:
2712 case Builtin::BI__sync_nand_and_fetch_1:
2713 case Builtin::BI__sync_nand_and_fetch_2:
2714 case Builtin::BI__sync_nand_and_fetch_4:
2715 case Builtin::BI__sync_nand_and_fetch_8:
2716 case Builtin::BI__sync_nand_and_fetch_16:
2717 case Builtin::BI__sync_val_compare_and_swap:
2718 case Builtin::BI__sync_val_compare_and_swap_1:
2719 case Builtin::BI__sync_val_compare_and_swap_2:
2720 case Builtin::BI__sync_val_compare_and_swap_4:
2721 case Builtin::BI__sync_val_compare_and_swap_8:
2722 case Builtin::BI__sync_val_compare_and_swap_16:
2723 case Builtin::BI__sync_bool_compare_and_swap:
2724 case Builtin::BI__sync_bool_compare_and_swap_1:
2725 case Builtin::BI__sync_bool_compare_and_swap_2:
2726 case Builtin::BI__sync_bool_compare_and_swap_4:
2727 case Builtin::BI__sync_bool_compare_and_swap_8:
2728 case Builtin::BI__sync_bool_compare_and_swap_16:
2729 case Builtin::BI__sync_lock_test_and_set:
2730 case Builtin::BI__sync_lock_test_and_set_1:
2731 case Builtin::BI__sync_lock_test_and_set_2:
2732 case Builtin::BI__sync_lock_test_and_set_4:
2733 case Builtin::BI__sync_lock_test_and_set_8:
2734 case Builtin::BI__sync_lock_test_and_set_16:
2735 case Builtin::BI__sync_lock_release:
2736 case Builtin::BI__sync_lock_release_1:
2737 case Builtin::BI__sync_lock_release_2:
2738 case Builtin::BI__sync_lock_release_4:
2739 case Builtin::BI__sync_lock_release_8:
2740 case Builtin::BI__sync_lock_release_16:
2741 case Builtin::BI__sync_swap:
2742 case Builtin::BI__sync_swap_1:
2743 case Builtin::BI__sync_swap_2:
2744 case Builtin::BI__sync_swap_4:
2745 case Builtin::BI__sync_swap_8:
2746 case Builtin::BI__sync_swap_16:
2747 return BuiltinAtomicOverloaded(TheCallResult);
2748 case Builtin::BI__sync_synchronize:
2749 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
2750 << TheCall->getCallee()->getSourceRange();
2751 break;
2752 case Builtin::BI__builtin_nontemporal_load:
2753 case Builtin::BI__builtin_nontemporal_store:
2754 return BuiltinNontemporalOverloaded(TheCallResult);
2755 case Builtin::BI__builtin_memcpy_inline: {
2756 clang::Expr *SizeOp = TheCall->getArg(2);
2757 // We warn about copying to or from `nullptr` pointers when `size` is
2758 // greater than 0. When `size` is value dependent we cannot evaluate its
2759 // value so we bail out.
2760 if (SizeOp->isValueDependent())
2761 break;
2762 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
2763 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2764 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
2765 }
2766 break;
2767 }
2768 case Builtin::BI__builtin_memset_inline: {
2769 clang::Expr *SizeOp = TheCall->getArg(2);
2770 // We warn about filling to `nullptr` pointers when `size` is greater than
2771 // 0. When `size` is value dependent we cannot evaluate its value so we bail
2772 // out.
2773 if (SizeOp->isValueDependent())
2774 break;
2775 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
2776 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2777 break;
2778 }
2779#define BUILTIN(ID, TYPE, ATTRS)
2780#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
2781 case Builtin::BI##ID: \
2782 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
2783#include "clang/Basic/Builtins.inc"
2784 case Builtin::BI__annotation:
2785 if (BuiltinMSVCAnnotation(*this, TheCall))
2786 return ExprError();
2787 break;
2788 case Builtin::BI__builtin_annotation:
2789 if (BuiltinAnnotation(*this, TheCall))
2790 return ExprError();
2791 break;
2792 case Builtin::BI__builtin_addressof:
2793 if (BuiltinAddressof(*this, TheCall))
2794 return ExprError();
2795 break;
2796 case Builtin::BI__builtin_function_start:
2797 if (BuiltinFunctionStart(*this, TheCall))
2798 return ExprError();
2799 break;
2800 case Builtin::BI__builtin_is_aligned:
2801 case Builtin::BI__builtin_align_up:
2802 case Builtin::BI__builtin_align_down:
2803 if (BuiltinAlignment(*this, TheCall, BuiltinID))
2804 return ExprError();
2805 break;
2806 case Builtin::BI__builtin_add_overflow:
2807 case Builtin::BI__builtin_sub_overflow:
2808 case Builtin::BI__builtin_mul_overflow:
2809 if (BuiltinOverflow(*this, TheCall, BuiltinID))
2810 return ExprError();
2811 break;
2812 case Builtin::BI__builtin_operator_new:
2813 case Builtin::BI__builtin_operator_delete: {
2814 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
2815 ExprResult Res =
2816 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
2817 if (Res.isInvalid())
2818 CorrectDelayedTyposInExpr(TheCallResult.get());
2819 return Res;
2820 }
2821 case Builtin::BI__builtin_dump_struct:
2822 return BuiltinDumpStruct(*this, TheCall);
2823 case Builtin::BI__builtin_expect_with_probability: {
2824 // We first want to ensure we are called with 3 arguments
2825 if (checkArgCount(*this, TheCall, 3))
2826 return ExprError();
2827 // then check probability is constant float in range [0.0, 1.0]
2828 const Expr *ProbArg = TheCall->getArg(2);
2830 Expr::EvalResult Eval;
2831 Eval.Diag = &Notes;
2832 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2833 !Eval.Val.isFloat()) {
2834 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2835 << ProbArg->getSourceRange();
2836 for (const PartialDiagnosticAt &PDiag : Notes)
2837 Diag(PDiag.first, PDiag.second);
2838 return ExprError();
2839 }
2840 llvm::APFloat Probability = Eval.Val.getFloat();
2841 bool LoseInfo = false;
2842 Probability.convert(llvm::APFloat::IEEEdouble(),
2843 llvm::RoundingMode::Dynamic, &LoseInfo);
2844 if (!(Probability >= llvm::APFloat(0.0) &&
2845 Probability <= llvm::APFloat(1.0))) {
2846 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2847 << ProbArg->getSourceRange();
2848 return ExprError();
2849 }
2850 break;
2851 }
2852 case Builtin::BI__builtin_preserve_access_index:
2853 if (BuiltinPreserveAI(*this, TheCall))
2854 return ExprError();
2855 break;
2856 case Builtin::BI__builtin_call_with_static_chain:
2857 if (BuiltinCallWithStaticChain(*this, TheCall))
2858 return ExprError();
2859 break;
2860 case Builtin::BI__exception_code:
2861 case Builtin::BI_exception_code:
2862 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2863 diag::err_seh___except_block))
2864 return ExprError();
2865 break;
2866 case Builtin::BI__exception_info:
2867 case Builtin::BI_exception_info:
2868 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2869 diag::err_seh___except_filter))
2870 return ExprError();
2871 break;
2872 case Builtin::BI__GetExceptionInfo:
2873 if (checkArgCount(*this, TheCall, 1))
2874 return ExprError();
2875
2877 TheCall->getBeginLoc(),
2879 TheCall))
2880 return ExprError();
2881
2882 TheCall->setType(Context.VoidPtrTy);
2883 break;
2884 case Builtin::BIaddressof:
2885 case Builtin::BI__addressof:
2886 case Builtin::BIforward:
2887 case Builtin::BIforward_like:
2888 case Builtin::BImove:
2889 case Builtin::BImove_if_noexcept:
2890 case Builtin::BIas_const: {
2891 // These are all expected to be of the form
2892 // T &/&&/* f(U &/&&)
2893 // where T and U only differ in qualification.
2894 if (checkArgCount(*this, TheCall, 1))
2895 return ExprError();
2896 QualType Param = FDecl->getParamDecl(0)->getType();
2897 QualType Result = FDecl->getReturnType();
2898 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
2899 BuiltinID == Builtin::BI__addressof;
2900 if (!(Param->isReferenceType() &&
2901 (ReturnsPointer ? Result->isAnyPointerType()
2902 : Result->isReferenceType()) &&
2904 Result->getPointeeType()))) {
2905 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
2906 << FDecl;
2907 return ExprError();
2908 }
2909 break;
2910 }
2911 case Builtin::BI__builtin_ptrauth_strip:
2912 return PointerAuthStrip(*this, TheCall);
2913 case Builtin::BI__builtin_ptrauth_blend_discriminator:
2914 return PointerAuthBlendDiscriminator(*this, TheCall);
2915 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
2916 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign);
2917 case Builtin::BI__builtin_ptrauth_auth:
2918 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth);
2919 case Builtin::BI__builtin_ptrauth_sign_generic_data:
2920 return PointerAuthSignGenericData(*this, TheCall);
2921 case Builtin::BI__builtin_ptrauth_auth_and_resign:
2922 return PointerAuthAuthAndResign(*this, TheCall);
2923 // OpenCL v2.0, s6.13.16 - Pipe functions
2924 case Builtin::BIread_pipe:
2925 case Builtin::BIwrite_pipe:
2926 // Since those two functions are declared with var args, we need a semantic
2927 // check for the argument.
2928 if (BuiltinRWPipe(*this, TheCall))
2929 return ExprError();
2930 break;
2931 case Builtin::BIreserve_read_pipe:
2932 case Builtin::BIreserve_write_pipe:
2933 case Builtin::BIwork_group_reserve_read_pipe:
2934 case Builtin::BIwork_group_reserve_write_pipe:
2935 if (BuiltinReserveRWPipe(*this, TheCall))
2936 return ExprError();
2937 break;
2938 case Builtin::BIsub_group_reserve_read_pipe:
2939 case Builtin::BIsub_group_reserve_write_pipe:
2940 if (checkOpenCLSubgroupExt(*this, TheCall) ||
2941 BuiltinReserveRWPipe(*this, TheCall))
2942 return ExprError();
2943 break;
2944 case Builtin::BIcommit_read_pipe:
2945 case Builtin::BIcommit_write_pipe:
2946 case Builtin::BIwork_group_commit_read_pipe:
2947 case Builtin::BIwork_group_commit_write_pipe:
2948 if (BuiltinCommitRWPipe(*this, TheCall))
2949 return ExprError();
2950 break;
2951 case Builtin::BIsub_group_commit_read_pipe:
2952 case Builtin::BIsub_group_commit_write_pipe:
2953 if (checkOpenCLSubgroupExt(*this, TheCall) ||
2954 BuiltinCommitRWPipe(*this, TheCall))
2955 return ExprError();
2956 break;
2957 case Builtin::BIget_pipe_num_packets:
2958 case Builtin::BIget_pipe_max_packets:
2959 if (BuiltinPipePackets(*this, TheCall))
2960 return ExprError();
2961 break;
2962 case Builtin::BIto_global:
2963 case Builtin::BIto_local:
2964 case Builtin::BIto_private:
2965 if (OpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2966 return ExprError();
2967 break;
2968 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2969 case Builtin::BIenqueue_kernel:
2970 if (OpenCLBuiltinEnqueueKernel(*this, TheCall))
2971 return ExprError();
2972 break;
2973 case Builtin::BIget_kernel_work_group_size:
2974 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2975 if (OpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2976 return ExprError();
2977 break;
2978 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2979 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2980 if (OpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2981 return ExprError();
2982 break;
2983 case Builtin::BI__builtin_os_log_format:
2985 [[fallthrough]];
2986 case Builtin::BI__builtin_os_log_format_buffer_size:
2987 if (BuiltinOSLogFormat(TheCall))
2988 return ExprError();
2989 break;
2990 case Builtin::BI__builtin_frame_address:
2991 case Builtin::BI__builtin_return_address: {
2992 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2993 return ExprError();
2994
2995 // -Wframe-address warning if non-zero passed to builtin
2996 // return/frame address.
2998 if (!TheCall->getArg(0)->isValueDependent() &&
2999 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3000 Result.Val.getInt() != 0)
3001 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3002 << ((BuiltinID == Builtin::BI__builtin_return_address)
3003 ? "__builtin_return_address"
3004 : "__builtin_frame_address")
3005 << TheCall->getSourceRange();
3006 break;
3007 }
3008
3009 case Builtin::BI__builtin_nondeterministic_value: {
3010 if (BuiltinNonDeterministicValue(TheCall))
3011 return ExprError();
3012 break;
3013 }
3014
3015 // __builtin_elementwise_abs restricts the element type to signed integers or
3016 // floating point types only.
3017 case Builtin::BI__builtin_elementwise_abs: {
3018 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
3019 return ExprError();
3020
3021 QualType ArgTy = TheCall->getArg(0)->getType();
3022 QualType EltTy = ArgTy;
3023
3024 if (auto *VecTy = EltTy->getAs<VectorType>())
3025 EltTy = VecTy->getElementType();
3026 if (EltTy->isUnsignedIntegerType()) {
3027 Diag(TheCall->getArg(0)->getBeginLoc(),
3028 diag::err_builtin_invalid_arg_type)
3029 << 1 << /* signed integer or float ty*/ 3 << ArgTy;
3030 return ExprError();
3031 }
3032 break;
3033 }
3034
3035 // These builtins restrict the element type to floating point
3036 // types only.
3037 case Builtin::BI__builtin_elementwise_ceil:
3038 case Builtin::BI__builtin_elementwise_cos:
3039 case Builtin::BI__builtin_elementwise_exp:
3040 case Builtin::BI__builtin_elementwise_exp2:
3041 case Builtin::BI__builtin_elementwise_floor:
3042 case Builtin::BI__builtin_elementwise_log:
3043 case Builtin::BI__builtin_elementwise_log2:
3044 case Builtin::BI__builtin_elementwise_log10:
3045 case Builtin::BI__builtin_elementwise_roundeven:
3046 case Builtin::BI__builtin_elementwise_round:
3047 case Builtin::BI__builtin_elementwise_rint:
3048 case Builtin::BI__builtin_elementwise_nearbyint:
3049 case Builtin::BI__builtin_elementwise_sin:
3050 case Builtin::BI__builtin_elementwise_sqrt:
3051 case Builtin::BI__builtin_elementwise_tan:
3052 case Builtin::BI__builtin_elementwise_trunc:
3053 case Builtin::BI__builtin_elementwise_canonicalize: {
3054 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
3055 return ExprError();
3056
3057 QualType ArgTy = TheCall->getArg(0)->getType();
3058 if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
3059 ArgTy, 1))
3060 return ExprError();
3061 break;
3062 }
3063 case Builtin::BI__builtin_elementwise_fma: {
3064 if (BuiltinElementwiseTernaryMath(TheCall))
3065 return ExprError();
3066 break;
3067 }
3068
3069 // These builtins restrict the element type to floating point
3070 // types only, and take in two arguments.
3071 case Builtin::BI__builtin_elementwise_pow: {
3072 if (BuiltinElementwiseMath(TheCall))
3073 return ExprError();
3074
3075 QualType ArgTy = TheCall->getArg(0)->getType();
3076 if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
3077 ArgTy, 1) ||
3078 checkFPMathBuiltinElementType(*this, TheCall->getArg(1)->getBeginLoc(),
3079 ArgTy, 2))
3080 return ExprError();
3081 break;
3082 }
3083
3084 // These builtins restrict the element type to integer
3085 // types only.
3086 case Builtin::BI__builtin_elementwise_add_sat:
3087 case Builtin::BI__builtin_elementwise_sub_sat: {
3088 if (BuiltinElementwiseMath(TheCall))
3089 return ExprError();
3090
3091 const Expr *Arg = TheCall->getArg(0);
3092 QualType ArgTy = Arg->getType();
3093 QualType EltTy = ArgTy;
3094
3095 if (auto *VecTy = EltTy->getAs<VectorType>())
3096 EltTy = VecTy->getElementType();
3097
3098 if (!EltTy->isIntegerType()) {
3099 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3100 << 1 << /* integer ty */ 6 << ArgTy;
3101 return ExprError();
3102 }
3103 break;
3104 }
3105
3106 case Builtin::BI__builtin_elementwise_min:
3107 case Builtin::BI__builtin_elementwise_max:
3108 if (BuiltinElementwiseMath(TheCall))
3109 return ExprError();
3110 break;
3111
3112 case Builtin::BI__builtin_elementwise_bitreverse: {
3113 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
3114 return ExprError();
3115
3116 const Expr *Arg = TheCall->getArg(0);
3117 QualType ArgTy = Arg->getType();
3118 QualType EltTy = ArgTy;
3119
3120 if (auto *VecTy = EltTy->getAs<VectorType>())
3121 EltTy = VecTy->getElementType();
3122
3123 if (!EltTy->isIntegerType()) {
3124 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3125 << 1 << /* integer ty */ 6 << ArgTy;
3126 return ExprError();
3127 }
3128 break;
3129 }
3130
3131 case Builtin::BI__builtin_elementwise_copysign: {
3132 if (checkArgCount(*this, TheCall, 2))
3133 return ExprError();
3134
3135 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3136 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3137 if (Magnitude.isInvalid() || Sign.isInvalid())
3138 return ExprError();
3139
3140 QualType MagnitudeTy = Magnitude.get()->getType();
3141 QualType SignTy = Sign.get()->getType();
3142 if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
3143 MagnitudeTy, 1) ||
3144 checkFPMathBuiltinElementType(*this, TheCall->getArg(1)->getBeginLoc(),
3145 SignTy, 2)) {
3146 return ExprError();
3147 }
3148
3149 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3150 return Diag(Sign.get()->getBeginLoc(),
3151 diag::err_typecheck_call_different_arg_types)
3152 << MagnitudeTy << SignTy;
3153 }
3154
3155 TheCall->setArg(0, Magnitude.get());
3156 TheCall->setArg(1, Sign.get());
3157 TheCall->setType(Magnitude.get()->getType());
3158 break;
3159 }
3160 case Builtin::BI__builtin_reduce_max:
3161 case Builtin::BI__builtin_reduce_min: {
3162 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3163 return ExprError();
3164
3165 const Expr *Arg = TheCall->getArg(0);
3166 const auto *TyA = Arg->getType()->getAs<VectorType>();
3167
3168 QualType ElTy;
3169 if (TyA)
3170 ElTy = TyA->getElementType();
3171 else if (Arg->getType()->isSizelessVectorType())
3173
3174 if (ElTy.isNull()) {
3175 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3176 << 1 << /* vector ty*/ 4 << Arg->getType();
3177 return ExprError();
3178 }
3179
3180 TheCall->setType(ElTy);
3181 break;
3182 }
3183
3184 // These builtins support vectors of integers only.
3185 // TODO: ADD/MUL should support floating-point types.
3186 case Builtin::BI__builtin_reduce_add:
3187 case Builtin::BI__builtin_reduce_mul:
3188 case Builtin::BI__builtin_reduce_xor:
3189 case Builtin::BI__builtin_reduce_or:
3190 case Builtin::BI__builtin_reduce_and: {
3191 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3192 return ExprError();
3193
3194 const Expr *Arg = TheCall->getArg(0);
3195 const auto *TyA = Arg->getType()->getAs<VectorType>();
3196
3197 QualType ElTy;
3198 if (TyA)
3199 ElTy = TyA->getElementType();
3200 else if (Arg->getType()->isSizelessVectorType())
3202
3203 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3204 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3205 << 1 << /* vector of integers */ 6 << Arg->getType();
3206 return ExprError();
3207 }
3208
3209 TheCall->setType(ElTy);
3210 break;
3211 }
3212
3213 case Builtin::BI__builtin_matrix_transpose:
3214 return BuiltinMatrixTranspose(TheCall, TheCallResult);
3215
3216 case Builtin::BI__builtin_matrix_column_major_load:
3217 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
3218
3219 case Builtin::BI__builtin_matrix_column_major_store:
3220 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
3221
3222 case Builtin::BI__builtin_get_device_side_mangled_name: {
3223 auto Check = [](CallExpr *TheCall) {
3224 if (TheCall->getNumArgs() != 1)
3225 return false;
3226 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
3227 if (!DRE)
3228 return false;
3229 auto *D = DRE->getDecl();
3230 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
3231 return false;
3232 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3233 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3234 };
3235 if (!Check(TheCall)) {
3236 Diag(TheCall->getBeginLoc(),
3237 diag::err_hip_invalid_args_builtin_mangled_name);
3238 return ExprError();
3239 }
3240 break;
3241 }
3242 case Builtin::BI__builtin_popcountg:
3243 if (BuiltinPopcountg(*this, TheCall))
3244 return ExprError();
3245 break;
3246 case Builtin::BI__builtin_clzg:
3247 case Builtin::BI__builtin_ctzg:
3248 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
3249 return ExprError();
3250 break;
3251
3252 case Builtin::BI__builtin_allow_runtime_check: {
3253 Expr *Arg = TheCall->getArg(0);
3254 // Check if the argument is a string literal.
3255 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) {
3256 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3257 << Arg->getSourceRange();
3258 return ExprError();
3259 }
3260 break;
3261 }
3262 }
3263
3264 if (getLangOpts().HLSL && CheckHLSLBuiltinFunctionCall(BuiltinID, TheCall))
3265 return ExprError();
3266
3267 // Since the target specific builtins for each arch overlap, only check those
3268 // of the arch we are compiling for.
3269 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
3270 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
3271 assert(Context.getAuxTargetInfo() &&
3272 "Aux Target Builtin, but not an aux target?");
3273
3274 if (CheckTSBuiltinFunctionCall(
3276 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
3277 return ExprError();
3278 } else {
3279 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
3280 TheCall))
3281 return ExprError();
3282 }
3283 }
3284
3285 return TheCallResult;
3286}
3287
3288// Get the valid immediate range for the specified NEON type code.
3289static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
3291 int IsQuad = ForceQuad ? true : Type.isQuad();
3292 switch (Type.getEltType()) {
3295 return shift ? 7 : (8 << IsQuad) - 1;
3298 return shift ? 15 : (4 << IsQuad) - 1;
3300 return shift ? 31 : (2 << IsQuad) - 1;
3303 return shift ? 63 : (1 << IsQuad) - 1;
3305 return shift ? 127 : (1 << IsQuad) - 1;
3307 assert(!shift && "cannot shift float types!");
3308 return (4 << IsQuad) - 1;
3310 assert(!shift && "cannot shift float types!");
3311 return (2 << IsQuad) - 1;
3313 assert(!shift && "cannot shift float types!");
3314 return (1 << IsQuad) - 1;
3316 assert(!shift && "cannot shift float types!");
3317 return (4 << IsQuad) - 1;
3318 }
3319 llvm_unreachable("Invalid NeonTypeFlag!");
3320}
3321
3322/// getNeonEltType - Return the QualType corresponding to the elements of
3323/// the vector type specified by the NeonTypeFlags. This is used to check
3324/// the pointer arguments for Neon load/store intrinsics.
3326 bool IsPolyUnsigned, bool IsInt64Long) {
3327 switch (Flags.getEltType()) {
3329 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
3331 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
3333 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
3335 if (IsInt64Long)
3336 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
3337 else
3338 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
3339 : Context.LongLongTy;
3341 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
3343 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
3345 if (IsInt64Long)
3346 return Context.UnsignedLongTy;
3347 else
3348 return Context.UnsignedLongLongTy;
3350 break;
3352 return Context.HalfTy;
3354 return Context.FloatTy;
3356 return Context.DoubleTy;
3358 return Context.BFloat16Ty;
3359 }
3360 llvm_unreachable("Invalid NeonTypeFlag!");
3361}
3362
3369
3370enum ArmSMEState : unsigned {
3372
3373 ArmInZA = 0b01,
3374 ArmOutZA = 0b10,
3377
3378 ArmInZT0 = 0b01 << 2,
3379 ArmOutZT0 = 0b10 << 2,
3380 ArmInOutZT0 = 0b11 << 2,
3381 ArmZT0Mask = 0b11 << 2
3383
3384bool Sema::ParseSVEImmChecks(
3385 CallExpr *TheCall, SmallVector<std::tuple<int, int, int>, 3> &ImmChecks) {
3386 // Perform all the immediate checks for this builtin call.
3387 bool HasError = false;
3388 for (auto &I : ImmChecks) {
3389 int ArgNum, CheckTy, ElementSizeInBits;
3390 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
3391
3392 typedef bool (*OptionSetCheckFnTy)(int64_t Value);
3393
3394 // Function that checks whether the operand (ArgNum) is an immediate
3395 // that is one of the predefined values.
3396 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
3397 int ErrDiag) -> bool {
3398 // We can't check the value of a dependent argument.
3399 Expr *Arg = TheCall->getArg(ArgNum);
3400 if (Arg->isTypeDependent() || Arg->isValueDependent())
3401 return false;
3402
3403 // Check constant-ness first.
3404 llvm::APSInt Imm;
3405 if (BuiltinConstantArg(TheCall, ArgNum, Imm))
3406 return true;
3407
3408 if (!CheckImm(Imm.getSExtValue()))
3409 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
3410 return false;
3411 };
3412
3413 switch ((SVETypeFlags::ImmCheckType)CheckTy) {
3414 case SVETypeFlags::ImmCheck0_31:
3415 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
3416 HasError = true;
3417 break;
3418 case SVETypeFlags::ImmCheck0_13:
3419 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
3420 HasError = true;
3421 break;
3422 case SVETypeFlags::ImmCheck1_16:
3423 if (BuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
3424 HasError = true;
3425 break;
3426 case SVETypeFlags::ImmCheck0_7:
3427 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
3428 HasError = true;
3429 break;
3430 case SVETypeFlags::ImmCheck1_1:
3431 if (BuiltinConstantArgRange(TheCall, ArgNum, 1, 1))
3432 HasError = true;
3433 break;
3434 case SVETypeFlags::ImmCheck1_3:
3435 if (BuiltinConstantArgRange(TheCall, ArgNum, 1, 3))
3436 HasError = true;
3437 break;
3438 case SVETypeFlags::ImmCheck1_7:
3439 if (BuiltinConstantArgRange(TheCall, ArgNum, 1, 7))
3440 HasError = true;
3441 break;
3442 case SVETypeFlags::ImmCheckExtract:
3443 if (BuiltinConstantArgRange(TheCall, ArgNum, 0,
3444 (2048 / ElementSizeInBits) - 1))
3445 HasError = true;
3446 break;
3447 case SVETypeFlags::ImmCheckShiftRight:
3448 if (BuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
3449 HasError = true;
3450 break;
3451 case SVETypeFlags::ImmCheckShiftRightNarrow:
3452 if (BuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits / 2))
3453 HasError = true;
3454 break;
3455 case SVETypeFlags::ImmCheckShiftLeft:
3456 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, ElementSizeInBits - 1))
3457 HasError = true;
3458 break;
3459 case SVETypeFlags::ImmCheckLaneIndex:
3460 if (BuiltinConstantArgRange(TheCall, ArgNum, 0,
3461 (128 / (1 * ElementSizeInBits)) - 1))
3462 HasError = true;
3463 break;
3464 case SVETypeFlags::ImmCheckLaneIndexCompRotate:
3465 if (BuiltinConstantArgRange(TheCall, ArgNum, 0,
3466 (128 / (2 * ElementSizeInBits)) - 1))
3467 HasError = true;
3468 break;
3469 case SVETypeFlags::ImmCheckLaneIndexDot:
3470 if (BuiltinConstantArgRange(TheCall, ArgNum, 0,
3471 (128 / (4 * ElementSizeInBits)) - 1))
3472 HasError = true;
3473 break;
3474 case SVETypeFlags::ImmCheckComplexRot90_270:
3475 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
3476 diag::err_rotation_argument_to_cadd))
3477 HasError = true;
3478 break;
3479 case SVETypeFlags::ImmCheckComplexRotAll90:
3480 if (CheckImmediateInSet(
3481 [](int64_t V) {
3482 return V == 0 || V == 90 || V == 180 || V == 270;
3483 },
3484 diag::err_rotation_argument_to_cmla))
3485 HasError = true;
3486 break;
3487 case SVETypeFlags::ImmCheck0_1:
3488 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
3489 HasError = true;
3490 break;
3491 case SVETypeFlags::ImmCheck0_2:
3492 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
3493 HasError = true;
3494 break;
3495 case SVETypeFlags::ImmCheck0_3:
3496 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
3497 HasError = true;
3498 break;
3499 case SVETypeFlags::ImmCheck0_0:
3500 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 0))
3501 HasError = true;
3502 break;
3503 case SVETypeFlags::ImmCheck0_15:
3504 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 15))
3505 HasError = true;
3506 break;
3507 case SVETypeFlags::ImmCheck0_255:
3508 if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 255))
3509 HasError = true;
3510 break;
3511 case SVETypeFlags::ImmCheck2_4_Mul2:
3512 if (BuiltinConstantArgRange(TheCall, ArgNum, 2, 4) ||
3513 BuiltinConstantArgMultiple(TheCall, ArgNum, 2))
3514 HasError = true;
3515 break;
3516 }
3517 }
3518
3519 return HasError;
3520}
3521
3523 if (FD->hasAttr<ArmLocallyStreamingAttr>())
3524 return ArmStreaming;
3525 if (const Type *Ty = FD->getType().getTypePtrOrNull()) {
3526 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
3527 if (FPT->getAArch64SMEAttributes() &
3529 return ArmStreaming;
3530 if (FPT->getAArch64SMEAttributes() &
3533 }
3534 }
3535 return ArmNonStreaming;
3536}
3537
3538static void checkArmStreamingBuiltin(Sema &S, CallExpr *TheCall,
3539 const FunctionDecl *FD,
3543 // Check intrinsics that are available in [sve2p1 or sme/sme2].
3544 llvm::StringMap<bool> CallerFeatureMap;
3545 S.Context.getFunctionFeatureMap(CallerFeatureMap, FD);
3546 if (Builtin::evaluateRequiredTargetFeatures("sve2p1", CallerFeatureMap))
3548 else
3550 }
3551
3552 if (FnType == ArmStreaming && BuiltinType == ArmNonStreaming) {
3553 S.Diag(TheCall->getBeginLoc(), diag::warn_attribute_arm_sm_incompat_builtin)
3554 << TheCall->getSourceRange() << "streaming";
3555 }
3556
3557 if (FnType == ArmStreamingCompatible &&
3559 S.Diag(TheCall->getBeginLoc(), diag::warn_attribute_arm_sm_incompat_builtin)
3560 << TheCall->getSourceRange() << "streaming compatible";
3561 return;
3562 }
3563
3564 if (FnType == ArmNonStreaming && BuiltinType == ArmStreaming) {
3565 S.Diag(TheCall->getBeginLoc(), diag::warn_attribute_arm_sm_incompat_builtin)
3566 << TheCall->getSourceRange() << "non-streaming";
3567 }
3568}
3569
3570static bool hasArmZAState(const FunctionDecl *FD) {
3571 const auto *T = FD->getType()->getAs<FunctionProtoType>();
3574 (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZA());
3575}
3576
3577static bool hasArmZT0State(const FunctionDecl *FD) {
3578 const auto *T = FD->getType()->getAs<FunctionProtoType>();
3581 (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZT0());
3582}
3583
3584static ArmSMEState getSMEState(unsigned BuiltinID) {
3585 switch (BuiltinID) {
3586 default:
3587 return ArmNoState;
3588#define GET_SME_BUILTIN_GET_STATE
3589#include "clang/Basic/arm_sme_builtins_za_state.inc"
3590#undef GET_SME_BUILTIN_GET_STATE
3591 }
3592}
3593
3594bool Sema::CheckSMEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3595 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3596 std::optional<ArmStreamingType> BuiltinType;
3597
3598 switch (BuiltinID) {
3599#define GET_SME_STREAMING_ATTRS
3600#include "clang/Basic/arm_sme_streaming_attrs.inc"
3601#undef GET_SME_STREAMING_ATTRS
3602 }
3603
3604 if (BuiltinType)
3605 checkArmStreamingBuiltin(*this, TheCall, FD, *BuiltinType);
3606
3607 if ((getSMEState(BuiltinID) & ArmZAMask) && !hasArmZAState(FD))
3608 Diag(TheCall->getBeginLoc(),
3609 diag::warn_attribute_arm_za_builtin_no_za_state)
3610 << TheCall->getSourceRange();
3611
3612 if ((getSMEState(BuiltinID) & ArmZT0Mask) && !hasArmZT0State(FD))
3613 Diag(TheCall->getBeginLoc(),
3614 diag::warn_attribute_arm_zt0_builtin_no_zt0_state)
3615 << TheCall->getSourceRange();
3616 }
3617
3618 // Range check SME intrinsics that take immediate values.
3620
3621 switch (BuiltinID) {
3622 default:
3623 return false;
3624#define GET_SME_IMMEDIATE_CHECK
3625#include "clang/Basic/arm_sme_sema_rangechecks.inc"
3626#undef GET_SME_IMMEDIATE_CHECK
3627 }
3628
3629 return ParseSVEImmChecks(TheCall, ImmChecks);
3630}
3631
3632bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3633 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3634 std::optional<ArmStreamingType> BuiltinType;
3635
3636 switch (BuiltinID) {
3637#define GET_SVE_STREAMING_ATTRS
3638#include "clang/Basic/arm_sve_streaming_attrs.inc"
3639#undef GET_SVE_STREAMING_ATTRS
3640 }
3641 if (BuiltinType)
3642 checkArmStreamingBuiltin(*this, TheCall, FD, *BuiltinType);
3643 }
3644 // Range check SVE intrinsics that take immediate values.
3646
3647 switch (BuiltinID) {
3648 default:
3649 return false;
3650#define GET_SVE_IMMEDIATE_CHECK
3651#include "clang/Basic/arm_sve_sema_rangechecks.inc"
3652#undef GET_SVE_IMMEDIATE_CHECK
3653 }
3654
3655 return ParseSVEImmChecks(TheCall, ImmChecks);
3656}
3657
3658bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
3659 unsigned BuiltinID, CallExpr *TheCall) {
3660 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3661
3662 switch (BuiltinID) {
3663 default:
3664 break;
3665#define GET_NEON_BUILTINS
3666#define TARGET_BUILTIN(id, ...) case NEON::BI##id:
3667#define BUILTIN(id, ...) case NEON::BI##id:
3668#include "clang/Basic/arm_neon.inc"
3669 checkArmStreamingBuiltin(*this, TheCall, FD, ArmNonStreaming);
3670 break;
3671#undef TARGET_BUILTIN
3672#undef BUILTIN
3673#undef GET_NEON_BUILTINS
3674 }
3675 }
3676
3677 llvm::APSInt Result;
3678 uint64_t mask = 0;
3679 unsigned TV = 0;
3680 int PtrArgNum = -1;
3681 bool HasConstPtr = false;
3682 switch (BuiltinID) {
3683#define GET_NEON_OVERLOAD_CHECK
3684#include "clang/Basic/arm_neon.inc"
3685#include "clang/Basic/arm_fp16.inc"
3686#undef GET_NEON_OVERLOAD_CHECK
3687 }
3688
3689 // For NEON intrinsics which are overloaded on vector element type, validate
3690 // the immediate which specifies which variant to emit.
3691 unsigned ImmArg = TheCall->getNumArgs()-1;
3692 if (mask) {
3693 if (BuiltinConstantArg(TheCall, ImmArg, Result))
3694 return true;
3695
3696 TV = Result.getLimitedValue(64);
3697 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
3698 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
3699 << TheCall->getArg(ImmArg)->getSourceRange();
3700 }
3701
3702 if (PtrArgNum >= 0) {
3703 // Check that pointer arguments have the specified type.
3704 Expr *Arg = TheCall->getArg(PtrArgNum);
3705 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
3706 Arg = ICE->getSubExpr();
3708 QualType RHSTy = RHS.get()->getType();
3709
3710 llvm::Triple::ArchType Arch = TI.getTriple().getArch();
3711 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
3712 Arch == llvm::Triple::aarch64_32 ||
3713 Arch == llvm::Triple::aarch64_be;
3714 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
3715 QualType EltTy =
3716 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
3717 if (HasConstPtr)
3718 EltTy = EltTy.withConst();
3719 QualType LHSTy = Context.getPointerType(EltTy);
3720 AssignConvertType ConvTy;
3721 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
3722 if (RHS.isInvalid())
3723 return true;
3724 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
3725 RHS.get(), AA_Assigning))
3726 return true;
3727 }
3728
3729 // For NEON intrinsics which take an immediate value as part of the
3730 // instruction, range check them here.
3731 unsigned i = 0, l = 0, u = 0;
3732 switch (BuiltinID) {
3733 default:
3734 return false;
3735 #define GET_NEON_IMMEDIATE_CHECK
3736 #include "clang/Basic/arm_neon.inc"
3737 #include "clang/Basic/arm_fp16.inc"
3738 #undef GET_NEON_IMMEDIATE_CHECK
3739 }
3740
3741 return BuiltinConstantArgRange(TheCall, i, l, u + l);
3742}
3743
3744bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3745 switch (BuiltinID) {
3746 default:
3747 return false;
3748 #include "clang/Basic/arm_mve_builtin_sema.inc"
3749 }
3750}
3751
3752bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3753 CallExpr *TheCall) {
3754 bool Err = false;
3755 switch (BuiltinID) {
3756 default:
3757 return false;
3758#include "clang/Basic/arm_cde_builtin_sema.inc"
3759 }
3760
3761 if (Err)
3762 return true;
3763
3764 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
3765}
3766
3767bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
3768 const Expr *CoprocArg, bool WantCDE) {
3770 return false;
3771
3772 // We can't check the value of a dependent argument.
3773 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
3774 return false;
3775
3776 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
3777 int64_t CoprocNo = CoprocNoAP.getExtValue();
3778 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
3779
3780 uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
3781 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
3782
3783 if (IsCDECoproc != WantCDE)
3784 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
3785 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
3786
3787 return false;
3788}
3789
3790bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
3791 unsigned MaxWidth) {
3792 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
3793 BuiltinID == ARM::BI__builtin_arm_ldaex ||
3794 BuiltinID == ARM::BI__builtin_arm_strex ||
3795 BuiltinID == ARM::BI__builtin_arm_stlex ||
3796 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
3797 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
3798 BuiltinID == AArch64::BI__builtin_arm_strex ||
3799 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
3800 "unexpected ARM builtin");
3801 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
3802 BuiltinID == ARM::BI__builtin_arm_ldaex ||
3803 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
3804 BuiltinID == AArch64::BI__builtin_arm_ldaex;
3805
3806 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3807
3808 // Ensure that we have the proper number of arguments.
3809 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
3810 return true;
3811
3812 // Inspect the pointer argument of the atomic builtin. This should always be
3813 // a pointer type, whose element is an integral scalar or pointer type.
3814 // Because it is a pointer type, we don't have to worry about any implicit
3815 // casts here.
3816 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
3817 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
3818 if (PointerArgRes.isInvalid())
3819 return true;
3820 PointerArg = PointerArgRes.get();
3821
3822 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3823 if (!pointerType) {
3824 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
3825 << PointerArg->getType() << PointerArg->getSourceRange();
3826 return true;
3827 }
3828
3829 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
3830 // task is to insert the appropriate casts into the AST. First work out just
3831 // what the appropriate type is.
3832 QualType ValType = pointerType->getPointeeType();
3833 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
3834 if (IsLdrex)
3835 AddrType.addConst();
3836
3837 // Issue a warning if the cast is dodgy.
3838 CastKind CastNeeded = CK_NoOp;
3839 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
3840 CastNeeded = CK_BitCast;
3841 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
3842 << PointerArg->getType() << Context.getPointerType(AddrType)
3843 << AA_Passing << PointerArg->getSourceRange();
3844 }
3845
3846 // Finally, do the cast and replace the argument with the corrected version.
3847 AddrType = Context.getPointerType(AddrType);
3848 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
3849 if (PointerArgRes.isInvalid())
3850 return true;
3851 PointerArg = PointerArgRes.get();
3852
3853 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
3854
3855 // In general, we allow ints, floats and pointers to be loaded and stored.
3856 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3857 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
3858 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
3859 << PointerArg->getType() << PointerArg->getSourceRange();
3860 return true;
3861 }
3862
3863 // But ARM doesn't have instructions to deal with 128-bit versions.
3864 if (Context.getTypeSize(ValType) > MaxWidth) {
3865 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
3866 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
3867 << PointerArg->getType() << PointerArg->getSourceRange();
3868 return true;
3869 }
3870
3871 switch (ValType.getObjCLifetime()) {
3874 // okay
3875 break;
3876
3880 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
3881 << ValType << PointerArg->getSourceRange();
3882 return true;
3883 }
3884
3885 if (IsLdrex) {
3886 TheCall->setType(ValType);
3887 return false;
3888 }
3889
3890 // Initialize the argument to be stored.
3891 ExprResult ValArg = TheCall->getArg(0);
3893 Context, ValType, /*consume*/ false);
3894 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3895 if (ValArg.isInvalid())
3896 return true;
3897 TheCall->setArg(0, ValArg.get());
3898
3899 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
3900 // but the custom checker bypasses all default analysis.
3901 TheCall->setType(Context.IntTy);
3902 return false;
3903}
3904
3905bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3906 CallExpr *TheCall) {
3907 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
3908 BuiltinID == ARM::BI__builtin_arm_ldaex ||
3909 BuiltinID == ARM::BI__builtin_arm_strex ||
3910 BuiltinID == ARM::BI__builtin_arm_stlex) {
3911 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
3912 }
3913
3914 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
3915 return BuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3916 BuiltinConstantArgRange(TheCall, 2, 0, 1);
3917 }
3918
3919 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3920 BuiltinID == ARM::BI__builtin_arm_wsr64)
3921 return BuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
3922
3923 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
3924 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3925 BuiltinID == ARM::BI__builtin_arm_wsr ||
3926 BuiltinID == ARM::BI__builtin_arm_wsrp)
3927 return BuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
3928
3929 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
3930 return true;
3931 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
3932 return true;
3933 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
3934 return true;
3935
3936 // For intrinsics which take an immediate value as part of the instruction,
3937 // range check them here.
3938 // FIXME: VFP Intrinsics should error if VFP not present.
3939 switch (BuiltinID) {
3940 default: return false;
3941 case ARM::BI__builtin_arm_ssat:
3942 return BuiltinConstantArgRange(TheCall, 1, 1, 32);
3943 case ARM::BI__builtin_arm_usat:
3944 return BuiltinConstantArgRange(TheCall, 1, 0, 31);
3945 case ARM::BI__builtin_arm_ssat16:
3946 return BuiltinConstantArgRange(TheCall, 1, 1, 16);
3947 case ARM::BI__builtin_arm_usat16:
3948 return BuiltinConstantArgRange(TheCall, 1, 0, 15);
3949 case ARM::BI__builtin_arm_vcvtr_f:
3950 case ARM::BI__builtin_arm_vcvtr_d:
3951 return BuiltinConstantArgRange(TheCall, 1, 0, 1);
3952 case ARM::BI__builtin_arm_dmb:
3953 case ARM::BI__builtin_arm_dsb:
3954 case ARM::BI__builtin_arm_isb:
3955 case ARM::BI__builtin_arm_dbg:
3956 return BuiltinConstantArgRange(TheCall, 0, 0, 15);
3957 case ARM::BI__builtin_arm_cdp:
3958 case ARM::BI__builtin_arm_cdp2:
3959 case ARM::BI__builtin_arm_mcr:
3960 case ARM::BI__builtin_arm_mcr2:
3961 case ARM::BI__builtin_arm_mrc:
3962 case ARM::BI__builtin_arm_mrc2:
3963 case ARM::BI__builtin_arm_mcrr:
3964 case ARM::BI__builtin_arm_mcrr2:
3965 case ARM::BI__builtin_arm_mrrc:
3966 case ARM::BI__builtin_arm_mrrc2:
3967 case ARM::BI__builtin_arm_ldc:
3968 case ARM::BI__builtin_arm_ldcl:
3969 case ARM::BI__builtin_arm_ldc2:
3970 case ARM::BI__builtin_arm_ldc2l:
3971 case ARM::BI__builtin_arm_stc:
3972 case ARM::BI__builtin_arm_stcl:
3973 case ARM::BI__builtin_arm_stc2:
3974 case ARM::BI__builtin_arm_stc2l:
3975 return BuiltinConstantArgRange(TheCall, 0, 0, 15) ||
3976 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
3977 /*WantCDE*/ false);
3978 }
3979}
3980
3981bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
3982 unsigned BuiltinID,
3983 CallExpr *TheCall) {
3984 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
3985 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
3986 BuiltinID == AArch64::BI__builtin_arm_strex ||
3987 BuiltinID == AArch64::BI__builtin_arm_stlex) {
3988 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
3989 }
3990
3991 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
3992 return BuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3993 BuiltinConstantArgRange(TheCall, 2, 0, 3) ||
3994 BuiltinConstantArgRange(TheCall, 3, 0, 1) ||
3995 BuiltinConstantArgRange(TheCall, 4, 0, 1);
3996 }
3997
3998 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3999 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4000 BuiltinID == AArch64::BI__builtin_arm_rsr128 ||
4001 BuiltinID == AArch64::BI__builtin_arm_wsr128)
4002 return BuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
4003
4004 // Memory Tagging Extensions (MTE) Intrinsics
4005 if (BuiltinID == AArch64::BI__builtin_arm_irg ||
4006 BuiltinID == AArch64::BI__builtin_arm_addg ||
4007 BuiltinID == AArch64::BI__builtin_arm_gmi ||
4008 BuiltinID == AArch64::BI__builtin_arm_ldg ||
4009 BuiltinID == AArch64::BI__builtin_arm_stg ||
4010 BuiltinID == AArch64::BI__builtin_arm_subp) {
4011 return BuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
4012 }
4013
4014 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
4015 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4016 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4017 BuiltinID == AArch64::BI__builtin_arm_wsrp)
4018 return BuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
4019
4020 // Only check the valid encoding range. Any constant in this range would be
4021 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
4022 // an exception for incorrect registers. This matches MSVC behavior.
4023 if (BuiltinID == AArch64::BI_ReadStatusReg ||
4024 BuiltinID == AArch64::BI_WriteStatusReg)
4025 return BuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
4026
4027 if (BuiltinID == AArch64::BI__getReg)
4028 return BuiltinConstantArgRange(TheCall, 0, 0, 31);
4029
4030 if (BuiltinID == AArch64::BI__break)
4031 return BuiltinConstantArgRange(TheCall, 0, 0, 0xffff);
4032
4033 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
4034 return true;
4035
4036 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
4037 return true;
4038
4039 if (CheckSMEBuiltinFunctionCall(BuiltinID, TheCall))
4040 return true;
4041
4042 // For intrinsics which take an immediate value as part of the instruction,
4043 // range check them here.
4044 unsigned i = 0, l = 0, u = 0;
4045 switch (BuiltinID) {
4046 default: return false;
4047 case AArch64::BI__builtin_arm_dmb:
4048 case AArch64::BI__builtin_arm_dsb:
4049 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
4050 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
4051 }
4052
4053 return BuiltinConstantArgRange(TheCall, i, l, u + l);
4054}
4055
4057 if (Arg->getType()->getAsPlaceholderType())
4058 return false;
4059
4060 // The first argument needs to be a record field access.
4061 // If it is an array element access, we delay decision
4062 // to BPF backend to check whether the access is a
4063 // field access or not.
4064 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
4065 isa<MemberExpr>(Arg->IgnoreParens()) ||
4066 isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
4067}
4068
4070 QualType ArgType = Arg->getType();
4071 if (ArgType->getAsPlaceholderType())
4072 return false;
4073
4074 // for TYPE_EXISTENCE/TYPE_MATCH/TYPE_SIZEOF reloc type
4075 // format:
4076 // 1. __builtin_preserve_type_info(*(<type> *)0, flag);
4077 // 2. <type> var;
4078 // __builtin_preserve_type_info(var, flag);
4079 if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
4080 !isa<UnaryOperator>(Arg->IgnoreParens()))
4081 return false;
4082
4083 // Typedef type.
4084 if (ArgType->getAs<TypedefType>())
4085 return true;
4086
4087 // Record type or Enum type.
4088 const Type *Ty = ArgType->getUnqualifiedDesugaredType();
4089 if (const auto *RT = Ty->getAs<RecordType>()) {
4090 if (!RT->getDecl()->getDeclName().isEmpty())
4091 return true;
4092 } else if (const auto *ET = Ty->getAs<EnumType>()) {
4093 if (!ET->getDecl()->getDeclName().isEmpty())
4094 return true;
4095 }
4096
4097 return false;
4098}
4099
4101 QualType ArgType = Arg->getType();
4102 if (ArgType->getAsPlaceholderType())
4103 return false;
4104
4105 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
4106 // format:
4107 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
4108 // flag);
4109 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
4110 if (!UO)
4111 return false;
4112
4113 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
4114 if (!CE)
4115 return false;
4116 if (CE->getCastKind() != CK_IntegralToPointer &&
4117 CE->getCastKind() != CK_NullToPointer)
4118 return false;
4119
4120 // The integer must be from an EnumConstantDecl.
4121 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
4122 if (!DR)
4123 return false;
4124
4125 const EnumConstantDecl *Enumerator =
4126 dyn_cast<EnumConstantDecl>(DR->getDecl());
4127 if (!Enumerator)
4128 return false;
4129
4130 // The type must be EnumType.
4131 const Type *Ty = ArgType->getUnqualifiedDesugaredType();
4132 const auto *ET = Ty->getAs<EnumType>();
4133 if (!ET)
4134 return false;
4135
4136 // The enum value must be supported.
4137 return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
4138}
4139
4140bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
4141 CallExpr *TheCall) {
4142 assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
4143 BuiltinID == BPF::BI__builtin_btf_type_id ||
4144 BuiltinID == BPF::BI__builtin_preserve_type_info ||
4145 BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
4146 "unexpected BPF builtin");
4147
4148 if (checkArgCount(*this, TheCall, 2))
4149 return true;
4150
4151 // The second argument needs to be a constant int
4152 Expr *Arg = TheCall->getArg(1);
4153 std::optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
4155 if (!Value) {
4156 if (BuiltinID == BPF::BI__builtin_preserve_field_info)
4157 kind = diag::err_preserve_field_info_not_const;
4158 else if (BuiltinID == BPF::BI__builtin_btf_type_id)
4159 kind = diag::err_btf_type_id_not_const;
4160 else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
4161 kind = diag::err_preserve_type_info_not_const;
4162 else
4163 kind = diag::err_preserve_enum_value_not_const;
4164 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
4165 return true;
4166 }
4167
4168 // The first argument
4169 Arg = TheCall->getArg(0);
4170 bool InvalidArg = false;
4171 bool ReturnUnsignedInt = true;
4172 if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
4174 InvalidArg = true;
4175 kind = diag::err_preserve_field_info_not_field;
4176 }
4177 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
4179 InvalidArg = true;
4180 kind = diag::err_preserve_type_info_invalid;
4181 }
4182 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
4184 InvalidArg = true;
4185 kind = diag::err_preserve_enum_value_invalid;
4186 }
4187 ReturnUnsignedInt = false;
4188 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
4189 ReturnUnsignedInt = false;
4190 }
4191
4192 if (InvalidArg) {
4193 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
4194 return true;
4195 }
4196
4197 if (ReturnUnsignedInt)
4198 TheCall->setType(Context.UnsignedIntTy);
4199 else
4200 TheCall->setType(Context.UnsignedLongTy);
4201 return false;
4202}
4203
4204bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
4205 struct ArgInfo {
4206 uint8_t OpNum;
4207 bool IsSigned;
4208 uint8_t BitWidth;
4209 uint8_t Align;
4210 };
4211 struct BuiltinInfo {
4212 unsigned BuiltinID;
4213 ArgInfo Infos[2];
4214 };
4215
4216 static BuiltinInfo Infos[] = {
4217 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
4218 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
4219 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
4220 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} },
4221 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
4222 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
4223 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
4224 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
4225 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
4226 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
4227 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
4228
4229 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
4230 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
4231 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
4232 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
4233 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
4234 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
4235 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
4236 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
4237 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
4238 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
4239 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
4240
4241 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
4242 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
4243 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
4244 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
4245 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
4246 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
4247 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
4248 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
4249 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
4250 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
4251 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
4252 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
4253 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
4254 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
4255 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
4256 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
4257 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
4258 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
4259 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
4260 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
4261 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
4262 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
4263 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
4264 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
4265 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
4266 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
4267 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
4268 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
4269 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
4270 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
4271 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
4272 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
4273 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
4274 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
4275 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
4276 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
4277 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
4278 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
4279 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
4280 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
4281 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
4282 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
4283 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
4284 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
4285 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
4286 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
4287 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
4288 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
4289 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
4290 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
4291 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
4292 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
4293 {{ 1, false, 6, 0 }} },
4294 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
4295 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
4296 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
4297 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
4298 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
4299 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
4300 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
4301 {{ 1, false, 5, 0 }} },
4302 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
4303 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
4304 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
4305 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
4306 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
4307 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
4308 { 2, false, 5, 0 }} },
4309 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
4310 { 2, false, 6, 0 }} },
4311 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
4312 { 3, false, 5, 0 }} },
4313 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
4314 { 3, false, 6, 0 }} },
4315 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
4316 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
4317 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
4318 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
4319 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
4320 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
4321 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
4322 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
4323 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
4324 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
4325 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
4326 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
4327 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
4328 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
4329 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
4330 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
4331 {{ 2, false, 4, 0 },
4332 { 3, false, 5, 0 }} },
4333 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
4334 {{ 2, false, 4, 0 },
4335 { 3, false, 5, 0 }} },
4336 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
4337 {{ 2, false, 4, 0 },
4338 { 3, false, 5, 0 }} },
4339 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
4340 {{ 2, false, 4, 0 },
4341 { 3, false, 5, 0 }} },
4342 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
4343 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
4344 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
4345 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
4346 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
4347 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
4348 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
4349 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
4350 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
4351 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
4352 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
4353 { 2, false, 5, 0 }} },
4354 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
4355 { 2, false, 6, 0 }} },
4356 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
4357 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
4358 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
4359 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
4360 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
4361 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
4362 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
4363 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
4364 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
4365 {{ 1, false, 4, 0 }} },
4366 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
4367 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
4368 {{ 1, false, 4, 0 }} },
4369 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
4370 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
4371 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
4372 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
4373 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
4374 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
4375 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
4376 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
4377 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
4378 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
4379 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
4380 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
4381 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
4382 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
4383 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
4384 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
4385 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
4386 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
4387 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
4388 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
4389 {{ 3, false, 1, 0 }} },
4390 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
4391 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
4392 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
4393 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
4394 {{ 3, false, 1, 0 }} },
4395 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
4396 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
4397 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
4398 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
4399 {{ 3, false, 1, 0 }} },
4400
4401 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10, {{ 2, false, 2, 0 }} },
4402 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10_128B,
4403 {{ 2, false, 2, 0 }} },
4404 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10_vxx,
4405 {{ 3, false, 2, 0 }} },
4406 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10_vxx_128B,
4407 {{ 3, false, 2, 0 }} },
4408 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10, {{ 2, false, 2, 0 }} },
4409 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10_128B,
4410 {{ 2, false, 2, 0 }} },
4411 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10_vxx,
4412 {{ 3, false, 2, 0 }} },
4413 { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10_vxx_128B,
4414 {{ 3, false, 2, 0 }} },
4415 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, {{ 2, false, 3, 0 }} },
4416 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, {{ 2, false, 3, 0 }} },
4417 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, {{ 3, false, 3, 0 }} },
4418 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B,
4419 {{ 3, false, 3, 0 }} },
4420 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, {{ 2, false, 3, 0 }} },
4421 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, {{ 2, false, 3, 0 }} },
4422 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, {{ 3, false, 3, 0 }} },
4423 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B,
4424 {{ 3, false, 3, 0 }} },
4425 };
4426
4427 // Use a dynamically initialized static to sort the table exactly once on
4428 // first run.
4429 static const bool SortOnce =
4430 (llvm::sort(Infos,
4431 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
4432 return LHS.BuiltinID < RHS.BuiltinID;
4433 }),
4434 true);
4435 (void)SortOnce;
4436
4437 const BuiltinInfo *F = llvm::partition_point(
4438 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
4439 if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
4440 return false;
4441
4442 bool Error = false;
4443
4444 for (const ArgInfo &A : F->Infos) {
4445 // Ignore empty ArgInfo elements.
4446 if (A.BitWidth == 0)
4447 continue;
4448
4449 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
4450 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
4451 if (!A.Align) {
4452 Error |= BuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
4453 } else {
4454 unsigned M = 1 << A.Align;
4455 Min *= M;
4456 Max *= M;
4457 Error |= BuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
4458 Error |= BuiltinConstantArgMultiple(TheCall, A.OpNum, M);
4459 }
4460 }
4461 return Error;
4462}
4463
4464bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
4465 CallExpr *TheCall) {
4466 return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
4467}
4468
4469bool Sema::CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI,
4470 unsigned BuiltinID,
4471 CallExpr *TheCall) {
4472 switch (BuiltinID) {
4473 default:
4474 break;
4475 // Basic intrinsics.
4476 case LoongArch::BI__builtin_loongarch_cacop_d:
4477 case LoongArch::BI__builtin_loongarch_cacop_w: {
4478 BuiltinConstantArgRange(TheCall, 0, 0, llvm::maxUIntN(5));
4479 BuiltinConstantArgRange(TheCall, 2, llvm::minIntN(12), llvm::maxIntN(12));
4480 break;
4481 }
4482 case LoongArch::BI__builtin_loongarch_break:
4483 case LoongArch::BI__builtin_loongarch_dbar:
4484 case LoongArch::BI__builtin_loongarch_ibar:
4485 case LoongArch::BI__builtin_loongarch_syscall:
4486 // Check if immediate is in [0, 32767].
4487 return BuiltinConstantArgRange(TheCall, 0, 0, 32767);
4488 case LoongArch::BI__builtin_loongarch_csrrd_w:
4489 case LoongArch::BI__builtin_loongarch_csrrd_d:
4490 return BuiltinConstantArgRange(TheCall, 0, 0, 16383);
4491 case LoongArch::BI__builtin_loongarch_csrwr_w:
4492 case LoongArch::BI__builtin_loongarch_csrwr_d:
4493 return BuiltinConstantArgRange(TheCall, 1, 0, 16383);
4494 case LoongArch::BI__builtin_loongarch_csrxchg_w:
4495 case LoongArch::BI__builtin_loongarch_csrxchg_d:
4496 return BuiltinConstantArgRange(TheCall, 2, 0, 16383);
4497 case LoongArch::BI__builtin_loongarch_lddir_d:
4498 case LoongArch::BI__builtin_loongarch_ldpte_d:
4499 return BuiltinConstantArgRange(TheCall, 1, 0, 31);
4500 case LoongArch::BI__builtin_loongarch_movfcsr2gr:
4501 case LoongArch::BI__builtin_loongarch_movgr2fcsr:
4502 return BuiltinConstantArgRange(TheCall, 0, 0, llvm::maxUIntN(2));
4503
4504 // LSX intrinsics.
4505 case LoongArch::BI__builtin_lsx_vbitclri_b:
4506 case LoongArch::BI__builtin_lsx_vbitrevi_b:
4507 case LoongArch::BI__builtin_lsx_vbitseti_b:
4508 case LoongArch::BI__builtin_lsx_vsat_b:
4509 case LoongArch::BI__builtin_lsx_vsat_bu:
4510 case LoongArch::BI__builtin_lsx_vslli_b:
4511 case LoongArch::BI__builtin_lsx_vsrai_b:
4512 case LoongArch::BI__builtin_lsx_vsrari_b:
4513 case LoongArch::BI__builtin_lsx_vsrli_b:
4514 case LoongArch::BI__builtin_lsx_vsllwil_h_b:
4515 case LoongArch::BI__builtin_lsx_vsllwil_hu_bu:
4516 case LoongArch::BI__builtin_lsx_vrotri_b:
4517 case LoongArch::BI__builtin_lsx_vsrlri_b:
4518 return BuiltinConstantArgRange(TheCall, 1, 0, 7);
4519 case LoongArch::BI__builtin_lsx_vbitclri_h:
4520 case LoongArch::BI__builtin_lsx_vbitrevi_h:
4521 case LoongArch::BI__builtin_lsx_vbitseti_h:
4522 case LoongArch::BI__builtin_lsx_vsat_h:
4523 case LoongArch::BI__builtin_lsx_vsat_hu:
4524 case LoongArch::BI__builtin_lsx_vslli_h:
4525 case LoongArch::BI__builtin_lsx_vsrai_h:
4526 case LoongArch::BI__builtin_lsx_vsrari_h:
4527 case LoongArch::BI__builtin_lsx_vsrli_h:
4528 case LoongArch::BI__builtin_lsx_vsllwil_w_h:
4529 case LoongArch::BI__builtin_lsx_vsllwil_wu_hu:
4530 case LoongArch::BI__builtin_lsx_vrotri_h:
4531 case LoongArch::BI__builtin_lsx_vsrlri_h:
4532 return BuiltinConstantArgRange(TheCall, 1, 0, 15);
4533 case LoongArch::BI__builtin_lsx_vssrarni_b_h:
4534 case LoongArch::BI__builtin_lsx_vssrarni_bu_h:
4535 case LoongArch::BI__builtin_lsx_vssrani_b_h:
4536 case LoongArch::BI__builtin_lsx_vssrani_bu_h:
4537 case LoongArch::BI__builtin_lsx_vsrarni_b_h:
4538 case LoongArch::BI__builtin_lsx_vsrlni_b_h:
4539 case LoongArch::BI__builtin_lsx_vsrlrni_b_h:
4540 case LoongArch::BI__builtin_lsx_vssrlni_b_h:
4541 case LoongArch::BI__builtin_lsx_vssrlni_bu_h:
4542 case LoongArch::BI__builtin_lsx_vssrlrni_b_h:
4543 case LoongArch::BI__builtin_lsx_vssrlrni_bu_h:
4544 case LoongArch::BI__builtin_lsx_vsrani_b_h:
4545 return BuiltinConstantArgRange(TheCall, 2, 0, 15);
4546 case LoongArch::BI__builtin_lsx_vslei_bu:
4547 case LoongArch::BI__builtin_lsx_vslei_hu:
4548 case LoongArch::BI__builtin_lsx_vslei_wu:
4549 case LoongArch::BI__builtin_lsx_vslei_du:
4550 case LoongArch::BI__builtin_lsx_vslti_bu:
4551 case LoongArch::BI__builtin_lsx_vslti_hu:
4552 case LoongArch::BI__builtin_lsx_vslti_wu:
4553 case LoongArch::BI__builtin_lsx_vslti_du:
4554 case LoongArch::BI__builtin_lsx_vmaxi_bu:
4555 case LoongArch::BI__builtin_lsx_vmaxi_hu:
4556 case LoongArch::BI__builtin_lsx_vmaxi_wu:
4557 case LoongArch::BI__builtin_lsx_vmaxi_du:
4558 case LoongArch::BI__builtin_lsx_vmini_bu:
4559 case LoongArch::BI__builtin_lsx_vmini_hu:
4560 case LoongArch::BI__builtin_lsx_vmini_wu:
4561 case LoongArch::BI__builtin_lsx_vmini_du:
4562 case LoongArch::BI__builtin_lsx_vaddi_bu:
4563 case LoongArch::BI__builtin_lsx_vaddi_hu:
4564 case LoongArch::BI__builtin_lsx_vaddi_wu:
4565 case LoongArch::BI__builtin_lsx_vaddi_du:
4566 case LoongArch::BI__builtin_lsx_vbitclri_w:
4567 case LoongArch::BI__builtin_lsx_vbitrevi_w:
4568 case LoongArch::BI__builtin_lsx_vbitseti_w:
4569 case LoongArch::BI__builtin_lsx_vsat_w:
4570 case LoongArch::BI__builtin_lsx_vsat_wu:
4571 case LoongArch::BI__builtin_lsx_vslli_w:
4572 case LoongArch::BI__builtin_lsx_vsrai_w:
4573 case LoongArch::BI__builtin_lsx_vsrari_w:
4574 case LoongArch::BI__builtin_lsx_vsrli_w:
4575 case LoongArch::BI__builtin_lsx_vsllwil_d_w:
4576 case LoongArch::BI__builtin_lsx_vsllwil_du_wu:
4577 case LoongArch::BI__builtin_lsx_vsrlri_w:
4578 case LoongArch::BI__builtin_lsx_vrotri_w:
4579 case LoongArch::BI__builtin_lsx_vsubi_bu:
4580 case LoongArch::BI__builtin_lsx_vsubi_hu:
4581 case LoongArch::BI__builtin_lsx_vbsrl_v:
4582 case LoongArch::BI__builtin_lsx_vbsll_v:
4583 case LoongArch::BI__builtin_lsx_vsubi_wu:
4584 case LoongArch::BI__builtin_lsx_vsubi_du:
4585 return BuiltinConstantArgRange(TheCall, 1, 0, 31);
4586 case LoongArch::BI__builtin_lsx_vssrarni_h_w:
4587 case LoongArch::BI__builtin_lsx_vssrarni_hu_w:
4588 case LoongArch::BI__builtin_lsx_vssrani_h_w:
4589 case LoongArch::BI__builtin_lsx_vssrani_hu_w:
4590 case LoongArch::BI__builtin_lsx_vsrarni_h_w:
4591 case LoongArch::BI__builtin_lsx_vsrani_h_w:
4592 case LoongArch::BI__builtin_lsx_vfrstpi_b:
4593 case LoongArch::BI__builtin_lsx_vfrstpi_h:
4594 case LoongArch::BI__builtin_lsx_vsrlni_h_w:
4595 case LoongArch::BI__builtin_lsx_vsrlrni_h_w:
4596 case LoongArch::BI__builtin_lsx_vssrlni_h_w:
4597 case LoongArch::BI__builtin_lsx_vssrlni_hu_w:
4598 case LoongArch::BI__builtin_lsx_vssrlrni_h_w:
4599 case LoongArch::BI__builtin_lsx_vssrlrni_hu_w:
4600 return BuiltinConstantArgRange(TheCall, 2, 0, 31);
4601 case LoongArch::BI__builtin_lsx_vbitclri_d:
4602 case LoongArch::BI__builtin_lsx_vbitrevi_d:
4603 case LoongArch::BI__builtin_lsx_vbitseti_d:
4604 case LoongArch::BI__builtin_lsx_vsat_d:
4605 case LoongArch::BI__builtin_lsx_vsat_du:
4606 case LoongArch::BI__builtin_lsx_vslli_d:
4607 case LoongArch::BI__builtin_lsx_vsrai_d:
4608 case LoongArch::BI__builtin_lsx_vsrli_d:
4609 case LoongArch::BI__builtin_lsx_vsrari_d:
4610 case LoongArch::BI__builtin_lsx_vrotri_d:
4611 case LoongArch::BI__builtin_lsx_vsrlri_d:
4612 return BuiltinConstantArgRange(TheCall, 1, 0, 63);
4613 case LoongArch::BI__builtin_lsx_vssrarni_w_d:
4614 case LoongArch::BI__builtin_lsx_vssrarni_wu_d:
4615 case LoongArch::BI__builtin_lsx_vssrani_w_d:
4616 case LoongArch::BI__builtin_lsx_vssrani_wu_d:
4617 case LoongArch::BI__builtin_lsx_vsrarni_w_d:
4618 case LoongArch::BI__builtin_lsx_vsrlni_w_d:
4619 case LoongArch::BI__builtin_lsx_vsrlrni_w_d:
4620 case LoongArch::BI__builtin_lsx_vssrlni_w_d:
4621 case LoongArch::BI__builtin_lsx_vssrlni_wu_d:
4622 case LoongArch::BI__builtin_lsx_vssrlrni_w_d:
4623 case LoongArch::BI__builtin_lsx_vssrlrni_wu_d:
4624 case LoongArch::BI__builtin_lsx_vsrani_w_d:
4625 return BuiltinConstantArgRange(TheCall, 2, 0, 63);
4626 case LoongArch::BI__builtin_lsx_vssrarni_d_q:
4627 case LoongArch::BI__builtin_lsx_vssrarni_du_q:
4628 case LoongArch::BI__builtin_lsx_vssrani_d_q:
4629 case LoongArch::BI__builtin_lsx_vssrani_du_q:
4630 case LoongArch::BI__builtin_lsx_vsrarni_d_q:
4631 case LoongArch::BI__builtin_lsx_vssrlni_d_q:
4632 case LoongArch::BI__builtin_lsx_vssrlni_du_q:
4633 case LoongArch::BI__builtin_lsx_vssrlrni_d_q:
4634 case LoongArch::BI__builtin_lsx_vssrlrni_du_q:
4635 case LoongArch::BI__builtin_lsx_vsrani_d_q:
4636 case LoongArch::BI__builtin_lsx_vsrlrni_d_q:
4637 case LoongArch::BI__builtin_lsx_vsrlni_d_q:
4638 return BuiltinConstantArgRange(TheCall, 2, 0, 127);
4639 case LoongArch::BI__builtin_lsx_vseqi_b:
4640 case LoongArch::BI__builtin_lsx_vseqi_h:
4641 case LoongArch::BI__builtin_lsx_vseqi_w:
4642 case LoongArch::BI__builtin_lsx_vseqi_d:
4643 case LoongArch::BI__builtin_lsx_vslti_b:
4644 case LoongArch::BI__builtin_lsx_vslti_h:
4645 case LoongArch::BI__builtin_lsx_vslti_w:
4646 case LoongArch::BI__builtin_lsx_vslti_d:
4647 case LoongArch::BI__builtin_lsx_vslei_b:
4648 case LoongArch::BI__builtin_lsx_vslei_h:
4649 case LoongArch::BI__builtin_lsx_vslei_w:
4650 case LoongArch::BI__builtin_lsx_vslei_d:
4651 case LoongArch::BI__builtin_lsx_vmaxi_b:
4652 case LoongArch::BI__builtin_lsx_vmaxi_h:
4653 case LoongArch::BI__builtin_lsx_vmaxi_w:
4654 case LoongArch::BI__builtin_lsx_vmaxi_d:
4655 case LoongArch::BI__builtin_lsx_vmini_b:
4656 case LoongArch::BI__builtin_lsx_vmini_h:
4657 case LoongArch::BI__builtin_lsx_vmini_w:
4658 case LoongArch::BI__builtin_lsx_vmini_d:
4659 return BuiltinConstantArgRange(TheCall, 1, -16, 15);
4660 case LoongArch::BI__builtin_lsx_vandi_b:
4661 case LoongArch::BI__builtin_lsx_vnori_b:
4662 case LoongArch::BI__builtin_lsx_vori_b:
4663 case LoongArch::BI__builtin_lsx_vshuf4i_b:
4664 case LoongArch::BI__builtin_lsx_vshuf4i_h:
4665 case LoongArch::BI__builtin_lsx_vshuf4i_w:
4666 case LoongArch::BI__builtin_lsx_vxori_b:
4667 return BuiltinConstantArgRange(TheCall, 1, 0, 255);
4668 case LoongArch::BI__builtin_lsx_vbitseli_b:
4669 case LoongArch::BI__builtin_lsx_vshuf4i_d:
4670 case LoongArch::BI__builtin_lsx_vextrins_b:
4671 case LoongArch::BI__builtin_lsx_vextrins_h:
4672 case LoongArch::BI__builtin_lsx_vextrins_w:
4673 case LoongArch::BI__builtin_lsx_vextrins_d:
4674 case LoongArch::BI__builtin_lsx_vpermi_w:
4675 return BuiltinConstantArgRange(TheCall, 2, 0, 255);
4676 case LoongArch::BI__builtin_lsx_vpickve2gr_b:
4677 case LoongArch::BI__builtin_lsx_vpickve2gr_bu:
4678 case LoongArch::BI__builtin_lsx_vreplvei_b:
4679 return BuiltinConstantArgRange(TheCall, 1, 0, 15);
4680 case LoongArch::BI__builtin_lsx_vinsgr2vr_b:
4681 return BuiltinConstantArgRange(TheCall, 2, 0, 15);
4682 case LoongArch::BI__builtin_lsx_vpickve2gr_h:
4683 case LoongArch::BI__builtin_lsx_vpickve2gr_hu:
4684 case LoongArch::BI__builtin_lsx_vreplvei_h:
4685 return BuiltinConstantArgRange(TheCall, 1, 0, 7);
4686 case LoongArch::BI__builtin_lsx_vinsgr2vr_h:
4687 return BuiltinConstantArgRange(TheCall, 2, 0, 7);
4688 case LoongArch::BI__builtin_lsx_vpickve2gr_w:
4689 case LoongArch::BI__builtin_lsx_vpickve2gr_wu:
4690 case LoongArch::BI__builtin_lsx_vreplvei_w:
4691 return BuiltinConstantArgRange(TheCall, 1, 0, 3);
4692 case LoongArch::BI__builtin_lsx_vinsgr2vr_w:
4693 return BuiltinConstantArgRange(TheCall, 2, 0, 3);
4694 case LoongArch::BI__builtin_lsx_vpickve2gr_d:
4695 case LoongArch::BI__builtin_lsx_vpickve2gr_du:
4696 case LoongArch::BI__builtin_lsx_vreplvei_d:
4697 return BuiltinConstantArgRange(TheCall, 1, 0, 1);
4698 case LoongArch::BI__builtin_lsx_vinsgr2vr_d:
4699 return BuiltinConstantArgRange(TheCall, 2, 0, 1);
4700 case LoongArch::BI__builtin_lsx_vstelm_b:
4701 return BuiltinConstantArgRange(TheCall, 2, -128, 127) ||
4702 BuiltinConstantArgRange(TheCall, 3, 0, 15);
4703 case LoongArch::BI__builtin_lsx_vstelm_h:
4704 return BuiltinConstantArgRange(TheCall, 2, -256, 254) ||
4705 BuiltinConstantArgRange(TheCall, 3, 0, 7);
4706 case LoongArch::BI__builtin_lsx_vstelm_w:
4707 return BuiltinConstantArgRange(TheCall, 2, -512, 508) ||
4708 BuiltinConstantArgRange(TheCall, 3, 0, 3);
4709 case LoongArch::BI__builtin_lsx_vstelm_d:
4710 return BuiltinConstantArgRange(TheCall, 2, -1024, 1016) ||
4711 BuiltinConstantArgRange(TheCall, 3, 0, 1);
4712 case LoongArch::BI__builtin_lsx_vldrepl_b:
4713 case LoongArch::BI__builtin_lsx_vld:
4714 return BuiltinConstantArgRange(TheCall, 1, -2048, 2047);
4715 case LoongArch::BI__builtin_lsx_vldrepl_h:
4716 return BuiltinConstantArgRange(TheCall, 1, -2048, 2046);
4717 case LoongArch::BI__builtin_lsx_vldrepl_w:
4718 return BuiltinConstantArgRange(TheCall, 1, -2048, 2044);
4719 case LoongArch::BI__builtin_lsx_vldrepl_d:
4720 return BuiltinConstantArgRange(TheCall, 1, -2048, 2040);
4721 case LoongArch::BI__builtin_lsx_vst:
4722 return BuiltinConstantArgRange(TheCall, 2, -2048, 2047);
4723 case LoongArch::BI__builtin_lsx_vldi:
4724 return BuiltinConstantArgRange(TheCall, 0, -4096, 4095);
4725 case LoongArch::BI__builtin_lsx_vrepli_b:
4726 case LoongArch::BI__builtin_lsx_vrepli_h:
4727 case LoongArch::BI__builtin_lsx_vrepli_w:
4728 case LoongArch::BI__builtin_lsx_vrepli_d:
4729 return BuiltinConstantArgRange(TheCall, 0, -512, 511);
4730
4731 // LASX intrinsics.
4732 case LoongArch::BI__builtin_lasx_xvbitclri_b:
4733 case LoongArch::BI__builtin_lasx_xvbitrevi_b:
4734 case LoongArch::BI__builtin_lasx_xvbitseti_b:
4735 case LoongArch::BI__builtin_lasx_xvsat_b:
4736 case LoongArch::BI__builtin_lasx_xvsat_bu:
4737 case LoongArch::BI__builtin_lasx_xvslli_b:
4738 case LoongArch::BI__builtin_lasx_xvsrai_b:
4739 case LoongArch::BI__builtin_lasx_xvsrari_b:
4740 case LoongArch::BI__builtin_lasx_xvsrli_b:
4741 case LoongArch::BI__builtin_lasx_xvsllwil_h_b:
4742 case LoongArch::BI__builtin_lasx_xvsllwil_hu_bu:
4743 case LoongArch::BI__builtin_lasx_xvrotri_b:
4744 case LoongArch::BI__builtin_lasx_xvsrlri_b:
4745 return BuiltinConstantArgRange(TheCall, 1, 0, 7);
4746 case LoongArch::BI__builtin_lasx_xvbitclri_h:
4747 case LoongArch::BI__builtin_lasx_xvbitrevi_h:
4748 case LoongArch::BI__builtin_lasx_xvbitseti_h:
4749 case LoongArch::BI__builtin_lasx_xvsat_h:
4750 case LoongArch::BI__builtin_lasx_xvsat_hu:
4751 case LoongArch::BI__builtin_lasx_xvslli_h:
4752 case LoongArch::BI__builtin_lasx_xvsrai_h:
4753 case LoongArch::BI__builtin_lasx_xvsrari_h:
4754 case LoongArch::BI__builtin_lasx_xvsrli_h:
4755 case LoongArch::BI__builtin_lasx_xvsllwil_w_h:
4756 case LoongArch::BI__builtin_lasx_xvsllwil_wu_hu:
4757 case LoongArch::BI__builtin_lasx_xvrotri_h:
4758 case LoongArch::BI__builtin_lasx_xvsrlri_h:
4759 return BuiltinConstantArgRange(TheCall, 1, 0, 15);
4760 case LoongArch::BI__builtin_lasx_xvssrarni_b_h:
4761 case LoongArch::BI__builtin_lasx_xvssrarni_bu_h:
4762 case LoongArch::BI__builtin_lasx_xvssrani_b_h:
4763 case LoongArch::BI__builtin_lasx_xvssrani_bu_h:
4764 case LoongArch::BI__builtin_lasx_xvsrarni_b_h:
4765 case LoongArch::BI__builtin_lasx_xvsrlni_b_h:
4766 case LoongArch::BI__builtin_lasx_xvsrlrni_b_h:
4767 case LoongArch::BI__builtin_lasx_xvssrlni_b_h:
4768 case LoongArch::BI__builtin_lasx_xvssrlni_bu_h:
4769 case LoongArch::BI__builtin_lasx_xvssrlrni_b_h:
4770 case LoongArch::BI__builtin_lasx_xvssrlrni_bu_h:
4771 case LoongArch::BI__builtin_lasx_xvsrani_b_h:
4772 return BuiltinConstantArgRange(TheCall, 2, 0, 15);
4773 case LoongArch::BI__builtin_lasx_xvslei_bu:
4774 case LoongArch::BI__builtin_lasx_xvslei_hu:
4775 case LoongArch::BI__builtin_lasx_xvslei_wu:
4776 case LoongArch::BI__builtin_lasx_xvslei_du:
4777 case LoongArch::BI__builtin_lasx_xvslti_bu:
4778 case LoongArch::BI__builtin_lasx_xvslti_hu:
4779 case LoongArch::BI__builtin_lasx_xvslti_wu:
4780 case LoongArch::BI__builtin_lasx_xvslti_du:
4781 case LoongArch::BI__builtin_lasx_xvmaxi_bu:
4782 case LoongArch::BI__builtin_lasx_xvmaxi_hu:
4783 case LoongArch::BI__builtin_lasx_xvmaxi_wu:
4784 case LoongArch::BI__builtin_lasx_xvmaxi_du:
4785 case LoongArch::BI__builtin_lasx_xvmini_bu:
4786 case LoongArch::BI__builtin_lasx_xvmini_hu:
4787 case LoongArch::BI__builtin_lasx_xvmini_wu:
4788 case LoongArch::BI__builtin_lasx_xvmini_du:
4789 case LoongArch::BI__builtin_lasx_xvaddi_bu:
4790 case LoongArch::BI__builtin_lasx_xvaddi_hu:
4791 case LoongArch::BI__builtin_lasx_xvaddi_wu:
4792 case LoongArch::BI__builtin_lasx_xvaddi_du:
4793 case LoongArch::BI__builtin_lasx_xvbitclri_w:
4794 case LoongArch::BI__builtin_lasx_xvbitrevi_w:
4795 case LoongArch::BI__builtin_lasx_xvbitseti_w:
4796 case LoongArch::BI__builtin_lasx_xvsat_w:
4797 case LoongArch::BI__builtin_lasx_xvsat_wu:
4798 case LoongArch::BI__builtin_lasx_xvslli_w:
4799 case LoongArch::BI__builtin_lasx_xvsrai_w:
4800 case LoongArch::BI__builtin_lasx_xvsrari_w:
4801 case LoongArch::BI__builtin_lasx_xvsrli_w:
4802 case LoongArch::BI__builtin_lasx_xvsllwil_d_w:
4803 case LoongArch::BI__builtin_lasx_xvsllwil_du_wu:
4804 case LoongArch::BI__builtin_lasx_xvsrlri_w:
4805 case LoongArch::BI__builtin_lasx_xvrotri_w:
4806 case LoongArch::BI__builtin_lasx_xvsubi_bu:
4807 case LoongArch::BI__builtin_lasx_xvsubi_hu:
4808 case LoongArch::BI__builtin_lasx_xvsubi_wu:
4809 case LoongArch::BI__builtin_lasx_xvsubi_du:
4810 case LoongArch::BI__builtin_lasx_xvbsrl_v:
4811 case LoongArch::BI__builtin_lasx_xvbsll_v:
4812 return BuiltinConstantArgRange(TheCall, 1, 0, 31);
4813 case LoongArch::BI__builtin_lasx_xvssrarni_h_w:
4814 case LoongArch::BI__builtin_lasx_xvssrarni_hu_w:
4815 case LoongArch::BI__builtin_lasx_xvssrani_h_w:
4816 case LoongArch::BI__builtin_lasx_xvssrani_hu_w:
4817 case LoongArch::BI__builtin_lasx_xvsrarni_h_w:
4818 case LoongArch::BI__builtin_lasx_xvsrani_h_w:
4819 case LoongArch::BI__builtin_lasx_xvfrstpi_b:
4820 case LoongArch::BI__builtin_lasx_xvfrstpi_h:
4821 case LoongArch::BI__builtin_lasx_xvsrlni_h_w:
4822 case LoongArch::BI__builtin_lasx_xvsrlrni_h_w:
4823 case LoongArch::BI__builtin_lasx_xvssrlni_h_w:
4824 case LoongArch::BI__builtin_lasx_xvssrlni_hu_w:
4825 case LoongArch::BI__builtin_lasx_xvssrlrni_h_w:
4826 case LoongArch::BI__builtin_lasx_xvssrlrni_hu_w:
4827 return BuiltinConstantArgRange(TheCall, 2, 0, 31);
4828 case LoongArch::BI__builtin_lasx_xvbitclri_d:
4829 case LoongArch::BI__builtin_lasx_xvbitrevi_d:
4830 case LoongArch::BI__builtin_lasx_xvbitseti_d:
4831 case LoongArch::BI__builtin_lasx_xvsat_d:
4832 case LoongArch::BI__builtin_lasx_xvsat_du:
4833 case LoongArch::BI__builtin_lasx_xvslli_d:
4834 case LoongArch::BI__builtin_lasx_xvsrai_d:
4835 case LoongArch::BI__builtin_lasx_xvsrli_d:
4836 case LoongArch::BI__builtin_lasx_xvsrari_d:
4837 case LoongArch::BI__builtin_lasx_xvrotri_d:
4838 case LoongArch::BI__builtin_lasx_xvsrlri_d:
4839 return BuiltinConstantArgRange(TheCall, 1, 0, 63);
4840 case LoongArch::BI__builtin_lasx_xvssrarni_w_d:
4841 case LoongArch::BI__builtin_lasx_xvssrarni_wu_d:
4842 case LoongArch::BI__builtin_lasx_xvssrani_w_d:
4843 case LoongArch::BI__builtin_lasx_xvssrani_wu_d:
4844 case LoongArch::BI__builtin_lasx_xvsrarni_w_d:
4845 case LoongArch::BI__builtin_lasx_xvsrlni_w_d:
4846 case LoongArch::BI__builtin_lasx_xvsrlrni_w_d:
4847 case LoongArch::BI__builtin_lasx_xvssrlni_w_d:
4848 case LoongArch::BI__builtin_lasx_xvssrlni_wu_d:
4849 case LoongArch::BI__builtin_lasx_xvssrlrni_w_d:
4850 case LoongArch::BI__builtin_lasx_xvssrlrni_wu_d:
4851 case LoongArch::BI__builtin_lasx_xvsrani_w_d:
4852 return BuiltinConstantArgRange(TheCall, 2, 0, 63);
4853 case LoongArch::BI__builtin_lasx_xvssrarni_d_q:
4854 case LoongArch::BI__builtin_lasx_xvssrarni_du_q:
4855 case LoongArch::BI__builtin_lasx_xvssrani_d_q:
4856 case LoongArch::BI__builtin_lasx_xvssrani_du_q:
4857 case LoongArch::BI__builtin_lasx_xvsrarni_d_q:
4858 case LoongArch::BI__builtin_lasx_xvssrlni_d_q:
4859 case LoongArch::BI__builtin_lasx_xvssrlni_du_q:
4860 case LoongArch::BI__builtin_lasx_xvssrlrni_d_q:
4861 case LoongArch::BI__builtin_lasx_xvssrlrni_du_q:
4862 case LoongArch::BI__builtin_lasx_xvsrani_d_q:
4863 case LoongArch::BI__builtin_lasx_xvsrlni_d_q:
4864 case LoongArch::BI__builtin_lasx_xvsrlrni_d_q:
4865 return BuiltinConstantArgRange(TheCall, 2, 0, 127);
4866 case LoongArch::BI__builtin_lasx_xvseqi_b:
4867 case LoongArch::BI__builtin_lasx_xvseqi_h:
4868 case LoongArch::BI__builtin_lasx_xvseqi_w:
4869 case LoongArch::BI__builtin_lasx_xvseqi_d:
4870 case LoongArch::BI__builtin_lasx_xvslti_b:
4871 case LoongArch::BI__builtin_lasx_xvslti_h:
4872 case LoongArch::BI__builtin_lasx_xvslti_w:
4873 case LoongArch::BI__builtin_lasx_xvslti_d:
4874 case LoongArch::BI__builtin_lasx_xvslei_b:
4875 case LoongArch::BI__builtin_lasx_xvslei_h:
4876 case LoongArch::BI__builtin_lasx_xvslei_w:
4877 case LoongArch::BI__builtin_lasx_xvslei_d:
4878 case LoongArch::BI__builtin_lasx_xvmaxi_b:
4879 case LoongArch::BI__builtin_lasx_xvmaxi_h:
4880 case LoongArch::BI__builtin_lasx_xvmaxi_w:
4881 case LoongArch::BI__builtin_lasx_xvmaxi_d:
4882 case LoongArch::BI__builtin_lasx_xvmini_b:
4883 case LoongArch::BI__builtin_lasx_xvmini_h:
4884 case LoongArch::BI__builtin_lasx_xvmini_w:
4885 case LoongArch::BI__builtin_lasx_xvmini_d:
4886 return BuiltinConstantArgRange(TheCall, 1, -16, 15);
4887 case LoongArch::BI__builtin_lasx_xvandi_b:
4888 case LoongArch::BI__builtin_lasx_xvnori_b:
4889 case LoongArch::BI__builtin_lasx_xvori_b:
4890 case LoongArch::BI__builtin_lasx_xvshuf4i_b:
4891 case LoongArch::BI__builtin_lasx_xvshuf4i_h:
4892 case LoongArch::BI__builtin_lasx_xvshuf4i_w:
4893 case LoongArch::BI__builtin_lasx_xvxori_b:
4894 case LoongArch::BI__builtin_lasx_xvpermi_d:
4895 return BuiltinConstantArgRange(TheCall, 1, 0, 255);
4896 case LoongArch::BI__builtin_lasx_xvbitseli_b:
4897 case LoongArch::BI__builtin_lasx_xvshuf4i_d:
4898 case LoongArch::BI__builtin_lasx_xvextrins_b:
4899 case LoongArch::BI__builtin_lasx_xvextrins_h:
4900 case LoongArch::BI__builtin_lasx_xvextrins_w:
4901 case LoongArch::BI__builtin_lasx_xvextrins_d:
4902 case LoongArch::BI__builtin_lasx_xvpermi_q:
4903 case LoongArch::BI__builtin_lasx_xvpermi_w:
4904 return BuiltinConstantArgRange(TheCall, 2, 0, 255);
4905 case LoongArch::BI__builtin_lasx_xvrepl128vei_b:
4906 return BuiltinConstantArgRange(TheCall, 1, 0, 15);
4907 case LoongArch::BI__builtin_lasx_xvrepl128vei_h:
4908 case LoongArch::BI__builtin_lasx_xvpickve2gr_w:
4909 case LoongArch::BI__builtin_lasx_xvpickve2gr_wu:
4910 case LoongArch::BI__builtin_lasx_xvpickve_w_f:
4911 case LoongArch::BI__builtin_lasx_xvpickve_w:
4912 return BuiltinConstantArgRange(TheCall, 1, 0, 7);
4913 case LoongArch::BI__builtin_lasx_xvinsgr2vr_w:
4914 case LoongArch::BI__builtin_lasx_xvinsve0_w:
4915 return BuiltinConstantArgRange(TheCall, 2, 0, 7);
4916 case LoongArch::BI__builtin_lasx_xvrepl128vei_w:
4917 case LoongArch::BI__builtin_lasx_xvpickve2gr_d:
4918 case LoongArch::BI__builtin_lasx_xvpickve2gr_du:
4919 case LoongArch::BI__builtin_lasx_xvpickve_d_f:
4920 case LoongArch::BI__builtin_lasx_xvpickve_d:
4921 return BuiltinConstantArgRange(TheCall, 1, 0, 3);
4922 case LoongArch::BI__builtin_lasx_xvinsve0_d:
4923 case LoongArch::BI__builtin_lasx_xvinsgr2vr_d:
4924 return BuiltinConstantArgRange(TheCall, 2, 0, 3);
4925 case LoongArch::BI__builtin_lasx_xvstelm_b:
4926 return BuiltinConstantArgRange(TheCall, 2, -128, 127) ||
4927 BuiltinConstantArgRange(TheCall, 3, 0, 31);
4928 case LoongArch::BI__builtin_lasx_xvstelm_h:
4929 return BuiltinConstantArgRange(TheCall, 2, -256, 254) ||
4930 BuiltinConstantArgRange(TheCall, 3, 0, 15);
4931 case LoongArch::BI__builtin_lasx_xvstelm_w:
4932 return BuiltinConstantArgRange(TheCall, 2, -512, 508) ||
4933 BuiltinConstantArgRange(TheCall, 3, 0, 7);
4934 case LoongArch::BI__builtin_lasx_xvstelm_d:
4935 return BuiltinConstantArgRange(TheCall, 2, -1024, 1016) ||
4936 BuiltinConstantArgRange(TheCall, 3, 0, 3);
4937 case LoongArch::BI__builtin_lasx_xvrepl128vei_d:
4938 return BuiltinConstantArgRange(TheCall, 1, 0, 1);
4939 case LoongArch::BI__builtin_lasx_xvldrepl_b:
4940 case LoongArch::BI__builtin_lasx_xvld:
4941 return BuiltinConstantArgRange(TheCall, 1, -2048, 2047);
4942 case LoongArch::BI__builtin_lasx_xvldrepl_h:
4943 return BuiltinConstantArgRange(TheCall, 1, -2048, 2046);
4944 case LoongArch::BI__builtin_lasx_xvldrepl_w:
4945 return BuiltinConstantArgRange(TheCall, 1, -2048, 2044);
4946 case LoongArch::BI__builtin_lasx_xvldrepl_d:
4947 return BuiltinConstantArgRange(TheCall, 1, -2048, 2040);
4948 case LoongArch::BI__builtin_lasx_xvst:
4949 return BuiltinConstantArgRange(TheCall, 2, -2048, 2047);
4950 case LoongArch::BI__builtin_lasx_xvldi:
4951 return BuiltinConstantArgRange(TheCall, 0, -4096, 4095);
4952 case LoongArch::BI__builtin_lasx_xvrepli_b:
4953 case LoongArch::BI__builtin_lasx_xvrepli_h:
4954 case LoongArch::BI__builtin_lasx_xvrepli_w:
4955 case LoongArch::BI__builtin_lasx_xvrepli_d:
4956 return BuiltinConstantArgRange(TheCall, 0, -512, 511);
4957 }
4958 return false;
4959}
4960
4961bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
4962 unsigned BuiltinID, CallExpr *TheCall) {
4963 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
4964 CheckMipsBuiltinArgument(BuiltinID, TheCall);
4965}
4966
4967bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
4968 CallExpr *TheCall) {
4969
4970 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
4971 BuiltinID <= Mips::BI__builtin_mips_lwx) {
4972 if (!TI.hasFeature("dsp"))
4973 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
4974 }
4975
4976 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
4977 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
4978 if (!TI.hasFeature("dspr2"))
4979 return Diag(TheCall->getBeginLoc(),
4980 diag::err_mips_builtin_requires_dspr2);
4981 }
4982
4983 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
4984 BuiltinID <= Mips::BI__builtin_msa_xori_b) {
4985 if (!TI.hasFeature("msa"))
4986 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
4987 }
4988
4989 return false;
4990}
4991
4992// CheckMipsBuiltinArgument - Checks the constant value passed to the
4993// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
4994// ordering for DSP is unspecified. MSA is ordered by the data format used
4995// by the underlying instruction i.e., df/m, df/n and then by size.
4996//
4997// FIXME: The size tests here should instead be tablegen'd along with the
4998// definitions from include/clang/Basic/BuiltinsMips.def.
4999// FIXME: GCC is strict on signedness for some of these intrinsics, we should
5000// be too.
5001bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
5002 unsigned i = 0, l = 0, u = 0, m = 0;
5003 switch (BuiltinID) {
5004 default: return false;
5005 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
5006 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
5007 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
5008 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
5009 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
5010 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
5011 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
5012 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
5013 // df/m field.
5014 // These intrinsics take an unsigned 3 bit immediate.
5015 case Mips::BI__builtin_msa_bclri_b:
5016 case Mips::BI__builtin_msa_bnegi_b:
5017 case Mips::BI__builtin_msa_bseti_b:
5018 case Mips::BI__builtin_msa_sat_s_b:
5019 case Mips::BI__builtin_msa_sat_u_b:
5020 case Mips::BI__builtin_msa_slli_b:
5021 case Mips::BI__builtin_msa_srai_b:
5022 case Mips::BI__builtin_msa_srari_b:
5023 case Mips::BI__builtin_msa_srli_b:
5024 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
5025 case Mips::BI__builtin_msa_binsli_b:
5026 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
5027 // These intrinsics take an unsigned 4 bit immediate.
5028 case Mips::BI__builtin_msa_bclri_h:
5029 case Mips::BI__builtin_msa_bnegi_h:
5030 case Mips::BI__builtin_msa_bseti_h:
5031 case Mips::BI__builtin_msa_sat_s_h:
5032 case Mips::BI__builtin_msa_sat_u_h:
5033 case Mips::BI__builtin_msa_slli_h:
5034 case Mips::BI__builtin_msa_srai_h:
5035 case Mips::BI__builtin_msa_srari_h:
5036 case Mips::BI__builtin_msa_srli_h:
5037 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
5038 case Mips::BI__builtin_msa_binsli_h:
5039 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
5040 // These intrinsics take an unsigned 5 bit immediate.
5041 // The first block of intrinsics actually have an unsigned 5 bit field,
5042 // not a df/n field.
5043 case Mips::BI__builtin_msa_cfcmsa:
5044 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
5045 case Mips::BI__builtin_msa_clei_u_b:
5046 case Mips::BI__builtin_msa_clei_u_h:
5047 case Mips::BI__builtin_msa_clei_u_w:
5048 case Mips::BI__builtin_msa_clei_u_d:
5049 case Mips::BI__builtin_msa_clti_u_b:
5050 case Mips::BI__builtin_msa_clti_u_h:
5051 case Mips::BI__builtin_msa_clti_u_w:
5052 case Mips::BI__builtin_msa_clti_u_d:
5053 case Mips::BI__builtin_msa_maxi_u_b:
5054 case Mips::BI__builtin_msa_maxi_u_h:
5055 case Mips::BI__builtin_msa_maxi_u_w:
5056 case Mips::BI__builtin_msa_maxi_u_d:
5057 case Mips::BI__builtin_msa_mini_u_b:
5058 case Mips::BI__builtin_msa_mini_u_h:
5059 case Mips::BI__builtin_msa_mini_u_w:
5060 case Mips::BI__builtin_msa_mini_u_d:
5061 case Mips::BI__builtin_msa_addvi_b:
5062 case Mips::BI__builtin_msa_addvi_h:
5063 case Mips::BI__builtin_msa_addvi_w:
5064 case Mips::BI__builtin_msa_addvi_d:
5065 case Mips::BI__builtin_msa_bclri_w:
5066 case Mips::BI__builtin_msa_bnegi_w:
5067 case Mips::BI__builtin_msa_bseti_w:
5068 case Mips::BI__builtin_msa_sat_s_w:
5069 case Mips::BI__builtin_msa_sat_u_w:
5070 case Mips::BI__builtin_msa_slli_w:
5071 case Mips::BI__builtin_msa_srai_w:
5072 case Mips::BI__builtin_msa_srari_w:
5073 case Mips::BI__builtin_msa_srli_w:
5074 case Mips::BI__builtin_msa_srlri_w:
5075 case Mips::BI__builtin_msa_subvi_b:
5076 case Mips::BI__builtin_msa_subvi_h:
5077 case Mips::BI__builtin_msa_subvi_w:
5078 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
5079 case Mips::BI__builtin_msa_binsli_w:
5080 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
5081 // These intrinsics take an unsigned 6 bit immediate.
5082 case Mips::BI__builtin_msa_bclri_d:
5083 case Mips::BI__builtin_msa_bnegi_d:
5084 case Mips::BI__builtin_msa_bseti_d:
5085 case Mips::BI__builtin_msa_sat_s_d:
5086 case Mips::BI__builtin_msa_sat_u_d:
5087 case Mips::BI__builtin_msa_slli_d:
5088 case Mips::BI__builtin_msa_srai_d:
5089 case Mips::BI__builtin_msa_srari_d:
5090 case Mips::BI__builtin_msa_srli_d:
5091 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
5092 case Mips::BI__builtin_msa_binsli_d:
5093 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
5094 // These intrinsics take a signed 5 bit immediate.
5095 case Mips::BI__builtin_msa_ceqi_b:
5096 case Mips::BI__builtin_msa_ceqi_h:
5097 case Mips::BI__builtin_msa_ceqi_w:
5098 case Mips::BI__builtin_msa_ceqi_d:
5099 case Mips::BI__builtin_msa_clti_s_b:
5100 case Mips::BI__builtin_msa_clti_s_h:
5101 case Mips::BI__builtin_msa_clti_s_w:
5102 case Mips::BI__builtin_msa_clti_s_d:
5103 case Mips::BI__builtin_msa_clei_s_b:
5104 case Mips::BI__builtin_msa_clei_s_h:
5105 case Mips::BI__builtin_msa_clei_s_w:
5106 case Mips::BI__builtin_msa_clei_s_d:
5107 case Mips::BI__builtin_msa_maxi_s_b:
5108 case Mips::BI__builtin_msa_maxi_s_h:
5109 case Mips::BI__builtin_msa_maxi_s_w:
5110 case Mips::BI__builtin_msa_maxi_s_d:
5111 case Mips::BI__builtin_msa_mini_s_b:
5112 case Mips::BI__builtin_msa_mini_s_h:
5113 case Mips::BI__builtin_msa_mini_s_w:
5114 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
5115 // These intrinsics take an unsigned 8 bit immediate.
5116 case Mips::BI__builtin_msa_andi_b:
5117 case Mips::BI__builtin_msa_nori_b:
5118 case Mips::BI__builtin_msa_ori_b:
5119 case Mips::BI__builtin_msa_shf_b:
5120 case Mips::BI__builtin_msa_shf_h:
5121 case Mips::BI__builtin_msa_shf_w:
5122 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
5123 case Mips::BI__builtin_msa_bseli_b:
5124 case Mips::BI__builtin_msa_bmnzi_b:
5125 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
5126 // df/n format
5127 // These intrinsics take an unsigned 4 bit immediate.
5128 case Mips::BI__builtin_msa_copy_s_b:
5129 case Mips::BI__builtin_msa_copy_u_b:
5130 case Mips::BI__builtin_msa_insve_b:
5131 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
5132 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
5133 // These intrinsics take an unsigned 3 bit immediate.
5134 case Mips::BI__builtin_msa_copy_s_h:
5135 case Mips::BI__builtin_msa_copy_u_h:
5136 case Mips::BI__builtin_msa_insve_h:
5137 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
5138 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
5139 // These intrinsics take an unsigned 2 bit immediate.
5140 case Mips::BI__builtin_msa_copy_s_w:
5141 case Mips::BI__builtin_msa_copy_u_w:
5142 case Mips::BI__builtin_msa_insve_w:
5143 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
5144 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
5145 // These intrinsics take an unsigned 1 bit immediate.
5146 case Mips::BI__builtin_msa_copy_s_d:
5147 case Mips::BI__builtin_msa_copy_u_d:
5148 case Mips::BI__builtin_msa_insve_d:
5149 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
5150 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
5151 // Memory offsets and immediate loads.
5152 // These intrinsics take a signed 10 bit immediate.
5153 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
5154 case Mips::BI__builtin_msa_ldi_h:
5155 case Mips::BI__builtin_msa_ldi_w:
5156 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
5157 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
5158 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
5159 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
5160 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
5161 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
5162 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
5163 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
5164 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
5165 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
5166 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
5167 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
5168 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
5169 }
5170
5171 if (!m)
5172 return BuiltinConstantArgRange(TheCall, i, l, u);
5173
5174 return BuiltinConstantArgRange(TheCall, i, l, u) ||
5175 BuiltinConstantArgMultiple(TheCall, i, m);
5176}
5177
5178/// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
5179/// advancing the pointer over the consumed characters. The decoded type is
5180/// returned. If the decoded type represents a constant integer with a
5181/// constraint on its value then Mask is set to that value. The type descriptors
5182/// used in Str are specific to PPC MMA builtins and are documented in the file
5183/// defining the PPC builtins.
5184static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
5185 unsigned &Mask) {
5186 bool RequireICE = false;
5188 switch (*Str++) {
5189 case 'V':
5190 return Context.getVectorType(Context.UnsignedCharTy, 16,
5192 case 'i': {
5193 char *End;
5194 unsigned size = strtoul(Str, &End, 10);
5195 assert(End != Str && "Missing constant parameter constraint");
5196 Str = End;
5197 Mask = size;
5198 return Context.IntTy;
5199 }
5200 case 'W': {
5201 char *End;
5202 unsigned size = strtoul(Str, &End, 10);
5203 assert(End != Str && "Missing PowerPC MMA type size");
5204 Str = End;
5205 QualType Type;
5206 switch (size) {
5207 #define PPC_VECTOR_TYPE(typeName, Id, size) \
5208 case size: Type = Context.Id##Ty; break;
5209 #include "clang/Basic/PPCTypes.def"
5210 default: llvm_unreachable("Invalid PowerPC MMA vector type");
5211 }
5212 bool CheckVectorArgs = false;
5213 while (!CheckVectorArgs) {
5214 switch (*Str++) {
5215 case '*':
5216 Type = Context.getPointerType(Type);
5217 break;
5218 case 'C':
5219 Type = Type.withConst();
5220 break;
5221 default:
5222 CheckVectorArgs = true;
5223 --Str;
5224 break;
5225 }
5226 }
5227 return Type;
5228 }
5229 default:
5230 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
5231 }
5232}
5233
5234static bool isPPC_64Builtin(unsigned BuiltinID) {
5235 // These builtins only work on PPC 64bit targets.
5236 switch (BuiltinID) {
5237 case PPC::BI__builtin_divde:
5238 case PPC::BI__builtin_divdeu:
5239 case PPC::BI__builtin_bpermd:
5240 case PPC::BI__builtin_pdepd:
5241 case PPC::BI__builtin_pextd:
5242 case PPC::BI__builtin_ppc_ldarx:
5243 case PPC::BI__builtin_ppc_stdcx:
5244 case PPC::BI__builtin_ppc_tdw:
5245 case PPC::BI__builtin_ppc_trapd:
5246 case PPC::BI__builtin_ppc_cmpeqb:
5247 case PPC::BI__builtin_ppc_setb:
5248 case PPC::BI__builtin_ppc_mulhd:
5249 case PPC::BI__builtin_ppc_mulhdu:
5250 case PPC::BI__builtin_ppc_maddhd:
5251 case PPC::BI__builtin_ppc_maddhdu:
5252 case PPC::BI__builtin_ppc_maddld:
5253 case PPC::BI__builtin_ppc_load8r:
5254 case PPC::BI__builtin_ppc_store8r:
5255 case PPC::BI__builtin_ppc_insert_exp:
5256 case PPC::BI__builtin_ppc_extract_sig:
5257 case PPC::BI__builtin_ppc_addex:
5258 case PPC::BI__builtin_darn:
5259 case PPC::BI__builtin_darn_raw:
5260 case PPC::BI__builtin_ppc_compare_and_swaplp:
5261 case PPC::BI__builtin_ppc_fetch_and_addlp:
5262 case PPC::BI__builtin_ppc_fetch_and_andlp:
5263 case PPC::BI__builtin_ppc_fetch_and_orlp:
5264 case PPC::BI__builtin_ppc_fetch_and_swaplp:
5265 return true;
5266 }
5267 return false;
5268}
5269
5270/// Returns true if the argument consists of one contiguous run of 1s with any
5271/// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
5272/// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
5273/// since all 1s are not contiguous.
5274bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
5275 llvm::APSInt Result;
5276 // We can't check the value of a dependent argument.
5277 Expr *Arg = TheCall->getArg(ArgNum);
5278 if (Arg->isTypeDependent() || Arg->isValueDependent())
5279 return false;
5280
5281 // Check constant-ness first.
5282 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5283 return true;
5284
5285 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
5286 if (Result.isShiftedMask() || (~Result).isShiftedMask())
5287 return false;
5288
5289 return Diag(TheCall->getBeginLoc(),
5290 diag::err_argument_not_contiguous_bit_field)
5291 << ArgNum << Arg->getSourceRange();
5292}
5293
5294bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
5295 CallExpr *TheCall) {
5296 unsigned i = 0, l = 0, u = 0;
5297 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
5298 llvm::APSInt Result;
5299
5300 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
5301 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
5302 << TheCall->getSourceRange();
5303
5304 switch (BuiltinID) {
5305 default: return false;
5306 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
5307 case PPC::BI__builtin_altivec_crypto_vshasigmad:
5308 return BuiltinConstantArgRange(TheCall, 1, 0, 1) ||
5309 BuiltinConstantArgRange(TheCall, 2, 0, 15);
5310 case PPC::BI__builtin_altivec_dss:
5311 return BuiltinConstantArgRange(TheCall, 0, 0, 3);
5312 case PPC::BI__builtin_tbegin:
5313 case PPC::BI__builtin_tend:
5314 return BuiltinConstantArgRange(TheCall, 0, 0, 1);
5315 case PPC::BI__builtin_tsr:
5316 return BuiltinConstantArgRange(TheCall, 0, 0, 7);
5317 case PPC::BI__builtin_tabortwc:
5318 case PPC::BI__builtin_tabortdc:
5319 return BuiltinConstantArgRange(TheCall, 0, 0, 31);
5320 case PPC::BI__builtin_tabortwci:
5321 case PPC::BI__builtin_tabortdci:
5322 return BuiltinConstantArgRange(TheCall, 0, 0, 31) ||
5323 BuiltinConstantArgRange(TheCall, 2, 0, 31);
5324 // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
5325 // __builtin_(un)pack_longdouble are available only if long double uses IBM
5326 // extended double representation.
5327 case PPC::BI__builtin_unpack_longdouble:
5328 if (BuiltinConstantArgRange(TheCall, 1, 0, 1))
5329 return true;
5330 [[fallthrough]];
5331 case PPC::BI__builtin_pack_longdouble:
5332 if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
5333 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
5334 << "ibmlongdouble";
5335 return false;
5336 case PPC::BI__builtin_altivec_dst:
5337 case PPC::BI__builtin_altivec_dstt:
5338 case PPC::BI__builtin_altivec_dstst:
5339 case PPC::BI__builtin_altivec_dststt:
5340 return BuiltinConstantArgRange(TheCall, 2, 0, 3);
5341 case PPC::BI__builtin_vsx_xxpermdi:
5342 case PPC::BI__builtin_vsx_xxsldwi:
5343 return BuiltinVSX(TheCall);
5344 case PPC::BI__builtin_unpack_vector_int128:
5345 return BuiltinConstantArgRange(TheCall, 1, 0, 1);
5346 case PPC::BI__builtin_altivec_vgnb:
5347 return BuiltinConstantArgRange(TheCall, 1, 2, 7);
5348 case PPC::BI__builtin_vsx_xxeval:
5349 return BuiltinConstantArgRange(TheCall, 3, 0, 255);
5350 case PPC::BI__builtin_altivec_vsldbi:
5351 return BuiltinConstantArgRange(TheCall, 2, 0, 7);
5352 case PPC::BI__builtin_altivec_vsrdbi:
5353 return BuiltinConstantArgRange(TheCall, 2, 0, 7);
5354 case PPC::BI__builtin_vsx_xxpermx:
5355 return BuiltinConstantArgRange(TheCall, 3, 0, 7);
5356 case PPC::BI__builtin_ppc_tw:
5357 case PPC::BI__builtin_ppc_tdw:
5358 return BuiltinConstantArgRange(TheCall, 2, 1, 31);
5359 case PPC::BI__builtin_ppc_cmprb:
5360 return BuiltinConstantArgRange(TheCall, 0, 0, 1);
5361 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
5362 // be a constant that represents a contiguous bit field.
5363 case PPC::BI__builtin_ppc_rlwnm:
5364 return ValueIsRunOfOnes(TheCall, 2);
5365 case PPC::BI__builtin_ppc_rlwimi:
5366 return BuiltinConstantArgRange(TheCall, 2, 0, 31) ||
5367 ValueIsRunOfOnes(TheCall, 3);
5368 case PPC::BI__builtin_ppc_rldimi:
5369 return BuiltinConstantArgRange(TheCall, 2, 0, 63) ||
5370 ValueIsRunOfOnes(TheCall, 3);
5371 case PPC::BI__builtin_ppc_addex: {
5372 if (BuiltinConstantArgRange(TheCall, 2, 0, 3))
5373 return true;
5374 // Output warning for reserved values 1 to 3.
5375 int ArgValue =
5376 TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
5377 if (ArgValue != 0)
5378 Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
5379 << ArgValue;
5380 return false;
5381 }
5382 case PPC::BI__builtin_ppc_mtfsb0:
5383 case PPC::BI__builtin_ppc_mtfsb1:
5384 return BuiltinConstantArgRange(TheCall, 0, 0, 31);
5385 case PPC::BI__builtin_ppc_mtfsf:
5386 return BuiltinConstantArgRange(TheCall, 0, 0, 255);
5387 case PPC::BI__builtin_ppc_mtfsfi:
5388 return BuiltinConstantArgRange(TheCall, 0, 0, 7) ||
5389 BuiltinConstantArgRange(TheCall, 1, 0, 15);
5390 case PPC::BI__builtin_ppc_alignx:
5391 return BuiltinConstantArgPower2(TheCall, 0);
5392 case PPC::BI__builtin_ppc_rdlam:
5393 return ValueIsRunOfOnes(TheCall, 2);
5394 case PPC::BI__builtin_vsx_ldrmb:
5395 case PPC::BI__builtin_vsx_strmb:
5396 return BuiltinConstantArgRange(TheCall, 1, 1, 16);
5397 case PPC::BI__builtin_altivec_vcntmbb:
5398 case PPC::BI__builtin_altivec_vcntmbh:
5399 case PPC::BI__builtin_altivec_vcntmbw:
5400 case PPC::BI__builtin_altivec_vcntmbd:
5401 return BuiltinConstantArgRange(TheCall, 1, 0, 1);
5402 case PPC::BI__builtin_vsx_xxgenpcvbm:
5403 case PPC::BI__builtin_vsx_xxgenpcvhm:
5404 case PPC::BI__builtin_vsx_xxgenpcvwm:
5405 case PPC::BI__builtin_vsx_xxgenpcvdm:
5406 return BuiltinConstantArgRange(TheCall, 1, 0, 3);
5407 case PPC::BI__builtin_ppc_test_data_class: {
5408 // Check if the first argument of the __builtin_ppc_test_data_class call is
5409 // valid. The argument must be 'float' or 'double' or '__float128'.
5410 QualType ArgType = TheCall->getArg(0)->getType();
5411 if (ArgType != QualType(Context.FloatTy) &&
5412 ArgType != QualType(Context.DoubleTy) &&
5413 ArgType != QualType(Context.Float128Ty))
5414 return Diag(TheCall->getBeginLoc(),
5415 diag::err_ppc_invalid_test_data_class_type);
5416 return BuiltinConstantArgRange(TheCall, 1, 0, 127);
5417 }
5418 case PPC::BI__builtin_ppc_maxfe:
5419 case PPC::BI__builtin_ppc_minfe:
5420 case PPC::BI__builtin_ppc_maxfl:
5421 case PPC::BI__builtin_ppc_minfl:
5422 case PPC::BI__builtin_ppc_maxfs:
5423 case PPC::BI__builtin_ppc_minfs: {
5424 if (Context.getTargetInfo().getTriple().isOSAIX() &&
5425 (BuiltinID == PPC::BI__builtin_ppc_maxfe ||
5426 BuiltinID == PPC::BI__builtin_ppc_minfe))
5427 return Diag(TheCall->getBeginLoc(), diag::err_target_unsupported_type)
5428 << "builtin" << true << 128 << QualType(Context.LongDoubleTy)
5429 << false << Context.getTargetInfo().getTriple().str();
5430 // Argument type should be exact.
5432 if (BuiltinID == PPC::BI__builtin_ppc_maxfl ||
5433 BuiltinID == PPC::BI__builtin_ppc_minfl)
5434 ArgType = QualType(Context.DoubleTy);
5435 else if (BuiltinID == PPC::BI__builtin_ppc_maxfs ||
5436 BuiltinID == PPC::BI__builtin_ppc_minfs)
5437 ArgType = QualType(Context.FloatTy);
5438 for (unsigned I = 0, E = TheCall->getNumArgs(); I < E; ++I)
5439 if (TheCall->getArg(I)->getType() != ArgType)
5440 return Diag(TheCall->getBeginLoc(),
5441 diag::err_typecheck_convert_incompatible)
5442 << TheCall->getArg(I)->getType() << ArgType << 1 << 0 << 0;
5443 return false;
5444 }
5445#define CUSTOM_BUILTIN(Name, Intr, Types, Acc, Feature) \
5446 case PPC::BI__builtin_##Name: \
5447 return BuiltinPPCMMACall(TheCall, BuiltinID, Types);
5448#include "clang/Basic/BuiltinsPPC.def"
5449 }
5450 return BuiltinConstantArgRange(TheCall, i, l, u);
5451}
5452
5453// Check if the given type is a non-pointer PPC MMA type. This function is used
5454// in Sema to prevent invalid uses of restricted PPC MMA types.
5455bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
5456 if (Type->isPointerType() || Type->isArrayType())
5457 return false;
5458
5459 QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
5460#define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
5461 if (false
5462#include "clang/Basic/PPCTypes.def"
5463 ) {
5464 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
5465 return true;
5466 }
5467 return false;
5468}
5469
5470// Helper function for CheckHLSLBuiltinFunctionCall
5472 assert(TheCall->getNumArgs() > 1);
5473 ExprResult A = TheCall->getArg(0);
5474
5475 QualType ArgTyA = A.get()->getType();
5476
5477 auto *VecTyA = ArgTyA->getAs<VectorType>();
5478 SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5479
5480 for (unsigned i = 1; i < TheCall->getNumArgs(); ++i) {
5481 ExprResult B = TheCall->getArg(i);
5482 QualType ArgTyB = B.get()->getType();
5483 auto *VecTyB = ArgTyB->getAs<VectorType>();
5484 if (VecTyA == nullptr && VecTyB == nullptr)
5485 return false;
5486
5487 if (VecTyA && VecTyB) {
5488 bool retValue = false;
5489 if (VecTyA->getElementType() != VecTyB->getElementType()) {
5490 // Note: type promotion is intended to be handeled via the intrinsics
5491 // and not the builtin itself.
5492 S->Diag(TheCall->getBeginLoc(),
5493 diag::err_vec_builtin_incompatible_vector)
5494 << TheCall->getDirectCallee() << /*useAllTerminology*/ true
5495 << SourceRange(A.get()->getBeginLoc(), B.get()->getEndLoc());
5496 retValue = true;
5497 }
5498 if (VecTyA->getNumElements() != VecTyB->getNumElements()) {
5499 // You should only be hitting this case if you are calling the builtin
5500 // directly. HLSL intrinsics should avoid this case via a
5501 // HLSLVectorTruncation.
5502 S->Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5503 << TheCall->getDirectCallee() << /*useAllTerminology*/ true
5504 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5505 TheCall->getArg(1)->getEndLoc());
5506 retValue = true;
5507 }
5508 return retValue;
5509 }
5510 }
5511
5512 // Note: if we get here one of the args is a scalar which
5513 // requires a VectorSplat on Arg0 or Arg1
5514 S->Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5515 << TheCall->getDirectCallee() << /*useAllTerminology*/ true
5516 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5517 TheCall->getArg(1)->getEndLoc());
5518 return true;
5519}
5520
5522 Sema *S, CallExpr *TheCall, QualType ExpectedType,
5523 llvm::function_ref<bool(clang::QualType PassedType)> Check) {
5524 for (unsigned i = 0; i < TheCall->getNumArgs(); ++i) {
5525 QualType PassedType = TheCall->getArg(i)->getType();
5526 if (Check(PassedType)) {
5527 if (auto *VecTyA = PassedType->getAs<VectorType>())
5529 ExpectedType, VecTyA->getNumElements(), VecTyA->getVectorKind());
5530 S->Diag(TheCall->getArg(0)->getBeginLoc(),
5531 diag::err_typecheck_convert_incompatible)
5532 << PassedType << ExpectedType << 1 << 0 << 0;
5533 return true;
5534 }
5535 }
5536 return false;
5537}
5538
5540 auto checkAllFloatTypes = [](clang::QualType PassedType) -> bool {
5541 return !PassedType->hasFloatingRepresentation();
5542 };
5543 return CheckArgsTypesAreCorrect(S, TheCall, S->Context.FloatTy,
5544 checkAllFloatTypes);
5545}
5546
5548 auto checkFloatorHalf = [](clang::QualType PassedType) -> bool {
5549 clang::QualType BaseType =
5550 PassedType->isVectorType()
5551 ? PassedType->getAs<clang::VectorType>()->getElementType()
5552 : PassedType;
5553 return !BaseType->isHalfType() && !BaseType->isFloat32Type();
5554 };
5555 return CheckArgsTypesAreCorrect(S, TheCall, S->Context.FloatTy,
5556 checkFloatorHalf);
5557}
5558
5560 auto checkDoubleVector = [](clang::QualType PassedType) -> bool {
5561 if (const auto *VecTy = PassedType->getAs<VectorType>())
5562 return VecTy->getElementType()->isDoubleType();
5563 return false;
5564 };
5565 return CheckArgsTypesAreCorrect(S, TheCall, S->Context.FloatTy,
5566 checkDoubleVector);
5567}
5568
5570 auto checkAllUnsignedTypes = [](clang::QualType PassedType) -> bool {
5571 return !PassedType->hasUnsignedIntegerRepresentation();
5572 };
5573 return CheckArgsTypesAreCorrect(S, TheCall, S->Context.UnsignedIntTy,
5574 checkAllUnsignedTypes);
5575}
5576
5578 QualType ReturnType) {
5579 auto *VecTyA = TheCall->getArg(0)->getType()->getAs<VectorType>();
5580 if (VecTyA)
5581 ReturnType = S->Context.getVectorType(ReturnType, VecTyA->getNumElements(),
5583 TheCall->setType(ReturnType);
5584}
5585
5586// Note: returning true in this case results in CheckBuiltinFunctionCall
5587// returning an ExprError
5588bool Sema::CheckHLSLBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
5589 switch (BuiltinID) {
5590 case Builtin::BI__builtin_hlsl_elementwise_all:
5591 case Builtin::BI__builtin_hlsl_elementwise_any: {
5592 if (checkArgCount(*this, TheCall, 1))
5593 return true;
5594 break;
5595 }
5596 case Builtin::BI__builtin_hlsl_elementwise_clamp: {
5597 if (checkArgCount(*this, TheCall, 3))
5598 return true;
5599 if (CheckVectorElementCallArgs(this, TheCall))
5600 return true;
5601 if (BuiltinElementwiseTernaryMath(
5602 TheCall, /*CheckForFloatArgs*/
5603 TheCall->getArg(0)->getType()->hasFloatingRepresentation()))
5604 return true;
5605 break;
5606 }
5607 case Builtin::BI__builtin_hlsl_dot: {
5608 if (checkArgCount(*this, TheCall, 2))
5609 return true;
5610 if (CheckVectorElementCallArgs(this, TheCall))
5611 return true;
5612 if (BuiltinVectorToScalarMath(TheCall))
5613 return true;
5614 if (CheckNoDoubleVectors(this, TheCall))
5615 return true;
5616 break;
5617 }
5618 case Builtin::BI__builtin_hlsl_elementwise_rcp: {
5619 if (CheckAllArgsHaveFloatRepresentation(this, TheCall))
5620 return true;
5621 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5622 return true;
5623 break;
5624 }
5625 case Builtin::BI__builtin_hlsl_elementwise_rsqrt:
5626 case Builtin::BI__builtin_hlsl_elementwise_frac: {
5627 if (CheckFloatOrHalfRepresentations(this, TheCall))
5628 return true;
5629 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5630 return true;
5631 break;
5632 }
5633 case Builtin::BI__builtin_hlsl_elementwise_isinf: {
5634 if (CheckFloatOrHalfRepresentations(this, TheCall))
5635 return true;
5636 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5637 return true;
5638 SetElementTypeAsReturnType(this, TheCall, this->Context.BoolTy);
5639 break;
5640 }
5641 case Builtin::BI__builtin_hlsl_lerp: {
5642 if (checkArgCount(*this, TheCall, 3))
5643 return true;
5644 if (CheckVectorElementCallArgs(this, TheCall))
5645 return true;
5646 if (BuiltinElementwiseTernaryMath(TheCall))
5647 return true;
5648 if (CheckFloatOrHalfRepresentations(this, TheCall))
5649 return true;
5650 break;
5651 }
5652 case Builtin::BI__builtin_hlsl_mad: {
5653 if (checkArgCount(*this, TheCall, 3))
5654 return true;
5655 if (CheckVectorElementCallArgs(this, TheCall))
5656 return true;
5657 if (BuiltinElementwiseTernaryMath(
5658 TheCall, /*CheckForFloatArgs*/
5659 TheCall->getArg(0)->getType()->hasFloatingRepresentation()))
5660 return true;
5661 break;
5662 }
5663 // Note these are llvm builtins that we want to catch invalid intrinsic
5664 // generation. Normal handling of these builitns will occur elsewhere.
5665 case Builtin::BI__builtin_elementwise_bitreverse: {
5666 if (CheckUnsignedIntRepresentation(this, TheCall))
5667 return true;
5668 break;
5669 }
5670 case Builtin::BI__builtin_elementwise_ceil:
5671 case Builtin::BI__builtin_elementwise_cos:
5672 case Builtin::BI__builtin_elementwise_exp:
5673 case Builtin::BI__builtin_elementwise_exp2:
5674 case Builtin::BI__builtin_elementwise_floor:
5675 case Builtin::BI__builtin_elementwise_log:
5676 case Builtin::BI__builtin_elementwise_log2:
5677 case Builtin::BI__builtin_elementwise_log10:
5678 case Builtin::BI__builtin_elementwise_pow:
5679 case Builtin::BI__builtin_elementwise_roundeven:
5680 case Builtin::BI__builtin_elementwise_sin:
5681 case Builtin::BI__builtin_elementwise_sqrt:
5682 case Builtin::BI__builtin_elementwise_tan:
5683 case Builtin::BI__builtin_elementwise_trunc: {
5684 if (CheckFloatOrHalfRepresentations(this, TheCall))
5685 return true;
5686 break;
5687 }
5688 }
5689 return false;
5690}
5691
5692bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
5693 CallExpr *TheCall) {
5694 // position of memory order and scope arguments in the builtin
5695 unsigned OrderIndex, ScopeIndex;
5696 switch (BuiltinID) {
5697 case AMDGPU::BI__builtin_amdgcn_get_fpenv:
5698 case AMDGPU::BI__builtin_amdgcn_set_fpenv:
5699 return false;
5700 case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
5701 case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
5702 case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
5703 case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
5704 OrderIndex = 2;
5705 ScopeIndex = 3;
5706 break;
5707 case AMDGPU::BI__builtin_amdgcn_fence:
5708 OrderIndex = 0;
5709 ScopeIndex = 1;
5710 break;
5711 default:
5712 return false;
5713 }
5714
5715 ExprResult Arg = TheCall->getArg(OrderIndex);
5716 auto ArgExpr = Arg.get();
5717 Expr::EvalResult ArgResult;
5718
5719 if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
5720 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
5721 << ArgExpr->getType();
5722 auto Ord = ArgResult.Val.getInt().getZExtValue();
5723
5724 // Check validity of memory ordering as per C11 / C++11's memody model.
5725 // Only fence needs check. Atomic dec/inc allow all memory orders.
5726 if (!llvm::isValidAtomicOrderingCABI(Ord))
5727 return Diag(ArgExpr->getBeginLoc(),
5728 diag::warn_atomic_op_has_invalid_memory_order)
5729 << 0 << ArgExpr->getSourceRange();
5730 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
5731 case llvm::AtomicOrderingCABI::relaxed:
5732 case llvm::AtomicOrderingCABI::consume:
5733 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
5734 return Diag(ArgExpr->getBeginLoc(),
5735 diag::warn_atomic_op_has_invalid_memory_order)
5736 << 0 << ArgExpr->getSourceRange();
5737 break;
5738 case llvm::AtomicOrderingCABI::acquire:
5739 case llvm::AtomicOrderingCABI::release:
5740 case llvm::AtomicOrderingCABI::acq_rel:
5741 case llvm::AtomicOrderingCABI::seq_cst:
5742 break;
5743 }
5744
5745 Arg = TheCall->getArg(ScopeIndex);
5746 ArgExpr = Arg.get();
5747 Expr::EvalResult ArgResult1;
5748 // Check that sync scope is a constant literal
5749 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
5750 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
5751 << ArgExpr->getType();
5752
5753 return false;
5754}
5755
5756bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
5757 llvm::APSInt Result;
5758
5759 // We can't check the value of a dependent argument.
5760 Expr *Arg = TheCall->getArg(ArgNum);
5761 if (Arg->isTypeDependent() || Arg->isValueDependent())
5762 return false;
5763
5764 // Check constant-ness first.
5765 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5766 return true;
5767
5768 int64_t Val = Result.getSExtValue();
5769 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
5770 return false;
5771
5772 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
5773 << Arg->getSourceRange();
5774}
5775
5776static bool CheckInvalidVLENandLMUL(const TargetInfo &TI, CallExpr *TheCall,
5777 Sema &S, QualType Type, int EGW) {
5778 assert((EGW == 128 || EGW == 256) && "EGW can only be 128 or 256 bits");
5779
5780 // LMUL * VLEN >= EGW
5783 unsigned ElemSize = S.Context.getTypeSize(Info.ElementType);
5784 unsigned MinElemCount = Info.EC.getKnownMinValue();
5785
5786 unsigned EGS = EGW / ElemSize;
5787 // If EGS is less than or equal to the minimum number of elements, then the
5788 // type is valid.
5789 if (EGS <= MinElemCount)
5790 return false;
5791
5792 // Otherwise, we need vscale to be at least EGS / MinElemCont.
5793 assert(EGS % MinElemCount == 0);
5794 unsigned VScaleFactor = EGS / MinElemCount;
5795 // Vscale is VLEN/RVVBitsPerBlock.
5796 unsigned MinRequiredVLEN = VScaleFactor * llvm::RISCV::RVVBitsPerBlock;
5797 std::string RequiredExt = "zvl" + std::to_string(MinRequiredVLEN) + "b";
5798 if (!TI.hasFeature(RequiredExt))
5799 return S.Diag(TheCall->getBeginLoc(),
5800 diag::err_riscv_type_requires_extension) << Type << RequiredExt;
5801
5802 return false;
5803}
5804
5805bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
5806 unsigned BuiltinID,
5807 CallExpr *TheCall) {
5808 // vmulh.vv, vmulh.vx, vmulhu.vv, vmulhu.vx, vmulhsu.vv, vmulhsu.vx,
5809 // vsmul.vv, vsmul.vx are not included for EEW=64 in Zve64*.
5810 switch (BuiltinID) {
5811 default:
5812 break;
5813 case RISCVVector::BI__builtin_rvv_vmulhsu_vv:
5814 case RISCVVector::BI__builtin_rvv_vmulhsu_vx:
5815 case RISCVVector::BI__builtin_rvv_vmulhsu_vv_tu:
5816 case RISCVVector::BI__builtin_rvv_vmulhsu_vx_tu:
5817 case RISCVVector::BI__builtin_rvv_vmulhsu_vv_m:
5818 case RISCVVector::BI__builtin_rvv_vmulhsu_vx_m:
5819 case RISCVVector::BI__builtin_rvv_vmulhsu_vv_mu:
5820 case RISCVVector::BI__builtin_rvv_vmulhsu_vx_mu:
5821 case RISCVVector::BI__builtin_rvv_vmulhsu_vv_tum:
5822 case RISCVVector::BI__builtin_rvv_vmulhsu_vx_tum:
5823 case RISCVVector::BI__builtin_rvv_vmulhsu_vv_tumu:
5824 case RISCVVector::BI__builtin_rvv_vmulhsu_vx_tumu:
5825 case RISCVVector::BI__builtin_rvv_vmulhu_vv:
5826 case RISCVVector::BI__builtin_rvv_vmulhu_vx:
5827 case RISCVVector::BI__builtin_rvv_vmulhu_vv_tu:
5828 case RISCVVector::BI__builtin_rvv_vmulhu_vx_tu:
5829 case RISCVVector::BI__builtin_rvv_vmulhu_vv_m:
5830 case RISCVVector::BI__builtin_rvv_vmulhu_vx_m:
5831 case RISCVVector::BI__builtin_rvv_vmulhu_vv_mu:
5832 case RISCVVector::BI__builtin_rvv_vmulhu_vx_mu:
5833 case RISCVVector::BI__builtin_rvv_vmulhu_vv_tum:
5834 case RISCVVector::BI__builtin_rvv_vmulhu_vx_tum:
5835 case RISCVVector::BI__builtin_rvv_vmulhu_vv_tumu:
5836 case RISCVVector::BI__builtin_rvv_vmulhu_vx_tumu:
5837 case RISCVVector::BI__builtin_rvv_vmulh_vv:
5838 case RISCVVector::BI__builtin_rvv_vmulh_vx:
5839 case RISCVVector::BI__builtin_rvv_vmulh_vv_tu:
5840 case RISCVVector::BI__builtin_rvv_vmulh_vx_tu:
5841 case RISCVVector::BI__builtin_rvv_vmulh_vv_m:
5842 case RISCVVector::BI__builtin_rvv_vmulh_vx_m:
5843 case RISCVVector::BI__builtin_rvv_vmulh_vv_mu:
5844 case RISCVVector::BI__builtin_rvv_vmulh_vx_mu:
5845 case RISCVVector::BI__builtin_rvv_vmulh_vv_tum:
5846 case RISCVVector::BI__builtin_rvv_vmulh_vx_tum:
5847 case RISCVVector::BI__builtin_rvv_vmulh_vv_tumu:
5848 case RISCVVector::BI__builtin_rvv_vmulh_vx_tumu:
5849 case RISCVVector::BI__builtin_rvv_vsmul_vv:
5850 case RISCVVector::BI__builtin_rvv_vsmul_vx:
5851 case RISCVVector::BI__builtin_rvv_vsmul_vv_tu:
5852 case RISCVVector::BI__builtin_rvv_vsmul_vx_tu:
5853 case RISCVVector::BI__builtin_rvv_vsmul_vv_m:
5854 case RISCVVector::BI__builtin_rvv_vsmul_vx_m:
5855 case RISCVVector::BI__builtin_rvv_vsmul_vv_mu:
5856 case RISCVVector::BI__builtin_rvv_vsmul_vx_mu:
5857 case RISCVVector::BI__builtin_rvv_vsmul_vv_tum:
5858 case RISCVVector::BI__builtin_rvv_vsmul_vx_tum:
5859 case RISCVVector::BI__builtin_rvv_vsmul_vv_tumu:
5860 case RISCVVector::BI__builtin_rvv_vsmul_vx_tumu: {
5862 TheCall->getType()->castAs<BuiltinType>());
5863
5864 if (Context.getTypeSize(Info.ElementType) == 64 && !TI.hasFeature("v"))
5865 return Diag(TheCall->getBeginLoc(),
5866 diag::err_riscv_builtin_requires_extension)
5867 << /* IsExtension */ true << TheCall->getSourceRange() << "v";
5868
5869 break;
5870 }
5871 }
5872
5873 switch (BuiltinID) {
5874 case RISCVVector::BI__builtin_rvv_vsetvli:
5875 return BuiltinConstantArgRange(TheCall, 1, 0, 3) ||
5876 CheckRISCVLMUL(TheCall, 2);
5877 case RISCVVector::BI__builtin_rvv_vsetvlimax:
5878 return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
5879 CheckRISCVLMUL(TheCall, 1);
5880 case RISCVVector::BI__builtin_rvv_vget_v: {
5882 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
5883 TheCall->getType().getCanonicalType().getTypePtr()));
5885 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
5886 TheCall->getArg(0)->getType().getCanonicalType().getTypePtr()));
5887 unsigned MaxIndex;
5888 if (VecInfo.NumVectors != 1) // vget for tuple type
5889 MaxIndex = VecInfo.NumVectors;
5890 else // vget for non-tuple type
5891 MaxIndex = (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors) /
5892 (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors);
5893 return BuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1);
5894 }
5895 case RISCVVector::BI__builtin_rvv_vset_v: {
5897 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
5898 TheCall->getType().getCanonicalType().getTypePtr()));
5900 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
5901 TheCall->getArg(2)->getType().getCanonicalType().getTypePtr()));
5902 unsigned MaxIndex;
5903 if (ResVecInfo.NumVectors != 1) // vset for tuple type
5904 MaxIndex = ResVecInfo.NumVectors;
5905 else // vset fo non-tuple type
5906 MaxIndex = (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors) /
5907 (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors);
5908 return BuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1);
5909 }
5910 // Vector Crypto
5911 case RISCVVector::BI__builtin_rvv_vaeskf1_vi_tu:
5912 case RISCVVector::BI__builtin_rvv_vaeskf2_vi_tu:
5913 case RISCVVector::BI__builtin_rvv_vaeskf2_vi:
5914 case RISCVVector::BI__builtin_rvv_vsm4k_vi_tu: {
5915 QualType Op1Type = TheCall->getArg(0)->getType();
5916 QualType Op2Type = TheCall->getArg(1)->getType();
5917 return CheckInvalidVLENandLMUL(TI, TheCall, *this, Op1Type, 128) ||
5918 CheckInvalidVLENandLMUL(TI, TheCall, *this, Op2Type, 128) ||
5919 BuiltinConstantArgRange(TheCall, 2, 0, 31);
5920 }
5921 case RISCVVector::BI__builtin_rvv_vsm3c_vi_tu:
5922 case RISCVVector::BI__builtin_rvv_vsm3c_vi: {
5923 QualType Op1Type = TheCall->getArg(0)->getType();
5924 return CheckInvalidVLENandLMUL(TI, TheCall, *this, Op1Type, 256) ||
5925 BuiltinConstantArgRange(TheCall, 2, 0, 31);
5926 }
5927 case RISCVVector::BI__builtin_rvv_vaeskf1_vi:
5928 case RISCVVector::BI__builtin_rvv_vsm4k_vi: {
5929 QualType Op1Type = TheCall->getArg(0)->getType();
5930 return CheckInvalidVLENandLMUL(TI, TheCall, *this, Op1Type, 128) ||
5931 BuiltinConstantArgRange(TheCall, 1, 0, 31);
5932 }
5933 case RISCVVector::BI__builtin_rvv_vaesdf_vv:
5934 case RISCVVector::BI__builtin_rvv_vaesdf_vs:
5935 case RISCVVector::BI__builtin_rvv_vaesdm_vv:
5936 case RISCVVector::BI__builtin_rvv_vaesdm_vs:
5937 case RISCVVector::BI__builtin_rvv_vaesef_vv:
5938 case RISCVVector::BI__builtin_rvv_vaesef_vs:
5939 case RISCVVector::BI__builtin_rvv_vaesem_vv:
5940 case RISCVVector::BI__builtin_rvv_vaesem_vs:
5941 case RISCVVector::BI__builtin_rvv_vaesz_vs:
5942 case RISCVVector::BI__builtin_rvv_vsm4r_vv:
5943 case RISCVVector::BI__builtin_rvv_vsm4r_vs:
5944 case RISCVVector::BI__builtin_rvv_vaesdf_vv_tu:
5945 case RISCVVector::BI__builtin_rvv_vaesdf_vs_tu:
5946 case RISCVVector::BI__builtin_rvv_vaesdm_vv_tu:
5947 case RISCVVector::BI__builtin_rvv_vaesdm_vs_tu:
5948 case RISCVVector::BI__builtin_rvv_vaesef_vv_tu:
5949 case RISCVVector::BI__builtin_rvv_vaesef_vs_tu:
5950 case RISCVVector::BI__builtin_rvv_vaesem_vv_tu:
5951 case RISCVVector::BI__builtin_rvv_vaesem_vs_tu:
5952 case RISCVVector::BI__builtin_rvv_vaesz_vs_tu:
5953 case RISCVVector::BI__builtin_rvv_vsm4r_vv_tu:
5954 case RISCVVector::BI__builtin_rvv_vsm4r_vs_tu: {
5955 QualType Op1Type = TheCall->getArg(0)->getType();
5956 QualType Op2Type = TheCall->getArg(1)->getType();
5957 return CheckInvalidVLENandLMUL(TI, TheCall, *this, Op1Type, 128) ||
5958 CheckInvalidVLENandLMUL(TI, TheCall, *this, Op2Type, 128);
5959 }
5960 case RISCVVector::BI__builtin_rvv_vsha2ch_vv:
5961 case RISCVVector::BI__builtin_rvv_vsha2cl_vv:
5962 case RISCVVector::BI__builtin_rvv_vsha2ms_vv:
5963 case RISCVVector::BI__builtin_rvv_vsha2ch_vv_tu:
5964 case RISCVVector::BI__builtin_rvv_vsha2cl_vv_tu:
5965 case RISCVVector::BI__builtin_rvv_vsha2ms_vv_tu: {
5966 QualType Op1Type = TheCall->getArg(0)->getType();
5967 QualType Op2Type = TheCall->getArg(1)->getType();
5968 QualType Op3Type = TheCall->getArg(2)->getType();
5971 uint64_t ElemSize = Context.getTypeSize(Info.ElementType);
5972 if (ElemSize == 64 && !TI.hasFeature("zvknhb"))
5973 return Diag(TheCall->getBeginLoc(),
5974 diag::err_riscv_builtin_requires_extension)
5975 << /* IsExtension */ true << TheCall->getSourceRange() << "zvknb";
5976
5977 return CheckInvalidVLENandLMUL(TI, TheCall, *this, Op1Type, ElemSize * 4) ||
5978 CheckInvalidVLENandLMUL(TI, TheCall, *this, Op2Type, ElemSize * 4) ||
5979 CheckInvalidVLENandLMUL(TI, TheCall, *this, Op3Type, ElemSize * 4);
5980 }
5981
5982 case RISCVVector::BI__builtin_rvv_sf_vc_i_se:
5983 // bit_27_26, bit_24_20, bit_11_7, simm5, sew, log2lmul
5984 return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
5985 BuiltinConstantArgRange(TheCall, 1, 0, 31) ||
5986 BuiltinConstantArgRange(TheCall, 2, 0, 31) ||
5987 BuiltinConstantArgRange(TheCall, 3, -16, 15) ||
5988 CheckRISCVLMUL(TheCall, 5);
5989 case RISCVVector::BI__builtin_rvv_sf_vc_iv_se:
5990 // bit_27_26, bit_11_7, vs2, simm5
5991 return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
5992 BuiltinConstantArgRange(TheCall, 1, 0, 31) ||
5993 BuiltinConstantArgRange(TheCall, 3, -16, 15);
5994 case RISCVVector::BI__builtin_rvv_sf_vc_v_i:
5995 case RISCVVector::BI__builtin_rvv_sf_vc_v_i_se:
5996 // bit_27_26, bit_24_20, simm5
5997 return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
5998 BuiltinConstantArgRange(TheCall, 1, 0, 31) ||
5999 BuiltinConstantArgRange(TheCall, 2, -16, 15);
6000 case RISCVVector::BI__builtin_rvv_sf_vc_v_iv:
6001 case RISCVVector::BI__builtin_rvv_sf_vc_v_iv_se:
6002 // bit_27_26, vs2, simm5
6003 return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
6004 BuiltinConstantArgRange(TheCall, 2, -16, 15);
6005 case RISCVVector::BI__builtin_rvv_sf_vc_ivv_se:
6006 case RISCVVector::BI__builtin_rvv_sf_vc_ivw_se:
6007 case RISCVVector::BI__builtin_rvv_sf_vc_v_ivv:
6008 case RISCVVector::BI__builtin_rvv_sf_vc_v_ivw:
6009 case RISCVVector::BI__builtin_rvv_sf_vc_v_ivv_se:
6010 case RISCVVector::BI__builtin_rvv_sf_vc_v_ivw_se:
6011 // bit_27_26, vd, vs2, simm5
6012 return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
6013 BuiltinConstantArgRange(TheCall, 3, -16, 15);
6014 case RISCVVector::BI__builtin_rvv_sf_vc_x_se:
6015 // bit_27_26, bit_24_20, bit_11_7, xs1, sew, log2lmul
6016 return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
6017 BuiltinConstantArgRange(TheCall, 1, 0, 31) ||
6018 BuiltinConstantArgRange(TheCall, 2, 0, 31) ||
6019 CheckRISCVLMUL(TheCall, 5);
6020 case RISCVVector::BI__builtin_rvv_sf_vc_xv_se:
6021 case RISCVVector::BI__builtin_rvv_sf_vc_vv_se:
6022 // bit_27_26, bit_11_7, vs2, xs1/vs1
6023 case RISCVVector::BI__builtin_rvv_sf_vc_v_x:
6024 case RISCVVector::BI__builtin_rvv_sf_vc_v_x_se:
6025 // bit_27_26, bit_24-20, xs1
6026 return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
6027 BuiltinConstantArgRange(TheCall, 1, 0, 31);
6028 case RISCVVector::BI__builtin_rvv_sf_vc_vvv_se:
6029 case RISCVVector::BI__builtin_rvv_sf_vc_xvv_se:
6030 case RISCVVector::BI__builtin_rvv_sf_vc_vvw_se:
6031 case RISCVVector::BI__builtin_rvv_sf_vc_xvw_se:
6032 // bit_27_26, vd, vs2, xs1
6033 case RISCVVector::BI__builtin_rvv_sf_vc_v_xv:
6034 case RISCVVector::BI__builtin_rvv_sf_vc_v_vv:
6035 case RISCVVector::BI__builtin_rvv_sf_vc_v_xv_se:
6036 case RISCVVector::BI__builtin_rvv_sf_vc_v_vv_se:
6037 // bit_27_26, vs2, xs1/vs1
6038 case RISCVVector::BI__builtin_rvv_sf_vc_v_xvv:
6039 case RISCVVector::BI__builtin_rvv_sf_vc_v_vvv:
6040 case RISCVVector::BI__builtin_rvv_sf_vc_v_xvw:
6041 case RISCVVector::BI__builtin_rvv_sf_vc_v_vvw:
6042 case RISCVVector::BI__builtin_rvv_sf_vc_v_xvv_se:
6043 case RISCVVector::BI__builtin_rvv_sf_vc_v_vvv_se:
6044 case RISCVVector::BI__builtin_rvv_sf_vc_v_xvw_se:
6045 case RISCVVector::BI__builtin_rvv_sf_vc_v_vvw_se:
6046 // bit_27_26, vd, vs2, xs1/vs1
6047 return BuiltinConstantArgRange(TheCall, 0, 0, 3);
6048 case RISCVVector::BI__builtin_rvv_sf_vc_fv_se:
6049 // bit_26, bit_11_7, vs2, fs1
6050 return BuiltinConstantArgRange(TheCall, 0, 0, 1) ||
6051 BuiltinConstantArgRange(TheCall, 1, 0, 31);
6052 case RISCVVector::BI__builtin_rvv_sf_vc_fvv_se:
6053 case RISCVVector::BI__builtin_rvv_sf_vc_fvw_se:
6054 case RISCVVector::BI__builtin_rvv_sf_vc_v_fvv:
6055 case RISCVVector::BI__builtin_rvv_sf_vc_v_fvw:
6056 case RISCVVector::BI__builtin_rvv_sf_vc_v_fvv_se:
6057 case RISCVVector::BI__builtin_rvv_sf_vc_v_fvw_se:
6058 // bit_26, vd, vs2, fs1
6059 case RISCVVector::BI__builtin_rvv_sf_vc_v_fv:
6060 case RISCVVector::BI__builtin_rvv_sf_vc_v_fv_se:
6061 // bit_26, vs2, fs1
6062 return BuiltinConstantArgRange(TheCall, 0, 0, 1);
6063 // Check if byteselect is in [0, 3]
6064 case RISCV::BI__builtin_riscv_aes32dsi:
6065 case RISCV::BI__builtin_riscv_aes32dsmi:
6066 case RISCV::BI__builtin_riscv_aes32esi:
6067 case RISCV::BI__builtin_riscv_aes32esmi:
6068 case RISCV::BI__builtin_riscv_sm4ks:
6069 case RISCV::BI__builtin_riscv_sm4ed:
6070 return BuiltinConstantArgRange(TheCall, 2, 0, 3);
6071 // Check if rnum is in [0, 10]
6072 case RISCV::BI__builtin_riscv_aes64ks1i:
6073 return BuiltinConstantArgRange(TheCall, 1, 0, 10);
6074 // Check if value range for vxrm is in [0, 3]
6075 case RISCVVector::BI__builtin_rvv_vaaddu_vv:
6076 case RISCVVector::BI__builtin_rvv_vaaddu_vx:
6077 case RISCVVector::BI__builtin_rvv_vaadd_vv:
6078 case RISCVVector::BI__builtin_rvv_vaadd_vx:
6079 case RISCVVector::BI__builtin_rvv_vasubu_vv:
6080 case RISCVVector::BI__builtin_rvv_vasubu_vx:
6081 case RISCVVector::BI__builtin_rvv_vasub_vv:
6082 case RISCVVector::BI__builtin_rvv_vasub_vx:
6083 case RISCVVector::BI__builtin_rvv_vsmul_vv:
6084 case RISCVVector::BI__builtin_rvv_vsmul_vx:
6085 case RISCVVector::BI__builtin_rvv_vssra_vv:
6086 case RISCVVector::BI__builtin_rvv_vssra_vx:
6087 case RISCVVector::BI__builtin_rvv_vssrl_vv:
6088 case RISCVVector::BI__builtin_rvv_vssrl_vx:
6089 case RISCVVector::BI__builtin_rvv_vnclip_wv:
6090 case RISCVVector::BI__builtin_rvv_vnclip_wx:
6091 case RISCVVector::BI__builtin_rvv_vnclipu_wv:
6092 case RISCVVector::BI__builtin_rvv_vnclipu_wx:
6093 return BuiltinConstantArgRange(TheCall, 2, 0, 3);
6094 case RISCVVector::BI__builtin_rvv_vaaddu_vv_tu:
6095 case RISCVVector::BI__builtin_rvv_vaaddu_vx_tu:
6096 case RISCVVector::BI__builtin_rvv_vaadd_vv_tu:
6097 case RISCVVector::BI__builtin_rvv_vaadd_vx_tu:
6098 case RISCVVector::BI__builtin_rvv_vasubu_vv_tu:
6099 case RISCVVector::BI__builtin_rvv_vasubu_vx_tu:
6100 case RISCVVector::BI__builtin_rvv_vasub_vv_tu:
6101 case RISCVVector::BI__builtin_rvv_vasub_vx_tu:
6102 case RISCVVector::BI__builtin_rvv_vsmul_vv_tu:
6103 case RISCVVector::BI__builtin_rvv_vsmul_vx_tu:
6104 case RISCVVector::BI__builtin_rvv_vssra_vv_tu:
6105 case RISCVVector::BI__builtin_rvv_vssra_vx_tu:
6106 case RISCVVector::BI__builtin_rvv_vssrl_vv_tu:
6107 case RISCVVector::BI__builtin_rvv_vssrl_vx_tu:
6108 case RISCVVector::BI__builtin_rvv_vnclip_wv_tu:
6109 case RISCVVector::BI__builtin_rvv_vnclip_wx_tu:
6110 case RISCVVector::BI__builtin_rvv_vnclipu_wv_tu:
6111 case RISCVVector::BI__builtin_rvv_vnclipu_wx_tu:
6112 case RISCVVector::BI__builtin_rvv_vaaddu_vv_m:
6113 case RISCVVector::BI__builtin_rvv_vaaddu_vx_m:
6114 case RISCVVector::BI__builtin_rvv_vaadd_vv_m:
6115 case RISCVVector::BI__builtin_rvv_vaadd_vx_m:
6116 case RISCVVector::BI__builtin_rvv_vasubu_vv_m:
6117 case RISCVVector::BI__builtin_rvv_vasubu_vx_m:
6118 case RISCVVector::BI__builtin_rvv_vasub_vv_m:
6119 case RISCVVector::BI__builtin_rvv_vasub_vx_m:
6120 case RISCVVector::BI__builtin_rvv_vsmul_vv_m:
6121 case RISCVVector::BI__builtin_rvv_vsmul_vx_m:
6122 case RISCVVector::BI__builtin_rvv_vssra_vv_m:
6123 case RISCVVector::BI__builtin_rvv_vssra_vx_m:
6124 case RISCVVector::BI__builtin_rvv_vssrl_vv_m:
6125 case RISCVVector::BI__builtin_rvv_vssrl_vx_m:
6126 case RISCVVector::BI__builtin_rvv_vnclip_wv_m:
6127 case RISCVVector::BI__builtin_rvv_vnclip_wx_m:
6128 case RISCVVector::BI__builtin_rvv_vnclipu_wv_m:
6129 case RISCVVector::BI__builtin_rvv_vnclipu_wx_m:
6130 return BuiltinConstantArgRange(TheCall, 3, 0, 3);
6131 case RISCVVector::BI__builtin_rvv_vaaddu_vv_tum:
6132 case RISCVVector::BI__builtin_rvv_vaaddu_vv_tumu:
6133 case RISCVVector::BI__builtin_rvv_vaaddu_vv_mu:
6134 case RISCVVector::BI__builtin_rvv_vaaddu_vx_tum:
6135 case RISCVVector::BI__builtin_rvv_vaaddu_vx_tumu:
6136 case RISCVVector::BI__builtin_rvv_vaaddu_vx_mu:
6137 case RISCVVector::BI__builtin_rvv_vaadd_vv_tum:
6138 case RISCVVector::BI__builtin_rvv_vaadd_vv_tumu:
6139 case RISCVVector::BI__builtin_rvv_vaadd_vv_mu:
6140 case RISCVVector::BI__builtin_rvv_vaadd_vx_tum:
6141 case RISCVVector::BI__builtin_rvv_vaadd_vx_tumu:
6142 case RISCVVector::BI__builtin_rvv_vaadd_vx_mu:
6143 case RISCVVector::BI__builtin_rvv_vasubu_vv_tum:
6144 case RISCVVector::BI__builtin_rvv_vasubu_vv_tumu:
6145 case RISCVVector::BI__builtin_rvv_vasubu_vv_mu:
6146 case RISCVVector::BI__builtin_rvv_vasubu_vx_tum:
6147 case RISCVVector::BI__builtin_rvv_vasubu_vx_tumu:
6148 case RISCVVector::BI__builtin_rvv_vasubu_vx_mu:
6149 case RISCVVector::BI__builtin_rvv_vasub_vv_tum:
6150 case RISCVVector::BI__builtin_rvv_vasub_vv_tumu:
6151 case RISCVVector::BI__builtin_rvv_vasub_vv_mu:
6152 case RISCVVector::BI__builtin_rvv_vasub_vx_tum:
6153 case RISCVVector::BI__builtin_rvv_vasub_vx_tumu:
6154 case RISCVVector::BI__builtin_rvv_vasub_vx_mu:
6155 case RISCVVector::BI__builtin_rvv_vsmul_vv_mu:
6156 case RISCVVector::BI__builtin_rvv_vsmul_vx_mu:
6157 case RISCVVector::BI__builtin_rvv_vssra_vv_mu:
6158 case RISCVVector::BI__builtin_rvv_vssra_vx_mu:
6159 case RISCVVector::BI__builtin_rvv_vssrl_vv_mu:
6160 case RISCVVector::BI__builtin_rvv_vssrl_vx_mu:
6161 case RISCVVector::BI__builtin_rvv_vnclip_wv_mu:
6162 case RISCVVector::BI__builtin_rvv_vnclip_wx_mu:
6163 case RISCVVector::BI__builtin_rvv_vnclipu_wv_mu:
6164 case RISCVVector::BI__builtin_rvv_vnclipu_wx_mu:
6165 case RISCVVector::BI__builtin_rvv_vsmul_vv_tum:
6166 case RISCVVector::BI__builtin_rvv_vsmul_vx_tum:
6167 case RISCVVector::BI__builtin_rvv_vssra_vv_tum:
6168 case RISCVVector::BI__builtin_rvv_vssra_vx_tum:
6169 case RISCVVector::BI__builtin_rvv_vssrl_vv_tum:
6170 case RISCVVector::BI__builtin_rvv_vssrl_vx_tum:
6171 case RISCVVector::BI__builtin_rvv_vnclip_wv_tum:
6172 case RISCVVector::BI__builtin_rvv_vnclip_wx_tum:
6173 case RISCVVector::BI__builtin_rvv_vnclipu_wv_tum:
6174 case RISCVVector::BI__builtin_rvv_vnclipu_wx_tum:
6175 case RISCVVector::BI__builtin_rvv_vsmul_vv_tumu:
6176 case RISCVVector::BI__builtin_rvv_vsmul_vx_tumu:
6177 case RISCVVector::BI__builtin_rvv_vssra_vv_tumu:
6178 case RISCVVector::BI__builtin_rvv_vssra_vx_tumu:
6179 case RISCVVector::BI__builtin_rvv_vssrl_vv_tumu:
6180 case RISCVVector::BI__builtin_rvv_vssrl_vx_tumu:
6181 case RISCVVector::BI__builtin_rvv_vnclip_wv_tumu:
6182 case RISCVVector::BI__builtin_rvv_vnclip_wx_tumu:
6183 case RISCVVector::BI__builtin_rvv_vnclipu_wv_tumu:
6184 case RISCVVector::BI__builtin_rvv_vnclipu_wx_tumu:
6185 return BuiltinConstantArgRange(TheCall, 4, 0, 3);
6186 case RISCVVector::BI__builtin_rvv_vfsqrt_v_rm:
6187 case RISCVVector::BI__builtin_rvv_vfrec7_v_rm:
6188 case RISCVVector::BI__builtin_rvv_vfcvt_x_f_v_rm:
6189 case RISCVVector::BI__builtin_rvv_vfcvt_xu_f_v_rm:
6190 case RISCVVector::BI__builtin_rvv_vfcvt_f_x_v_rm:
6191 case RISCVVector::BI__builtin_rvv_vfcvt_f_xu_v_rm:
6192 case RISCVVector::BI__builtin_rvv_vfwcvt_x_f_v_rm:
6193 case RISCVVector::BI__builtin_rvv_vfwcvt_xu_f_v_rm:
6194 case RISCVVector::BI__builtin_rvv_vfncvt_x_f_w_rm:
6195 case RISCVVector::BI__builtin_rvv_vfncvt_xu_f_w_rm:
6196 case RISCVVector::BI__builtin_rvv_vfncvt_f_x_w_rm:
6197 case RISCVVector::BI__builtin_rvv_vfncvt_f_xu_w_rm:
6198 case RISCVVector::BI__builtin_rvv_vfncvt_f_f_w_rm:
6199 return BuiltinConstantArgRange(TheCall, 1, 0, 4);
6200 case RISCVVector::BI__builtin_rvv_vfadd_vv_rm:
6201 case RISCVVector::BI__builtin_rvv_vfadd_vf_rm:
6202 case RISCVVector::BI__builtin_rvv_vfsub_vv_rm:
6203 case RISCVVector::BI__builtin_rvv_vfsub_vf_rm:
6204 case RISCVVector::BI__builtin_rvv_vfrsub_vf_rm:
6205 case RISCVVector::BI__builtin_rvv_vfwadd_vv_rm:
6206 case RISCVVector::BI__builtin_rvv_vfwadd_vf_rm:
6207 case RISCVVector::BI__builtin_rvv_vfwsub_vv_rm:
6208 case RISCVVector::BI__builtin_rvv_vfwsub_vf_rm:
6209 case RISCVVector::BI__builtin_rvv_vfwadd_wv_rm:
6210 case RISCVVector::BI__builtin_rvv_vfwadd_wf_rm:
6211 case RISCVVector::BI__builtin_rvv_vfwsub_wv_rm:
6212 case RISCVVector::BI__builtin_rvv_vfwsub_wf_rm:
6213 case RISCVVector::BI__builtin_rvv_vfmul_vv_rm:
6214 case RISCVVector::BI__builtin_rvv_vfmul_vf_rm:
6215 case RISCVVector::BI__builtin_rvv_vfdiv_vv_rm:
6216 case RISCVVector::BI__builtin_rvv_vfdiv_vf_rm:
6217 case RISCVVector::BI__builtin_rvv_vfrdiv_vf_rm:
6218 case RISCVVector::BI__builtin_rvv_vfwmul_vv_rm:
6219 case RISCVVector::BI__builtin_rvv_vfwmul_vf_rm:
6220 case RISCVVector::BI__builtin_rvv_vfredosum_vs_rm:
6221 case RISCVVector::BI__builtin_rvv_vfredusum_vs_rm:
6222 case RISCVVector::BI__builtin_rvv_vfwredosum_vs_rm:
6223 case RISCVVector::BI__builtin_rvv_vfwredusum_vs_rm:
6224 case RISCVVector::BI__builtin_rvv_vfsqrt_v_rm_tu:
6225 case RISCVVector::BI__builtin_rvv_vfrec7_v_rm_tu:
6226 case RISCVVector::BI__builtin_rvv_vfcvt_x_f_v_rm_tu:
6227 case RISCVVector::BI__builtin_rvv_vfcvt_xu_f_v_rm_tu:
6228 case RISCVVector::BI__builtin_rvv_vfcvt_f_x_v_rm_tu:
6229 case RISCVVector::BI__builtin_rvv_vfcvt_f_xu_v_rm_tu:
6230 case RISCVVector::BI__builtin_rvv_vfwcvt_x_f_v_rm_tu:
6231 case RISCVVector::BI__builtin_rvv_vfwcvt_xu_f_v_rm_tu:
6232 case RISCVVector::BI__builtin_rvv_vfncvt_x_f_w_rm_tu:
6233 case RISCVVector::BI__builtin_rvv_vfncvt_xu_f_w_rm_tu:
6234 case RISCVVector::BI__builtin_rvv_vfncvt_f_x_w_rm_tu:
6235 case RISCVVector::BI__builtin_rvv_vfncvt_f_xu_w_rm_tu:
6236 case RISCVVector::BI__builtin_rvv_vfncvt_f_f_w_rm_tu:
6237 case RISCVVector::BI__builtin_rvv_vfsqrt_v_rm_m:
6238 case RISCVVector::BI__builtin_rvv_vfrec7_v_rm_m:
6239 case RISCVVector::BI__builtin_rvv_vfcvt_x_f_v_rm_m:
6240 case RISCVVector::BI__builtin_rvv_vfcvt_xu_f_v_rm_m:
6241 case RISCVVector::BI__builtin_rvv_vfcvt_f_x_v_rm_m:
6242 case RISCVVector::BI__builtin_rvv_vfcvt_f_xu_v_rm_m:
6243 case RISCVVector::BI__builtin_rvv_vfwcvt_x_f_v_rm_m:
6244 case RISCVVector::BI__builtin_rvv_vfwcvt_xu_f_v_rm_m:
6245 case RISCVVector::BI__builtin_rvv_vfncvt_x_f_w_rm_m:
6246 case RISCVVector::BI__builtin_rvv_vfncvt_xu_f_w_rm_m:
6247 case RISCVVector::BI__builtin_rvv_vfncvt_f_x_w_rm_m:
6248 case RISCVVector::BI__builtin_rvv_vfncvt_f_xu_w_rm_m:
6249 case RISCVVector::BI__builtin_rvv_vfncvt_f_f_w_rm_m:
6250 return BuiltinConstantArgRange(TheCall, 2, 0, 4);
6251 case RISCVVector::BI__builtin_rvv_vfadd_vv_rm_tu:
6252 case RISCVVector::BI__builtin_rvv_vfadd_vf_rm_tu:
6253 case RISCVVector::BI__builtin_rvv_vfsub_vv_rm_tu:
6254 case RISCVVector::BI__builtin_rvv_vfsub_vf_rm_tu:
6255 case RISCVVector::BI__builtin_rvv_vfrsub_vf_rm_tu:
6256 case RISCVVector::BI__builtin_rvv_vfwadd_vv_rm_tu:
6257 case RISCVVector::BI__builtin_rvv_vfwadd_vf_rm_tu:
6258 case RISCVVector::BI__builtin_rvv_vfwsub_vv_rm_tu:
6259 case RISCVVector::BI__builtin_rvv_vfwsub_vf_rm_tu:
6260 case RISCVVector::BI__builtin_rvv_vfwadd_wv_rm_tu:
6261 case RISCVVector::BI__builtin_rvv_vfwadd_wf_rm_tu:
6262 case RISCVVector::BI__builtin_rvv_vfwsub_wv_rm_tu:
6263 case RISCVVector::BI__builtin_rvv_vfwsub_wf_rm_tu:
6264 case RISCVVector::BI__builtin_rvv_vfmul_vv_rm_tu:
6265 case RISCVVector::BI__builtin_rvv_vfmul_vf_rm_tu:
6266 case RISCVVector::BI__builtin_rvv_vfdiv_vv_rm_tu:
6267 case RISCVVector::BI__builtin_rvv_vfdiv_vf_rm_tu:
6268 case RISCVVector::BI__builtin_rvv_vfrdiv_vf_rm_tu:
6269 case RISCVVector::BI__builtin_rvv_vfwmul_vv_rm_tu:
6270 case RISCVVector::BI__builtin_rvv_vfwmul_vf_rm_tu:
6271 case RISCVVector::BI__builtin_rvv_vfredosum_vs_rm_tu:
6272 case RISCVVector::BI__builtin_rvv_vfredusum_vs_rm_tu:
6273 case RISCVVector::BI__builtin_rvv_vfwredosum_vs_rm_tu:
6274 case RISCVVector::BI__builtin_rvv_vfwredusum_vs_rm_tu:
6275 case RISCVVector::BI__builtin_rvv_vfmacc_vv_rm:
6276 case RISCVVector::BI__builtin_rvv_vfmacc_vf_rm:
6277 case RISCVVector::BI__builtin_rvv_vfnmacc_vv_rm:
6278 case RISCVVector::BI__builtin_rvv_vfnmacc_vf_rm:
6279 case RISCVVector::BI__builtin_rvv_vfmsac_vv_rm:
6280 case RISCVVector::BI__builtin_rvv_vfmsac_vf_rm:
6281 case RISCVVector::BI__builtin_rvv_vfnmsac_vv_rm:
6282 case RISCVVector::BI__builtin_rvv_vfnmsac_vf_rm:
6283 case RISCVVector::BI__builtin_rvv_vfmadd_vv_rm:
6284 case RISCVVector::BI__builtin_rvv_vfmadd_vf_rm:
6285 case RISCVVector::BI__builtin_rvv_vfnmadd_vv_rm:
6286 case RISCVVector::BI__builtin_rvv_vfnmadd_vf_rm:
6287 case RISCVVector::BI__builtin_rvv_vfmsub_vv_rm:
6288 case RISCVVector::BI__builtin_rvv_vfmsub_vf_rm:
6289 case RISCVVector::BI__builtin_rvv_vfnmsub_vv_rm:
6290 case RISCVVector::BI__builtin_rvv_vfnmsub_vf_rm:
6291 case RISCVVector::BI__builtin_rvv_vfwmacc_vv_rm:
6292 case RISCVVector::BI__builtin_rvv_vfwmacc_vf_rm:
6293 case RISCVVector::BI__builtin_rvv_vfwnmacc_vv_rm:
6294 case RISCVVector::BI__builtin_rvv_vfwnmacc_vf_rm:
6295 case RISCVVector::BI__builtin_rvv_vfwmsac_vv_rm:
6296 case RISCVVector::BI__builtin_rvv_vfwmsac_vf_rm:
6297 case RISCVVector::BI__builtin_rvv_vfwnmsac_vv_rm:
6298 case RISCVVector::BI__builtin_rvv_vfwnmsac_vf_rm:
6299 case RISCVVector::BI__builtin_rvv_vfmacc_vv_rm_tu:
6300 case RISCVVector::BI__builtin_rvv_vfmacc_vf_rm_tu:
6301 case RISCVVector::BI__builtin_rvv_vfnmacc_vv_rm_tu:
6302 case RISCVVector::BI__builtin_rvv_vfnmacc_vf_rm_tu:
6303 case RISCVVector::BI__builtin_rvv_vfmsac_vv_rm_tu:
6304 case RISCVVector::BI__builtin_rvv_vfmsac_vf_rm_tu:
6305 case RISCVVector::BI__builtin_rvv_vfnmsac_vv_rm_tu:
6306 case RISCVVector::BI__builtin_rvv_vfnmsac_vf_rm_tu:
6307 case RISCVVector::BI__builtin_rvv_vfmadd_vv_rm_tu:
6308 case RISCVVector::BI__builtin_rvv_vfmadd_vf_rm_tu:
6309 case RISCVVector::BI__builtin_rvv_vfnmadd_vv_rm_tu:
6310 case RISCVVector::BI__builtin_rvv_vfnmadd_vf_rm_tu:
6311 case RISCVVector::BI__builtin_rvv_vfmsub_vv_rm_tu:
6312 case RISCVVector::BI__builtin_rvv_vfmsub_vf_rm_tu:
6313 case RISCVVector::BI__builtin_rvv_vfnmsub_vv_rm_tu:
6314 case RISCVVector::BI__builtin_rvv_vfnmsub_vf_rm_tu:
6315 case RISCVVector::BI__builtin_rvv_vfwmacc_vv_rm_tu:
6316 case RISCVVector::BI__builtin_rvv_vfwmacc_vf_rm_tu:
6317 case RISCVVector::BI__builtin_rvv_vfwnmacc_vv_rm_tu:
6318 case RISCVVector::BI__builtin_rvv_vfwnmacc_vf_rm_tu:
6319 case RISCVVector::BI__builtin_rvv_vfwmsac_vv_rm_tu:
6320 case RISCVVector::BI__builtin_rvv_vfwmsac_vf_rm_tu:
6321 case RISCVVector::BI__builtin_rvv_vfwnmsac_vv_rm_tu:
6322 case RISCVVector::BI__builtin_rvv_vfwnmsac_vf_rm_tu:
6323 case RISCVVector::BI__builtin_rvv_vfadd_vv_rm_m:
6324 case RISCVVector::BI__builtin_rvv_vfadd_vf_rm_m:
6325 case RISCVVector::BI__builtin_rvv_vfsub_vv_rm_m:
6326 case RISCVVector::BI__builtin_rvv_vfsub_vf_rm_m:
6327 case RISCVVector::BI__builtin_rvv_vfrsub_vf_rm_m:
6328 case RISCVVector::BI__builtin_rvv_vfwadd_vv_rm_m:
6329 case RISCVVector::BI__builtin_rvv_vfwadd_vf_rm_m:
6330 case RISCVVector::BI__builtin_rvv_vfwsub_vv_rm_m:
6331 case RISCVVector::BI__builtin_rvv_vfwsub_vf_rm_m:
6332 case RISCVVector::BI__builtin_rvv_vfwadd_wv_rm_m:
6333 case RISCVVector::BI__builtin_rvv_vfwadd_wf_rm_m:
6334 case RISCVVector::BI__builtin_rvv_vfwsub_wv_rm_m:
6335 case RISCVVector::BI__builtin_rvv_vfwsub_wf_rm_m:
6336 case RISCVVector::BI__builtin_rvv_vfmul_vv_rm_m:
6337 case RISCVVector::BI__builtin_rvv_vfmul_vf_rm_m:
6338 case RISCVVector::BI__builtin_rvv_vfdiv_vv_rm_m:
6339 case RISCVVector::BI__builtin_rvv_vfdiv_vf_rm_m:
6340 case RISCVVector::BI__builtin_rvv_vfrdiv_vf_rm_m:
6341 case RISCVVector::BI__builtin_rvv_vfwmul_vv_rm_m:
6342 case RISCVVector::BI__builtin_rvv_vfwmul_vf_rm_m:
6343 case RISCVVector::BI__builtin_rvv_vfredosum_vs_rm_m:
6344 case RISCVVector::BI__builtin_rvv_vfredusum_vs_rm_m:
6345 case RISCVVector::BI__builtin_rvv_vfwredosum_vs_rm_m:
6346 case RISCVVector::BI__builtin_rvv_vfwredusum_vs_rm_m:
6347 case RISCVVector::BI__builtin_rvv_vfsqrt_v_rm_tum:
6348 case RISCVVector::BI__builtin_rvv_vfrec7_v_rm_tum:
6349 case RISCVVector::BI__builtin_rvv_vfcvt_x_f_v_rm_tum:
6350 case RISCVVector::BI__builtin_rvv_vfcvt_xu_f_v_rm_tum:
6351 case RISCVVector::BI__builtin_rvv_vfcvt_f_x_v_rm_tum:
6352 case RISCVVector::BI__builtin_rvv_vfcvt_f_xu_v_rm_tum:
6353 case RISCVVector::BI__builtin_rvv_vfwcvt_x_f_v_rm_tum:
6354 case RISCVVector::BI__builtin_rvv_vfwcvt_xu_f_v_rm_tum:
6355 case RISCVVector::BI__builtin_rvv_vfncvt_x_f_w_rm_tum:
6356 case RISCVVector::BI__builtin_rvv_vfncvt_xu_f_w_rm_tum:
6357 case RISCVVector::BI__builtin_rvv_vfncvt_f_x_w_rm_tum:
6358 case RISCVVector::BI__builtin_rvv_vfncvt_f_xu_w_rm_tum:
6359 case RISCVVector::BI__builtin_rvv_vfncvt_f_f_w_rm_tum:
6360 case RISCVVector::BI__builtin_rvv_vfsqrt_v_rm_tumu:
6361 case RISCVVector::BI__builtin_rvv_vfrec7_v_rm_tumu:
6362 case RISCVVector::BI__builtin_rvv_vfcvt_x_f_v_rm_tumu:
6363 case RISCVVector::BI__builtin_rvv_vfcvt_xu_f_v_rm_tumu:
6364 case RISCVVector::BI__builtin_rvv_vfcvt_f_x_v_rm_tumu:
6365 case RISCVVector::BI__builtin_rvv_vfcvt_f_xu_v_rm_tumu:
6366 case RISCVVector::BI__builtin_rvv_vfwcvt_x_f_v_rm_tumu:
6367 case RISCVVector::BI__builtin_rvv_vfwcvt_xu_f_v_rm_tumu:
6368 case RISCVVector::BI__builtin_rvv_vfncvt_x_f_w_rm_tumu:
6369 case RISCVVector::BI__builtin_rvv_vfncvt_xu_f_w_rm_tumu:
6370 case RISCVVector::BI__builtin_rvv_vfncvt_f_x_w_rm_tumu:
6371 case RISCVVector::BI__builtin_rvv_vfncvt_f_xu_w_rm_tumu:
6372 case RISCVVector::BI__builtin_rvv_vfncvt_f_f_w_rm_tumu:
6373 case RISCVVector::BI__builtin_rvv_vfsqrt_v_rm_mu:
6374 case RISCVVector::BI__builtin_rvv_vfrec7_v_rm_mu:
6375 case RISCVVector::BI__builtin_rvv_vfcvt_x_f_v_rm_mu:
6376 case RISCVVector::BI__builtin_rvv_vfcvt_xu_f_v_rm_mu:
6377 case RISCVVector::BI__builtin_rvv_vfcvt_f_x_v_rm_mu:
6378 case RISCVVector::BI__builtin_rvv_vfcvt_f_xu_v_rm_mu:
6379 case RISCVVector::BI__builtin_rvv_vfwcvt_x_f_v_rm_mu:
6380 case RISCVVector::BI__builtin_rvv_vfwcvt_xu_f_v_rm_mu:
6381 case RISCVVector::BI__builtin_rvv_vfncvt_x_f_w_rm_mu:
6382 case RISCVVector::BI__builtin_rvv_vfncvt_xu_f_w_rm_mu:
6383 case RISCVVector::BI__builtin_rvv_vfncvt_f_x_w_rm_mu:
6384 case RISCVVector::BI__builtin_rvv_vfncvt_f_xu_w_rm_mu:
6385 case RISCVVector::BI__builtin_rvv_vfncvt_f_f_w_rm_mu:
6386 return BuiltinConstantArgRange(TheCall, 3, 0, 4);
6387 case RISCVVector::BI__builtin_rvv_vfmacc_vv_rm_m:
6388 case RISCVVector::BI__builtin_rvv_vfmacc_vf_rm_m:
6389 case RISCVVector::BI__builtin_rvv_vfnmacc_vv_rm_m:
6390 case RISCVVector::BI__builtin_rvv_vfnmacc_vf_rm_m:
6391 case RISCVVector::BI__builtin_rvv_vfmsac_vv_rm_m:
6392 case RISCVVector::BI__builtin_rvv_vfmsac_vf_rm_m:
6393 case RISCVVector::BI__builtin_rvv_vfnmsac_vv_rm_m:
6394 case RISCVVector::BI__builtin_rvv_vfnmsac_vf_rm_m:
6395 case RISCVVector::BI__builtin_rvv_vfmadd_vv_rm_m:
6396 case RISCVVector::BI__builtin_rvv_vfmadd_vf_rm_m:
6397 case RISCVVector::BI__builtin_rvv_vfnmadd_vv_rm_m:
6398 case RISCVVector::BI__builtin_rvv_vfnmadd_vf_rm_m:
6399 case RISCVVector::BI__builtin_rvv_vfmsub_vv_rm_m:
6400 case RISCVVector::BI__builtin_rvv_vfmsub_vf_rm_m:
6401 case RISCVVector::BI__builtin_rvv_vfnmsub_vv_rm_m:
6402 case RISCVVector::BI__builtin_rvv_vfnmsub_vf_rm_m:
6403 case RISCVVector::BI__builtin_rvv_vfwmacc_vv_rm_m:
6404 case RISCVVector::BI__builtin_rvv_vfwmacc_vf_rm_m:
6405 case RISCVVector::BI__builtin_rvv_vfwnmacc_vv_rm_m:
6406 case RISCVVector::BI__builtin_rvv_vfwnmacc_vf_rm_m:
6407 case RISCVVector::BI__builtin_rvv_vfwmsac_vv_rm_m:
6408 case RISCVVector::BI__builtin_rvv_vfwmsac_vf_rm_m:
6409 case RISCVVector::BI__builtin_rvv_vfwnmsac_vv_rm_m:
6410 case RISCVVector::BI__builtin_rvv_vfwnmsac_vf_rm_m:
6411 case RISCVVector::BI__builtin_rvv_vfadd_vv_rm_tum:
6412 case RISCVVector::BI__builtin_rvv_vfadd_vf_rm_tum:
6413 case RISCVVector::BI__builtin_rvv_vfsub_vv_rm_tum:
6414 case RISCVVector::BI__builtin_rvv_vfsub_vf_rm_tum:
6415 case RISCVVector::BI__builtin_rvv_vfrsub_vf_rm_tum:
6416 case RISCVVector::BI__builtin_rvv_vfwadd_vv_rm_tum:
6417 case RISCVVector::BI__builtin_rvv_vfwadd_vf_rm_tum:
6418 case RISCVVector::BI__builtin_rvv_vfwsub_vv_rm_tum:
6419 case RISCVVector::BI__builtin_rvv_vfwsub_vf_rm_tum:
6420 case RISCVVector::BI__builtin_rvv_vfwadd_wv_rm_tum:
6421 case RISCVVector::BI__builtin_rvv_vfwadd_wf_rm_tum:
6422 case RISCVVector::BI__builtin_rvv_vfwsub_wv_rm_tum:
6423 case RISCVVector::BI__builtin_rvv_vfwsub_wf_rm_tum:
6424 case RISCVVector::BI__builtin_rvv_vfmul_vv_rm_tum:
6425 case RISCVVector::BI__builtin_rvv_vfmul_vf_rm_tum:
6426 case RISCVVector::BI__builtin_rvv_vfdiv_vv_rm_tum:
6427 case RISCVVector::BI__builtin_rvv_vfdiv_vf_rm_tum:
6428 case RISCVVector::BI__builtin_rvv_vfrdiv_vf_rm_tum:
6429 case RISCVVector::BI__builtin_rvv_vfwmul_vv_rm_tum:
6430 case RISCVVector::BI__builtin_rvv_vfwmul_vf_rm_tum:
6431 case RISCVVector::BI__builtin_rvv_vfmacc_vv_rm_tum:
6432 case RISCVVector::BI__builtin_rvv_vfmacc_vf_rm_tum:
6433 case RISCVVector::BI__builtin_rvv_vfnmacc_vv_rm_tum:
6434 case RISCVVector::BI__builtin_rvv_vfnmacc_vf_rm_tum:
6435 case RISCVVector::BI__builtin_rvv_vfmsac_vv_rm_tum:
6436 case RISCVVector::BI__builtin_rvv_vfmsac_vf_rm_tum:
6437 case RISCVVector::BI__builtin_rvv_vfnmsac_vv_rm_tum:
6438 case RISCVVector::BI__builtin_rvv_vfnmsac_vf_rm_tum:
6439 case RISCVVector::BI__builtin_rvv_vfmadd_vv_rm_tum:
6440 case RISCVVector::BI__builtin_rvv_vfmadd_vf_rm_tum:
6441 case RISCVVector::BI__builtin_rvv_vfnmadd_vv_rm_tum:
6442 case RISCVVector::BI__builtin_rvv_vfnmadd_vf_rm_tum:
6443 case RISCVVector::BI__builtin_rvv_vfmsub_vv_rm_tum:
6444 case RISCVVector::BI__builtin_rvv_vfmsub_vf_rm_tum:
6445 case RISCVVector::BI__builtin_rvv_vfnmsub_vv_rm_tum:
6446 case RISCVVector::BI__builtin_rvv_vfnmsub_vf_rm_tum:
6447 case RISCVVector::BI__builtin_rvv_vfwmacc_vv_rm_tum:
6448 case RISCVVector::BI__builtin_rvv_vfwmacc_vf_rm_tum:
6449 case RISCVVector::BI__builtin_rvv_vfwnmacc_vv_rm_tum:
6450 case RISCVVector::BI__builtin_rvv_vfwnmacc_vf_rm_tum:
6451 case RISCVVector::BI__builtin_rvv_vfwmsac_vv_rm_tum:
6452 case RISCVVector::BI__builtin_rvv_vfwmsac_vf_rm_tum:
6453 case RISCVVector::BI__builtin_rvv_vfwnmsac_vv_rm_tum:
6454 case RISCVVector::BI__builtin_rvv_vfwnmsac_vf_rm_tum:
6455 case RISCVVector::BI__builtin_rvv_vfredosum_vs_rm_tum:
6456 case RISCVVector::BI__builtin_rvv_vfredusum_vs_rm_tum:
6457 case RISCVVector::BI__builtin_rvv_vfwredosum_vs_rm_tum:
6458 case RISCVVector::BI__builtin_rvv_vfwredusum_vs_rm_tum:
6459 case RISCVVector::BI__builtin_rvv_vfadd_vv_rm_tumu:
6460 case RISCVVector::BI__builtin_rvv_vfadd_vf_rm_tumu:
6461 case RISCVVector::BI__builtin_rvv_vfsub_vv_rm_tumu:
6462 case RISCVVector::BI__builtin_rvv_vfsub_vf_rm_tumu:
6463 case RISCVVector::BI__builtin_rvv_vfrsub_vf_rm_tumu:
6464 case RISCVVector::BI__builtin_rvv_vfwadd_vv_rm_tumu:
6465 case RISCVVector::BI__builtin_rvv_vfwadd_vf_rm_tumu:
6466 case RISCVVector::BI__builtin_rvv_vfwsub_vv_rm_tumu:
6467 case RISCVVector::BI__builtin_rvv_vfwsub_vf_rm_tumu:
6468 case RISCVVector::BI__builtin_rvv_vfwadd_wv_rm_tumu:
6469 case RISCVVector::BI__builtin_rvv_vfwadd_wf_rm_tumu:
6470 case RISCVVector::BI__builtin_rvv_vfwsub_wv_rm_tumu:
6471 case RISCVVector::BI__builtin_rvv_vfwsub_wf_rm_tumu:
6472 case RISCVVector::BI__builtin_rvv_vfmul_vv_rm_tumu:
6473 case RISCVVector::BI__builtin_rvv_vfmul_vf_rm_tumu:
6474 case RISCVVector::BI__builtin_rvv_vfdiv_vv_rm_tumu:
6475 case RISCVVector::BI__builtin_rvv_vfdiv_vf_rm_tumu:
6476 case RISCVVector::BI__builtin_rvv_vfrdiv_vf_rm_tumu:
6477 case RISCVVector::BI__builtin_rvv_vfwmul_vv_rm_tumu:
6478 case RISCVVector::BI__builtin_rvv_vfwmul_vf_rm_tumu:
6479 case RISCVVector::BI__builtin_rvv_vfmacc_vv_rm_tumu:
6480 case RISCVVector::BI__builtin_rvv_vfmacc_vf_rm_tumu:
6481 case RISCVVector::BI__builtin_rvv_vfnmacc_vv_rm_tumu:
6482 case RISCVVector::BI__builtin_rvv_vfnmacc_vf_rm_tumu:
6483 case RISCVVector::BI__builtin_rvv_vfmsac_vv_rm_tumu:
6484 case RISCVVector::BI__builtin_rvv_vfmsac_vf_rm_tumu:
6485 case RISCVVector::BI__builtin_rvv_vfnmsac_vv_rm_tumu:
6486 case RISCVVector::BI__builtin_rvv_vfnmsac_vf_rm_tumu:
6487 case RISCVVector::BI__builtin_rvv_vfmadd_vv_rm_tumu:
6488 case RISCVVector::BI__builtin_rvv_vfmadd_vf_rm_tumu:
6489 case RISCVVector::BI__builtin_rvv_vfnmadd_vv_rm_tumu:
6490 case RISCVVector::BI__builtin_rvv_vfnmadd_vf_rm_tumu:
6491 case RISCVVector::BI__builtin_rvv_vfmsub_vv_rm_tumu:
6492 case RISCVVector::BI__builtin_rvv_vfmsub_vf_rm_tumu:
6493 case RISCVVector::BI__builtin_rvv_vfnmsub_vv_rm_tumu:
6494 case RISCVVector::BI__builtin_rvv_vfnmsub_vf_rm_tumu:
6495 case RISCVVector::BI__builtin_rvv_vfwmacc_vv_rm_tumu:
6496 case RISCVVector::BI__builtin_rvv_vfwmacc_vf_rm_tumu:
6497 case RISCVVector::BI__builtin_rvv_vfwnmacc_vv_rm_tumu:
6498 case RISCVVector::BI__builtin_rvv_vfwnmacc_vf_rm_tumu:
6499 case RISCVVector::BI__builtin_rvv_vfwmsac_vv_rm_tumu:
6500 case RISCVVector::BI__builtin_rvv_vfwmsac_vf_rm_tumu:
6501 case RISCVVector::BI__builtin_rvv_vfwnmsac_vv_rm_tumu:
6502 case RISCVVector::BI__builtin_rvv_vfwnmsac_vf_rm_tumu:
6503 case RISCVVector::BI__builtin_rvv_vfadd_vv_rm_mu:
6504 case RISCVVector::BI__builtin_rvv_vfadd_vf_rm_mu:
6505 case RISCVVector::BI__builtin_rvv_vfsub_vv_rm_mu:
6506 case RISCVVector::BI__builtin_rvv_vfsub_vf_rm_mu:
6507 case RISCVVector::BI__builtin_rvv_vfrsub_vf_rm_mu:
6508 case RISCVVector::BI__builtin_rvv_vfwadd_vv_rm_mu:
6509 case RISCVVector::BI__builtin_rvv_vfwadd_vf_rm_mu:
6510 case RISCVVector::BI__builtin_rvv_vfwsub_vv_rm_mu:
6511 case RISCVVector::BI__builtin_rvv_vfwsub_vf_rm_mu:
6512 case RISCVVector::BI__builtin_rvv_vfwadd_wv_rm_mu:
6513 case RISCVVector::BI__builtin_rvv_vfwadd_wf_rm_mu:
6514 case RISCVVector::BI__builtin_rvv_vfwsub_wv_rm_mu:
6515 case RISCVVector::BI__builtin_rvv_vfwsub_wf_rm_mu:
6516 case RISCVVector::BI__builtin_rvv_vfmul_vv_rm_mu:
6517 case RISCVVector::BI__builtin_rvv_vfmul_vf_rm_mu:
6518 case RISCVVector::BI__builtin_rvv_vfdiv_vv_rm_mu:
6519 case RISCVVector::BI__builtin_rvv_vfdiv_vf_rm_mu:
6520 case RISCVVector::BI__builtin_rvv_vfrdiv_vf_rm_mu:
6521 case RISCVVector::BI__builtin_rvv_vfwmul_vv_rm_mu:
6522 case RISCVVector::BI__builtin_rvv_vfwmul_vf_rm_mu:
6523 case RISCVVector::BI__builtin_rvv_vfmacc_vv_rm_mu:
6524 case RISCVVector::BI__builtin_rvv_vfmacc_vf_rm_mu:
6525 case RISCVVector::BI__builtin_rvv_vfnmacc_vv_rm_mu:
6526 case RISCVVector::BI__builtin_rvv_vfnmacc_vf_rm_mu:
6527 case RISCVVector::BI__builtin_rvv_vfmsac_vv_rm_mu:
6528 case RISCVVector::BI__builtin_rvv_vfmsac_vf_rm_mu:
6529 case RISCVVector::BI__builtin_rvv_vfnmsac_vv_rm_mu:
6530 case RISCVVector::BI__builtin_rvv_vfnmsac_vf_rm_mu:
6531 case RISCVVector::BI__builtin_rvv_vfmadd_vv_rm_mu:
6532 case RISCVVector::BI__builtin_rvv_vfmadd_vf_rm_mu:
6533 case RISCVVector::BI__builtin_rvv_vfnmadd_vv_rm_mu:
6534 case RISCVVector::BI__builtin_rvv_vfnmadd_vf_rm_mu:
6535 case RISCVVector::BI__builtin_rvv_vfmsub_vv_rm_mu:
6536 case RISCVVector::BI__builtin_rvv_vfmsub_vf_rm_mu:
6537 case RISCVVector::BI__builtin_rvv_vfnmsub_vv_rm_mu:
6538 case RISCVVector::BI__builtin_rvv_vfnmsub_vf_rm_mu:
6539 case RISCVVector::BI__builtin_rvv_vfwmacc_vv_rm_mu:
6540 case RISCVVector::BI__builtin_rvv_vfwmacc_vf_rm_mu:
6541 case RISCVVector::BI__builtin_rvv_vfwnmacc_vv_rm_mu:
6542 case RISCVVector::BI__builtin_rvv_vfwnmacc_vf_rm_mu:
6543 case RISCVVector::BI__builtin_rvv_vfwmsac_vv_rm_mu:
6544 case RISCVVector::BI__builtin_rvv_vfwmsac_vf_rm_mu:
6545 case RISCVVector::BI__builtin_rvv_vfwnmsac_vv_rm_mu:
6546 case RISCVVector::BI__builtin_rvv_vfwnmsac_vf_rm_mu:
6547 return BuiltinConstantArgRange(TheCall, 4, 0, 4);
6548 case RISCV::BI__builtin_riscv_ntl_load:
6549 case RISCV::BI__builtin_riscv_ntl_store:
6550 DeclRefExpr *DRE =
6551 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6552 assert((BuiltinID == RISCV::BI__builtin_riscv_ntl_store ||
6553 BuiltinID == RISCV::BI__builtin_riscv_ntl_load) &&
6554 "Unexpected RISC-V nontemporal load/store builtin!");
6555 bool IsStore = BuiltinID == RISCV::BI__builtin_riscv_ntl_store;
6556 unsigned NumArgs = IsStore ? 3 : 2;
6557
6558 if (checkArgCountAtLeast(*this, TheCall, NumArgs - 1))
6559 return true;
6560
6561 if (checkArgCountAtMost(*this, TheCall, NumArgs))
6562 return true;
6563
6564 // Domain value should be compile-time constant.
6565 // 2 <= domain <= 5
6566 if (TheCall->getNumArgs() == NumArgs &&
6567 BuiltinConstantArgRange(TheCall, NumArgs - 1, 2, 5))
6568 return true;
6569
6570 Expr *PointerArg = TheCall->getArg(0);
6571 ExprResult PointerArgResult =
6573
6574 if (PointerArgResult.isInvalid())
6575 return true;
6576 PointerArg = PointerArgResult.get();
6577
6578 const PointerType *PtrType = PointerArg->getType()->getAs<PointerType>();
6579 if (!PtrType) {
6580 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6581 << PointerArg->getType() << PointerArg->getSourceRange();
6582 return true;
6583 }
6584
6585 QualType ValType = PtrType->getPointeeType();
6586 ValType = ValType.getUnqualifiedType();
6587 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6588 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6589 !ValType->isVectorType() && !ValType->isRVVSizelessBuiltinType()) {
6590 Diag(DRE->getBeginLoc(),
6591 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6592 << PointerArg->getType() << PointerArg->getSourceRange();
6593 return true;
6594 }
6595
6596 if (!IsStore) {
6597 TheCall->setType(ValType);
6598 return false;
6599 }
6600
6601 ExprResult ValArg = TheCall->getArg(1);
6603 Context, ValType, /*consume*/ false);
6604 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6605 if (ValArg.isInvalid())
6606 return true;
6607
6608 TheCall->setArg(1, ValArg.get());
6609 TheCall->setType(Context.VoidTy);
6610 return false;
6611 }
6612
6613 return false;
6614}
6615
6616bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
6617 CallExpr *TheCall) {
6618 if (BuiltinID == SystemZ::BI__builtin_tabort) {
6619 Expr *Arg = TheCall->getArg(0);
6620 if (std::optional<llvm::APSInt> AbortCode =
6622 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
6623 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
6624 << Arg->getSourceRange();
6625 }
6626
6627 // For intrinsics which take an immediate value as part of the instruction,
6628 // range check them here.
6629 unsigned i = 0, l = 0, u = 0;
6630 switch (BuiltinID) {
6631 default: return false;
6632 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
6633 case SystemZ::BI__builtin_s390_verimb:
6634 case SystemZ::BI__builtin_s390_verimh:
6635 case SystemZ::BI__builtin_s390_verimf:
6636 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
6637 case SystemZ::BI__builtin_s390_vfaeb:
6638 case SystemZ::BI__builtin_s390_vfaeh:
6639 case SystemZ::BI__builtin_s390_vfaef:
6640 case SystemZ::BI__builtin_s390_vfaebs:
6641 case SystemZ::BI__builtin_s390_vfaehs:
6642 case SystemZ::BI__builtin_s390_vfaefs:
6643 case SystemZ::BI__builtin_s390_vfaezb:
6644 case SystemZ::BI__builtin_s390_vfaezh:
6645 case SystemZ::BI__builtin_s390_vfaezf:
6646 case SystemZ::BI__builtin_s390_vfaezbs:
6647 case SystemZ::BI__builtin_s390_vfaezhs:
6648 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
6649 case SystemZ::BI__builtin_s390_vfisb:
6650 case SystemZ::BI__builtin_s390_vfidb:
6651 return BuiltinConstantArgRange(TheCall, 1, 0, 15) ||
6652 BuiltinConstantArgRange(TheCall, 2, 0, 15);
6653 case SystemZ::BI__builtin_s390_vftcisb:
6654 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
6655 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
6656 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
6657 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
6658 case SystemZ::BI__builtin_s390_vstrcb:
6659 case SystemZ::BI__builtin_s390_vstrch:
6660 case SystemZ::BI__builtin_s390_vstrcf:
6661 case SystemZ::BI__builtin_s390_vstrczb:
6662 case SystemZ::BI__builtin_s390_vstrczh:
6663 case SystemZ::BI__builtin_s390_vstrczf:
6664 case SystemZ::BI__builtin_s390_vstrcbs:
6665 case SystemZ::BI__builtin_s390_vstrchs:
6666 case SystemZ::BI__builtin_s390_vstrcfs:
6667 case SystemZ::BI__builtin_s390_vstrczbs:
6668 case SystemZ::BI__builtin_s390_vstrczhs:
6669 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
6670 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
6671 case SystemZ::BI__builtin_s390_vfminsb:
6672 case SystemZ::BI__builtin_s390_vfmaxsb:
6673 case SystemZ::BI__builtin_s390_vfmindb:
6674 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
6675 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
6676 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
6677 case SystemZ::BI__builtin_s390_vclfnhs:
6678 case SystemZ::BI__builtin_s390_vclfnls:
6679 case SystemZ::BI__builtin_s390_vcfn:
6680 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
6681 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
6682 }
6683 return BuiltinConstantArgRange(TheCall, i, l, u);
6684}
6685
6686bool Sema::CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI,
6687 unsigned BuiltinID,
6688 CallExpr *TheCall) {
6689 switch (BuiltinID) {
6690 case WebAssembly::BI__builtin_wasm_ref_null_extern:
6691 return BuiltinWasmRefNullExtern(TheCall);
6692 case WebAssembly::BI__builtin_wasm_ref_null_func:
6693 return BuiltinWasmRefNullFunc(TheCall);
6694 case WebAssembly::BI__builtin_wasm_table_get:
6695 return BuiltinWasmTableGet(TheCall);
6696 case WebAssembly::BI__builtin_wasm_table_set:
6697 return BuiltinWasmTableSet(TheCall);
6698 case WebAssembly::BI__builtin_wasm_table_size:
6699 return BuiltinWasmTableSize(TheCall);
6700 case WebAssembly::BI__builtin_wasm_table_grow:
6701 return BuiltinWasmTableGrow(TheCall);
6702 case WebAssembly::BI__builtin_wasm_table_fill:
6703 return BuiltinWasmTableFill(TheCall);
6704 case WebAssembly::BI__builtin_wasm_table_copy:
6705 return BuiltinWasmTableCopy(TheCall);
6706 }
6707
6708 return false;
6709}
6710
6711void Sema::checkRVVTypeSupport(QualType Ty, SourceLocation Loc, Decl *D,
6712 const llvm::StringMap<bool> &FeatureMap) {
6715 unsigned EltSize = Context.getTypeSize(Info.ElementType);
6716 unsigned MinElts = Info.EC.getKnownMinValue();
6717
6718 if (Info.ElementType->isSpecificBuiltinType(BuiltinType::Double) &&
6719 !FeatureMap.lookup("zve64d"))
6720 Diag(Loc, diag::err_riscv_type_requires_extension, D) << Ty << "zve64d";
6721 // (ELEN, LMUL) pairs of (8, mf8), (16, mf4), (32, mf2), (64, m1) requires at
6722 // least zve64x
6723 else if (((EltSize == 64 && Info.ElementType->isIntegerType()) ||
6724 MinElts == 1) &&
6725 !FeatureMap.lookup("zve64x"))
6726 Diag(Loc, diag::err_riscv_type_requires_extension, D) << Ty << "zve64x";
6727 else if (Info.ElementType->isFloat16Type() && !FeatureMap.lookup("zvfh") &&
6728 !FeatureMap.lookup("zvfhmin"))
6729 Diag(Loc, diag::err_riscv_type_requires_extension, D)
6730 << Ty << "zvfh or zvfhmin";
6731 else if (Info.ElementType->isBFloat16Type() &&
6732 !FeatureMap.lookup("experimental-zvfbfmin"))
6733 Diag(Loc, diag::err_riscv_type_requires_extension, D) << Ty << "zvfbfmin";
6734 else if (Info.ElementType->isSpecificBuiltinType(BuiltinType::Float) &&
6735 !FeatureMap.lookup("zve32f"))
6736 Diag(Loc, diag::err_riscv_type_requires_extension, D) << Ty << "zve32f";
6737 // Given that caller already checked isRVVType() before calling this function,
6738 // if we don't have at least zve32x supported, then we need to emit error.
6739 else if (!FeatureMap.lookup("zve32x"))
6740 Diag(Loc, diag::err_riscv_type_requires_extension, D) << Ty << "zve32x";
6741}
6742
6743bool Sema::CheckNVPTXBuiltinFunctionCall(const TargetInfo &TI,
6744 unsigned BuiltinID,
6745 CallExpr *TheCall) {
6746 switch (BuiltinID) {
6747 case NVPTX::BI__nvvm_cp_async_ca_shared_global_4:
6748 case NVPTX::BI__nvvm_cp_async_ca_shared_global_8:
6749 case NVPTX::BI__nvvm_cp_async_ca_shared_global_16:
6750 case NVPTX::BI__nvvm_cp_async_cg_shared_global_16:
6751 return checkArgCountAtMost(*this, TheCall, 3);
6752 }
6753
6754 return false;
6755}
6756
6757// Check if the rounding mode is legal.
6758bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
6759 // Indicates if this instruction has rounding control or just SAE.
6760 bool HasRC = false;
6761
6762 unsigned ArgNum = 0;
6763 switch (BuiltinID) {
6764 default:
6765 return false;
6766 case X86::BI__builtin_ia32_vcvttsd2si32:
6767 case X86::BI__builtin_ia32_vcvttsd2si64:
6768 case X86::BI__builtin_ia32_vcvttsd2usi32:
6769 case X86::BI__builtin_ia32_vcvttsd2usi64:
6770 case X86::BI__builtin_ia32_vcvttss2si32:
6771 case X86::BI__builtin_ia32_vcvttss2si64:
6772 case X86::BI__builtin_ia32_vcvttss2usi32:
6773 case X86::BI__builtin_ia32_vcvttss2usi64:
6774 case X86::BI__builtin_ia32_vcvttsh2si32:
6775 case X86::BI__builtin_ia32_vcvttsh2si64:
6776 case X86::BI__builtin_ia32_vcvttsh2usi32:
6777 case X86::BI__builtin_ia32_vcvttsh2usi64:
6778 ArgNum = 1;
6779 break;
6780 case X86::BI__builtin_ia32_maxpd512:
6781 case X86::BI__builtin_ia32_maxps512:
6782 case X86::BI__builtin_ia32_minpd512:
6783 case X86::BI__builtin_ia32_minps512:
6784 case X86::BI__builtin_ia32_maxph512:
6785 case X86::BI__builtin_ia32_minph512:
6786 ArgNum = 2;
6787 break;
6788 case X86::BI__builtin_ia32_vcvtph2pd512_mask:
6789 case X86::BI__builtin_ia32_vcvtph2psx512_mask:
6790 case X86::BI__builtin_ia32_cvtps2pd512_mask:
6791 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
6792 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
6793 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
6794 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
6795 case X86::BI__builtin_ia32_cvttps2dq512_mask:
6796 case X86::BI__builtin_ia32_cvttps2qq512_mask:
6797 case X86::BI__builtin_ia32_cvttps2udq512_mask:
6798 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
6799 case X86::BI__builtin_ia32_vcvttph2w512_mask:
6800 case X86::BI__builtin_ia32_vcvttph2uw512_mask:
6801 case X86::BI__builtin_ia32_vcvttph2dq512_mask:
6802 case X86::BI__builtin_ia32_vcvttph2udq512_mask:
6803 case X86::BI__builtin_ia32_vcvttph2qq512_mask:
6804 case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
6805 case X86::BI__builtin_ia32_exp2pd_mask:
6806 case X86::BI__builtin_ia32_exp2ps_mask:
6807 case X86::BI__builtin_ia32_getexppd512_mask:
6808 case X86::BI__builtin_ia32_getexpps512_mask:
6809 case X86::BI__builtin_ia32_getexpph512_mask:
6810 case X86::BI__builtin_ia32_rcp28pd_mask:
6811 case X86::BI__builtin_ia32_rcp28ps_mask:
6812 case X86::BI__builtin_ia32_rsqrt28pd_mask:
6813 case X86::BI__builtin_ia32_rsqrt28ps_mask:
6814 case X86::BI__builtin_ia32_vcomisd:
6815 case X86::BI__builtin_ia32_vcomiss:
6816 case X86::BI__builtin_ia32_vcomish:
6817 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
6818 ArgNum = 3;
6819 break;
6820 case X86::BI__builtin_ia32_cmppd512_mask:
6821 case X86::BI__builtin_ia32_cmpps512_mask:
6822 case X86::BI__builtin_ia32_cmpsd_mask:
6823 case X86::BI__builtin_ia32_cmpss_mask:
6824 case X86::BI__builtin_ia32_cmpsh_mask:
6825 case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
6826 case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
6827 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
6828 case X86::BI__builtin_ia32_getexpsd128_round_mask:
6829 case X86::BI__builtin_ia32_getexpss128_round_mask:
6830 case X86::BI__builtin_ia32_getexpsh128_round_mask:
6831 case X86::BI__builtin_ia32_getmantpd512_mask:
6832 case X86::BI__builtin_ia32_getmantps512_mask:
6833 case X86::BI__builtin_ia32_getmantph512_mask:
6834 case X86::BI__builtin_ia32_maxsd_round_mask:
6835 case X86::BI__builtin_ia32_maxss_round_mask:
6836 case X86::BI__builtin_ia32_maxsh_round_mask:
6837 case X86::BI__builtin_ia32_minsd_round_mask:
6838 case X86::BI__builtin_ia32_minss_round_mask:
6839 case X86::BI__builtin_ia32_minsh_round_mask:
6840 case X86::BI__builtin_ia32_rcp28sd_round_mask:
6841 case X86::BI__builtin_ia32_rcp28ss_round_mask:
6842 case X86::BI__builtin_ia32_reducepd512_mask:
6843 case X86::BI__builtin_ia32_reduceps512_mask:
6844 case X86::BI__builtin_ia32_reduceph512_mask:
6845 case X86::BI__builtin_ia32_rndscalepd_mask:
6846 case X86::BI__builtin_ia32_rndscaleps_mask:
6847 case X86::BI__builtin_ia32_rndscaleph_mask:
6848 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
6849 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
6850 ArgNum = 4;
6851 break;
6852 case X86::BI__builtin_ia32_fixupimmpd512_mask:
6853 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
6854 case X86::BI__builtin_ia32_fixupimmps512_mask:
6855 case X86::BI__builtin_ia32_fixupimmps512_maskz:
6856 case X86::BI__builtin_ia32_fixupimmsd_mask:
6857 case X86::BI__builtin_ia32_fixupimmsd_maskz:
6858 case X86::BI__builtin_ia32_fixupimmss_mask:
6859 case X86::BI__builtin_ia32_fixupimmss_maskz:
6860 case X86::BI__builtin_ia32_getmantsd_round_mask:
6861 case X86::BI__builtin_ia32_getmantss_round_mask:
6862 case X86::BI__builtin_ia32_getmantsh_round_mask:
6863 case X86::BI__builtin_ia32_rangepd512_mask:
6864 case X86::BI__builtin_ia32_rangeps512_mask:
6865 case X86::BI__builtin_ia32_rangesd128_round_mask:
6866 case X86::BI__builtin_ia32_rangess128_round_mask:
6867 case X86::BI__builtin_ia32_reducesd_mask:
6868 case X86::BI__builtin_ia32_reducess_mask:
6869 case X86::BI__builtin_ia32_reducesh_mask:
6870 case X86::BI__builtin_ia32_rndscalesd_round_mask:
6871 case X86::BI__builtin_ia32_rndscaless_round_mask:
6872 case X86::BI__builtin_ia32_rndscalesh_round_mask:
6873 ArgNum = 5;
6874 break;
6875 case X86::BI__builtin_ia32_vcvtsd2si64:
6876 case X86::BI__builtin_ia32_vcvtsd2si32:
6877 case X86::BI__builtin_ia32_vcvtsd2usi32:
6878 case X86::BI__builtin_ia32_vcvtsd2usi64:
6879 case X86::BI__builtin_ia32_vcvtss2si32:
6880 case X86::BI__builtin_ia32_vcvtss2si64:
6881 case X86::BI__builtin_ia32_vcvtss2usi32:
6882 case X86::BI__builtin_ia32_vcvtss2usi64:
6883 case X86::BI__builtin_ia32_vcvtsh2si32:
6884 case X86::BI__builtin_ia32_vcvtsh2si64:
6885 case X86::BI__builtin_ia32_vcvtsh2usi32:
6886 case X86::BI__builtin_ia32_vcvtsh2usi64:
6887 case X86::BI__builtin_ia32_sqrtpd512:
6888 case X86::BI__builtin_ia32_sqrtps512:
6889 case X86::BI__builtin_ia32_sqrtph512:
6890 ArgNum = 1;
6891 HasRC = true;
6892 break;
6893 case X86::BI__builtin_ia32_addph512:
6894 case X86::BI__builtin_ia32_divph512:
6895 case X86::BI__builtin_ia32_mulph512:
6896 case X86::BI__builtin_ia32_subph512:
6897 case X86::BI__builtin_ia32_addpd512:
6898 case X86::BI__builtin_ia32_addps512:
6899 case X86::BI__builtin_ia32_divpd512:
6900 case X86::BI__builtin_ia32_divps512:
6901 case X86::BI__builtin_ia32_mulpd512:
6902 case X86::BI__builtin_ia32_mulps512:
6903 case X86::BI__builtin_ia32_subpd512:
6904 case X86::BI__builtin_ia32_subps512:
6905 case X86::BI__builtin_ia32_cvtsi2sd64:
6906 case X86::BI__builtin_ia32_cvtsi2ss32:
6907 case X86::BI__builtin_ia32_cvtsi2ss64:
6908 case X86::BI__builtin_ia32_cvtusi2sd64:
6909 case X86::BI__builtin_ia32_cvtusi2ss32:
6910 case X86::BI__builtin_ia32_cvtusi2ss64:
6911 case X86::BI__builtin_ia32_vcvtusi2sh:
6912 case X86::BI__builtin_ia32_vcvtusi642sh:
6913 case X86::BI__builtin_ia32_vcvtsi2sh:
6914 case X86::BI__builtin_ia32_vcvtsi642sh:
6915 ArgNum = 2;
6916 HasRC = true;
6917 break;
6918 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
6919 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
6920 case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
6921 case X86::BI__builtin_ia32_vcvtps2phx512_mask:
6922 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
6923 case X86::BI__builtin_ia32_cvtpd2dq512_mask:
6924 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
6925 case X86::BI__builtin_ia32_cvtpd2udq512_mask:
6926 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
6927 case X86::BI__builtin_ia32_cvtps2dq512_mask:
6928 case X86::BI__builtin_ia32_cvtps2qq512_mask:
6929 case X86::BI__builtin_ia32_cvtps2udq512_mask:
6930 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
6931 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
6932 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
6933 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
6934 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
6935 case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
6936 case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
6937 case X86::BI__builtin_ia32_vcvtw2ph512_mask:
6938 case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
6939 case X86::BI__builtin_ia32_vcvtph2w512_mask:
6940 case X86::BI__builtin_ia32_vcvtph2uw512_mask:
6941 case X86::BI__builtin_ia32_vcvtph2dq512_mask:
6942 case X86::BI__builtin_ia32_vcvtph2udq512_mask:
6943 case X86::BI__builtin_ia32_vcvtph2qq512_mask:
6944 case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
6945 case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
6946 case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
6947 ArgNum = 3;
6948 HasRC = true;
6949 break;
6950 case X86::BI__builtin_ia32_addsh_round_mask:
6951 case X86::BI__builtin_ia32_addss_round_mask:
6952 case X86::BI__builtin_ia32_addsd_round_mask:
6953 case X86::BI__builtin_ia32_divsh_round_mask:
6954 case X86::BI__builtin_ia32_divss_round_mask:
6955 case X86::BI__builtin_ia32_divsd_round_mask:
6956 case X86::BI__builtin_ia32_mulsh_round_mask:
6957 case X86::BI__builtin_ia32_mulss_round_mask:
6958 case X86::BI__builtin_ia32_mulsd_round_mask:
6959 case X86::BI__builtin_ia32_subsh_round_mask:
6960 case X86::BI__builtin_ia32_subss_round_mask:
6961 case X86::BI__builtin_ia32_subsd_round_mask:
6962 case X86::BI__builtin_ia32_scalefph512_mask:
6963 case X86::BI__builtin_ia32_scalefpd512_mask:
6964 case X86::BI__builtin_ia32_scalefps512_mask:
6965 case X86::BI__builtin_ia32_scalefsd_round_mask:
6966 case X86::BI__builtin_ia32_scalefss_round_mask:
6967 case X86::BI__builtin_ia32_scalefsh_round_mask:
6968 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
6969 case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
6970 case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
6971 case X86::BI__builtin_ia32_sqrtsd_round_mask:
6972 case X86::BI__builtin_ia32_sqrtss_round_mask:
6973 case X86::BI__builtin_ia32_sqrtsh_round_mask:
6974 case X86::BI__builtin_ia32_vfmaddsd3_mask:
6975 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
6976 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
6977 case X86::BI__builtin_ia32_vfmaddss3_mask:
6978 case X86::BI__builtin_ia32_vfmaddss3_maskz:
6979 case X86::BI__builtin_ia32_vfmaddss3_mask3:
6980 case X86::BI__builtin_ia32_vfmaddsh3_mask:
6981 case X86::BI__builtin_ia32_vfmaddsh3_maskz:
6982 case X86::BI__builtin_ia32_vfmaddsh3_mask3:
6983 case X86::BI__builtin_ia32_vfmaddpd512_mask:
6984 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
6985 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
6986 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
6987 case X86::BI__builtin_ia32_vfmaddps512_mask:
6988 case X86::BI__builtin_ia32_vfmaddps512_maskz:
6989 case X86::BI__builtin_ia32_vfmaddps512_mask3:
6990 case X86::BI__builtin_ia32_vfmsubps512_mask3:
6991 case X86::BI__builtin_ia32_vfmaddph512_mask:
6992 case X86::BI__builtin_ia32_vfmaddph512_maskz:
6993 case X86::BI__builtin_ia32_vfmaddph512_mask3:
6994 case X86::BI__builtin_ia32_vfmsubph512_mask3:
6995 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
6996 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
6997 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
6998 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
6999 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
7000 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
7001 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
7002 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
7003 case X86::BI__builtin_ia32_vfmaddsubph512_mask:
7004 case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
7005 case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
7006 case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
7007 case X86::BI__builtin_ia32_vfmaddcsh_mask:
7008 case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
7009 case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
7010 case X86::BI__builtin_ia32_vfmaddcph512_mask:
7011 case X86::BI__builtin_ia32_vfmaddcph512_maskz:
7012 case X86::BI__builtin_ia32_vfmaddcph512_mask3:
7013 case X86::BI__builtin_ia32_vfcmaddcsh_mask:
7014 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
7015 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
7016 case X86::BI__builtin_ia32_vfcmaddcph512_mask:
7017 case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
7018 case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
7019 case X86::BI__builtin_ia32_vfmulcsh_mask:
7020 case X86::BI__builtin_ia32_vfmulcph512_mask:
7021 case X86::BI__builtin_ia32_vfcmulcsh_mask:
7022 case X86::BI__builtin_ia32_vfcmulcph512_mask:
7023 ArgNum = 4;
7024 HasRC = true;
7025 break;
7026 }
7027
7028 llvm::APSInt Result;
7029
7030 // We can't check the value of a dependent argument.
7031 Expr *Arg = TheCall->getArg(ArgNum);
7032 if (Arg->isTypeDependent() || Arg->isValueDependent())
7033 return false;
7034
7035 // Check constant-ness first.
7036 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7037 return true;
7038
7039 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
7040 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
7041 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
7042 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
7043 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
7044 Result == 8/*ROUND_NO_EXC*/ ||
7045 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
7046 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
7047 return false;
7048
7049 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
7050 << Arg->getSourceRange();
7051}
7052
7053// Check if the gather/scatter scale is legal.
7054bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
7055 CallExpr *TheCall) {
7056 unsigned ArgNum = 0;
7057 switch (BuiltinID) {
7058 default:
7059 return false;
7060 case X86::BI__builtin_ia32_gatherpfdpd:
7061 case X86::BI__builtin_ia32_gatherpfdps:
7062 case X86::BI__builtin_ia32_gatherpfqpd:
7063 case X86::BI__builtin_ia32_gatherpfqps:
7064 case X86::BI__builtin_ia32_scatterpfdpd:
7065 case X86::BI__builtin_ia32_scatterpfdps:
7066 case X86::BI__builtin_ia32_scatterpfqpd:
7067 case X86::BI__builtin_ia32_scatterpfqps:
7068 ArgNum = 3;
7069 break;
7070 case X86::BI__builtin_ia32_gatherd_pd:
7071 case X86::BI__builtin_ia32_gatherd_pd256:
7072 case X86::BI__builtin_ia32_gatherq_pd:
7073 case X86::BI__builtin_ia32_gatherq_pd256:
7074 case X86::BI__builtin_ia32_gatherd_ps:
7075 case X86::BI__builtin_ia32_gatherd_ps256:
7076 case X86::BI__builtin_ia32_gatherq_ps:
7077 case X86::BI__builtin_ia32_gatherq_ps256:
7078 case X86::BI__builtin_ia32_gatherd_q:
7079 case X86::BI__builtin_ia32_gatherd_q256:
7080 case X86::BI__builtin_ia32_gatherq_q:
7081 case X86::BI__builtin_ia32_gatherq_q256:
7082 case X86::BI__builtin_ia32_gatherd_d:
7083 case X86::BI__builtin_ia32_gatherd_d256:
7084 case X86::BI__builtin_ia32_gatherq_d:
7085 case X86::BI__builtin_ia32_gatherq_d256:
7086 case X86::BI__builtin_ia32_gather3div2df:
7087 case X86::BI__builtin_ia32_gather3div2di:
7088 case X86::BI__builtin_ia32_gather3div4df:
7089 case X86::BI__builtin_ia32_gather3div4di:
7090 case X86::BI__builtin_ia32_gather3div4sf:
7091 case X86::BI__builtin_ia32_gather3div4si:
7092 case X86::BI__builtin_ia32_gather3div8sf:
7093 case X86::BI__builtin_ia32_gather3div8si:
7094 case X86::BI__builtin_ia32_gather3siv2df:
7095 case X86::BI__builtin_ia32_gather3siv2di:
7096 case X86::BI__builtin_ia32_gather3siv4df:
7097 case X86::BI__builtin_ia32_gather3siv4di:
7098 case X86::BI__builtin_ia32_gather3siv4sf:
7099 case X86::BI__builtin_ia32_gather3siv4si:
7100 case X86::BI__builtin_ia32_gather3siv8sf:
7101 case X86::BI__builtin_ia32_gather3siv8si:
7102 case X86::BI__builtin_ia32_gathersiv8df:
7103 case X86::BI__builtin_ia32_gathersiv16sf:
7104 case X86::BI__builtin_ia32_gatherdiv8df:
7105 case X86::BI__builtin_ia32_gatherdiv16sf:
7106 case X86::BI__builtin_ia32_gathersiv8di:
7107 case X86::BI__builtin_ia32_gathersiv16si:
7108 case X86::BI__builtin_ia32_gatherdiv8di:
7109 case X86::BI__builtin_ia32_gatherdiv16si:
7110 case X86::BI__builtin_ia32_scatterdiv2df:
7111 case X86::BI__builtin_ia32_scatterdiv2di:
7112 case X86::BI__builtin_ia32_scatterdiv4df:
7113 case X86::BI__builtin_ia32_scatterdiv4di:
7114 case X86::BI__builtin_ia32_scatterdiv4sf:
7115 case X86::BI__builtin_ia32_scatterdiv4si:
7116 case X86::BI__builtin_ia32_scatterdiv8sf:
7117 case X86::BI__builtin_ia32_scatterdiv8si:
7118 case X86::BI__builtin_ia32_scattersiv2df:
7119 case X86::BI__builtin_ia32_scattersiv2di:
7120 case X86::BI__builtin_ia32_scattersiv4df:
7121 case X86::BI__builtin_ia32_scattersiv4di:
7122 case X86::BI__builtin_ia32_scattersiv4sf:
7123 case X86::BI__builtin_ia32_scattersiv4si:
7124 case X86::BI__builtin_ia32_scattersiv8sf:
7125 case X86::BI__builtin_ia32_scattersiv8si:
7126 case X86::BI__builtin_ia32_scattersiv8df:
7127 case X86::BI__builtin_ia32_scattersiv16sf:
7128 case X86::BI__builtin_ia32_scatterdiv8df:
7129 case X86::BI__builtin_ia32_scatterdiv16sf:
7130 case X86::BI__builtin_ia32_scattersiv8di:
7131 case X86::BI__builtin_ia32_scattersiv16si:
7132 case X86::BI__builtin_ia32_scatterdiv8di:
7133 case X86::BI__builtin_ia32_scatterdiv16si:
7134 ArgNum = 4;
7135 break;
7136 }
7137
7138 llvm::APSInt Result;
7139
7140 // We can't check the value of a dependent argument.
7141 Expr *Arg = TheCall->getArg(ArgNum);
7142 if (Arg->isTypeDependent() || Arg->isValueDependent())
7143 return false;
7144
7145 // Check constant-ness first.
7146 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7147 return true;
7148
7149 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
7150 return false;
7151
7152 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
7153 << Arg->getSourceRange();
7154}
7155
7156enum { TileRegLow = 0, TileRegHigh = 7 };
7157
7158bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
7159 ArrayRef<int> ArgNums) {
7160 for (int ArgNum : ArgNums) {
7161 if (BuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
7162 return true;
7163 }
7164 return false;
7165}
7166
7167bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
7168 ArrayRef<int> ArgNums) {
7169 // Because the max number of tile register is TileRegHigh + 1, so here we use
7170 // each bit to represent the usage of them in bitset.
7171 std::bitset<TileRegHigh + 1> ArgValues;
7172 for (int ArgNum : ArgNums) {
7173 Expr *Arg = TheCall->getArg(ArgNum);
7174 if (Arg->isTypeDependent() || Arg->isValueDependent())
7175 continue;
7176
7177 llvm::APSInt Result;
7178 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7179 return true;
7180 int ArgExtValue = Result.getExtValue();
7181 assert((ArgExtValue >= TileRegLow && ArgExtValue <= TileRegHigh) &&
7182 "Incorrect tile register num.");
7183 if (ArgValues.test(ArgExtValue))
7184 return Diag(TheCall->getBeginLoc(),
7185 diag::err_x86_builtin_tile_arg_duplicate)
7186 << TheCall->getArg(ArgNum)->getSourceRange();
7187 ArgValues.set(ArgExtValue);
7188 }
7189 return false;
7190}
7191
7192bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
7193 ArrayRef<int> ArgNums) {
7194 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
7195 CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
7196}
7197
7198bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
7199 switch (BuiltinID) {
7200 default:
7201 return false;
7202 case X86::BI__builtin_ia32_tileloadd64:
7203 case X86::BI__builtin_ia32_tileloaddt164:
7204 case X86::BI__builtin_ia32_tilestored64:
7205 case X86::BI__builtin_ia32_tilezero:
7206 return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
7207 case X86::BI__builtin_ia32_tdpbssd:
7208 case X86::BI__builtin_ia32_tdpbsud:
7209 case X86::BI__builtin_ia32_tdpbusd:
7210 case X86::BI__builtin_ia32_tdpbuud:
7211 case X86::BI__builtin_ia32_tdpbf16ps:
7212 case X86::BI__builtin_ia32_tdpfp16ps:
7213 case X86::BI__builtin_ia32_tcmmimfp16ps:
7214 case X86::BI__builtin_ia32_tcmmrlfp16ps:
7215 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
7216 }
7217}
7218static bool isX86_32Builtin(unsigned BuiltinID) {
7219 // These builtins only work on x86-32 targets.
7220 switch (BuiltinID) {
7221 case X86::BI__builtin_ia32_readeflags_u32:
7222 case X86::BI__builtin_ia32_writeeflags_u32:
7223 return true;
7224 }
7225
7226 return false;
7227}
7228
7229bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
7230 CallExpr *TheCall) {
7231 // Check for 32-bit only builtins on a 64-bit target.
7232 const llvm::Triple &TT = TI.getTriple();
7233 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
7234 return Diag(TheCall->getCallee()->getBeginLoc(),
7235 diag::err_32_bit_builtin_64_bit_tgt);
7236
7237 // If the intrinsic has rounding or SAE make sure its valid.
7238 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
7239 return true;
7240
7241 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
7242 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
7243 return true;
7244
7245 // If the intrinsic has a tile arguments, make sure they are valid.
7246 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
7247 return true;
7248
7249 // For intrinsics which take an immediate value as part of the instruction,
7250 // range check them here.
7251 int i = 0, l = 0, u = 0;
7252 switch (BuiltinID) {
7253 default:
7254 return false;
7255 case X86::BI__builtin_ia32_vec_ext_v2si:
7256 case X86::BI__builtin_ia32_vec_ext_v2di:
7257 case X86::BI__builtin_ia32_vextractf128_pd256:
7258 case X86::BI__builtin_ia32_vextractf128_ps256:
7259 case X86::BI__builtin_ia32_vextractf128_si256:
7260 case X86::BI__builtin_ia32_extract128i256:
7261 case X86::BI__builtin_ia32_extractf64x4_mask:
7262 case X86::BI__builtin_ia32_extracti64x4_mask:
7263 case X86::BI__builtin_ia32_extractf32x8_mask:
7264 case X86::BI__builtin_ia32_extracti32x8_mask:
7265 case X86::BI__builtin_ia32_extractf64x2_256_mask:
7266 case X86::BI__builtin_ia32_extracti64x2_256_mask:
7267 case X86::BI__builtin_ia32_extractf32x4_256_mask:
7268 case X86::BI__builtin_ia32_extracti32x4_256_mask:
7269 i = 1; l = 0; u = 1;
7270 break;
7271 case X86::BI__builtin_ia32_vec_set_v2di:
7272 case X86::BI__builtin_ia32_vinsertf128_pd256:
7273 case X86::BI__builtin_ia32_vinsertf128_ps256:
7274 case X86::BI__builtin_ia32_vinsertf128_si256:
7275 case X86::BI__builtin_ia32_insert128i256:
7276 case X86::BI__builtin_ia32_insertf32x8:
7277 case X86::BI__builtin_ia32_inserti32x8:
7278 case X86::BI__builtin_ia32_insertf64x4:
7279 case X86::BI__builtin_ia32_inserti64x4:
7280 case X86::BI__builtin_ia32_insertf64x2_256:
7281 case X86::BI__builtin_ia32_inserti64x2_256:
7282 case X86::BI__builtin_ia32_insertf32x4_256:
7283 case X86::BI__builtin_ia32_inserti32x4_256:
7284 i = 2; l = 0; u = 1;
7285 break;
7286 case X86::BI__builtin_ia32_vpermilpd:
7287 case X86::BI__builtin_ia32_vec_ext_v4hi:
7288 case X86::BI__builtin_ia32_vec_ext_v4si:
7289 case X86::BI__builtin_ia32_vec_ext_v4sf:
7290 case X86::BI__builtin_ia32_vec_ext_v4di:
7291 case X86::BI__builtin_ia32_extractf32x4_mask:
7292 case X86::BI__builtin_ia32_extracti32x4_mask:
7293 case X86::BI__builtin_ia32_extractf64x2_512_mask:
7294 case X86::BI__builtin_ia32_extracti64x2_512_mask:
7295 i = 1; l = 0; u = 3;
7296 break;
7297 case X86::BI_mm_prefetch:
7298 case X86::BI__builtin_ia32_vec_ext_v8hi:
7299 case X86::BI__builtin_ia32_vec_ext_v8si:
7300 i = 1; l = 0; u = 7;
7301 break;
7302 case X86::BI__builtin_ia32_sha1rnds4:
7303 case X86::BI__builtin_ia32_blendpd:
7304 case X86::BI__builtin_ia32_shufpd:
7305 case X86::BI__builtin_ia32_vec_set_v4hi:
7306 case X86::BI__builtin_ia32_vec_set_v4si:
7307 case X86::BI__builtin_ia32_vec_set_v4di:
7308 case X86::BI__builtin_ia32_shuf_f32x4_256:
7309 case X86::BI__builtin_ia32_shuf_f64x2_256:
7310 case X86::BI__builtin_ia32_shuf_i32x4_256:
7311 case X86::BI__builtin_ia32_shuf_i64x2_256:
7312 case X86::BI__builtin_ia32_insertf64x2_512:
7313 case X86::BI__builtin_ia32_inserti64x2_512:
7314 case X86::BI__builtin_ia32_insertf32x4:
7315 case X86::BI__builtin_ia32_inserti32x4:
7316 i = 2; l = 0; u = 3;
7317 break;
7318 case X86::BI__builtin_ia32_vpermil2pd:
7319 case X86::BI__builtin_ia32_vpermil2pd256:
7320 case X86::BI__builtin_ia32_vpermil2ps:
7321 case X86::BI__builtin_ia32_vpermil2ps256:
7322 i = 3; l = 0; u = 3;
7323 break;
7324 case X86::BI__builtin_ia32_cmpb128_mask:
7325 case X86::BI__builtin_ia32_cmpw128_mask:
7326 case X86::BI__builtin_ia32_cmpd128_mask:
7327 case X86::BI__builtin_ia32_cmpq128_mask:
7328 case X86::BI__builtin_ia32_cmpb256_mask:
7329 case X86::BI__builtin_ia32_cmpw256_mask:
7330 case X86::BI__builtin_ia32_cmpd256_mask:
7331 case X86::BI__builtin_ia32_cmpq256_mask:
7332 case X86::BI__builtin_ia32_cmpb512_mask:
7333 case X86::BI__builtin_ia32_cmpw512_mask:
7334 case X86::BI__builtin_ia32_cmpd512_mask:
7335 case X86::BI__builtin_ia32_cmpq512_mask:
7336 case X86::BI__builtin_ia32_ucmpb128_mask:
7337 case X86::BI__builtin_ia32_ucmpw128_mask:
7338 case X86::BI__builtin_ia32_ucmpd128_mask:
7339 case X86::BI__builtin_ia32_ucmpq128_mask:
7340 case X86::BI__builtin_ia32_ucmpb256_mask:
7341 case X86::BI__builtin_ia32_ucmpw256_mask:
7342 case X86::BI__builtin_ia32_ucmpd256_mask:
7343 case X86::BI__builtin_ia32_ucmpq256_mask:
7344 case X86::BI__builtin_ia32_ucmpb512_mask:
7345 case X86::BI__builtin_ia32_ucmpw512_mask:
7346 case X86::BI__builtin_ia32_ucmpd512_mask:
7347 case X86::BI__builtin_ia32_ucmpq512_mask:
7348 case X86::BI__builtin_ia32_vpcomub:
7349 case X86::BI__builtin_ia32_vpcomuw:
7350 case X86::BI__builtin_ia32_vpcomud:
7351 case X86::BI__builtin_ia32_vpcomuq:
7352 case X86::BI__builtin_ia32_vpcomb:
7353 case X86::BI__builtin_ia32_vpcomw:
7354 case X86::BI__builtin_ia32_vpcomd:
7355 case X86::BI__builtin_ia32_vpcomq:
7356 case X86::BI__builtin_ia32_vec_set_v8hi:
7357 case X86::BI__builtin_ia32_vec_set_v8si:
7358 i = 2; l = 0; u = 7;
7359 break;
7360 case X86::BI__builtin_ia32_vpermilpd256:
7361 case X86::BI__builtin_ia32_roundps:
7362 case X86::BI__builtin_ia32_roundpd:
7363 case X86::BI__builtin_ia32_roundps256:
7364 case X86::BI__builtin_ia32_roundpd256:
7365 case X86::BI__builtin_ia32_getmantpd128_mask:
7366 case X86::BI__builtin_ia32_getmantpd256_mask:
7367 case X86::BI__builtin_ia32_getmantps128_mask:
7368 case X86::BI__builtin_ia32_getmantps256_mask:
7369 case X86::BI__builtin_ia32_getmantpd512_mask:
7370 case X86::BI__builtin_ia32_getmantps512_mask:
7371 case X86::BI__builtin_ia32_getmantph128_mask:
7372 case X86::BI__builtin_ia32_getmantph256_mask:
7373 case X86::BI__builtin_ia32_getmantph512_mask:
7374 case X86::BI__builtin_ia32_vec_ext_v16qi:
7375 case X86::BI__builtin_ia32_vec_ext_v16hi:
7376 i = 1; l = 0; u = 15;
7377 break;
7378 case X86::BI__builtin_ia32_pblendd128:
7379 case X86::BI__builtin_ia32_blendps:
7380 case X86::BI__builtin_ia32_blendpd256:
7381 case X86::BI__builtin_ia32_shufpd256:
7382 case X86::BI__builtin_ia32_roundss:
7383 case X86::BI__builtin_ia32_roundsd:
7384 case X86::BI__builtin_ia32_rangepd128_mask:
7385 case X86::BI__builtin_ia32_rangepd256_mask:
7386 case X86::BI__builtin_ia32_rangepd512_mask:
7387 case X86::BI__builtin_ia32_rangeps128_mask:
7388 case X86::BI__builtin_ia32_rangeps256_mask:
7389 case X86::BI__builtin_ia32_rangeps512_mask:
7390 case X86::BI__builtin_ia32_getmantsd_round_mask:
7391 case X86::BI__builtin_ia32_getmantss_round_mask:
7392 case X86::BI__builtin_ia32_getmantsh_round_mask:
7393 case X86::BI__builtin_ia32_vec_set_v16qi:
7394 case X86::BI__builtin_ia32_vec_set_v16hi:
7395 i = 2; l = 0; u = 15;
7396 break;
7397 case X86::BI__builtin_ia32_vec_ext_v32qi:
7398 i = 1; l = 0; u = 31;
7399 break;
7400 case X86::BI__builtin_ia32_cmpps:
7401 case X86::BI__builtin_ia32_cmpss:
7402 case X86::BI__builtin_ia32_cmppd:
7403 case X86::BI__builtin_ia32_cmpsd:
7404 case X86::BI__builtin_ia32_cmpps256:
7405 case X86::BI__builtin_ia32_cmppd256:
7406 case X86::BI__builtin_ia32_cmpps128_mask:
7407 case X86::BI__builtin_ia32_cmppd128_mask:
7408 case X86::BI__builtin_ia32_cmpps256_mask:
7409 case X86::BI__builtin_ia32_cmppd256_mask:
7410 case X86::BI__builtin_ia32_cmpps512_mask:
7411 case X86::BI__builtin_ia32_cmppd512_mask:
7412 case X86::BI__builtin_ia32_cmpsd_mask:
7413 case X86::BI__builtin_ia32_cmpss_mask:
7414 case X86::BI__builtin_ia32_vec_set_v32qi:
7415 i = 2; l = 0; u = 31;
7416 break;
7417 case X86::BI__builtin_ia32_permdf256:
7418 case X86::BI__builtin_ia32_permdi256:
7419 case X86::BI__builtin_ia32_permdf512:
7420 case X86::BI__builtin_ia32_permdi512:
7421 case X86::BI__builtin_ia32_vpermilps:
7422 case X86::BI__builtin_ia32_vpermilps256:
7423 case X86::BI__builtin_ia32_vpermilpd512:
7424 case X86::BI__builtin_ia32_vpermilps512:
7425 case X86::BI__builtin_ia32_pshufd:
7426 case X86::BI__builtin_ia32_pshufd256:
7427 case X86::BI__builtin_ia32_pshufd512:
7428 case X86::BI__builtin_ia32_pshufhw:
7429 case X86::BI__builtin_ia32_pshufhw256:
7430 case X86::BI__builtin_ia32_pshufhw512:
7431 case X86::BI__builtin_ia32_pshuflw:
7432 case X86::BI__builtin_ia32_pshuflw256:
7433 case X86::BI__builtin_ia32_pshuflw512:
7434 case X86::BI__builtin_ia32_vcvtps2ph:
7435 case X86::BI__builtin_ia32_vcvtps2ph_mask:
7436 case X86::BI__builtin_ia32_vcvtps2ph256:
7437 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
7438 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
7439 case X86::BI__builtin_ia32_rndscaleps_128_mask:
7440 case X86::BI__builtin_ia32_rndscalepd_128_mask:
7441 case X86::BI__builtin_ia32_rndscaleps_256_mask:
7442 case X86::BI__builtin_ia32_rndscalepd_256_mask:
7443 case X86::BI__builtin_ia32_rndscaleps_mask:
7444 case X86::BI__builtin_ia32_rndscalepd_mask:
7445 case X86::BI__builtin_ia32_rndscaleph_mask:
7446 case X86::BI__builtin_ia32_reducepd128_mask:
7447 case X86::BI__builtin_ia32_reducepd256_mask:
7448 case X86::BI__builtin_ia32_reducepd512_mask:
7449 case X86::BI__builtin_ia32_reduceps128_mask:
7450 case X86::BI__builtin_ia32_reduceps256_mask:
7451 case X86::BI__builtin_ia32_reduceps512_mask:
7452 case X86::BI__builtin_ia32_reduceph128_mask:
7453 case X86::BI__builtin_ia32_reduceph256_mask:
7454 case X86::BI__builtin_ia32_reduceph512_mask:
7455 case X86::BI__builtin_ia32_prold512:
7456 case X86::BI__builtin_ia32_prolq512:
7457 case X86::BI__builtin_ia32_prold128:
7458 case X86::BI__builtin_ia32_prold256:
7459 case X86::BI__builtin_ia32_prolq128:
7460 case X86::BI__builtin_ia32_prolq256:
7461 case X86::BI__builtin_ia32_prord512:
7462 case X86::BI__builtin_ia32_prorq512:
7463 case X86::BI__builtin_ia32_prord128:
7464 case X86::BI__builtin_ia32_prord256:
7465 case X86::BI__builtin_ia32_prorq128:
7466 case X86::BI__builtin_ia32_prorq256:
7467 case X86::BI__builtin_ia32_fpclasspd128_mask:
7468 case X86::BI__builtin_ia32_fpclasspd256_mask:
7469 case X86::BI__builtin_ia32_fpclassps128_mask:
7470 case X86::BI__builtin_ia32_fpclassps256_mask:
7471 case X86::BI__builtin_ia32_fpclassps512_mask:
7472 case X86::BI__builtin_ia32_fpclasspd512_mask:
7473 case X86::BI__builtin_ia32_fpclassph128_mask:
7474 case X86::BI__builtin_ia32_fpclassph256_mask:
7475 case X86::BI__builtin_ia32_fpclassph512_mask:
7476 case X86::BI__builtin_ia32_fpclasssd_mask:
7477 case X86::BI__builtin_ia32_fpclassss_mask:
7478 case X86::BI__builtin_ia32_fpclasssh_mask:
7479 case X86::BI__builtin_ia32_pslldqi128_byteshift:
7480 case X86::BI__builtin_ia32_pslldqi256_byteshift:
7481 case X86::BI__builtin_ia32_pslldqi512_byteshift:
7482 case X86::BI__builtin_ia32_psrldqi128_byteshift:
7483 case X86::BI__builtin_ia32_psrldqi256_byteshift:
7484 case X86::BI__builtin_ia32_psrldqi512_byteshift:
7485 case X86::BI__builtin_ia32_kshiftliqi:
7486 case X86::BI__builtin_ia32_kshiftlihi:
7487 case X86::BI__builtin_ia32_kshiftlisi:
7488 case X86::BI__builtin_ia32_kshiftlidi:
7489 case X86::BI__builtin_ia32_kshiftriqi:
7490 case X86::BI__builtin_ia32_kshiftrihi:
7491 case X86::BI__builtin_ia32_kshiftrisi:
7492 case X86::BI__builtin_ia32_kshiftridi:
7493 i = 1; l = 0; u = 255;
7494 break;
7495 case X86::BI__builtin_ia32_vperm2f128_pd256:
7496 case X86::BI__builtin_ia32_vperm2f128_ps256:
7497 case X86::BI__builtin_ia32_vperm2f128_si256:
7498 case X86::BI__builtin_ia32_permti256:
7499 case X86::BI__builtin_ia32_pblendw128:
7500 case X86::BI__builtin_ia32_pblendw256:
7501 case X86::BI__builtin_ia32_blendps256:
7502 case X86::BI__builtin_ia32_pblendd256:
7503 case X86::BI__builtin_ia32_palignr128:
7504 case X86::BI__builtin_ia32_palignr256:
7505 case X86::BI__builtin_ia32_palignr512:
7506 case X86::BI__builtin_ia32_alignq512:
7507 case X86::BI__builtin_ia32_alignd512:
7508 case X86::BI__builtin_ia32_alignd128:
7509 case X86::BI__builtin_ia32_alignd256:
7510 case X86::BI__builtin_ia32_alignq128:
7511 case X86::BI__builtin_ia32_alignq256:
7512 case X86::BI__builtin_ia32_vcomisd:
7513 case X86::BI__builtin_ia32_vcomiss:
7514 case X86::BI__builtin_ia32_shuf_f32x4:
7515 case X86::BI__builtin_ia32_shuf_f64x2:
7516 case X86::BI__builtin_ia32_shuf_i32x4:
7517 case X86::BI__builtin_ia32_shuf_i64x2:
7518 case X86::BI__builtin_ia32_shufpd512:
7519 case X86::BI__builtin_ia32_shufps:
7520 case X86::BI__builtin_ia32_shufps256:
7521 case X86::BI__builtin_ia32_shufps512:
7522 case X86::BI__builtin_ia32_dbpsadbw128:
7523 case X86::BI__builtin_ia32_dbpsadbw256:
7524 case X86::BI__builtin_ia32_dbpsadbw512:
7525 case X86::BI__builtin_ia32_vpshldd128:
7526 case X86::BI__builtin_ia32_vpshldd256:
7527 case X86::BI__builtin_ia32_vpshldd512:
7528 case X86::BI__builtin_ia32_vpshldq128:
7529 case X86::BI__builtin_ia32_vpshldq256:
7530 case X86::BI__builtin_ia32_vpshldq512:
7531 case X86::BI__builtin_ia32_vpshldw128:
7532 case X86::BI__builtin_ia32_vpshldw256:
7533 case X86::BI__builtin_ia32_vpshldw512:
7534 case X86::BI__builtin_ia32_vpshrdd128:
7535 case X86::BI__builtin_ia32_vpshrdd256:
7536 case X86::BI__builtin_ia32_vpshrdd512:
7537 case X86::BI__builtin_ia32_vpshrdq128:
7538 case X86::BI__builtin_ia32_vpshrdq256:
7539 case X86::BI__builtin_ia32_vpshrdq512:
7540 case X86::BI__builtin_ia32_vpshrdw128:
7541 case X86::BI__builtin_ia32_vpshrdw256:
7542 case X86::BI__builtin_ia32_vpshrdw512:
7543 i = 2; l = 0; u = 255;
7544 break;
7545 case X86::BI__builtin_ia32_fixupimmpd512_mask:
7546 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
7547 case X86::BI__builtin_ia32_fixupimmps512_mask:
7548 case X86::BI__builtin_ia32_fixupimmps512_maskz:
7549 case X86::BI__builtin_ia32_fixupimmsd_mask:
7550 case X86::BI__builtin_ia32_fixupimmsd_maskz:
7551 case X86::BI__builtin_ia32_fixupimmss_mask:
7552 case X86::BI__builtin_ia32_fixupimmss_maskz:
7553 case X86::BI__builtin_ia32_fixupimmpd128_mask:
7554 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
7555 case X86::BI__builtin_ia32_fixupimmpd256_mask:
7556 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
7557 case X86::BI__builtin_ia32_fixupimmps128_mask:
7558 case X86::BI__builtin_ia32_fixupimmps128_maskz:
7559 case X86::BI__builtin_ia32_fixupimmps256_mask:
7560 case X86::BI__builtin_ia32_fixupimmps256_maskz:
7561 case X86::BI__builtin_ia32_pternlogd512_mask:
7562 case X86::BI__builtin_ia32_pternlogd512_maskz:
7563 case X86::BI__builtin_ia32_pternlogq512_mask:
7564 case X86::BI__builtin_ia32_pternlogq512_maskz:
7565 case X86::BI__builtin_ia32_pternlogd128_mask:
7566 case X86::BI__builtin_ia32_pternlogd128_maskz:
7567 case X86::BI__builtin_ia32_pternlogd256_mask:
7568 case X86::BI__builtin_ia32_pternlogd256_maskz:
7569 case X86::BI__builtin_ia32_pternlogq128_mask:
7570 case X86::BI__builtin_ia32_pternlogq128_maskz:
7571 case X86::BI__builtin_ia32_pternlogq256_mask:
7572 case X86::BI__builtin_ia32_pternlogq256_maskz:
7573 case X86::BI__builtin_ia32_vsm3rnds2:
7574 i = 3; l = 0; u = 255;
7575 break;
7576 case X86::BI__builtin_ia32_gatherpfdpd:
7577 case X86::BI__builtin_ia32_gatherpfdps:
7578 case X86::BI__builtin_ia32_gatherpfqpd:
7579 case X86::BI__builtin_ia32_gatherpfqps:
7580 case X86::BI__builtin_ia32_scatterpfdpd:
7581 case X86::BI__builtin_ia32_scatterpfdps:
7582 case X86::BI__builtin_ia32_scatterpfqpd:
7583 case X86::BI__builtin_ia32_scatterpfqps:
7584 i = 4; l = 2; u = 3;
7585 break;
7586 case X86::BI__builtin_ia32_reducesd_mask:
7587 case X86::BI__builtin_ia32_reducess_mask:
7588 case X86::BI__builtin_ia32_rndscalesd_round_mask:
7589 case X86::BI__builtin_ia32_rndscaless_round_mask:
7590 case X86::BI__builtin_ia32_rndscalesh_round_mask:
7591 case X86::BI__builtin_ia32_reducesh_mask:
7592 i = 4; l = 0; u = 255;
7593 break;
7594 case X86::BI__builtin_ia32_cmpccxadd32:
7595 case X86::BI__builtin_ia32_cmpccxadd64:
7596 i = 3; l = 0; u = 15;
7597 break;
7598 }
7599
7600 // Note that we don't force a hard error on the range check here, allowing
7601 // template-generated or macro-generated dead code to potentially have out-of-
7602 // range values. These need to code generate, but don't need to necessarily
7603 // make any sense. We use a warning that defaults to an error.
7604 return BuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
7605}
7606
7607/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
7608/// parameter with the FormatAttr's correct format_idx and firstDataArg.
7609/// Returns true when the format fits the function and the FormatStringInfo has
7610/// been populated.
7611bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
7612 bool IsVariadic, FormatStringInfo *FSI) {
7613 if (Format->getFirstArg() == 0)
7615 else if (IsVariadic)
7617 else
7619 FSI->FormatIdx = Format->getFormatIdx() - 1;
7620 FSI->FirstDataArg =
7621 FSI->ArgPassingKind == FAPK_VAList ? 0 : Format->getFirstArg() - 1;
7622
7623 // The way the format attribute works in GCC, the implicit this argument
7624 // of member functions is counted. However, it doesn't appear in our own
7625 // lists, so decrement format_idx in that case.
7626 if (IsCXXMember) {
7627 if(FSI->FormatIdx == 0)
7628 return false;
7629 --FSI->FormatIdx;
7630 if (FSI->FirstDataArg != 0)
7631 --FSI->FirstDataArg;
7632 }
7633 return true;
7634}
7635
7636/// Checks if a the given expression evaluates to null.
7637///
7638/// Returns true if the value evaluates to null.
7639static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
7640 // Treat (smart) pointers constructed from nullptr as null, whether we can
7641 // const-evaluate them or not.
7642 // This must happen first: the smart pointer expr might have _Nonnull type!
7643 if (isa<CXXNullPtrLiteralExpr>(
7646 return true;
7647
7648 // If the expression has non-null type, it doesn't evaluate to null.
7649 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
7650 if (*nullability == NullabilityKind::NonNull)
7651 return false;
7652 }
7653
7654 // As a special case, transparent unions initialized with zero are
7655 // considered null for the purposes of the nonnull attribute.
7656 if (const RecordType *UT = Expr->getType()->getAsUnionType();
7657 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
7658 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
7659 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
7660 Expr = ILE->getInit(0);
7661 }
7662
7663 bool Result;
7664 return (!Expr->isValueDependent() &&
7666 !Result);
7667}
7668
7670 const Expr *ArgExpr,
7671 SourceLocation CallSiteLoc) {
7672 if (CheckNonNullExpr(S, ArgExpr))
7673 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
7674 S.PDiag(diag::warn_null_arg)
7675 << ArgExpr->getSourceRange());
7676}
7677
7678bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
7679 FormatStringInfo FSI;
7680 if ((GetFormatStringType(Format) == FST_NSString) &&
7681 getFormatStringInfo(Format, false, true, &FSI)) {
7682 Idx = FSI.FormatIdx;
7683 return true;
7684 }
7685 return false;
7686}
7687
7688/// Diagnose use of %s directive in an NSString which is being passed
7689/// as formatting string to formatting method.
7690static void
7692 const NamedDecl *FDecl,
7693 Expr **Args,
7694 unsigned NumArgs) {
7695 unsigned Idx = 0;
7696 bool Format = false;
7698 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
7699 Idx = 2;
7700 Format = true;
7701 }
7702 else
7703 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
7704 if (S.GetFormatNSStringIdx(I, Idx)) {
7705 Format = true;
7706 break;
7707 }
7708 }
7709 if (!Format || NumArgs <= Idx)
7710 return;
7711 const Expr *FormatExpr = Args[Idx];
7712 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
7713 FormatExpr = CSCE->getSubExpr();
7714 const StringLiteral *FormatString;
7715 if (const ObjCStringLiteral *OSL =
7716 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
7717 FormatString = OSL->getString();
7718 else
7719 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
7720 if (!FormatString)
7721 return;
7722 if (S.FormatStringHasSArg(FormatString)) {
7723 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
7724 << "%s" << 1 << 1;
7725 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
7726 << FDecl->getDeclName();
7727 }
7728}
7729
7730/// Determine whether the given type has a non-null nullability annotation.
7732 if (auto nullability = type->getNullability())
7733 return *nullability == NullabilityKind::NonNull;
7734
7735 return false;
7736}
7737
7739 const NamedDecl *FDecl,
7740 const FunctionProtoType *Proto,
7742 SourceLocation CallSiteLoc) {
7743 assert((FDecl || Proto) && "Need a function declaration or prototype");
7744
7745 // Already checked by constant evaluator.
7747 return;
7748 // Check the attributes attached to the method/function itself.
7749 llvm::SmallBitVector NonNullArgs;
7750 if (FDecl) {
7751 // Handle the nonnull attribute on the function/method declaration itself.
7752 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
7753 if (!NonNull->args_size()) {
7754 // Easy case: all pointer arguments are nonnull.
7755 for (const auto *Arg : Args)
7756 if (S.isValidPointerAttrType(Arg->getType()))
7757 CheckNonNullArgument(S, Arg, CallSiteLoc);
7758 return;
7759 }
7760
7761 for (const ParamIdx &Idx : NonNull->args()) {
7762 unsigned IdxAST = Idx.getASTIndex();
7763 if (IdxAST >= Args.size())
7764 continue;
7765 if (NonNullArgs.empty())
7766 NonNullArgs.resize(Args.size());
7767 NonNullArgs.set(IdxAST);
7768 }
7769 }
7770 }
7771
7772 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
7773 // Handle the nonnull attribute on the parameters of the
7774 // function/method.
7776 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
7777 parms = FD->parameters();
7778 else
7779 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
7780
7781 unsigned ParamIndex = 0;
7782 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
7783 I != E; ++I, ++ParamIndex) {
7784 const ParmVarDecl *PVD = *I;
7785 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
7786 if (NonNullArgs.empty())
7787 NonNullArgs.resize(Args.size());
7788
7789 NonNullArgs.set(ParamIndex);
7790 }
7791 }
7792 } else {
7793 // If we have a non-function, non-method declaration but no
7794 // function prototype, try to dig out the function prototype.
7795 if (!Proto) {
7796 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
7797 QualType type = VD->getType().getNonReferenceType();
7798 if (auto pointerType = type->getAs<PointerType>())
7799 type = pointerType->getPointeeType();
7800 else if (auto blockType = type->getAs<BlockPointerType>())
7801 type = blockType->getPointeeType();
7802 // FIXME: data member pointers?
7803
7804 // Dig out the function prototype, if there is one.
7805 Proto = type->getAs<FunctionProtoType>();
7806 }
7807 }
7808
7809 // Fill in non-null argument information from the nullability
7810 // information on the parameter types (if we have them).
7811 if (Proto) {
7812 unsigned Index = 0;
7813 for (auto paramType : Proto->getParamTypes()) {
7814 if (isNonNullType(paramType)) {
7815 if (NonNullArgs.empty())
7816 NonNullArgs.resize(Args.size());
7817
7818 NonNullArgs.set(Index);
7819 }
7820
7821 ++Index;
7822 }
7823 }
7824 }
7825
7826 // Check for non-null arguments.
7827 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
7828 ArgIndex != ArgIndexEnd; ++ArgIndex) {
7829 if (NonNullArgs[ArgIndex])
7830 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
7831 }
7832}
7833
7834// 16 byte ByVal alignment not due to a vector member is not honoured by XL
7835// on AIX. Emit a warning here that users are generating binary incompatible
7836// code to be safe.
7837// Here we try to get information about the alignment of the struct member
7838// from the struct passed to the caller function. We only warn when the struct
7839// is passed byval, hence the series of checks and early returns if we are a not
7840// passing a struct byval.
7841void Sema::checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg) {
7842 const auto *ICE = dyn_cast<ImplicitCastExpr>(Arg->IgnoreParens());
7843 if (!ICE)
7844 return;
7845
7846 const auto *DR = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
7847 if (!DR)
7848 return;
7849
7850 const auto *PD = dyn_cast<ParmVarDecl>(DR->getDecl());
7851 if (!PD || !PD->getType()->isRecordType())
7852 return;
7853
7854 QualType ArgType = Arg->getType();
7855 for (const FieldDecl *FD :
7856 ArgType->castAs<RecordType>()->getDecl()->fields()) {
7857 if (const auto *AA = FD->getAttr<AlignedAttr>()) {
7858 CharUnits Alignment =
7859 Context.toCharUnitsFromBits(AA->getAlignment(Context));
7860 if (Alignment.getQuantity() == 16) {
7861 Diag(FD->getLocation(), diag::warn_not_xl_compatible) << FD;
7862 Diag(Loc, diag::note_misaligned_member_used_here) << PD;
7863 }
7864 }
7865 }
7866}
7867
7868/// Warn if a pointer or reference argument passed to a function points to an
7869/// object that is less aligned than the parameter. This can happen when
7870/// creating a typedef with a lower alignment than the original type and then
7871/// calling functions defined in terms of the original type.
7872void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
7873 StringRef ParamName, QualType ArgTy,
7874 QualType ParamTy) {
7875
7876 // If a function accepts a pointer or reference type
7877 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
7878 return;
7879
7880 // If the parameter is a pointer type, get the pointee type for the
7881 // argument too. If the parameter is a reference type, don't try to get
7882 // the pointee type for the argument.
7883 if (ParamTy->isPointerType())
7884 ArgTy = ArgTy->getPointeeType();
7885
7886 // Remove reference or pointer
7887 ParamTy = ParamTy->getPointeeType();
7888
7889 // Find expected alignment, and the actual alignment of the passed object.
7890 // getTypeAlignInChars requires complete types
7891 if (ArgTy.isNull() || ParamTy->isDependentType() ||
7892 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
7893 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
7894 return;
7895
7896 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
7897 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
7898
7899 // If the argument is less aligned than the parameter, there is a
7900 // potential alignment issue.
7901 if (ArgAlign < ParamAlign)
7902 Diag(Loc, diag::warn_param_mismatched_alignment)
7903 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
7904 << ParamName << (FDecl != nullptr) << FDecl;
7905}
7906
7907/// Handles the checks for format strings, non-POD arguments to vararg
7908/// functions, NULL arguments passed to non-NULL parameters, diagnose_if
7909/// attributes and AArch64 SME attributes.
7911 const Expr *ThisArg, ArrayRef<const Expr *> Args,
7912 bool IsMemberFunction, SourceLocation Loc,
7914 // FIXME: We should check as much as we can in the template definition.
7916 return;
7917
7918 // Printf and scanf checking.
7919 llvm::SmallBitVector CheckedVarArgs;
7920 if (FDecl) {
7921 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
7922 // Only create vector if there are format attributes.
7923 CheckedVarArgs.resize(Args.size());
7924
7925 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
7926 CheckedVarArgs);
7927 }
7928 }
7929
7930 // Refuse POD arguments that weren't caught by the format string
7931 // checks above.
7932 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
7933 if (CallType != VariadicDoesNotApply &&
7934 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
7935 unsigned NumParams = Proto ? Proto->getNumParams()
7936 : FDecl && isa<FunctionDecl>(FDecl)
7937 ? cast<FunctionDecl>(FDecl)->getNumParams()
7938 : FDecl && isa<ObjCMethodDecl>(FDecl)
7939 ? cast<ObjCMethodDecl>(FDecl)->param_size()
7940 : 0;
7941
7942 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
7943 // Args[ArgIdx] can be null in malformed code.
7944 if (const Expr *Arg = Args[ArgIdx]) {
7945 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
7946 checkVariadicArgument(Arg, CallType);
7947 }
7948 }
7949 }
7950
7951 if (FDecl || Proto) {
7952 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
7953
7954 // Type safety checking.
7955 if (FDecl) {
7956 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
7957 CheckArgumentWithTypeTag(I, Args, Loc);
7958 }
7959 }
7960
7961 // Check that passed arguments match the alignment of original arguments.
7962 // Try to get the missing prototype from the declaration.
7963 if (!Proto && FDecl) {
7964 const auto *FT = FDecl->getFunctionType();
7965 if (isa_and_nonnull<FunctionProtoType>(FT))
7966 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
7967 }
7968 if (Proto) {
7969 // For variadic functions, we may have more args than parameters.
7970 // For some K&R functions, we may have less args than parameters.
7971 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
7972 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
7973 bool IsScalableArg = false;
7974 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
7975 // Args[ArgIdx] can be null in malformed code.
7976 if (const Expr *Arg = Args[ArgIdx]) {
7977 if (Arg->containsErrors())
7978 continue;
7979
7980 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
7981 FDecl->hasLinkage() &&
7982 FDecl->getFormalLinkage() != Linkage::Internal &&
7983 CallType == VariadicDoesNotApply)
7984 checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
7985
7986 QualType ParamTy = Proto->getParamType(ArgIdx);
7987 if (ParamTy->isSizelessVectorType())
7988 IsScalableArg = true;
7989 QualType ArgTy = Arg->getType();
7990 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
7991 ArgTy, ParamTy);
7992 }
7993 }
7994
7995 // If the callee has an AArch64 SME attribute to indicate that it is an
7996 // __arm_streaming function, then the caller requires SME to be available.
7999 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
8000 llvm::StringMap<bool> CallerFeatureMap;
8001 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
8002 if (!CallerFeatureMap.contains("sme"))
8003 Diag(Loc, diag::err_sme_call_in_non_sme_target);
8004 } else if (!Context.getTargetInfo().hasFeature("sme")) {
8005 Diag(Loc, diag::err_sme_call_in_non_sme_target);
8006 }
8007 }
8008
8009 // If the call requires a streaming-mode change and has scalable vector
8010 // arguments or return values, then warn the user that the streaming and
8011 // non-streaming vector lengths may be different.
8012 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
8013 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
8014 (IsScalableArg || IsScalableRet)) {
8015 bool IsCalleeStreaming =
8017 bool IsCalleeStreamingCompatible =
8018 ExtInfo.AArch64SMEAttributes &
8020 ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
8021 if (!IsCalleeStreamingCompatible &&
8022 (CallerFnType == ArmStreamingCompatible ||
8023 ((CallerFnType == ArmStreaming) ^ IsCalleeStreaming))) {
8024 if (IsScalableArg)
8025 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
8026 << /*IsArg=*/true;
8027 if (IsScalableRet)
8028 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
8029 << /*IsArg=*/false;
8030 }
8031 }
8032
8033 FunctionType::ArmStateValue CalleeArmZAState =
8035 FunctionType::ArmStateValue CalleeArmZT0State =
8037 if (CalleeArmZAState != FunctionType::ARM_None ||
8038 CalleeArmZT0State != FunctionType::ARM_None) {
8039 bool CallerHasZAState = false;
8040 bool CallerHasZT0State = false;
8041 if (CallerFD) {
8042 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
8043 if (Attr && Attr->isNewZA())
8044 CallerHasZAState = true;
8045 if (Attr && Attr->isNewZT0())
8046 CallerHasZT0State = true;
8047 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
8048 CallerHasZAState |=
8050 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
8052 CallerHasZT0State |=
8054 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
8056 }
8057 }
8058
8059 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
8060 Diag(Loc, diag::err_sme_za_call_no_za_state);
8061
8062 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
8063 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
8064
8065 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
8066 CalleeArmZT0State != FunctionType::ARM_None) {
8067 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
8068 Diag(Loc, diag::note_sme_use_preserves_za);
8069 }
8070 }
8071 }
8072
8073 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
8074 auto *AA = FDecl->getAttr<AllocAlignAttr>();
8075 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
8076 if (!Arg->isValueDependent()) {
8077 Expr::EvalResult Align;
8078 if (Arg->EvaluateAsInt(Align, Context)) {
8079 const llvm::APSInt &I = Align.Val.getInt();
8080 if (!I.isPowerOf2())
8081 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
8082 << Arg->getSourceRange();
8083
8084 if (I > Sema::MaximumAlignment)
8085 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
8086 << Arg->getSourceRange() << Sema::MaximumAlignment;
8087 }
8088 }
8089 }
8090
8091 if (FD)
8092 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
8093}
8094
8096 if (ConceptDecl *Decl = AutoT->getTypeConstraintConcept()) {
8098 }
8099}
8100
8101/// CheckConstructorCall - Check a constructor call for correctness and safety
8102/// properties not enforced by the C type system.
8103void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
8105 const FunctionProtoType *Proto,
8107 VariadicCallType CallType =
8109
8110 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
8111 CheckArgAlignment(
8112 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
8113 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
8114
8115 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
8116 Loc, SourceRange(), CallType);
8117}
8118
8119/// CheckFunctionCall - Check a direct function call for various correctness
8120/// and safety properties not strictly enforced by the C type system.
8122 const FunctionProtoType *Proto) {
8123 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
8124 isa<CXXMethodDecl>(FDecl);
8125 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
8126 IsMemberOperatorCall;
8127 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
8128 TheCall->getCallee());
8129 Expr** Args = TheCall->getArgs();
8130 unsigned NumArgs = TheCall->getNumArgs();
8131
8132 Expr *ImplicitThis = nullptr;
8133 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
8134 // If this is a call to a member operator, hide the first
8135 // argument from checkCall.
8136 // FIXME: Our choice of AST representation here is less than ideal.
8137 ImplicitThis = Args[0];
8138 ++Args;
8139 --NumArgs;
8140 } else if (IsMemberFunction && !FDecl->isStatic() &&
8142 ImplicitThis =
8143 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
8144
8145 if (ImplicitThis) {
8146 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
8147 // used.
8148 QualType ThisType = ImplicitThis->getType();
8149 if (!ThisType->isPointerType()) {
8150 assert(!ThisType->isReferenceType());
8151 ThisType = Context.getPointerType(ThisType);
8152 }
8153
8154 QualType ThisTypeFromDecl = Context.getPointerType(
8155 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
8156
8157 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
8158 ThisTypeFromDecl);
8159 }
8160
8161 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
8162 IsMemberFunction, TheCall->getRParenLoc(),
8163 TheCall->getCallee()->getSourceRange(), CallType);
8164
8165 IdentifierInfo *FnInfo = FDecl->getIdentifier();
8166 // None of the checks below are needed for functions that don't have
8167 // simple names (e.g., C++ conversion functions).
8168 if (!FnInfo)
8169 return false;
8170
8171 // Enforce TCB except for builtin calls, which are always allowed.
8172 if (FDecl->getBuiltinID() == 0)
8173 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
8174
8175 CheckAbsoluteValueFunction(TheCall, FDecl);
8176 CheckMaxUnsignedZero(TheCall, FDecl);
8177 CheckInfNaNFunction(TheCall, FDecl);
8178
8179 if (getLangOpts().ObjC)
8180 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
8181
8182 unsigned CMId = FDecl->getMemoryFunctionKind();
8183
8184 // Handle memory setting and copying functions.
8185 switch (CMId) {
8186 case 0:
8187 return false;
8188 case Builtin::BIstrlcpy: // fallthrough
8189 case Builtin::BIstrlcat:
8190 CheckStrlcpycatArguments(TheCall, FnInfo);
8191 break;
8192 case Builtin::BIstrncat:
8193 CheckStrncatArguments(TheCall, FnInfo);
8194 break;
8195 case Builtin::BIfree:
8196 CheckFreeArguments(TheCall);
8197 break;
8198 default:
8199 CheckMemaccessArguments(TheCall, CMId, FnInfo);
8200 }
8201
8202 return false;
8203}
8204
8205bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
8206 const FunctionProtoType *Proto) {
8207 QualType Ty;
8208 if (const auto *V = dyn_cast<VarDecl>(NDecl))
8209 Ty = V->getType().getNonReferenceType();
8210 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
8211 Ty = F->getType().getNonReferenceType();
8212 else
8213 return false;
8214
8215 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
8216 !Ty->isFunctionProtoType())
8217 return false;
8218
8219 VariadicCallType CallType;
8220 if (!Proto || !Proto->isVariadic()) {
8221 CallType = VariadicDoesNotApply;
8222 } else if (Ty->isBlockPointerType()) {
8223 CallType = VariadicBlock;
8224 } else { // Ty->isFunctionPointerType()
8225 CallType = VariadicFunction;
8226 }
8227
8228 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
8229 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
8230 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
8231 TheCall->getCallee()->getSourceRange(), CallType);
8232
8233 return false;
8234}
8235
8236/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
8237/// such as function pointers returned from functions.
8238bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
8239 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
8240 TheCall->getCallee());
8241 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
8242 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
8243 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
8244 TheCall->getCallee()->getSourceRange(), CallType);
8245
8246 return false;
8247}
8248
8249static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
8250 if (!llvm::isValidAtomicOrderingCABI(Ordering))
8251 return false;
8252
8253 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
8254 switch (Op) {
8255 case AtomicExpr::AO__c11_atomic_init:
8256 case AtomicExpr::AO__opencl_atomic_init:
8257 llvm_unreachable("There is no ordering argument for an init");
8258
8259 case AtomicExpr::AO__c11_atomic_load:
8260 case AtomicExpr::AO__opencl_atomic_load:
8261 case AtomicExpr::AO__hip_atomic_load:
8262 case AtomicExpr::AO__atomic_load_n:
8263 case AtomicExpr::AO__atomic_load:
8264 case AtomicExpr::AO__scoped_atomic_load_n:
8265 case AtomicExpr::AO__scoped_atomic_load:
8266 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
8267 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
8268
8269 case AtomicExpr::AO__c11_atomic_store:
8270 case AtomicExpr::AO__opencl_atomic_store:
8271 case AtomicExpr::AO__hip_atomic_store:
8272 case AtomicExpr::AO__atomic_store:
8273 case AtomicExpr::AO__atomic_store_n:
8274 case AtomicExpr::AO__scoped_atomic_store:
8275 case AtomicExpr::AO__scoped_atomic_store_n:
8276 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
8277 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
8278 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
8279
8280 default:
8281 return true;
8282 }
8283}
8284
8285ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
8287 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
8288 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
8289 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
8290 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
8291 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
8292 Op);
8293}
8294
8296 SourceLocation RParenLoc, MultiExprArg Args,
8298 AtomicArgumentOrder ArgOrder) {
8299 // All the non-OpenCL operations take one of the following forms.
8300 // The OpenCL operations take the __c11 forms with one extra argument for
8301 // synchronization scope.
8302 enum {
8303 // C __c11_atomic_init(A *, C)
8304 Init,
8305
8306 // C __c11_atomic_load(A *, int)
8307 Load,
8308
8309 // void __atomic_load(A *, CP, int)
8310 LoadCopy,
8311
8312 // void __atomic_store(A *, CP, int)
8313 Copy,
8314
8315 // C __c11_atomic_add(A *, M, int)
8316 Arithmetic,
8317
8318 // C __atomic_exchange_n(A *, CP, int)
8319 Xchg,
8320
8321 // void __atomic_exchange(A *, C *, CP, int)
8322 GNUXchg,
8323
8324 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
8325 C11CmpXchg,
8326
8327 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
8328 GNUCmpXchg
8329 } Form = Init;
8330
8331 const unsigned NumForm = GNUCmpXchg + 1;
8332 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
8333 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
8334 // where:
8335 // C is an appropriate type,
8336 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
8337 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
8338 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
8339 // the int parameters are for orderings.
8340
8341 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
8342 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
8343 "need to update code for modified forms");
8344 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
8345 AtomicExpr::AO__atomic_xor_fetch + 1 ==
8346 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
8347 "need to update code for modified C11 atomics");
8348 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
8349 Op <= AtomicExpr::AO__opencl_atomic_store;
8350 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
8351 Op <= AtomicExpr::AO__hip_atomic_store;
8352 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
8353 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
8354 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
8355 Op <= AtomicExpr::AO__c11_atomic_store) ||
8356 IsOpenCL;
8357 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
8358 Op == AtomicExpr::AO__atomic_store_n ||
8359 Op == AtomicExpr::AO__atomic_exchange_n ||
8360 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
8361 Op == AtomicExpr::AO__scoped_atomic_load_n ||
8362 Op == AtomicExpr::AO__scoped_atomic_store_n ||
8363 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
8364 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
8365 // Bit mask for extra allowed value types other than integers for atomic
8366 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
8367 // allow floating point.
8368 enum ArithOpExtraValueType {
8369 AOEVT_None = 0,
8370 AOEVT_Pointer = 1,
8371 AOEVT_FP = 2,
8372 };
8373 unsigned ArithAllows = AOEVT_None;
8374
8375 switch (Op) {
8376 case AtomicExpr::AO__c11_atomic_init:
8377 case AtomicExpr::AO__opencl_atomic_init:
8378 Form = Init;
8379 break;
8380
8381 case AtomicExpr::AO__c11_atomic_load:
8382 case AtomicExpr::AO__opencl_atomic_load:
8383 case AtomicExpr::AO__hip_atomic_load:
8384 case AtomicExpr::AO__atomic_load_n:
8385 case AtomicExpr::AO__scoped_atomic_load_n:
8386 Form = Load;
8387 break;
8388
8389 case AtomicExpr::AO__atomic_load:
8390 case AtomicExpr::AO__scoped_atomic_load:
8391 Form = LoadCopy;
8392 break;
8393
8394 case AtomicExpr::AO__c11_atomic_store:
8395 case AtomicExpr::AO__opencl_atomic_store:
8396 case AtomicExpr::AO__hip_atomic_store:
8397 case AtomicExpr::AO__atomic_store:
8398 case AtomicExpr::AO__atomic_store_n:
8399 case AtomicExpr::AO__scoped_atomic_store:
8400 case AtomicExpr::AO__scoped_atomic_store_n:
8401 Form = Copy;
8402 break;
8403 case AtomicExpr::AO__atomic_fetch_add:
8404 case AtomicExpr::AO__atomic_fetch_sub:
8405 case AtomicExpr::AO__atomic_add_fetch:
8406 case AtomicExpr::AO__atomic_sub_fetch:
8407 case AtomicExpr::AO__scoped_atomic_fetch_add:
8408 case AtomicExpr::AO__scoped_atomic_fetch_sub:
8409 case AtomicExpr::AO__scoped_atomic_add_fetch:
8410 case AtomicExpr::AO__scoped_atomic_sub_fetch:
8411 case AtomicExpr::AO__c11_atomic_fetch_add:
8412 case AtomicExpr::AO__c11_atomic_fetch_sub:
8413 case AtomicExpr::AO__opencl_atomic_fetch_add:
8414 case AtomicExpr::AO__opencl_atomic_fetch_sub:
8415 case AtomicExpr::AO__hip_atomic_fetch_add:
8416 case AtomicExpr::AO__hip_atomic_fetch_sub:
8417 ArithAllows = AOEVT_Pointer | AOEVT_FP;
8418 Form = Arithmetic;
8419 break;
8420 case AtomicExpr::AO__atomic_fetch_max:
8421 case AtomicExpr::AO__atomic_fetch_min:
8422 case AtomicExpr::AO__atomic_max_fetch:
8423 case AtomicExpr::AO__atomic_min_fetch:
8424 case AtomicExpr::AO__scoped_atomic_fetch_max:
8425 case AtomicExpr::AO__scoped_atomic_fetch_min:
8426 case AtomicExpr::AO__scoped_atomic_max_fetch:
8427 case AtomicExpr::AO__scoped_atomic_min_fetch:
8428 case AtomicExpr::AO__c11_atomic_fetch_max:
8429 case AtomicExpr::AO__c11_atomic_fetch_min:
8430 case AtomicExpr::AO__opencl_atomic_fetch_max:
8431 case AtomicExpr::AO__opencl_atomic_fetch_min:
8432 case AtomicExpr::AO__hip_atomic_fetch_max:
8433 case AtomicExpr::AO__hip_atomic_fetch_min:
8434 ArithAllows = AOEVT_FP;
8435 Form = Arithmetic;
8436 break;
8437 case AtomicExpr::AO__c11_atomic_fetch_and:
8438 case AtomicExpr::AO__c11_atomic_fetch_or:
8439 case AtomicExpr::AO__c11_atomic_fetch_xor:
8440 case AtomicExpr::AO__hip_atomic_fetch_and:
8441 case AtomicExpr::AO__hip_atomic_fetch_or:
8442 case AtomicExpr::AO__hip_atomic_fetch_xor:
8443 case AtomicExpr::AO__c11_atomic_fetch_nand:
8444 case AtomicExpr::AO__opencl_atomic_fetch_and:
8445 case AtomicExpr::AO__opencl_atomic_fetch_or:
8446 case AtomicExpr::AO__opencl_atomic_fetch_xor:
8447 case AtomicExpr::AO__atomic_fetch_and:
8448 case AtomicExpr::AO__atomic_fetch_or:
8449 case AtomicExpr::AO__atomic_fetch_xor:
8450 case AtomicExpr::AO__atomic_fetch_nand:
8451 case AtomicExpr::AO__atomic_and_fetch:
8452 case AtomicExpr::AO__atomic_or_fetch:
8453 case AtomicExpr::AO__atomic_xor_fetch:
8454 case AtomicExpr::AO__atomic_nand_fetch:
8455 case AtomicExpr::AO__scoped_atomic_fetch_and:
8456 case AtomicExpr::AO__scoped_atomic_fetch_or:
8457 case AtomicExpr::AO__scoped_atomic_fetch_xor:
8458 case AtomicExpr::AO__scoped_atomic_fetch_nand:
8459 case AtomicExpr::AO__scoped_atomic_and_fetch:
8460 case AtomicExpr::AO__scoped_atomic_or_fetch:
8461 case AtomicExpr::AO__scoped_atomic_xor_fetch:
8462 case AtomicExpr::AO__scoped_atomic_nand_fetch:
8463 Form = Arithmetic;
8464 break;
8465
8466 case AtomicExpr::AO__c11_atomic_exchange:
8467 case AtomicExpr::AO__hip_atomic_exchange:
8468 case AtomicExpr::AO__opencl_atomic_exchange:
8469 case AtomicExpr::AO__atomic_exchange_n:
8470 case AtomicExpr::AO__scoped_atomic_exchange_n:
8471 Form = Xchg;
8472 break;
8473
8474 case AtomicExpr::AO__atomic_exchange:
8475 case AtomicExpr::AO__scoped_atomic_exchange:
8476 Form = GNUXchg;
8477 break;
8478
8479 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
8480 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
8481 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
8482 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
8483 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
8484 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
8485 Form = C11CmpXchg;
8486 break;
8487
8488 case AtomicExpr::AO__atomic_compare_exchange:
8489 case AtomicExpr::AO__atomic_compare_exchange_n:
8490 case AtomicExpr::AO__scoped_atomic_compare_exchange:
8491 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
8492 Form = GNUCmpXchg;
8493 break;
8494 }
8495
8496 unsigned AdjustedNumArgs = NumArgs[Form];
8497 if ((IsOpenCL || IsHIP || IsScoped) &&
8498 Op != AtomicExpr::AO__opencl_atomic_init)
8499 ++AdjustedNumArgs;
8500 // Check we have the right number of arguments.
8501 if (Args.size() < AdjustedNumArgs) {
8502 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
8503 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
8504 << /*is non object*/ 0 << ExprRange;
8505 return ExprError();
8506 } else if (Args.size() > AdjustedNumArgs) {
8507 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
8508 diag::err_typecheck_call_too_many_args)
8509 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
8510 << /*is non object*/ 0 << ExprRange;
8511 return ExprError();
8512 }
8513
8514 // Inspect the first argument of the atomic operation.
8515 Expr *Ptr = Args[0];
8517 if (ConvertedPtr.isInvalid())
8518 return ExprError();
8519
8520 Ptr = ConvertedPtr.get();
8521 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
8522 if (!pointerType) {
8523 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
8524 << Ptr->getType() << Ptr->getSourceRange();
8525 return ExprError();
8526 }
8527
8528 // For a __c11 builtin, this should be a pointer to an _Atomic type.
8529 QualType AtomTy = pointerType->getPointeeType(); // 'A'
8530 QualType ValType = AtomTy; // 'C'
8531 if (IsC11) {
8532 if (!AtomTy->isAtomicType()) {
8533 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
8534 << Ptr->getType() << Ptr->getSourceRange();
8535 return ExprError();
8536 }
8537 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
8539 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
8540 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
8541 << Ptr->getSourceRange();
8542 return ExprError();
8543 }
8544 ValType = AtomTy->castAs<AtomicType>()->getValueType();
8545 } else if (Form != Load && Form != LoadCopy) {
8546 if (ValType.isConstQualified()) {
8547 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
8548 << Ptr->getType() << Ptr->getSourceRange();
8549 return ExprError();
8550 }
8551 }
8552
8553 // For an arithmetic operation, the implied arithmetic must be well-formed.
8554 if (Form == Arithmetic) {
8555 // GCC does not enforce these rules for GNU atomics, but we do to help catch
8556 // trivial type errors.
8557 auto IsAllowedValueType = [&](QualType ValType,
8558 unsigned AllowedType) -> bool {
8559 if (ValType->isIntegerType())
8560 return true;
8561 if (ValType->isPointerType())
8562 return AllowedType & AOEVT_Pointer;
8563 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
8564 return false;
8565 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
8566 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
8568 &llvm::APFloat::x87DoubleExtended())
8569 return false;
8570 return true;
8571 };
8572 if (!IsAllowedValueType(ValType, ArithAllows)) {
8573 auto DID = ArithAllows & AOEVT_FP
8574 ? (ArithAllows & AOEVT_Pointer
8575 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
8576 : diag::err_atomic_op_needs_atomic_int_or_fp)
8577 : diag::err_atomic_op_needs_atomic_int;
8578 Diag(ExprRange.getBegin(), DID)
8579 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
8580 return ExprError();
8581 }
8582 if (IsC11 && ValType->isPointerType() &&
8584 diag::err_incomplete_type)) {
8585 return ExprError();
8586 }
8587 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
8588 // For __atomic_*_n operations, the value type must be a scalar integral or
8589 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
8590 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
8591 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
8592 return ExprError();
8593 }
8594
8595 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
8596 !AtomTy->isScalarType()) {
8597 // For GNU atomics, require a trivially-copyable type. This is not part of
8598 // the GNU atomics specification but we enforce it for consistency with
8599 // other atomics which generally all require a trivially-copyable type. This
8600 // is because atomics just copy bits.
8601 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
8602 << Ptr->getType() << Ptr->getSourceRange();
8603 return ExprError();
8604 }
8605
8606 switch (ValType.getObjCLifetime()) {
8609 // okay
8610 break;
8611
8615 // FIXME: Can this happen? By this point, ValType should be known
8616 // to be trivially copyable.
8617 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
8618 << ValType << Ptr->getSourceRange();
8619 return ExprError();
8620 }
8621
8622 // All atomic operations have an overload which takes a pointer to a volatile
8623 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
8624 // into the result or the other operands. Similarly atomic_load takes a
8625 // pointer to a const 'A'.
8626 ValType.removeLocalVolatile();
8627 ValType.removeLocalConst();
8628 QualType ResultType = ValType;
8629 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
8630 Form == Init)
8631 ResultType = Context.VoidTy;
8632 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
8633 ResultType = Context.BoolTy;
8634
8635 // The type of a parameter passed 'by value'. In the GNU atomics, such
8636 // arguments are actually passed as pointers.
8637 QualType ByValType = ValType; // 'CP'
8638 bool IsPassedByAddress = false;
8639 if (!IsC11 && !IsHIP && !IsN) {
8640 ByValType = Ptr->getType();
8641 IsPassedByAddress = true;
8642 }
8643
8644 SmallVector<Expr *, 5> APIOrderedArgs;
8645 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
8646 APIOrderedArgs.push_back(Args[0]);
8647 switch (Form) {
8648 case Init:
8649 case Load:
8650 APIOrderedArgs.push_back(Args[1]); // Val1/Order
8651 break;
8652 case LoadCopy:
8653 case Copy:
8654 case Arithmetic:
8655 case Xchg:
8656 APIOrderedArgs.push_back(Args[2]); // Val1
8657 APIOrderedArgs.push_back(Args[1]); // Order
8658 break;
8659 case GNUXchg:
8660 APIOrderedArgs.push_back(Args[2]); // Val1
8661 APIOrderedArgs.push_back(Args[3]); // Val2
8662 APIOrderedArgs.push_back(Args[1]); // Order
8663 break;
8664 case C11CmpXchg:
8665 APIOrderedArgs.push_back(Args[2]); // Val1
8666 APIOrderedArgs.push_back(Args[4]); // Val2
8667 APIOrderedArgs.push_back(Args[1]); // Order
8668 APIOrderedArgs.push_back(Args[3]); // OrderFail
8669 break;
8670 case GNUCmpXchg:
8671 APIOrderedArgs.push_back(Args[2]); // Val1
8672 APIOrderedArgs.push_back(Args[4]); // Val2
8673 APIOrderedArgs.push_back(Args[5]); // Weak
8674 APIOrderedArgs.push_back(Args[1]); // Order
8675 APIOrderedArgs.push_back(Args[3]); // OrderFail
8676 break;
8677 }
8678 } else
8679 APIOrderedArgs.append(Args.begin(), Args.end());
8680
8681 // The first argument's non-CV pointer type is used to deduce the type of
8682 // subsequent arguments, except for:
8683 // - weak flag (always converted to bool)
8684 // - memory order (always converted to int)
8685 // - scope (always converted to int)
8686 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
8687 QualType Ty;
8688 if (i < NumVals[Form] + 1) {
8689 switch (i) {
8690 case 0:
8691 // The first argument is always a pointer. It has a fixed type.
8692 // It is always dereferenced, a nullptr is undefined.
8693 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
8694 // Nothing else to do: we already know all we want about this pointer.
8695 continue;
8696 case 1:
8697 // The second argument is the non-atomic operand. For arithmetic, this
8698 // is always passed by value, and for a compare_exchange it is always
8699 // passed by address. For the rest, GNU uses by-address and C11 uses
8700 // by-value.
8701 assert(Form != Load);
8702 if (Form == Arithmetic && ValType->isPointerType())
8704 else if (Form == Init || Form == Arithmetic)
8705 Ty = ValType;
8706 else if (Form == Copy || Form == Xchg) {
8707 if (IsPassedByAddress) {
8708 // The value pointer is always dereferenced, a nullptr is undefined.
8709 CheckNonNullArgument(*this, APIOrderedArgs[i],
8710 ExprRange.getBegin());
8711 }
8712 Ty = ByValType;
8713 } else {
8714 Expr *ValArg = APIOrderedArgs[i];
8715 // The value pointer is always dereferenced, a nullptr is undefined.
8716 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
8718 // Keep address space of non-atomic pointer type.
8719 if (const PointerType *PtrTy =
8720 ValArg->getType()->getAs<PointerType>()) {
8721 AS = PtrTy->getPointeeType().getAddressSpace();
8722 }
8725 }
8726 break;
8727 case 2:
8728 // The third argument to compare_exchange / GNU exchange is the desired
8729 // value, either by-value (for the C11 and *_n variant) or as a pointer.
8730 if (IsPassedByAddress)
8731 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
8732 Ty = ByValType;
8733 break;
8734 case 3:
8735 // The fourth argument to GNU compare_exchange is a 'weak' flag.
8736 Ty = Context.BoolTy;
8737 break;
8738 }
8739 } else {
8740 // The order(s) and scope are always converted to int.
8741 Ty = Context.IntTy;
8742 }
8743
8744 InitializedEntity Entity =
8746 ExprResult Arg = APIOrderedArgs[i];
8747 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
8748 if (Arg.isInvalid())
8749 return true;
8750 APIOrderedArgs[i] = Arg.get();
8751 }
8752
8753 // Permute the arguments into a 'consistent' order.
8754 SmallVector<Expr*, 5> SubExprs;
8755 SubExprs.push_back(Ptr);
8756 switch (Form) {
8757 case Init:
8758 // Note, AtomicExpr::getVal1() has a special case for this atomic.
8759 SubExprs.push_back(APIOrderedArgs[1]); // Val1
8760 break;
8761 case Load:
8762 SubExprs.push_back(APIOrderedArgs[1]); // Order
8763 break;
8764 case LoadCopy:
8765 case Copy:
8766 case Arithmetic:
8767 case Xchg:
8768 SubExprs.push_back(APIOrderedArgs[2]); // Order
8769 SubExprs.push_back(APIOrderedArgs[1]); // Val1
8770 break;
8771 case GNUXchg:
8772 // Note, AtomicExpr::getVal2() has a special case for this atomic.
8773 SubExprs.push_back(APIOrderedArgs[3]); // Order
8774 SubExprs.push_back(APIOrderedArgs[1]); // Val1
8775 SubExprs.push_back(APIOrderedArgs[2]); // Val2
8776 break;
8777 case C11CmpXchg:
8778 SubExprs.push_back(APIOrderedArgs[3]); // Order
8779 SubExprs.push_back(APIOrderedArgs[1]); // Val1
8780 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
8781 SubExprs.push_back(APIOrderedArgs[2]); // Val2
8782 break;
8783 case GNUCmpXchg:
8784 SubExprs.push_back(APIOrderedArgs[4]); // Order
8785 SubExprs.push_back(APIOrderedArgs[1]); // Val1
8786 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
8787 SubExprs.push_back(APIOrderedArgs[2]); // Val2
8788 SubExprs.push_back(APIOrderedArgs[3]); // Weak
8789 break;
8790 }
8791
8792 // If the memory orders are constants, check they are valid.
8793 if (SubExprs.size() >= 2 && Form != Init) {
8794 std::optional<llvm::APSInt> Success =
8795 SubExprs[1]->getIntegerConstantExpr(Context);
8796 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
8797 Diag(SubExprs[1]->getBeginLoc(),
8798 diag::warn_atomic_op_has_invalid_memory_order)
8799 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
8800 << SubExprs[1]->getSourceRange();
8801 }
8802 if (SubExprs.size() >= 5) {
8803 if (std::optional<llvm::APSInt> Failure =
8804 SubExprs[3]->getIntegerConstantExpr(Context)) {
8805 if (!llvm::is_contained(
8806 {llvm::AtomicOrderingCABI::relaxed,
8807 llvm::AtomicOrderingCABI::consume,
8808 llvm::AtomicOrderingCABI::acquire,
8809 llvm::AtomicOrderingCABI::seq_cst},
8810 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
8811 Diag(SubExprs[3]->getBeginLoc(),
8812 diag::warn_atomic_op_has_invalid_memory_order)
8813 << /*failure=*/2 << SubExprs[3]->getSourceRange();
8814 }
8815 }
8816 }
8817 }
8818
8819 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
8820 auto *Scope = Args[Args.size() - 1];
8821 if (std::optional<llvm::APSInt> Result =
8822 Scope->getIntegerConstantExpr(Context)) {
8823 if (!ScopeModel->isValid(Result->getZExtValue()))
8824 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
8825 << Scope->getSourceRange();
8826 }
8827 SubExprs.push_back(Scope);
8828 }
8829
8830 AtomicExpr *AE = new (Context)
8831 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
8832
8833 if ((Op == AtomicExpr::AO__c11_atomic_load ||
8834 Op == AtomicExpr::AO__c11_atomic_store ||
8835 Op == AtomicExpr::AO__opencl_atomic_load ||
8836 Op == AtomicExpr::AO__hip_atomic_load ||
8837 Op == AtomicExpr::AO__opencl_atomic_store ||
8838 Op == AtomicExpr::AO__hip_atomic_store) &&
8840 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
8841 << ((Op == AtomicExpr::AO__c11_atomic_load ||
8842 Op == AtomicExpr::AO__opencl_atomic_load ||
8843 Op == AtomicExpr::AO__hip_atomic_load)
8844 ? 0
8845 : 1);
8846
8847 if (ValType->isBitIntType()) {
8848 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
8849 return ExprError();
8850 }
8851
8852 return AE;
8853}
8854
8855/// checkBuiltinArgument - Given a call to a builtin function, perform
8856/// normal type-checking on the given argument, updating the call in
8857/// place. This is useful when a builtin function requires custom
8858/// type-checking for some of its arguments but not necessarily all of
8859/// them.
8860///
8861/// Returns true on error.
8862static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
8863 FunctionDecl *Fn = E->getDirectCallee();
8864 assert(Fn && "builtin call without direct callee!");
8865
8866 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
8867 InitializedEntity Entity =
8869
8870 ExprResult Arg = E->getArg(ArgIndex);
8871 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
8872 if (Arg.isInvalid())
8873 return true;
8874
8875 E->setArg(ArgIndex, Arg.get());
8876 return false;
8877}
8878
8879bool Sema::BuiltinWasmRefNullExtern(CallExpr *TheCall) {
8880 if (TheCall->getNumArgs() != 0)
8881 return true;
8882
8884
8885 return false;
8886}
8887
8888bool Sema::BuiltinWasmRefNullFunc(CallExpr *TheCall) {
8889 if (TheCall->getNumArgs() != 0) {
8890 Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_many_args)
8891 << 0 /*function call*/ << /*expected*/ 0 << TheCall->getNumArgs()
8892 << /*is non object*/ 0;
8893 return true;
8894 }
8895
8896 // This custom type checking code ensures that the nodes are as expected
8897 // in order to later on generate the necessary builtin.
8898 QualType Pointee = Context.getFunctionType(Context.VoidTy, {}, {});
8901 Type = Context.getAttributedType(attr::WebAssemblyFuncref, Type,
8902 Context.getPointerType(Pointee));
8903 TheCall->setType(Type);
8904
8905 return false;
8906}
8907
8908/// We have a call to a function like __sync_fetch_and_add, which is an
8909/// overloaded function based on the pointer type of its first argument.
8910/// The main BuildCallExpr routines have already promoted the types of
8911/// arguments because all of these calls are prototyped as void(...).
8912///
8913/// This function goes through and does final semantic checking for these
8914/// builtins, as well as generating any warnings.
8915ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
8916 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
8917 Expr *Callee = TheCall->getCallee();
8918 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
8919 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
8920
8921 // Ensure that we have at least one argument to do type inference from.
8922 if (TheCall->getNumArgs() < 1) {
8923 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
8924 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
8925 << Callee->getSourceRange();
8926 return ExprError();
8927 }
8928
8929 // Inspect the first argument of the atomic builtin. This should always be
8930 // a pointer type, whose element is an integral scalar or pointer type.
8931 // Because it is a pointer type, we don't have to worry about any implicit
8932 // casts here.
8933 // FIXME: We don't allow floating point scalars as input.
8934 Expr *FirstArg = TheCall->getArg(0);
8935 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
8936 if (FirstArgResult.isInvalid())
8937 return ExprError();
8938 FirstArg = FirstArgResult.get();
8939 TheCall->setArg(0, FirstArg);
8940
8941 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
8942 if (!pointerType) {
8943 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
8944 << FirstArg->getType() << FirstArg->getSourceRange();
8945 return ExprError();
8946 }
8947
8948 QualType ValType = pointerType->getPointeeType();
8949 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
8950 !ValType->isBlockPointerType()) {
8951 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
8952 << FirstArg->getType() << FirstArg->getSourceRange();
8953 return ExprError();
8954 }
8955
8956 if (ValType.isConstQualified()) {
8957 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
8958 << FirstArg->getType() << FirstArg->getSourceRange();
8959 return ExprError();
8960 }
8961
8962 switch (ValType.getObjCLifetime()) {
8965 // okay
8966 break;
8967
8971 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
8972 << ValType << FirstArg->getSourceRange();
8973 return ExprError();
8974 }
8975
8976 // Strip any qualifiers off ValType.
8977 ValType = ValType.getUnqualifiedType();
8978
8979 // The majority of builtins return a value, but a few have special return
8980 // types, so allow them to override appropriately below.
8981 QualType ResultType = ValType;
8982
8983 // We need to figure out which concrete builtin this maps onto. For example,
8984 // __sync_fetch_and_add with a 2 byte object turns into
8985 // __sync_fetch_and_add_2.
8986#define BUILTIN_ROW(x) \
8987 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
8988 Builtin::BI##x##_8, Builtin::BI##x##_16 }
8989
8990 static const unsigned BuiltinIndices[][5] = {
8991 BUILTIN_ROW(__sync_fetch_and_add),
8992 BUILTIN_ROW(__sync_fetch_and_sub),
8993 BUILTIN_ROW(__sync_fetch_and_or),
8994 BUILTIN_ROW(__sync_fetch_and_and),
8995 BUILTIN_ROW(__sync_fetch_and_xor),
8996 BUILTIN_ROW(__sync_fetch_and_nand),
8997
8998 BUILTIN_ROW(__sync_add_and_fetch),
8999 BUILTIN_ROW(__sync_sub_and_fetch),
9000 BUILTIN_ROW(__sync_and_and_fetch),
9001 BUILTIN_ROW(__sync_or_and_fetch),
9002 BUILTIN_ROW(__sync_xor_and_fetch),
9003 BUILTIN_ROW(__sync_nand_and_fetch),
9004
9005 BUILTIN_ROW(__sync_val_compare_and_swap),
9006 BUILTIN_ROW(__sync_bool_compare_and_swap),
9007 BUILTIN_ROW(__sync_lock_test_and_set),
9008 BUILTIN_ROW(__sync_lock_release),
9009 BUILTIN_ROW(__sync_swap)
9010 };
9011#undef BUILTIN_ROW
9012
9013 // Determine the index of the size.
9014 unsigned SizeIndex;
9015 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
9016 case 1: SizeIndex = 0; break;
9017 case 2: SizeIndex = 1; break;
9018 case 4: SizeIndex = 2; break;
9019 case 8: SizeIndex = 3; break;
9020 case 16: SizeIndex = 4; break;
9021 default:
9022 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
9023 << FirstArg->getType() << FirstArg->getSourceRange();
9024 return ExprError();
9025 }
9026
9027 // Each of these builtins has one pointer argument, followed by some number of
9028 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
9029 // that we ignore. Find out which row of BuiltinIndices to read from as well
9030 // as the number of fixed args.
9031 unsigned BuiltinID = FDecl->getBuiltinID();
9032 unsigned BuiltinIndex, NumFixed = 1;
9033 bool WarnAboutSemanticsChange = false;
9034 switch (BuiltinID) {
9035 default: llvm_unreachable("Unknown overloaded atomic builtin!");
9036 case Builtin::BI__sync_fetch_and_add:
9037 case Builtin::BI__sync_fetch_and_add_1:
9038 case Builtin::BI__sync_fetch_and_add_2:
9039 case Builtin::BI__sync_fetch_and_add_4:
9040 case Builtin::BI__sync_fetch_and_add_8:
9041 case Builtin::BI__sync_fetch_and_add_16:
9042 BuiltinIndex = 0;
9043 break;
9044
9045 case Builtin::BI__sync_fetch_and_sub:
9046 case Builtin::BI__sync_fetch_and_sub_1:
9047 case Builtin::BI__sync_fetch_and_sub_2:
9048 case Builtin::BI__sync_fetch_and_sub_4:
9049 case Builtin::BI__sync_fetch_and_sub_8:
9050 case Builtin::BI__sync_fetch_and_sub_16:
9051 BuiltinIndex = 1;
9052 break;
9053
9054 case Builtin::BI__sync_fetch_and_or:
9055 case Builtin::BI__sync_fetch_and_or_1:
9056 case Builtin::BI__sync_fetch_and_or_2:
9057 case Builtin::BI__sync_fetch_and_or_4:
9058 case Builtin::BI__sync_fetch_and_or_8:
9059 case Builtin::BI__sync_fetch_and_or_16:
9060 BuiltinIndex = 2;
9061 break;
9062
9063 case Builtin::BI__sync_fetch_and_and:
9064 case Builtin::BI__sync_fetch_and_and_1:
9065 case Builtin::BI__sync_fetch_and_and_2:
9066 case Builtin::BI__sync_fetch_and_and_4:
9067 case Builtin::BI__sync_fetch_and_and_8:
9068 case Builtin::BI__sync_fetch_and_and_16:
9069 BuiltinIndex = 3;
9070 break;
9071
9072 case Builtin::BI__sync_fetch_and_xor:
9073 case Builtin::BI__sync_fetch_and_xor_1:
9074 case Builtin::BI__sync_fetch_and_xor_2:
9075 case Builtin::BI__sync_fetch_and_xor_4:
9076 case Builtin::BI__sync_fetch_and_xor_8:
9077 case Builtin::BI__sync_fetch_and_xor_16:
9078 BuiltinIndex = 4;
9079 break;
9080
9081 case Builtin::BI__sync_fetch_and_nand:
9082 case Builtin::BI__sync_fetch_and_nand_1:
9083 case Builtin::BI__sync_fetch_and_nand_2:
9084 case Builtin::BI__sync_fetch_and_nand_4:
9085 case Builtin::BI__sync_fetch_and_nand_8:
9086 case Builtin::BI__sync_fetch_and_nand_16:
9087 BuiltinIndex = 5;
9088 WarnAboutSemanticsChange = true;
9089 break;
9090
9091 case Builtin::BI__sync_add_and_fetch:
9092 case Builtin::BI__sync_add_and_fetch_1:
9093 case Builtin::BI__sync_add_and_fetch_2:
9094 case Builtin::BI__sync_add_and_fetch_4:
9095 case Builtin::BI__sync_add_and_fetch_8:
9096 case Builtin::BI__sync_add_and_fetch_16:
9097 BuiltinIndex = 6;
9098 break;
9099
9100 case Builtin::BI__sync_sub_and_fetch:
9101 case Builtin::BI__sync_sub_and_fetch_1:
9102 case Builtin::BI__sync_sub_and_fetch_2:
9103 case Builtin::BI__sync_sub_and_fetch_4:
9104 case Builtin::BI__sync_sub_and_fetch_8:
9105 case Builtin::BI__sync_sub_and_fetch_16:
9106 BuiltinIndex = 7;
9107 break;
9108
9109 case Builtin::BI__sync_and_and_fetch:
9110 case Builtin::BI__sync_and_and_fetch_1:
9111 case Builtin::BI__sync_and_and_fetch_2:
9112 case Builtin::BI__sync_and_and_fetch_4:
9113 case Builtin::BI__sync_and_and_fetch_8:
9114 case Builtin::BI__sync_and_and_fetch_16:
9115 BuiltinIndex = 8;
9116 break;
9117
9118 case Builtin::BI__sync_or_and_fetch:
9119 case Builtin::BI__sync_or_and_fetch_1:
9120 case Builtin::BI__sync_or_and_fetch_2:
9121 case Builtin::BI__sync_or_and_fetch_4:
9122 case Builtin::BI__sync_or_and_fetch_8:
9123 case Builtin::BI__sync_or_and_fetch_16:
9124 BuiltinIndex = 9;
9125 break;
9126
9127 case Builtin::BI__sync_xor_and_fetch:
9128 case Builtin::BI__sync_xor_and_fetch_1:
9129 case Builtin::BI__sync_xor_and_fetch_2:
9130 case Builtin::BI__sync_xor_and_fetch_4:
9131 case Builtin::BI__sync_xor_and_fetch_8:
9132 case Builtin::BI__sync_xor_and_fetch_16:
9133 BuiltinIndex = 10;
9134 break;
9135
9136 case Builtin::BI__sync_nand_and_fetch:
9137 case Builtin::BI__sync_nand_and_fetch_1:
9138 case Builtin::BI__sync_nand_and_fetch_2:
9139 case Builtin::BI__sync_nand_and_fetch_4:
9140 case Builtin::BI__sync_nand_and_fetch_8:
9141 case Builtin::BI__sync_nand_and_fetch_16:
9142 BuiltinIndex = 11;
9143 WarnAboutSemanticsChange = true;
9144 break;
9145
9146 case Builtin::BI__sync_val_compare_and_swap:
9147 case Builtin::BI__sync_val_compare_and_swap_1:
9148 case Builtin::BI__sync_val_compare_and_swap_2:
9149 case Builtin::BI__sync_val_compare_and_swap_4:
9150 case Builtin::BI__sync_val_compare_and_swap_8:
9151 case Builtin::BI__sync_val_compare_and_swap_16:
9152 BuiltinIndex = 12;
9153 NumFixed = 2;
9154 break;
9155
9156 case Builtin::BI__sync_bool_compare_and_swap:
9157 case Builtin::BI__sync_bool_compare_and_swap_1:
9158 case Builtin::BI__sync_bool_compare_and_swap_2:
9159 case Builtin::BI__sync_bool_compare_and_swap_4:
9160 case Builtin::BI__sync_bool_compare_and_swap_8:
9161 case Builtin::BI__sync_bool_compare_and_swap_16:
9162 BuiltinIndex = 13;
9163 NumFixed = 2;
9164 ResultType = Context.BoolTy;
9165 break;
9166
9167 case Builtin::BI__sync_lock_test_and_set:
9168 case Builtin::BI__sync_lock_test_and_set_1:
9169 case Builtin::BI__sync_lock_test_and_set_2:
9170 case Builtin::BI__sync_lock_test_and_set_4:
9171 case Builtin::BI__sync_lock_test_and_set_8:
9172 case Builtin::BI__sync_lock_test_and_set_16:
9173 BuiltinIndex = 14;
9174 break;
9175
9176 case Builtin::BI__sync_lock_release:
9177 case Builtin::BI__sync_lock_release_1:
9178 case Builtin::BI__sync_lock_release_2:
9179 case Builtin::BI__sync_lock_release_4:
9180 case Builtin::BI__sync_lock_release_8:
9181 case Builtin::BI__sync_lock_release_16:
9182 BuiltinIndex = 15;
9183 NumFixed = 0;
9184 ResultType = Context.VoidTy;
9185 break;
9186
9187 case Builtin::BI__sync_swap:
9188 case Builtin::BI__sync_swap_1:
9189 case Builtin::BI__sync_swap_2:
9190 case Builtin::BI__sync_swap_4:
9191 case Builtin::BI__sync_swap_8:
9192 case Builtin::BI__sync_swap_16:
9193 BuiltinIndex = 16;
9194 break;
9195 }
9196
9197 // Now that we know how many fixed arguments we expect, first check that we
9198 // have at least that many.
9199 if (TheCall->getNumArgs() < 1+NumFixed) {
9200 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
9201 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
9202 << Callee->getSourceRange();
9203 return ExprError();
9204 }
9205
9206 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
9207 << Callee->getSourceRange();
9208
9209 if (WarnAboutSemanticsChange) {
9210 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
9211 << Callee->getSourceRange();
9212 }
9213
9214 // Get the decl for the concrete builtin from this, we can tell what the
9215 // concrete integer type we should convert to is.
9216 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
9217 StringRef NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
9218 FunctionDecl *NewBuiltinDecl;
9219 if (NewBuiltinID == BuiltinID)
9220 NewBuiltinDecl = FDecl;
9221 else {
9222 // Perform builtin lookup to avoid redeclaring it.
9223 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
9224 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
9225 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
9226 assert(Res.getFoundDecl());
9227 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
9228 if (!NewBuiltinDecl)
9229 return ExprError();
9230 }
9231
9232 // The first argument --- the pointer --- has a fixed type; we
9233 // deduce the types of the rest of the arguments accordingly. Walk
9234 // the remaining arguments, converting them to the deduced value type.
9235 for (unsigned i = 0; i != NumFixed; ++i) {
9236 ExprResult Arg = TheCall->getArg(i+1);
9237
9238 // GCC does an implicit conversion to the pointer or integer ValType. This
9239 // can fail in some cases (1i -> int**), check for this error case now.
9240 // Initialize the argument.
9242 ValType, /*consume*/ false);
9243 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
9244 if (Arg.isInvalid())
9245 return ExprError();
9246
9247 // Okay, we have something that *can* be converted to the right type. Check
9248 // to see if there is a potentially weird extension going on here. This can
9249 // happen when you do an atomic operation on something like an char* and
9250 // pass in 42. The 42 gets converted to char. This is even more strange
9251 // for things like 45.123 -> char, etc.
9252 // FIXME: Do this check.
9253 TheCall->setArg(i+1, Arg.get());
9254 }
9255
9256 // Create a new DeclRefExpr to refer to the new decl.
9258 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
9259 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
9260 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
9261
9262 // Set the callee in the CallExpr.
9263 // FIXME: This loses syntactic information.
9264 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
9265 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
9266 CK_BuiltinFnToFnPtr);
9267 TheCall->setCallee(PromotedCall.get());
9268
9269 // Change the result type of the call to match the original value type. This
9270 // is arbitrary, but the codegen for these builtins ins design to handle it
9271 // gracefully.
9272 TheCall->setType(ResultType);
9273
9274 // Prohibit problematic uses of bit-precise integer types with atomic
9275 // builtins. The arguments would have already been converted to the first
9276 // argument's type, so only need to check the first argument.
9277 const auto *BitIntValType = ValType->getAs<BitIntType>();
9278 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
9279 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
9280 return ExprError();
9281 }
9282
9283 return TheCallResult;
9284}
9285
9286/// BuiltinNontemporalOverloaded - We have a call to
9287/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
9288/// overloaded function based on the pointer type of its last argument.
9289///
9290/// This function goes through and does final semantic checking for these
9291/// builtins.
9292ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
9293 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
9294 DeclRefExpr *DRE =
9295 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
9296 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
9297 unsigned BuiltinID = FDecl->getBuiltinID();
9298 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
9299 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
9300 "Unexpected nontemporal load/store builtin!");
9301 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
9302 unsigned numArgs = isStore ? 2 : 1;
9303
9304 // Ensure that we have the proper number of arguments.
9305 if (checkArgCount(*this, TheCall, numArgs))
9306 return ExprError();
9307
9308 // Inspect the last argument of the nontemporal builtin. This should always
9309 // be a pointer type, from which we imply the type of the memory access.
9310 // Because it is a pointer type, we don't have to worry about any implicit
9311 // casts here.
9312 Expr *PointerArg = TheCall->getArg(numArgs - 1);
9313 ExprResult PointerArgResult =
9315
9316 if (PointerArgResult.isInvalid())
9317 return ExprError();
9318 PointerArg = PointerArgResult.get();
9319 TheCall->setArg(numArgs - 1, PointerArg);
9320
9321 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
9322 if (!pointerType) {
9323 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
9324 << PointerArg->getType() << PointerArg->getSourceRange();
9325 return ExprError();
9326 }
9327
9328 QualType ValType = pointerType->getPointeeType();
9329
9330 // Strip any qualifiers off ValType.
9331 ValType = ValType.getUnqualifiedType();
9332 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
9333 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
9334 !ValType->isVectorType()) {
9335 Diag(DRE->getBeginLoc(),
9336 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
9337 << PointerArg->getType() << PointerArg->getSourceRange();
9338 return ExprError();
9339 }
9340
9341 if (!isStore) {
9342 TheCall->setType(ValType);
9343 return TheCallResult;
9344 }
9345
9346 ExprResult ValArg = TheCall->getArg(0);
9348 Context, ValType, /*consume*/ false);
9349 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
9350 if (ValArg.isInvalid())
9351 return ExprError();
9352
9353 TheCall->setArg(0, ValArg.get());
9354 TheCall->setType(Context.VoidTy);
9355 return TheCallResult;
9356}
9357
9358/// CheckObjCString - Checks that the format string argument to the os_log()
9359/// and os_trace() functions is correct, and converts it to const char *.
9360ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
9361 Arg = Arg->IgnoreParenCasts();
9362 auto *Literal = dyn_cast<StringLiteral>(Arg);
9363 if (!Literal) {
9364 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
9365 Literal = ObjcLiteral->getString();
9366 }
9367 }
9368
9369 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
9370 return ExprError(
9371 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
9372 << Arg->getSourceRange());
9373 }
9374
9375 ExprResult Result(Literal);
9377 InitializedEntity Entity =
9380 return Result;
9381}
9382
9383/// Check that the user is calling the appropriate va_start builtin for the
9384/// target and calling convention.
9385static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
9386 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
9387 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
9388 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
9389 TT.getArch() == llvm::Triple::aarch64_32);
9390 bool IsWindows = TT.isOSWindows();
9391 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
9392 if (IsX64 || IsAArch64) {
9393 CallingConv CC = CC_C;
9394 if (const FunctionDecl *FD = S.getCurFunctionDecl())
9395 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
9396 if (IsMSVAStart) {
9397 // Don't allow this in System V ABI functions.
9398 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
9399 return S.Diag(Fn->getBeginLoc(),
9400 diag::err_ms_va_start_used_in_sysv_function);
9401 } else {
9402 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
9403 // On x64 Windows, don't allow this in System V ABI functions.
9404 // (Yes, that means there's no corresponding way to support variadic
9405 // System V ABI functions on Windows.)
9406 if ((IsWindows && CC == CC_X86_64SysV) ||
9407 (!IsWindows && CC == CC_Win64))
9408 return S.Diag(Fn->getBeginLoc(),
9409 diag::err_va_start_used_in_wrong_abi_function)
9410 << !IsWindows;
9411 }
9412 return false;
9413 }
9414
9415 if (IsMSVAStart)
9416 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
9417 return false;
9418}
9419
9421 ParmVarDecl **LastParam = nullptr) {
9422 // Determine whether the current function, block, or obj-c method is variadic
9423 // and get its parameter list.
9424 bool IsVariadic = false;
9426 DeclContext *Caller = S.CurContext;
9427 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
9428 IsVariadic = Block->isVariadic();
9429 Params = Block->parameters();
9430 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
9431 IsVariadic = FD->isVariadic();
9432 Params = FD->parameters();
9433 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
9434 IsVariadic = MD->isVariadic();
9435 // FIXME: This isn't correct for methods (results in bogus warning).
9436 Params = MD->parameters();
9437 } else if (isa<CapturedDecl>(Caller)) {
9438 // We don't support va_start in a CapturedDecl.
9439 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
9440 return true;
9441 } else {
9442 // This must be some other declcontext that parses exprs.
9443 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
9444 return true;
9445 }
9446
9447 if (!IsVariadic) {
9448 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
9449 return true;
9450 }
9451
9452 if (LastParam)
9453 *LastParam = Params.empty() ? nullptr : Params.back();
9454
9455 return false;
9456}
9457
9458/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
9459/// for validity. Emit an error and return true on failure; return false
9460/// on success.
9461bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
9462 Expr *Fn = TheCall->getCallee();
9463
9464 if (checkVAStartABI(*this, BuiltinID, Fn))
9465 return true;
9466
9467 // In C23 mode, va_start only needs one argument. However, the builtin still
9468 // requires two arguments (which matches the behavior of the GCC builtin),
9469 // <stdarg.h> passes `0` as the second argument in C23 mode.
9470 if (checkArgCount(*this, TheCall, 2))
9471 return true;
9472
9473 // Type-check the first argument normally.
9474 if (checkBuiltinArgument(*this, TheCall, 0))
9475 return true;
9476
9477 // Check that the current function is variadic, and get its last parameter.
9478 ParmVarDecl *LastParam;
9479 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
9480 return true;
9481
9482 // Verify that the second argument to the builtin is the last argument of the
9483 // current function or method. In C23 mode, if the second argument is an
9484 // integer constant expression with value 0, then we don't bother with this
9485 // check.
9486 bool SecondArgIsLastNamedArgument = false;
9487 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
9488 if (std::optional<llvm::APSInt> Val =
9490 Val && LangOpts.C23 && *Val == 0)
9491 return false;
9492
9493 // These are valid if SecondArgIsLastNamedArgument is false after the next
9494 // block.
9495 QualType Type;
9496 SourceLocation ParamLoc;
9497 bool IsCRegister = false;
9498
9499 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
9500 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
9501 SecondArgIsLastNamedArgument = PV == LastParam;
9502
9503 Type = PV->getType();
9504 ParamLoc = PV->getLocation();
9505 IsCRegister =
9506 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
9507 }
9508 }
9509
9510 if (!SecondArgIsLastNamedArgument)
9511 Diag(TheCall->getArg(1)->getBeginLoc(),
9512 diag::warn_second_arg_of_va_start_not_last_named_param);
9513 else if (IsCRegister || Type->isReferenceType() ||
9514 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
9515 // Promotable integers are UB, but enumerations need a bit of
9516 // extra checking to see what their promotable type actually is.
9517 if (!Context.isPromotableIntegerType(Type))
9518 return false;
9519 if (!Type->isEnumeralType())
9520 return true;
9521 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
9522 return !(ED &&
9523 Context.typesAreCompatible(ED->getPromotionType(), Type));
9524 }()) {
9525 unsigned Reason = 0;
9526 if (Type->isReferenceType()) Reason = 1;
9527 else if (IsCRegister) Reason = 2;
9528 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
9529 Diag(ParamLoc, diag::note_parameter_type) << Type;
9530 }
9531
9532 return false;
9533}
9534
9535bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
9536 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
9537 const LangOptions &LO = getLangOpts();
9538
9539 if (LO.CPlusPlus)
9540 return Arg->getType()
9542 .getTypePtr()
9543 ->getPointeeType()
9545
9546 // In C, allow aliasing through `char *`, this is required for AArch64 at
9547 // least.
9548 return true;
9549 };
9550
9551 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
9552 // const char *named_addr);
9553
9554 Expr *Func = Call->getCallee();
9555
9556 if (Call->getNumArgs() < 3)
9557 return Diag(Call->getEndLoc(),
9558 diag::err_typecheck_call_too_few_args_at_least)
9559 << 0 /*function call*/ << 3 << Call->getNumArgs()
9560 << /*is non object*/ 0;
9561
9562 // Type-check the first argument normally.
9563 if (checkBuiltinArgument(*this, Call, 0))
9564 return true;
9565
9566 // Check that the current function is variadic.
9568 return true;
9569
9570 // __va_start on Windows does not validate the parameter qualifiers
9571
9572 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
9573 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
9574
9575 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
9576 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
9577
9578 const QualType &ConstCharPtrTy =
9580 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
9581 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
9582 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
9583 << 0 /* qualifier difference */
9584 << 3 /* parameter mismatch */
9585 << 2 << Arg1->getType() << ConstCharPtrTy;
9586
9587 const QualType SizeTy = Context.getSizeType();
9588 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
9589 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
9590 << Arg2->getType() << SizeTy << 1 /* different class */
9591 << 0 /* qualifier difference */
9592 << 3 /* parameter mismatch */
9593 << 3 << Arg2->getType() << SizeTy;
9594
9595 return false;
9596}
9597
9598/// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
9599/// friends. This is declared to take (...), so we have to check everything.
9600bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
9601 if (checkArgCount(*this, TheCall, 2))
9602 return true;
9603
9604 if (BuiltinID == Builtin::BI__builtin_isunordered &&
9605 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
9606 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9607 << 1 << 0 << TheCall->getSourceRange();
9608
9609 ExprResult OrigArg0 = TheCall->getArg(0);
9610 ExprResult OrigArg1 = TheCall->getArg(1);
9611
9612 // Do standard promotions between the two arguments, returning their common
9613 // type.
9615 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
9616 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
9617 return true;
9618
9619 // Make sure any conversions are pushed back into the call; this is
9620 // type safe since unordered compare builtins are declared as "_Bool
9621 // foo(...)".
9622 TheCall->setArg(0, OrigArg0.get());
9623 TheCall->setArg(1, OrigArg1.get());
9624
9625 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
9626 return false;
9627
9628 // If the common type isn't a real floating type, then the arguments were
9629 // invalid for this operation.
9630 if (Res.isNull() || !Res->isRealFloatingType())
9631 return Diag(OrigArg0.get()->getBeginLoc(),
9632 diag::err_typecheck_call_invalid_ordered_compare)
9633 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
9634 << SourceRange(OrigArg0.get()->getBeginLoc(),
9635 OrigArg1.get()->getEndLoc());
9636
9637 return false;
9638}
9639
9640/// BuiltinSemaBuiltinFPClassification - Handle functions like
9641/// __builtin_isnan and friends. This is declared to take (...), so we have
9642/// to check everything.
9643bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
9644 unsigned BuiltinID) {
9645 if (checkArgCount(*this, TheCall, NumArgs))
9646 return true;
9647
9649 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
9650 BuiltinID == Builtin::BI__builtin_isinf ||
9651 BuiltinID == Builtin::BI__builtin_isinf_sign))
9652 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9653 << 0 << 0 << TheCall->getSourceRange();
9654
9655 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
9656 BuiltinID == Builtin::BI__builtin_isunordered))
9657 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9658 << 1 << 0 << TheCall->getSourceRange();
9659
9660 bool IsFPClass = NumArgs == 2;
9661
9662 // Find out position of floating-point argument.
9663 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
9664
9665 // We can count on all parameters preceding the floating-point just being int.
9666 // Try all of those.
9667 for (unsigned i = 0; i < FPArgNo; ++i) {
9668 Expr *Arg = TheCall->getArg(i);
9669
9670 if (Arg->isTypeDependent())
9671 return false;
9672
9674
9675 if (Res.isInvalid())
9676 return true;
9677 TheCall->setArg(i, Res.get());
9678 }
9679
9680 Expr *OrigArg = TheCall->getArg(FPArgNo);
9681
9682 if (OrigArg->isTypeDependent())
9683 return false;
9684
9685 // Usual Unary Conversions will convert half to float, which we want for
9686 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
9687 // type how it is, but do normal L->Rvalue conversions.
9689 OrigArg = UsualUnaryConversions(OrigArg).get();
9690 else
9691 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
9692 TheCall->setArg(FPArgNo, OrigArg);
9693
9694 QualType VectorResultTy;
9695 QualType ElementTy = OrigArg->getType();
9696 // TODO: When all classification function are implemented with is_fpclass,
9697 // vector argument can be supported in all of them.
9698 if (ElementTy->isVectorType() && IsFPClass) {
9699 VectorResultTy = GetSignedVectorType(ElementTy);
9700 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
9701 }
9702
9703 // This operation requires a non-_Complex floating-point number.
9704 if (!ElementTy->isRealFloatingType())
9705 return Diag(OrigArg->getBeginLoc(),
9706 diag::err_typecheck_call_invalid_unary_fp)
9707 << OrigArg->getType() << OrigArg->getSourceRange();
9708
9709 // __builtin_isfpclass has integer parameter that specify test mask. It is
9710 // passed in (...), so it should be analyzed completely here.
9711 if (IsFPClass)
9712 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
9713 return true;
9714
9715 // TODO: enable this code to all classification functions.
9716 if (IsFPClass) {
9717 QualType ResultTy;
9718 if (!VectorResultTy.isNull())
9719 ResultTy = VectorResultTy;
9720 else
9721 ResultTy = Context.IntTy;
9722 TheCall->setType(ResultTy);
9723 }
9724
9725 return false;
9726}
9727
9728/// Perform semantic analysis for a call to __builtin_complex.
9729bool Sema::BuiltinComplex(CallExpr *TheCall) {
9730 if (checkArgCount(*this, TheCall, 2))
9731 return true;
9732
9733 bool Dependent = false;
9734 for (unsigned I = 0; I != 2; ++I) {
9735 Expr *Arg = TheCall->getArg(I);
9736 QualType T = Arg->getType();
9737 if (T->isDependentType()) {
9738 Dependent = true;
9739 continue;
9740 }
9741
9742 // Despite supporting _Complex int, GCC requires a real floating point type
9743 // for the operands of __builtin_complex.
9744 if (!T->isRealFloatingType()) {
9745 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
9746 << Arg->getType() << Arg->getSourceRange();
9747 }
9748
9749 ExprResult Converted = DefaultLvalueConversion(Arg);
9750 if (Converted.isInvalid())
9751 return true;
9752 TheCall->setArg(I, Converted.get());
9753 }
9754
9755 if (Dependent) {
9756 TheCall->setType(Context.DependentTy);
9757 return false;
9758 }
9759
9760 Expr *Real = TheCall->getArg(0);
9761 Expr *Imag = TheCall->getArg(1);
9762 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
9763 return Diag(Real->getBeginLoc(),
9764 diag::err_typecheck_call_different_arg_types)
9765 << Real->getType() << Imag->getType()
9766 << Real->getSourceRange() << Imag->getSourceRange();
9767 }
9768
9769 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
9770 // don't allow this builtin to form those types either.
9771 // FIXME: Should we allow these types?
9772 if (Real->getType()->isFloat16Type())
9773 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
9774 << "_Float16";
9775 if (Real->getType()->isHalfType())
9776 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
9777 << "half";
9778
9779 TheCall->setType(Context.getComplexType(Real->getType()));
9780 return false;
9781}
9782
9783// Customized Sema Checking for VSX builtins that have the following signature:
9784// vector [...] builtinName(vector [...], vector [...], const int);
9785// Which takes the same type of vectors (any legal vector type) for the first
9786// two arguments and takes compile time constant for the third argument.
9787// Example builtins are :
9788// vector double vec_xxpermdi(vector double, vector double, int);
9789// vector short vec_xxsldwi(vector short, vector short, int);
9790bool Sema::BuiltinVSX(CallExpr *TheCall) {
9791 unsigned ExpectedNumArgs = 3;
9792 if (checkArgCount(*this, TheCall, ExpectedNumArgs))
9793 return true;
9794
9795 // Check the third argument is a compile time constant
9796 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
9797 return Diag(TheCall->getBeginLoc(),
9798 diag::err_vsx_builtin_nonconstant_argument)
9799 << 3 /* argument index */ << TheCall->getDirectCallee()
9800 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
9801 TheCall->getArg(2)->getEndLoc());
9802
9803 QualType Arg1Ty = TheCall->getArg(0)->getType();
9804 QualType Arg2Ty = TheCall->getArg(1)->getType();
9805
9806 // Check the type of argument 1 and argument 2 are vectors.
9807 SourceLocation BuiltinLoc = TheCall->getBeginLoc();
9808 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
9809 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
9810 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
9811 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ false
9812 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
9813 TheCall->getArg(1)->getEndLoc());
9814 }
9815
9816 // Check the first two arguments are the same type.
9817 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
9818 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
9819 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ false
9820 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
9821 TheCall->getArg(1)->getEndLoc());
9822 }
9823
9824 // When default clang type checking is turned off and the customized type
9825 // checking is used, the returning type of the function must be explicitly
9826 // set. Otherwise it is _Bool by default.
9827 TheCall->setType(Arg1Ty);
9828
9829 return false;
9830}
9831
9832/// BuiltinShuffleVector - Handle __builtin_shufflevector.
9833// This is declared to take (...), so we have to check everything.
9835 if (TheCall->getNumArgs() < 2)
9836 return ExprError(Diag(TheCall->getEndLoc(),
9837 diag::err_typecheck_call_too_few_args_at_least)
9838 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
9839 << /*is non object*/ 0 << TheCall->getSourceRange());
9840
9841 // Determine which of the following types of shufflevector we're checking:
9842 // 1) unary, vector mask: (lhs, mask)
9843 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
9844 QualType resType = TheCall->getArg(0)->getType();
9845 unsigned numElements = 0;
9846
9847 if (!TheCall->getArg(0)->isTypeDependent() &&
9848 !TheCall->getArg(1)->isTypeDependent()) {
9849 QualType LHSType = TheCall->getArg(0)->getType();
9850 QualType RHSType = TheCall->getArg(1)->getType();
9851
9852 if (!LHSType->isVectorType() || !RHSType->isVectorType())
9853 return ExprError(
9854 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
9855 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ false
9856 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
9857 TheCall->getArg(1)->getEndLoc()));
9858
9859 numElements = LHSType->castAs<VectorType>()->getNumElements();
9860 unsigned numResElements = TheCall->getNumArgs() - 2;
9861
9862 // Check to see if we have a call with 2 vector arguments, the unary shuffle
9863 // with mask. If so, verify that RHS is an integer vector type with the
9864 // same number of elts as lhs.
9865 if (TheCall->getNumArgs() == 2) {
9866 if (!RHSType->hasIntegerRepresentation() ||
9867 RHSType->castAs<VectorType>()->getNumElements() != numElements)
9868 return ExprError(Diag(TheCall->getBeginLoc(),
9869 diag::err_vec_builtin_incompatible_vector)
9870 << TheCall->getDirectCallee()
9871 << /*isMorethantwoArgs*/ false
9872 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
9873 TheCall->getArg(1)->getEndLoc()));
9874 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
9875 return ExprError(Diag(TheCall->getBeginLoc(),
9876 diag::err_vec_builtin_incompatible_vector)
9877 << TheCall->getDirectCallee()
9878 << /*isMorethantwoArgs*/ false
9879 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
9880 TheCall->getArg(1)->getEndLoc()));
9881 } else if (numElements != numResElements) {
9882 QualType eltType = LHSType->castAs<VectorType>()->getElementType();
9883 resType =
9884 Context.getVectorType(eltType, numResElements, VectorKind::Generic);
9885 }
9886 }
9887
9888 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
9889 if (TheCall->getArg(i)->isTypeDependent() ||
9890 TheCall->getArg(i)->isValueDependent())
9891 continue;
9892
9893 std::optional<llvm::APSInt> Result;
9894 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
9895 return ExprError(Diag(TheCall->getBeginLoc(),
9896 diag::err_shufflevector_nonconstant_argument)
9897 << TheCall->getArg(i)->getSourceRange());
9898
9899 // Allow -1 which will be translated to undef in the IR.
9900 if (Result->isSigned() && Result->isAllOnes())
9901 continue;
9902
9903 if (Result->getActiveBits() > 64 ||
9904 Result->getZExtValue() >= numElements * 2)
9905 return ExprError(Diag(TheCall->getBeginLoc(),
9906 diag::err_shufflevector_argument_too_large)
9907 << TheCall->getArg(i)->getSourceRange());
9908 }
9909
9911
9912 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
9913 exprs.push_back(TheCall->getArg(i));
9914 TheCall->setArg(i, nullptr);
9915 }
9916
9917 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
9918 TheCall->getCallee()->getBeginLoc(),
9919 TheCall->getRParenLoc());
9920}
9921
9922/// ConvertVectorExpr - Handle __builtin_convertvector
9924 SourceLocation BuiltinLoc,
9925 SourceLocation RParenLoc) {
9928 QualType DstTy = TInfo->getType();
9929 QualType SrcTy = E->getType();
9930
9931 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
9932 return ExprError(Diag(BuiltinLoc,
9933 diag::err_convertvector_non_vector)
9934 << E->getSourceRange());
9935 if (!DstTy->isVectorType() && !DstTy->isDependentType())
9936 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
9937 << "second"
9938 << "__builtin_convertvector");
9939
9940 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
9941 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
9942 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
9943 if (SrcElts != DstElts)
9944 return ExprError(Diag(BuiltinLoc,
9945 diag::err_convertvector_incompatible_vector)
9946 << E->getSourceRange());
9947 }
9948
9949 return new (Context) class ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
9950 BuiltinLoc, RParenLoc);
9951}
9952
9953/// BuiltinPrefetch - Handle __builtin_prefetch.
9954// This is declared to take (const void*, ...) and can take two
9955// optional constant int args.
9956bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
9957 unsigned NumArgs = TheCall->getNumArgs();
9958
9959 if (NumArgs > 3)
9960 return Diag(TheCall->getEndLoc(),
9961 diag::err_typecheck_call_too_many_args_at_most)
9962 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
9963 << TheCall->getSourceRange();
9964
9965 // Argument 0 is checked for us and the remaining arguments must be
9966 // constant integers.
9967 for (unsigned i = 1; i != NumArgs; ++i)
9968 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
9969 return true;
9970
9971 return false;
9972}
9973
9974/// BuiltinArithmeticFence - Handle __arithmetic_fence.
9975bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
9977 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
9978 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
9979 if (checkArgCount(*this, TheCall, 1))
9980 return true;
9981 Expr *Arg = TheCall->getArg(0);
9982 if (Arg->isInstantiationDependent())
9983 return false;
9984
9985 QualType ArgTy = Arg->getType();
9986 if (!ArgTy->hasFloatingRepresentation())
9987 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
9988 << ArgTy;
9989 if (Arg->isLValue()) {
9990 ExprResult FirstArg = DefaultLvalueConversion(Arg);
9991 TheCall->setArg(0, FirstArg.get());
9992 }
9993 TheCall->setType(TheCall->getArg(0)->getType());
9994 return false;
9995}
9996
9997/// BuiltinAssume - Handle __assume (MS Extension).
9998// __assume does not evaluate its arguments, and should warn if its argument
9999// has side effects.
10000bool Sema::BuiltinAssume(CallExpr *TheCall) {
10001 Expr *Arg = TheCall->getArg(0);
10002 if (Arg->isInstantiationDependent()) return false;
10003
10004 if (Arg->HasSideEffects(Context))
10005 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
10006 << Arg->getSourceRange()
10007 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
10008
10009 return false;
10010}
10011
10012/// Handle __builtin_alloca_with_align. This is declared
10013/// as (size_t, size_t) where the second size_t must be a power of 2 greater
10014/// than 8.
10015bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
10016 // The alignment must be a constant integer.
10017 Expr *Arg = TheCall->getArg(1);
10018
10019 // We can't check the value of a dependent argument.
10020 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
10021 if (const auto *UE =
10022 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
10023 if (UE->getKind() == UETT_AlignOf ||
10024 UE->getKind() == UETT_PreferredAlignOf)
10025 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
10026 << Arg->getSourceRange();
10027
10028 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
10029
10030 if (!Result.isPowerOf2())
10031 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
10032 << Arg->getSourceRange();
10033
10034 if (Result < Context.getCharWidth())
10035 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
10037
10038 if (Result > std::numeric_limits<int32_t>::max())
10039 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
10040 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
10041 }
10042
10043 return false;
10044}
10045
10046/// Handle __builtin_assume_aligned. This is declared
10047/// as (const void*, size_t, ...) and can take one optional constant int arg.
10048bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
10049 if (checkArgCountRange(*this, TheCall, 2, 3))
10050 return true;
10051
10052 unsigned NumArgs = TheCall->getNumArgs();
10053 Expr *FirstArg = TheCall->getArg(0);
10054
10055 {
10056 ExprResult FirstArgResult =
10058 if (checkBuiltinArgument(*this, TheCall, 0))
10059 return true;
10060 /// In-place updation of FirstArg by checkBuiltinArgument is ignored.
10061 TheCall->setArg(0, FirstArgResult.get());
10062 }
10063
10064 // The alignment must be a constant integer.
10065 Expr *SecondArg = TheCall->getArg(1);
10066
10067 // We can't check the value of a dependent argument.
10068 if (!SecondArg->isValueDependent()) {
10069 llvm::APSInt Result;
10070 if (BuiltinConstantArg(TheCall, 1, Result))
10071 return true;
10072
10073 if (!Result.isPowerOf2())
10074 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
10075 << SecondArg->getSourceRange();
10076
10078 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
10079 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
10080 }
10081
10082 if (NumArgs > 2) {
10083 Expr *ThirdArg = TheCall->getArg(2);
10084 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
10085 return true;
10086 TheCall->setArg(2, ThirdArg);
10087 }
10088
10089 return false;
10090}
10091
10092bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
10093 unsigned BuiltinID =
10094 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
10095 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
10096
10097 unsigned NumArgs = TheCall->getNumArgs();
10098 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
10099 if (NumArgs < NumRequiredArgs) {
10100 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
10101 << 0 /* function call */ << NumRequiredArgs << NumArgs
10102 << /*is non object*/ 0 << TheCall->getSourceRange();
10103 }
10104 if (NumArgs >= NumRequiredArgs + 0x100) {
10105 return Diag(TheCall->getEndLoc(),
10106 diag::err_typecheck_call_too_many_args_at_most)
10107 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
10108 << /*is non object*/ 0 << TheCall->getSourceRange();
10109 }
10110 unsigned i = 0;
10111
10112 // For formatting call, check buffer arg.
10113 if (!IsSizeCall) {
10114 ExprResult Arg(TheCall->getArg(i));
10116 Context, Context.VoidPtrTy, false);
10117 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
10118 if (Arg.isInvalid())
10119 return true;
10120 TheCall->setArg(i, Arg.get());
10121 i++;
10122 }
10123
10124 // Check string literal arg.
10125 unsigned FormatIdx = i;
10126 {
10127 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
10128 if (Arg.isInvalid())
10129 return true;
10130 TheCall->setArg(i, Arg.get());
10131 i++;
10132 }
10133
10134 // Make sure variadic args are scalar.
10135 unsigned FirstDataArg = i;
10136 while (i < NumArgs) {
10138 TheCall->getArg(i), VariadicFunction, nullptr);
10139 if (Arg.isInvalid())
10140 return true;
10141 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
10142 if (ArgSize.getQuantity() >= 0x100) {
10143 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
10144 << i << (int)ArgSize.getQuantity() << 0xff
10145 << TheCall->getSourceRange();
10146 }
10147 TheCall->setArg(i, Arg.get());
10148 i++;
10149 }
10150
10151 // Check formatting specifiers. NOTE: We're only doing this for the non-size
10152 // call to avoid duplicate diagnostics.
10153 if (!IsSizeCall) {
10154 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
10155 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
10156 bool Success = CheckFormatArguments(
10157 Args, FAPK_Variadic, FormatIdx, FirstDataArg, FST_OSLog,
10159 CheckedVarArgs);
10160 if (!Success)
10161 return true;
10162 }
10163
10164 if (IsSizeCall) {
10165 TheCall->setType(Context.getSizeType());
10166 } else {
10167 TheCall->setType(Context.VoidPtrTy);
10168 }
10169 return false;
10170}
10171
10172/// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
10173/// TheCall is a constant expression.
10174bool Sema::BuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10175 llvm::APSInt &Result) {
10176 Expr *Arg = TheCall->getArg(ArgNum);
10177 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
10178 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
10179
10180 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
10181
10182 std::optional<llvm::APSInt> R;
10183 if (!(R = Arg->getIntegerConstantExpr(Context)))
10184 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
10185 << FDecl->getDeclName() << Arg->getSourceRange();
10186 Result = *R;
10187 return false;
10188}
10189
10190/// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
10191/// TheCall is a constant expression in the range [Low, High].
10192bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
10193 int High, bool RangeIsError) {
10195 return false;
10196 llvm::APSInt Result;
10197
10198 // We can't check the value of a dependent argument.
10199 Expr *Arg = TheCall->getArg(ArgNum);
10200 if (Arg->isTypeDependent() || Arg->isValueDependent())
10201 return false;
10202
10203 // Check constant-ness first.
10204 if (BuiltinConstantArg(TheCall, ArgNum, Result))
10205 return true;
10206
10207 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
10208 if (RangeIsError)
10209 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
10210 << toString(Result, 10) << Low << High << Arg->getSourceRange();
10211 else
10212 // Defer the warning until we know if the code will be emitted so that
10213 // dead code can ignore this.
10214 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
10215 PDiag(diag::warn_argument_invalid_range)
10216 << toString(Result, 10) << Low << High
10217 << Arg->getSourceRange());
10218 }
10219
10220 return false;
10221}
10222
10223/// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
10224/// TheCall is a constant expression is a multiple of Num..
10225bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10226 unsigned Num) {
10227 llvm::APSInt Result;
10228
10229 // We can't check the value of a dependent argument.
10230 Expr *Arg = TheCall->getArg(ArgNum);
10231 if (Arg->isTypeDependent() || Arg->isValueDependent())
10232 return false;
10233
10234 // Check constant-ness first.
10235 if (BuiltinConstantArg(TheCall, ArgNum, Result))
10236 return true;
10237
10238 if (Result.getSExtValue() % Num != 0)
10239 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
10240 << Num << Arg->getSourceRange();
10241
10242 return false;
10243}
10244
10245/// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
10246/// constant expression representing a power of 2.
10247bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
10248 llvm::APSInt Result;
10249
10250 // We can't check the value of a dependent argument.
10251 Expr *Arg = TheCall->getArg(ArgNum);
10252 if (Arg->isTypeDependent() || Arg->isValueDependent())
10253 return false;
10254
10255 // Check constant-ness first.
10256 if (BuiltinConstantArg(TheCall, ArgNum, Result))
10257 return true;
10258
10259 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
10260 // and only if x is a power of 2.
10261 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
10262 return false;
10263
10264 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
10265 << Arg->getSourceRange();
10266}
10267
10268static bool IsShiftedByte(llvm::APSInt Value) {
10269 if (Value.isNegative())
10270 return false;
10271
10272 // Check if it's a shifted byte, by shifting it down
10273 while (true) {
10274 // If the value fits in the bottom byte, the check passes.
10275 if (Value < 0x100)
10276 return true;
10277
10278 // Otherwise, if the value has _any_ bits in the bottom byte, the check
10279 // fails.
10280 if ((Value & 0xFF) != 0)
10281 return false;
10282
10283 // If the bottom 8 bits are all 0, but something above that is nonzero,
10284 // then shifting the value right by 8 bits won't affect whether it's a
10285 // shifted byte or not. So do that, and go round again.
10286 Value >>= 8;
10287 }
10288}
10289
10290/// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
10291/// a constant expression representing an arbitrary byte value shifted left by
10292/// a multiple of 8 bits.
10293bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
10294 unsigned ArgBits) {
10295 llvm::APSInt Result;
10296
10297 // We can't check the value of a dependent argument.
10298 Expr *Arg = TheCall->getArg(ArgNum);
10299 if (Arg->isTypeDependent() || Arg->isValueDependent())
10300 return false;
10301
10302 // Check constant-ness first.
10303 if (BuiltinConstantArg(TheCall, ArgNum, Result))
10304 return true;
10305
10306 // Truncate to the given size.
10307 Result = Result.getLoBits(ArgBits);
10308 Result.setIsUnsigned(true);
10309
10310 if (IsShiftedByte(Result))
10311 return false;
10312
10313 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
10314 << Arg->getSourceRange();
10315}
10316
10317/// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
10318/// TheCall is a constant expression representing either a shifted byte value,
10319/// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
10320/// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
10321/// Arm MVE intrinsics.
10322bool Sema::BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
10323 unsigned ArgBits) {
10324 llvm::APSInt Result;
10325
10326 // We can't check the value of a dependent argument.
10327 Expr *Arg = TheCall->getArg(ArgNum);
10328 if (Arg->isTypeDependent() || Arg->isValueDependent())
10329 return false;
10330
10331 // Check constant-ness first.
10332 if (BuiltinConstantArg(TheCall, ArgNum, Result))
10333 return true;
10334
10335 // Truncate to the given size.
10336 Result = Result.getLoBits(ArgBits);
10337 Result.setIsUnsigned(true);
10338
10339 // Check to see if it's in either of the required forms.
10340 if (IsShiftedByte(Result) ||
10341 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
10342 return false;
10343
10344 return Diag(TheCall->getBeginLoc(),
10345 diag::err_argument_not_shifted_byte_or_xxff)
10346 << Arg->getSourceRange();
10347}
10348
10349/// BuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
10350bool Sema::BuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
10351 if (BuiltinID == AArch64::BI__builtin_arm_irg) {
10352 if (checkArgCount(*this, TheCall, 2))
10353 return true;
10354 Expr *Arg0 = TheCall->getArg(0);
10355 Expr *Arg1 = TheCall->getArg(1);
10356
10358 if (FirstArg.isInvalid())
10359 return true;
10360 QualType FirstArgType = FirstArg.get()->getType();
10361 if (!FirstArgType->isAnyPointerType())
10362 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
10363 << "first" << FirstArgType << Arg0->getSourceRange();
10364 TheCall->setArg(0, FirstArg.get());
10365
10366 ExprResult SecArg = DefaultLvalueConversion(Arg1);
10367 if (SecArg.isInvalid())
10368 return true;
10369 QualType SecArgType = SecArg.get()->getType();
10370 if (!SecArgType->isIntegerType())
10371 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
10372 << "second" << SecArgType << Arg1->getSourceRange();
10373
10374 // Derive the return type from the pointer argument.
10375 TheCall->setType(FirstArgType);
10376 return false;
10377 }
10378
10379 if (BuiltinID == AArch64::BI__builtin_arm_addg) {
10380 if (checkArgCount(*this, TheCall, 2))
10381 return true;
10382
10383 Expr *Arg0 = TheCall->getArg(0);
10385 if (FirstArg.isInvalid())
10386 return true;
10387 QualType FirstArgType = FirstArg.get()->getType();
10388 if (!FirstArgType->isAnyPointerType())
10389 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
10390 << "first" << FirstArgType << Arg0->getSourceRange();
10391 TheCall->setArg(0, FirstArg.get());
10392
10393 // Derive the return type from the pointer argument.
10394 TheCall->setType(FirstArgType);
10395
10396 // Second arg must be an constant in range [0,15]
10397 return BuiltinConstantArgRange(TheCall, 1, 0, 15);
10398 }
10399
10400 if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
10401 if (checkArgCount(*this, TheCall, 2))
10402 return true;
10403 Expr *Arg0 = TheCall->getArg(0);
10404 Expr *Arg1 = TheCall->getArg(1);
10405
10407 if (FirstArg.isInvalid())
10408 return true;
10409 QualType FirstArgType = FirstArg.get()->getType();
10410 if (!FirstArgType->isAnyPointerType())
10411 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
10412 << "first" << FirstArgType << Arg0->getSourceRange();
10413
10414 QualType SecArgType = Arg1->getType();
10415 if (!SecArgType->isIntegerType())
10416 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
10417 << "second" << SecArgType << Arg1->getSourceRange();
10418 TheCall->setType(Context.IntTy);
10419 return false;
10420 }
10421
10422 if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
10423 BuiltinID == AArch64::BI__builtin_arm_stg) {
10424 if (checkArgCount(*this, TheCall, 1))
10425 return true;
10426 Expr *Arg0 = TheCall->getArg(0);
10428 if (FirstArg.isInvalid())
10429 return true;
10430
10431 QualType FirstArgType = FirstArg.get()->getType();
10432 if (!FirstArgType->isAnyPointerType())
10433 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
10434 << "first" << FirstArgType << Arg0->getSourceRange();
10435 TheCall->setArg(0, FirstArg.get());
10436
10437 // Derive the return type from the pointer argument.
10438 if (BuiltinID == AArch64::BI__builtin_arm_ldg)
10439 TheCall->setType(FirstArgType);
10440 return false;
10441 }
10442
10443 if (BuiltinID == AArch64::BI__builtin_arm_subp) {
10444 Expr *ArgA = TheCall->getArg(0);
10445 Expr *ArgB = TheCall->getArg(1);
10446
10449
10450 if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
10451 return true;
10452
10453 QualType ArgTypeA = ArgExprA.get()->getType();
10454 QualType ArgTypeB = ArgExprB.get()->getType();
10455
10456 auto isNull = [&] (Expr *E) -> bool {
10457 return E->isNullPointerConstant(
10459
10460 // argument should be either a pointer or null
10461 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
10462 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
10463 << "first" << ArgTypeA << ArgA->getSourceRange();
10464
10465 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
10466 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
10467 << "second" << ArgTypeB << ArgB->getSourceRange();
10468
10469 // Ensure Pointee types are compatible
10470 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
10471 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
10472 QualType pointeeA = ArgTypeA->getPointeeType();
10473 QualType pointeeB = ArgTypeB->getPointeeType();
10477 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
10478 << ArgTypeA << ArgTypeB << ArgA->getSourceRange()
10479 << ArgB->getSourceRange();
10480 }
10481 }
10482
10483 // at least one argument should be pointer type
10484 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
10485 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
10486 << ArgTypeA << ArgTypeB << ArgA->getSourceRange();
10487
10488 if (isNull(ArgA)) // adopt type of the other pointer
10489 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
10490
10491 if (isNull(ArgB))
10492 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
10493
10494 TheCall->setArg(0, ArgExprA.get());
10495 TheCall->setArg(1, ArgExprB.get());
10496 TheCall->setType(Context.LongLongTy);
10497 return false;
10498 }
10499 assert(false && "Unhandled ARM MTE intrinsic");
10500 return true;
10501}
10502
10503/// BuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
10504/// TheCall is an ARM/AArch64 special register string literal.
10505bool Sema::BuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10506 int ArgNum, unsigned ExpectedFieldNum,
10507 bool AllowName) {
10508 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
10509 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
10510 BuiltinID == ARM::BI__builtin_arm_rsr ||
10511 BuiltinID == ARM::BI__builtin_arm_rsrp ||
10512 BuiltinID == ARM::BI__builtin_arm_wsr ||
10513 BuiltinID == ARM::BI__builtin_arm_wsrp;
10514 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
10515 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
10516 BuiltinID == AArch64::BI__builtin_arm_rsr128 ||
10517 BuiltinID == AArch64::BI__builtin_arm_wsr128 ||
10518 BuiltinID == AArch64::BI__builtin_arm_rsr ||
10519 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
10520 BuiltinID == AArch64::BI__builtin_arm_wsr ||
10521 BuiltinID == AArch64::BI__builtin_arm_wsrp;
10522 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
10523
10524 // We can't check the value of a dependent argument.
10525 Expr *Arg = TheCall->getArg(ArgNum);
10526 if (Arg->isTypeDependent() || Arg->isValueDependent())
10527 return false;
10528
10529 // Check if the argument is a string literal.
10530 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
10531 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
10532 << Arg->getSourceRange();
10533
10534 // Check the type of special register given.
10535 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
10537 Reg.split(Fields, ":");
10538
10539 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
10540 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
10541 << Arg->getSourceRange();
10542
10543 // If the string is the name of a register then we cannot check that it is
10544 // valid here but if the string is of one the forms described in ACLE then we
10545 // can check that the supplied fields are integers and within the valid
10546 // ranges.
10547 if (Fields.size() > 1) {
10548 bool FiveFields = Fields.size() == 5;
10549
10550 bool ValidString = true;
10551 if (IsARMBuiltin) {
10552 ValidString &= Fields[0].starts_with_insensitive("cp") ||
10553 Fields[0].starts_with_insensitive("p");
10554 if (ValidString)
10555 Fields[0] = Fields[0].drop_front(
10556 Fields[0].starts_with_insensitive("cp") ? 2 : 1);
10557
10558 ValidString &= Fields[2].starts_with_insensitive("c");
10559 if (ValidString)
10560 Fields[2] = Fields[2].drop_front(1);
10561
10562 if (FiveFields) {
10563 ValidString &= Fields[3].starts_with_insensitive("c");
10564 if (ValidString)
10565 Fields[3] = Fields[3].drop_front(1);
10566 }
10567 }
10568
10569 SmallVector<int, 5> Ranges;
10570 if (FiveFields)
10571 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
10572 else
10573 Ranges.append({15, 7, 15});
10574
10575 for (unsigned i=0; i<Fields.size(); ++i) {
10576 int IntField;
10577 ValidString &= !Fields[i].getAsInteger(10, IntField);
10578 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
10579 }
10580
10581 if (!ValidString)
10582 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
10583 << Arg->getSourceRange();
10584 } else if (IsAArch64Builtin && Fields.size() == 1) {
10585 // This code validates writes to PSTATE registers.
10586
10587 // Not a write.
10588 if (TheCall->getNumArgs() != 2)
10589 return false;
10590
10591 // The 128-bit system register accesses do not touch PSTATE.
10592 if (BuiltinID == AArch64::BI__builtin_arm_rsr128 ||
10593 BuiltinID == AArch64::BI__builtin_arm_wsr128)
10594 return false;
10595
10596 // These are the named PSTATE accesses using "MSR (immediate)" instructions,
10597 // along with the upper limit on the immediates allowed.
10598 auto MaxLimit = llvm::StringSwitch<std::optional<unsigned>>(Reg)
10599 .CaseLower("spsel", 15)
10600 .CaseLower("daifclr", 15)
10601 .CaseLower("daifset", 15)
10602 .CaseLower("pan", 15)
10603 .CaseLower("uao", 15)
10604 .CaseLower("dit", 15)
10605 .CaseLower("ssbs", 15)
10606 .CaseLower("tco", 15)
10607 .CaseLower("allint", 1)
10608 .CaseLower("pm", 1)
10609 .Default(std::nullopt);
10610
10611 // If this is not a named PSTATE, just continue without validating, as this
10612 // will be lowered to an "MSR (register)" instruction directly
10613 if (!MaxLimit)
10614 return false;
10615
10616 // Here we only allow constants in the range for that pstate, as required by
10617 // the ACLE.
10618 //
10619 // While clang also accepts the names of system registers in its ACLE
10620 // intrinsics, we prevent this with the PSTATE names used in MSR (immediate)
10621 // as the value written via a register is different to the value used as an
10622 // immediate to have the same effect. e.g., for the instruction `msr tco,
10623 // x0`, it is bit 25 of register x0 that is written into PSTATE.TCO, but
10624 // with `msr tco, #imm`, it is bit 0 of xN that is written into PSTATE.TCO.
10625 //
10626 // If a programmer wants to codegen the MSR (register) form of `msr tco,
10627 // xN`, they can still do so by specifying the register using five
10628 // colon-separated numbers in a string.
10629 return BuiltinConstantArgRange(TheCall, 1, 0, *MaxLimit);
10630 }
10631
10632 return false;
10633}
10634
10635/// BuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
10636/// Emit an error and return true on failure; return false on success.
10637/// TypeStr is a string containing the type descriptor of the value returned by
10638/// the builtin and the descriptors of the expected type of the arguments.
10639bool Sema::BuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
10640 const char *TypeStr) {
10641
10642 assert((TypeStr[0] != '\0') &&
10643 "Invalid types in PPC MMA builtin declaration");
10644
10645 unsigned Mask = 0;
10646 unsigned ArgNum = 0;
10647
10648 // The first type in TypeStr is the type of the value returned by the
10649 // builtin. So we first read that type and change the type of TheCall.
10650 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
10651 TheCall->setType(type);
10652
10653 while (*TypeStr != '\0') {
10654 Mask = 0;
10656 if (ArgNum >= TheCall->getNumArgs()) {
10657 ArgNum++;
10658 break;
10659 }
10660
10661 Expr *Arg = TheCall->getArg(ArgNum);
10662 QualType PassedType = Arg->getType();
10663 QualType StrippedRVType = PassedType.getCanonicalType();
10664
10665 // Strip Restrict/Volatile qualifiers.
10666 if (StrippedRVType.isRestrictQualified() ||
10667 StrippedRVType.isVolatileQualified())
10668 StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
10669
10670 // The only case where the argument type and expected type are allowed to
10671 // mismatch is if the argument type is a non-void pointer (or array) and
10672 // expected type is a void pointer.
10673 if (StrippedRVType != ExpectedType)
10674 if (!(ExpectedType->isVoidPointerType() &&
10675 (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
10676 return Diag(Arg->getBeginLoc(),
10677 diag::err_typecheck_convert_incompatible)
10678 << PassedType << ExpectedType << 1 << 0 << 0;
10679
10680 // If the value of the Mask is not 0, we have a constraint in the size of
10681 // the integer argument so here we ensure the argument is a constant that
10682 // is in the valid range.
10683 if (Mask != 0 && BuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
10684 return true;
10685
10686 ArgNum++;
10687 }
10688
10689 // In case we exited early from the previous loop, there are other types to
10690 // read from TypeStr. So we need to read them all to ensure we have the right
10691 // number of arguments in TheCall and if it is not the case, to display a
10692 // better error message.
10693 while (*TypeStr != '\0') {
10694 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
10695 ArgNum++;
10696 }
10697 if (checkArgCount(*this, TheCall, ArgNum))
10698 return true;
10699
10700 return false;
10701}
10702
10703/// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
10704/// This checks that the target supports __builtin_longjmp and
10705/// that val is a constant 1.
10706bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
10708 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
10709 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
10710
10711 Expr *Arg = TheCall->getArg(1);
10712 llvm::APSInt Result;
10713
10714 // TODO: This is less than ideal. Overload this to take a value.
10715 if (BuiltinConstantArg(TheCall, 1, Result))
10716 return true;
10717
10718 if (Result != 1)
10719 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
10720 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
10721
10722 return false;
10723}
10724
10725/// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
10726/// This checks that the target supports __builtin_setjmp.
10727bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
10729 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
10730 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
10731 return false;
10732}
10733
10734namespace {
10735
10736class UncoveredArgHandler {
10737 enum { Unknown = -1, AllCovered = -2 };
10738
10739 signed FirstUncoveredArg = Unknown;
10740 SmallVector<const Expr *, 4> DiagnosticExprs;
10741
10742public:
10743 UncoveredArgHandler() = default;
10744
10745 bool hasUncoveredArg() const {
10746 return (FirstUncoveredArg >= 0);
10747 }
10748
10749 unsigned getUncoveredArg() const {
10750 assert(hasUncoveredArg() && "no uncovered argument");
10751 return FirstUncoveredArg;
10752 }
10753
10754 void setAllCovered() {
10755 // A string has been found with all arguments covered, so clear out
10756 // the diagnostics.
10757 DiagnosticExprs.clear();
10758 FirstUncoveredArg = AllCovered;
10759 }
10760
10761 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
10762 assert(NewFirstUncoveredArg >= 0 && "Outside range");
10763
10764 // Don't update if a previous string covers all arguments.
10765 if (FirstUncoveredArg == AllCovered)
10766 return;
10767
10768 // UncoveredArgHandler tracks the highest uncovered argument index
10769 // and with it all the strings that match this index.
10770 if (NewFirstUncoveredArg == FirstUncoveredArg)
10771 DiagnosticExprs.push_back(StrExpr);
10772 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
10773 DiagnosticExprs.clear();
10774 DiagnosticExprs.push_back(StrExpr);
10775 FirstUncoveredArg = NewFirstUncoveredArg;
10776 }
10777 }
10778
10779 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
10780};
10781
10782enum StringLiteralCheckType {
10783 SLCT_NotALiteral,
10784 SLCT_UncheckedLiteral,
10785 SLCT_CheckedLiteral
10786};
10787
10788} // namespace
10789
10790static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
10791 BinaryOperatorKind BinOpKind,
10792 bool AddendIsRight) {
10793 unsigned BitWidth = Offset.getBitWidth();
10794 unsigned AddendBitWidth = Addend.getBitWidth();
10795 // There might be negative interim results.
10796 if (Addend.isUnsigned()) {
10797 Addend = Addend.zext(++AddendBitWidth);
10798 Addend.setIsSigned(true);
10799 }
10800 // Adjust the bit width of the APSInts.
10801 if (AddendBitWidth > BitWidth) {
10802 Offset = Offset.sext(AddendBitWidth);
10803 BitWidth = AddendBitWidth;
10804 } else if (BitWidth > AddendBitWidth) {
10805 Addend = Addend.sext(BitWidth);
10806 }
10807
10808 bool Ov = false;
10809 llvm::APSInt ResOffset = Offset;
10810 if (BinOpKind == BO_Add)
10811 ResOffset = Offset.sadd_ov(Addend, Ov);
10812 else {
10813 assert(AddendIsRight && BinOpKind == BO_Sub &&
10814 "operator must be add or sub with addend on the right");
10815 ResOffset = Offset.ssub_ov(Addend, Ov);
10816 }
10817
10818 // We add an offset to a pointer here so we should support an offset as big as
10819 // possible.
10820 if (Ov) {
10821 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
10822 "index (intermediate) result too big");
10823 Offset = Offset.sext(2 * BitWidth);
10824 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
10825 return;
10826 }
10827
10828 Offset = ResOffset;
10829}
10830
10831namespace {
10832
10833// This is a wrapper class around StringLiteral to support offsetted string
10834// literals as format strings. It takes the offset into account when returning
10835// the string and its length or the source locations to display notes correctly.
10836class FormatStringLiteral {
10837 const StringLiteral *FExpr;
10838 int64_t Offset;
10839
10840 public:
10841 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
10842 : FExpr(fexpr), Offset(Offset) {}
10843
10844 StringRef getString() const {
10845 return FExpr->getString().drop_front(Offset);
10846 }
10847
10848 unsigned getByteLength() const {
10849 return FExpr->getByteLength() - getCharByteWidth() * Offset;
10850 }
10851
10852 unsigned getLength() const { return FExpr->getLength() - Offset; }
10853 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
10854
10855 StringLiteralKind getKind() const { return FExpr->getKind(); }
10856
10857 QualType getType() const { return FExpr->getType(); }
10858
10859 bool isAscii() const { return FExpr->isOrdinary(); }
10860 bool isWide() const { return FExpr->isWide(); }
10861 bool isUTF8() const { return FExpr->isUTF8(); }
10862 bool isUTF16() const { return FExpr->isUTF16(); }
10863 bool isUTF32() const { return FExpr->isUTF32(); }
10864 bool isPascal() const { return FExpr->isPascal(); }
10865
10866 SourceLocation getLocationOfByte(
10867 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
10868 const TargetInfo &Target, unsigned *StartToken = nullptr,
10869 unsigned *StartTokenByteOffset = nullptr) const {
10870 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
10871 StartToken, StartTokenByteOffset);
10872 }
10873
10874 SourceLocation getBeginLoc() const LLVM_READONLY {
10875 return FExpr->getBeginLoc().getLocWithOffset(Offset);
10876 }
10877
10878 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
10879};
10880
10881} // namespace
10882
10883static void CheckFormatString(
10884 Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr,
10886 unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type,
10887 bool inFunctionCall, Sema::VariadicCallType CallType,
10888 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
10889 bool IgnoreStringsWithoutSpecifiers);
10890
10891static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
10892 const Expr *E);
10893
10894// Determine if an expression is a string literal or constant string.
10895// If this function returns false on the arguments to a function expecting a
10896// format string, we will usually need to emit a warning.
10897// True string literals are then checked by CheckFormatString.
10898static StringLiteralCheckType
10900 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
10901 unsigned firstDataArg, Sema::FormatStringType Type,
10902 Sema::VariadicCallType CallType, bool InFunctionCall,
10903 llvm::SmallBitVector &CheckedVarArgs,
10904 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
10905 bool IgnoreStringsWithoutSpecifiers = false) {
10907 return SLCT_NotALiteral;
10908tryAgain:
10909 assert(Offset.isSigned() && "invalid offset");
10910
10911 if (E->isTypeDependent() || E->isValueDependent())
10912 return SLCT_NotALiteral;
10913
10914 E = E->IgnoreParenCasts();
10915
10917 // Technically -Wformat-nonliteral does not warn about this case.
10918 // The behavior of printf and friends in this case is implementation
10919 // dependent. Ideally if the format string cannot be null then
10920 // it should have a 'nonnull' attribute in the function prototype.
10921 return SLCT_UncheckedLiteral;
10922
10923 switch (E->getStmtClass()) {
10924 case Stmt::InitListExprClass:
10925 // Handle expressions like {"foobar"}.
10926 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
10927 return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg,
10928 Type, CallType, /*InFunctionCall*/ false,
10929 CheckedVarArgs, UncoveredArg, Offset,
10930 IgnoreStringsWithoutSpecifiers);
10931 }
10932 return SLCT_NotALiteral;
10933 case Stmt::BinaryConditionalOperatorClass:
10934 case Stmt::ConditionalOperatorClass: {
10935 // The expression is a literal if both sub-expressions were, and it was
10936 // completely checked only if both sub-expressions were checked.
10938 cast<AbstractConditionalOperator>(E);
10939
10940 // Determine whether it is necessary to check both sub-expressions, for
10941 // example, because the condition expression is a constant that can be
10942 // evaluated at compile time.
10943 bool CheckLeft = true, CheckRight = true;
10944
10945 bool Cond;
10946 if (C->getCond()->EvaluateAsBooleanCondition(
10947 Cond, S.getASTContext(), S.isConstantEvaluatedContext())) {
10948 if (Cond)
10949 CheckRight = false;
10950 else
10951 CheckLeft = false;
10952 }
10953
10954 // We need to maintain the offsets for the right and the left hand side
10955 // separately to check if every possible indexed expression is a valid
10956 // string literal. They might have different offsets for different string
10957 // literals in the end.
10958 StringLiteralCheckType Left;
10959 if (!CheckLeft)
10960 Left = SLCT_UncheckedLiteral;
10961 else {
10962 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, APK, format_idx,
10963 firstDataArg, Type, CallType, InFunctionCall,
10964 CheckedVarArgs, UncoveredArg, Offset,
10965 IgnoreStringsWithoutSpecifiers);
10966 if (Left == SLCT_NotALiteral || !CheckRight) {
10967 return Left;
10968 }
10969 }
10970
10971 StringLiteralCheckType Right = checkFormatStringExpr(
10972 S, C->getFalseExpr(), Args, APK, format_idx, firstDataArg, Type,
10973 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
10974 IgnoreStringsWithoutSpecifiers);
10975
10976 return (CheckLeft && Left < Right) ? Left : Right;
10977 }
10978
10979 case Stmt::ImplicitCastExprClass:
10980 E = cast<ImplicitCastExpr>(E)->getSubExpr();
10981 goto tryAgain;
10982
10983 case Stmt::OpaqueValueExprClass:
10984 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
10985 E = src;
10986 goto tryAgain;
10987 }
10988 return SLCT_NotALiteral;
10989
10990 case Stmt::PredefinedExprClass:
10991 // While __func__, etc., are technically not string literals, they
10992 // cannot contain format specifiers and thus are not a security
10993 // liability.
10994 return SLCT_UncheckedLiteral;
10995
10996 case Stmt::DeclRefExprClass: {
10997 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
10998
10999 // As an exception, do not flag errors for variables binding to
11000 // const string literals.
11001 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
11002 bool isConstant = false;
11003 QualType T = DR->getType();
11004
11005 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
11006 isConstant = AT->getElementType().isConstant(S.Context);
11007 } else if (const PointerType *PT = T->getAs<PointerType>()) {
11008 isConstant = T.isConstant(S.Context) &&
11010 } else if (T->isObjCObjectPointerType()) {
11011 // In ObjC, there is usually no "const ObjectPointer" type,
11012 // so don't check if the pointee type is constant.
11013 isConstant = T.isConstant(S.Context);
11014 }
11015
11016 if (isConstant) {
11017 if (const Expr *Init = VD->getAnyInitializer()) {
11018 // Look through initializers like const char c[] = { "foo" }
11019 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
11020 if (InitList->isStringLiteralInit())
11021 Init = InitList->getInit(0)->IgnoreParenImpCasts();
11022 }
11023 return checkFormatStringExpr(
11024 S, Init, Args, APK, format_idx, firstDataArg, Type, CallType,
11025 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg, Offset);
11026 }
11027 }
11028
11029 // When the format argument is an argument of this function, and this
11030 // function also has the format attribute, there are several interactions
11031 // for which there shouldn't be a warning. For instance, when calling
11032 // v*printf from a function that has the printf format attribute, we
11033 // should not emit a warning about using `fmt`, even though it's not
11034 // constant, because the arguments have already been checked for the
11035 // caller of `logmessage`:
11036 //
11037 // __attribute__((format(printf, 1, 2)))
11038 // void logmessage(char const *fmt, ...) {
11039 // va_list ap;
11040 // va_start(ap, fmt);
11041 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
11042 // ...
11043 // }
11044 //
11045 // Another interaction that we need to support is calling a variadic
11046 // format function from a format function that has fixed arguments. For
11047 // instance:
11048 //
11049 // __attribute__((format(printf, 1, 2)))
11050 // void logstring(char const *fmt, char const *str) {
11051 // printf(fmt, str); /* do not emit a warning about "fmt" */
11052 // }
11053 //
11054 // Same (and perhaps more relatably) for the variadic template case:
11055 //
11056 // template<typename... Args>
11057 // __attribute__((format(printf, 1, 2)))
11058 // void log(const char *fmt, Args&&... args) {
11059 // printf(fmt, forward<Args>(args)...);
11060 // /* do not emit a warning about "fmt" */
11061 // }
11062 //
11063 // Due to implementation difficulty, we only check the format, not the
11064 // format arguments, in all cases.
11065 //
11066 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
11067 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
11068 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
11069 bool IsCXXMember = false;
11070 if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
11071 IsCXXMember = MD->isInstance();
11072
11073 bool IsVariadic = false;
11074 if (const FunctionType *FnTy = D->getFunctionType())
11075 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
11076 else if (const auto *BD = dyn_cast<BlockDecl>(D))
11077 IsVariadic = BD->isVariadic();
11078 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
11079 IsVariadic = OMD->isVariadic();
11080
11081 Sema::FormatStringInfo CallerFSI;
11082 if (Sema::getFormatStringInfo(PVFormat, IsCXXMember, IsVariadic,
11083 &CallerFSI)) {
11084 // We also check if the formats are compatible.
11085 // We can't pass a 'scanf' string to a 'printf' function.
11086 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx &&
11087 Type == S.GetFormatStringType(PVFormat)) {
11088 // Lastly, check that argument passing kinds transition in a
11089 // way that makes sense:
11090 // from a caller with FAPK_VAList, allow FAPK_VAList
11091 // from a caller with FAPK_Fixed, allow FAPK_Fixed
11092 // from a caller with FAPK_Fixed, allow FAPK_Variadic
11093 // from a caller with FAPK_Variadic, allow FAPK_VAList
11094 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
11099 return SLCT_UncheckedLiteral;
11100 }
11101 }
11102 }
11103 }
11104 }
11105 }
11106 }
11107
11108 return SLCT_NotALiteral;
11109 }
11110
11111 case Stmt::CallExprClass:
11112 case Stmt::CXXMemberCallExprClass: {
11113 const CallExpr *CE = cast<CallExpr>(E);
11114 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
11115 bool IsFirst = true;
11116 StringLiteralCheckType CommonResult;
11117 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
11118 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
11119 StringLiteralCheckType Result = checkFormatStringExpr(
11120 S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
11121 InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
11122 IgnoreStringsWithoutSpecifiers);
11123 if (IsFirst) {
11124 CommonResult = Result;
11125 IsFirst = false;
11126 }
11127 }
11128 if (!IsFirst)
11129 return CommonResult;
11130
11131 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
11132 unsigned BuiltinID = FD->getBuiltinID();
11133 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
11134 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
11135 const Expr *Arg = CE->getArg(0);
11136 return checkFormatStringExpr(
11137 S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
11138 InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
11139 IgnoreStringsWithoutSpecifiers);
11140 }
11141 }
11142 }
11143 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
11144 return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg,
11145 Type, CallType, /*InFunctionCall*/ false,
11146 CheckedVarArgs, UncoveredArg, Offset,
11147 IgnoreStringsWithoutSpecifiers);
11148 return SLCT_NotALiteral;
11149 }
11150 case Stmt::ObjCMessageExprClass: {
11151 const auto *ME = cast<ObjCMessageExpr>(E);
11152 if (const auto *MD = ME->getMethodDecl()) {
11153 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
11154 // As a special case heuristic, if we're using the method -[NSBundle
11155 // localizedStringForKey:value:table:], ignore any key strings that lack
11156 // format specifiers. The idea is that if the key doesn't have any
11157 // format specifiers then its probably just a key to map to the
11158 // localized strings. If it does have format specifiers though, then its
11159 // likely that the text of the key is the format string in the
11160 // programmer's language, and should be checked.
11161 const ObjCInterfaceDecl *IFace;
11162 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
11163 IFace->getIdentifier()->isStr("NSBundle") &&
11164 MD->getSelector().isKeywordSelector(
11165 {"localizedStringForKey", "value", "table"})) {
11166 IgnoreStringsWithoutSpecifiers = true;
11167 }
11168
11169 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
11170 return checkFormatStringExpr(
11171 S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
11172 InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
11173 IgnoreStringsWithoutSpecifiers);
11174 }
11175 }
11176
11177 return SLCT_NotALiteral;
11178 }
11179 case Stmt::ObjCStringLiteralClass:
11180 case Stmt::StringLiteralClass: {
11181 const StringLiteral *StrE = nullptr;
11182
11183 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
11184 StrE = ObjCFExpr->getString();
11185 else
11186 StrE = cast<StringLiteral>(E);
11187
11188 if (StrE) {
11189 if (Offset.isNegative() || Offset > StrE->getLength()) {
11190 // TODO: It would be better to have an explicit warning for out of
11191 // bounds literals.
11192 return SLCT_NotALiteral;
11193 }
11194 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
11195 CheckFormatString(S, &FStr, E, Args, APK, format_idx, firstDataArg, Type,
11196 InFunctionCall, CallType, CheckedVarArgs, UncoveredArg,
11197 IgnoreStringsWithoutSpecifiers);
11198 return SLCT_CheckedLiteral;
11199 }
11200
11201 return SLCT_NotALiteral;
11202 }
11203 case Stmt::BinaryOperatorClass: {
11204 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
11205
11206 // A string literal + an int offset is still a string literal.
11207 if (BinOp->isAdditiveOp()) {
11208 Expr::EvalResult LResult, RResult;
11209
11210 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
11211 LResult, S.Context, Expr::SE_NoSideEffects,
11213 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
11214 RResult, S.Context, Expr::SE_NoSideEffects,
11216
11217 if (LIsInt != RIsInt) {
11218 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
11219
11220 if (LIsInt) {
11221 if (BinOpKind == BO_Add) {
11222 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
11223 E = BinOp->getRHS();
11224 goto tryAgain;
11225 }
11226 } else {
11227 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
11228 E = BinOp->getLHS();
11229 goto tryAgain;
11230 }
11231 }
11232 }
11233
11234 return SLCT_NotALiteral;
11235 }
11236 case Stmt::UnaryOperatorClass: {
11237 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
11238 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
11239 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
11240 Expr::EvalResult IndexResult;
11241 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
11244 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
11245 /*RHS is int*/ true);
11246 E = ASE->getBase();
11247 goto tryAgain;
11248 }
11249 }
11250
11251 return SLCT_NotALiteral;
11252 }
11253
11254 default:
11255 return SLCT_NotALiteral;
11256 }
11257}
11258
11259// If this expression can be evaluated at compile-time,
11260// check if the result is a StringLiteral and return it
11261// otherwise return nullptr
11263 const Expr *E) {
11265 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
11266 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
11267 if (isa_and_nonnull<StringLiteral>(LVE))
11268 return LVE;
11269 }
11270 return nullptr;
11271}
11272
11274 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
11275 .Case("scanf", FST_Scanf)
11276 .Cases("printf", "printf0", FST_Printf)
11277 .Cases("NSString", "CFString", FST_NSString)
11278 .Case("strftime", FST_Strftime)
11279 .Case("strfmon", FST_Strfmon)
11280 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
11281 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
11282 .Case("os_trace", FST_OSLog)
11283 .Case("os_log", FST_OSLog)
11284 .Default(FST_Unknown);
11285}
11286
11287/// CheckFormatArguments - Check calls to printf and scanf (and similar
11288/// functions) for correct use of format strings.
11289/// Returns true if a format string has been fully checked.
11290bool Sema::CheckFormatArguments(const FormatAttr *Format,
11291 ArrayRef<const Expr *> Args, bool IsCXXMember,
11292 VariadicCallType CallType, SourceLocation Loc,
11294 llvm::SmallBitVector &CheckedVarArgs) {
11295 FormatStringInfo FSI;
11296 if (getFormatStringInfo(Format, IsCXXMember, CallType != VariadicDoesNotApply,
11297 &FSI))
11298 return CheckFormatArguments(Args, FSI.ArgPassingKind, FSI.FormatIdx,
11299 FSI.FirstDataArg, GetFormatStringType(Format),
11300 CallType, Loc, Range, CheckedVarArgs);
11301 return false;
11302}
11303
11304bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
11306 unsigned format_idx, unsigned firstDataArg,
11307 FormatStringType Type,
11308 VariadicCallType CallType, SourceLocation Loc,
11310 llvm::SmallBitVector &CheckedVarArgs) {
11311 // CHECK: printf/scanf-like function is called with no format string.
11312 if (format_idx >= Args.size()) {
11313 Diag(Loc, diag::warn_missing_format_string) << Range;
11314 return false;
11315 }
11316
11317 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
11318
11319 // CHECK: format string is not a string literal.
11320 //
11321 // Dynamically generated format strings are difficult to
11322 // automatically vet at compile time. Requiring that format strings
11323 // are string literals: (1) permits the checking of format strings by
11324 // the compiler and thereby (2) can practically remove the source of
11325 // many format string exploits.
11326
11327 // Format string can be either ObjC string (e.g. @"%d") or
11328 // C string (e.g. "%d")
11329 // ObjC string uses the same format specifiers as C string, so we can use
11330 // the same format string checking logic for both ObjC and C strings.
11331 UncoveredArgHandler UncoveredArg;
11332 StringLiteralCheckType CT = checkFormatStringExpr(
11333 *this, OrigFormatExpr, Args, APK, format_idx, firstDataArg, Type,
11334 CallType,
11335 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
11336 /*no string offset*/ llvm::APSInt(64, false) = 0);
11337
11338 // Generate a diagnostic where an uncovered argument is detected.
11339 if (UncoveredArg.hasUncoveredArg()) {
11340 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
11341 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
11342 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
11343 }
11344
11345 if (CT != SLCT_NotALiteral)
11346 // Literal format string found, check done!
11347 return CT == SLCT_CheckedLiteral;
11348
11349 // Strftime is particular as it always uses a single 'time' argument,
11350 // so it is safe to pass a non-literal string.
11351 if (Type == FST_Strftime)
11352 return false;
11353
11354 // Do not emit diag when the string param is a macro expansion and the
11355 // format is either NSString or CFString. This is a hack to prevent
11356 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
11357 // which are usually used in place of NS and CF string literals.
11358 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
11359 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
11360 return false;
11361
11362 // If there are no arguments specified, warn with -Wformat-security, otherwise
11363 // warn only with -Wformat-nonliteral.
11364 if (Args.size() == firstDataArg) {
11365 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
11366 << OrigFormatExpr->getSourceRange();
11367 switch (Type) {
11368 default:
11369 break;
11370 case FST_Kprintf:
11371 case FST_FreeBSDKPrintf:
11372 case FST_Printf:
11373 Diag(FormatLoc, diag::note_format_security_fixit)
11374 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
11375 break;
11376 case FST_NSString:
11377 Diag(FormatLoc, diag::note_format_security_fixit)
11378 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
11379 break;
11380 }
11381 } else {
11382 Diag(FormatLoc, diag::warn_format_nonliteral)
11383 << OrigFormatExpr->getSourceRange();
11384 }
11385 return false;
11386}
11387
11388namespace {
11389
11390class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
11391protected:
11392 Sema &S;
11393 const FormatStringLiteral *FExpr;
11394 const Expr *OrigFormatExpr;
11395 const Sema::FormatStringType FSType;
11396 const unsigned FirstDataArg;
11397 const unsigned NumDataArgs;
11398 const char *Beg; // Start of format string.
11399 const Sema::FormatArgumentPassingKind ArgPassingKind;
11401 unsigned FormatIdx;
11402 llvm::SmallBitVector CoveredArgs;
11403 bool usesPositionalArgs = false;
11404 bool atFirstArg = true;
11405 bool inFunctionCall;
11406 Sema::VariadicCallType CallType;
11407 llvm::SmallBitVector &CheckedVarArgs;
11408 UncoveredArgHandler &UncoveredArg;
11409
11410public:
11411 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
11412 const Expr *origFormatExpr,
11413 const Sema::FormatStringType type, unsigned firstDataArg,
11414 unsigned numDataArgs, const char *beg,
11416 ArrayRef<const Expr *> Args, unsigned formatIdx,
11417 bool inFunctionCall, Sema::VariadicCallType callType,
11418 llvm::SmallBitVector &CheckedVarArgs,
11419 UncoveredArgHandler &UncoveredArg)
11420 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
11421 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
11422 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
11423 inFunctionCall(inFunctionCall), CallType(callType),
11424 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
11425 CoveredArgs.resize(numDataArgs);
11426 CoveredArgs.reset();
11427 }
11428
11429 void DoneProcessing();
11430
11431 void HandleIncompleteSpecifier(const char *startSpecifier,
11432 unsigned specifierLen) override;
11433
11434 void HandleInvalidLengthModifier(
11437 const char *startSpecifier, unsigned specifierLen,
11438 unsigned DiagID);
11439
11440 void HandleNonStandardLengthModifier(
11442 const char *startSpecifier, unsigned specifierLen);
11443
11444 void HandleNonStandardConversionSpecifier(
11446 const char *startSpecifier, unsigned specifierLen);
11447
11448 void HandlePosition(const char *startPos, unsigned posLen) override;
11449
11450 void HandleInvalidPosition(const char *startSpecifier,
11451 unsigned specifierLen,
11453
11454 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
11455
11456 void HandleNullChar(const char *nullCharacter) override;
11457
11458 template <typename Range>
11459 static void
11460 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
11461 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
11462 bool IsStringLocation, Range StringRange,
11463 ArrayRef<FixItHint> Fixit = std::nullopt);
11464
11465protected:
11466 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
11467 const char *startSpec,
11468 unsigned specifierLen,
11469 const char *csStart, unsigned csLen);
11470
11471 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
11472 const char *startSpec,
11473 unsigned specifierLen);
11474
11475 SourceRange getFormatStringRange();
11476 CharSourceRange getSpecifierRange(const char *startSpecifier,
11477 unsigned specifierLen);
11478 SourceLocation getLocationOfByte(const char *x);
11479
11480 const Expr *getDataArg(unsigned i) const;
11481
11482 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
11484 const char *startSpecifier, unsigned specifierLen,
11485 unsigned argIndex);
11486
11487 template <typename Range>
11488 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
11489 bool IsStringLocation, Range StringRange,
11490 ArrayRef<FixItHint> Fixit = std::nullopt);
11491};
11492
11493} // namespace
11494
11495SourceRange CheckFormatHandler::getFormatStringRange() {
11496 return OrigFormatExpr->getSourceRange();
11497}
11498
11499CharSourceRange CheckFormatHandler::
11500getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
11501 SourceLocation Start = getLocationOfByte(startSpecifier);
11502 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
11503
11504 // Advance the end SourceLocation by one due to half-open ranges.
11505 End = End.getLocWithOffset(1);
11506
11507 return CharSourceRange::getCharRange(Start, End);
11508}
11509
11510SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
11511 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
11513}
11514
11515void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
11516 unsigned specifierLen){
11517 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
11518 getLocationOfByte(startSpecifier),
11519 /*IsStringLocation*/true,
11520 getSpecifierRange(startSpecifier, specifierLen));
11521}
11522
11523void CheckFormatHandler::HandleInvalidLengthModifier(
11526 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
11527 using namespace analyze_format_string;
11528
11529 const LengthModifier &LM = FS.getLengthModifier();
11530 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
11531
11532 // See if we know how to fix this length modifier.
11533 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
11534 if (FixedLM) {
11535 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
11536 getLocationOfByte(LM.getStart()),
11537 /*IsStringLocation*/true,
11538 getSpecifierRange(startSpecifier, specifierLen));
11539
11540 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
11541 << FixedLM->toString()
11542 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
11543
11544 } else {
11545 FixItHint Hint;
11546 if (DiagID == diag::warn_format_nonsensical_length)
11547 Hint = FixItHint::CreateRemoval(LMRange);
11548
11549 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
11550 getLocationOfByte(LM.getStart()),
11551 /*IsStringLocation*/true,
11552 getSpecifierRange(startSpecifier, specifierLen),
11553 Hint);
11554 }
11555}
11556
11557void CheckFormatHandler::HandleNonStandardLengthModifier(
11559 const char *startSpecifier, unsigned specifierLen) {
11560 using namespace analyze_format_string;
11561
11562 const LengthModifier &LM = FS.getLengthModifier();
11563 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
11564
11565 // See if we know how to fix this length modifier.
11566 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
11567 if (FixedLM) {
11568 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
11569 << LM.toString() << 0,
11570 getLocationOfByte(LM.getStart()),
11571 /*IsStringLocation*/true,
11572 getSpecifierRange(startSpecifier, specifierLen));
11573
11574 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
11575 << FixedLM->toString()
11576 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
11577
11578 } else {
11579 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
11580 << LM.toString() << 0,
11581 getLocationOfByte(LM.getStart()),
11582 /*IsStringLocation*/true,
11583 getSpecifierRange(startSpecifier, specifierLen));
11584 }
11585}
11586
11587void CheckFormatHandler::HandleNonStandardConversionSpecifier(
11589 const char *startSpecifier, unsigned specifierLen) {
11590 using namespace analyze_format_string;
11591
11592 // See if we know how to fix this conversion specifier.
11593 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
11594 if (FixedCS) {
11595 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
11596 << CS.toString() << /*conversion specifier*/1,
11597 getLocationOfByte(CS.getStart()),
11598 /*IsStringLocation*/true,
11599 getSpecifierRange(startSpecifier, specifierLen));
11600
11601 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
11602 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
11603 << FixedCS->toString()
11604 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
11605 } else {
11606 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
11607 << CS.toString() << /*conversion specifier*/1,
11608 getLocationOfByte(CS.getStart()),
11609 /*IsStringLocation*/true,
11610 getSpecifierRange(startSpecifier, specifierLen));
11611 }
11612}
11613
11614void CheckFormatHandler::HandlePosition(const char *startPos,
11615 unsigned posLen) {
11616 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
11617 getLocationOfByte(startPos),
11618 /*IsStringLocation*/true,
11619 getSpecifierRange(startPos, posLen));
11620}
11621
11622void CheckFormatHandler::HandleInvalidPosition(
11623 const char *startSpecifier, unsigned specifierLen,
11625 EmitFormatDiagnostic(
11626 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
11627 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
11628 getSpecifierRange(startSpecifier, specifierLen));
11629}
11630
11631void CheckFormatHandler::HandleZeroPosition(const char *startPos,
11632 unsigned posLen) {
11633 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
11634 getLocationOfByte(startPos),
11635 /*IsStringLocation*/true,
11636 getSpecifierRange(startPos, posLen));
11637}
11638
11639void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
11640 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
11641 // The presence of a null character is likely an error.
11642 EmitFormatDiagnostic(
11643 S.PDiag(diag::warn_printf_format_string_contains_null_char),
11644 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
11645 getFormatStringRange());
11646 }
11647}
11648
11649// Note that this may return NULL if there was an error parsing or building
11650// one of the argument expressions.
11651const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
11652 return Args[FirstDataArg + i];
11653}
11654
11655void CheckFormatHandler::DoneProcessing() {
11656 // Does the number of data arguments exceed the number of
11657 // format conversions in the format string?
11658 if (ArgPassingKind != Sema::FAPK_VAList) {
11659 // Find any arguments that weren't covered.
11660 CoveredArgs.flip();
11661 signed notCoveredArg = CoveredArgs.find_first();
11662 if (notCoveredArg >= 0) {
11663 assert((unsigned)notCoveredArg < NumDataArgs);
11664 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
11665 } else {
11666 UncoveredArg.setAllCovered();
11667 }
11668 }
11669}
11670
11671void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
11672 const Expr *ArgExpr) {
11673 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
11674 "Invalid state");
11675
11676 if (!ArgExpr)
11677 return;
11678
11679 SourceLocation Loc = ArgExpr->getBeginLoc();
11680
11682 return;
11683
11684 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
11685 for (auto E : DiagnosticExprs)
11686 PDiag << E->getSourceRange();
11687
11688 CheckFormatHandler::EmitFormatDiagnostic(
11689 S, IsFunctionCall, DiagnosticExprs[0],
11690 PDiag, Loc, /*IsStringLocation*/false,
11691 DiagnosticExprs[0]->getSourceRange());
11692}
11693
11694bool
11695CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
11697 const char *startSpec,
11698 unsigned specifierLen,
11699 const char *csStart,
11700 unsigned csLen) {
11701 bool keepGoing = true;
11702 if (argIndex < NumDataArgs) {
11703 // Consider the argument coverered, even though the specifier doesn't
11704 // make sense.
11705 CoveredArgs.set(argIndex);
11706 }
11707 else {
11708 // If argIndex exceeds the number of data arguments we
11709 // don't issue a warning because that is just a cascade of warnings (and
11710 // they may have intended '%%' anyway). We don't want to continue processing
11711 // the format string after this point, however, as we will like just get
11712 // gibberish when trying to match arguments.
11713 keepGoing = false;
11714 }
11715
11716 StringRef Specifier(csStart, csLen);
11717
11718 // If the specifier in non-printable, it could be the first byte of a UTF-8
11719 // sequence. In that case, print the UTF-8 code point. If not, print the byte
11720 // hex value.
11721 std::string CodePointStr;
11722 if (!llvm::sys::locale::isPrint(*csStart)) {
11723 llvm::UTF32 CodePoint;
11724 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
11725 const llvm::UTF8 *E =
11726 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
11727 llvm::ConversionResult Result =
11728 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
11729
11730 if (Result != llvm::conversionOK) {
11731 unsigned char FirstChar = *csStart;
11732 CodePoint = (llvm::UTF32)FirstChar;
11733 }
11734
11735 llvm::raw_string_ostream OS(CodePointStr);
11736 if (CodePoint < 256)
11737 OS << "\\x" << llvm::format("%02x", CodePoint);
11738 else if (CodePoint <= 0xFFFF)
11739 OS << "\\u" << llvm::format("%04x", CodePoint);
11740 else
11741 OS << "\\U" << llvm::format("%08x", CodePoint);
11742 OS.flush();
11743 Specifier = CodePointStr;
11744 }
11745
11746 EmitFormatDiagnostic(
11747 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
11748 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
11749
11750 return keepGoing;
11751}
11752
11753void
11754CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
11755 const char *startSpec,
11756 unsigned specifierLen) {
11757 EmitFormatDiagnostic(
11758 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
11759 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
11760}
11761
11762bool
11763CheckFormatHandler::CheckNumArgs(
11766 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
11767
11768 if (argIndex >= NumDataArgs) {
11769 PartialDiagnostic PDiag = FS.usesPositionalArg()
11770 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
11771 << (argIndex+1) << NumDataArgs)
11772 : S.PDiag(diag::warn_printf_insufficient_data_args);
11773 EmitFormatDiagnostic(
11774 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
11775 getSpecifierRange(startSpecifier, specifierLen));
11776
11777 // Since more arguments than conversion tokens are given, by extension
11778 // all arguments are covered, so mark this as so.
11779 UncoveredArg.setAllCovered();
11780 return false;
11781 }
11782 return true;
11783}
11784
11785template<typename Range>
11786void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
11788 bool IsStringLocation,
11789 Range StringRange,
11790 ArrayRef<FixItHint> FixIt) {
11791 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
11792 Loc, IsStringLocation, StringRange, FixIt);
11793}
11794
11795/// If the format string is not within the function call, emit a note
11796/// so that the function call and string are in diagnostic messages.
11797///
11798/// \param InFunctionCall if true, the format string is within the function
11799/// call and only one diagnostic message will be produced. Otherwise, an
11800/// extra note will be emitted pointing to location of the format string.
11801///
11802/// \param ArgumentExpr the expression that is passed as the format string
11803/// argument in the function call. Used for getting locations when two
11804/// diagnostics are emitted.
11805///
11806/// \param PDiag the callee should already have provided any strings for the
11807/// diagnostic message. This function only adds locations and fixits
11808/// to diagnostics.
11809///
11810/// \param Loc primary location for diagnostic. If two diagnostics are
11811/// required, one will be at Loc and a new SourceLocation will be created for
11812/// the other one.
11813///
11814/// \param IsStringLocation if true, Loc points to the format string should be
11815/// used for the note. Otherwise, Loc points to the argument list and will
11816/// be used with PDiag.
11817///
11818/// \param StringRange some or all of the string to highlight. This is
11819/// templated so it can accept either a CharSourceRange or a SourceRange.
11820///
11821/// \param FixIt optional fix it hint for the format string.
11822template <typename Range>
11823void CheckFormatHandler::EmitFormatDiagnostic(
11824 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
11825 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
11826 Range StringRange, ArrayRef<FixItHint> FixIt) {
11827 if (InFunctionCall) {
11828 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
11829 D << StringRange;
11830 D << FixIt;
11831 } else {
11832 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
11833 << ArgumentExpr->getSourceRange();
11834
11836 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
11837 diag::note_format_string_defined);
11838
11839 Note << StringRange;
11840 Note << FixIt;
11841 }
11842}
11843
11844//===--- CHECK: Printf format string checking -----------------------------===//
11845
11846namespace {
11847
11848class CheckPrintfHandler : public CheckFormatHandler {
11849public:
11850 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
11851 const Expr *origFormatExpr,
11852 const Sema::FormatStringType type, unsigned firstDataArg,
11853 unsigned numDataArgs, bool isObjC, const char *beg,
11855 ArrayRef<const Expr *> Args, unsigned formatIdx,
11856 bool inFunctionCall, Sema::VariadicCallType CallType,
11857 llvm::SmallBitVector &CheckedVarArgs,
11858 UncoveredArgHandler &UncoveredArg)
11859 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
11860 numDataArgs, beg, APK, Args, formatIdx,
11861 inFunctionCall, CallType, CheckedVarArgs,
11862 UncoveredArg) {}
11863
11864 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
11865
11866 /// Returns true if '%@' specifiers are allowed in the format string.
11867 bool allowsObjCArg() const {
11868 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
11869 FSType == Sema::FST_OSTrace;
11870 }
11871
11872 bool HandleInvalidPrintfConversionSpecifier(
11874 const char *startSpecifier,
11875 unsigned specifierLen) override;
11876
11877 void handleInvalidMaskType(StringRef MaskType) override;
11878
11879 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
11880 const char *startSpecifier, unsigned specifierLen,
11881 const TargetInfo &Target) override;
11882 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
11883 const char *StartSpecifier,
11884 unsigned SpecifierLen,
11885 const Expr *E);
11886
11887 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
11888 const char *startSpecifier, unsigned specifierLen);
11889 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
11891 unsigned type,
11892 const char *startSpecifier, unsigned specifierLen);
11893 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
11894 const analyze_printf::OptionalFlag &flag,
11895 const char *startSpecifier, unsigned specifierLen);
11896 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
11897 const analyze_printf::OptionalFlag &ignoredFlag,
11898 const analyze_printf::OptionalFlag &flag,
11899 const char *startSpecifier, unsigned specifierLen);
11900 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
11901 const Expr *E);
11902
11903 void HandleEmptyObjCModifierFlag(const char *startFlag,
11904 unsigned flagLen) override;
11905
11906 void HandleInvalidObjCModifierFlag(const char *startFlag,
11907 unsigned flagLen) override;
11908
11909 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
11910 const char *flagsEnd,
11911 const char *conversionPosition)
11912 override;
11913};
11914
11915} // namespace
11916
11917bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
11919 const char *startSpecifier,
11920 unsigned specifierLen) {
11922 FS.getConversionSpecifier();
11923
11924 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
11925 getLocationOfByte(CS.getStart()),
11926 startSpecifier, specifierLen,
11927 CS.getStart(), CS.getLength());
11928}
11929
11930void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
11931 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
11932}
11933
11934bool CheckPrintfHandler::HandleAmount(
11935 const analyze_format_string::OptionalAmount &Amt, unsigned k,
11936 const char *startSpecifier, unsigned specifierLen) {
11937 if (Amt.hasDataArgument()) {
11938 if (ArgPassingKind != Sema::FAPK_VAList) {
11939 unsigned argIndex = Amt.getArgIndex();
11940 if (argIndex >= NumDataArgs) {
11941 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
11942 << k,
11943 getLocationOfByte(Amt.getStart()),
11944 /*IsStringLocation*/ true,
11945 getSpecifierRange(startSpecifier, specifierLen));
11946 // Don't do any more checking. We will just emit
11947 // spurious errors.
11948 return false;
11949 }
11950
11951 // Type check the data argument. It should be an 'int'.
11952 // Although not in conformance with C99, we also allow the argument to be
11953 // an 'unsigned int' as that is a reasonably safe case. GCC also
11954 // doesn't emit a warning for that case.
11955 CoveredArgs.set(argIndex);
11956 const Expr *Arg = getDataArg(argIndex);
11957 if (!Arg)
11958 return false;
11959
11960 QualType T = Arg->getType();
11961
11962 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
11963 assert(AT.isValid());
11964
11965 if (!AT.matchesType(S.Context, T)) {
11966 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
11968 << T << Arg->getSourceRange(),
11969 getLocationOfByte(Amt.getStart()),
11970 /*IsStringLocation*/true,
11971 getSpecifierRange(startSpecifier, specifierLen));
11972 // Don't do any more checking. We will just emit
11973 // spurious errors.
11974 return false;
11975 }
11976 }
11977 }
11978 return true;
11979}
11980
11981void CheckPrintfHandler::HandleInvalidAmount(
11984 unsigned type,
11985 const char *startSpecifier,
11986 unsigned specifierLen) {
11988 FS.getConversionSpecifier();
11989
11990 FixItHint fixit =
11992 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
11993 Amt.getConstantLength()))
11994 : FixItHint();
11995
11996 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
11997 << type << CS.toString(),
11998 getLocationOfByte(Amt.getStart()),
11999 /*IsStringLocation*/true,
12000 getSpecifierRange(startSpecifier, specifierLen),
12001 fixit);
12002}
12003
12004void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
12005 const analyze_printf::OptionalFlag &flag,
12006 const char *startSpecifier,
12007 unsigned specifierLen) {
12008 // Warn about pointless flag with a fixit removal.
12010 FS.getConversionSpecifier();
12011 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
12012 << flag.toString() << CS.toString(),
12013 getLocationOfByte(flag.getPosition()),
12014 /*IsStringLocation*/true,
12015 getSpecifierRange(startSpecifier, specifierLen),
12017 getSpecifierRange(flag.getPosition(), 1)));
12018}
12019
12020void CheckPrintfHandler::HandleIgnoredFlag(
12022 const analyze_printf::OptionalFlag &ignoredFlag,
12023 const analyze_printf::OptionalFlag &flag,
12024 const char *startSpecifier,
12025 unsigned specifierLen) {
12026 // Warn about ignored flag with a fixit removal.
12027 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
12028 << ignoredFlag.toString() << flag.toString(),
12029 getLocationOfByte(ignoredFlag.getPosition()),
12030 /*IsStringLocation*/true,
12031 getSpecifierRange(startSpecifier, specifierLen),
12033 getSpecifierRange(ignoredFlag.getPosition(), 1)));
12034}
12035
12036void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
12037 unsigned flagLen) {
12038 // Warn about an empty flag.
12039 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
12040 getLocationOfByte(startFlag),
12041 /*IsStringLocation*/true,
12042 getSpecifierRange(startFlag, flagLen));
12043}
12044
12045void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
12046 unsigned flagLen) {
12047 // Warn about an invalid flag.
12048 auto Range = getSpecifierRange(startFlag, flagLen);
12049 StringRef flag(startFlag, flagLen);
12050 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
12051 getLocationOfByte(startFlag),
12052 /*IsStringLocation*/true,
12054}
12055
12056void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
12057 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
12058 // Warn about using '[...]' without a '@' conversion.
12059 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
12060 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
12061 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
12062 getLocationOfByte(conversionPosition),
12063 /*IsStringLocation*/true,
12065}
12066
12067// Determines if the specified is a C++ class or struct containing
12068// a member with the specified name and kind (e.g. a CXXMethodDecl named
12069// "c_str()").
12070template<typename MemberKind>
12072CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
12073 const RecordType *RT = Ty->getAs<RecordType>();
12075
12076 if (!RT)
12077 return Results;
12078 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
12079 if (!RD || !RD->getDefinition())
12080 return Results;
12081
12082 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
12085
12086 // We just need to include all members of the right kind turned up by the
12087 // filter, at this point.
12088 if (S.LookupQualifiedName(R, RT->getDecl()))
12089 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12090 NamedDecl *decl = (*I)->getUnderlyingDecl();
12091 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
12092 Results.insert(FK);
12093 }
12094 return Results;
12095}
12096
12097/// Check if we could call '.c_str()' on an object.
12098///
12099/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
12100/// allow the call, or if it would be ambiguous).
12102 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
12103
12104 MethodSet Results =
12105 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
12106 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
12107 MI != ME; ++MI)
12108 if ((*MI)->getMinRequiredArguments() == 0)
12109 return true;
12110 return false;
12111}
12112
12113// Check if a (w)string was passed when a (w)char* was needed, and offer a
12114// better diagnostic if so. AT is assumed to be valid.
12115// Returns true when a c_str() conversion method is found.
12116bool CheckPrintfHandler::checkForCStrMembers(
12117 const analyze_printf::ArgType &AT, const Expr *E) {
12118 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
12119
12120 MethodSet Results =
12121 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
12122
12123 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
12124 MI != ME; ++MI) {
12125 const CXXMethodDecl *Method = *MI;
12126 if (Method->getMinRequiredArguments() == 0 &&
12127 AT.matchesType(S.Context, Method->getReturnType())) {
12128 // FIXME: Suggest parens if the expression needs them.
12130 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
12131 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
12132 return true;
12133 }
12134 }
12135
12136 return false;
12137}
12138
12139bool CheckPrintfHandler::HandlePrintfSpecifier(
12140 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
12141 unsigned specifierLen, const TargetInfo &Target) {
12142 using namespace analyze_format_string;
12143 using namespace analyze_printf;
12144
12145 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
12146
12147 if (FS.consumesDataArgument()) {
12148 if (atFirstArg) {
12149 atFirstArg = false;
12150 usesPositionalArgs = FS.usesPositionalArg();
12151 }
12152 else if (usesPositionalArgs != FS.usesPositionalArg()) {
12153 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
12154 startSpecifier, specifierLen);
12155 return false;
12156 }
12157 }
12158
12159 // First check if the field width, precision, and conversion specifier
12160 // have matching data arguments.
12161 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
12162 startSpecifier, specifierLen)) {
12163 return false;
12164 }
12165
12166 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
12167 startSpecifier, specifierLen)) {
12168 return false;
12169 }
12170
12171 if (!CS.consumesDataArgument()) {
12172 // FIXME: Technically specifying a precision or field width here
12173 // makes no sense. Worth issuing a warning at some point.
12174 return true;
12175 }
12176
12177 // Consume the argument.
12178 unsigned argIndex = FS.getArgIndex();
12179 if (argIndex < NumDataArgs) {
12180 // The check to see if the argIndex is valid will come later.
12181 // We set the bit here because we may exit early from this
12182 // function if we encounter some other error.
12183 CoveredArgs.set(argIndex);
12184 }
12185
12186 // FreeBSD kernel extensions.
12187 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
12188 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
12189 // We need at least two arguments.
12190 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
12191 return false;
12192
12193 // Claim the second argument.
12194 CoveredArgs.set(argIndex + 1);
12195
12196 // Type check the first argument (int for %b, pointer for %D)
12197 const Expr *Ex = getDataArg(argIndex);
12198 const analyze_printf::ArgType &AT =
12199 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
12200 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
12201 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
12202 EmitFormatDiagnostic(
12203 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
12204 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
12205 << false << Ex->getSourceRange(),
12206 Ex->getBeginLoc(), /*IsStringLocation*/ false,
12207 getSpecifierRange(startSpecifier, specifierLen));
12208
12209 // Type check the second argument (char * for both %b and %D)
12210 Ex = getDataArg(argIndex + 1);
12211 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
12212 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
12213 EmitFormatDiagnostic(
12214 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
12215 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
12216 << false << Ex->getSourceRange(),
12217 Ex->getBeginLoc(), /*IsStringLocation*/ false,
12218 getSpecifierRange(startSpecifier, specifierLen));
12219
12220 return true;
12221 }
12222
12223 // Check for using an Objective-C specific conversion specifier
12224 // in a non-ObjC literal.
12225 if (!allowsObjCArg() && CS.isObjCArg()) {
12226 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
12227 specifierLen);
12228 }
12229
12230 // %P can only be used with os_log.
12231 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
12232 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
12233 specifierLen);
12234 }
12235
12236 // %n is not allowed with os_log.
12237 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
12238 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
12239 getLocationOfByte(CS.getStart()),
12240 /*IsStringLocation*/ false,
12241 getSpecifierRange(startSpecifier, specifierLen));
12242
12243 return true;
12244 }
12245
12246 // Only scalars are allowed for os_trace.
12247 if (FSType == Sema::FST_OSTrace &&
12248 (CS.getKind() == ConversionSpecifier::PArg ||
12249 CS.getKind() == ConversionSpecifier::sArg ||
12250 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
12251 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
12252 specifierLen);
12253 }
12254
12255 // Check for use of public/private annotation outside of os_log().
12256 if (FSType != Sema::FST_OSLog) {
12257 if (FS.isPublic().isSet()) {
12258 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
12259 << "public",
12260 getLocationOfByte(FS.isPublic().getPosition()),
12261 /*IsStringLocation*/ false,
12262 getSpecifierRange(startSpecifier, specifierLen));
12263 }
12264 if (FS.isPrivate().isSet()) {
12265 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
12266 << "private",
12267 getLocationOfByte(FS.isPrivate().getPosition()),
12268 /*IsStringLocation*/ false,
12269 getSpecifierRange(startSpecifier, specifierLen));
12270 }
12271 }
12272
12273 const llvm::Triple &Triple = Target.getTriple();
12274 if (CS.getKind() == ConversionSpecifier::nArg &&
12275 (Triple.isAndroid() || Triple.isOSFuchsia())) {
12276 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
12277 getLocationOfByte(CS.getStart()),
12278 /*IsStringLocation*/ false,
12279 getSpecifierRange(startSpecifier, specifierLen));
12280 }
12281
12282 // Check for invalid use of field width
12283 if (!FS.hasValidFieldWidth()) {
12284 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
12285 startSpecifier, specifierLen);
12286 }
12287
12288 // Check for invalid use of precision
12289 if (!FS.hasValidPrecision()) {
12290 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
12291 startSpecifier, specifierLen);
12292 }
12293
12294 // Precision is mandatory for %P specifier.
12295 if (CS.getKind() == ConversionSpecifier::PArg &&
12296 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
12297 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
12298 getLocationOfByte(startSpecifier),
12299 /*IsStringLocation*/ false,
12300 getSpecifierRange(startSpecifier, specifierLen));
12301 }
12302
12303 // Check each flag does not conflict with any other component.
12304 if (!FS.hasValidThousandsGroupingPrefix())
12305 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
12306 if (!FS.hasValidLeadingZeros())
12307 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
12308 if (!FS.hasValidPlusPrefix())
12309 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
12310 if (!FS.hasValidSpacePrefix())
12311 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
12312 if (!FS.hasValidAlternativeForm())
12313 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
12314 if (!FS.hasValidLeftJustified())
12315 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
12316
12317 // Check that flags are not ignored by another flag
12318 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
12319 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
12320 startSpecifier, specifierLen);
12321 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
12322 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
12323 startSpecifier, specifierLen);
12324
12325 // Check the length modifier is valid with the given conversion specifier.
12326 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
12327 S.getLangOpts()))
12328 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
12329 diag::warn_format_nonsensical_length);
12330 else if (!FS.hasStandardLengthModifier())
12331 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
12332 else if (!FS.hasStandardLengthConversionCombination())
12333 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
12334 diag::warn_format_non_standard_conversion_spec);
12335
12336 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
12337 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
12338
12339 // The remaining checks depend on the data arguments.
12340 if (ArgPassingKind == Sema::FAPK_VAList)
12341 return true;
12342
12343 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
12344 return false;
12345
12346 const Expr *Arg = getDataArg(argIndex);
12347 if (!Arg)
12348 return true;
12349
12350 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
12351}
12352
12353static bool requiresParensToAddCast(const Expr *E) {
12354 // FIXME: We should have a general way to reason about operator
12355 // precedence and whether parens are actually needed here.
12356 // Take care of a few common cases where they aren't.
12357 const Expr *Inside = E->IgnoreImpCasts();
12358 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
12359 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
12360
12361 switch (Inside->getStmtClass()) {
12362 case Stmt::ArraySubscriptExprClass:
12363 case Stmt::CallExprClass:
12364 case Stmt::CharacterLiteralClass:
12365 case Stmt::CXXBoolLiteralExprClass:
12366 case Stmt::DeclRefExprClass:
12367 case Stmt::FloatingLiteralClass:
12368 case Stmt::IntegerLiteralClass:
12369 case Stmt::MemberExprClass:
12370 case Stmt::ObjCArrayLiteralClass:
12371 case Stmt::ObjCBoolLiteralExprClass:
12372 case Stmt::ObjCBoxedExprClass:
12373 case Stmt::ObjCDictionaryLiteralClass:
12374 case Stmt::ObjCEncodeExprClass:
12375 case Stmt::ObjCIvarRefExprClass:
12376 case Stmt::ObjCMessageExprClass:
12377 case Stmt::ObjCPropertyRefExprClass:
12378 case Stmt::ObjCStringLiteralClass:
12379 case Stmt::ObjCSubscriptRefExprClass:
12380 case Stmt::ParenExprClass:
12381 case Stmt::StringLiteralClass:
12382 case Stmt::UnaryOperatorClass:
12383 return false;
12384 default:
12385 return true;
12386 }
12387}
12388
12389static std::pair<QualType, StringRef>
12391 QualType IntendedTy,
12392 const Expr *E) {
12393 // Use a 'while' to peel off layers of typedefs.
12394 QualType TyTy = IntendedTy;
12395 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
12396 StringRef Name = UserTy->getDecl()->getName();
12397 QualType CastTy = llvm::StringSwitch<QualType>(Name)
12398 .Case("CFIndex", Context.getNSIntegerType())
12399 .Case("NSInteger", Context.getNSIntegerType())
12400 .Case("NSUInteger", Context.getNSUIntegerType())
12401 .Case("SInt32", Context.IntTy)
12402 .Case("UInt32", Context.UnsignedIntTy)
12403 .Default(QualType());
12404
12405 if (!CastTy.isNull())
12406 return std::make_pair(CastTy, Name);
12407
12408 TyTy = UserTy->desugar();
12409 }
12410
12411 // Strip parens if necessary.
12412 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
12413 return shouldNotPrintDirectly(Context,
12414 PE->getSubExpr()->getType(),
12415 PE->getSubExpr());
12416
12417 // If this is a conditional expression, then its result type is constructed
12418 // via usual arithmetic conversions and thus there might be no necessary
12419 // typedef sugar there. Recurse to operands to check for NSInteger &
12420 // Co. usage condition.
12421 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12422 QualType TrueTy, FalseTy;
12423 StringRef TrueName, FalseName;
12424
12425 std::tie(TrueTy, TrueName) =
12426 shouldNotPrintDirectly(Context,
12427 CO->getTrueExpr()->getType(),
12428 CO->getTrueExpr());
12429 std::tie(FalseTy, FalseName) =
12430 shouldNotPrintDirectly(Context,
12431 CO->getFalseExpr()->getType(),
12432 CO->getFalseExpr());
12433
12434 if (TrueTy == FalseTy)
12435 return std::make_pair(TrueTy, TrueName);
12436 else if (TrueTy.isNull())
12437 return std::make_pair(FalseTy, FalseName);
12438 else if (FalseTy.isNull())
12439 return std::make_pair(TrueTy, TrueName);
12440 }
12441
12442 return std::make_pair(QualType(), StringRef());
12443}
12444
12445/// Return true if \p ICE is an implicit argument promotion of an arithmetic
12446/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
12447/// type do not count.
12448static bool
12450 QualType From = ICE->getSubExpr()->getType();
12451 QualType To = ICE->getType();
12452 // It's an integer promotion if the destination type is the promoted
12453 // source type.
12454 if (ICE->getCastKind() == CK_IntegralCast &&
12456 S.Context.getPromotedIntegerType(From) == To)
12457 return true;
12458 // Look through vector types, since we do default argument promotion for
12459 // those in OpenCL.
12460 if (const auto *VecTy = From->getAs<ExtVectorType>())
12461 From = VecTy->getElementType();
12462 if (const auto *VecTy = To->getAs<ExtVectorType>())
12463 To = VecTy->getElementType();
12464 // It's a floating promotion if the source type is a lower rank.
12465 return ICE->getCastKind() == CK_FloatingCast &&
12466 S.Context.getFloatingTypeOrder(From, To) < 0;
12467}
12468
12473 Match =
12474 Diags.isIgnored(
12475 diag::warn_format_conversion_argument_type_mismatch_signedness, Loc)
12478 }
12479 return Match;
12480}
12481
12482bool
12483CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
12484 const char *StartSpecifier,
12485 unsigned SpecifierLen,
12486 const Expr *E) {
12487 using namespace analyze_format_string;
12488 using namespace analyze_printf;
12489
12490 // Now type check the data expression that matches the
12491 // format specifier.
12492 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
12493 if (!AT.isValid())
12494 return true;
12495
12496 QualType ExprTy = E->getType();
12497 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
12498 ExprTy = TET->getUnderlyingExpr()->getType();
12499 }
12500
12501 // When using the format attribute in C++, you can receive a function or an
12502 // array that will necessarily decay to a pointer when passed to the final
12503 // format consumer. Apply decay before type comparison.
12504 if (ExprTy->canDecayToPointerType())
12505 ExprTy = S.Context.getDecayedType(ExprTy);
12506
12507 // Diagnose attempts to print a boolean value as a character. Unlike other
12508 // -Wformat diagnostics, this is fine from a type perspective, but it still
12509 // doesn't make sense.
12510 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
12512 const CharSourceRange &CSR =
12513 getSpecifierRange(StartSpecifier, SpecifierLen);
12514 SmallString<4> FSString;
12515 llvm::raw_svector_ostream os(FSString);
12516 FS.toString(os);
12517 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
12518 << FSString,
12519 E->getExprLoc(), false, CSR);
12520 return true;
12521 }
12522
12523 // Diagnose attempts to use '%P' with ObjC object types, which will result in
12524 // dumping raw class data (like is-a pointer), not actual data.
12525 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::PArg &&
12526 ExprTy->isObjCObjectPointerType()) {
12527 const CharSourceRange &CSR =
12528 getSpecifierRange(StartSpecifier, SpecifierLen);
12529 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
12530 E->getExprLoc(), false, CSR);
12531 return true;
12532 }
12533
12534 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
12535 ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
12536 ArgType::MatchKind OrigMatch = Match;
12537
12538 Match = handleFormatSignedness(Match, S.getDiagnostics(), E->getExprLoc());
12539 if (Match == ArgType::Match)
12540 return true;
12541
12542 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
12543 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
12544
12545 // Look through argument promotions for our error message's reported type.
12546 // This includes the integral and floating promotions, but excludes array
12547 // and function pointer decay (seeing that an argument intended to be a
12548 // string has type 'char [6]' is probably more confusing than 'char *') and
12549 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
12550 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12551 if (isArithmeticArgumentPromotion(S, ICE)) {
12552 E = ICE->getSubExpr();
12553 ExprTy = E->getType();
12554
12555 // Check if we didn't match because of an implicit cast from a 'char'
12556 // or 'short' to an 'int'. This is done because printf is a varargs
12557 // function.
12558 if (ICE->getType() == S.Context.IntTy ||
12559 ICE->getType() == S.Context.UnsignedIntTy) {
12560 // All further checking is done on the subexpression
12561 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
12562 if (OrigMatch == ArgType::NoMatchSignedness &&
12563 ImplicitMatch != ArgType::NoMatchSignedness)
12564 // If the original match was a signedness match this match on the
12565 // implicit cast type also need to be signedness match otherwise we
12566 // might introduce new unexpected warnings from -Wformat-signedness.
12567 return true;
12568 ImplicitMatch = handleFormatSignedness(
12569 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
12570 if (ImplicitMatch == ArgType::Match)
12571 return true;
12572 }
12573 }
12574 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
12575 // Special case for 'a', which has type 'int' in C.
12576 // Note, however, that we do /not/ want to treat multibyte constants like
12577 // 'MooV' as characters! This form is deprecated but still exists. In
12578 // addition, don't treat expressions as of type 'char' if one byte length
12579 // modifier is provided.
12580 if (ExprTy == S.Context.IntTy &&
12581 FS.getLengthModifier().getKind() != LengthModifier::AsChar)
12582 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
12583 ExprTy = S.Context.CharTy;
12584 // To improve check results, we consider a character literal in C
12585 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
12586 // more likely a type confusion situation, so we will suggest to
12587 // use '%hhd' instead by discarding the MatchPromotion.
12588 if (Match == ArgType::MatchPromotion)
12589 Match = ArgType::NoMatch;
12590 }
12591 }
12592 if (Match == ArgType::MatchPromotion) {
12593 // WG14 N2562 only clarified promotions in *printf
12594 // For NSLog in ObjC, just preserve -Wformat behavior
12595 if (!S.getLangOpts().ObjC &&
12596 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
12597 ImplicitMatch != ArgType::NoMatchTypeConfusion)
12598 return true;
12599 Match = ArgType::NoMatch;
12600 }
12601 if (ImplicitMatch == ArgType::NoMatchPedantic ||
12602 ImplicitMatch == ArgType::NoMatchTypeConfusion)
12603 Match = ImplicitMatch;
12604 assert(Match != ArgType::MatchPromotion);
12605
12606 // Look through unscoped enums to their underlying type.
12607 bool IsEnum = false;
12608 bool IsScopedEnum = false;
12609 QualType IntendedTy = ExprTy;
12610 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
12611 IntendedTy = EnumTy->getDecl()->getIntegerType();
12612 if (EnumTy->isUnscopedEnumerationType()) {
12613 ExprTy = IntendedTy;
12614 // This controls whether we're talking about the underlying type or not,
12615 // which we only want to do when it's an unscoped enum.
12616 IsEnum = true;
12617 } else {
12618 IsScopedEnum = true;
12619 }
12620 }
12621
12622 // %C in an Objective-C context prints a unichar, not a wchar_t.
12623 // If the argument is an integer of some kind, believe the %C and suggest
12624 // a cast instead of changing the conversion specifier.
12625 if (isObjCContext() &&
12626 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
12628 !ExprTy->isCharType()) {
12629 // 'unichar' is defined as a typedef of unsigned short, but we should
12630 // prefer using the typedef if it is visible.
12631 IntendedTy = S.Context.UnsignedShortTy;
12632
12633 // While we are here, check if the value is an IntegerLiteral that happens
12634 // to be within the valid range.
12635 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
12636 const llvm::APInt &V = IL->getValue();
12637 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
12638 return true;
12639 }
12640
12641 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
12643 if (S.LookupName(Result, S.getCurScope())) {
12644 NamedDecl *ND = Result.getFoundDecl();
12645 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
12646 if (TD->getUnderlyingType() == IntendedTy)
12647 IntendedTy = S.Context.getTypedefType(TD);
12648 }
12649 }
12650 }
12651
12652 // Special-case some of Darwin's platform-independence types by suggesting
12653 // casts to primitive types that are known to be large enough.
12654 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
12655 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
12656 QualType CastTy;
12657 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
12658 if (!CastTy.isNull()) {
12659 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
12660 // (long in ASTContext). Only complain to pedants or when they're the
12661 // underlying type of a scoped enum (which always needs a cast).
12662 if (!IsScopedEnum &&
12663 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
12664 (AT.isSizeT() || AT.isPtrdiffT()) &&
12665 AT.matchesType(S.Context, CastTy))
12666 Match = ArgType::NoMatchPedantic;
12667 IntendedTy = CastTy;
12668 ShouldNotPrintDirectly = true;
12669 }
12670 }
12671
12672 // We may be able to offer a FixItHint if it is a supported type.
12673 PrintfSpecifier fixedFS = FS;
12674 bool Success =
12675 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
12676
12677 if (Success) {
12678 // Get the fix string from the fixed format specifier
12679 SmallString<16> buf;
12680 llvm::raw_svector_ostream os(buf);
12681 fixedFS.toString(os);
12682
12683 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
12684
12685 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
12686 unsigned Diag;
12687 switch (Match) {
12688 case ArgType::Match:
12689 case ArgType::MatchPromotion:
12690 case ArgType::NoMatchPromotionTypeConfusion:
12691 case ArgType::NoMatchSignedness:
12692 llvm_unreachable("expected non-matching");
12693 case ArgType::NoMatchPedantic:
12694 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
12695 break;
12696 case ArgType::NoMatchTypeConfusion:
12697 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
12698 break;
12699 case ArgType::NoMatch:
12700 Diag = diag::warn_format_conversion_argument_type_mismatch;
12701 break;
12702 }
12703
12704 // In this case, the specifier is wrong and should be changed to match
12705 // the argument.
12706 EmitFormatDiagnostic(S.PDiag(Diag)
12708 << IntendedTy << IsEnum << E->getSourceRange(),
12709 E->getBeginLoc(),
12710 /*IsStringLocation*/ false, SpecRange,
12711 FixItHint::CreateReplacement(SpecRange, os.str()));
12712 } else {
12713 // The canonical type for formatting this value is different from the
12714 // actual type of the expression. (This occurs, for example, with Darwin's
12715 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
12716 // should be printed as 'long' for 64-bit compatibility.)
12717 // Rather than emitting a normal format/argument mismatch, we want to
12718 // add a cast to the recommended type (and correct the format string
12719 // if necessary). We should also do so for scoped enumerations.
12720 SmallString<16> CastBuf;
12721 llvm::raw_svector_ostream CastFix(CastBuf);
12722 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
12723 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
12724 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
12725
12727 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
12728 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
12729 E->getExprLoc());
12730 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
12731 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
12732
12733 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
12734 // If there's already a cast present, just replace it.
12735 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
12736 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
12737
12738 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
12739 // If the expression has high enough precedence,
12740 // just write the C-style cast.
12741 Hints.push_back(
12742 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
12743 } else {
12744 // Otherwise, add parens around the expression as well as the cast.
12745 CastFix << "(";
12746 Hints.push_back(
12747 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
12748
12749 // We don't use getLocForEndOfToken because it returns invalid source
12750 // locations for macro expansions (by design).
12754 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
12755 }
12756
12757 if (ShouldNotPrintDirectly && !IsScopedEnum) {
12758 // The expression has a type that should not be printed directly.
12759 // We extract the name from the typedef because we don't want to show
12760 // the underlying type in the diagnostic.
12761 StringRef Name;
12762 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
12763 Name = TypedefTy->getDecl()->getName();
12764 else
12765 Name = CastTyName;
12766 unsigned Diag = Match == ArgType::NoMatchPedantic
12767 ? diag::warn_format_argument_needs_cast_pedantic
12768 : diag::warn_format_argument_needs_cast;
12769 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
12770 << E->getSourceRange(),
12771 E->getBeginLoc(), /*IsStringLocation=*/false,
12772 SpecRange, Hints);
12773 } else {
12774 // In this case, the expression could be printed using a different
12775 // specifier, but we've decided that the specifier is probably correct
12776 // and we should cast instead. Just use the normal warning message.
12777
12778 unsigned Diag =
12779 IsScopedEnum
12780 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
12781 : diag::warn_format_conversion_argument_type_mismatch;
12782
12783 EmitFormatDiagnostic(
12784 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
12785 << IsEnum << E->getSourceRange(),
12786 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
12787 }
12788 }
12789 } else {
12790 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
12791 SpecifierLen);
12792 // Since the warning for passing non-POD types to variadic functions
12793 // was deferred until now, we emit a warning for non-POD
12794 // arguments here.
12795 bool EmitTypeMismatch = false;
12796 switch (S.isValidVarArgType(ExprTy)) {
12797 case Sema::VAK_Valid:
12799 unsigned Diag;
12800 switch (Match) {
12801 case ArgType::Match:
12802 case ArgType::MatchPromotion:
12803 case ArgType::NoMatchPromotionTypeConfusion:
12804 case ArgType::NoMatchSignedness:
12805 llvm_unreachable("expected non-matching");
12806 case ArgType::NoMatchPedantic:
12807 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
12808 break;
12809 case ArgType::NoMatchTypeConfusion:
12810 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
12811 break;
12812 case ArgType::NoMatch:
12813 Diag = diag::warn_format_conversion_argument_type_mismatch;
12814 break;
12815 }
12816
12817 EmitFormatDiagnostic(
12818 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
12819 << IsEnum << CSR << E->getSourceRange(),
12820 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
12821 break;
12822 }
12825 if (CallType == Sema::VariadicDoesNotApply) {
12826 EmitTypeMismatch = true;
12827 } else {
12828 EmitFormatDiagnostic(
12829 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
12830 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
12831 << AT.getRepresentativeTypeName(S.Context) << CSR
12832 << E->getSourceRange(),
12833 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
12834 checkForCStrMembers(AT, E);
12835 }
12836 break;
12837
12838 case Sema::VAK_Invalid:
12839 if (CallType == Sema::VariadicDoesNotApply)
12840 EmitTypeMismatch = true;
12841 else if (ExprTy->isObjCObjectType())
12842 EmitFormatDiagnostic(
12843 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
12844 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
12845 << AT.getRepresentativeTypeName(S.Context) << CSR
12846 << E->getSourceRange(),
12847 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
12848 else
12849 // FIXME: If this is an initializer list, suggest removing the braces
12850 // or inserting a cast to the target type.
12851 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
12852 << isa<InitListExpr>(E) << ExprTy << CallType
12854 break;
12855 }
12856
12857 if (EmitTypeMismatch) {
12858 // The function is not variadic, so we do not generate warnings about
12859 // being allowed to pass that object as a variadic argument. Instead,
12860 // since there are inherently no printf specifiers for types which cannot
12861 // be passed as variadic arguments, emit a plain old specifier mismatch
12862 // argument.
12863 EmitFormatDiagnostic(
12864 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
12865 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
12866 << E->getSourceRange(),
12867 E->getBeginLoc(), false, CSR);
12868 }
12869
12870 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
12871 "format string specifier index out of range");
12872 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
12873 }
12874
12875 return true;
12876}
12877
12878//===--- CHECK: Scanf format string checking ------------------------------===//
12879
12880namespace {
12881
12882class CheckScanfHandler : public CheckFormatHandler {
12883public:
12884 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
12885 const Expr *origFormatExpr, Sema::FormatStringType type,
12886 unsigned firstDataArg, unsigned numDataArgs,
12887 const char *beg, Sema::FormatArgumentPassingKind APK,
12888 ArrayRef<const Expr *> Args, unsigned formatIdx,
12889 bool inFunctionCall, Sema::VariadicCallType CallType,
12890 llvm::SmallBitVector &CheckedVarArgs,
12891 UncoveredArgHandler &UncoveredArg)
12892 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
12893 numDataArgs, beg, APK, Args, formatIdx,
12894 inFunctionCall, CallType, CheckedVarArgs,
12895 UncoveredArg) {}
12896
12897 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
12898 const char *startSpecifier,
12899 unsigned specifierLen) override;
12900
12901 bool HandleInvalidScanfConversionSpecifier(
12903 const char *startSpecifier,
12904 unsigned specifierLen) override;
12905
12906 void HandleIncompleteScanList(const char *start, const char *end) override;
12907};
12908
12909} // namespace
12910
12911void CheckScanfHandler::HandleIncompleteScanList(const char *start,
12912 const char *end) {
12913 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
12914 getLocationOfByte(end), /*IsStringLocation*/true,
12915 getSpecifierRange(start, end - start));
12916}
12917
12918bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
12920 const char *startSpecifier,
12921 unsigned specifierLen) {
12923 FS.getConversionSpecifier();
12924
12925 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
12926 getLocationOfByte(CS.getStart()),
12927 startSpecifier, specifierLen,
12928 CS.getStart(), CS.getLength());
12929}
12930
12931bool CheckScanfHandler::HandleScanfSpecifier(
12933 const char *startSpecifier,
12934 unsigned specifierLen) {
12935 using namespace analyze_scanf;
12936 using namespace analyze_format_string;
12937
12938 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
12939
12940 // Handle case where '%' and '*' don't consume an argument. These shouldn't
12941 // be used to decide if we are using positional arguments consistently.
12942 if (FS.consumesDataArgument()) {
12943 if (atFirstArg) {
12944 atFirstArg = false;
12945 usesPositionalArgs = FS.usesPositionalArg();
12946 }
12947 else if (usesPositionalArgs != FS.usesPositionalArg()) {
12948 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
12949 startSpecifier, specifierLen);
12950 return false;
12951 }
12952 }
12953
12954 // Check if the field with is non-zero.
12955 const OptionalAmount &Amt = FS.getFieldWidth();
12956 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
12957 if (Amt.getConstantAmount() == 0) {
12958 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
12959 Amt.getConstantLength());
12960 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
12961 getLocationOfByte(Amt.getStart()),
12962 /*IsStringLocation*/true, R,
12964 }
12965 }
12966
12967 if (!FS.consumesDataArgument()) {
12968 // FIXME: Technically specifying a precision or field width here
12969 // makes no sense. Worth issuing a warning at some point.
12970 return true;
12971 }
12972
12973 // Consume the argument.
12974 unsigned argIndex = FS.getArgIndex();
12975 if (argIndex < NumDataArgs) {
12976 // The check to see if the argIndex is valid will come later.
12977 // We set the bit here because we may exit early from this
12978 // function if we encounter some other error.
12979 CoveredArgs.set(argIndex);
12980 }
12981
12982 // Check the length modifier is valid with the given conversion specifier.
12983 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
12984 S.getLangOpts()))
12985 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
12986 diag::warn_format_nonsensical_length);
12987 else if (!FS.hasStandardLengthModifier())
12988 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
12989 else if (!FS.hasStandardLengthConversionCombination())
12990 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
12991 diag::warn_format_non_standard_conversion_spec);
12992
12993 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
12994 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
12995
12996 // The remaining checks depend on the data arguments.
12997 if (ArgPassingKind == Sema::FAPK_VAList)
12998 return true;
12999
13000 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
13001 return false;
13002
13003 // Check that the argument type matches the format specifier.
13004 const Expr *Ex = getDataArg(argIndex);
13005 if (!Ex)
13006 return true;
13007
13008 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
13009
13010 if (!AT.isValid()) {
13011 return true;
13012 }
13013
13015 AT.matchesType(S.Context, Ex->getType());
13016 Match = handleFormatSignedness(Match, S.getDiagnostics(), Ex->getExprLoc());
13019 return true;
13020
13021 ScanfSpecifier fixedFS = FS;
13022 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
13023 S.getLangOpts(), S.Context);
13024
13025 unsigned Diag =
13026 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
13027 : diag::warn_format_conversion_argument_type_mismatch;
13028
13029 if (Success) {
13030 // Get the fix string from the fixed format specifier.
13031 SmallString<128> buf;
13032 llvm::raw_svector_ostream os(buf);
13033 fixedFS.toString(os);
13034
13035 EmitFormatDiagnostic(
13037 << Ex->getType() << false << Ex->getSourceRange(),
13038 Ex->getBeginLoc(),
13039 /*IsStringLocation*/ false,
13040 getSpecifierRange(startSpecifier, specifierLen),
13042 getSpecifierRange(startSpecifier, specifierLen), os.str()));
13043 } else {
13044 EmitFormatDiagnostic(S.PDiag(Diag)
13046 << Ex->getType() << false << Ex->getSourceRange(),
13047 Ex->getBeginLoc(),
13048 /*IsStringLocation*/ false,
13049 getSpecifierRange(startSpecifier, specifierLen));
13050 }
13051
13052 return true;
13053}
13054
13056 Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr,
13058 unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type,
13059 bool inFunctionCall, Sema::VariadicCallType CallType,
13060 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
13061 bool IgnoreStringsWithoutSpecifiers) {
13062 // CHECK: is the format string a wide literal?
13063 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
13064 CheckFormatHandler::EmitFormatDiagnostic(
13065 S, inFunctionCall, Args[format_idx],
13066 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
13067 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
13068 return;
13069 }
13070
13071 // Str - The format string. NOTE: this is NOT null-terminated!
13072 StringRef StrRef = FExpr->getString();
13073 const char *Str = StrRef.data();
13074 // Account for cases where the string literal is truncated in a declaration.
13075 const ConstantArrayType *T =
13076 S.Context.getAsConstantArrayType(FExpr->getType());
13077 assert(T && "String literal not of constant array type!");
13078 size_t TypeSize = T->getZExtSize();
13079 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
13080 const unsigned numDataArgs = Args.size() - firstDataArg;
13081
13082 if (IgnoreStringsWithoutSpecifiers &&
13084 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
13085 return;
13086
13087 // Emit a warning if the string literal is truncated and does not contain an
13088 // embedded null character.
13089 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
13090 CheckFormatHandler::EmitFormatDiagnostic(
13091 S, inFunctionCall, Args[format_idx],
13092 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
13093 FExpr->getBeginLoc(),
13094 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
13095 return;
13096 }
13097
13098 // CHECK: empty format string?
13099 if (StrLen == 0 && numDataArgs > 0) {
13100 CheckFormatHandler::EmitFormatDiagnostic(
13101 S, inFunctionCall, Args[format_idx],
13102 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
13103 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
13104 return;
13105 }
13106
13110 CheckPrintfHandler H(
13111 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
13112 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, APK,
13113 Args, format_idx, inFunctionCall, CallType, CheckedVarArgs,
13114 UncoveredArg);
13115
13117 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
13119 H.DoneProcessing();
13120 } else if (Type == Sema::FST_Scanf) {
13121 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
13122 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
13123 CallType, CheckedVarArgs, UncoveredArg);
13124
13126 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
13127 H.DoneProcessing();
13128 } // TODO: handle other formats
13129}
13130
13132 // Str - The format string. NOTE: this is NOT null-terminated!
13133 StringRef StrRef = FExpr->getString();
13134 const char *Str = StrRef.data();
13135 // Account for cases where the string literal is truncated in a declaration.
13137 assert(T && "String literal not of constant array type!");
13138 size_t TypeSize = T->getZExtSize();
13139 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
13140 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
13141 getLangOpts(),
13143}
13144
13145//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
13146
13147// Returns the related absolute value function that is larger, of 0 if one
13148// does not exist.
13149static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
13150 switch (AbsFunction) {
13151 default:
13152 return 0;
13153
13154 case Builtin::BI__builtin_abs:
13155 return Builtin::BI__builtin_labs;
13156 case Builtin::BI__builtin_labs:
13157 return Builtin::BI__builtin_llabs;
13158 case Builtin::BI__builtin_llabs:
13159 return 0;
13160
13161 case Builtin::BI__builtin_fabsf:
13162 return Builtin::BI__builtin_fabs;
13163 case Builtin::BI__builtin_fabs:
13164 return Builtin::BI__builtin_fabsl;
13165 case Builtin::BI__builtin_fabsl:
13166 return 0;
13167
13168 case Builtin::BI__builtin_cabsf:
13169 return Builtin::BI__builtin_cabs;
13170 case Builtin::BI__builtin_cabs:
13171 return Builtin::BI__builtin_cabsl;
13172 case Builtin::BI__builtin_cabsl:
13173 return 0;
13174
13175 case Builtin::BIabs:
13176 return Builtin::BIlabs;
13177 case Builtin::BIlabs:
13178 return Builtin::BIllabs;
13179 case Builtin::BIllabs:
13180 return 0;
13181
13182 case Builtin::BIfabsf:
13183 return Builtin::BIfabs;
13184 case Builtin::BIfabs:
13185 return Builtin::BIfabsl;
13186 case Builtin::BIfabsl:
13187 return 0;
13188
13189 case Builtin::BIcabsf:
13190 return Builtin::BIcabs;
13191 case Builtin::BIcabs:
13192 return Builtin::BIcabsl;
13193 case Builtin::BIcabsl:
13194 return 0;
13195 }
13196}
13197
13198// Returns the argument type of the absolute value function.
13200 unsigned AbsType) {
13201 if (AbsType == 0)
13202 return QualType();
13203
13205 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
13206 if (Error != ASTContext::GE_None)
13207 return QualType();
13208
13210 if (!FT)
13211 return QualType();
13212
13213 if (FT->getNumParams() != 1)
13214 return QualType();
13215
13216 return FT->getParamType(0);
13217}
13218
13219// Returns the best absolute value function, or zero, based on type and
13220// current absolute value function.
13221static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
13222 unsigned AbsFunctionKind) {
13223 unsigned BestKind = 0;
13224 uint64_t ArgSize = Context.getTypeSize(ArgType);
13225 for (unsigned Kind = AbsFunctionKind; Kind != 0;
13226 Kind = getLargerAbsoluteValueFunction(Kind)) {
13227 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
13228 if (Context.getTypeSize(ParamType) >= ArgSize) {
13229 if (BestKind == 0)
13230 BestKind = Kind;
13231 else if (Context.hasSameType(ParamType, ArgType)) {
13232 BestKind = Kind;
13233 break;
13234 }
13235 }
13236 }
13237 return BestKind;
13238}
13239
13245
13248 return AVK_Integer;
13249 if (T->isRealFloatingType())
13250 return AVK_Floating;
13251 if (T->isAnyComplexType())
13252 return AVK_Complex;
13253
13254 llvm_unreachable("Type not integer, floating, or complex");
13255}
13256
13257// Changes the absolute value function to a different type. Preserves whether
13258// the function is a builtin.
13259static unsigned changeAbsFunction(unsigned AbsKind,
13260 AbsoluteValueKind ValueKind) {
13261 switch (ValueKind) {
13262 case AVK_Integer:
13263 switch (AbsKind) {
13264 default:
13265 return 0;
13266 case Builtin::BI__builtin_fabsf:
13267 case Builtin::BI__builtin_fabs:
13268 case Builtin::BI__builtin_fabsl:
13269 case Builtin::BI__builtin_cabsf:
13270 case Builtin::BI__builtin_cabs:
13271 case Builtin::BI__builtin_cabsl:
13272 return Builtin::BI__builtin_abs;
13273 case Builtin::BIfabsf:
13274 case Builtin::BIfabs:
13275 case Builtin::BIfabsl:
13276 case Builtin::BIcabsf:
13277 case Builtin::BIcabs:
13278 case Builtin::BIcabsl:
13279 return Builtin::BIabs;
13280 }
13281 case AVK_Floating:
13282 switch (AbsKind) {
13283 default:
13284 return 0;
13285 case Builtin::BI__builtin_abs:
13286 case Builtin::BI__builtin_labs:
13287 case Builtin::BI__builtin_llabs:
13288 case Builtin::BI__builtin_cabsf:
13289 case Builtin::BI__builtin_cabs:
13290 case Builtin::BI__builtin_cabsl:
13291 return Builtin::BI__builtin_fabsf;
13292 case Builtin::BIabs:
13293 case Builtin::BIlabs:
13294 case Builtin::BIllabs:
13295 case Builtin::BIcabsf:
13296 case Builtin::BIcabs:
13297 case Builtin::BIcabsl:
13298 return Builtin::BIfabsf;
13299 }
13300 case AVK_Complex:
13301 switch (AbsKind) {
13302 default:
13303 return 0;
13304 case Builtin::BI__builtin_abs:
13305 case Builtin::BI__builtin_labs:
13306 case Builtin::BI__builtin_llabs:
13307 case Builtin::BI__builtin_fabsf:
13308 case Builtin::BI__builtin_fabs:
13309 case Builtin::BI__builtin_fabsl:
13310 return Builtin::BI__builtin_cabsf;
13311 case Builtin::BIabs:
13312 case Builtin::BIlabs:
13313 case Builtin::BIllabs:
13314 case Builtin::BIfabsf:
13315 case Builtin::BIfabs:
13316 case Builtin::BIfabsl:
13317 return Builtin::BIcabsf;
13318 }
13319 }
13320 llvm_unreachable("Unable to convert function");
13321}
13322
13323static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
13324 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
13325 if (!FnInfo)
13326 return 0;
13327
13328 switch (FDecl->getBuiltinID()) {
13329 default:
13330 return 0;
13331 case Builtin::BI__builtin_abs:
13332 case Builtin::BI__builtin_fabs:
13333 case Builtin::BI__builtin_fabsf:
13334 case Builtin::BI__builtin_fabsl:
13335 case Builtin::BI__builtin_labs:
13336 case Builtin::BI__builtin_llabs:
13337 case Builtin::BI__builtin_cabs:
13338 case Builtin::BI__builtin_cabsf:
13339 case Builtin::BI__builtin_cabsl:
13340 case Builtin::BIabs:
13341 case Builtin::BIlabs:
13342 case Builtin::BIllabs:
13343 case Builtin::BIfabs:
13344 case Builtin::BIfabsf:
13345 case Builtin::BIfabsl:
13346 case Builtin::BIcabs:
13347 case Builtin::BIcabsf:
13348 case Builtin::BIcabsl:
13349 return FDecl->getBuiltinID();
13350 }
13351 llvm_unreachable("Unknown Builtin type");
13352}
13353
13354// If the replacement is valid, emit a note with replacement function.
13355// Additionally, suggest including the proper header if not already included.
13357 unsigned AbsKind, QualType ArgType) {
13358 bool EmitHeaderHint = true;
13359 const char *HeaderName = nullptr;
13360 StringRef FunctionName;
13361 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
13362 FunctionName = "std::abs";
13363 if (ArgType->isIntegralOrEnumerationType()) {
13364 HeaderName = "cstdlib";
13365 } else if (ArgType->isRealFloatingType()) {
13366 HeaderName = "cmath";
13367 } else {
13368 llvm_unreachable("Invalid Type");
13369 }
13370
13371 // Lookup all std::abs
13372 if (NamespaceDecl *Std = S.getStdNamespace()) {
13376
13377 for (const auto *I : R) {
13378 const FunctionDecl *FDecl = nullptr;
13379 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
13380 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
13381 } else {
13382 FDecl = dyn_cast<FunctionDecl>(I);
13383 }
13384 if (!FDecl)
13385 continue;
13386
13387 // Found std::abs(), check that they are the right ones.
13388 if (FDecl->getNumParams() != 1)
13389 continue;
13390
13391 // Check that the parameter type can handle the argument.
13392 QualType ParamType = FDecl->getParamDecl(0)->getType();
13393 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
13394 S.Context.getTypeSize(ArgType) <=
13395 S.Context.getTypeSize(ParamType)) {
13396 // Found a function, don't need the header hint.
13397 EmitHeaderHint = false;
13398 break;
13399 }
13400 }
13401 }
13402 } else {
13403 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
13404 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
13405
13406 if (HeaderName) {
13407 DeclarationName DN(&S.Context.Idents.get(FunctionName));
13410 S.LookupName(R, S.getCurScope());
13411
13412 if (R.isSingleResult()) {
13413 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
13414 if (FD && FD->getBuiltinID() == AbsKind) {
13415 EmitHeaderHint = false;
13416 } else {
13417 return;
13418 }
13419 } else if (!R.empty()) {
13420 return;
13421 }
13422 }
13423 }
13424
13425 S.Diag(Loc, diag::note_replace_abs_function)
13426 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
13427
13428 if (!HeaderName)
13429 return;
13430
13431 if (!EmitHeaderHint)
13432 return;
13433
13434 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
13435 << FunctionName;
13436}
13437
13438template <std::size_t StrLen>
13439static bool IsStdFunction(const FunctionDecl *FDecl,
13440 const char (&Str)[StrLen]) {
13441 if (!FDecl)
13442 return false;
13443 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
13444 return false;
13445 if (!FDecl->isInStdNamespace())
13446 return false;
13447
13448 return true;
13449}
13450
13451void Sema::CheckInfNaNFunction(const CallExpr *Call,
13452 const FunctionDecl *FDecl) {
13453 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
13454 if ((IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
13455 (Call->getBuiltinCallee() == Builtin::BI__builtin_nanf)) &&
13456 FPO.getNoHonorNaNs())
13457 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
13458 << 1 << 0 << Call->getSourceRange();
13459 else if ((IsStdFunction(FDecl, "isinf") ||
13460 (IsStdFunction(FDecl, "isfinite") ||
13461 (FDecl->getIdentifier() && FDecl->getName() == "infinity"))) &&
13462 FPO.getNoHonorInfs())
13463 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
13464 << 0 << 0 << Call->getSourceRange();
13465}
13466
13467// Warn when using the wrong abs() function.
13468void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
13469 const FunctionDecl *FDecl) {
13470 if (Call->getNumArgs() != 1)
13471 return;
13472
13473 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
13474 bool IsStdAbs = IsStdFunction(FDecl, "abs");
13475 if (AbsKind == 0 && !IsStdAbs)
13476 return;
13477
13478 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
13479 QualType ParamType = Call->getArg(0)->getType();
13480
13481 // Unsigned types cannot be negative. Suggest removing the absolute value
13482 // function call.
13483 if (ArgType->isUnsignedIntegerType()) {
13484 StringRef FunctionName =
13485 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
13486 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
13487 Diag(Call->getExprLoc(), diag::note_remove_abs)
13488 << FunctionName
13489 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
13490 return;
13491 }
13492
13493 // Taking the absolute value of a pointer is very suspicious, they probably
13494 // wanted to index into an array, dereference a pointer, call a function, etc.
13495 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
13496 unsigned DiagType = 0;
13497 if (ArgType->isFunctionType())
13498 DiagType = 1;
13499 else if (ArgType->isArrayType())
13500 DiagType = 2;
13501
13502 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
13503 return;
13504 }
13505
13506 // std::abs has overloads which prevent most of the absolute value problems
13507 // from occurring.
13508 if (IsStdAbs)
13509 return;
13510
13511 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
13512 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
13513
13514 // The argument and parameter are the same kind. Check if they are the right
13515 // size.
13516 if (ArgValueKind == ParamValueKind) {
13517 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
13518 return;
13519
13520 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
13521 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
13522 << FDecl << ArgType << ParamType;
13523
13524 if (NewAbsKind == 0)
13525 return;
13526
13527 emitReplacement(*this, Call->getExprLoc(),
13528 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
13529 return;
13530 }
13531
13532 // ArgValueKind != ParamValueKind
13533 // The wrong type of absolute value function was used. Attempt to find the
13534 // proper one.
13535 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
13536 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
13537 if (NewAbsKind == 0)
13538 return;
13539
13540 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
13541 << FDecl << ParamValueKind << ArgValueKind;
13542
13543 emitReplacement(*this, Call->getExprLoc(),
13544 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
13545}
13546
13547//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
13548void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
13549 const FunctionDecl *FDecl) {
13550 if (!Call || !FDecl) return;
13551
13552 // Ignore template specializations and macros.
13553 if (inTemplateInstantiation()) return;
13554 if (Call->getExprLoc().isMacroID()) return;
13555
13556 // Only care about the one template argument, two function parameter std::max
13557 if (Call->getNumArgs() != 2) return;
13558 if (!IsStdFunction(FDecl, "max")) return;
13559 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
13560 if (!ArgList) return;
13561 if (ArgList->size() != 1) return;
13562
13563 // Check that template type argument is unsigned integer.
13564 const auto& TA = ArgList->get(0);
13565 if (TA.getKind() != TemplateArgument::Type) return;
13566 QualType ArgType = TA.getAsType();
13567 if (!ArgType->isUnsignedIntegerType()) return;
13568
13569 // See if either argument is a literal zero.
13570 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
13571 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
13572 if (!MTE) return false;
13573 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
13574 if (!Num) return false;
13575 if (Num->getValue() != 0) return false;
13576 return true;
13577 };
13578
13579 const Expr *FirstArg = Call->getArg(0);
13580 const Expr *SecondArg = Call->getArg(1);
13581 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
13582 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
13583
13584 // Only warn when exactly one argument is zero.
13585 if (IsFirstArgZero == IsSecondArgZero) return;
13586
13587 SourceRange FirstRange = FirstArg->getSourceRange();
13588 SourceRange SecondRange = SecondArg->getSourceRange();
13589
13590 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
13591
13592 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
13593 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
13594
13595 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
13596 SourceRange RemovalRange;
13597 if (IsFirstArgZero) {
13598 RemovalRange = SourceRange(FirstRange.getBegin(),
13599 SecondRange.getBegin().getLocWithOffset(-1));
13600 } else {
13601 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
13602 SecondRange.getEnd());
13603 }
13604
13605 Diag(Call->getExprLoc(), diag::note_remove_max_call)
13606 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
13607 << FixItHint::CreateRemoval(RemovalRange);
13608}
13609
13610//===--- CHECK: Standard memory functions ---------------------------------===//
13611
13612/// Takes the expression passed to the size_t parameter of functions
13613/// such as memcmp, strncat, etc and warns if it's a comparison.
13614///
13615/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
13617 IdentifierInfo *FnName,
13618 SourceLocation FnLoc,
13619 SourceLocation RParenLoc) {
13620 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
13621 if (!Size)
13622 return false;
13623
13624 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
13625 if (!Size->isComparisonOp() && !Size->isLogicalOp())
13626 return false;
13627
13628 SourceRange SizeRange = Size->getSourceRange();
13629 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
13630 << SizeRange << FnName;
13631 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
13632 << FnName
13634 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
13635 << FixItHint::CreateRemoval(RParenLoc);
13636 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
13637 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
13639 ")");
13640
13641 return true;
13642}
13643
13644/// Determine whether the given type is or contains a dynamic class type
13645/// (e.g., whether it has a vtable).
13647 bool &IsContained) {
13648 // Look through array types while ignoring qualifiers.
13649 const Type *Ty = T->getBaseElementTypeUnsafe();
13650 IsContained = false;
13651
13652 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
13653 RD = RD ? RD->getDefinition() : nullptr;
13654 if (!RD || RD->isInvalidDecl())
13655 return nullptr;
13656
13657 if (RD->isDynamicClass())
13658 return RD;
13659
13660 // Check all the fields. If any bases were dynamic, the class is dynamic.
13661 // It's impossible for a class to transitively contain itself by value, so
13662 // infinite recursion is impossible.
13663 for (auto *FD : RD->fields()) {
13664 bool SubContained;
13665 if (const CXXRecordDecl *ContainedRD =
13666 getContainedDynamicClass(FD->getType(), SubContained)) {
13667 IsContained = true;
13668 return ContainedRD;
13669 }
13670 }
13671
13672 return nullptr;
13673}
13674
13676 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
13677 if (Unary->getKind() == UETT_SizeOf)
13678 return Unary;
13679 return nullptr;
13680}
13681
13682/// If E is a sizeof expression, returns its argument expression,
13683/// otherwise returns NULL.
13684static const Expr *getSizeOfExprArg(const Expr *E) {
13686 if (!SizeOf->isArgumentType())
13687 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
13688 return nullptr;
13689}
13690
13691/// If E is a sizeof expression, returns its argument type.
13694 return SizeOf->getTypeOfArgument();
13695 return QualType();
13696}
13697
13698namespace {
13699
13700struct SearchNonTrivialToInitializeField
13701 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
13702 using Super =
13704
13705 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
13706
13707 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
13708 SourceLocation SL) {
13709 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
13710 asDerived().visitArray(PDIK, AT, SL);
13711 return;
13712 }
13713
13714 Super::visitWithKind(PDIK, FT, SL);
13715 }
13716
13717 void visitARCStrong(QualType FT, SourceLocation SL) {
13718 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
13719 }
13720 void visitARCWeak(QualType FT, SourceLocation SL) {
13721 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
13722 }
13723 void visitStruct(QualType FT, SourceLocation SL) {
13724 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
13725 visit(FD->getType(), FD->getLocation());
13726 }
13727 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
13728 const ArrayType *AT, SourceLocation SL) {
13729 visit(getContext().getBaseElementType(AT), SL);
13730 }
13731 void visitTrivial(QualType FT, SourceLocation SL) {}
13732
13733 static void diag(QualType RT, const Expr *E, Sema &S) {
13734 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
13735 }
13736
13737 ASTContext &getContext() { return S.getASTContext(); }
13738
13739 const Expr *E;
13740 Sema &S;
13741};
13742
13743struct SearchNonTrivialToCopyField
13744 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
13746
13747 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
13748
13749 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
13750 SourceLocation SL) {
13751 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
13752 asDerived().visitArray(PCK, AT, SL);
13753 return;
13754 }
13755
13756 Super::visitWithKind(PCK, FT, SL);
13757 }
13758
13759 void visitARCStrong(QualType FT, SourceLocation SL) {
13760 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
13761 }
13762 void visitARCWeak(QualType FT, SourceLocation SL) {
13763 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
13764 }
13765 void visitStruct(QualType FT, SourceLocation SL) {
13766 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
13767 visit(FD->getType(), FD->getLocation());
13768 }
13769 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
13770 SourceLocation SL) {
13771 visit(getContext().getBaseElementType(AT), SL);
13772 }
13773 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
13774 SourceLocation SL) {}
13775 void visitTrivial(QualType FT, SourceLocation SL) {}
13776 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
13777
13778 static void diag(QualType RT, const Expr *E, Sema &S) {
13779 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
13780 }
13781
13782 ASTContext &getContext() { return S.getASTContext(); }
13783
13784 const Expr *E;
13785 Sema &S;
13786};
13787
13788}
13789
13790/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
13791static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
13792 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
13793
13794 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
13795 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
13796 return false;
13797
13798 return doesExprLikelyComputeSize(BO->getLHS()) ||
13799 doesExprLikelyComputeSize(BO->getRHS());
13800 }
13801
13802 return getAsSizeOfExpr(SizeofExpr) != nullptr;
13803}
13804
13805/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
13806///
13807/// \code
13808/// #define MACRO 0
13809/// foo(MACRO);
13810/// foo(0);
13811/// \endcode
13812///
13813/// This should return true for the first call to foo, but not for the second
13814/// (regardless of whether foo is a macro or function).
13816 SourceLocation CallLoc,
13817 SourceLocation ArgLoc) {
13818 if (!CallLoc.isMacroID())
13819 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
13820
13821 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
13822 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
13823}
13824
13825/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
13826/// last two arguments transposed.
13827static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
13828 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
13829 return;
13830
13831 const Expr *SizeArg =
13832 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
13833
13834 auto isLiteralZero = [](const Expr *E) {
13835 return (isa<IntegerLiteral>(E) &&
13836 cast<IntegerLiteral>(E)->getValue() == 0) ||
13837 (isa<CharacterLiteral>(E) &&
13838 cast<CharacterLiteral>(E)->getValue() == 0);
13839 };
13840
13841 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
13842 SourceLocation CallLoc = Call->getRParenLoc();
13844 if (isLiteralZero(SizeArg) &&
13845 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
13846
13847 SourceLocation DiagLoc = SizeArg->getExprLoc();
13848
13849 // Some platforms #define bzero to __builtin_memset. See if this is the
13850 // case, and if so, emit a better diagnostic.
13851 if (BId == Builtin::BIbzero ||
13853 CallLoc, SM, S.getLangOpts()) == "bzero")) {
13854 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
13855 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
13856 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
13857 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
13858 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
13859 }
13860 return;
13861 }
13862
13863 // If the second argument to a memset is a sizeof expression and the third
13864 // isn't, this is also likely an error. This should catch
13865 // 'memset(buf, sizeof(buf), 0xff)'.
13866 if (BId == Builtin::BImemset &&
13867 doesExprLikelyComputeSize(Call->getArg(1)) &&
13868 !doesExprLikelyComputeSize(Call->getArg(2))) {
13869 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
13870 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
13871 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
13872 return;
13873 }
13874}
13875
13876/// Check for dangerous or invalid arguments to memset().
13877///
13878/// This issues warnings on known problematic, dangerous or unspecified
13879/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
13880/// function calls.
13881///
13882/// \param Call The call expression to diagnose.
13883void Sema::CheckMemaccessArguments(const CallExpr *Call,
13884 unsigned BId,
13885 IdentifierInfo *FnName) {
13886 assert(BId != 0);
13887
13888 // It is possible to have a non-standard definition of memset. Validate
13889 // we have enough arguments, and if not, abort further checking.
13890 unsigned ExpectedNumArgs =
13891 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
13892 if (Call->getNumArgs() < ExpectedNumArgs)
13893 return;
13894
13895 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
13896 BId == Builtin::BIstrndup ? 1 : 2);
13897 unsigned LenArg =
13898 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
13899 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
13900
13901 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
13902 Call->getBeginLoc(), Call->getRParenLoc()))
13903 return;
13904
13905 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
13906 CheckMemaccessSize(*this, BId, Call);
13907
13908 // We have special checking when the length is a sizeof expression.
13909 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
13910 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
13911 llvm::FoldingSetNodeID SizeOfArgID;
13912
13913 // Although widely used, 'bzero' is not a standard function. Be more strict
13914 // with the argument types before allowing diagnostics and only allow the
13915 // form bzero(ptr, sizeof(...)).
13916 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
13917 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
13918 return;
13919
13920 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
13921 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
13922 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
13923
13924 QualType DestTy = Dest->getType();
13925 QualType PointeeTy;
13926 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
13927 PointeeTy = DestPtrTy->getPointeeType();
13928
13929 // Never warn about void type pointers. This can be used to suppress
13930 // false positives.
13931 if (PointeeTy->isVoidType())
13932 continue;
13933
13934 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
13935 // actually comparing the expressions for equality. Because computing the
13936 // expression IDs can be expensive, we only do this if the diagnostic is
13937 // enabled.
13938 if (SizeOfArg &&
13939 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
13940 SizeOfArg->getExprLoc())) {
13941 // We only compute IDs for expressions if the warning is enabled, and
13942 // cache the sizeof arg's ID.
13943 if (SizeOfArgID == llvm::FoldingSetNodeID())
13944 SizeOfArg->Profile(SizeOfArgID, Context, true);
13945 llvm::FoldingSetNodeID DestID;
13946 Dest->Profile(DestID, Context, true);
13947 if (DestID == SizeOfArgID) {
13948 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
13949 // over sizeof(src) as well.
13950 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
13951 StringRef ReadableName = FnName->getName();
13952
13953 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
13954 if (UnaryOp->getOpcode() == UO_AddrOf)
13955 ActionIdx = 1; // If its an address-of operator, just remove it.
13956 if (!PointeeTy->isIncompleteType() &&
13957 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
13958 ActionIdx = 2; // If the pointee's size is sizeof(char),
13959 // suggest an explicit length.
13960
13961 // If the function is defined as a builtin macro, do not show macro
13962 // expansion.
13963 SourceLocation SL = SizeOfArg->getExprLoc();
13964 SourceRange DSR = Dest->getSourceRange();
13965 SourceRange SSR = SizeOfArg->getSourceRange();
13967
13968 if (SM.isMacroArgExpansion(SL)) {
13969 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
13970 SL = SM.getSpellingLoc(SL);
13971 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
13972 SM.getSpellingLoc(DSR.getEnd()));
13973 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
13974 SM.getSpellingLoc(SSR.getEnd()));
13975 }
13976
13977 DiagRuntimeBehavior(SL, SizeOfArg,
13978 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
13979 << ReadableName
13980 << PointeeTy
13981 << DestTy
13982 << DSR
13983 << SSR);
13984 DiagRuntimeBehavior(SL, SizeOfArg,
13985 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
13986 << ActionIdx
13987 << SSR);
13988
13989 break;
13990 }
13991 }
13992
13993 // Also check for cases where the sizeof argument is the exact same
13994 // type as the memory argument, and where it points to a user-defined
13995 // record type.
13996 if (SizeOfArgTy != QualType()) {
13997 if (PointeeTy->isRecordType() &&
13998 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
13999 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
14000 PDiag(diag::warn_sizeof_pointer_type_memaccess)
14001 << FnName << SizeOfArgTy << ArgIdx
14002 << PointeeTy << Dest->getSourceRange()
14003 << LenExpr->getSourceRange());
14004 break;
14005 }
14006 }
14007 } else if (DestTy->isArrayType()) {
14008 PointeeTy = DestTy;
14009 }
14010
14011 if (PointeeTy == QualType())
14012 continue;
14013
14014 // Always complain about dynamic classes.
14015 bool IsContained;
14016 if (const CXXRecordDecl *ContainedRD =
14017 getContainedDynamicClass(PointeeTy, IsContained)) {
14018
14019 unsigned OperationType = 0;
14020 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
14021 // "overwritten" if we're warning about the destination for any call
14022 // but memcmp; otherwise a verb appropriate to the call.
14023 if (ArgIdx != 0 || IsCmp) {
14024 if (BId == Builtin::BImemcpy)
14025 OperationType = 1;
14026 else if(BId == Builtin::BImemmove)
14027 OperationType = 2;
14028 else if (IsCmp)
14029 OperationType = 3;
14030 }
14031
14032 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
14033 PDiag(diag::warn_dyn_class_memaccess)
14034 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
14035 << IsContained << ContainedRD << OperationType
14036 << Call->getCallee()->getSourceRange());
14037 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
14038 BId != Builtin::BImemset)
14040 Dest->getExprLoc(), Dest,
14041 PDiag(diag::warn_arc_object_memaccess)
14042 << ArgIdx << FnName << PointeeTy
14043 << Call->getCallee()->getSourceRange());
14044 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
14045 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
14046 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
14047 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
14048 PDiag(diag::warn_cstruct_memaccess)
14049 << ArgIdx << FnName << PointeeTy << 0);
14050 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
14051 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
14052 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
14053 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
14054 PDiag(diag::warn_cstruct_memaccess)
14055 << ArgIdx << FnName << PointeeTy << 1);
14056 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
14057 } else {
14058 continue;
14059 }
14060 } else
14061 continue;
14062
14064 Dest->getExprLoc(), Dest,
14065 PDiag(diag::note_bad_memaccess_silence)
14066 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
14067 break;
14068 }
14069}
14070
14071// A little helper routine: ignore addition and subtraction of integer literals.
14072// This intentionally does not ignore all integer constant expressions because
14073// we don't want to remove sizeof().
14074static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
14075 Ex = Ex->IgnoreParenCasts();
14076
14077 while (true) {
14078 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
14079 if (!BO || !BO->isAdditiveOp())
14080 break;
14081
14082 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
14083 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
14084
14085 if (isa<IntegerLiteral>(RHS))
14086 Ex = LHS;
14087 else if (isa<IntegerLiteral>(LHS))
14088 Ex = RHS;
14089 else
14090 break;
14091 }
14092
14093 return Ex;
14094}
14095
14097 ASTContext &Context) {
14098 // Only handle constant-sized or VLAs, but not flexible members.
14099 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
14100 // Only issue the FIXIT for arrays of size > 1.
14101 if (CAT->getZExtSize() <= 1)
14102 return false;
14103 } else if (!Ty->isVariableArrayType()) {
14104 return false;
14105 }
14106 return true;
14107}
14108
14109// Warn if the user has made the 'size' argument to strlcpy or strlcat
14110// be the size of the source, instead of the destination.
14111void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
14112 IdentifierInfo *FnName) {
14113
14114 // Don't crash if the user has the wrong number of arguments
14115 unsigned NumArgs = Call->getNumArgs();
14116 if ((NumArgs != 3) && (NumArgs != 4))
14117 return;
14118
14119 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
14120 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
14121 const Expr *CompareWithSrc = nullptr;
14122
14123 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
14124 Call->getBeginLoc(), Call->getRParenLoc()))
14125 return;
14126
14127 // Look for 'strlcpy(dst, x, sizeof(x))'
14128 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
14129 CompareWithSrc = Ex;
14130 else {
14131 // Look for 'strlcpy(dst, x, strlen(x))'
14132 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
14133 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
14134 SizeCall->getNumArgs() == 1)
14135 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
14136 }
14137 }
14138
14139 if (!CompareWithSrc)
14140 return;
14141
14142 // Determine if the argument to sizeof/strlen is equal to the source
14143 // argument. In principle there's all kinds of things you could do
14144 // here, for instance creating an == expression and evaluating it with
14145 // EvaluateAsBooleanCondition, but this uses a more direct technique:
14146 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
14147 if (!SrcArgDRE)
14148 return;
14149
14150 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
14151 if (!CompareWithSrcDRE ||
14152 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
14153 return;
14154
14155 const Expr *OriginalSizeArg = Call->getArg(2);
14156 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
14157 << OriginalSizeArg->getSourceRange() << FnName;
14158
14159 // Output a FIXIT hint if the destination is an array (rather than a
14160 // pointer to an array). This could be enhanced to handle some
14161 // pointers if we know the actual size, like if DstArg is 'array+2'
14162 // we could say 'sizeof(array)-2'.
14163 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
14165 return;
14166
14167 SmallString<128> sizeString;
14168 llvm::raw_svector_ostream OS(sizeString);
14169 OS << "sizeof(";
14170 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
14171 OS << ")";
14172
14173 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
14174 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
14175 OS.str());
14176}
14177
14178/// Check if two expressions refer to the same declaration.
14179static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
14180 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
14181 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
14182 return D1->getDecl() == D2->getDecl();
14183 return false;
14184}
14185
14186static const Expr *getStrlenExprArg(const Expr *E) {
14187 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
14188 const FunctionDecl *FD = CE->getDirectCallee();
14189 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
14190 return nullptr;
14191 return CE->getArg(0)->IgnoreParenCasts();
14192 }
14193 return nullptr;
14194}
14195
14196// Warn on anti-patterns as the 'size' argument to strncat.
14197// The correct size argument should look like following:
14198// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
14199void Sema::CheckStrncatArguments(const CallExpr *CE,
14200 IdentifierInfo *FnName) {
14201 // Don't crash if the user has the wrong number of arguments.
14202 if (CE->getNumArgs() < 3)
14203 return;
14204 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
14205 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
14206 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
14207
14208 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
14209 CE->getRParenLoc()))
14210 return;
14211
14212 // Identify common expressions, which are wrongly used as the size argument
14213 // to strncat and may lead to buffer overflows.
14214 unsigned PatternType = 0;
14215 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
14216 // - sizeof(dst)
14217 if (referToTheSameDecl(SizeOfArg, DstArg))
14218 PatternType = 1;
14219 // - sizeof(src)
14220 else if (referToTheSameDecl(SizeOfArg, SrcArg))
14221 PatternType = 2;
14222 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
14223 if (BE->getOpcode() == BO_Sub) {
14224 const Expr *L = BE->getLHS()->IgnoreParenCasts();
14225 const Expr *R = BE->getRHS()->IgnoreParenCasts();
14226 // - sizeof(dst) - strlen(dst)
14227 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
14229 PatternType = 1;
14230 // - sizeof(src) - (anything)
14231 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
14232 PatternType = 2;
14233 }
14234 }
14235
14236 if (PatternType == 0)
14237 return;
14238
14239 // Generate the diagnostic.
14240 SourceLocation SL = LenArg->getBeginLoc();
14241 SourceRange SR = LenArg->getSourceRange();
14243
14244 // If the function is defined as a builtin macro, do not show macro expansion.
14245 if (SM.isMacroArgExpansion(SL)) {
14246 SL = SM.getSpellingLoc(SL);
14247 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
14248 SM.getSpellingLoc(SR.getEnd()));
14249 }
14250
14251 // Check if the destination is an array (rather than a pointer to an array).
14252 QualType DstTy = DstArg->getType();
14253 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
14254 Context);
14255 if (!isKnownSizeArray) {
14256 if (PatternType == 1)
14257 Diag(SL, diag::warn_strncat_wrong_size) << SR;
14258 else
14259 Diag(SL, diag::warn_strncat_src_size) << SR;
14260 return;
14261 }
14262
14263 if (PatternType == 1)
14264 Diag(SL, diag::warn_strncat_large_size) << SR;
14265 else
14266 Diag(SL, diag::warn_strncat_src_size) << SR;
14267
14268 SmallString<128> sizeString;
14269 llvm::raw_svector_ostream OS(sizeString);
14270 OS << "sizeof(";
14271 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
14272 OS << ") - ";
14273 OS << "strlen(";
14274 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
14275 OS << ") - 1";
14276
14277 Diag(SL, diag::note_strncat_wrong_size)
14278 << FixItHint::CreateReplacement(SR, OS.str());
14279}
14280
14281namespace {
14282void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
14283 const UnaryOperator *UnaryExpr, const Decl *D) {
14284 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
14285 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
14286 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
14287 return;
14288 }
14289}
14290
14291void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
14292 const UnaryOperator *UnaryExpr) {
14293 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
14294 const Decl *D = Lvalue->getDecl();
14295 if (isa<DeclaratorDecl>(D))
14296 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
14297 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
14298 }
14299
14300 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
14301 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
14302 Lvalue->getMemberDecl());
14303}
14304
14305void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
14306 const UnaryOperator *UnaryExpr) {
14307 const auto *Lambda = dyn_cast<LambdaExpr>(
14309 if (!Lambda)
14310 return;
14311
14312 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
14313 << CalleeName << 2 /*object: lambda expression*/;
14314}
14315
14316void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
14317 const DeclRefExpr *Lvalue) {
14318 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
14319 if (Var == nullptr)
14320 return;
14321
14322 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
14323 << CalleeName << 0 /*object: */ << Var;
14324}
14325
14326void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
14327 const CastExpr *Cast) {
14328 SmallString<128> SizeString;
14329 llvm::raw_svector_ostream OS(SizeString);
14330
14331 clang::CastKind Kind = Cast->getCastKind();
14332 if (Kind == clang::CK_BitCast &&
14333 !Cast->getSubExpr()->getType()->isFunctionPointerType())
14334 return;
14335 if (Kind == clang::CK_IntegralToPointer &&
14336 !isa<IntegerLiteral>(
14337 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
14338 return;
14339
14340 switch (Cast->getCastKind()) {
14341 case clang::CK_BitCast:
14342 case clang::CK_IntegralToPointer:
14343 case clang::CK_FunctionToPointerDecay:
14344 OS << '\'';
14345 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
14346 OS << '\'';
14347 break;
14348 default:
14349 return;
14350 }
14351
14352 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
14353 << CalleeName << 0 /*object: */ << OS.str();
14354}
14355} // namespace
14356
14357/// Alerts the user that they are attempting to free a non-malloc'd object.
14358void Sema::CheckFreeArguments(const CallExpr *E) {
14359 const std::string CalleeName =
14360 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
14361
14362 { // Prefer something that doesn't involve a cast to make things simpler.
14363 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
14364 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
14365 switch (UnaryExpr->getOpcode()) {
14366 case UnaryOperator::Opcode::UO_AddrOf:
14367 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
14368 case UnaryOperator::Opcode::UO_Plus:
14369 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
14370 default:
14371 break;
14372 }
14373
14374 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
14375 if (Lvalue->getType()->isArrayType())
14376 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
14377
14378 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
14379 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
14380 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
14381 return;
14382 }
14383
14384 if (isa<BlockExpr>(Arg)) {
14385 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
14386 << CalleeName << 1 /*object: block*/;
14387 return;
14388 }
14389 }
14390 // Maybe the cast was important, check after the other cases.
14391 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
14392 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
14393}
14394
14395void
14396Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
14397 SourceLocation ReturnLoc,
14398 bool isObjCMethod,
14399 const AttrVec *Attrs,
14400 const FunctionDecl *FD) {
14401 // Check if the return value is null but should not be.
14402 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
14403 (!isObjCMethod && isNonNullType(lhsType))) &&
14404 CheckNonNullExpr(*this, RetValExp))
14405 Diag(ReturnLoc, diag::warn_null_ret)
14406 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
14407
14408 // C++11 [basic.stc.dynamic.allocation]p4:
14409 // If an allocation function declared with a non-throwing
14410 // exception-specification fails to allocate storage, it shall return
14411 // a null pointer. Any other allocation function that fails to allocate
14412 // storage shall indicate failure only by throwing an exception [...]
14413 if (FD) {
14415 if (Op == OO_New || Op == OO_Array_New) {
14416 const FunctionProtoType *Proto
14417 = FD->getType()->castAs<FunctionProtoType>();
14418 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
14419 CheckNonNullExpr(*this, RetValExp))
14420 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
14421 << FD << getLangOpts().CPlusPlus11;
14422 }
14423 }
14424
14425 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
14426 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
14427 }
14428
14429 // PPC MMA non-pointer types are not allowed as return type. Checking the type
14430 // here prevent the user from using a PPC MMA type as trailing return type.
14431 if (Context.getTargetInfo().getTriple().isPPC64())
14432 CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
14433}
14434
14435/// Check for comparisons of floating-point values using == and !=. Issue a
14436/// warning if the comparison is not likely to do what the programmer intended.
14438 BinaryOperatorKind Opcode) {
14439 if (!BinaryOperator::isEqualityOp(Opcode))
14440 return;
14441
14442 // Match and capture subexpressions such as "(float) X == 0.1".
14443 FloatingLiteral *FPLiteral;
14444 CastExpr *FPCast;
14445 auto getCastAndLiteral = [&FPLiteral, &FPCast](Expr *L, Expr *R) {
14446 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
14447 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
14448 return FPLiteral && FPCast;
14449 };
14450
14451 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
14452 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
14453 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
14454 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
14455 TargetTy->isFloatingPoint()) {
14456 bool Lossy;
14457 llvm::APFloat TargetC = FPLiteral->getValue();
14458 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
14459 llvm::APFloat::rmNearestTiesToEven, &Lossy);
14460 if (Lossy) {
14461 // If the literal cannot be represented in the source type, then a
14462 // check for == is always false and check for != is always true.
14463 Diag(Loc, diag::warn_float_compare_literal)
14464 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
14465 << LHS->getSourceRange() << RHS->getSourceRange();
14466 return;
14467 }
14468 }
14469 }
14470
14471 // Match a more general floating-point equality comparison (-Wfloat-equal).
14472 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
14473 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
14474
14475 // Special case: check for x == x (which is OK).
14476 // Do not emit warnings for such cases.
14477 if (auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
14478 if (auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
14479 if (DRL->getDecl() == DRR->getDecl())
14480 return;
14481
14482 // Special case: check for comparisons against literals that can be exactly
14483 // represented by APFloat. In such cases, do not emit a warning. This
14484 // is a heuristic: often comparison against such literals are used to
14485 // detect if a value in a variable has not changed. This clearly can
14486 // lead to false negatives.
14487 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
14488 if (FLL->isExact())
14489 return;
14490 } else
14491 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
14492 if (FLR->isExact())
14493 return;
14494
14495 // Check for comparisons with builtin types.
14496 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
14497 if (CL->getBuiltinCallee())
14498 return;
14499
14500 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
14501 if (CR->getBuiltinCallee())
14502 return;
14503
14504 // Emit the diagnostic.
14505 Diag(Loc, diag::warn_floatingpoint_eq)
14506 << LHS->getSourceRange() << RHS->getSourceRange();
14507}
14508
14509//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
14510//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
14511
14512namespace {
14513
14514/// Structure recording the 'active' range of an integer-valued
14515/// expression.
14516struct IntRange {
14517 /// The number of bits active in the int. Note that this includes exactly one
14518 /// sign bit if !NonNegative.
14519 unsigned Width;
14520
14521 /// True if the int is known not to have negative values. If so, all leading
14522 /// bits before Width are known zero, otherwise they are known to be the
14523 /// same as the MSB within Width.
14524 bool NonNegative;
14525
14526 IntRange(unsigned Width, bool NonNegative)
14527 : Width(Width), NonNegative(NonNegative) {}
14528
14529 /// Number of bits excluding the sign bit.
14530 unsigned valueBits() const {
14531 return NonNegative ? Width : Width - 1;
14532 }
14533
14534 /// Returns the range of the bool type.
14535 static IntRange forBoolType() {
14536 return IntRange(1, true);
14537 }
14538
14539 /// Returns the range of an opaque value of the given integral type.
14540 static IntRange forValueOfType(ASTContext &C, QualType T) {
14541 return forValueOfCanonicalType(C,
14543 }
14544
14545 /// Returns the range of an opaque value of a canonical integral type.
14546 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
14547 assert(T->isCanonicalUnqualified());
14548
14549 if (const VectorType *VT = dyn_cast<VectorType>(T))
14550 T = VT->getElementType().getTypePtr();
14551 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
14552 T = CT->getElementType().getTypePtr();
14553 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
14554 T = AT->getValueType().getTypePtr();
14555
14556 if (!C.getLangOpts().CPlusPlus) {
14557 // For enum types in C code, use the underlying datatype.
14558 if (const EnumType *ET = dyn_cast<EnumType>(T))
14559 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
14560 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
14561 // For enum types in C++, use the known bit width of the enumerators.
14562 EnumDecl *Enum = ET->getDecl();
14563 // In C++11, enums can have a fixed underlying type. Use this type to
14564 // compute the range.
14565 if (Enum->isFixed()) {
14566 return IntRange(C.getIntWidth(QualType(T, 0)),
14567 !ET->isSignedIntegerOrEnumerationType());
14568 }
14569
14570 unsigned NumPositive = Enum->getNumPositiveBits();
14571 unsigned NumNegative = Enum->getNumNegativeBits();
14572
14573 if (NumNegative == 0)
14574 return IntRange(NumPositive, true/*NonNegative*/);
14575 else
14576 return IntRange(std::max(NumPositive + 1, NumNegative),
14577 false/*NonNegative*/);
14578 }
14579
14580 if (const auto *EIT = dyn_cast<BitIntType>(T))
14581 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
14582
14583 const BuiltinType *BT = cast<BuiltinType>(T);
14584 assert(BT->isInteger());
14585
14586 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
14587 }
14588
14589 /// Returns the "target" range of a canonical integral type, i.e.
14590 /// the range of values expressible in the type.
14591 ///
14592 /// This matches forValueOfCanonicalType except that enums have the
14593 /// full range of their type, not the range of their enumerators.
14594 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
14595 assert(T->isCanonicalUnqualified());
14596
14597 if (const VectorType *VT = dyn_cast<VectorType>(T))
14598 T = VT->getElementType().getTypePtr();
14599 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
14600 T = CT->getElementType().getTypePtr();
14601 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
14602 T = AT->getValueType().getTypePtr();
14603 if (const EnumType *ET = dyn_cast<EnumType>(T))
14604 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
14605
14606 if (const auto *EIT = dyn_cast<BitIntType>(T))
14607 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
14608
14609 const BuiltinType *BT = cast<BuiltinType>(T);
14610 assert(BT->isInteger());
14611
14612 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
14613 }
14614
14615 /// Returns the supremum of two ranges: i.e. their conservative merge.
14616 static IntRange join(IntRange L, IntRange R) {
14617 bool Unsigned = L.NonNegative && R.NonNegative;
14618 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
14619 L.NonNegative && R.NonNegative);
14620 }
14621
14622 /// Return the range of a bitwise-AND of the two ranges.
14623 static IntRange bit_and(IntRange L, IntRange R) {
14624 unsigned Bits = std::max(L.Width, R.Width);
14625 bool NonNegative = false;
14626 if (L.NonNegative) {
14627 Bits = std::min(Bits, L.Width);
14628 NonNegative = true;
14629 }
14630 if (R.NonNegative) {
14631 Bits = std::min(Bits, R.Width);
14632 NonNegative = true;
14633 }
14634 return IntRange(Bits, NonNegative);
14635 }
14636
14637 /// Return the range of a sum of the two ranges.
14638 static IntRange sum(IntRange L, IntRange R) {
14639 bool Unsigned = L.NonNegative && R.NonNegative;
14640 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
14641 Unsigned);
14642 }
14643
14644 /// Return the range of a difference of the two ranges.
14645 static IntRange difference(IntRange L, IntRange R) {
14646 // We need a 1-bit-wider range if:
14647 // 1) LHS can be negative: least value can be reduced.
14648 // 2) RHS can be negative: greatest value can be increased.
14649 bool CanWiden = !L.NonNegative || !R.NonNegative;
14650 bool Unsigned = L.NonNegative && R.Width == 0;
14651 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
14652 !Unsigned,
14653 Unsigned);
14654 }
14655
14656 /// Return the range of a product of the two ranges.
14657 static IntRange product(IntRange L, IntRange R) {
14658 // If both LHS and RHS can be negative, we can form
14659 // -2^L * -2^R = 2^(L + R)
14660 // which requires L + R + 1 value bits to represent.
14661 bool CanWiden = !L.NonNegative && !R.NonNegative;
14662 bool Unsigned = L.NonNegative && R.NonNegative;
14663 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
14664 Unsigned);
14665 }
14666
14667 /// Return the range of a remainder operation between the two ranges.
14668 static IntRange rem(IntRange L, IntRange R) {
14669 // The result of a remainder can't be larger than the result of
14670 // either side. The sign of the result is the sign of the LHS.
14671 bool Unsigned = L.NonNegative;
14672 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
14673 Unsigned);
14674 }
14675};
14676
14677} // namespace
14678
14679static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
14680 unsigned MaxWidth) {
14681 if (value.isSigned() && value.isNegative())
14682 return IntRange(value.getSignificantBits(), false);
14683
14684 if (value.getBitWidth() > MaxWidth)
14685 value = value.trunc(MaxWidth);
14686
14687 // isNonNegative() just checks the sign bit without considering
14688 // signedness.
14689 return IntRange(value.getActiveBits(), true);
14690}
14691
14692static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
14693 unsigned MaxWidth) {
14694 if (result.isInt())
14695 return GetValueRange(C, result.getInt(), MaxWidth);
14696
14697 if (result.isVector()) {
14698 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
14699 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
14700 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
14701 R = IntRange::join(R, El);
14702 }
14703 return R;
14704 }
14705
14706 if (result.isComplexInt()) {
14707 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
14708 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
14709 return IntRange::join(R, I);
14710 }
14711
14712 // This can happen with lossless casts to intptr_t of "based" lvalues.
14713 // Assume it might use arbitrary bits.
14714 // FIXME: The only reason we need to pass the type in here is to get
14715 // the sign right on this one case. It would be nice if APValue
14716 // preserved this.
14717 assert(result.isLValue() || result.isAddrLabelDiff());
14718 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
14719}
14720
14721static QualType GetExprType(const Expr *E) {
14722 QualType Ty = E->getType();
14723 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
14724 Ty = AtomicRHS->getValueType();
14725 return Ty;
14726}
14727
14728/// Pseudo-evaluate the given integer expression, estimating the
14729/// range of values it might take.
14730///
14731/// \param MaxWidth The width to which the value will be truncated.
14732/// \param Approximate If \c true, return a likely range for the result: in
14733/// particular, assume that arithmetic on narrower types doesn't leave
14734/// those types. If \c false, return a range including all possible
14735/// result values.
14736static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
14737 bool InConstantContext, bool Approximate) {
14738 E = E->IgnoreParens();
14739
14740 // Try a full evaluation first.
14741 Expr::EvalResult result;
14742 if (E->EvaluateAsRValue(result, C, InConstantContext))
14743 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
14744
14745 // I think we only want to look through implicit casts here; if the
14746 // user has an explicit widening cast, we should treat the value as
14747 // being of the new, wider type.
14748 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
14749 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
14750 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
14751 Approximate);
14752
14753 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
14754
14755 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
14756 CE->getCastKind() == CK_BooleanToSignedIntegral;
14757
14758 // Assume that non-integer casts can span the full range of the type.
14759 if (!isIntegerCast)
14760 return OutputTypeRange;
14761
14762 IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
14763 std::min(MaxWidth, OutputTypeRange.Width),
14764 InConstantContext, Approximate);
14765
14766 // Bail out if the subexpr's range is as wide as the cast type.
14767 if (SubRange.Width >= OutputTypeRange.Width)
14768 return OutputTypeRange;
14769
14770 // Otherwise, we take the smaller width, and we're non-negative if
14771 // either the output type or the subexpr is.
14772 return IntRange(SubRange.Width,
14773 SubRange.NonNegative || OutputTypeRange.NonNegative);
14774 }
14775
14776 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
14777 // If we can fold the condition, just take that operand.
14778 bool CondResult;
14779 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
14780 return GetExprRange(C,
14781 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
14782 MaxWidth, InConstantContext, Approximate);
14783
14784 // Otherwise, conservatively merge.
14785 // GetExprRange requires an integer expression, but a throw expression
14786 // results in a void type.
14787 Expr *E = CO->getTrueExpr();
14788 IntRange L = E->getType()->isVoidType()
14789 ? IntRange{0, true}
14790 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
14791 E = CO->getFalseExpr();
14792 IntRange R = E->getType()->isVoidType()
14793 ? IntRange{0, true}
14794 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
14795 return IntRange::join(L, R);
14796 }
14797
14798 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
14799 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
14800
14801 switch (BO->getOpcode()) {
14802 case BO_Cmp:
14803 llvm_unreachable("builtin <=> should have class type");
14804
14805 // Boolean-valued operations are single-bit and positive.
14806 case BO_LAnd:
14807 case BO_LOr:
14808 case BO_LT:
14809 case BO_GT:
14810 case BO_LE:
14811 case BO_GE:
14812 case BO_EQ:
14813 case BO_NE:
14814 return IntRange::forBoolType();
14815
14816 // The type of the assignments is the type of the LHS, so the RHS
14817 // is not necessarily the same type.
14818 case BO_MulAssign:
14819 case BO_DivAssign:
14820 case BO_RemAssign:
14821 case BO_AddAssign:
14822 case BO_SubAssign:
14823 case BO_XorAssign:
14824 case BO_OrAssign:
14825 // TODO: bitfields?
14826 return IntRange::forValueOfType(C, GetExprType(E));
14827
14828 // Simple assignments just pass through the RHS, which will have
14829 // been coerced to the LHS type.
14830 case BO_Assign:
14831 // TODO: bitfields?
14832 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
14833 Approximate);
14834
14835 // Operations with opaque sources are black-listed.
14836 case BO_PtrMemD:
14837 case BO_PtrMemI:
14838 return IntRange::forValueOfType(C, GetExprType(E));
14839
14840 // Bitwise-and uses the *infinum* of the two source ranges.
14841 case BO_And:
14842 case BO_AndAssign:
14843 Combine = IntRange::bit_and;
14844 break;
14845
14846 // Left shift gets black-listed based on a judgement call.
14847 case BO_Shl:
14848 // ...except that we want to treat '1 << (blah)' as logically
14849 // positive. It's an important idiom.
14850 if (IntegerLiteral *I
14851 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
14852 if (I->getValue() == 1) {
14853 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
14854 return IntRange(R.Width, /*NonNegative*/ true);
14855 }
14856 }
14857 [[fallthrough]];
14858
14859 case BO_ShlAssign:
14860 return IntRange::forValueOfType(C, GetExprType(E));
14861
14862 // Right shift by a constant can narrow its left argument.
14863 case BO_Shr:
14864 case BO_ShrAssign: {
14865 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
14866 Approximate);
14867
14868 // If the shift amount is a positive constant, drop the width by
14869 // that much.
14870 if (std::optional<llvm::APSInt> shift =
14871 BO->getRHS()->getIntegerConstantExpr(C)) {
14872 if (shift->isNonNegative()) {
14873 if (shift->uge(L.Width))
14874 L.Width = (L.NonNegative ? 0 : 1);
14875 else
14876 L.Width -= shift->getZExtValue();
14877 }
14878 }
14879
14880 return L;
14881 }
14882
14883 // Comma acts as its right operand.
14884 case BO_Comma:
14885 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
14886 Approximate);
14887
14888 case BO_Add:
14889 if (!Approximate)
14890 Combine = IntRange::sum;
14891 break;
14892
14893 case BO_Sub:
14894 if (BO->getLHS()->getType()->isPointerType())
14895 return IntRange::forValueOfType(C, GetExprType(E));
14896 if (!Approximate)
14897 Combine = IntRange::difference;
14898 break;
14899
14900 case BO_Mul:
14901 if (!Approximate)
14902 Combine = IntRange::product;
14903 break;
14904
14905 // The width of a division result is mostly determined by the size
14906 // of the LHS.
14907 case BO_Div: {
14908 // Don't 'pre-truncate' the operands.
14909 unsigned opWidth = C.getIntWidth(GetExprType(E));
14910 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
14911 Approximate);
14912
14913 // If the divisor is constant, use that.
14914 if (std::optional<llvm::APSInt> divisor =
14915 BO->getRHS()->getIntegerConstantExpr(C)) {
14916 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
14917 if (log2 >= L.Width)
14918 L.Width = (L.NonNegative ? 0 : 1);
14919 else
14920 L.Width = std::min(L.Width - log2, MaxWidth);
14921 return L;
14922 }
14923
14924 // Otherwise, just use the LHS's width.
14925 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
14926 // could be -1.
14927 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
14928 Approximate);
14929 return IntRange(L.Width, L.NonNegative && R.NonNegative);
14930 }
14931
14932 case BO_Rem:
14933 Combine = IntRange::rem;
14934 break;
14935
14936 // The default behavior is okay for these.
14937 case BO_Xor:
14938 case BO_Or:
14939 break;
14940 }
14941
14942 // Combine the two ranges, but limit the result to the type in which we
14943 // performed the computation.
14944 QualType T = GetExprType(E);
14945 unsigned opWidth = C.getIntWidth(T);
14946 IntRange L =
14947 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
14948 IntRange R =
14949 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
14950 IntRange C = Combine(L, R);
14951 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
14952 C.Width = std::min(C.Width, MaxWidth);
14953 return C;
14954 }
14955
14956 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
14957 switch (UO->getOpcode()) {
14958 // Boolean-valued operations are white-listed.
14959 case UO_LNot:
14960 return IntRange::forBoolType();
14961
14962 // Operations with opaque sources are black-listed.
14963 case UO_Deref:
14964 case UO_AddrOf: // should be impossible
14965 return IntRange::forValueOfType(C, GetExprType(E));
14966
14967 default:
14968 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
14969 Approximate);
14970 }
14971 }
14972
14973 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
14974 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
14975 Approximate);
14976
14977 if (const auto *BitField = E->getSourceBitField())
14978 return IntRange(BitField->getBitWidthValue(C),
14979 BitField->getType()->isUnsignedIntegerOrEnumerationType());
14980
14981 return IntRange::forValueOfType(C, GetExprType(E));
14982}
14983
14984static IntRange GetExprRange(ASTContext &C, const Expr *E,
14985 bool InConstantContext, bool Approximate) {
14986 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
14987 Approximate);
14988}
14989
14990/// Checks whether the given value, which currently has the given
14991/// source semantics, has the same value when coerced through the
14992/// target semantics.
14993static bool IsSameFloatAfterCast(const llvm::APFloat &value,
14994 const llvm::fltSemantics &Src,
14995 const llvm::fltSemantics &Tgt) {
14996 llvm::APFloat truncated = value;
14997
14998 bool ignored;
14999 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
15000 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
15001
15002 return truncated.bitwiseIsEqual(value);
15003}
15004
15005/// Checks whether the given value, which currently has the given
15006/// source semantics, has the same value when coerced through the
15007/// target semantics.
15008///
15009/// The value might be a vector of floats (or a complex number).
15010static bool IsSameFloatAfterCast(const APValue &value,
15011 const llvm::fltSemantics &Src,
15012 const llvm::fltSemantics &Tgt) {
15013 if (value.isFloat())
15014 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
15015
15016 if (value.isVector()) {
15017 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
15018 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
15019 return false;
15020 return true;
15021 }
15022
15023 assert(value.isComplexFloat());
15024 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
15025 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
15026}
15027
15028static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
15029 bool IsListInit = false);
15030
15031static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
15032 // Suppress cases where we are comparing against an enum constant.
15033 if (const DeclRefExpr *DR =
15034 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
15035 if (isa<EnumConstantDecl>(DR->getDecl()))
15036 return true;
15037
15038 // Suppress cases where the value is expanded from a macro, unless that macro
15039 // is how a language represents a boolean literal. This is the case in both C
15040 // and Objective-C.
15041 SourceLocation BeginLoc = E->getBeginLoc();
15042 if (BeginLoc.isMacroID()) {
15043 StringRef MacroName = Lexer::getImmediateMacroName(
15044 BeginLoc, S.getSourceManager(), S.getLangOpts());
15045 return MacroName != "YES" && MacroName != "NO" &&
15046 MacroName != "true" && MacroName != "false";
15047 }
15048
15049 return false;
15050}
15051
15053 return E->getType()->isIntegerType() &&
15054 (!E->getType()->isSignedIntegerType() ||
15056}
15057
15058namespace {
15059/// The promoted range of values of a type. In general this has the
15060/// following structure:
15061///
15062/// |-----------| . . . |-----------|
15063/// ^ ^ ^ ^
15064/// Min HoleMin HoleMax Max
15065///
15066/// ... where there is only a hole if a signed type is promoted to unsigned
15067/// (in which case Min and Max are the smallest and largest representable
15068/// values).
15069struct PromotedRange {
15070 // Min, or HoleMax if there is a hole.
15071 llvm::APSInt PromotedMin;
15072 // Max, or HoleMin if there is a hole.
15073 llvm::APSInt PromotedMax;
15074
15075 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
15076 if (R.Width == 0)
15077 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
15078 else if (R.Width >= BitWidth && !Unsigned) {
15079 // Promotion made the type *narrower*. This happens when promoting
15080 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
15081 // Treat all values of 'signed int' as being in range for now.
15082 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
15083 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
15084 } else {
15085 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
15086 .extOrTrunc(BitWidth);
15087 PromotedMin.setIsUnsigned(Unsigned);
15088
15089 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
15090 .extOrTrunc(BitWidth);
15091 PromotedMax.setIsUnsigned(Unsigned);
15092 }
15093 }
15094
15095 // Determine whether this range is contiguous (has no hole).
15096 bool isContiguous() const { return PromotedMin <= PromotedMax; }
15097
15098 // Where a constant value is within the range.
15099 enum ComparisonResult {
15100 LT = 0x1,
15101 LE = 0x2,
15102 GT = 0x4,
15103 GE = 0x8,
15104 EQ = 0x10,
15105 NE = 0x20,
15106 InRangeFlag = 0x40,
15107
15108 Less = LE | LT | NE,
15109 Min = LE | InRangeFlag,
15110 InRange = InRangeFlag,
15111 Max = GE | InRangeFlag,
15112 Greater = GE | GT | NE,
15113
15114 OnlyValue = LE | GE | EQ | InRangeFlag,
15115 InHole = NE
15116 };
15117
15118 ComparisonResult compare(const llvm::APSInt &Value) const {
15119 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
15120 Value.isUnsigned() == PromotedMin.isUnsigned());
15121 if (!isContiguous()) {
15122 assert(Value.isUnsigned() && "discontiguous range for signed compare");
15123 if (Value.isMinValue()) return Min;
15124 if (Value.isMaxValue()) return Max;
15125 if (Value >= PromotedMin) return InRange;
15126 if (Value <= PromotedMax) return InRange;
15127 return InHole;
15128 }
15129
15130 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
15131 case -1: return Less;
15132 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
15133 case 1:
15134 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
15135 case -1: return InRange;
15136 case 0: return Max;
15137 case 1: return Greater;
15138 }
15139 }
15140
15141 llvm_unreachable("impossible compare result");
15142 }
15143
15144 static std::optional<StringRef>
15145 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
15146 if (Op == BO_Cmp) {
15147 ComparisonResult LTFlag = LT, GTFlag = GT;
15148 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
15149
15150 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
15151 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
15152 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
15153 return std::nullopt;
15154 }
15155
15156 ComparisonResult TrueFlag, FalseFlag;
15157 if (Op == BO_EQ) {
15158 TrueFlag = EQ;
15159 FalseFlag = NE;
15160 } else if (Op == BO_NE) {
15161 TrueFlag = NE;
15162 FalseFlag = EQ;
15163 } else {
15164 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
15165 TrueFlag = LT;
15166 FalseFlag = GE;
15167 } else {
15168 TrueFlag = GT;
15169 FalseFlag = LE;
15170 }
15171 if (Op == BO_GE || Op == BO_LE)
15172 std::swap(TrueFlag, FalseFlag);
15173 }
15174 if (R & TrueFlag)
15175 return StringRef("true");
15176 if (R & FalseFlag)
15177 return StringRef("false");
15178 return std::nullopt;
15179 }
15180};
15181}
15182
15183static bool HasEnumType(Expr *E) {
15184 // Strip off implicit integral promotions.
15185 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
15186 if (ICE->getCastKind() != CK_IntegralCast &&
15187 ICE->getCastKind() != CK_NoOp)
15188 break;
15189 E = ICE->getSubExpr();
15190 }
15191
15192 return E->getType()->isEnumeralType();
15193}
15194
15195static int classifyConstantValue(Expr *Constant) {
15196 // The values of this enumeration are used in the diagnostics
15197 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
15198 enum ConstantValueKind {
15199 Miscellaneous = 0,
15200 LiteralTrue,
15201 LiteralFalse
15202 };
15203 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
15204 return BL->getValue() ? ConstantValueKind::LiteralTrue
15205 : ConstantValueKind::LiteralFalse;
15206 return ConstantValueKind::Miscellaneous;
15207}
15208
15210 Expr *Constant, Expr *Other,
15211 const llvm::APSInt &Value,
15212 bool RhsConstant) {
15214 return false;
15215
15216 Expr *OriginalOther = Other;
15217
15218 Constant = Constant->IgnoreParenImpCasts();
15219 Other = Other->IgnoreParenImpCasts();
15220
15221 // Suppress warnings on tautological comparisons between values of the same
15222 // enumeration type. There are only two ways we could warn on this:
15223 // - If the constant is outside the range of representable values of
15224 // the enumeration. In such a case, we should warn about the cast
15225 // to enumeration type, not about the comparison.
15226 // - If the constant is the maximum / minimum in-range value. For an
15227 // enumeratin type, such comparisons can be meaningful and useful.
15228 if (Constant->getType()->isEnumeralType() &&
15229 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
15230 return false;
15231
15232 IntRange OtherValueRange = GetExprRange(
15233 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
15234
15235 QualType OtherT = Other->getType();
15236 if (const auto *AT = OtherT->getAs<AtomicType>())
15237 OtherT = AT->getValueType();
15238 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
15239
15240 // Special case for ObjC BOOL on targets where its a typedef for a signed char
15241 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
15242 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
15243 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
15244 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
15245
15246 // Whether we're treating Other as being a bool because of the form of
15247 // expression despite it having another type (typically 'int' in C).
15248 bool OtherIsBooleanDespiteType =
15249 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
15250 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
15251 OtherTypeRange = OtherValueRange = IntRange::forBoolType();
15252
15253 // Check if all values in the range of possible values of this expression
15254 // lead to the same comparison outcome.
15255 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
15256 Value.isUnsigned());
15257 auto Cmp = OtherPromotedValueRange.compare(Value);
15258 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
15259 if (!Result)
15260 return false;
15261
15262 // Also consider the range determined by the type alone. This allows us to
15263 // classify the warning under the proper diagnostic group.
15264 bool TautologicalTypeCompare = false;
15265 {
15266 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
15267 Value.isUnsigned());
15268 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
15269 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
15270 RhsConstant)) {
15271 TautologicalTypeCompare = true;
15272 Cmp = TypeCmp;
15274 }
15275 }
15276
15277 // Don't warn if the non-constant operand actually always evaluates to the
15278 // same value.
15279 if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
15280 return false;
15281
15282 // Suppress the diagnostic for an in-range comparison if the constant comes
15283 // from a macro or enumerator. We don't want to diagnose
15284 //
15285 // some_long_value <= INT_MAX
15286 //
15287 // when sizeof(int) == sizeof(long).
15288 bool InRange = Cmp & PromotedRange::InRangeFlag;
15289 if (InRange && IsEnumConstOrFromMacro(S, Constant))
15290 return false;
15291
15292 // A comparison of an unsigned bit-field against 0 is really a type problem,
15293 // even though at the type level the bit-field might promote to 'signed int'.
15294 if (Other->refersToBitField() && InRange && Value == 0 &&
15295 Other->getType()->isUnsignedIntegerOrEnumerationType())
15296 TautologicalTypeCompare = true;
15297
15298 // If this is a comparison to an enum constant, include that
15299 // constant in the diagnostic.
15300 const EnumConstantDecl *ED = nullptr;
15301 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
15302 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
15303
15304 // Should be enough for uint128 (39 decimal digits)
15305 SmallString<64> PrettySourceValue;
15306 llvm::raw_svector_ostream OS(PrettySourceValue);
15307 if (ED) {
15308 OS << '\'' << *ED << "' (" << Value << ")";
15309 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
15310 Constant->IgnoreParenImpCasts())) {
15311 OS << (BL->getValue() ? "YES" : "NO");
15312 } else {
15313 OS << Value;
15314 }
15315
15316 if (!TautologicalTypeCompare) {
15317 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
15318 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
15319 << E->getOpcodeStr() << OS.str() << *Result
15320 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
15321 return true;
15322 }
15323
15324 if (IsObjCSignedCharBool) {
15326 S.PDiag(diag::warn_tautological_compare_objc_bool)
15327 << OS.str() << *Result);
15328 return true;
15329 }
15330
15331 // FIXME: We use a somewhat different formatting for the in-range cases and
15332 // cases involving boolean values for historical reasons. We should pick a
15333 // consistent way of presenting these diagnostics.
15334 if (!InRange || Other->isKnownToHaveBooleanValue()) {
15335
15337 E->getOperatorLoc(), E,
15338 S.PDiag(!InRange ? diag::warn_out_of_range_compare
15339 : diag::warn_tautological_bool_compare)
15340 << OS.str() << classifyConstantValue(Constant) << OtherT
15341 << OtherIsBooleanDespiteType << *Result
15342 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
15343 } else {
15344 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
15345 unsigned Diag =
15346 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
15347 ? (HasEnumType(OriginalOther)
15348 ? diag::warn_unsigned_enum_always_true_comparison
15349 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
15350 : diag::warn_unsigned_always_true_comparison)
15351 : diag::warn_tautological_constant_compare;
15352
15353 S.Diag(E->getOperatorLoc(), Diag)
15354 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
15355 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
15356 }
15357
15358 return true;
15359}
15360
15361/// Analyze the operands of the given comparison. Implements the
15362/// fallback case from AnalyzeComparison.
15366}
15367
15368/// Implements -Wsign-compare.
15369///
15370/// \param E the binary operator to check for warnings
15372 // The type the comparison is being performed in.
15373 QualType T = E->getLHS()->getType();
15374
15375 // Only analyze comparison operators where both sides have been converted to
15376 // the same type.
15378 return AnalyzeImpConvsInComparison(S, E);
15379
15380 // Don't analyze value-dependent comparisons directly.
15381 if (E->isValueDependent())
15382 return AnalyzeImpConvsInComparison(S, E);
15383
15384 Expr *LHS = E->getLHS();
15385 Expr *RHS = E->getRHS();
15386
15387 if (T->isIntegralType(S.Context)) {
15388 std::optional<llvm::APSInt> RHSValue =
15390 std::optional<llvm::APSInt> LHSValue =
15392
15393 // We don't care about expressions whose result is a constant.
15394 if (RHSValue && LHSValue)
15395 return AnalyzeImpConvsInComparison(S, E);
15396
15397 // We only care about expressions where just one side is literal
15398 if ((bool)RHSValue ^ (bool)LHSValue) {
15399 // Is the constant on the RHS or LHS?
15400 const bool RhsConstant = (bool)RHSValue;
15401 Expr *Const = RhsConstant ? RHS : LHS;
15402 Expr *Other = RhsConstant ? LHS : RHS;
15403 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
15404
15405 // Check whether an integer constant comparison results in a value
15406 // of 'true' or 'false'.
15407 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
15408 return AnalyzeImpConvsInComparison(S, E);
15409 }
15410 }
15411
15413 // We don't do anything special if this isn't an unsigned integral
15414 // comparison: we're only interested in integral comparisons, and
15415 // signed comparisons only happen in cases we don't care to warn about.
15416 return AnalyzeImpConvsInComparison(S, E);
15417 }
15418
15419 LHS = LHS->IgnoreParenImpCasts();
15420 RHS = RHS->IgnoreParenImpCasts();
15421
15422 if (!S.getLangOpts().CPlusPlus) {
15423 // Avoid warning about comparison of integers with different signs when
15424 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
15425 // the type of `E`.
15426 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
15427 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
15428 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
15429 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
15430 }
15431
15432 // Check to see if one of the (unmodified) operands is of different
15433 // signedness.
15434 Expr *signedOperand, *unsignedOperand;
15436 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
15437 "unsigned comparison between two signed integer expressions?");
15438 signedOperand = LHS;
15439 unsignedOperand = RHS;
15440 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
15441 signedOperand = RHS;
15442 unsignedOperand = LHS;
15443 } else {
15444 return AnalyzeImpConvsInComparison(S, E);
15445 }
15446
15447 // Otherwise, calculate the effective range of the signed operand.
15448 IntRange signedRange =
15449 GetExprRange(S.Context, signedOperand, S.isConstantEvaluatedContext(),
15450 /*Approximate=*/true);
15451
15452 // Go ahead and analyze implicit conversions in the operands. Note
15453 // that we skip the implicit conversions on both sides.
15456
15457 // If the signed range is non-negative, -Wsign-compare won't fire.
15458 if (signedRange.NonNegative)
15459 return;
15460
15461 // For (in)equality comparisons, if the unsigned operand is a
15462 // constant which cannot collide with a overflowed signed operand,
15463 // then reinterpreting the signed operand as unsigned will not
15464 // change the result of the comparison.
15465 if (E->isEqualityOp()) {
15466 unsigned comparisonWidth = S.Context.getIntWidth(T);
15467 IntRange unsignedRange =
15468 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
15469 /*Approximate=*/true);
15470
15471 // We should never be unable to prove that the unsigned operand is
15472 // non-negative.
15473 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
15474
15475 if (unsignedRange.Width < comparisonWidth)
15476 return;
15477 }
15478
15480 S.PDiag(diag::warn_mixed_sign_comparison)
15481 << LHS->getType() << RHS->getType()
15482 << LHS->getSourceRange() << RHS->getSourceRange());
15483}
15484
15485/// Analyzes an attempt to assign the given value to a bitfield.
15486///
15487/// Returns true if there was something fishy about the attempt.
15489 SourceLocation InitLoc) {
15490 assert(Bitfield->isBitField());
15491 if (Bitfield->isInvalidDecl())
15492 return false;
15493
15494 // White-list bool bitfields.
15495 QualType BitfieldType = Bitfield->getType();
15496 if (BitfieldType->isBooleanType())
15497 return false;
15498
15499 if (BitfieldType->isEnumeralType()) {
15500 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
15501 // If the underlying enum type was not explicitly specified as an unsigned
15502 // type and the enum contain only positive values, MSVC++ will cause an
15503 // inconsistency by storing this as a signed type.
15504 if (S.getLangOpts().CPlusPlus11 &&
15505 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
15506 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
15507 BitfieldEnumDecl->getNumNegativeBits() == 0) {
15508 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
15509 << BitfieldEnumDecl;
15510 }
15511 }
15512
15513 // Ignore value- or type-dependent expressions.
15514 if (Bitfield->getBitWidth()->isValueDependent() ||
15515 Bitfield->getBitWidth()->isTypeDependent() ||
15516 Init->isValueDependent() ||
15517 Init->isTypeDependent())
15518 return false;
15519
15520 Expr *OriginalInit = Init->IgnoreParenImpCasts();
15521 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
15522
15524 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
15526 // The RHS is not constant. If the RHS has an enum type, make sure the
15527 // bitfield is wide enough to hold all the values of the enum without
15528 // truncation.
15529 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
15530 EnumDecl *ED = EnumTy->getDecl();
15531 bool SignedBitfield = BitfieldType->isSignedIntegerType();
15532
15533 // Enum types are implicitly signed on Windows, so check if there are any
15534 // negative enumerators to see if the enum was intended to be signed or
15535 // not.
15536 bool SignedEnum = ED->getNumNegativeBits() > 0;
15537
15538 // Check for surprising sign changes when assigning enum values to a
15539 // bitfield of different signedness. If the bitfield is signed and we
15540 // have exactly the right number of bits to store this unsigned enum,
15541 // suggest changing the enum to an unsigned type. This typically happens
15542 // on Windows where unfixed enums always use an underlying type of 'int'.
15543 unsigned DiagID = 0;
15544 if (SignedEnum && !SignedBitfield) {
15545 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
15546 } else if (SignedBitfield && !SignedEnum &&
15547 ED->getNumPositiveBits() == FieldWidth) {
15548 DiagID = diag::warn_signed_bitfield_enum_conversion;
15549 }
15550
15551 if (DiagID) {
15552 S.Diag(InitLoc, DiagID) << Bitfield << ED;
15553 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
15554 SourceRange TypeRange =
15555 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
15556 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
15557 << SignedEnum << TypeRange;
15558 }
15559
15560 // Compute the required bitwidth. If the enum has negative values, we need
15561 // one more bit than the normal number of positive bits to represent the
15562 // sign bit.
15563 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
15564 ED->getNumNegativeBits())
15565 : ED->getNumPositiveBits();
15566
15567 // Check the bitwidth.
15568 if (BitsNeeded > FieldWidth) {
15569 Expr *WidthExpr = Bitfield->getBitWidth();
15570 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
15571 << Bitfield << ED;
15572 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
15573 << BitsNeeded << ED << WidthExpr->getSourceRange();
15574 }
15575 }
15576
15577 return false;
15578 }
15579
15580 llvm::APSInt Value = Result.Val.getInt();
15581
15582 unsigned OriginalWidth = Value.getBitWidth();
15583
15584 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
15585 // false positives where the user is demonstrating they intend to use the
15586 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
15587 // to a one-bit bit-field to see if the value came from a macro named 'true'.
15588 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
15589 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
15590 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
15591 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
15592 S.findMacroSpelling(MaybeMacroLoc, "true"))
15593 return false;
15594 }
15595
15596 if (!Value.isSigned() || Value.isNegative())
15597 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
15598 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
15599 OriginalWidth = Value.getSignificantBits();
15600
15601 if (OriginalWidth <= FieldWidth)
15602 return false;
15603
15604 // Compute the value which the bitfield will contain.
15605 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
15606 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
15607
15608 // Check whether the stored value is equal to the original value.
15609 TruncatedValue = TruncatedValue.extend(OriginalWidth);
15610 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
15611 return false;
15612
15613 std::string PrettyValue = toString(Value, 10);
15614 std::string PrettyTrunc = toString(TruncatedValue, 10);
15615
15616 S.Diag(InitLoc, OneAssignedToOneBitBitfield
15617 ? diag::warn_impcast_single_bit_bitield_precision_constant
15618 : diag::warn_impcast_bitfield_precision_constant)
15619 << PrettyValue << PrettyTrunc << OriginalInit->getType()
15620 << Init->getSourceRange();
15621
15622 return true;
15623}
15624
15625/// Analyze the given simple or compound assignment for warning-worthy
15626/// operations.
15628 // Just recurse on the LHS.
15630
15631 // We want to recurse on the RHS as normal unless we're assigning to
15632 // a bitfield.
15633 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
15634 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
15635 E->getOperatorLoc())) {
15636 // Recurse, ignoring any implicit conversions on the RHS.
15638 E->getOperatorLoc());
15639 }
15640 }
15641
15643
15644 // Diagnose implicitly sequentially-consistent atomic assignment.
15645 if (E->getLHS()->getType()->isAtomicType())
15646 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
15647}
15648
15649/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
15650static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
15651 SourceLocation CContext, unsigned diag,
15652 bool pruneControlFlow = false) {
15653 if (pruneControlFlow) {
15655 S.PDiag(diag)
15656 << SourceType << T << E->getSourceRange()
15657 << SourceRange(CContext));
15658 return;
15659 }
15660 S.Diag(E->getExprLoc(), diag)
15661 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
15662}
15663
15664/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
15665static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
15666 SourceLocation CContext,
15667 unsigned diag, bool pruneControlFlow = false) {
15668 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
15669}
15670
15672 return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
15673 S.getLangOpts().ObjC && S.ObjC().NSAPIObj->isObjCBOOLType(Ty);
15674}
15675
15677 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
15678 Expr *Ignored = SourceExpr->IgnoreImplicit();
15679 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
15680 Ignored = OVE->getSourceExpr();
15681 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
15682 isa<BinaryOperator>(Ignored) ||
15683 isa<CXXOperatorCallExpr>(Ignored);
15684 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
15685 if (NeedsParens)
15686 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
15687 << FixItHint::CreateInsertion(EndLoc, ")");
15688 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
15689}
15690
15691/// Diagnose an implicit cast from a floating point value to an integer value.
15693 SourceLocation CContext) {
15694 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
15695 const bool PruneWarnings = S.inTemplateInstantiation();
15696
15697 Expr *InnerE = E->IgnoreParenImpCasts();
15698 // We also want to warn on, e.g., "int i = -1.234"
15699 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
15700 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
15701 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
15702
15703 const bool IsLiteral =
15704 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
15705
15706 llvm::APFloat Value(0.0);
15707 bool IsConstant =
15709 if (!IsConstant) {
15710 if (isObjCSignedCharBool(S, T)) {
15712 S, E,
15713 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
15714 << E->getType());
15715 }
15716
15717 return DiagnoseImpCast(S, E, T, CContext,
15718 diag::warn_impcast_float_integer, PruneWarnings);
15719 }
15720
15721 bool isExact = false;
15722
15723 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
15725 llvm::APFloat::opStatus Result = Value.convertToInteger(
15726 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
15727
15728 // FIXME: Force the precision of the source value down so we don't print
15729 // digits which are usually useless (we don't really care here if we
15730 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
15731 // would automatically print the shortest representation, but it's a bit
15732 // tricky to implement.
15733 SmallString<16> PrettySourceValue;
15734 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
15735 precision = (precision * 59 + 195) / 196;
15736 Value.toString(PrettySourceValue, precision);
15737
15738 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
15740 S, E,
15741 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
15742 << PrettySourceValue);
15743 }
15744
15745 if (Result == llvm::APFloat::opOK && isExact) {
15746 if (IsLiteral) return;
15747 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
15748 PruneWarnings);
15749 }
15750
15751 // Conversion of a floating-point value to a non-bool integer where the
15752 // integral part cannot be represented by the integer type is undefined.
15753 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
15754 return DiagnoseImpCast(
15755 S, E, T, CContext,
15756 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
15757 : diag::warn_impcast_float_to_integer_out_of_range,
15758 PruneWarnings);
15759
15760 unsigned DiagID = 0;
15761 if (IsLiteral) {
15762 // Warn on floating point literal to integer.
15763 DiagID = diag::warn_impcast_literal_float_to_integer;
15764 } else if (IntegerValue == 0) {
15765 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
15766 return DiagnoseImpCast(S, E, T, CContext,
15767 diag::warn_impcast_float_integer, PruneWarnings);
15768 }
15769 // Warn on non-zero to zero conversion.
15770 DiagID = diag::warn_impcast_float_to_integer_zero;
15771 } else {
15772 if (IntegerValue.isUnsigned()) {
15773 if (!IntegerValue.isMaxValue()) {
15774 return DiagnoseImpCast(S, E, T, CContext,
15775 diag::warn_impcast_float_integer, PruneWarnings);
15776 }
15777 } else { // IntegerValue.isSigned()
15778 if (!IntegerValue.isMaxSignedValue() &&
15779 !IntegerValue.isMinSignedValue()) {
15780 return DiagnoseImpCast(S, E, T, CContext,
15781 diag::warn_impcast_float_integer, PruneWarnings);
15782 }
15783 }
15784 // Warn on evaluatable floating point expression to integer conversion.
15785 DiagID = diag::warn_impcast_float_to_integer;
15786 }
15787
15788 SmallString<16> PrettyTargetValue;
15789 if (IsBool)
15790 PrettyTargetValue = Value.isZero() ? "false" : "true";
15791 else
15792 IntegerValue.toString(PrettyTargetValue);
15793
15794 if (PruneWarnings) {
15796 S.PDiag(DiagID)
15797 << E->getType() << T.getUnqualifiedType()
15798 << PrettySourceValue << PrettyTargetValue
15799 << E->getSourceRange() << SourceRange(CContext));
15800 } else {
15801 S.Diag(E->getExprLoc(), DiagID)
15802 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
15803 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
15804 }
15805}
15806
15807/// Analyze the given compound assignment for the possible losing of
15808/// floating-point precision.
15810 assert(isa<CompoundAssignOperator>(E) &&
15811 "Must be compound assignment operation");
15812 // Recurse on the LHS and RHS in here
15815
15816 if (E->getLHS()->getType()->isAtomicType())
15817 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
15818
15819 // Now check the outermost expression
15820 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
15821 const auto *RBT = cast<CompoundAssignOperator>(E)
15822 ->getComputationResultType()
15823 ->getAs<BuiltinType>();
15824
15825 // The below checks assume source is floating point.
15826 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
15827
15828 // If source is floating point but target is an integer.
15829 if (ResultBT->isInteger())
15830 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
15831 E->getExprLoc(), diag::warn_impcast_float_integer);
15832
15833 if (!ResultBT->isFloatingPoint())
15834 return;
15835
15836 // If both source and target are floating points, warn about losing precision.
15838 QualType(ResultBT, 0), QualType(RBT, 0));
15839 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
15840 // warn about dropping FP rank.
15841 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
15842 diag::warn_impcast_float_result_precision);
15843}
15844
15845static std::string PrettyPrintInRange(const llvm::APSInt &Value,
15846 IntRange Range) {
15847 if (!Range.Width) return "0";
15848
15849 llvm::APSInt ValueInRange = Value;
15850 ValueInRange.setIsSigned(!Range.NonNegative);
15851 ValueInRange = ValueInRange.trunc(Range.Width);
15852 return toString(ValueInRange, 10);
15853}
15854
15855static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
15856 if (!isa<ImplicitCastExpr>(Ex))
15857 return false;
15858
15859 Expr *InnerE = Ex->IgnoreParenImpCasts();
15861 const Type *Source =
15863 if (Target->isDependentType())
15864 return false;
15865
15866 const BuiltinType *FloatCandidateBT =
15867 dyn_cast<BuiltinType>(ToBool ? Source : Target);
15868 const Type *BoolCandidateType = ToBool ? Target : Source;
15869
15870 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
15871 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
15872}
15873
15875 SourceLocation CC) {
15876 unsigned NumArgs = TheCall->getNumArgs();
15877 for (unsigned i = 0; i < NumArgs; ++i) {
15878 Expr *CurrA = TheCall->getArg(i);
15879 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
15880 continue;
15881
15882 bool IsSwapped = ((i > 0) &&
15883 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
15884 IsSwapped |= ((i < (NumArgs - 1)) &&
15885 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
15886 if (IsSwapped) {
15887 // Warn on this floating-point to bool conversion.
15889 CurrA->getType(), CC,
15890 diag::warn_impcast_floating_point_to_bool);
15891 }
15892 }
15893}
15894
15896 SourceLocation CC) {
15897 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
15898 E->getExprLoc()))
15899 return;
15900
15901 // Don't warn on functions which have return type nullptr_t.
15902 if (isa<CallExpr>(E))
15903 return;
15904
15905 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
15906 const Expr *NewE = E->IgnoreParenImpCasts();
15907 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
15908 bool HasNullPtrType = NewE->getType()->isNullPtrType();
15909 if (!IsGNUNullExpr && !HasNullPtrType)
15910 return;
15911
15912 // Return if target type is a safe conversion.
15913 if (T->isAnyPointerType() || T->isBlockPointerType() ||
15915 return;
15916
15918
15919 // Venture through the macro stacks to get to the source of macro arguments.
15920 // The new location is a better location than the complete location that was
15921 // passed in.
15924
15925 // __null is usually wrapped in a macro. Go up a macro if that is the case.
15926 if (IsGNUNullExpr && Loc.isMacroID()) {
15927 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
15928 Loc, S.SourceMgr, S.getLangOpts());
15929 if (MacroName == "NULL")
15931 }
15932
15933 // Only warn if the null and context location are in the same macro expansion.
15934 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
15935 return;
15936
15937 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
15938 << HasNullPtrType << T << SourceRange(CC)
15941}
15942
15943static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
15944 ObjCArrayLiteral *ArrayLiteral);
15945
15946static void
15948 ObjCDictionaryLiteral *DictionaryLiteral);
15949
15950/// Check a single element within a collection literal against the
15951/// target element type.
15953 QualType TargetElementType,
15954 Expr *Element,
15955 unsigned ElementKind) {
15956 // Skip a bitcast to 'id' or qualified 'id'.
15957 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
15958 if (ICE->getCastKind() == CK_BitCast &&
15959 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
15960 Element = ICE->getSubExpr();
15961 }
15962
15963 QualType ElementType = Element->getType();
15964 ExprResult ElementResult(Element);
15965 if (ElementType->getAs<ObjCObjectPointerType>() &&
15966 S.CheckSingleAssignmentConstraints(TargetElementType,
15967 ElementResult,
15968 false, false)
15969 != Sema::Compatible) {
15970 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
15971 << ElementType << ElementKind << TargetElementType
15972 << Element->getSourceRange();
15973 }
15974
15975 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
15976 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
15977 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
15978 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
15979}
15980
15981/// Check an Objective-C array literal being converted to the given
15982/// target type.
15983static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
15984 ObjCArrayLiteral *ArrayLiteral) {
15985 if (!S.ObjC().NSArrayDecl)
15986 return;
15987
15988 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
15989 if (!TargetObjCPtr)
15990 return;
15991
15992 if (TargetObjCPtr->isUnspecialized() ||
15993 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() !=
15995 return;
15996
15997 auto TypeArgs = TargetObjCPtr->getTypeArgs();
15998 if (TypeArgs.size() != 1)
15999 return;
16000
16001 QualType TargetElementType = TypeArgs[0];
16002 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
16003 checkObjCCollectionLiteralElement(S, TargetElementType,
16004 ArrayLiteral->getElement(I),
16005 0);
16006 }
16007}
16008
16009/// Check an Objective-C dictionary literal being converted to the given
16010/// target type.
16011static void
16013 ObjCDictionaryLiteral *DictionaryLiteral) {
16014 if (!S.ObjC().NSDictionaryDecl)
16015 return;
16016
16017 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
16018 if (!TargetObjCPtr)
16019 return;
16020
16021 if (TargetObjCPtr->isUnspecialized() ||
16022 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() !=
16024 return;
16025
16026 auto TypeArgs = TargetObjCPtr->getTypeArgs();
16027 if (TypeArgs.size() != 2)
16028 return;
16029
16030 QualType TargetKeyType = TypeArgs[0];
16031 QualType TargetObjectType = TypeArgs[1];
16032 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
16033 auto Element = DictionaryLiteral->getKeyValueElement(I);
16034 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
16035 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
16036 }
16037}
16038
16039// Helper function to filter out cases for constant width constant conversion.
16040// Don't warn on char array initialization or for non-decimal values.
16042 SourceLocation CC) {
16043 // If initializing from a constant, and the constant starts with '0',
16044 // then it is a binary, octal, or hexadecimal. Allow these constants
16045 // to fill all the bits, even if there is a sign change.
16046 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
16047 const char FirstLiteralCharacter =
16048 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
16049 if (FirstLiteralCharacter == '0')
16050 return false;
16051 }
16052
16053 // If the CC location points to a '{', and the type is char, then assume
16054 // assume it is an array initialization.
16055 if (CC.isValid() && T->isCharType()) {
16056 const char FirstContextCharacter =
16058 if (FirstContextCharacter == '{')
16059 return false;
16060 }
16061
16062 return true;
16063}
16064
16066 const auto *IL = dyn_cast<IntegerLiteral>(E);
16067 if (!IL) {
16068 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
16069 if (UO->getOpcode() == UO_Minus)
16070 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
16071 }
16072 }
16073
16074 return IL;
16075}
16076
16078 E = E->IgnoreParenImpCasts();
16079 SourceLocation ExprLoc = E->getExprLoc();
16080
16081 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
16082 BinaryOperator::Opcode Opc = BO->getOpcode();
16084 // Do not diagnose unsigned shifts.
16085 if (Opc == BO_Shl) {
16086 const auto *LHS = getIntegerLiteral(BO->getLHS());
16087 const auto *RHS = getIntegerLiteral(BO->getRHS());
16088 if (LHS && LHS->getValue() == 0)
16089 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
16090 else if (!E->isValueDependent() && LHS && RHS &&
16091 RHS->getValue().isNonNegative() &&
16093 S.Diag(ExprLoc, diag::warn_left_shift_always)
16094 << (Result.Val.getInt() != 0);
16095 else if (E->getType()->isSignedIntegerType())
16096 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
16097 }
16098 }
16099
16100 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
16101 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
16102 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
16103 if (!LHS || !RHS)
16104 return;
16105 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
16106 (RHS->getValue() == 0 || RHS->getValue() == 1))
16107 // Do not diagnose common idioms.
16108 return;
16109 if (LHS->getValue() != 0 && RHS->getValue() != 0)
16110 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
16111 }
16112}
16113
16115 SourceLocation CC,
16116 bool *ICContext = nullptr,
16117 bool IsListInit = false) {
16118 if (E->isTypeDependent() || E->isValueDependent()) return;
16119
16120 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
16122 if (Source == Target) return;
16123 if (Target->isDependentType()) return;
16124
16125 // If the conversion context location is invalid don't complain. We also
16126 // don't want to emit a warning if the issue occurs from the expansion of
16127 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
16128 // delay this check as long as possible. Once we detect we are in that
16129 // scenario, we just return.
16130 if (CC.isInvalid())
16131 return;
16132
16133 if (Source->isAtomicType())
16134 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
16135
16136 // Diagnose implicit casts to bool.
16137 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
16138 if (isa<StringLiteral>(E))
16139 // Warn on string literal to bool. Checks for string literals in logical
16140 // and expressions, for instance, assert(0 && "error here"), are
16141 // prevented by a check in AnalyzeImplicitConversions().
16142 return DiagnoseImpCast(S, E, T, CC,
16143 diag::warn_impcast_string_literal_to_bool);
16144 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
16145 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
16146 // This covers the literal expressions that evaluate to Objective-C
16147 // objects.
16148 return DiagnoseImpCast(S, E, T, CC,
16149 diag::warn_impcast_objective_c_literal_to_bool);
16150 }
16151 if (Source->isPointerType() || Source->canDecayToPointerType()) {
16152 // Warn on pointer to bool conversion that is always true.
16153 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
16154 SourceRange(CC));
16155 }
16156 }
16157
16158 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
16159 // is a typedef for signed char (macOS), then that constant value has to be 1
16160 // or 0.
16161 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
16165 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
16167 S, E,
16168 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
16169 << toString(Result.Val.getInt(), 10));
16170 }
16171 return;
16172 }
16173 }
16174
16175 // Check implicit casts from Objective-C collection literals to specialized
16176 // collection types, e.g., NSArray<NSString *> *.
16177 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
16178 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
16179 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
16180 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
16181
16182 // Strip vector types.
16183 if (isa<VectorType>(Source)) {
16184 if (Target->isSveVLSBuiltinType() &&
16186 QualType(Source, 0)) ||
16188 QualType(Source, 0))))
16189 return;
16190
16191 if (Target->isRVVVLSBuiltinType() &&
16193 QualType(Source, 0)) ||
16195 QualType(Source, 0))))
16196 return;
16197
16198 if (!isa<VectorType>(Target)) {
16199 if (S.SourceMgr.isInSystemMacro(CC))
16200 return;
16201 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
16202 } else if (S.getLangOpts().HLSL &&
16203 Target->castAs<VectorType>()->getNumElements() <
16204 Source->castAs<VectorType>()->getNumElements()) {
16205 // Diagnose vector truncation but don't return. We may also want to
16206 // diagnose an element conversion.
16207 DiagnoseImpCast(S, E, T, CC, diag::warn_hlsl_impcast_vector_truncation);
16208 }
16209
16210 // If the vector cast is cast between two vectors of the same size, it is
16211 // a bitcast, not a conversion, except under HLSL where it is a conversion.
16212 if (!S.getLangOpts().HLSL &&
16214 return;
16215
16216 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
16217 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
16218 }
16219 if (auto VecTy = dyn_cast<VectorType>(Target))
16220 Target = VecTy->getElementType().getTypePtr();
16221
16222 // Strip complex types.
16223 if (isa<ComplexType>(Source)) {
16224 if (!isa<ComplexType>(Target)) {
16225 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
16226 return;
16227
16228 return DiagnoseImpCast(S, E, T, CC,
16229 S.getLangOpts().CPlusPlus
16230 ? diag::err_impcast_complex_scalar
16231 : diag::warn_impcast_complex_scalar);
16232 }
16233
16234 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
16235 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
16236 }
16237
16238 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
16239 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
16240
16241 // Strip SVE vector types
16242 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
16243 // Need the original target type for vector type checks
16244 const Type *OriginalTarget = S.Context.getCanonicalType(T).getTypePtr();
16245 // Handle conversion from scalable to fixed when msve-vector-bits is
16246 // specified
16247 if (S.Context.areCompatibleSveTypes(QualType(OriginalTarget, 0),
16248 QualType(Source, 0)) ||
16249 S.Context.areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
16250 QualType(Source, 0)))
16251 return;
16252
16253 // If the vector cast is cast between two vectors of the same size, it is
16254 // a bitcast, not a conversion.
16255 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
16256 return;
16257
16258 Source = SourceBT->getSveEltType(S.Context).getTypePtr();
16259 }
16260
16261 if (TargetBT && TargetBT->isSveVLSBuiltinType())
16262 Target = TargetBT->getSveEltType(S.Context).getTypePtr();
16263
16264 // If the source is floating point...
16265 if (SourceBT && SourceBT->isFloatingPoint()) {
16266 // ...and the target is floating point...
16267 if (TargetBT && TargetBT->isFloatingPoint()) {
16268 // ...then warn if we're dropping FP rank.
16269
16271 QualType(SourceBT, 0), QualType(TargetBT, 0));
16272 if (Order > 0) {
16273 // Don't warn about float constants that are precisely
16274 // representable in the target type.
16275 Expr::EvalResult result;
16276 if (E->EvaluateAsRValue(result, S.Context)) {
16277 // Value might be a float, a float vector, or a float complex.
16278 if (IsSameFloatAfterCast(result.Val,
16279 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
16280 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
16281 return;
16282 }
16283
16284 if (S.SourceMgr.isInSystemMacro(CC))
16285 return;
16286
16287 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
16288 }
16289 // ... or possibly if we're increasing rank, too
16290 else if (Order < 0) {
16291 if (S.SourceMgr.isInSystemMacro(CC))
16292 return;
16293
16294 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
16295 }
16296 return;
16297 }
16298
16299 // If the target is integral, always warn.
16300 if (TargetBT && TargetBT->isInteger()) {
16301 if (S.SourceMgr.isInSystemMacro(CC))
16302 return;
16303
16304 DiagnoseFloatingImpCast(S, E, T, CC);
16305 }
16306
16307 // Detect the case where a call result is converted from floating-point to
16308 // to bool, and the final argument to the call is converted from bool, to
16309 // discover this typo:
16310 //
16311 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
16312 //
16313 // FIXME: This is an incredibly special case; is there some more general
16314 // way to detect this class of misplaced-parentheses bug?
16315 if (Target->isBooleanType() && isa<CallExpr>(E)) {
16316 // Check last argument of function call to see if it is an
16317 // implicit cast from a type matching the type the result
16318 // is being cast to.
16319 CallExpr *CEx = cast<CallExpr>(E);
16320 if (unsigned NumArgs = CEx->getNumArgs()) {
16321 Expr *LastA = CEx->getArg(NumArgs - 1);
16322 Expr *InnerE = LastA->IgnoreParenImpCasts();
16323 if (isa<ImplicitCastExpr>(LastA) &&
16324 InnerE->getType()->isBooleanType()) {
16325 // Warn on this floating-point to bool conversion
16326 DiagnoseImpCast(S, E, T, CC,
16327 diag::warn_impcast_floating_point_to_bool);
16328 }
16329 }
16330 }
16331 return;
16332 }
16333
16334 // Valid casts involving fixed point types should be accounted for here.
16335 if (Source->isFixedPointType()) {
16336 if (Target->isUnsaturatedFixedPointType()) {
16340 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
16341 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
16342 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
16343 if (Value > MaxVal || Value < MinVal) {
16345 S.PDiag(diag::warn_impcast_fixed_point_range)
16346 << Value.toString() << T
16347 << E->getSourceRange()
16348 << clang::SourceRange(CC));
16349 return;
16350 }
16351 }
16352 } else if (Target->isIntegerType()) {
16354 if (!S.isConstantEvaluatedContext() &&
16357 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
16358
16359 bool Overflowed;
16360 llvm::APSInt IntResult = FXResult.convertToInt(
16362 Target->isSignedIntegerOrEnumerationType(), &Overflowed);
16363
16364 if (Overflowed) {
16366 S.PDiag(diag::warn_impcast_fixed_point_range)
16367 << FXResult.toString() << T
16368 << E->getSourceRange()
16369 << clang::SourceRange(CC));
16370 return;
16371 }
16372 }
16373 }
16374 } else if (Target->isUnsaturatedFixedPointType()) {
16375 if (Source->isIntegerType()) {
16377 if (!S.isConstantEvaluatedContext() &&
16379 llvm::APSInt Value = Result.Val.getInt();
16380
16381 bool Overflowed;
16382 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
16383 Value, S.Context.getFixedPointSemantics(T), &Overflowed);
16384
16385 if (Overflowed) {
16387 S.PDiag(diag::warn_impcast_fixed_point_range)
16388 << toString(Value, /*Radix=*/10) << T
16389 << E->getSourceRange()
16390 << clang::SourceRange(CC));
16391 return;
16392 }
16393 }
16394 }
16395 }
16396
16397 // If we are casting an integer type to a floating point type without
16398 // initialization-list syntax, we might lose accuracy if the floating
16399 // point type has a narrower significand than the integer type.
16400 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
16401 TargetBT->isFloatingType() && !IsListInit) {
16402 // Determine the number of precision bits in the source integer type.
16403 IntRange SourceRange =
16405 /*Approximate=*/true);
16406 unsigned int SourcePrecision = SourceRange.Width;
16407
16408 // Determine the number of precision bits in the
16409 // target floating point type.
16410 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
16411 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
16412
16413 if (SourcePrecision > 0 && TargetPrecision > 0 &&
16414 SourcePrecision > TargetPrecision) {
16415
16416 if (std::optional<llvm::APSInt> SourceInt =
16418 // If the source integer is a constant, convert it to the target
16419 // floating point type. Issue a warning if the value changes
16420 // during the whole conversion.
16421 llvm::APFloat TargetFloatValue(
16422 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
16423 llvm::APFloat::opStatus ConversionStatus =
16424 TargetFloatValue.convertFromAPInt(
16425 *SourceInt, SourceBT->isSignedInteger(),
16426 llvm::APFloat::rmNearestTiesToEven);
16427
16428 if (ConversionStatus != llvm::APFloat::opOK) {
16429 SmallString<32> PrettySourceValue;
16430 SourceInt->toString(PrettySourceValue, 10);
16431 SmallString<32> PrettyTargetValue;
16432 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
16433
16435 E->getExprLoc(), E,
16436 S.PDiag(diag::warn_impcast_integer_float_precision_constant)
16437 << PrettySourceValue << PrettyTargetValue << E->getType() << T
16438 << E->getSourceRange() << clang::SourceRange(CC));
16439 }
16440 } else {
16441 // Otherwise, the implicit conversion may lose precision.
16442 DiagnoseImpCast(S, E, T, CC,
16443 diag::warn_impcast_integer_float_precision);
16444 }
16445 }
16446 }
16447
16448 DiagnoseNullConversion(S, E, T, CC);
16449
16451
16452 if (Target->isBooleanType())
16454
16455 if (!Source->isIntegerType() || !Target->isIntegerType())
16456 return;
16457
16458 // TODO: remove this early return once the false positives for constant->bool
16459 // in templates, macros, etc, are reduced or removed.
16460 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
16461 return;
16462
16463 if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
16464 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
16466 S, E,
16467 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
16468 << E->getType());
16469 }
16470
16471 IntRange SourceTypeRange =
16472 IntRange::forTargetOfCanonicalType(S.Context, Source);
16473 IntRange LikelySourceRange = GetExprRange(
16474 S.Context, E, S.isConstantEvaluatedContext(), /*Approximate=*/true);
16475 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
16476
16477 if (LikelySourceRange.Width > TargetRange.Width) {
16478 // If the source is a constant, use a default-on diagnostic.
16479 // TODO: this should happen for bitfield stores, too.
16483 llvm::APSInt Value(32);
16484 Value = Result.Val.getInt();
16485
16486 if (S.SourceMgr.isInSystemMacro(CC))
16487 return;
16488
16489 std::string PrettySourceValue = toString(Value, 10);
16490 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
16491
16493 E->getExprLoc(), E,
16494 S.PDiag(diag::warn_impcast_integer_precision_constant)
16495 << PrettySourceValue << PrettyTargetValue << E->getType() << T
16496 << E->getSourceRange() << SourceRange(CC));
16497 return;
16498 }
16499
16500 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
16501 if (S.SourceMgr.isInSystemMacro(CC))
16502 return;
16503
16504 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
16505 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
16506 /* pruneControlFlow */ true);
16507 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
16508 }
16509
16510 if (TargetRange.Width > SourceTypeRange.Width) {
16511 if (auto *UO = dyn_cast<UnaryOperator>(E))
16512 if (UO->getOpcode() == UO_Minus)
16513 if (Source->isUnsignedIntegerType()) {
16514 if (Target->isUnsignedIntegerType())
16515 return DiagnoseImpCast(S, E, T, CC,
16516 diag::warn_impcast_high_order_zero_bits);
16517 if (Target->isSignedIntegerType())
16518 return DiagnoseImpCast(S, E, T, CC,
16519 diag::warn_impcast_nonnegative_result);
16520 }
16521 }
16522
16523 if (TargetRange.Width == LikelySourceRange.Width &&
16524 !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
16525 Source->isSignedIntegerType()) {
16526 // Warn when doing a signed to signed conversion, warn if the positive
16527 // source value is exactly the width of the target type, which will
16528 // cause a negative value to be stored.
16529
16532 !S.SourceMgr.isInSystemMacro(CC)) {
16533 llvm::APSInt Value = Result.Val.getInt();
16534 if (isSameWidthConstantConversion(S, E, T, CC)) {
16535 std::string PrettySourceValue = toString(Value, 10);
16536 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
16537
16538 S.Diag(E->getExprLoc(),
16539 S.PDiag(diag::warn_impcast_integer_precision_constant)
16540 << PrettySourceValue << PrettyTargetValue << E->getType()
16541 << T << E->getSourceRange() << SourceRange(CC));
16542 return;
16543 }
16544 }
16545
16546 // Fall through for non-constants to give a sign conversion warning.
16547 }
16548
16549 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
16550 ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
16551 (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
16552 LikelySourceRange.Width == TargetRange.Width))) {
16553 if (S.SourceMgr.isInSystemMacro(CC))
16554 return;
16555
16556 if (SourceBT && SourceBT->isInteger() && TargetBT &&
16557 TargetBT->isInteger() &&
16558 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
16559 return;
16560 }
16561
16562 unsigned DiagID = diag::warn_impcast_integer_sign;
16563
16564 // Traditionally, gcc has warned about this under -Wsign-compare.
16565 // We also want to warn about it in -Wconversion.
16566 // So if -Wconversion is off, use a completely identical diagnostic
16567 // in the sign-compare group.
16568 // The conditional-checking code will
16569 if (ICContext) {
16570 DiagID = diag::warn_impcast_integer_sign_conditional;
16571 *ICContext = true;
16572 }
16573
16574 return DiagnoseImpCast(S, E, T, CC, DiagID);
16575 }
16576
16577 // Diagnose conversions between different enumeration types.
16578 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
16579 // type, to give us better diagnostics.
16580 QualType SourceType = E->getEnumCoercedType(S.Context);
16581 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
16582
16583 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
16584 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
16585 if (SourceEnum->getDecl()->hasNameForLinkage() &&
16586 TargetEnum->getDecl()->hasNameForLinkage() &&
16587 SourceEnum != TargetEnum) {
16588 if (S.SourceMgr.isInSystemMacro(CC))
16589 return;
16590
16591 return DiagnoseImpCast(S, E, SourceType, T, CC,
16592 diag::warn_impcast_different_enum_types);
16593 }
16594}
16595
16598
16600 SourceLocation CC, bool &ICContext) {
16601 E = E->IgnoreParenImpCasts();
16602 // Diagnose incomplete type for second or third operand in C.
16603 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
16604 S.RequireCompleteExprType(E, diag::err_incomplete_type);
16605
16606 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
16607 return CheckConditionalOperator(S, CO, CC, T);
16608
16610 if (E->getType() != T)
16611 return CheckImplicitConversion(S, E, T, CC, &ICContext);
16612}
16613
16617
16618 Expr *TrueExpr = E->getTrueExpr();
16619 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
16620 TrueExpr = BCO->getCommon();
16621
16622 bool Suspicious = false;
16623 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
16624 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
16625
16626 if (T->isBooleanType())
16628
16629 // If -Wconversion would have warned about either of the candidates
16630 // for a signedness conversion to the context type...
16631 if (!Suspicious) return;
16632
16633 // ...but it's currently ignored...
16634 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
16635 return;
16636
16637 // ...then check whether it would have warned about either of the
16638 // candidates for a signedness conversion to the condition type.
16639 if (E->getType() == T) return;
16640
16641 Suspicious = false;
16643 E->getType(), CC, &Suspicious);
16644 if (!Suspicious)
16646 E->getType(), CC, &Suspicious);
16647}
16648
16649/// Check conversion of given expression to boolean.
16650/// Input argument E is a logical expression.
16652 // Run the bool-like conversion checks only for C since there bools are
16653 // still not used as the return type from "boolean" operators or as the input
16654 // type for conditional operators.
16655 if (S.getLangOpts().CPlusPlus)
16656 return;
16658 return;
16660}
16661
16662namespace {
16663struct AnalyzeImplicitConversionsWorkItem {
16664 Expr *E;
16665 SourceLocation CC;
16666 bool IsListInit;
16667};
16668}
16669
16670/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
16671/// that should be visited are added to WorkList.
16673 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
16675 Expr *OrigE = Item.E;
16676 SourceLocation CC = Item.CC;
16677
16678 QualType T = OrigE->getType();
16679 Expr *E = OrigE->IgnoreParenImpCasts();
16680
16681 // Propagate whether we are in a C++ list initialization expression.
16682 // If so, we do not issue warnings for implicit int-float conversion
16683 // precision loss, because C++11 narrowing already handles it.
16684 bool IsListInit = Item.IsListInit ||
16685 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
16686
16687 if (E->isTypeDependent() || E->isValueDependent())
16688 return;
16689
16690 Expr *SourceExpr = E;
16691 // Examine, but don't traverse into the source expression of an
16692 // OpaqueValueExpr, since it may have multiple parents and we don't want to
16693 // emit duplicate diagnostics. Its fine to examine the form or attempt to
16694 // evaluate it in the context of checking the specific conversion to T though.
16695 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
16696 if (auto *Src = OVE->getSourceExpr())
16697 SourceExpr = Src;
16698
16699 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
16700 if (UO->getOpcode() == UO_Not &&
16701 UO->getSubExpr()->isKnownToHaveBooleanValue())
16702 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
16703 << OrigE->getSourceRange() << T->isBooleanType()
16704 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
16705
16706 if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
16707 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
16708 BO->getLHS()->isKnownToHaveBooleanValue() &&
16709 BO->getRHS()->isKnownToHaveBooleanValue() &&
16710 BO->getLHS()->HasSideEffects(S.Context) &&
16711 BO->getRHS()->HasSideEffects(S.Context)) {
16713 const LangOptions &LO = S.getLangOpts();
16714 SourceLocation BLoc = BO->getOperatorLoc();
16715 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
16716 StringRef SR = clang::Lexer::getSourceText(
16717 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
16718 // To reduce false positives, only issue the diagnostic if the operator
16719 // is explicitly spelled as a punctuator. This suppresses the diagnostic
16720 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
16721 // in C, along with other macro spellings the user might invent.
16722 if (SR.str() == "&" || SR.str() == "|") {
16723
16724 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
16725 << (BO->getOpcode() == BO_And ? "&" : "|")
16726 << OrigE->getSourceRange()
16728 BO->getOperatorLoc(),
16729 (BO->getOpcode() == BO_And ? "&&" : "||"));
16730 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
16731 }
16732 }
16733
16734 // For conditional operators, we analyze the arguments as if they
16735 // were being fed directly into the output.
16736 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
16737 CheckConditionalOperator(S, CO, CC, T);
16738 return;
16739 }
16740
16741 // Check implicit argument conversions for function calls.
16742 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
16744
16745 // Go ahead and check any implicit conversions we might have skipped.
16746 // The non-canonical typecheck is just an optimization;
16747 // CheckImplicitConversion will filter out dead implicit conversions.
16748 if (SourceExpr->getType() != T)
16749 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
16750
16751 // Now continue drilling into this expression.
16752
16753 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
16754 // The bound subexpressions in a PseudoObjectExpr are not reachable
16755 // as transitive children.
16756 // FIXME: Use a more uniform representation for this.
16757 for (auto *SE : POE->semantics())
16758 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
16759 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
16760 }
16761
16762 // Skip past explicit casts.
16763 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
16764 E = CE->getSubExpr()->IgnoreParenImpCasts();
16765 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
16766 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
16767 WorkList.push_back({E, CC, IsListInit});
16768 return;
16769 }
16770
16771 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
16772 // Do a somewhat different check with comparison operators.
16773 if (BO->isComparisonOp())
16774 return AnalyzeComparison(S, BO);
16775
16776 // And with simple assignments.
16777 if (BO->getOpcode() == BO_Assign)
16778 return AnalyzeAssignment(S, BO);
16779 // And with compound assignments.
16780 if (BO->isAssignmentOp())
16781 return AnalyzeCompoundAssignment(S, BO);
16782 }
16783
16784 // These break the otherwise-useful invariant below. Fortunately,
16785 // we don't really need to recurse into them, because any internal
16786 // expressions should have been analyzed already when they were
16787 // built into statements.
16788 if (isa<StmtExpr>(E)) return;
16789
16790 // Don't descend into unevaluated contexts.
16791 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
16792
16793 // Now just recurse over the expression's children.
16794 CC = E->getExprLoc();
16795 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
16796 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
16797 for (Stmt *SubStmt : E->children()) {
16798 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
16799 if (!ChildExpr)
16800 continue;
16801
16802 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
16803 if (ChildExpr == CSE->getOperand())
16804 // Do not recurse over a CoroutineSuspendExpr's operand.
16805 // The operand is also a subexpression of getCommonExpr(), and
16806 // recursing into it directly would produce duplicate diagnostics.
16807 continue;
16808
16809 if (IsLogicalAndOperator &&
16810 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
16811 // Ignore checking string literals that are in logical and operators.
16812 // This is a common pattern for asserts.
16813 continue;
16814 WorkList.push_back({ChildExpr, CC, IsListInit});
16815 }
16816
16817 if (BO && BO->isLogicalOp()) {
16818 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
16819 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
16820 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
16821
16822 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
16823 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
16824 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
16825 }
16826
16827 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
16828 if (U->getOpcode() == UO_LNot) {
16829 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
16830 } else if (U->getOpcode() != UO_AddrOf) {
16831 if (U->getSubExpr()->getType()->isAtomicType())
16832 S.Diag(U->getSubExpr()->getBeginLoc(),
16833 diag::warn_atomic_implicit_seq_cst);
16834 }
16835 }
16836}
16837
16838/// AnalyzeImplicitConversions - Find and report any interesting
16839/// implicit conversions in the given expression. There are a couple
16840/// of competing diagnostics here, -Wconversion and -Wsign-compare.
16842 bool IsListInit/*= false*/) {
16844 WorkList.push_back({OrigE, CC, IsListInit});
16845 while (!WorkList.empty())
16846 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
16847}
16848
16849/// Diagnose integer type and any valid implicit conversion to it.
16850static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
16851 // Taking into account implicit conversions,
16852 // allow any integer.
16853 if (!E->getType()->isIntegerType()) {
16854 S.Diag(E->getBeginLoc(),
16855 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
16856 return true;
16857 }
16858 // Potentially emit standard warnings for implicit conversions if enabled
16859 // using -Wconversion.
16860 CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
16861 return false;
16862}
16863
16864// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
16865// Returns true when emitting a warning about taking the address of a reference.
16866static bool CheckForReference(Sema &SemaRef, const Expr *E,
16867 const PartialDiagnostic &PD) {
16868 E = E->IgnoreParenImpCasts();
16869
16870 const FunctionDecl *FD = nullptr;
16871
16872 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16873 if (!DRE->getDecl()->getType()->isReferenceType())
16874 return false;
16875 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
16876 if (!M->getMemberDecl()->getType()->isReferenceType())
16877 return false;
16878 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
16879 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
16880 return false;
16881 FD = Call->getDirectCallee();
16882 } else {
16883 return false;
16884 }
16885
16886 SemaRef.Diag(E->getExprLoc(), PD);
16887
16888 // If possible, point to location of function.
16889 if (FD) {
16890 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
16891 }
16892
16893 return true;
16894}
16895
16896// Returns true if the SourceLocation is expanded from any macro body.
16897// Returns false if the SourceLocation is invalid, is from not in a macro
16898// expansion, or is from expanded from a top-level macro argument.
16900 if (Loc.isInvalid())
16901 return false;
16902
16903 while (Loc.isMacroID()) {
16904 if (SM.isMacroBodyExpansion(Loc))
16905 return true;
16906 Loc = SM.getImmediateMacroCallerLoc(Loc);
16907 }
16908
16909 return false;
16910}
16911
16912/// Diagnose pointers that are always non-null.
16913/// \param E the expression containing the pointer
16914/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
16915/// compared to a null pointer
16916/// \param IsEqual True when the comparison is equal to a null pointer
16917/// \param Range Extra SourceRange to highlight in the diagnostic
16920 bool IsEqual, SourceRange Range) {
16921 if (!E)
16922 return;
16923
16924 // Don't warn inside macros.
16925 if (E->getExprLoc().isMacroID()) {
16927 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
16929 return;
16930 }
16931 E = E->IgnoreImpCasts();
16932
16933 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
16934
16935 if (isa<CXXThisExpr>(E)) {
16936 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
16937 : diag::warn_this_bool_conversion;
16938 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
16939 return;
16940 }
16941
16942 bool IsAddressOf = false;
16943
16944 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
16945 if (UO->getOpcode() != UO_AddrOf)
16946 return;
16947 IsAddressOf = true;
16948 E = UO->getSubExpr();
16949 }
16950
16951 if (IsAddressOf) {
16952 unsigned DiagID = IsCompare
16953 ? diag::warn_address_of_reference_null_compare
16954 : diag::warn_address_of_reference_bool_conversion;
16955 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
16956 << IsEqual;
16957 if (CheckForReference(*this, E, PD)) {
16958 return;
16959 }
16960 }
16961
16962 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
16963 bool IsParam = isa<NonNullAttr>(NonnullAttr);
16964 std::string Str;
16965 llvm::raw_string_ostream S(Str);
16966 E->printPretty(S, nullptr, getPrintingPolicy());
16967 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
16968 : diag::warn_cast_nonnull_to_bool;
16969 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
16970 << E->getSourceRange() << Range << IsEqual;
16971 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
16972 };
16973
16974 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
16975 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
16976 if (auto *Callee = Call->getDirectCallee()) {
16977 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
16978 ComplainAboutNonnullParamOrCall(A);
16979 return;
16980 }
16981 }
16982 }
16983
16984 // Complain if we are converting a lambda expression to a boolean value
16985 // outside of instantiation.
16986 if (!inTemplateInstantiation()) {
16987 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
16988 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
16989 MRecordDecl && MRecordDecl->isLambda()) {
16990 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
16991 << /*LambdaPointerConversionOperatorType=*/3
16992 << MRecordDecl->getSourceRange() << Range << IsEqual;
16993 return;
16994 }
16995 }
16996 }
16997
16998 // Expect to find a single Decl. Skip anything more complicated.
16999 ValueDecl *D = nullptr;
17000 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
17001 D = R->getDecl();
17002 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
17003 D = M->getMemberDecl();
17004 }
17005
17006 // Weak Decls can be null.
17007 if (!D || D->isWeak())
17008 return;
17009
17010 // Check for parameter decl with nonnull attribute
17011 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
17012 if (getCurFunction() &&
17013 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
17014 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
17015 ComplainAboutNonnullParamOrCall(A);
17016 return;
17017 }
17018
17019 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
17020 // Skip function template not specialized yet.
17022 return;
17023 auto ParamIter = llvm::find(FD->parameters(), PV);
17024 assert(ParamIter != FD->param_end());
17025 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
17026
17027 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
17028 if (!NonNull->args_size()) {
17029 ComplainAboutNonnullParamOrCall(NonNull);
17030 return;
17031 }
17032
17033 for (const ParamIdx &ArgNo : NonNull->args()) {
17034 if (ArgNo.getASTIndex() == ParamNo) {
17035 ComplainAboutNonnullParamOrCall(NonNull);
17036 return;
17037 }
17038 }
17039 }
17040 }
17041 }
17042 }
17043
17044 QualType T = D->getType();
17045 const bool IsArray = T->isArrayType();
17046 const bool IsFunction = T->isFunctionType();
17047
17048 // Address of function is used to silence the function warning.
17049 if (IsAddressOf && IsFunction) {
17050 return;
17051 }
17052
17053 // Found nothing.
17054 if (!IsAddressOf && !IsFunction && !IsArray)
17055 return;
17056
17057 // Pretty print the expression for the diagnostic.
17058 std::string Str;
17059 llvm::raw_string_ostream S(Str);
17060 E->printPretty(S, nullptr, getPrintingPolicy());
17061
17062 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
17063 : diag::warn_impcast_pointer_to_bool;
17064 enum {
17065 AddressOf,
17066 FunctionPointer,
17067 ArrayPointer
17068 } DiagType;
17069 if (IsAddressOf)
17070 DiagType = AddressOf;
17071 else if (IsFunction)
17072 DiagType = FunctionPointer;
17073 else if (IsArray)
17074 DiagType = ArrayPointer;
17075 else
17076 llvm_unreachable("Could not determine diagnostic.");
17077 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
17078 << Range << IsEqual;
17079
17080 if (!IsFunction)
17081 return;
17082
17083 // Suggest '&' to silence the function warning.
17084 Diag(E->getExprLoc(), diag::note_function_warning_silence)
17086
17087 // Check to see if '()' fixit should be emitted.
17088 QualType ReturnType;
17089 UnresolvedSet<4> NonTemplateOverloads;
17090 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
17091 if (ReturnType.isNull())
17092 return;
17093
17094 if (IsCompare) {
17095 // There are two cases here. If there is null constant, the only suggest
17096 // for a pointer return type. If the null is 0, then suggest if the return
17097 // type is a pointer or an integer type.
17098 if (!ReturnType->isPointerType()) {
17099 if (NullKind == Expr::NPCK_ZeroExpression ||
17100 NullKind == Expr::NPCK_ZeroLiteral) {
17101 if (!ReturnType->isIntegerType())
17102 return;
17103 } else {
17104 return;
17105 }
17106 }
17107 } else { // !IsCompare
17108 // For function to bool, only suggest if the function pointer has bool
17109 // return type.
17110 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
17111 return;
17112 }
17113 Diag(E->getExprLoc(), diag::note_function_to_function_call)
17115}
17116
17117/// Diagnoses "dangerous" implicit conversions within the given
17118/// expression (which is a full expression). Implements -Wconversion
17119/// and -Wsign-compare.
17120///
17121/// \param CC the "context" location of the implicit conversion, i.e.
17122/// the most location of the syntactic entity requiring the implicit
17123/// conversion
17124void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
17125 // Don't diagnose in unevaluated contexts.
17127 return;
17128
17129 // Don't diagnose for value- or type-dependent expressions.
17130 if (E->isTypeDependent() || E->isValueDependent())
17131 return;
17132
17133 // Check for array bounds violations in cases where the check isn't triggered
17134 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
17135 // ArraySubscriptExpr is on the RHS of a variable initialization.
17136 CheckArrayAccess(E);
17137
17138 // This is not the right CC for (e.g.) a variable initialization.
17139 AnalyzeImplicitConversions(*this, E, CC);
17140}
17141
17142/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
17143/// Input argument E is a logical expression.
17144void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
17145 ::CheckBoolLikeConversion(*this, E, CC);
17146}
17147
17148/// Diagnose when expression is an integer constant expression and its evaluation
17149/// results in integer overflow
17150void Sema::CheckForIntOverflow (const Expr *E) {
17151 // Use a work list to deal with nested struct initializers.
17152 SmallVector<const Expr *, 2> Exprs(1, E);
17153
17154 do {
17155 const Expr *OriginalE = Exprs.pop_back_val();
17156 const Expr *E = OriginalE->IgnoreParenCasts();
17157
17158 if (isa<BinaryOperator, UnaryOperator>(E)) {
17160 continue;
17161 }
17162
17163 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
17164 Exprs.append(InitList->inits().begin(), InitList->inits().end());
17165 else if (isa<ObjCBoxedExpr>(OriginalE))
17167 else if (const auto *Call = dyn_cast<CallExpr>(E))
17168 Exprs.append(Call->arg_begin(), Call->arg_end());
17169 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
17170 Exprs.append(Message->arg_begin(), Message->arg_end());
17171 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
17172 Exprs.append(Construct->arg_begin(), Construct->arg_end());
17173 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
17174 Exprs.push_back(Temporary->getSubExpr());
17175 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
17176 Exprs.push_back(Array->getIdx());
17177 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
17178 Exprs.push_back(Compound->getInitializer());
17179 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
17180 New && New->isArray()) {
17181 if (auto ArraySize = New->getArraySize())
17182 Exprs.push_back(*ArraySize);
17183 }
17184 } while (!Exprs.empty());
17185}
17186
17187namespace {
17188
17189/// Visitor for expressions which looks for unsequenced operations on the
17190/// same object.
17191class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
17193
17194 /// A tree of sequenced regions within an expression. Two regions are
17195 /// unsequenced if one is an ancestor or a descendent of the other. When we
17196 /// finish processing an expression with sequencing, such as a comma
17197 /// expression, we fold its tree nodes into its parent, since they are
17198 /// unsequenced with respect to nodes we will visit later.
17199 class SequenceTree {
17200 struct Value {
17201 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
17202 unsigned Parent : 31;
17203 LLVM_PREFERRED_TYPE(bool)
17204 unsigned Merged : 1;
17205 };
17206 SmallVector<Value, 8> Values;
17207
17208 public:
17209 /// A region within an expression which may be sequenced with respect
17210 /// to some other region.
17211 class Seq {
17212 friend class SequenceTree;
17213
17214 unsigned Index;
17215
17216 explicit Seq(unsigned N) : Index(N) {}
17217
17218 public:
17219 Seq() : Index(0) {}
17220 };
17221
17222 SequenceTree() { Values.push_back(Value(0)); }
17223 Seq root() const { return Seq(0); }
17224
17225 /// Create a new sequence of operations, which is an unsequenced
17226 /// subset of \p Parent. This sequence of operations is sequenced with
17227 /// respect to other children of \p Parent.
17228 Seq allocate(Seq Parent) {
17229 Values.push_back(Value(Parent.Index));
17230 return Seq(Values.size() - 1);
17231 }
17232
17233 /// Merge a sequence of operations into its parent.
17234 void merge(Seq S) {
17235 Values[S.Index].Merged = true;
17236 }
17237
17238 /// Determine whether two operations are unsequenced. This operation
17239 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
17240 /// should have been merged into its parent as appropriate.
17241 bool isUnsequenced(Seq Cur, Seq Old) {
17242 unsigned C = representative(Cur.Index);
17243 unsigned Target = representative(Old.Index);
17244 while (C >= Target) {
17245 if (C == Target)
17246 return true;
17247 C = Values[C].Parent;
17248 }
17249 return false;
17250 }
17251
17252 private:
17253 /// Pick a representative for a sequence.
17254 unsigned representative(unsigned K) {
17255 if (Values[K].Merged)
17256 // Perform path compression as we go.
17257 return Values[K].Parent = representative(Values[K].Parent);
17258 return K;
17259 }
17260 };
17261
17262 /// An object for which we can track unsequenced uses.
17263 using Object = const NamedDecl *;
17264
17265 /// Different flavors of object usage which we track. We only track the
17266 /// least-sequenced usage of each kind.
17267 enum UsageKind {
17268 /// A read of an object. Multiple unsequenced reads are OK.
17269 UK_Use,
17270
17271 /// A modification of an object which is sequenced before the value
17272 /// computation of the expression, such as ++n in C++.
17273 UK_ModAsValue,
17274
17275 /// A modification of an object which is not sequenced before the value
17276 /// computation of the expression, such as n++.
17277 UK_ModAsSideEffect,
17278
17279 UK_Count = UK_ModAsSideEffect + 1
17280 };
17281
17282 /// Bundle together a sequencing region and the expression corresponding
17283 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
17284 struct Usage {
17285 const Expr *UsageExpr = nullptr;
17286 SequenceTree::Seq Seq;
17287
17288 Usage() = default;
17289 };
17290
17291 struct UsageInfo {
17292 Usage Uses[UK_Count];
17293
17294 /// Have we issued a diagnostic for this object already?
17295 bool Diagnosed = false;
17296
17297 UsageInfo();
17298 };
17299 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
17300
17301 Sema &SemaRef;
17302
17303 /// Sequenced regions within the expression.
17304 SequenceTree Tree;
17305
17306 /// Declaration modifications and references which we have seen.
17307 UsageInfoMap UsageMap;
17308
17309 /// The region we are currently within.
17310 SequenceTree::Seq Region;
17311
17312 /// Filled in with declarations which were modified as a side-effect
17313 /// (that is, post-increment operations).
17314 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
17315
17316 /// Expressions to check later. We defer checking these to reduce
17317 /// stack usage.
17319
17320 /// RAII object wrapping the visitation of a sequenced subexpression of an
17321 /// expression. At the end of this process, the side-effects of the evaluation
17322 /// become sequenced with respect to the value computation of the result, so
17323 /// we downgrade any UK_ModAsSideEffect within the evaluation to
17324 /// UK_ModAsValue.
17325 struct SequencedSubexpression {
17326 SequencedSubexpression(SequenceChecker &Self)
17327 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
17328 Self.ModAsSideEffect = &ModAsSideEffect;
17329 }
17330
17331 ~SequencedSubexpression() {
17332 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
17333 // Add a new usage with usage kind UK_ModAsValue, and then restore
17334 // the previous usage with UK_ModAsSideEffect (thus clearing it if
17335 // the previous one was empty).
17336 UsageInfo &UI = Self.UsageMap[M.first];
17337 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
17338 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
17339 SideEffectUsage = M.second;
17340 }
17341 Self.ModAsSideEffect = OldModAsSideEffect;
17342 }
17343
17344 SequenceChecker &Self;
17345 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
17346 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
17347 };
17348
17349 /// RAII object wrapping the visitation of a subexpression which we might
17350 /// choose to evaluate as a constant. If any subexpression is evaluated and
17351 /// found to be non-constant, this allows us to suppress the evaluation of
17352 /// the outer expression.
17353 class EvaluationTracker {
17354 public:
17355 EvaluationTracker(SequenceChecker &Self)
17356 : Self(Self), Prev(Self.EvalTracker) {
17357 Self.EvalTracker = this;
17358 }
17359
17360 ~EvaluationTracker() {
17361 Self.EvalTracker = Prev;
17362 if (Prev)
17363 Prev->EvalOK &= EvalOK;
17364 }
17365
17366 bool evaluate(const Expr *E, bool &Result) {
17367 if (!EvalOK || E->isValueDependent())
17368 return false;
17369 EvalOK = E->EvaluateAsBooleanCondition(
17370 Result, Self.SemaRef.Context,
17371 Self.SemaRef.isConstantEvaluatedContext());
17372 return EvalOK;
17373 }
17374
17375 private:
17376 SequenceChecker &Self;
17377 EvaluationTracker *Prev;
17378 bool EvalOK = true;
17379 } *EvalTracker = nullptr;
17380
17381 /// Find the object which is produced by the specified expression,
17382 /// if any.
17383 Object getObject(const Expr *E, bool Mod) const {
17384 E = E->IgnoreParenCasts();
17385 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
17386 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
17387 return getObject(UO->getSubExpr(), Mod);
17388 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
17389 if (BO->getOpcode() == BO_Comma)
17390 return getObject(BO->getRHS(), Mod);
17391 if (Mod && BO->isAssignmentOp())
17392 return getObject(BO->getLHS(), Mod);
17393 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
17394 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
17395 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
17396 return ME->getMemberDecl();
17397 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
17398 // FIXME: If this is a reference, map through to its value.
17399 return DRE->getDecl();
17400 return nullptr;
17401 }
17402
17403 /// Note that an object \p O was modified or used by an expression
17404 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
17405 /// the object \p O as obtained via the \p UsageMap.
17406 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
17407 // Get the old usage for the given object and usage kind.
17408 Usage &U = UI.Uses[UK];
17409 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
17410 // If we have a modification as side effect and are in a sequenced
17411 // subexpression, save the old Usage so that we can restore it later
17412 // in SequencedSubexpression::~SequencedSubexpression.
17413 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
17414 ModAsSideEffect->push_back(std::make_pair(O, U));
17415 // Then record the new usage with the current sequencing region.
17416 U.UsageExpr = UsageExpr;
17417 U.Seq = Region;
17418 }
17419 }
17420
17421 /// Check whether a modification or use of an object \p O in an expression
17422 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
17423 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
17424 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
17425 /// usage and false we are checking for a mod-use unsequenced usage.
17426 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
17427 UsageKind OtherKind, bool IsModMod) {
17428 if (UI.Diagnosed)
17429 return;
17430
17431 const Usage &U = UI.Uses[OtherKind];
17432 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
17433 return;
17434
17435 const Expr *Mod = U.UsageExpr;
17436 const Expr *ModOrUse = UsageExpr;
17437 if (OtherKind == UK_Use)
17438 std::swap(Mod, ModOrUse);
17439
17440 SemaRef.DiagRuntimeBehavior(
17441 Mod->getExprLoc(), {Mod, ModOrUse},
17442 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
17443 : diag::warn_unsequenced_mod_use)
17444 << O << SourceRange(ModOrUse->getExprLoc()));
17445 UI.Diagnosed = true;
17446 }
17447
17448 // A note on note{Pre, Post}{Use, Mod}:
17449 //
17450 // (It helps to follow the algorithm with an expression such as
17451 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
17452 // operations before C++17 and both are well-defined in C++17).
17453 //
17454 // When visiting a node which uses/modify an object we first call notePreUse
17455 // or notePreMod before visiting its sub-expression(s). At this point the
17456 // children of the current node have not yet been visited and so the eventual
17457 // uses/modifications resulting from the children of the current node have not
17458 // been recorded yet.
17459 //
17460 // We then visit the children of the current node. After that notePostUse or
17461 // notePostMod is called. These will 1) detect an unsequenced modification
17462 // as side effect (as in "k++ + k") and 2) add a new usage with the
17463 // appropriate usage kind.
17464 //
17465 // We also have to be careful that some operation sequences modification as
17466 // side effect as well (for example: || or ,). To account for this we wrap
17467 // the visitation of such a sub-expression (for example: the LHS of || or ,)
17468 // with SequencedSubexpression. SequencedSubexpression is an RAII object
17469 // which record usages which are modifications as side effect, and then
17470 // downgrade them (or more accurately restore the previous usage which was a
17471 // modification as side effect) when exiting the scope of the sequenced
17472 // subexpression.
17473
17474 void notePreUse(Object O, const Expr *UseExpr) {
17475 UsageInfo &UI = UsageMap[O];
17476 // Uses conflict with other modifications.
17477 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
17478 }
17479
17480 void notePostUse(Object O, const Expr *UseExpr) {
17481 UsageInfo &UI = UsageMap[O];
17482 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
17483 /*IsModMod=*/false);
17484 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
17485 }
17486
17487 void notePreMod(Object O, const Expr *ModExpr) {
17488 UsageInfo &UI = UsageMap[O];
17489 // Modifications conflict with other modifications and with uses.
17490 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
17491 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
17492 }
17493
17494 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
17495 UsageInfo &UI = UsageMap[O];
17496 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
17497 /*IsModMod=*/true);
17498 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
17499 }
17500
17501public:
17502 SequenceChecker(Sema &S, const Expr *E,
17504 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
17505 Visit(E);
17506 // Silence a -Wunused-private-field since WorkList is now unused.
17507 // TODO: Evaluate if it can be used, and if not remove it.
17508 (void)this->WorkList;
17509 }
17510
17511 void VisitStmt(const Stmt *S) {
17512 // Skip all statements which aren't expressions for now.
17513 }
17514
17515 void VisitExpr(const Expr *E) {
17516 // By default, just recurse to evaluated subexpressions.
17517 Base::VisitStmt(E);
17518 }
17519
17520 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
17521 for (auto *Sub : CSE->children()) {
17522 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
17523 if (!ChildExpr)
17524 continue;
17525
17526 if (ChildExpr == CSE->getOperand())
17527 // Do not recurse over a CoroutineSuspendExpr's operand.
17528 // The operand is also a subexpression of getCommonExpr(), and
17529 // recursing into it directly could confuse object management
17530 // for the sake of sequence tracking.
17531 continue;
17532
17533 Visit(Sub);
17534 }
17535 }
17536
17537 void VisitCastExpr(const CastExpr *E) {
17538 Object O = Object();
17539 if (E->getCastKind() == CK_LValueToRValue)
17540 O = getObject(E->getSubExpr(), false);
17541
17542 if (O)
17543 notePreUse(O, E);
17544 VisitExpr(E);
17545 if (O)
17546 notePostUse(O, E);
17547 }
17548
17549 void VisitSequencedExpressions(const Expr *SequencedBefore,
17550 const Expr *SequencedAfter) {
17551 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
17552 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
17553 SequenceTree::Seq OldRegion = Region;
17554
17555 {
17556 SequencedSubexpression SeqBefore(*this);
17557 Region = BeforeRegion;
17558 Visit(SequencedBefore);
17559 }
17560
17561 Region = AfterRegion;
17562 Visit(SequencedAfter);
17563
17564 Region = OldRegion;
17565
17566 Tree.merge(BeforeRegion);
17567 Tree.merge(AfterRegion);
17568 }
17569
17570 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
17571 // C++17 [expr.sub]p1:
17572 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
17573 // expression E1 is sequenced before the expression E2.
17574 if (SemaRef.getLangOpts().CPlusPlus17)
17575 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
17576 else {
17577 Visit(ASE->getLHS());
17578 Visit(ASE->getRHS());
17579 }
17580 }
17581
17582 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
17583 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
17584 void VisitBinPtrMem(const BinaryOperator *BO) {
17585 // C++17 [expr.mptr.oper]p4:
17586 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
17587 // the expression E1 is sequenced before the expression E2.
17588 if (SemaRef.getLangOpts().CPlusPlus17)
17589 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
17590 else {
17591 Visit(BO->getLHS());
17592 Visit(BO->getRHS());
17593 }
17594 }
17595
17596 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
17597 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
17598 void VisitBinShlShr(const BinaryOperator *BO) {
17599 // C++17 [expr.shift]p4:
17600 // The expression E1 is sequenced before the expression E2.
17601 if (SemaRef.getLangOpts().CPlusPlus17)
17602 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
17603 else {
17604 Visit(BO->getLHS());
17605 Visit(BO->getRHS());
17606 }
17607 }
17608
17609 void VisitBinComma(const BinaryOperator *BO) {
17610 // C++11 [expr.comma]p1:
17611 // Every value computation and side effect associated with the left
17612 // expression is sequenced before every value computation and side
17613 // effect associated with the right expression.
17614 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
17615 }
17616
17617 void VisitBinAssign(const BinaryOperator *BO) {
17618 SequenceTree::Seq RHSRegion;
17619 SequenceTree::Seq LHSRegion;
17620 if (SemaRef.getLangOpts().CPlusPlus17) {
17621 RHSRegion = Tree.allocate(Region);
17622 LHSRegion = Tree.allocate(Region);
17623 } else {
17624 RHSRegion = Region;
17625 LHSRegion = Region;
17626 }
17627 SequenceTree::Seq OldRegion = Region;
17628
17629 // C++11 [expr.ass]p1:
17630 // [...] the assignment is sequenced after the value computation
17631 // of the right and left operands, [...]
17632 //
17633 // so check it before inspecting the operands and update the
17634 // map afterwards.
17635 Object O = getObject(BO->getLHS(), /*Mod=*/true);
17636 if (O)
17637 notePreMod(O, BO);
17638
17639 if (SemaRef.getLangOpts().CPlusPlus17) {
17640 // C++17 [expr.ass]p1:
17641 // [...] The right operand is sequenced before the left operand. [...]
17642 {
17643 SequencedSubexpression SeqBefore(*this);
17644 Region = RHSRegion;
17645 Visit(BO->getRHS());
17646 }
17647
17648 Region = LHSRegion;
17649 Visit(BO->getLHS());
17650
17651 if (O && isa<CompoundAssignOperator>(BO))
17652 notePostUse(O, BO);
17653
17654 } else {
17655 // C++11 does not specify any sequencing between the LHS and RHS.
17656 Region = LHSRegion;
17657 Visit(BO->getLHS());
17658
17659 if (O && isa<CompoundAssignOperator>(BO))
17660 notePostUse(O, BO);
17661
17662 Region = RHSRegion;
17663 Visit(BO->getRHS());
17664 }
17665
17666 // C++11 [expr.ass]p1:
17667 // the assignment is sequenced [...] before the value computation of the
17668 // assignment expression.
17669 // C11 6.5.16/3 has no such rule.
17670 Region = OldRegion;
17671 if (O)
17672 notePostMod(O, BO,
17673 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
17674 : UK_ModAsSideEffect);
17675 if (SemaRef.getLangOpts().CPlusPlus17) {
17676 Tree.merge(RHSRegion);
17677 Tree.merge(LHSRegion);
17678 }
17679 }
17680
17681 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
17682 VisitBinAssign(CAO);
17683 }
17684
17685 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
17686 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
17687 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
17688 Object O = getObject(UO->getSubExpr(), true);
17689 if (!O)
17690 return VisitExpr(UO);
17691
17692 notePreMod(O, UO);
17693 Visit(UO->getSubExpr());
17694 // C++11 [expr.pre.incr]p1:
17695 // the expression ++x is equivalent to x+=1
17696 notePostMod(O, UO,
17697 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
17698 : UK_ModAsSideEffect);
17699 }
17700
17701 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
17702 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
17703 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
17704 Object O = getObject(UO->getSubExpr(), true);
17705 if (!O)
17706 return VisitExpr(UO);
17707
17708 notePreMod(O, UO);
17709 Visit(UO->getSubExpr());
17710 notePostMod(O, UO, UK_ModAsSideEffect);
17711 }
17712
17713 void VisitBinLOr(const BinaryOperator *BO) {
17714 // C++11 [expr.log.or]p2:
17715 // If the second expression is evaluated, every value computation and
17716 // side effect associated with the first expression is sequenced before
17717 // every value computation and side effect associated with the
17718 // second expression.
17719 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
17720 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
17721 SequenceTree::Seq OldRegion = Region;
17722
17723 EvaluationTracker Eval(*this);
17724 {
17725 SequencedSubexpression Sequenced(*this);
17726 Region = LHSRegion;
17727 Visit(BO->getLHS());
17728 }
17729
17730 // C++11 [expr.log.or]p1:
17731 // [...] the second operand is not evaluated if the first operand
17732 // evaluates to true.
17733 bool EvalResult = false;
17734 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
17735 bool ShouldVisitRHS = !EvalOK || !EvalResult;
17736 if (ShouldVisitRHS) {
17737 Region = RHSRegion;
17738 Visit(BO->getRHS());
17739 }
17740
17741 Region = OldRegion;
17742 Tree.merge(LHSRegion);
17743 Tree.merge(RHSRegion);
17744 }
17745
17746 void VisitBinLAnd(const BinaryOperator *BO) {
17747 // C++11 [expr.log.and]p2:
17748 // If the second expression is evaluated, every value computation and
17749 // side effect associated with the first expression is sequenced before
17750 // every value computation and side effect associated with the
17751 // second expression.
17752 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
17753 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
17754 SequenceTree::Seq OldRegion = Region;
17755
17756 EvaluationTracker Eval(*this);
17757 {
17758 SequencedSubexpression Sequenced(*this);
17759 Region = LHSRegion;
17760 Visit(BO->getLHS());
17761 }
17762
17763 // C++11 [expr.log.and]p1:
17764 // [...] the second operand is not evaluated if the first operand is false.
17765 bool EvalResult = false;
17766 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
17767 bool ShouldVisitRHS = !EvalOK || EvalResult;
17768 if (ShouldVisitRHS) {
17769 Region = RHSRegion;
17770 Visit(BO->getRHS());
17771 }
17772
17773 Region = OldRegion;
17774 Tree.merge(LHSRegion);
17775 Tree.merge(RHSRegion);
17776 }
17777
17778 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
17779 // C++11 [expr.cond]p1:
17780 // [...] Every value computation and side effect associated with the first
17781 // expression is sequenced before every value computation and side effect
17782 // associated with the second or third expression.
17783 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
17784
17785 // No sequencing is specified between the true and false expression.
17786 // However since exactly one of both is going to be evaluated we can
17787 // consider them to be sequenced. This is needed to avoid warning on
17788 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
17789 // both the true and false expressions because we can't evaluate x.
17790 // This will still allow us to detect an expression like (pre C++17)
17791 // "(x ? y += 1 : y += 2) = y".
17792 //
17793 // We don't wrap the visitation of the true and false expression with
17794 // SequencedSubexpression because we don't want to downgrade modifications
17795 // as side effect in the true and false expressions after the visition
17796 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
17797 // not warn between the two "y++", but we should warn between the "y++"
17798 // and the "y".
17799 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
17800 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
17801 SequenceTree::Seq OldRegion = Region;
17802
17803 EvaluationTracker Eval(*this);
17804 {
17805 SequencedSubexpression Sequenced(*this);
17806 Region = ConditionRegion;
17807 Visit(CO->getCond());
17808 }
17809
17810 // C++11 [expr.cond]p1:
17811 // [...] The first expression is contextually converted to bool (Clause 4).
17812 // It is evaluated and if it is true, the result of the conditional
17813 // expression is the value of the second expression, otherwise that of the
17814 // third expression. Only one of the second and third expressions is
17815 // evaluated. [...]
17816 bool EvalResult = false;
17817 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
17818 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
17819 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
17820 if (ShouldVisitTrueExpr) {
17821 Region = TrueRegion;
17822 Visit(CO->getTrueExpr());
17823 }
17824 if (ShouldVisitFalseExpr) {
17825 Region = FalseRegion;
17826 Visit(CO->getFalseExpr());
17827 }
17828
17829 Region = OldRegion;
17830 Tree.merge(ConditionRegion);
17831 Tree.merge(TrueRegion);
17832 Tree.merge(FalseRegion);
17833 }
17834
17835 void VisitCallExpr(const CallExpr *CE) {
17836 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
17837
17838 if (CE->isUnevaluatedBuiltinCall(Context))
17839 return;
17840
17841 // C++11 [intro.execution]p15:
17842 // When calling a function [...], every value computation and side effect
17843 // associated with any argument expression, or with the postfix expression
17844 // designating the called function, is sequenced before execution of every
17845 // expression or statement in the body of the function [and thus before
17846 // the value computation of its result].
17847 SequencedSubexpression Sequenced(*this);
17848 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
17849 // C++17 [expr.call]p5
17850 // The postfix-expression is sequenced before each expression in the
17851 // expression-list and any default argument. [...]
17852 SequenceTree::Seq CalleeRegion;
17853 SequenceTree::Seq OtherRegion;
17854 if (SemaRef.getLangOpts().CPlusPlus17) {
17855 CalleeRegion = Tree.allocate(Region);
17856 OtherRegion = Tree.allocate(Region);
17857 } else {
17858 CalleeRegion = Region;
17859 OtherRegion = Region;
17860 }
17861 SequenceTree::Seq OldRegion = Region;
17862
17863 // Visit the callee expression first.
17864 Region = CalleeRegion;
17865 if (SemaRef.getLangOpts().CPlusPlus17) {
17866 SequencedSubexpression Sequenced(*this);
17867 Visit(CE->getCallee());
17868 } else {
17869 Visit(CE->getCallee());
17870 }
17871
17872 // Then visit the argument expressions.
17873 Region = OtherRegion;
17874 for (const Expr *Argument : CE->arguments())
17875 Visit(Argument);
17876
17877 Region = OldRegion;
17878 if (SemaRef.getLangOpts().CPlusPlus17) {
17879 Tree.merge(CalleeRegion);
17880 Tree.merge(OtherRegion);
17881 }
17882 });
17883 }
17884
17885 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
17886 // C++17 [over.match.oper]p2:
17887 // [...] the operator notation is first transformed to the equivalent
17888 // function-call notation as summarized in Table 12 (where @ denotes one
17889 // of the operators covered in the specified subclause). However, the
17890 // operands are sequenced in the order prescribed for the built-in
17891 // operator (Clause 8).
17892 //
17893 // From the above only overloaded binary operators and overloaded call
17894 // operators have sequencing rules in C++17 that we need to handle
17895 // separately.
17896 if (!SemaRef.getLangOpts().CPlusPlus17 ||
17897 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
17898 return VisitCallExpr(CXXOCE);
17899
17900 enum {
17901 NoSequencing,
17902 LHSBeforeRHS,
17903 RHSBeforeLHS,
17904 LHSBeforeRest
17905 } SequencingKind;
17906 switch (CXXOCE->getOperator()) {
17907 case OO_Equal:
17908 case OO_PlusEqual:
17909 case OO_MinusEqual:
17910 case OO_StarEqual:
17911 case OO_SlashEqual:
17912 case OO_PercentEqual:
17913 case OO_CaretEqual:
17914 case OO_AmpEqual:
17915 case OO_PipeEqual:
17916 case OO_LessLessEqual:
17917 case OO_GreaterGreaterEqual:
17918 SequencingKind = RHSBeforeLHS;
17919 break;
17920
17921 case OO_LessLess:
17922 case OO_GreaterGreater:
17923 case OO_AmpAmp:
17924 case OO_PipePipe:
17925 case OO_Comma:
17926 case OO_ArrowStar:
17927 case OO_Subscript:
17928 SequencingKind = LHSBeforeRHS;
17929 break;
17930
17931 case OO_Call:
17932 SequencingKind = LHSBeforeRest;
17933 break;
17934
17935 default:
17936 SequencingKind = NoSequencing;
17937 break;
17938 }
17939
17940 if (SequencingKind == NoSequencing)
17941 return VisitCallExpr(CXXOCE);
17942
17943 // This is a call, so all subexpressions are sequenced before the result.
17944 SequencedSubexpression Sequenced(*this);
17945
17946 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
17947 assert(SemaRef.getLangOpts().CPlusPlus17 &&
17948 "Should only get there with C++17 and above!");
17949 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
17950 "Should only get there with an overloaded binary operator"
17951 " or an overloaded call operator!");
17952
17953 if (SequencingKind == LHSBeforeRest) {
17954 assert(CXXOCE->getOperator() == OO_Call &&
17955 "We should only have an overloaded call operator here!");
17956
17957 // This is very similar to VisitCallExpr, except that we only have the
17958 // C++17 case. The postfix-expression is the first argument of the
17959 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
17960 // are in the following arguments.
17961 //
17962 // Note that we intentionally do not visit the callee expression since
17963 // it is just a decayed reference to a function.
17964 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
17965 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
17966 SequenceTree::Seq OldRegion = Region;
17967
17968 assert(CXXOCE->getNumArgs() >= 1 &&
17969 "An overloaded call operator must have at least one argument"
17970 " for the postfix-expression!");
17971 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
17972 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
17973 CXXOCE->getNumArgs() - 1);
17974
17975 // Visit the postfix-expression first.
17976 {
17977 Region = PostfixExprRegion;
17978 SequencedSubexpression Sequenced(*this);
17979 Visit(PostfixExpr);
17980 }
17981
17982 // Then visit the argument expressions.
17983 Region = ArgsRegion;
17984 for (const Expr *Arg : Args)
17985 Visit(Arg);
17986
17987 Region = OldRegion;
17988 Tree.merge(PostfixExprRegion);
17989 Tree.merge(ArgsRegion);
17990 } else {
17991 assert(CXXOCE->getNumArgs() == 2 &&
17992 "Should only have two arguments here!");
17993 assert((SequencingKind == LHSBeforeRHS ||
17994 SequencingKind == RHSBeforeLHS) &&
17995 "Unexpected sequencing kind!");
17996
17997 // We do not visit the callee expression since it is just a decayed
17998 // reference to a function.
17999 const Expr *E1 = CXXOCE->getArg(0);
18000 const Expr *E2 = CXXOCE->getArg(1);
18001 if (SequencingKind == RHSBeforeLHS)
18002 std::swap(E1, E2);
18003
18004 return VisitSequencedExpressions(E1, E2);
18005 }
18006 });
18007 }
18008
18009 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
18010 // This is a call, so all subexpressions are sequenced before the result.
18011 SequencedSubexpression Sequenced(*this);
18012
18013 if (!CCE->isListInitialization())
18014 return VisitExpr(CCE);
18015
18016 // In C++11, list initializations are sequenced.
18017 SequenceExpressionsInOrder(
18018 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
18019 }
18020
18021 void VisitInitListExpr(const InitListExpr *ILE) {
18022 if (!SemaRef.getLangOpts().CPlusPlus11)
18023 return VisitExpr(ILE);
18024
18025 // In C++11, list initializations are sequenced.
18026 SequenceExpressionsInOrder(ILE->inits());
18027 }
18028
18029 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
18030 // C++20 parenthesized list initializations are sequenced. See C++20
18031 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
18032 SequenceExpressionsInOrder(PLIE->getInitExprs());
18033 }
18034
18035private:
18036 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
18038 SequenceTree::Seq Parent = Region;
18039 for (const Expr *E : ExpressionList) {
18040 if (!E)
18041 continue;
18042 Region = Tree.allocate(Parent);
18043 Elts.push_back(Region);
18044 Visit(E);
18045 }
18046
18047 // Forget that the initializers are sequenced.
18048 Region = Parent;
18049 for (unsigned I = 0; I < Elts.size(); ++I)
18050 Tree.merge(Elts[I]);
18051 }
18052};
18053
18054SequenceChecker::UsageInfo::UsageInfo() = default;
18055
18056} // namespace
18057
18058void Sema::CheckUnsequencedOperations(const Expr *E) {
18060 WorkList.push_back(E);
18061 while (!WorkList.empty()) {
18062 const Expr *Item = WorkList.pop_back_val();
18063 SequenceChecker(*this, Item, WorkList);
18064 }
18065}
18066
18067void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
18068 bool IsConstexpr) {
18070 IsConstexpr || isa<ConstantExpr>(E));
18071 CheckImplicitConversions(E, CheckLoc);
18072 if (!E->isInstantiationDependent())
18073 CheckUnsequencedOperations(E);
18074 if (!IsConstexpr && !E->isValueDependent())
18075 CheckForIntOverflow(E);
18077}
18078
18079void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
18080 FieldDecl *BitField,
18081 Expr *Init) {
18082 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
18083}
18084
18087 if (!PType->isVariablyModifiedType())
18088 return;
18089 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
18090 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
18091 return;
18092 }
18093 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
18094 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
18095 return;
18096 }
18097 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
18098 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
18099 return;
18100 }
18101
18102 const ArrayType *AT = S.Context.getAsArrayType(PType);
18103 if (!AT)
18104 return;
18105
18108 return;
18109 }
18110
18111 S.Diag(Loc, diag::err_array_star_in_function_definition);
18112}
18113
18114/// CheckParmsForFunctionDef - Check that the parameters of the given
18115/// function are appropriate for the definition of a function. This
18116/// takes care of any checks that cannot be performed on the
18117/// declaration itself, e.g., that the types of each of the function
18118/// parameters are complete.
18120 bool CheckParameterNames) {
18121 bool HasInvalidParm = false;
18122 for (ParmVarDecl *Param : Parameters) {
18123 assert(Param && "null in a parameter list");
18124 // C99 6.7.5.3p4: the parameters in a parameter type list in a
18125 // function declarator that is part of a function definition of
18126 // that function shall not have incomplete type.
18127 //
18128 // C++23 [dcl.fct.def.general]/p2
18129 // The type of a parameter [...] for a function definition
18130 // shall not be a (possibly cv-qualified) class type that is incomplete
18131 // or abstract within the function body unless the function is deleted.
18132 if (!Param->isInvalidDecl() &&
18133 (RequireCompleteType(Param->getLocation(), Param->getType(),
18134 diag::err_typecheck_decl_incomplete_type) ||
18135 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
18136 diag::err_abstract_type_in_decl,
18138 Param->setInvalidDecl();
18139 HasInvalidParm = true;
18140 }
18141
18142 // C99 6.9.1p5: If the declarator includes a parameter type list, the
18143 // declaration of each parameter shall include an identifier.
18144 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
18145 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
18146 // Diagnose this as an extension in C17 and earlier.
18147 if (!getLangOpts().C23)
18148 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
18149 }
18150
18151 // C99 6.7.5.3p12:
18152 // If the function declarator is not part of a definition of that
18153 // function, parameters may have incomplete type and may use the [*]
18154 // notation in their sequences of declarator specifiers to specify
18155 // variable length array types.
18156 QualType PType = Param->getOriginalType();
18157 // FIXME: This diagnostic should point the '[*]' if source-location
18158 // information is added for it.
18159 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
18160
18161 // If the parameter is a c++ class type and it has to be destructed in the
18162 // callee function, declare the destructor so that it can be called by the
18163 // callee function. Do not perform any direct access check on the dtor here.
18164 if (!Param->isInvalidDecl()) {
18165 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
18166 if (!ClassDecl->isInvalidDecl() &&
18167 !ClassDecl->hasIrrelevantDestructor() &&
18168 !ClassDecl->isDependentContext() &&
18169 ClassDecl->isParamDestroyedInCallee()) {
18171 MarkFunctionReferenced(Param->getLocation(), Destructor);
18172 DiagnoseUseOfDecl(Destructor, Param->getLocation());
18173 }
18174 }
18175 }
18176
18177 // Parameters with the pass_object_size attribute only need to be marked
18178 // constant at function definitions. Because we lack information about
18179 // whether we're on a declaration or definition when we're instantiating the
18180 // attribute, we need to check for constness here.
18181 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
18182 if (!Param->getType().isConstQualified())
18183 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
18184 << Attr->getSpelling() << 1;
18185
18186 // Check for parameter names shadowing fields from the class.
18187 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
18188 // The owning context for the parameter should be the function, but we
18189 // want to see if this function's declaration context is a record.
18190 DeclContext *DC = Param->getDeclContext();
18191 if (DC && DC->isFunctionOrMethod()) {
18192 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
18193 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
18194 RD, /*DeclIsField*/ false);
18195 }
18196 }
18197
18198 if (!Param->isInvalidDecl() &&
18199 Param->getOriginalType()->isWebAssemblyTableType()) {
18200 Param->setInvalidDecl();
18201 HasInvalidParm = true;
18202 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
18203 }
18204 }
18205
18206 return HasInvalidParm;
18207}
18208
18209std::optional<std::pair<
18211 *E,
18213 &Ctx);
18214
18215/// Compute the alignment and offset of the base class object given the
18216/// derived-to-base cast expression and the alignment and offset of the derived
18217/// class object.
18218static std::pair<CharUnits, CharUnits>
18220 CharUnits BaseAlignment, CharUnits Offset,
18221 ASTContext &Ctx) {
18222 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
18223 ++PathI) {
18224 const CXXBaseSpecifier *Base = *PathI;
18225 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
18226 if (Base->isVirtual()) {
18227 // The complete object may have a lower alignment than the non-virtual
18228 // alignment of the base, in which case the base may be misaligned. Choose
18229 // the smaller of the non-virtual alignment and BaseAlignment, which is a
18230 // conservative lower bound of the complete object alignment.
18231 CharUnits NonVirtualAlignment =
18233 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
18234 Offset = CharUnits::Zero();
18235 } else {
18236 const ASTRecordLayout &RL =
18237 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
18238 Offset += RL.getBaseClassOffset(BaseDecl);
18239 }
18240 DerivedType = Base->getType();
18241 }
18242
18243 return std::make_pair(BaseAlignment, Offset);
18244}
18245
18246/// Compute the alignment and offset of a binary additive operator.
18247static std::optional<std::pair<CharUnits, CharUnits>>
18249 bool IsSub, ASTContext &Ctx) {
18250 QualType PointeeType = PtrE->getType()->getPointeeType();
18251
18252 if (!PointeeType->isConstantSizeType())
18253 return std::nullopt;
18254
18255 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
18256
18257 if (!P)
18258 return std::nullopt;
18259
18260 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
18261 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
18262 CharUnits Offset = EltSize * IdxRes->getExtValue();
18263 if (IsSub)
18264 Offset = -Offset;
18265 return std::make_pair(P->first, P->second + Offset);
18266 }
18267
18268 // If the integer expression isn't a constant expression, compute the lower
18269 // bound of the alignment using the alignment and offset of the pointer
18270 // expression and the element size.
18271 return std::make_pair(
18272 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
18273 CharUnits::Zero());
18274}
18275
18276/// This helper function takes an lvalue expression and returns the alignment of
18277/// a VarDecl and a constant offset from the VarDecl.
18278std::optional<std::pair<
18279 CharUnits,
18281 ASTContext &Ctx) {
18282 E = E->IgnoreParens();
18283 switch (E->getStmtClass()) {
18284 default:
18285 break;
18286 case Stmt::CStyleCastExprClass:
18287 case Stmt::CXXStaticCastExprClass:
18288 case Stmt::ImplicitCastExprClass: {
18289 auto *CE = cast<CastExpr>(E);
18290 const Expr *From = CE->getSubExpr();
18291 switch (CE->getCastKind()) {
18292 default:
18293 break;
18294 case CK_NoOp:
18295 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
18296 case CK_UncheckedDerivedToBase:
18297 case CK_DerivedToBase: {
18298 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
18299 if (!P)
18300 break;
18301 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
18302 P->second, Ctx);
18303 }
18304 }
18305 break;
18306 }
18307 case Stmt::ArraySubscriptExprClass: {
18308 auto *ASE = cast<ArraySubscriptExpr>(E);
18310 false, Ctx);
18311 }
18312 case Stmt::DeclRefExprClass: {
18313 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
18314 // FIXME: If VD is captured by copy or is an escaping __block variable,
18315 // use the alignment of VD's type.
18316 if (!VD->getType()->isReferenceType()) {
18317 // Dependent alignment cannot be resolved -> bail out.
18318 if (VD->hasDependentAlignment())
18319 break;
18320 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
18321 }
18322 if (VD->hasInit())
18323 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
18324 }
18325 break;
18326 }
18327 case Stmt::MemberExprClass: {
18328 auto *ME = cast<MemberExpr>(E);
18329 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
18330 if (!FD || FD->getType()->isReferenceType() ||
18331 FD->getParent()->isInvalidDecl())
18332 break;
18333 std::optional<std::pair<CharUnits, CharUnits>> P;
18334 if (ME->isArrow())
18335 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
18336 else
18337 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
18338 if (!P)
18339 break;
18340 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
18341 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
18342 return std::make_pair(P->first,
18343 P->second + CharUnits::fromQuantity(Offset));
18344 }
18345 case Stmt::UnaryOperatorClass: {
18346 auto *UO = cast<UnaryOperator>(E);
18347 switch (UO->getOpcode()) {
18348 default:
18349 break;
18350 case UO_Deref:
18352 }
18353 break;
18354 }
18355 case Stmt::BinaryOperatorClass: {
18356 auto *BO = cast<BinaryOperator>(E);
18357 auto Opcode = BO->getOpcode();
18358 switch (Opcode) {
18359 default:
18360 break;
18361 case BO_Comma:
18363 }
18364 break;
18365 }
18366 }
18367 return std::nullopt;
18368}
18369
18370/// This helper function takes a pointer expression and returns the alignment of
18371/// a VarDecl and a constant offset from the VarDecl.
18372std::optional<std::pair<
18374 *E,
18376 &Ctx) {
18377 E = E->IgnoreParens();
18378 switch (E->getStmtClass()) {
18379 default:
18380 break;
18381 case Stmt::CStyleCastExprClass:
18382 case Stmt::CXXStaticCastExprClass:
18383 case Stmt::ImplicitCastExprClass: {
18384 auto *CE = cast<CastExpr>(E);
18385 const Expr *From = CE->getSubExpr();
18386 switch (CE->getCastKind()) {
18387 default:
18388 break;
18389 case CK_NoOp:
18390 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
18391 case CK_ArrayToPointerDecay:
18392 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
18393 case CK_UncheckedDerivedToBase:
18394 case CK_DerivedToBase: {
18395 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
18396 if (!P)
18397 break;
18399 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
18400 }
18401 }
18402 break;
18403 }
18404 case Stmt::CXXThisExprClass: {
18405 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
18407 return std::make_pair(Alignment, CharUnits::Zero());
18408 }
18409 case Stmt::UnaryOperatorClass: {
18410 auto *UO = cast<UnaryOperator>(E);
18411 if (UO->getOpcode() == UO_AddrOf)
18413 break;
18414 }
18415 case Stmt::BinaryOperatorClass: {
18416 auto *BO = cast<BinaryOperator>(E);
18417 auto Opcode = BO->getOpcode();
18418 switch (Opcode) {
18419 default:
18420 break;
18421 case BO_Add:
18422 case BO_Sub: {
18423 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
18424 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
18425 std::swap(LHS, RHS);
18426 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
18427 Ctx);
18428 }
18429 case BO_Comma:
18430 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
18431 }
18432 break;
18433 }
18434 }
18435 return std::nullopt;
18436}
18437
18439 // See if we can compute the alignment of a VarDecl and an offset from it.
18440 std::optional<std::pair<CharUnits, CharUnits>> P =
18442
18443 if (P)
18444 return P->first.alignmentAtOffset(P->second);
18445
18446 // If that failed, return the type's alignment.
18448}
18449
18450/// CheckCastAlign - Implements -Wcast-align, which warns when a
18451/// pointer cast increases the alignment requirements.
18453 // This is actually a lot of work to potentially be doing on every
18454 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
18455 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
18456 return;
18457
18458 // Ignore dependent types.
18459 if (T->isDependentType() || Op->getType()->isDependentType())
18460 return;
18461
18462 // Require that the destination be a pointer type.
18463 const PointerType *DestPtr = T->getAs<PointerType>();
18464 if (!DestPtr) return;
18465
18466 // If the destination has alignment 1, we're done.
18467 QualType DestPointee = DestPtr->getPointeeType();
18468 if (DestPointee->isIncompleteType()) return;
18469 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
18470 if (DestAlign.isOne()) return;
18471
18472 // Require that the source be a pointer type.
18473 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
18474 if (!SrcPtr) return;
18475 QualType SrcPointee = SrcPtr->getPointeeType();
18476
18477 // Explicitly allow casts from cv void*. We already implicitly
18478 // allowed casts to cv void*, since they have alignment 1.
18479 // Also allow casts involving incomplete types, which implicitly
18480 // includes 'void'.
18481 if (SrcPointee->isIncompleteType()) return;
18482
18483 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
18484
18485 if (SrcAlign >= DestAlign) return;
18486
18487 Diag(TRange.getBegin(), diag::warn_cast_align)
18488 << Op->getType() << T
18489 << static_cast<unsigned>(SrcAlign.getQuantity())
18490 << static_cast<unsigned>(DestAlign.getQuantity())
18491 << TRange << Op->getSourceRange();
18492}
18493
18494void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
18495 const ArraySubscriptExpr *ASE,
18496 bool AllowOnePastEnd, bool IndexNegated) {
18497 // Already diagnosed by the constant evaluator.
18499 return;
18500
18501 IndexExpr = IndexExpr->IgnoreParenImpCasts();
18502 if (IndexExpr->isValueDependent())
18503 return;
18504
18505 const Type *EffectiveType =
18507 BaseExpr = BaseExpr->IgnoreParenCasts();
18508 const ConstantArrayType *ArrayTy =
18510
18512 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
18513
18514 const Type *BaseType =
18515 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
18516 bool IsUnboundedArray =
18517 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
18518 Context, StrictFlexArraysLevel,
18519 /*IgnoreTemplateOrMacroSubstitution=*/true);
18520 if (EffectiveType->isDependentType() ||
18521 (!IsUnboundedArray && BaseType->isDependentType()))
18522 return;
18523
18526 return;
18527
18528 llvm::APSInt index = Result.Val.getInt();
18529 if (IndexNegated) {
18530 index.setIsUnsigned(false);
18531 index = -index;
18532 }
18533
18534 if (IsUnboundedArray) {
18535 if (EffectiveType->isFunctionType())
18536 return;
18537 if (index.isUnsigned() || !index.isNegative()) {
18538 const auto &ASTC = getASTContext();
18539 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
18540 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
18541 if (index.getBitWidth() < AddrBits)
18542 index = index.zext(AddrBits);
18543 std::optional<CharUnits> ElemCharUnits =
18544 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
18545 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
18546 // pointer) bounds-checking isn't meaningful.
18547 if (!ElemCharUnits || ElemCharUnits->isZero())
18548 return;
18549 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
18550 // If index has more active bits than address space, we already know
18551 // we have a bounds violation to warn about. Otherwise, compute
18552 // address of (index + 1)th element, and warn about bounds violation
18553 // only if that address exceeds address space.
18554 if (index.getActiveBits() <= AddrBits) {
18555 bool Overflow;
18556 llvm::APInt Product(index);
18557 Product += 1;
18558 Product = Product.umul_ov(ElemBytes, Overflow);
18559 if (!Overflow && Product.getActiveBits() <= AddrBits)
18560 return;
18561 }
18562
18563 // Need to compute max possible elements in address space, since that
18564 // is included in diag message.
18565 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
18566 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
18567 MaxElems += 1;
18568 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
18569 MaxElems = MaxElems.udiv(ElemBytes);
18570
18571 unsigned DiagID =
18572 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
18573 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
18574
18575 // Diag message shows element size in bits and in "bytes" (platform-
18576 // dependent CharUnits)
18577 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
18578 PDiag(DiagID)
18579 << toString(index, 10, true) << AddrBits
18580 << (unsigned)ASTC.toBits(*ElemCharUnits)
18581 << toString(ElemBytes, 10, false)
18582 << toString(MaxElems, 10, false)
18583 << (unsigned)MaxElems.getLimitedValue(~0U)
18584 << IndexExpr->getSourceRange());
18585
18586 const NamedDecl *ND = nullptr;
18587 // Try harder to find a NamedDecl to point at in the note.
18588 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
18589 BaseExpr = ASE->getBase()->IgnoreParenCasts();
18590 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
18591 ND = DRE->getDecl();
18592 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
18593 ND = ME->getMemberDecl();
18594
18595 if (ND)
18596 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
18597 PDiag(diag::note_array_declared_here) << ND);
18598 }
18599 return;
18600 }
18601
18602 if (index.isUnsigned() || !index.isNegative()) {
18603 // It is possible that the type of the base expression after
18604 // IgnoreParenCasts is incomplete, even though the type of the base
18605 // expression before IgnoreParenCasts is complete (see PR39746 for an
18606 // example). In this case we have no information about whether the array
18607 // access exceeds the array bounds. However we can still diagnose an array
18608 // access which precedes the array bounds.
18609 if (BaseType->isIncompleteType())
18610 return;
18611
18612 llvm::APInt size = ArrayTy->getSize();
18613
18614 if (BaseType != EffectiveType) {
18615 // Make sure we're comparing apples to apples when comparing index to
18616 // size.
18617 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
18618 uint64_t array_typesize = Context.getTypeSize(BaseType);
18619
18620 // Handle ptrarith_typesize being zero, such as when casting to void*.
18621 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
18622 if (!ptrarith_typesize)
18623 ptrarith_typesize = Context.getCharWidth();
18624
18625 if (ptrarith_typesize != array_typesize) {
18626 // There's a cast to a different size type involved.
18627 uint64_t ratio = array_typesize / ptrarith_typesize;
18628
18629 // TODO: Be smarter about handling cases where array_typesize is not a
18630 // multiple of ptrarith_typesize.
18631 if (ptrarith_typesize * ratio == array_typesize)
18632 size *= llvm::APInt(size.getBitWidth(), ratio);
18633 }
18634 }
18635
18636 if (size.getBitWidth() > index.getBitWidth())
18637 index = index.zext(size.getBitWidth());
18638 else if (size.getBitWidth() < index.getBitWidth())
18639 size = size.zext(index.getBitWidth());
18640
18641 // For array subscripting the index must be less than size, but for pointer
18642 // arithmetic also allow the index (offset) to be equal to size since
18643 // computing the next address after the end of the array is legal and
18644 // commonly done e.g. in C++ iterators and range-based for loops.
18645 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
18646 return;
18647
18648 // Suppress the warning if the subscript expression (as identified by the
18649 // ']' location) and the index expression are both from macro expansions
18650 // within a system header.
18651 if (ASE) {
18653 ASE->getRBracketLoc());
18654 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
18655 SourceLocation IndexLoc =
18656 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
18657 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
18658 return;
18659 }
18660 }
18661
18662 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
18663 : diag::warn_ptr_arith_exceeds_bounds;
18664 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
18665 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
18666
18668 BaseExpr->getBeginLoc(), BaseExpr,
18669 PDiag(DiagID) << toString(index, 10, true) << ArrayTy->desugar()
18670 << CastMsg << CastMsgTy << IndexExpr->getSourceRange());
18671 } else {
18672 unsigned DiagID = diag::warn_array_index_precedes_bounds;
18673 if (!ASE) {
18674 DiagID = diag::warn_ptr_arith_precedes_bounds;
18675 if (index.isNegative()) index = -index;
18676 }
18677
18678 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
18679 PDiag(DiagID) << toString(index, 10, true)
18680 << IndexExpr->getSourceRange());
18681 }
18682
18683 const NamedDecl *ND = nullptr;
18684 // Try harder to find a NamedDecl to point at in the note.
18685 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
18686 BaseExpr = ASE->getBase()->IgnoreParenCasts();
18687 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
18688 ND = DRE->getDecl();
18689 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
18690 ND = ME->getMemberDecl();
18691
18692 if (ND)
18693 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
18694 PDiag(diag::note_array_declared_here) << ND);
18695}
18696
18697void Sema::CheckArrayAccess(const Expr *expr) {
18698 int AllowOnePastEnd = 0;
18699 while (expr) {
18700 expr = expr->IgnoreParenImpCasts();
18701 switch (expr->getStmtClass()) {
18702 case Stmt::ArraySubscriptExprClass: {
18703 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
18704 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
18705 AllowOnePastEnd > 0);
18706 expr = ASE->getBase();
18707 break;
18708 }
18709 case Stmt::MemberExprClass: {
18710 expr = cast<MemberExpr>(expr)->getBase();
18711 break;
18712 }
18713 case Stmt::ArraySectionExprClass: {
18714 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
18715 // FIXME: We should probably be checking all of the elements to the
18716 // 'length' here as well.
18717 if (ASE->getLowerBound())
18718 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
18719 /*ASE=*/nullptr, AllowOnePastEnd > 0);
18720 return;
18721 }
18722 case Stmt::UnaryOperatorClass: {
18723 // Only unwrap the * and & unary operators
18724 const UnaryOperator *UO = cast<UnaryOperator>(expr);
18725 expr = UO->getSubExpr();
18726 switch (UO->getOpcode()) {
18727 case UO_AddrOf:
18728 AllowOnePastEnd++;
18729 break;
18730 case UO_Deref:
18731 AllowOnePastEnd--;
18732 break;
18733 default:
18734 return;
18735 }
18736 break;
18737 }
18738 case Stmt::ConditionalOperatorClass: {
18739 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
18740 if (const Expr *lhs = cond->getLHS())
18741 CheckArrayAccess(lhs);
18742 if (const Expr *rhs = cond->getRHS())
18743 CheckArrayAccess(rhs);
18744 return;
18745 }
18746 case Stmt::CXXOperatorCallExprClass: {
18747 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
18748 for (const auto *Arg : OCE->arguments())
18749 CheckArrayAccess(Arg);
18750 return;
18751 }
18752 default:
18753 return;
18754 }
18755 }
18756}
18757
18759 Expr *RHS, bool isProperty) {
18760 // Check if RHS is an Objective-C object literal, which also can get
18761 // immediately zapped in a weak reference. Note that we explicitly
18762 // allow ObjCStringLiterals, since those are designed to never really die.
18763 RHS = RHS->IgnoreParenImpCasts();
18764
18765 // This enum needs to match with the 'select' in
18766 // warn_objc_arc_literal_assign (off-by-1).
18768 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
18769 return false;
18770
18771 S.Diag(Loc, diag::warn_arc_literal_assign)
18772 << (unsigned) Kind
18773 << (isProperty ? 0 : 1)
18774 << RHS->getSourceRange();
18775
18776 return true;
18777}
18778
18781 Expr *RHS, bool isProperty) {
18782 // Strip off any implicit cast added to get to the one ARC-specific.
18783 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
18784 if (cast->getCastKind() == CK_ARCConsumeObject) {
18785 S.Diag(Loc, diag::warn_arc_retained_assign)
18787 << (isProperty ? 0 : 1)
18788 << RHS->getSourceRange();
18789 return true;
18790 }
18791 RHS = cast->getSubExpr();
18792 }
18793
18794 if (LT == Qualifiers::OCL_Weak &&
18795 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
18796 return true;
18797
18798 return false;
18799}
18800
18802 QualType LHS, Expr *RHS) {
18804
18806 return false;
18807
18808 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
18809 return true;
18810
18811 return false;
18812}
18813
18815 Expr *LHS, Expr *RHS) {
18816 QualType LHSType;
18817 // PropertyRef on LHS type need be directly obtained from
18818 // its declaration as it has a PseudoType.
18820 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
18821 if (PRE && !PRE->isImplicitProperty()) {
18822 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
18823 if (PD)
18824 LHSType = PD->getType();
18825 }
18826
18827 if (LHSType.isNull())
18828 LHSType = LHS->getType();
18829
18831
18832 if (LT == Qualifiers::OCL_Weak) {
18833 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
18835 }
18836
18837 if (checkUnsafeAssigns(Loc, LHSType, RHS))
18838 return;
18839
18840 // FIXME. Check for other life times.
18841 if (LT != Qualifiers::OCL_None)
18842 return;
18843
18844 if (PRE) {
18845 if (PRE->isImplicitProperty())
18846 return;
18847 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
18848 if (!PD)
18849 return;
18850
18851 unsigned Attributes = PD->getPropertyAttributes();
18852 if (Attributes & ObjCPropertyAttribute::kind_assign) {
18853 // when 'assign' attribute was not explicitly specified
18854 // by user, ignore it and rely on property type itself
18855 // for lifetime info.
18856 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
18857 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
18858 LHSType->isObjCRetainableType())
18859 return;
18860
18861 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
18862 if (cast->getCastKind() == CK_ARCConsumeObject) {
18863 Diag(Loc, diag::warn_arc_retained_property_assign)
18864 << RHS->getSourceRange();
18865 return;
18866 }
18867 RHS = cast->getSubExpr();
18868 }
18869 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
18870 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
18871 return;
18872 }
18873 }
18874}
18875
18876//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
18877
18878static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
18879 SourceLocation StmtLoc,
18880 const NullStmt *Body) {
18881 // Do not warn if the body is a macro that expands to nothing, e.g:
18882 //
18883 // #define CALL(x)
18884 // if (condition)
18885 // CALL(0);
18886 if (Body->hasLeadingEmptyMacro())
18887 return false;
18888
18889 // Get line numbers of statement and body.
18890 bool StmtLineInvalid;
18891 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
18892 &StmtLineInvalid);
18893 if (StmtLineInvalid)
18894 return false;
18895
18896 bool BodyLineInvalid;
18897 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
18898 &BodyLineInvalid);
18899 if (BodyLineInvalid)
18900 return false;
18901
18902 // Warn if null statement and body are on the same line.
18903 if (StmtLine != BodyLine)
18904 return false;
18905
18906 return true;
18907}
18908
18910 const Stmt *Body,
18911 unsigned DiagID) {
18912 // Since this is a syntactic check, don't emit diagnostic for template
18913 // instantiations, this just adds noise.
18915 return;
18916
18917 // The body should be a null statement.
18918 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
18919 if (!NBody)
18920 return;
18921
18922 // Do the usual checks.
18923 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
18924 return;
18925
18926 Diag(NBody->getSemiLoc(), DiagID);
18927 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
18928}
18929
18931 const Stmt *PossibleBody) {
18932 assert(!CurrentInstantiationScope); // Ensured by caller
18933
18934 SourceLocation StmtLoc;
18935 const Stmt *Body;
18936 unsigned DiagID;
18937 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
18938 StmtLoc = FS->getRParenLoc();
18939 Body = FS->getBody();
18940 DiagID = diag::warn_empty_for_body;
18941 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
18942 StmtLoc = WS->getRParenLoc();
18943 Body = WS->getBody();
18944 DiagID = diag::warn_empty_while_body;
18945 } else
18946 return; // Neither `for' nor `while'.
18947
18948 // The body should be a null statement.
18949 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
18950 if (!NBody)
18951 return;
18952
18953 // Skip expensive checks if diagnostic is disabled.
18954 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
18955 return;
18956
18957 // Do the usual checks.
18958 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
18959 return;
18960
18961 // `for(...);' and `while(...);' are popular idioms, so in order to keep
18962 // noise level low, emit diagnostics only if for/while is followed by a
18963 // CompoundStmt, e.g.:
18964 // for (int i = 0; i < n; i++);
18965 // {
18966 // a(i);
18967 // }
18968 // or if for/while is followed by a statement with more indentation
18969 // than for/while itself:
18970 // for (int i = 0; i < n; i++);
18971 // a(i);
18972 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
18973 if (!ProbableTypo) {
18974 bool BodyColInvalid;
18975 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
18976 PossibleBody->getBeginLoc(), &BodyColInvalid);
18977 if (BodyColInvalid)
18978 return;
18979
18980 bool StmtColInvalid;
18981 unsigned StmtCol =
18982 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
18983 if (StmtColInvalid)
18984 return;
18985
18986 if (BodyCol > StmtCol)
18987 ProbableTypo = true;
18988 }
18989
18990 if (ProbableTypo) {
18991 Diag(NBody->getSemiLoc(), DiagID);
18992 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
18993 }
18994}
18995
18996//===--- CHECK: Warn on self move with std::move. -------------------------===//
18997
18998/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
18999void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
19000 SourceLocation OpLoc) {
19001 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
19002 return;
19003
19005 return;
19006
19007 // Strip parens and casts away.
19008 LHSExpr = LHSExpr->IgnoreParenImpCasts();
19009 RHSExpr = RHSExpr->IgnoreParenImpCasts();
19010
19011 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
19012 // which we can treat as an inlined std::move
19013 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
19014 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
19015 RHSExpr = CE->getArg(0);
19016 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
19017 CXXSCE && CXXSCE->isXValue())
19018 RHSExpr = CXXSCE->getSubExpr();
19019 else
19020 return;
19021
19022 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
19023 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
19024
19025 // Two DeclRefExpr's, check that the decls are the same.
19026 if (LHSDeclRef && RHSDeclRef) {
19027 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
19028 return;
19029 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
19030 RHSDeclRef->getDecl()->getCanonicalDecl())
19031 return;
19032
19033 auto D = Diag(OpLoc, diag::warn_self_move)
19034 << LHSExpr->getType() << LHSExpr->getSourceRange()
19035 << RHSExpr->getSourceRange();
19036 if (const FieldDecl *F =
19038 D << 1 << F
19039 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
19040 else
19041 D << 0;
19042 return;
19043 }
19044
19045 // Member variables require a different approach to check for self moves.
19046 // MemberExpr's are the same if every nested MemberExpr refers to the same
19047 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
19048 // the base Expr's are CXXThisExpr's.
19049 const Expr *LHSBase = LHSExpr;
19050 const Expr *RHSBase = RHSExpr;
19051 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
19052 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
19053 if (!LHSME || !RHSME)
19054 return;
19055
19056 while (LHSME && RHSME) {
19057 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
19058 RHSME->getMemberDecl()->getCanonicalDecl())
19059 return;
19060
19061 LHSBase = LHSME->getBase();
19062 RHSBase = RHSME->getBase();
19063 LHSME = dyn_cast<MemberExpr>(LHSBase);
19064 RHSME = dyn_cast<MemberExpr>(RHSBase);
19065 }
19066
19067 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
19068 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
19069 if (LHSDeclRef && RHSDeclRef) {
19070 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
19071 return;
19072 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
19073 RHSDeclRef->getDecl()->getCanonicalDecl())
19074 return;
19075
19076 Diag(OpLoc, diag::warn_self_move)
19077 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
19078 << RHSExpr->getSourceRange();
19079 return;
19080 }
19081
19082 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
19083 Diag(OpLoc, diag::warn_self_move)
19084 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
19085 << RHSExpr->getSourceRange();
19086}
19087
19088//===--- Layout compatibility ----------------------------------------------//
19089
19090static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
19091
19092/// Check if two enumeration types are layout-compatible.
19094 // C++11 [dcl.enum] p8:
19095 // Two enumeration types are layout-compatible if they have the same
19096 // underlying type.
19097 return ED1->isComplete() && ED2->isComplete() &&
19098 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
19099}
19100
19101/// Check if two fields are layout-compatible.
19102/// Can be used on union members, which are exempt from alignment requirement
19103/// of common initial sequence.
19105 FieldDecl *Field2,
19106 bool AreUnionMembers = false) {
19107 [[maybe_unused]] const Type *Field1Parent =
19108 Field1->getParent()->getTypeForDecl();
19109 [[maybe_unused]] const Type *Field2Parent =
19110 Field2->getParent()->getTypeForDecl();
19111 assert(((Field1Parent->isStructureOrClassType() &&
19112 Field2Parent->isStructureOrClassType()) ||
19113 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
19114 "Can't evaluate layout compatibility between a struct field and a "
19115 "union field.");
19116 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
19117 (AreUnionMembers && Field1Parent->isUnionType())) &&
19118 "AreUnionMembers should be 'true' for union fields (only).");
19119
19120 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
19121 return false;
19122
19123 if (Field1->isBitField() != Field2->isBitField())
19124 return false;
19125
19126 if (Field1->isBitField()) {
19127 // Make sure that the bit-fields are the same length.
19128 unsigned Bits1 = Field1->getBitWidthValue(C);
19129 unsigned Bits2 = Field2->getBitWidthValue(C);
19130
19131 if (Bits1 != Bits2)
19132 return false;
19133 }
19134
19135 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
19136 Field2->hasAttr<clang::NoUniqueAddressAttr>())
19137 return false;
19138
19139 if (!AreUnionMembers &&
19140 Field1->getMaxAlignment() != Field2->getMaxAlignment())
19141 return false;
19142
19143 return true;
19144}
19145
19146/// Check if two standard-layout structs are layout-compatible.
19147/// (C++11 [class.mem] p17)
19149 RecordDecl *RD2) {
19150 // If both records are C++ classes, check that base classes match.
19151 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
19152 // If one of records is a CXXRecordDecl we are in C++ mode,
19153 // thus the other one is a CXXRecordDecl, too.
19154 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
19155 // Check number of base classes.
19156 if (D1CXX->getNumBases() != D2CXX->getNumBases())
19157 return false;
19158
19159 // Check the base classes.
19161 Base1 = D1CXX->bases_begin(),
19162 BaseEnd1 = D1CXX->bases_end(),
19163 Base2 = D2CXX->bases_begin();
19164 Base1 != BaseEnd1;
19165 ++Base1, ++Base2) {
19166 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
19167 return false;
19168 }
19169 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
19170 // If only RD2 is a C++ class, it should have zero base classes.
19171 if (D2CXX->getNumBases() > 0)
19172 return false;
19173 }
19174
19175 // Check the fields.
19177 Field2End = RD2->field_end(),
19178 Field1 = RD1->field_begin(),
19179 Field1End = RD1->field_end();
19180 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
19181 if (!isLayoutCompatible(C, *Field1, *Field2))
19182 return false;
19183 }
19184 if (Field1 != Field1End || Field2 != Field2End)
19185 return false;
19186
19187 return true;
19188}
19189
19190/// Check if two standard-layout unions are layout-compatible.
19191/// (C++11 [class.mem] p18)
19193 RecordDecl *RD2) {
19194 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
19195 for (auto *Field2 : RD2->fields())
19196 UnmatchedFields.insert(Field2);
19197
19198 for (auto *Field1 : RD1->fields()) {
19200 I = UnmatchedFields.begin(),
19201 E = UnmatchedFields.end();
19202
19203 for ( ; I != E; ++I) {
19204 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
19205 bool Result = UnmatchedFields.erase(*I);
19206 (void) Result;
19207 assert(Result);
19208 break;
19209 }
19210 }
19211 if (I == E)
19212 return false;
19213 }
19214
19215 return UnmatchedFields.empty();
19216}
19217
19219 RecordDecl *RD2) {
19220 if (RD1->isUnion() != RD2->isUnion())
19221 return false;
19222
19223 if (RD1->isUnion())
19224 return isLayoutCompatibleUnion(C, RD1, RD2);
19225 else
19226 return isLayoutCompatibleStruct(C, RD1, RD2);
19227}
19228
19229/// Check if two types are layout-compatible in C++11 sense.
19231 if (T1.isNull() || T2.isNull())
19232 return false;
19233
19234 // C++20 [basic.types] p11:
19235 // Two types cv1 T1 and cv2 T2 are layout-compatible types
19236 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
19237 // or layout-compatible standard-layout class types (11.4).
19240
19241 if (C.hasSameType(T1, T2))
19242 return true;
19243
19244 const Type::TypeClass TC1 = T1->getTypeClass();
19245 const Type::TypeClass TC2 = T2->getTypeClass();
19246
19247 if (TC1 != TC2)
19248 return false;
19249
19250 if (TC1 == Type::Enum) {
19251 return isLayoutCompatible(C,
19252 cast<EnumType>(T1)->getDecl(),
19253 cast<EnumType>(T2)->getDecl());
19254 } else if (TC1 == Type::Record) {
19255 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
19256 return false;
19257
19258 return isLayoutCompatible(C,
19259 cast<RecordType>(T1)->getDecl(),
19260 cast<RecordType>(T2)->getDecl());
19261 }
19262
19263 return false;
19264}
19265
19267 return isLayoutCompatible(getASTContext(), T1, T2);
19268}
19269
19270//===-------------- Pointer interconvertibility ----------------------------//
19271
19273 const TypeSourceInfo *Derived) {
19274 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
19275 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
19276
19277 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
19278 getASTContext().hasSameType(BaseT, DerivedT))
19279 return true;
19280
19281 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
19282 return false;
19283
19284 // Per [basic.compound]/4.3, containing object has to be standard-layout.
19285 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
19286 return true;
19287
19288 return false;
19289}
19290
19291//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
19292
19293/// Given a type tag expression find the type tag itself.
19294///
19295/// \param TypeExpr Type tag expression, as it appears in user's code.
19296///
19297/// \param VD Declaration of an identifier that appears in a type tag.
19298///
19299/// \param MagicValue Type tag magic value.
19300///
19301/// \param isConstantEvaluated whether the evalaution should be performed in
19302
19303/// constant context.
19304static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
19305 const ValueDecl **VD, uint64_t *MagicValue,
19306 bool isConstantEvaluated) {
19307 while(true) {
19308 if (!TypeExpr)
19309 return false;
19310
19311 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
19312
19313 switch (TypeExpr->getStmtClass()) {
19314 case Stmt::UnaryOperatorClass: {
19315 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
19316 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
19317 TypeExpr = UO->getSubExpr();
19318 continue;
19319 }
19320 return false;
19321 }
19322
19323 case Stmt::DeclRefExprClass: {
19324 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
19325 *VD = DRE->getDecl();
19326 return true;
19327 }
19328
19329 case Stmt::IntegerLiteralClass: {
19330 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
19331 llvm::APInt MagicValueAPInt = IL->getValue();
19332 if (MagicValueAPInt.getActiveBits() <= 64) {
19333 *MagicValue = MagicValueAPInt.getZExtValue();
19334 return true;
19335 } else
19336 return false;
19337 }
19338
19339 case Stmt::BinaryConditionalOperatorClass:
19340 case Stmt::ConditionalOperatorClass: {
19341 const AbstractConditionalOperator *ACO =
19342 cast<AbstractConditionalOperator>(TypeExpr);
19343 bool Result;
19344 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
19345 isConstantEvaluated)) {
19346 if (Result)
19347 TypeExpr = ACO->getTrueExpr();
19348 else
19349 TypeExpr = ACO->getFalseExpr();
19350 continue;
19351 }
19352 return false;
19353 }
19354
19355 case Stmt::BinaryOperatorClass: {
19356 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
19357 if (BO->getOpcode() == BO_Comma) {
19358 TypeExpr = BO->getRHS();
19359 continue;
19360 }
19361 return false;
19362 }
19363
19364 default:
19365 return false;
19366 }
19367 }
19368}
19369
19370/// Retrieve the C type corresponding to type tag TypeExpr.
19371///
19372/// \param TypeExpr Expression that specifies a type tag.
19373///
19374/// \param MagicValues Registered magic values.
19375///
19376/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
19377/// kind.
19378///
19379/// \param TypeInfo Information about the corresponding C type.
19380///
19381/// \param isConstantEvaluated whether the evalaution should be performed in
19382/// constant context.
19383///
19384/// \returns true if the corresponding C type was found.
19386 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
19387 const ASTContext &Ctx,
19388 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
19389 *MagicValues,
19390 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
19391 bool isConstantEvaluated) {
19392 FoundWrongKind = false;
19393
19394 // Variable declaration that has type_tag_for_datatype attribute.
19395 const ValueDecl *VD = nullptr;
19396
19397 uint64_t MagicValue;
19398
19399 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
19400 return false;
19401
19402 if (VD) {
19403 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
19404 if (I->getArgumentKind() != ArgumentKind) {
19405 FoundWrongKind = true;
19406 return false;
19407 }
19408 TypeInfo.Type = I->getMatchingCType();
19409 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
19410 TypeInfo.MustBeNull = I->getMustBeNull();
19411 return true;
19412 }
19413 return false;
19414 }
19415
19416 if (!MagicValues)
19417 return false;
19418
19419 llvm::DenseMap<Sema::TypeTagMagicValue,
19420 Sema::TypeTagData>::const_iterator I =
19421 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
19422 if (I == MagicValues->end())
19423 return false;
19424
19425 TypeInfo = I->second;
19426 return true;
19427}
19428
19430 uint64_t MagicValue, QualType Type,
19431 bool LayoutCompatible,
19432 bool MustBeNull) {
19433 if (!TypeTagForDatatypeMagicValues)
19434 TypeTagForDatatypeMagicValues.reset(
19435 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
19436
19437 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
19438 (*TypeTagForDatatypeMagicValues)[Magic] =
19439 TypeTagData(Type, LayoutCompatible, MustBeNull);
19440}
19441
19442static bool IsSameCharType(QualType T1, QualType T2) {
19443 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
19444 if (!BT1)
19445 return false;
19446
19447 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
19448 if (!BT2)
19449 return false;
19450
19451 BuiltinType::Kind T1Kind = BT1->getKind();
19452 BuiltinType::Kind T2Kind = BT2->getKind();
19453
19454 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
19455 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
19456 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
19457 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
19458}
19459
19460void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
19461 const ArrayRef<const Expr *> ExprArgs,
19462 SourceLocation CallSiteLoc) {
19463 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
19464 bool IsPointerAttr = Attr->getIsPointer();
19465
19466 // Retrieve the argument representing the 'type_tag'.
19467 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
19468 if (TypeTagIdxAST >= ExprArgs.size()) {
19469 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
19470 << 0 << Attr->getTypeTagIdx().getSourceIndex();
19471 return;
19472 }
19473 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
19474 bool FoundWrongKind;
19475 TypeTagData TypeInfo;
19476 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
19477 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
19479 if (FoundWrongKind)
19480 Diag(TypeTagExpr->getExprLoc(),
19481 diag::warn_type_tag_for_datatype_wrong_kind)
19482 << TypeTagExpr->getSourceRange();
19483 return;
19484 }
19485
19486 // Retrieve the argument representing the 'arg_idx'.
19487 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
19488 if (ArgumentIdxAST >= ExprArgs.size()) {
19489 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
19490 << 1 << Attr->getArgumentIdx().getSourceIndex();
19491 return;
19492 }
19493 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
19494 if (IsPointerAttr) {
19495 // Skip implicit cast of pointer to `void *' (as a function argument).
19496 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
19497 if (ICE->getType()->isVoidPointerType() &&
19498 ICE->getCastKind() == CK_BitCast)
19499 ArgumentExpr = ICE->getSubExpr();
19500 }
19501 QualType ArgumentType = ArgumentExpr->getType();
19502
19503 // Passing a `void*' pointer shouldn't trigger a warning.
19504 if (IsPointerAttr && ArgumentType->isVoidPointerType())
19505 return;
19506
19507 if (TypeInfo.MustBeNull) {
19508 // Type tag with matching void type requires a null pointer.
19509 if (!ArgumentExpr->isNullPointerConstant(Context,
19511 Diag(ArgumentExpr->getExprLoc(),
19512 diag::warn_type_safety_null_pointer_required)
19513 << ArgumentKind->getName()
19514 << ArgumentExpr->getSourceRange()
19515 << TypeTagExpr->getSourceRange();
19516 }
19517 return;
19518 }
19519
19520 QualType RequiredType = TypeInfo.Type;
19521 if (IsPointerAttr)
19522 RequiredType = Context.getPointerType(RequiredType);
19523
19524 bool mismatch = false;
19525 if (!TypeInfo.LayoutCompatible) {
19526 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
19527
19528 // C++11 [basic.fundamental] p1:
19529 // Plain char, signed char, and unsigned char are three distinct types.
19530 //
19531 // But we treat plain `char' as equivalent to `signed char' or `unsigned
19532 // char' depending on the current char signedness mode.
19533 if (mismatch)
19534 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
19535 RequiredType->getPointeeType())) ||
19536 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
19537 mismatch = false;
19538 } else
19539 if (IsPointerAttr)
19540 mismatch = !isLayoutCompatible(Context,
19541 ArgumentType->getPointeeType(),
19542 RequiredType->getPointeeType());
19543 else
19544 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
19545
19546 if (mismatch)
19547 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
19548 << ArgumentType << ArgumentKind
19549 << TypeInfo.LayoutCompatible << RequiredType
19550 << ArgumentExpr->getSourceRange()
19551 << TypeTagExpr->getSourceRange();
19552}
19553
19554void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
19555 CharUnits Alignment) {
19556 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
19557}
19558
19560 for (MisalignedMember &m : MisalignedMembers) {
19561 const NamedDecl *ND = m.RD;
19562 if (ND->getName().empty()) {
19563 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
19564 ND = TD;
19565 }
19566 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
19567 << m.MD << ND << m.E->getSourceRange();
19568 }
19569 MisalignedMembers.clear();
19570}
19571
19573 E = E->IgnoreParens();
19574 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
19575 return;
19576 if (isa<UnaryOperator>(E) &&
19577 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
19578 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
19579 if (isa<MemberExpr>(Op)) {
19580 auto *MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
19581 if (MA != MisalignedMembers.end() &&
19582 (T->isDependentType() || T->isIntegerType() ||
19585 T->getPointeeType()) <= MA->Alignment))))
19586 MisalignedMembers.erase(MA);
19587 }
19588 }
19589}
19590
19592 Expr *E,
19593 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
19594 Action) {
19595 const auto *ME = dyn_cast<MemberExpr>(E);
19596 if (!ME)
19597 return;
19598
19599 // No need to check expressions with an __unaligned-qualified type.
19600 if (E->getType().getQualifiers().hasUnaligned())
19601 return;
19602
19603 // For a chain of MemberExpr like "a.b.c.d" this list
19604 // will keep FieldDecl's like [d, c, b].
19605 SmallVector<FieldDecl *, 4> ReverseMemberChain;
19606 const MemberExpr *TopME = nullptr;
19607 bool AnyIsPacked = false;
19608 do {
19609 QualType BaseType = ME->getBase()->getType();
19610 if (BaseType->isDependentType())
19611 return;
19612 if (ME->isArrow())
19613 BaseType = BaseType->getPointeeType();
19614 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
19615 if (RD->isInvalidDecl())
19616 return;
19617
19618 ValueDecl *MD = ME->getMemberDecl();
19619 auto *FD = dyn_cast<FieldDecl>(MD);
19620 // We do not care about non-data members.
19621 if (!FD || FD->isInvalidDecl())
19622 return;
19623
19624 AnyIsPacked =
19625 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
19626 ReverseMemberChain.push_back(FD);
19627
19628 TopME = ME;
19629 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
19630 } while (ME);
19631 assert(TopME && "We did not compute a topmost MemberExpr!");
19632
19633 // Not the scope of this diagnostic.
19634 if (!AnyIsPacked)
19635 return;
19636
19637 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
19638 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
19639 // TODO: The innermost base of the member expression may be too complicated.
19640 // For now, just disregard these cases. This is left for future
19641 // improvement.
19642 if (!DRE && !isa<CXXThisExpr>(TopBase))
19643 return;
19644
19645 // Alignment expected by the whole expression.
19646 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
19647
19648 // No need to do anything else with this case.
19649 if (ExpectedAlignment.isOne())
19650 return;
19651
19652 // Synthesize offset of the whole access.
19653 CharUnits Offset;
19654 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
19656
19657 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
19658 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
19659 ReverseMemberChain.back()->getParent()->getTypeForDecl());
19660
19661 // The base expression of the innermost MemberExpr may give
19662 // stronger guarantees than the class containing the member.
19663 if (DRE && !TopME->isArrow()) {
19664 const ValueDecl *VD = DRE->getDecl();
19665 if (!VD->getType()->isReferenceType())
19666 CompleteObjectAlignment =
19667 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
19668 }
19669
19670 // Check if the synthesized offset fulfills the alignment.
19671 if (Offset % ExpectedAlignment != 0 ||
19672 // It may fulfill the offset it but the effective alignment may still be
19673 // lower than the expected expression alignment.
19674 CompleteObjectAlignment < ExpectedAlignment) {
19675 // If this happens, we want to determine a sensible culprit of this.
19676 // Intuitively, watching the chain of member expressions from right to
19677 // left, we start with the required alignment (as required by the field
19678 // type) but some packed attribute in that chain has reduced the alignment.
19679 // It may happen that another packed structure increases it again. But if
19680 // we are here such increase has not been enough. So pointing the first
19681 // FieldDecl that either is packed or else its RecordDecl is,
19682 // seems reasonable.
19683 FieldDecl *FD = nullptr;
19684 CharUnits Alignment;
19685 for (FieldDecl *FDI : ReverseMemberChain) {
19686 if (FDI->hasAttr<PackedAttr>() ||
19687 FDI->getParent()->hasAttr<PackedAttr>()) {
19688 FD = FDI;
19689 Alignment = std::min(
19692 break;
19693 }
19694 }
19695 assert(FD && "We did not find a packed FieldDecl!");
19696 Action(E, FD->getParent(), FD, Alignment);
19697 }
19698}
19699
19700void Sema::CheckAddressOfPackedMember(Expr *rhs) {
19701 using namespace std::placeholders;
19702
19704 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
19705 _2, _3, _4));
19706}
19707
19708bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
19709 if (checkArgCount(*this, TheCall, 1))
19710 return true;
19711
19712 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
19713 if (A.isInvalid())
19714 return true;
19715
19716 TheCall->setArg(0, A.get());
19717 QualType TyA = A.get()->getType();
19718
19719 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA, 1))
19720 return true;
19721
19722 TheCall->setType(TyA);
19723 return false;
19724}
19725
19726bool Sema::BuiltinElementwiseMath(CallExpr *TheCall) {
19727 QualType Res;
19728 if (BuiltinVectorMath(TheCall, Res))
19729 return true;
19730 TheCall->setType(Res);
19731 return false;
19732}
19733
19735 QualType Res;
19736 if (BuiltinVectorMath(TheCall, Res))
19737 return true;
19738
19739 if (auto *VecTy0 = Res->getAs<VectorType>())
19740 TheCall->setType(VecTy0->getElementType());
19741 else
19742 TheCall->setType(Res);
19743
19744 return false;
19745}
19746
19748 if (checkArgCount(*this, TheCall, 2))
19749 return true;
19750
19751 ExprResult A = TheCall->getArg(0);
19752 ExprResult B = TheCall->getArg(1);
19753 // Do standard promotions between the two arguments, returning their common
19754 // type.
19755 Res = UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
19756 if (A.isInvalid() || B.isInvalid())
19757 return true;
19758
19759 QualType TyA = A.get()->getType();
19760 QualType TyB = B.get()->getType();
19761
19762 if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
19763 return Diag(A.get()->getBeginLoc(),
19764 diag::err_typecheck_call_different_arg_types)
19765 << TyA << TyB;
19766
19767 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA, 1))
19768 return true;
19769
19770 TheCall->setArg(0, A.get());
19771 TheCall->setArg(1, B.get());
19772 return false;
19773}
19774
19775bool Sema::BuiltinElementwiseTernaryMath(CallExpr *TheCall,
19776 bool CheckForFloatArgs) {
19777 if (checkArgCount(*this, TheCall, 3))
19778 return true;
19779
19780 Expr *Args[3];
19781 for (int I = 0; I < 3; ++I) {
19782 ExprResult Converted = UsualUnaryConversions(TheCall->getArg(I));
19783 if (Converted.isInvalid())
19784 return true;
19785 Args[I] = Converted.get();
19786 }
19787
19788 if (CheckForFloatArgs) {
19789 int ArgOrdinal = 1;
19790 for (Expr *Arg : Args) {
19792 Arg->getType(), ArgOrdinal++))
19793 return true;
19794 }
19795 } else {
19796 int ArgOrdinal = 1;
19797 for (Expr *Arg : Args) {
19798 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
19799 ArgOrdinal++))
19800 return true;
19801 }
19802 }
19803
19804 for (int I = 1; I < 3; ++I) {
19805 if (Args[0]->getType().getCanonicalType() !=
19806 Args[I]->getType().getCanonicalType()) {
19807 return Diag(Args[0]->getBeginLoc(),
19808 diag::err_typecheck_call_different_arg_types)
19809 << Args[0]->getType() << Args[I]->getType();
19810 }
19811
19812 TheCall->setArg(I, Args[I]);
19813 }
19814
19815 TheCall->setType(Args[0]->getType());
19816 return false;
19817}
19818
19819bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
19820 if (checkArgCount(*this, TheCall, 1))
19821 return true;
19822
19823 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
19824 if (A.isInvalid())
19825 return true;
19826
19827 TheCall->setArg(0, A.get());
19828 return false;
19829}
19830
19831bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
19832 if (checkArgCount(*this, TheCall, 1))
19833 return true;
19834
19835 ExprResult Arg = TheCall->getArg(0);
19836 QualType TyArg = Arg.get()->getType();
19837
19838 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
19839 return Diag(TheCall->getArg(0)->getBeginLoc(), diag::err_builtin_invalid_arg_type)
19840 << 1 << /*vector, integer or floating point ty*/ 0 << TyArg;
19841
19842 TheCall->setType(TyArg);
19843 return false;
19844}
19845
19846ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
19847 ExprResult CallResult) {
19848 if (checkArgCount(*this, TheCall, 1))
19849 return ExprError();
19850
19851 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
19852 if (MatrixArg.isInvalid())
19853 return MatrixArg;
19854 Expr *Matrix = MatrixArg.get();
19855
19856 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
19857 if (!MType) {
19858 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
19859 << 1 << /* matrix ty*/ 1 << Matrix->getType();
19860 return ExprError();
19861 }
19862
19863 // Create returned matrix type by swapping rows and columns of the argument
19864 // matrix type.
19866 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
19867
19868 // Change the return type to the type of the returned matrix.
19869 TheCall->setType(ResultType);
19870
19871 // Update call argument to use the possibly converted matrix argument.
19872 TheCall->setArg(0, Matrix);
19873 return CallResult;
19874}
19875
19876// Get and verify the matrix dimensions.
19877static std::optional<unsigned>
19879 SourceLocation ErrorPos;
19880 std::optional<llvm::APSInt> Value =
19881 Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
19882 if (!Value) {
19883 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
19884 << Name;
19885 return {};
19886 }
19887 uint64_t Dim = Value->getZExtValue();
19889 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
19891 return {};
19892 }
19893 return Dim;
19894}
19895
19896ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
19897 ExprResult CallResult) {
19898 if (!getLangOpts().MatrixTypes) {
19899 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
19900 return ExprError();
19901 }
19902
19903 if (checkArgCount(*this, TheCall, 4))
19904 return ExprError();
19905
19906 unsigned PtrArgIdx = 0;
19907 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
19908 Expr *RowsExpr = TheCall->getArg(1);
19909 Expr *ColumnsExpr = TheCall->getArg(2);
19910 Expr *StrideExpr = TheCall->getArg(3);
19911
19912 bool ArgError = false;
19913
19914 // Check pointer argument.
19915 {
19917 if (PtrConv.isInvalid())
19918 return PtrConv;
19919 PtrExpr = PtrConv.get();
19920 TheCall->setArg(0, PtrExpr);
19921 if (PtrExpr->isTypeDependent()) {
19922 TheCall->setType(Context.DependentTy);
19923 return TheCall;
19924 }
19925 }
19926
19927 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
19928 QualType ElementTy;
19929 if (!PtrTy) {
19930 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
19931 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
19932 ArgError = true;
19933 } else {
19934 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
19935
19937 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
19938 << PtrArgIdx + 1 << /* pointer to element ty*/ 2
19939 << PtrExpr->getType();
19940 ArgError = true;
19941 }
19942 }
19943
19944 // Apply default Lvalue conversions and convert the expression to size_t.
19945 auto ApplyArgumentConversions = [this](Expr *E) {
19947 if (Conv.isInvalid())
19948 return Conv;
19949
19950 return tryConvertExprToType(Conv.get(), Context.getSizeType());
19951 };
19952
19953 // Apply conversion to row and column expressions.
19954 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
19955 if (!RowsConv.isInvalid()) {
19956 RowsExpr = RowsConv.get();
19957 TheCall->setArg(1, RowsExpr);
19958 } else
19959 RowsExpr = nullptr;
19960
19961 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
19962 if (!ColumnsConv.isInvalid()) {
19963 ColumnsExpr = ColumnsConv.get();
19964 TheCall->setArg(2, ColumnsExpr);
19965 } else
19966 ColumnsExpr = nullptr;
19967
19968 // If any part of the result matrix type is still pending, just use
19969 // Context.DependentTy, until all parts are resolved.
19970 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
19971 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
19972 TheCall->setType(Context.DependentTy);
19973 return CallResult;
19974 }
19975
19976 // Check row and column dimensions.
19977 std::optional<unsigned> MaybeRows;
19978 if (RowsExpr)
19979 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
19980
19981 std::optional<unsigned> MaybeColumns;
19982 if (ColumnsExpr)
19983 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
19984
19985 // Check stride argument.
19986 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
19987 if (StrideConv.isInvalid())
19988 return ExprError();
19989 StrideExpr = StrideConv.get();
19990 TheCall->setArg(3, StrideExpr);
19991
19992 if (MaybeRows) {
19993 if (std::optional<llvm::APSInt> Value =
19994 StrideExpr->getIntegerConstantExpr(Context)) {
19995 uint64_t Stride = Value->getZExtValue();
19996 if (Stride < *MaybeRows) {
19997 Diag(StrideExpr->getBeginLoc(),
19998 diag::err_builtin_matrix_stride_too_small);
19999 ArgError = true;
20000 }
20001 }
20002 }
20003
20004 if (ArgError || !MaybeRows || !MaybeColumns)
20005 return ExprError();
20006
20007 TheCall->setType(
20008 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
20009 return CallResult;
20010}
20011
20012ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
20013 ExprResult CallResult) {
20014 if (checkArgCount(*this, TheCall, 3))
20015 return ExprError();
20016
20017 unsigned PtrArgIdx = 1;
20018 Expr *MatrixExpr = TheCall->getArg(0);
20019 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
20020 Expr *StrideExpr = TheCall->getArg(2);
20021
20022 bool ArgError = false;
20023
20024 {
20025 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
20026 if (MatrixConv.isInvalid())
20027 return MatrixConv;
20028 MatrixExpr = MatrixConv.get();
20029 TheCall->setArg(0, MatrixExpr);
20030 }
20031 if (MatrixExpr->isTypeDependent()) {
20032 TheCall->setType(Context.DependentTy);
20033 return TheCall;
20034 }
20035
20036 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
20037 if (!MatrixTy) {
20038 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
20039 << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
20040 ArgError = true;
20041 }
20042
20043 {
20045 if (PtrConv.isInvalid())
20046 return PtrConv;
20047 PtrExpr = PtrConv.get();
20048 TheCall->setArg(1, PtrExpr);
20049 if (PtrExpr->isTypeDependent()) {
20050 TheCall->setType(Context.DependentTy);
20051 return TheCall;
20052 }
20053 }
20054
20055 // Check pointer argument.
20056 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
20057 if (!PtrTy) {
20058 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
20059 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
20060 ArgError = true;
20061 } else {
20062 QualType ElementTy = PtrTy->getPointeeType();
20063 if (ElementTy.isConstQualified()) {
20064 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
20065 ArgError = true;
20066 }
20067 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
20068 if (MatrixTy &&
20069 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
20070 Diag(PtrExpr->getBeginLoc(),
20071 diag::err_builtin_matrix_pointer_arg_mismatch)
20072 << ElementTy << MatrixTy->getElementType();
20073 ArgError = true;
20074 }
20075 }
20076
20077 // Apply default Lvalue conversions and convert the stride expression to
20078 // size_t.
20079 {
20080 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
20081 if (StrideConv.isInvalid())
20082 return StrideConv;
20083
20084 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
20085 if (StrideConv.isInvalid())
20086 return StrideConv;
20087 StrideExpr = StrideConv.get();
20088 TheCall->setArg(2, StrideExpr);
20089 }
20090
20091 // Check stride argument.
20092 if (MatrixTy) {
20093 if (std::optional<llvm::APSInt> Value =
20094 StrideExpr->getIntegerConstantExpr(Context)) {
20095 uint64_t Stride = Value->getZExtValue();
20096 if (Stride < MatrixTy->getNumRows()) {
20097 Diag(StrideExpr->getBeginLoc(),
20098 diag::err_builtin_matrix_stride_too_small);
20099 ArgError = true;
20100 }
20101 }
20102 }
20103
20104 if (ArgError)
20105 return ExprError();
20106
20107 return CallResult;
20108}
20109
20110/// Checks the argument at the given index is a WebAssembly table and if it
20111/// is, sets ElTy to the element type.
20112static bool CheckWasmBuiltinArgIsTable(Sema &S, CallExpr *E, unsigned ArgIndex,
20113 QualType &ElTy) {
20114 Expr *ArgExpr = E->getArg(ArgIndex);
20115 const auto *ATy = dyn_cast<ArrayType>(ArgExpr->getType());
20116 if (!ATy || !ATy->getElementType().isWebAssemblyReferenceType()) {
20117 return S.Diag(ArgExpr->getBeginLoc(),
20118 diag::err_wasm_builtin_arg_must_be_table_type)
20119 << ArgIndex + 1 << ArgExpr->getSourceRange();
20120 }
20121 ElTy = ATy->getElementType();
20122 return false;
20123}
20124
20125/// Checks the argument at the given index is an integer.
20127 unsigned ArgIndex) {
20128 Expr *ArgExpr = E->getArg(ArgIndex);
20129 if (!ArgExpr->getType()->isIntegerType()) {
20130 return S.Diag(ArgExpr->getBeginLoc(),
20131 diag::err_wasm_builtin_arg_must_be_integer_type)
20132 << ArgIndex + 1 << ArgExpr->getSourceRange();
20133 }
20134 return false;
20135}
20136
20137/// Check that the first argument is a WebAssembly table, and the second
20138/// is an index to use as index into the table.
20139bool Sema::BuiltinWasmTableGet(CallExpr *TheCall) {
20140 if (checkArgCount(*this, TheCall, 2))
20141 return true;
20142
20143 QualType ElTy;
20144 if (CheckWasmBuiltinArgIsTable(*this, TheCall, 0, ElTy))
20145 return true;
20146
20147 if (CheckWasmBuiltinArgIsInteger(*this, TheCall, 1))
20148 return true;
20149
20150 // If all is well, we set the type of TheCall to be the type of the
20151 // element of the table.
20152 // i.e. a table.get on an externref table has type externref,
20153 // or whatever the type of the table element is.
20154 TheCall->setType(ElTy);
20155
20156 return false;
20157}
20158
20159/// Check that the first argumnet is a WebAssembly table, the second is
20160/// an index to use as index into the table and the third is the reference
20161/// type to set into the table.
20162bool Sema::BuiltinWasmTableSet(CallExpr *TheCall) {
20163 if (checkArgCount(*this, TheCall, 3))
20164 return true;
20165
20166 QualType ElTy;
20167 if (CheckWasmBuiltinArgIsTable(*this, TheCall, 0, ElTy))
20168 return true;
20169
20170 if (CheckWasmBuiltinArgIsInteger(*this, TheCall, 1))
20171 return true;
20172
20173 if (!Context.hasSameType(ElTy, TheCall->getArg(2)->getType()))
20174 return true;
20175
20176 return false;
20177}
20178
20179/// Check that the argument is a WebAssembly table.
20180bool Sema::BuiltinWasmTableSize(CallExpr *TheCall) {
20181 if (checkArgCount(*this, TheCall, 1))
20182 return true;
20183
20184 QualType ElTy;
20185 if (CheckWasmBuiltinArgIsTable(*this, TheCall, 0, ElTy))
20186 return true;
20187
20188 return false;
20189}
20190
20191/// Check that the first argument is a WebAssembly table, the second is the
20192/// value to use for new elements (of a type matching the table type), the
20193/// third value is an integer.
20194bool Sema::BuiltinWasmTableGrow(CallExpr *TheCall) {
20195 if (checkArgCount(*this, TheCall, 3))
20196 return true;
20197
20198 QualType ElTy;
20199 if (CheckWasmBuiltinArgIsTable(*this, TheCall, 0, ElTy))
20200 return true;
20201
20202 Expr *NewElemArg = TheCall->getArg(1);
20203 if (!Context.hasSameType(ElTy, NewElemArg->getType())) {
20204 return Diag(NewElemArg->getBeginLoc(),
20205 diag::err_wasm_builtin_arg_must_match_table_element_type)
20206 << 2 << 1 << NewElemArg->getSourceRange();
20207 }
20208
20209 if (CheckWasmBuiltinArgIsInteger(*this, TheCall, 2))
20210 return true;
20211
20212 return false;
20213}
20214
20215/// Check that the first argument is a WebAssembly table, the second is an
20216/// integer, the third is the value to use to fill the table (of a type
20217/// matching the table type), and the fourth is an integer.
20218bool Sema::BuiltinWasmTableFill(CallExpr *TheCall) {
20219 if (checkArgCount(*this, TheCall, 4))
20220 return true;
20221
20222 QualType ElTy;
20223 if (CheckWasmBuiltinArgIsTable(*this, TheCall, 0, ElTy))
20224 return true;
20225
20226 if (CheckWasmBuiltinArgIsInteger(*this, TheCall, 1))
20227 return true;
20228
20229 Expr *NewElemArg = TheCall->getArg(2);
20230 if (!Context.hasSameType(ElTy, NewElemArg->getType())) {
20231 return Diag(NewElemArg->getBeginLoc(),
20232 diag::err_wasm_builtin_arg_must_match_table_element_type)
20233 << 3 << 1 << NewElemArg->getSourceRange();
20234 }
20235
20236 if (CheckWasmBuiltinArgIsInteger(*this, TheCall, 3))
20237 return true;
20238
20239 return false;
20240}
20241
20242/// Check that the first argument is a WebAssembly table, the second is also a
20243/// WebAssembly table (of the same element type), and the third to fifth
20244/// arguments are integers.
20245bool Sema::BuiltinWasmTableCopy(CallExpr *TheCall) {
20246 if (checkArgCount(*this, TheCall, 5))
20247 return true;
20248
20249 QualType XElTy;
20250 if (CheckWasmBuiltinArgIsTable(*this, TheCall, 0, XElTy))
20251 return true;
20252
20253 QualType YElTy;
20254 if (CheckWasmBuiltinArgIsTable(*this, TheCall, 1, YElTy))
20255 return true;
20256
20257 Expr *TableYArg = TheCall->getArg(1);
20258 if (!Context.hasSameType(XElTy, YElTy)) {
20259 return Diag(TableYArg->getBeginLoc(),
20260 diag::err_wasm_builtin_arg_must_match_table_element_type)
20261 << 2 << 1 << TableYArg->getSourceRange();
20262 }
20263
20264 for (int I = 2; I <= 4; I++) {
20265 if (CheckWasmBuiltinArgIsInteger(*this, TheCall, I))
20266 return true;
20267 }
20268
20269 return false;
20270}
20271
20272/// \brief Enforce the bounds of a TCB
20273/// CheckTCBEnforcement - Enforces that every function in a named TCB only
20274/// directly calls other functions in the same TCB as marked by the enforce_tcb
20275/// and enforce_tcb_leaf attributes.
20277 const NamedDecl *Callee) {
20278 // This warning does not make sense in code that has no runtime behavior.
20280 return;
20281
20282 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
20283
20284 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
20285 return;
20286
20287 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
20288 // all TCBs the callee is a part of.
20289 llvm::StringSet<> CalleeTCBs;
20290 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
20291 CalleeTCBs.insert(A->getTCBName());
20292 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
20293 CalleeTCBs.insert(A->getTCBName());
20294
20295 // Go through the TCBs the caller is a part of and emit warnings if Caller
20296 // is in a TCB that the Callee is not.
20297 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
20298 StringRef CallerTCB = A->getTCBName();
20299 if (CalleeTCBs.count(CallerTCB) == 0) {
20300 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
20301 << Callee << CallerTCB;
20302 }
20303 }
20304}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3285
NodeId Parent
Definition: ASTDiff.cpp:191
SyntaxTree::Impl & Tree
Definition: ASTDiff.cpp:192
ASTImporterLookupTable & LT
StringRef P
Provides definitions for the various language-specific address spaces.
#define SM(sm)
Definition: Cuda.cpp:83
Defines the Diagnostic-related interfaces.
static constexpr Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:32
static bool getTypeString(SmallStringEnc &Enc, const Decl *D, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC)
The XCore ABI includes a type information section that communicates symbol type information to the li...
Definition: XCore.cpp:632
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1125
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
LangStandard::Kind Std
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition: MachO.h:50
Defines the clang::OpenCLOptions class.
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static bool BuiltinReserveRWPipe(Sema &S, CallExpr *Call)
static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, const ValueDecl **VD, uint64_t *MagicValue, bool isConstantEvaluated)
Given a type tag expression find the type tag itself.
static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, bool InConstantContext, bool Approximate)
Pseudo-evaluate the given integer expression, estimating the range of values it might take.
static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, SourceLocation CC, QualType T)
static QualType getSizeOfArgType(const Expr *E)
If E is a sizeof expression, returns its argument type.
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, SourceLocation CallSiteLoc)
static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, IdentifierInfo *FnName, SourceLocation FnLoc, SourceLocation RParenLoc)
Takes the expression passed to the size_t parameter of functions such as memcmp, strncat,...
static const CXXRecordDecl * getContainedDynamicClass(QualType T, bool &IsContained)
Determine whether the given type is or contains a dynamic class type (e.g., whether it has a vtable).
static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call)
static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext)
Diagnose an implicit cast from a floating point value to an integer value.
static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, bool inFunctionCall, Sema::VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, bool IgnoreStringsWithoutSpecifiers)
static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call)
static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, bool *ICContext=nullptr, bool IsListInit=false)
static bool IsSameFloatAfterCast(const llvm::APFloat &value, const llvm::fltSemantics &Src, const llvm::fltSemantics &Tgt)
Checks whether the given value, which currently has the given source semantics, has the same value wh...
static StringLiteralCheckType checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, Sema::VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset, bool IgnoreStringsWithoutSpecifiers=false)
static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth)
static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool)
static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, SourceLocation CContext, unsigned diag, bool pruneControlFlow=false)
Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg)
OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local void*, which is a requirem...
static bool isX86_32Builtin(unsigned BuiltinID)
static void AnalyzeComparison(Sema &S, BinaryOperator *E)
Implements -Wsign-compare.
static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, BinaryOperatorKind BinOpKind, bool AddendIsRight)
static std::pair< QualType, StringRef > shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy, const Expr *E)
static QualType GetExprType(const Expr *E)
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx)
This helper function takes an lvalue expression and returns the alignment of a VarDecl and a constant...
static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, SourceLocation CC)
static bool OpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall)
OpenCL C v2.0, s6.13.17.6 - Check the argument to the get_kernel_work_group_size and get_kernel_prefe...
static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, Expr *Other, const llvm::APSInt &Value, bool RhsConstant)
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
bool CheckNoDoubleVectors(Sema *S, CallExpr *TheCall)
static bool isKnownToHaveUnsignedValue(Expr *E)
static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall)
static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2)
Check if two standard-layout structs are layout-compatible.
bool CheckUnsignedIntRepresentation(Sema *S, CallExpr *TheCall)
bool CheckVectorElementCallArgs(Sema *S, CallExpr *TheCall)
static unsigned RFT(unsigned t, bool shift=false, bool ForceQuad=false)
static bool hasArmZAState(const FunctionDecl *FD)
static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntType)
Diagnose integer type and any valid implicit conversion to it.
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op)
static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, Scope::ScopeFlags NeededScopeFlags, unsigned DiagID)
static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E)
Analyze the given compound assignment for the possible losing of floating-point precision.
static bool doesExprLikelyComputeSize(const Expr *SizeofExpr)
Detect if SizeofExpr is likely to calculate the sizeof an object.
static bool isObjCSignedCharBool(Sema &S, QualType Ty)
static bool OpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, CallExpr *Call)
static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall)
Check the number of arguments and set the result type to the argument type.
bool CheckFloatOrHalfRepresentations(Sema *S, CallExpr *TheCall)
static bool isValidBPFPreserveTypeInfoArg(Expr *Arg)
static bool CheckForReference(Sema &SemaRef, const Expr *E, const PartialDiagnostic &PD)
static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, int ArgIndex)
static const UnaryExprOrTypeTraitExpr * getAsSizeOfExpr(const Expr *E)
static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID)
Check that the value argument for __builtin_is_aligned(value, alignment) and __builtin_aligned_{up,...
static bool BuiltinRWPipe(Sema &S, CallExpr *Call)
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind)
static bool checkArgCountAtLeast(Sema &S, CallExpr *Call, unsigned MinArgCount)
Checks that a call expression's argument count is at least the desired number.
static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call)
Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the last two arguments transpose...
static bool checkPointerAuthEnabled(Sema &S, Expr *E)
static std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range)
AbsoluteValueKind
@ AVK_Complex
@ AVK_Floating
@ AVK_Integer
static const Expr * getStrlenExprArg(const Expr *E)
static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type.
static void checkArmStreamingBuiltin(Sema &S, CallExpr *TheCall, const FunctionDecl *FD, ArmStreamingType BuiltinType)
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall, const TargetInfo *AuxTI, unsigned BuiltinID)
BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
static bool isBlockPointer(Expr *Arg)
static bool CheckWasmBuiltinArgIsTable(Sema &S, CallExpr *E, unsigned ArgIndex, QualType &ElTy)
Checks the argument at the given index is a WebAssembly table and if it is, sets ElTy to the element ...
static void adornObjCBoolConversionDiagWithTernaryFixit(Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder)
static bool OpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall)
OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different overload formats specified ...
static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, Expr *BlockArg, unsigned NumNonVarArgs)
OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 'local void*' parameter of passed blo...
static bool BuiltinCommitRWPipe(Sema &S, CallExpr *Call)
static bool IsSameCharType(QualType T1, QualType T2)
bool CheckAllArgsHaveFloatRepresentation(Sema *S, CallExpr *TheCall)
static OpenCLAccessAttr * getOpenCLArgAccess(const Decl *D)
Returns OpenCL access qual.
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
static bool isArgumentExpandedFromMacro(SourceManager &SM, SourceLocation CallLoc, SourceLocation ArgLoc)
Check if the ArgLoc originated from a macro passed to the call at CallLoc.
static const IntegerLiteral * getIntegerLiteral(Expr *E)
static ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD)
static const Expr * maybeConstEvalStringLiteral(ASTContext &Context, const Expr *E)
static bool IsStdFunction(const FunctionDecl *FDecl, const char(&Str)[StrLen])
static void AnalyzeAssignment(Sema &S, BinaryOperator *E)
Analyze the given simple or compound assignment for warning-worthy operations.
static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_function_start is a function.
static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall)
static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, SourceLocation StmtLoc, const NullStmt *Body)
static std::pair< CharUnits, CharUnits > getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, CharUnits BaseAlignment, CharUnits Offset, ASTContext &Ctx)
Compute the alignment and offset of the base class object given the derived-to-base cast expression a...
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
static ArmSMEState getSMEState(unsigned BuiltinID)
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool &ICContext)
static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2)
Check if two types are layout-compatible in C++11 sense.
static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool isValidBPFPreserveFieldInfoArg(Expr *Arg)
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall)
static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx)
Returns true if pipe element type is different from the pointer.
static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call)
static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, SourceLocation InitLoc)
Analyzes an attempt to assign the given value to a bitfield.
static int classifyConstantValue(Expr *Constant)
static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc)
static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, unsigned AbsKind, QualType ArgType)
static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call)
Returns true if pipe element type is different from the pointer.
static bool checkPointerAuthKey(Sema &S, Expr *&Arg)
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, Qualifiers::ObjCLifetime LT, Expr *RHS, bool isProperty)
static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID)
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl)
static llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, bool IsPolyUnsigned, bool IsInt64Long)
getNeonEltType - Return the QualType corresponding to the elements of the vector type specified by th...
static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall, ArrayRef< llvm::Triple::ArchType > SupportedArchs)
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr * > Args, SourceLocation CallSiteLoc)
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction)
static bool hasArmZT0State(const FunctionDecl *FD)
static analyze_format_string::ArgType::MatchKind handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match, DiagnosticsEngine &Diags, SourceLocation Loc)
static bool referToTheSameDecl(const Expr *E1, const Expr *E2)
Check if two expressions refer to the same declaration.
static bool OpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall)
#define BUILTIN_ROW(x)
static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_{clzg,ctzg} was called with a first argument, which is an unsigned integer,...
static bool requiresParensToAddCast(const Expr *E)
static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call)
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
static void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, Expr *Element, unsigned ElementKind)
Check a single element within a collection literal against the target element type.
static bool BuiltinPipePackets(Sema &S, CallExpr *Call)
static bool CheckWasmBuiltinArgIsInteger(Sema &S, CallExpr *E, unsigned ArgIndex)
Checks the argument at the given index is an integer.
static std::optional< unsigned > getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S)
static bool checkArgCountRange(Sema &S, CallExpr *Call, unsigned MinArgCount, unsigned MaxArgCount)
Checks that a call expression's argument count is in the desired range.
static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty)
static bool ProcessFormatStringLiteral(const Expr *FormatExpr, StringRef &FormatStrRef, size_t &StrLen, ASTContext &Context)
static bool checkArgCount(Sema &S, CallExpr *Call, unsigned DesiredArgCount)
Checks that a call expression's argument count is the desired number.
static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall)
Checks that __builtin_popcountg was called with a single argument, which is an unsigned integer.
void SetElementTypeAsReturnType(Sema *S, CallExpr *TheCall, QualType ReturnType)
static const Expr * getSizeOfExprArg(const Expr *E)
If E is a sizeof expression, returns its argument expression, otherwise returns NULL.
@ TileRegHigh
@ TileRegLow
static void DiagnoseIntInBoolContext(Sema &S, Expr *E)
static bool CheckBuiltinTargetNotInUnsupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall, ArrayRef< llvm::Triple::ObjectFormatType > UnsupportedObjectFormatTypes)
static bool BuiltinAddressof(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_addressof is a glvalue, and set the result type to the correspon...
static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S)
static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call, PointerAuthOpKind OpKind)
static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn)
Check that the user is calling the appropriate va_start builtin for the target and calling convention...
static bool IsEnumConstOrFromMacro(Sema &S, Expr *E)
ArmStreamingType
@ ArmStreamingOrSVE2p1
@ ArmStreaming
@ ArmStreamingCompatible
@ ArmNonStreaming
static bool CheckInvalidVLENandLMUL(const TargetInfo &TI, CallExpr *TheCall, Sema &S, QualType Type, int EGW)
static bool GetMatchingCType(const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, const ASTContext &Ctx, const llvm::DenseMap< Sema::TypeTagMagicValue, Sema::TypeTagData > *MagicValues, bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, bool isConstantEvaluated)
Retrieve the C type corresponding to type tag TypeExpr.
static void checkObjCArrayLiteral(Sema &S, QualType TargetType, ObjCArrayLiteral *ArrayLiteral)
Check an Objective-C array literal being converted to the given target type.
static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2)
Check if two standard-layout unions are layout-compatible.
static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, unsigned &Mask)
DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, advancing the pointer ov...
static QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
static void DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, const NamedDecl *FDecl, Expr **Args, unsigned NumArgs)
Diagnose use of s directive in an NSString which is being passed as formatting string to formatting m...
static bool isNonNullType(QualType type)
Determine whether the given type has a non-null nullability annotation.
static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A, Sema::FormatArgumentPassingKind B)
static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall)
Check that the first argument to __builtin_annotation is an integer and the second argument is a non-...
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx)
This helper function takes a pointer expression and returns the alignment of a VarDecl and a constant...
static bool IsShiftedByte(llvm::APSInt Value)
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, unsigned AbsFunctionKind)
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
checkBuiltinArgument - Given a call to a builtin function, perform normal type-checking on the given ...
static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E)
Analyze the operands of the given comparison.
static bool isPPC_64Builtin(unsigned BuiltinID)
static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call)
static bool isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE)
Return true if ICE is an implicit argument promotion of an arithmetic type.
static bool isValidBPFPreserveEnumValueArg(Expr *Arg)
static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, bool IsListInit=false)
AnalyzeImplicitConversions - Find and report any interesting implicit conversions in the given expres...
static bool HasEnumType(Expr *E)
static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, unsigned Start, unsigned End)
static std::optional< std::pair< CharUnits, CharUnits > > getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, bool IsSub, ASTContext &Ctx)
Compute the alignment and offset of a binary additive operator.
static bool checkFPMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, int ArgIndex)
ArmSMEState
@ ArmInOutZA
@ ArmOutZA
@ ArmInZT0
@ ArmNoState
@ ArmZT0Mask
@ ArmZAMask
@ ArmOutZT0
@ ArmInOutZT0
@ ArmInZA
static bool checkArgCountAtMost(Sema &S, CallExpr *Call, unsigned MaxArgCount)
Checks that a call expression's argument count is at most the desired number.
static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
bool CheckArgsTypesAreCorrect(Sema *S, CallExpr *TheCall, QualType ExpectedType, llvm::function_ref< bool(clang::QualType PassedType)> Check)
SourceRange Range
Definition: SemaObjC.cpp:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
This file declares semantic analysis for Objective-C.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Provides definitions for the atomic synchronization scopes.
Enumerates target-specific builtins in their own namespaces within namespace clang.
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
C Language Family Type Representation.
const NestedNameSpecifier * Specifier
std::string Label
__DEVICE__ int min(int __a, int __b)
__device__ int
__device__ __2f16 float __ockl_bool s
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
APSInt & getInt()
Definition: APValue.h:423
bool isVector() const
Definition: APValue.h:407
APSInt & getComplexIntImag()
Definition: APValue.h:461
bool isComplexInt() const
Definition: APValue.h:404
bool isFloat() const
Definition: APValue.h:402
bool isComplexFloat() const
Definition: APValue.h:405
APValue & getVectorElt(unsigned I)
Definition: APValue.h:497
unsigned getVectorLength() const
Definition: APValue.h:505
bool isLValue() const
Definition: APValue.h:406
bool isInt() const
Definition: APValue.h:401
APSInt & getComplexIntReal()
Definition: APValue.h:453
APFloat & getComplexFloatImag()
Definition: APValue.h:477
APFloat & getComplexFloatReal()
Definition: APValue.h:469
APFloat & getFloat()
Definition: APValue.h:437
bool isAddrLabelDiff() const
Definition: APValue.h:412
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2768
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
CanQualType LongTy
Definition: ASTContext.h:1100
unsigned getIntWidth(QualType T) const
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
QualType getRecordType(const RecordDecl *Decl) const
CanQualType FloatTy
Definition: ASTContext.h:1103
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2575
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2591
CanQualType DoubleTy
Definition: ASTContext.h:1103
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
CanQualType LongDoubleTy
Definition: ASTContext.h:1103
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1118
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1119
IdentifierTable & Idents
Definition: ASTContext.h:644
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:646
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
Definition: ASTContext.h:1092
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:758
CanQualType Float128Ty
Definition: ASTContext.h:1103
CanQualType UnsignedLongTy
Definition: ASTContext.h:1101
llvm::APFixedPoint getFixedPointMin(QualType Ty) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType CharTy
Definition: ASTContext.h:1093
CanQualType IntTy
Definition: ASTContext.h:1100
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2157
CanQualType SignedCharTy
Definition: ASTContext.h:1100
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
CanQualType OCLClkEventTy
Definition: ASTContext.h:1128
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:697
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2618
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2341
CanQualType BuiltinFnTy
Definition: ASTContext.h:1121
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1091
CanQualType UnsignedCharTy
Definition: ASTContext.h:1101
CanQualType UnsignedIntTy
Definition: ASTContext.h:1101
QualType getExceptionObjectType(QualType T) const
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1102
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1129
CanQualType UnsignedShortTy
Definition: ASTContext.h:1101
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1569
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType ShortTy
Definition: ASTContext.h:1100
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
CanQualType OCLQueueTy
Definition: ASTContext.h:1129
CanQualType BFloat16Ty
Definition: ASTContext.h:1116
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
Definition: ASTContext.h:1100
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Underlying=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const
@ GE_None
No error.
Definition: ASTContext.h:2243
CanQualType HalfTy
Definition: ASTContext.h:1115
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
CanQualType getNSUIntegerType() const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2345
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getNonVirtualAlignment() const
getNonVirtualAlignment - Get the non-virtual alignment (in chars) of an object, which is the alignmen...
Definition: RecordLayout.h:218
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition: Expr.h:4141
Expr * getCond() const
getCond - Return the expression representing the condition for the ?: operator.
Definition: Expr.h:4319
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition: Expr.h:4325
SourceLocation getQuestionLoc() const
Definition: Expr.h:4168
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition: Expr.h:4331
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
This class represents BOTH the OpenMP Array Section and OpenACC 'subarray', with a boolean differenti...
Definition: Expr.h:6734
Expr * getBase()
Get base of the array section.
Definition: Expr.h:6800
Expr * getLowerBound()
Get lower bound of array section.
Definition: Expr.h:6804
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2664
SourceLocation getRBracketLoc() const
Definition: Expr.h:2712
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition: Expr.h:2693
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3518
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3532
QualType getElementType() const
Definition: Type.h:3530
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition: Expr.h:6437
std::unique_ptr< AtomicScopeModel > getScopeModel() const
Get atomic scope model.
Definition: Expr.h:6578
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:6544
Attr - This represents one attribute.
Definition: Attr.h:42
const char * getSpelling() const
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5981
ConceptDecl * getTypeConstraintConcept() const
Definition: Type.h:5996
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3840
static bool isLogicalOp(Opcode Opc)
Definition: Expr.h:3972
Expr * getLHS() const
Definition: Expr.h:3889
SourceLocation getOperatorLoc() const
Definition: Expr.h:3881
SourceLocation getExprLoc() const
Definition: Expr.h:3880
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:2134
Expr * getRHS() const
Definition: Expr.h:3891
bool isEqualityOp() const
Definition: Expr.h:3937
static bool isAdditiveOp(Opcode Opc)
Definition: Expr.h:3925
Opcode getOpcode() const
Definition: Expr.h:3884
static bool isEqualityOp(Opcode Opc)
Definition: Expr.h:3936
A fixed int type of a specified bitwidth.
Definition: Type.h:7242
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4494
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:4600
Pointer to a block type.
Definition: Type.h:3349
QualType getPointeeType() const
Definition: Type.h:3361
This class is used for builtin types like 'int'.
Definition: Type.h:2981
bool isInteger() const
Definition: Type.h:3036
bool isFloatingPoint() const
Definition: Type.h:3048
bool isSignedInteger() const
Definition: Type.h:3040
bool isUnsignedInteger() const
Definition: Type.h:3044
Kind getKind() const
Definition: Type.h:3023
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition: Builtins.h:262
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition: Builtins.h:222
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
unsigned getAuxBuiltinID(unsigned ID) const
Return real builtin ID (i.e.
Definition: Builtins.h:268
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:111
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition: Expr.h:3771
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1542
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition: ExprCXX.h:1624
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition: ExprCXX.h:1682
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
SourceLocation getExprLoc() const LLVM_READONLY
Definition: ExprCXX.h:151
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition: ExprCXX.h:111
Represents a list-initialization with parenthesis.
Definition: ExprCXX.h:4944
ArrayRef< Expr * > getInitExprs()
Definition: ExprCXX.h:4984
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition: DeclCXX.h:1226
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:613
base_class_iterator bases_begin()
Definition: DeclCXX.h:626
bool isDynamicClass() const
Definition: DeclCXX.h:585
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2820
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3011
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3024
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1638
arg_iterator arg_begin()
Definition: Expr.h:3064
arg_iterator arg_end()
Definition: Expr.h:3067
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2990
bool isCallToStdMove() const
Definition: Expr.cpp:3510
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:1647
Expr * getCallee()
Definition: Expr.h:2970
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2998
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition: Expr.h:3096
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:3001
arg_range arguments()
Definition: Expr.h:3059
SourceLocation getRParenLoc() const
Definition: Expr.h:3130
Decl * getCalleeDecl()
Definition: Expr.h:2984
bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const
Returns true if this is a call to a builtin which does not evaluate side-effects within its arguments...
Definition: Expr.cpp:1584
void setCallee(Expr *F)
Definition: Expr.h:2972
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3483
path_iterator path_begin()
Definition: Expr.h:3553
CastKind getCastKind() const
Definition: Expr.h:3527
path_iterator path_end()
Definition: Expr.h:3554
Expr * getSubExpr()
Definition: Expr.h:3533
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
bool isOne() const
isOne - Test whether the quantity equals one.
Definition: CharUnits.h:125
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:28
Complex values, per C99 6.2.5p11.
Definition: Type.h:3086
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:4088
Declaration of a C++20 concept.
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4179
Expr * getLHS() const
Definition: Expr.h:4213
Expr * getRHS() const
Definition: Expr.h:4214
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3556
QualType desugar() const
Definition: Type.h:3657
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3612
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4167
static constexpr unsigned getMaxElementsPerDimension()
Returns the maximum number of elements per dimension.
Definition: Type.h:4201
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition: Type.h:4196
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4499
Represents an expression that might suspend coroutine execution; either a co_await or co_yield expres...
Definition: ExprCXX.h:5061
Expr * getOperand() const
Definition: ExprCXX.h:5130
child_range children()
Definition: ExprCXX.h:5160
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2342
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1282
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2322
bool isFunctionOrMethod() const
Definition: DeclBase.h:2118
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:488
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition: Expr.h:1347
ValueDecl * getDecl()
Definition: Expr.h:1328
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition: Expr.h:1452
SourceLocation getLocation() const
Definition: Expr.h:1336
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isInStdNamespace() const
Definition: DeclBase.cpp:403
T * getAttr() const
Definition: DeclBase.h:579
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:515
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1132
bool isInvalidDecl() const
Definition: DeclBase.h:594
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:565
SourceLocation getLocation() const
Definition: DeclBase.h:445
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:437
bool hasAttr() const
Definition: DeclBase.h:583
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:433
The name of a declaration.
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1985
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
RAII class that determines when any errors have occurred between the time the instance was created an...
Definition: Diagnostic.h:1077
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Definition: Diagnostic.h:1088
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3297
Represents an enum.
Definition: Decl.h:3867
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:4064
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4086
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists,...
Definition: Decl.h:4043
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4027
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum.
Definition: Decl.h:4053
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5575
This represents one expression.
Definition: Expr.h:110
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition: Expr.h:671
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition: Expr.h:668
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3064
void setType(QualType t)
Definition: Expr.h:143
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3059
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3047
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3055
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4084
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:821
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:825
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3051
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3556
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3039
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition: Expr.h:792
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:801
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:804
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition: Expr.h:794
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3923
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition: Expr.cpp:266
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:454
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition: Expr.h:457
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isFlexibleArrayMemberLike(ASTContext &Context, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution=false) const
Check whether this array fits the idiom of a flexible array member, depending on the value of -fstric...
Definition: Expr.cpp:206
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
const ValueDecl * getAsBuiltinConstantDeclRef(const ASTContext &Context) const
If this expression is an unambiguous reference to a single declaration, in the style of __builtin_fun...
Definition: Expr.cpp:226
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition: Expr.cpp:136
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition: Type.h:4061
Represents a member of a struct/union/class.
Definition: Decl.h:3057
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3148
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4592
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3270
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition: Decl.h:3161
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
llvm::APFloat getValue() const
Definition: Expr.h:1647
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:2781
Represents a function declaration or definition.
Definition: Decl.h:1971
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition: Decl.cpp:4399
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2706
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3713
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3632
param_iterator param_end()
Definition: Decl.h:2696
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3731
QualType getReturnType() const
Definition: Decl.h:2754
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2683
param_iterator param_begin()
Definition: Decl.h:2695
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3089
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4178
bool isStatic() const
Definition: Decl.h:2838
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3993
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3979
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3692
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4656
unsigned getNumParams() const
Definition: Type.h:4889
QualType getParamType(unsigned i) const
Definition: Type.h:4891
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition: Type.h:5094
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5012
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4900
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:5007
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4896
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4256
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4543
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4539
QualType getReturnType() const
Definition: Type.h:4573
@ SME_PStateSMEnabledMask
Definition: Type.h:4517
@ SME_PStateSMCompatibleMask
Definition: Type.h:4518
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3655
Describes an C or C++ initializer list.
Definition: Expr.h:4847
ArrayRef< Expr * > inits()
Definition: Expr.h:4887
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:977
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:1024
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1060
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition: Lexer.cpp:499
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1107
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition: Lexer.cpp:850
Represents the results of name lookup.
Definition: Lookup.h:46
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:568
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition: Type.h:4152
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3172
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3255
Expr * getBase() const
Definition: Expr.h:3249
bool isArrow() const
Definition: Expr.h:3356
This represents a decl that may have a name.
Definition: Decl.h:249
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
ObjCStringFormatFamily getObjCFStringFormattingFamily() const
Definition: Decl.cpp:1156
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1927
Represent a C++ namespace.
Definition: Decl.h:547
Flags to identify the types for overloaded Neon builtins.
bool isUnsigned() const
EltType getEltType() const
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition: Stmt.h:1569
bool hasLeadingEmptyMacro() const
Definition: Stmt.h:1583
SourceLocation getSemiLoc() const
Definition: Stmt.h:1580
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp,...
Definition: ExprObjC.h:191
Expr * getElement(unsigned Index)
getElement - Return the Element at the specified index.
Definition: ExprObjC.h:231
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c array literal.
Definition: ExprObjC.h:228
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition: ExprObjC.h:309
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c dictionary literal.
Definition: ExprObjC.h:360
ObjCDictionaryElement getKeyValueElement(unsigned Index) const
Definition: ExprObjC.h:362
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1913
Represents a pointer to an Objective C object.
Definition: Type.h:7008
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments for this type.
Definition: Type.h:7112
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
QualType getType() const
Definition: DeclObjC.h:803
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition: DeclObjC.h:826
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition: DeclObjC.h:814
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition: ExprObjC.h:617
ObjCPropertyDecl * getExplicitProperty() const
Definition: ExprObjC.h:706
bool isImplicitProperty() const
Definition: ExprObjC.h:703
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:51
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
bool isSupported(llvm::StringRef Ext, const LangOptions &LO) const
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:2130
Represents a parameter to a function.
Definition: Decl.h:1761
PipeType - OpenCL20.
Definition: Type.h:7208
QualType getElementType() const
Definition: Type.h:7219
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3139
QualType getPointeeType() const
Definition: Type.h:3149
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6305
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition: Expr.cpp:4880
A (possibly-)qualified type.
Definition: Type.h:940
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7443
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:7437
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2737
PrimitiveDefaultInitializeKind
Definition: Type.h:1451
QualType withoutLocalFastQualifiers() const
Definition: Type.h:1209
QualType withConst() const
Definition: Type.h:1154
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:7541
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7359
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7485
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:1100
QualType withVolatile() const
Definition: Type.h:1162
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7399
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1432
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition: Type.h:7411
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7453
void removeLocalVolatile()
Definition: Type.h:7475
void removeLocalConst()
Definition: Type.h:7467
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7432
const Type * getTypePtrOrNull() const
Definition: Type.h:7363
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1436
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:347
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:340
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:336
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:350
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:353
bool hasUnaligned() const
Definition: Type.h:497
Represents a struct/union/class.
Definition: Decl.h:4168
field_iterator field_end() const
Definition: Decl.h:4377
field_range fields() const
Definition: Decl.h:4374
field_iterator field_begin() const
Definition: Decl.cpp:5069
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5549
RecordDecl * getDecl() const
Definition: Type.h:5559
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
ScopeFlags
ScopeFlags - These are bitfields that are or'd together when creating a scope, which defines the sort...
Definition: Scope.h:45
@ SEHFilterScope
We are currently in the filter expression of an SEH except block.
Definition: Scope.h:131
@ SEHExceptScope
This scope corresponds to an SEH except.
Definition: Scope.h:128
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:56
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
ObjCInterfaceDecl * NSArrayDecl
The declaration of the Objective-C NSArray class.
Definition: SemaObjC.h:608
ObjCInterfaceDecl * NSDictionaryDecl
The declaration of the Objective-C NSDictionary class.
Definition: SemaObjC.h:614
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: SemaObjC.h:578
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:451
const FieldDecl * getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned)
Returns a field in a CXXRecordDecl that has the same name as the decl SelfAssigned when inside a CXXM...
Definition: SemaExpr.cpp:14480
bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base, const TypeSourceInfo *Derived)
bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef< const Expr * > Args, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any non-ArgDependent DiagnoseIf...
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:9702
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:688
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition: Sema.cpp:2459
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7287
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7295
@ LookupAnyName
Look up any declaration with any name.
Definition: Sema.h:7332
VariadicCallType
Definition: Sema.h:2004
@ VariadicDoesNotApply
Definition: Sema.h:2009
@ VariadicFunction
Definition: Sema.h:2005
@ VariadicConstructor
Definition: Sema.h:2008
@ VariadicBlock
Definition: Sema.h:2006
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull)
Register a magic integral constant to be used as a type tag.
bool isValidPointerAttrType(QualType T, bool RefOkay=false)
Determine if type T is a valid subject for a nonnull and similar attributes.
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
bool FormatStringHasSArg(const StringLiteral *FExpr)
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
Definition: SemaExpr.cpp:1563
static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, bool IsVariadic, FormatStringInfo *FSI)
Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo parameter with the Format...
void RefersToMemberWithReducedAlignment(Expr *E, llvm::function_ref< void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action)
This function calls Action when it determines that E designates a misaligned member due to the packed...
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition: Sema.cpp:1499
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition: SemaExpr.cpp:798
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but will create a trap if the resul...
Definition: SemaExpr.cpp:1048
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
Definition: SemaExpr.cpp:5045
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:14108
ASTContext & Context
Definition: Sema.h:848
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:514
static FormatStringType GetFormatStringType(const FormatAttr *Format)
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
SemaObjC & ObjC()
Definition: Sema.h:1003
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:764
ASTContext & getASTContext() const
Definition: Sema.h:517
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15667
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:645
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition: Sema.h:1859
bool BuiltinVectorToScalarMath(CallExpr *TheCall)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:765
bool CheckHLSLBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
Warn if a value is moved to itself.
AtomicArgumentOrder
Definition: Sema.h:1959
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:65
bool IsLayoutCompatible(QualType T1, QualType T2) const
const LangOptions & getLangOpts() const
Definition: Sema.h:510
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
Definition: SemaType.cpp:8801
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:5723
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6464
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
bool hasCStrMethod(const Expr *E)
Check to see if a given expression could have '.c_str()' called on it.
const LangOptions & LangOpts
Definition: Sema.h:846
static const uint64_t MaximumAlignment
Definition: Sema.h:788
SemaHLSL & HLSL()
Definition: Sema.h:998
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx)
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:5149
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1511
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:946
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
Definition: SemaCast.cpp:3341
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:882
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition: Sema.h:1937
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
Definition: SemaExpr.cpp:9682
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition: Sema.cpp:2085
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID)
Emit DiagID if statement located on StmtLoc has a suspicious null statement as a Body,...
void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody)
Warn if a for/while loop statement S, which is followed by PossibleBody, has a suspicious null statem...
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:652
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
bool BuiltinVectorMath(CallExpr *TheCall, QualType &Res)
void CheckTCBEnforcement(const SourceLocation CallExprLoc, const NamedDecl *Callee)
Enforce the bounds of a TCB CheckTCBEnforcement - Enforces that every function in a named TCB only di...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:986
@ VAK_Invalid
Definition: Sema.h:5980
@ VAK_Valid
Definition: Sema.h:5976
@ VAK_ValidInCXX11
Definition: Sema.h:5977
@ VAK_MSVCUndefined
Definition: Sema.h:5979
@ VAK_Undefined
Definition: Sema.h:5978
FormatArgumentPassingKind
Definition: Sema.h:1869
@ FAPK_Fixed
Definition: Sema.h:1870
@ FAPK_Variadic
Definition: Sema.h:1871
@ FAPK_VAList
Definition: Sema.h:1872
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:6211
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:6018
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:6020
@ ACK_Comparison
A comparison.
Definition: Sema.h:5867
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20806
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:10401
SourceManager & getSourceManager() const
Definition: Sema.h:515
@ AA_Assigning
Definition: Sema.h:5158
@ AA_Passing
Definition: Sema.h:5159
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20084
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:228
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
bool isConstantEvaluatedContext() const
Definition: Sema.h:1861
ExprResult BuiltinShuffleVector(CallExpr *TheCall)
BuiltinShuffleVector - Handle __builtin_shufflevector.
QualType GetSignedVectorType(QualType V)
Definition: SemaExpr.cpp:12645
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8831
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:820
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SourceManager & SourceMgr
Definition: Sema.h:851
DiagnosticsEngine & Diags
Definition: Sema.h:850
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:511
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10684
void checkVariadicArgument(const Expr *E, VariadicCallType CT)
Check to see if the given expression is a valid argument to a variadic function, issuing a diagnostic...
Definition: SemaExpr.cpp:1001
FormatStringType
Definition: Sema.h:1892
@ FST_NSString
Definition: Sema.h:1895
@ FST_Unknown
Definition: Sema.h:1902
@ FST_Strftime
Definition: Sema.h:1896
@ FST_Printf
Definition: Sema.h:1894
@ FST_FreeBSDKPrintf
Definition: Sema.h:1899
@ FST_Scanf
Definition: Sema.h:1893
@ FST_Strfmon
Definition: Sema.h:1897
@ FST_OSLog
Definition: Sema.h:1901
@ FST_Kprintf
Definition: Sema.h:1898
@ FST_OSTrace
Definition: Sema.h:1900
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:520
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
Definition: SemaExpr.cpp:16705
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:17940
@ AbstractParamType
Definition: Sema.h:4547
ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder=AtomicArgumentOrder::API)
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E)
CheckCXXThrowOperand - Validate the operand of a throw.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition: Expr.h:4431
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isWrittenInSameFile(SourceLocation Loc1, SourceLocation Loc2) const
Returns true if the spelling locations for both SourceLocations are part of the same file buffer.
unsigned getPresumedColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
child_range children()
Definition: Stmt.cpp:287
StmtClass getStmtClass() const
Definition: Stmt.h:1358
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1954
bool isUTF8() const
Definition: Expr.h:1899
bool isWide() const
Definition: Expr.h:1898
bool isPascal() const
Definition: Expr.h:1903
unsigned getLength() const
Definition: Expr.h:1890
StringLiteralKind getKind() const
Definition: Expr.h:1893
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
getLocationOfByte - Return a source location that points to the specified byte of this string literal...
Definition: Expr.cpp:1329
bool isUTF32() const
Definition: Expr.h:1901
unsigned getByteLength() const
Definition: Expr.h:1889
StringRef getString() const
Definition: Expr.h:1850
bool isUTF16() const
Definition: Expr.h:1900
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.h:1955
bool isOrdinary() const
Definition: Expr.h:1897
unsigned getCharByteWidth() const
Definition: Expr.h:1891
bool isUnion() const
Definition: Decl.h:3790
Exposes information about the current target.
Definition: TargetInfo.h:218
virtual bool validatePointerAuthKey(const llvm::APSInt &value) const
Determine whether the given pointer-authentication key is valid.
Definition: TargetInfo.cpp:939
virtual bool supportsCpuSupports() const
Definition: TargetInfo.h:1498
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1518
virtual bool supportsCpuInit() const
Definition: TargetInfo.h:1500
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
IntType getInt64Type() const
Definition: TargetInfo.h:405
virtual bool useFP16ConversionIntrinsics() const
Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used to convert to and from __fp...
Definition: TargetInfo.h:992
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Definition: TargetInfo.cpp:270
IntType getSizeType() const
Definition: TargetInfo.h:371
IntType getIntPtrType() const
Definition: TargetInfo.h:397
uint32_t getARMCDECoprocMask() const
For ARM targets returns a mask defining which coprocessors are configured as Custom Datapath.
Definition: TargetInfo.h:1052
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1504
virtual bool supportsCpuIs() const
Definition: TargetInfo.h:1499
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:785
virtual bool checkArithmeticFenceSupported() const
Controls if __arithmetic_fence is supported in the targeted backend.
Definition: TargetInfo.h:1657
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1472
virtual bool hasSjLjLowering() const
Controls if __builtin_longjmp / __builtin_setjmp can be lowered to llvm.eh.sjlj.longjmp / llvm....
Definition: TargetInfo.h:1706
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Definition: DeclTemplate.h:265
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
const Type * getTypeForDecl() const
Definition: Decl.h:3414
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: Type.h:5274
A container of type source information.
Definition: Type.h:7330
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7341
The base class of the type hierarchy.
Definition: Type.h:1813
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1871
bool isBlockPointerType() const
Definition: Type.h:7620
bool isVoidType() const
Definition: Type.h:7905
bool isBooleanType() const
Definition: Type.h:8033
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8083
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:730
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2135
bool isFloat16Type() const
Definition: Type.h:7914
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2206
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2060
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8063
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition: Type.cpp:2010
bool isVoidPointerType() const
Definition: Type.cpp:655
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2341
bool isArrayType() const
Definition: Type.h:7678
bool isCharType() const
Definition: Type.cpp:2078
bool isFunctionPointerType() const
Definition: Type.h:7646
bool isPointerType() const
Definition: Type.h:7612
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7945
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8193
bool isReferenceType() const
Definition: Type.h:7624
bool isEnumeralType() const
Definition: Type.h:7710
bool isScalarType() const
Definition: Type.h:8004
bool isVariableArrayType() const
Definition: Type.h:7690
bool isClkEventT() const
Definition: Type.h:7817
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2496
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2047
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:695
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8020
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2225
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2534
bool isPipeType() const
Definition: Type.h:7836
bool isBitIntType() const
Definition: Type.h:7840
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7874
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:7702
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2653
bool isFloat32Type() const
Definition: Type.h:7918
bool isAnyComplexType() const
Definition: Type.h:7714
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7958
bool isHalfType() const
Definition: Type.h:7909
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:7887
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2175
QualType getCanonicalTypeInternal() const
Definition: Type.h:2936
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2453
bool isQueueT() const
Definition: Type.h:7821
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8076
bool isMemberPointerType() const
Definition: Type.h:7660
bool isAtomicType() const
Definition: Type.h:7757
bool isFunctionProtoType() const
Definition: Type.h:2494
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition: Type.cpp:2982
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2671
bool isObjCObjectType() const
Definition: Type.h:7748
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8179
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8039
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2405
bool isBFloat16Type() const
Definition: Type.h:7926
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2351
bool isFunctionType() const
Definition: Type.h:7608
bool isObjCObjectPointerType() const
Definition: Type.h:7744
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2247
bool isStructureOrClassType() const
Definition: Type.cpp:647
bool isVectorType() const
Definition: Type.h:7718
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2255
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2483
bool isFloatingType() const
Definition: Type.cpp:2238
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2185
bool isAnyPointerType() const
Definition: Type.h:7616
TypeClass getTypeClass() const
Definition: Type.h:2300
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2326
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8126
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:605
bool isNullPtrType() const
Definition: Type.h:7938
bool isRecordType() const
Definition: Type.h:7706
bool isObjCRetainableType() const
Definition: Type.cpp:4886
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4633
bool isUnionType() const
Definition: Type.cpp:661
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2465
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition: Type.cpp:2522
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1875
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3432
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2568
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2183
Expr * getSubExpr() const
Definition: Expr.h:2228
Opcode getOpcode() const
Definition: Expr.h:2223
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:2305
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3320
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
QualType getType() const
Definition: Decl.h:717
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5365
Represents a variable declaration or definition.
Definition: Decl.h:918
Represents a GCC generic vector type.
Definition: Type.h:3969
unsigned getNumElements() const
Definition: Type.h:3984
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:2584
MatchKind
How well a given conversion specifier matches its argument.
Definition: FormatString.h:271
@ NoMatch
The conversion specifier and the argument types are incompatible.
Definition: FormatString.h:274
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
Definition: FormatString.h:286
@ Match
The conversion specifier and the argument type are compatible.
Definition: FormatString.h:277
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
Definition: FormatString.h:288
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
std::optional< ConversionSpecifier > getStandardSpecifier() const
ArgType getArgType(ASTContext &Ctx) const
Class representing optional flags with location and representation information.
Definition: FormatString.h:34
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
Definition: ScopeInfo.cpp:160
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition: larchintrin.h:181
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
bool parseFormatStringHasFormattingSpecifiers(const char *Begin, const char *End, const LangOptions &LO, const TargetInfo &Target)
Return true if the given string has at least one formatting specifier.
bool ParsePrintfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target, bool isFreeBSDKPrintf)
bool ParseScanfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
bool ParseFormatStringHasSArg(const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
const AstTypeMatcher< PointerType > pointerType
Matches pointer types, but does not match Objective-C object pointer types.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
ComparisonResult
Indicates the result of a tentative comparison.
uint32_t Literal
Literals are represented as positive integers.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:68
@ After
Like System, but searched after the system directories.
@ FixIt
Parse and apply any fixits to the source.
bool GT(InterpState &S, CodePtr OpPC)
Definition: Interp.h:890
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:868
bool LE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:882
bool InRange(InterpState &S, CodePtr OpPC)
Definition: Interp.h:909
bool Cast(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1713
bool EQ(InterpState &S, CodePtr OpPC)
Definition: Interp.h:837
bool GE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:897
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
The JSON file list parser is used to communicate input to InstallAPI.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
ObjCStringFormatFamily
@ CPlusPlus
Definition: LangStandard.h:55
Expr * IgnoreElidableImplicitConstructorSingleStep(Expr *E)
Definition: IgnoreExpr.h:125
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ NonNull
Values of this type can never be null.
Expr * IgnoreExprNodes(Expr *E, FnTys &&... Fns)
Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *, Recursively apply each of the f...
Definition: IgnoreExpr.h:34
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:146
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:151
BinaryOperatorKind
@ SC_Register
Definition: Specifiers.h:254
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ Result
The result type of a method or function.
ExprResult ExprError()
Definition: Ownership.h:264
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
CastKind
CastKind - The kind of operation required for a conversion.
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
for(const auto &A :T->param_types())
const FunctionProtoType * T
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition: IgnoreExpr.h:137
StringLiteralKind
Definition: Expr.h:1744
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ Success
Template argument deduction was successful.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_Win64
Definition: Specifiers.h:282
@ CC_C
Definition: Specifiers.h:276
@ CC_X86_64SysV
Definition: Specifiers.h:283
@ AltiVecVector
is AltiVec vector
@ Generic
not a target-specific vector type
U cast(CodeGen::Address addr)
Definition: Address.h:291
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Other
Other implicit parameter.
@ AS_public
Definition: Specifiers.h:121
unsigned long uint64_t
long int64_t
Definition: Format.h:5428
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
#define bool
Definition: stdbool.h:24
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:630
Extra information about a function prototype.
Definition: Type.h:4735
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
unsigned AnonymousTagLocations
When printing an anonymous tag name, also print the location of that entity (e.g.,...
unsigned Indentation
The number of spaces to use to indent each line.
Definition: PrettyPrinter.h:93
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:9719
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:9836
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition: Sema.h:9862
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition: Sema.h:9852
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition: Sema.h:9817
FormatArgumentPassingKind ArgPassingKind
Definition: Sema.h:1880
#define log2(__x)
Definition: tgmath.h:970