clang 23.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 "CheckExprLifetime.h"
15#include "clang/AST/APValue.h"
18#include "clang/AST/Attr.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclObjC.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprObjC.h"
32#include "clang/AST/NSAPI.h"
36#include "clang/AST/Stmt.h"
39#include "clang/AST/Type.h"
40#include "clang/AST/TypeBase.h"
41#include "clang/AST/TypeLoc.h"
47#include "clang/Basic/LLVM.h"
58#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
60#include "clang/Sema/Lookup.h"
62#include "clang/Sema/Scope.h"
64#include "clang/Sema/Sema.h"
66#include "clang/Sema/SemaARM.h"
67#include "clang/Sema/SemaBPF.h"
69#include "clang/Sema/SemaHLSL.h"
72#include "clang/Sema/SemaMIPS.h"
74#include "clang/Sema/SemaObjC.h"
76#include "clang/Sema/SemaPPC.h"
79#include "clang/Sema/SemaSYCL.h"
81#include "clang/Sema/SemaWasm.h"
82#include "clang/Sema/SemaX86.h"
83#include "llvm/ADT/APFloat.h"
84#include "llvm/ADT/APInt.h"
85#include "llvm/ADT/APSInt.h"
86#include "llvm/ADT/ArrayRef.h"
87#include "llvm/ADT/DenseMap.h"
88#include "llvm/ADT/FoldingSet.h"
89#include "llvm/ADT/STLExtras.h"
90#include "llvm/ADT/STLForwardCompat.h"
91#include "llvm/ADT/SmallBitVector.h"
92#include "llvm/ADT/SmallPtrSet.h"
93#include "llvm/ADT/SmallString.h"
94#include "llvm/ADT/SmallVector.h"
95#include "llvm/ADT/StringExtras.h"
96#include "llvm/ADT/StringRef.h"
97#include "llvm/ADT/StringSet.h"
98#include "llvm/ADT/StringSwitch.h"
99#include "llvm/Support/AtomicOrdering.h"
100#include "llvm/Support/Compiler.h"
101#include "llvm/Support/ConvertUTF.h"
102#include "llvm/Support/ErrorHandling.h"
103#include "llvm/Support/Format.h"
104#include "llvm/Support/Locale.h"
105#include "llvm/Support/MathExtras.h"
106#include "llvm/Support/SaveAndRestore.h"
107#include "llvm/Support/raw_ostream.h"
108#include "llvm/TargetParser/RISCVTargetParser.h"
109#include "llvm/TargetParser/Triple.h"
110#include <algorithm>
111#include <cassert>
112#include <cctype>
113#include <cstddef>
114#include <cstdint>
115#include <functional>
116#include <limits>
117#include <optional>
118#include <string>
119#include <tuple>
120#include <utility>
121
122using namespace clang;
123using namespace sema;
124
126 unsigned ByteNo) const {
127 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
128 Context.getTargetInfo());
129}
130
131static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
133 return (A << 8) | B;
134}
135
136bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
137 unsigned ArgCount = Call->getNumArgs();
138 if (ArgCount >= MinArgCount)
139 return false;
140
141 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
142 << 0 /*function call*/ << MinArgCount << ArgCount
143 << /*is non object*/ 0 << Call->getSourceRange();
144}
145
146bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
147 unsigned ArgCount = Call->getNumArgs();
148 if (ArgCount <= MaxArgCount)
149 return false;
150 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)
151 << 0 /*function call*/ << MaxArgCount << ArgCount
152 << /*is non object*/ 0 << Call->getSourceRange();
153}
154
155bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
156 unsigned MaxArgCount) {
157 return checkArgCountAtLeast(Call, MinArgCount) ||
158 checkArgCountAtMost(Call, MaxArgCount);
159}
160
161bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
162 unsigned ArgCount = Call->getNumArgs();
163 if (ArgCount == DesiredArgCount)
164 return false;
165
166 if (checkArgCountAtLeast(Call, DesiredArgCount))
167 return true;
168 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
169
170 // Highlight all the excess arguments.
171 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
172 Call->getArg(ArgCount - 1)->getEndLoc());
173
174 return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
175 << 0 /*function call*/ << DesiredArgCount << ArgCount
176 << /*is non object*/ 0 << Range;
177}
178
180 bool HasError = false;
181
182 for (const Expr *Arg : Call->arguments()) {
183 if (Arg->isValueDependent())
184 continue;
185
186 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
187 int DiagMsgKind = -1;
188 // Arguments must be pointers to constant strings and cannot use '$'.
189 if (!ArgString.has_value())
190 DiagMsgKind = 0;
191 else if (ArgString->find('$') != std::string::npos)
192 DiagMsgKind = 1;
193
194 if (DiagMsgKind >= 0) {
195 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
196 << DiagMsgKind << Arg->getSourceRange();
197 HasError = true;
198 }
199 }
200
201 return !HasError;
202}
203
205 if (Value->isTypeDependent())
206 return false;
207
208 InitializedEntity Entity =
212 if (Result.isInvalid())
213 return true;
214 Value = Result.get();
215 return false;
216}
217
218/// Check that the first argument to __builtin_annotation is an integer
219/// and the second argument is a non-wide string literal.
220static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
221 if (S.checkArgCount(TheCall, 2))
222 return true;
223
224 // First argument should be an integer.
225 Expr *ValArg = TheCall->getArg(0);
226 QualType Ty = ValArg->getType();
227 if (!Ty->isIntegerType()) {
228 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
229 << ValArg->getSourceRange();
230 return true;
231 }
232
233 // Second argument should be a constant string.
234 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
235 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
236 if (!Literal || !Literal->isOrdinary()) {
237 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
238 << StrArg->getSourceRange();
239 return true;
240 }
241
242 TheCall->setType(Ty);
243 return false;
244}
245
246static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
247 // We need at least one argument.
248 if (TheCall->getNumArgs() < 1) {
249 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
250 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
251 << TheCall->getCallee()->getSourceRange();
252 return true;
253 }
254
255 // All arguments should be wide string literals.
256 for (Expr *Arg : TheCall->arguments()) {
257 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
258 if (!Literal || !Literal->isWide()) {
259 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
260 << Arg->getSourceRange();
261 return true;
262 }
263 }
264
265 return false;
266}
267
268/// Check that the argument to __builtin_addressof is a glvalue, and set the
269/// result type to the corresponding pointer type.
270static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
271 if (S.checkArgCount(TheCall, 1))
272 return true;
273
274 ExprResult Arg(TheCall->getArg(0));
275 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
276 if (ResultType.isNull())
277 return true;
278
279 TheCall->setArg(0, Arg.get());
280 TheCall->setType(ResultType);
281 return false;
282}
283
284/// Check that the argument to __builtin_function_start is a function.
285static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
286 if (S.checkArgCount(TheCall, 1))
287 return true;
288
289 if (TheCall->getArg(0)->containsErrors())
290 return true;
291
293 if (Arg.isInvalid())
294 return true;
295
296 TheCall->setArg(0, Arg.get());
297 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
299
300 if (!FD) {
301 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
302 << TheCall->getSourceRange();
303 return true;
304 }
305
306 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
307 TheCall->getBeginLoc());
308}
309
310/// Check the number of arguments and set the result type to
311/// the argument type.
312static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
313 if (S.checkArgCount(TheCall, 1))
314 return true;
315
316 TheCall->setType(TheCall->getArg(0)->getType());
317 return false;
318}
319
320/// Check that the value argument for __builtin_is_aligned(value, alignment) and
321/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
322/// type (but not a function pointer) and that the alignment is a power-of-two.
323static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
324 if (S.checkArgCount(TheCall, 2))
325 return true;
326
327 clang::Expr *Source = TheCall->getArg(0);
328 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
329
330 auto IsValidIntegerType = [](QualType Ty) {
331 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
332 };
333 QualType SrcTy = Source->getType();
334 // We should also be able to use it with arrays (but not functions!).
335 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
336 SrcTy = S.Context.getDecayedType(SrcTy);
337 }
338 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
339 SrcTy->isFunctionPointerType()) {
340 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
341 << SrcTy;
342 if (SrcTy->isFloatingType())
343 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_type);
344 else if (SrcTy->isMemberPointerType())
345 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_member_pointer);
346 else if (SrcTy->isFunctionPointerType())
347 S.Diag(Source->getExprLoc(),
348 diag::note_alignment_invalid_function_pointer);
349 return true;
350 }
351
352 clang::Expr *AlignOp = TheCall->getArg(1);
353 if (!IsValidIntegerType(AlignOp->getType())) {
354 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
355 << AlignOp->getType();
356 return true;
357 }
358 Expr::EvalResult AlignResult;
359 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
360 // We can't check validity of alignment if it is value dependent.
361 if (!AlignOp->isValueDependent() &&
362 AlignOp->EvaluateAsInt(AlignResult, S.Context,
364 llvm::APSInt AlignValue = AlignResult.Val.getInt();
365 llvm::APSInt MaxValue(
366 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
367 if (AlignValue < 1) {
368 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
369 return true;
370 }
371 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
372 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
373 << toString(MaxValue, 10);
374 return true;
375 }
376 if (!AlignValue.isPowerOf2()) {
377 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
378 return true;
379 }
380 if (AlignValue == 1) {
381 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
382 << IsBooleanAlignBuiltin;
383 }
384 }
385
388 SourceLocation(), Source);
389 if (SrcArg.isInvalid())
390 return true;
391 TheCall->setArg(0, SrcArg.get());
392 ExprResult AlignArg =
394 S.Context, AlignOp->getType(), false),
395 SourceLocation(), AlignOp);
396 if (AlignArg.isInvalid())
397 return true;
398 TheCall->setArg(1, AlignArg.get());
399 // For align_up/align_down, the return type is the same as the (potentially
400 // decayed) argument type including qualifiers. For is_aligned(), the result
401 // is always bool.
402 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
403 return false;
404}
405
406static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
407 if (S.checkArgCount(TheCall, 3))
408 return true;
409
410 std::pair<unsigned, const char *> Builtins[] = {
411 { Builtin::BI__builtin_add_overflow, "ckd_add" },
412 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
413 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
414 };
415
416 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
417 const char *> &P) {
418 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
420 S.getSourceManager(), S.getLangOpts()) == P.second;
421 });
422
423 auto ValidCkdIntType = [](QualType QT) {
424 // A valid checked integer type is an integer type other than a plain char,
425 // bool, a bit-precise type, or an enumeration type.
426 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
427 return (BT->getKind() >= BuiltinType::Short &&
428 BT->getKind() <= BuiltinType::Int128) || (
429 BT->getKind() >= BuiltinType::UShort &&
430 BT->getKind() <= BuiltinType::UInt128) ||
431 BT->getKind() == BuiltinType::UChar ||
432 BT->getKind() == BuiltinType::SChar;
433 return false;
434 };
435
436 // First two arguments should be integers.
437 for (unsigned I = 0; I < 2; ++I) {
439 if (Arg.isInvalid()) return true;
440 TheCall->setArg(I, Arg.get());
441
442 QualType Ty = Arg.get()->getType();
443 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
444 if (!IsValid) {
445 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
446 << CkdOperation << Ty << Arg.get()->getSourceRange();
447 return true;
448 }
449 }
450
451 // Third argument should be a pointer to a non-const integer.
452 // IRGen correctly handles volatile, restrict, and address spaces, and
453 // the other qualifiers aren't possible.
454 {
456 if (Arg.isInvalid()) return true;
457 TheCall->setArg(2, Arg.get());
458
459 QualType Ty = Arg.get()->getType();
460 const auto *PtrTy = Ty->getAs<PointerType>();
461 if (!PtrTy ||
462 !PtrTy->getPointeeType()->isIntegerType() ||
463 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
464 PtrTy->getPointeeType().isConstQualified()) {
465 S.Diag(Arg.get()->getBeginLoc(),
466 diag::err_overflow_builtin_must_be_ptr_int)
467 << CkdOperation << Ty << Arg.get()->getSourceRange();
468 return true;
469 }
470 }
471
472 // Disallow signed bit-precise integer args larger than 128 bits to mul
473 // function until we improve backend support.
474 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
475 for (unsigned I = 0; I < 3; ++I) {
476 const auto Arg = TheCall->getArg(I);
477 // Third argument will be a pointer.
478 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
479 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
480 S.getASTContext().getIntWidth(Ty) > 128)
481 return S.Diag(Arg->getBeginLoc(),
482 diag::err_overflow_builtin_bit_int_max_size)
483 << 128;
484 }
485 }
486
487 return false;
488}
489
490namespace {
491struct BuiltinDumpStructGenerator {
492 Sema &S;
493 CallExpr *TheCall;
494 SourceLocation Loc = TheCall->getBeginLoc();
495 SmallVector<Expr *, 32> Actions;
496 DiagnosticErrorTrap ErrorTracker;
497 PrintingPolicy Policy;
498
499 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
500 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
501 Policy(S.Context.getPrintingPolicy()) {
502 Policy.AnonymousTagNameStyle =
503 llvm::to_underlying(PrintingPolicy::AnonymousTagMode::Plain);
504 }
505
506 Expr *makeOpaqueValueExpr(Expr *Inner) {
507 auto *OVE = new (S.Context)
508 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
509 Inner->getObjectKind(), Inner);
510 Actions.push_back(OVE);
511 return OVE;
512 }
513
514 Expr *getStringLiteral(llvm::StringRef Str) {
516 // Wrap the literal in parentheses to attach a source location.
517 return new (S.Context) ParenExpr(Loc, Loc, Lit);
518 }
519
520 bool callPrintFunction(llvm::StringRef Format,
521 llvm::ArrayRef<Expr *> Exprs = {}) {
522 SmallVector<Expr *, 8> Args;
523 assert(TheCall->getNumArgs() >= 2);
524 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
525 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
526 Args.push_back(getStringLiteral(Format));
527 llvm::append_range(Args, Exprs);
528
529 // Register a note to explain why we're performing the call.
530 Sema::CodeSynthesisContext Ctx;
532 Ctx.PointOfInstantiation = Loc;
533 Ctx.CallArgs = Args.data();
534 Ctx.NumCallArgs = Args.size();
536
537 ExprResult RealCall =
538 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
539 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
540
542 if (!RealCall.isInvalid())
543 Actions.push_back(RealCall.get());
544 // Bail out if we've hit any errors, even if we managed to build the
545 // call. We don't want to produce more than one error.
546 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
547 }
548
549 Expr *getIndentString(unsigned Depth) {
550 if (!Depth)
551 return nullptr;
552
553 llvm::SmallString<32> Indent;
554 Indent.resize(Depth * Policy.Indentation, ' ');
555 return getStringLiteral(Indent);
556 }
557
558 Expr *getTypeString(QualType T) {
559 return getStringLiteral(T.getAsString(Policy));
560 }
561
562 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
563 llvm::raw_svector_ostream OS(Str);
564
565 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
566 // than trying to print a single character.
567 if (auto *BT = T->getAs<BuiltinType>()) {
568 switch (BT->getKind()) {
569 case BuiltinType::Bool:
570 OS << "%d";
571 return true;
572 case BuiltinType::Char_U:
573 case BuiltinType::UChar:
574 OS << "%hhu";
575 return true;
576 case BuiltinType::Char_S:
577 case BuiltinType::SChar:
578 OS << "%hhd";
579 return true;
580 default:
581 break;
582 }
583 }
584
585 analyze_printf::PrintfSpecifier Specifier;
586 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
587 // We were able to guess how to format this.
588 if (Specifier.getConversionSpecifier().getKind() ==
589 analyze_printf::PrintfConversionSpecifier::sArg) {
590 // Wrap double-quotes around a '%s' specifier and limit its maximum
591 // length. Ideally we'd also somehow escape special characters in the
592 // contents but printf doesn't support that.
593 // FIXME: '%s' formatting is not safe in general.
594 OS << '"';
595 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
596 Specifier.toString(OS);
597 OS << '"';
598 // FIXME: It would be nice to include a '...' if the string doesn't fit
599 // in the length limit.
600 } else {
601 Specifier.toString(OS);
602 }
603 return true;
604 }
605
606 if (T->isPointerType()) {
607 // Format all pointers with '%p'.
608 OS << "%p";
609 return true;
610 }
611
612 return false;
613 }
614
615 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
616 Expr *IndentLit = getIndentString(Depth);
617 Expr *TypeLit = getTypeString(S.Context.getCanonicalTagType(RD));
618 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
619 : callPrintFunction("%s", {TypeLit}))
620 return true;
621
622 return dumpRecordValue(RD, E, IndentLit, Depth);
623 }
624
625 // Dump a record value. E should be a pointer or lvalue referring to an RD.
626 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
627 unsigned Depth) {
628 // FIXME: Decide what to do if RD is a union. At least we should probably
629 // turn off printing `const char*` members with `%s`, because that is very
630 // likely to crash if that's not the active member. Whatever we decide, we
631 // should document it.
632
633 // Build an OpaqueValueExpr so we can refer to E more than once without
634 // triggering re-evaluation.
635 Expr *RecordArg = makeOpaqueValueExpr(E);
636 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
637
638 if (callPrintFunction(" {\n"))
639 return true;
640
641 // Dump each base class, regardless of whether they're aggregates.
642 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
643 for (const auto &Base : CXXRD->bases()) {
644 QualType BaseType =
645 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
646 : S.Context.getLValueReferenceType(Base.getType());
648 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
649 RecordArg);
650 if (BasePtr.isInvalid() ||
651 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
652 Depth + 1))
653 return true;
654 }
655 }
656
657 Expr *FieldIndentArg = getIndentString(Depth + 1);
658
659 // Dump each field.
660 for (auto *D : RD->decls()) {
661 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
662 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
663 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
664 continue;
665
666 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
667 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
668 getTypeString(FD->getType()),
669 getStringLiteral(FD->getName())};
670
671 if (FD->isBitField()) {
672 Format += ": %zu ";
673 QualType SizeT = S.Context.getSizeType();
674 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
675 FD->getBitWidthValue());
676 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
677 }
678
679 Format += "=";
680
683 CXXScopeSpec(), Loc, IFD,
684 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
686 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
688 DeclarationNameInfo(FD->getDeclName(), Loc));
689 if (Field.isInvalid())
690 return true;
691
692 auto *InnerRD = FD->getType()->getAsRecordDecl();
693 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
694 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
695 // Recursively print the values of members of aggregate record type.
696 if (callPrintFunction(Format, Args) ||
697 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
698 return true;
699 } else {
700 Format += " ";
701 if (appendFormatSpecifier(FD->getType(), Format)) {
702 // We know how to print this field.
703 Args.push_back(Field.get());
704 } else {
705 // We don't know how to print this field. Print out its address
706 // with a format specifier that a smart tool will be able to
707 // recognize and treat specially.
708 Format += "*%p";
709 ExprResult FieldAddr =
710 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
711 if (FieldAddr.isInvalid())
712 return true;
713 Args.push_back(FieldAddr.get());
714 }
715 Format += "\n";
716 if (callPrintFunction(Format, Args))
717 return true;
718 }
719 }
720
721 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
722 : callPrintFunction("}\n");
723 }
724
725 Expr *buildWrapper() {
726 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
728 TheCall->setType(Wrapper->getType());
729 TheCall->setValueKind(Wrapper->getValueKind());
730 return Wrapper;
731 }
732};
733} // namespace
734
736 if (S.checkArgCountAtLeast(TheCall, 2))
737 return ExprError();
738
739 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
740 if (PtrArgResult.isInvalid())
741 return ExprError();
742 TheCall->setArg(0, PtrArgResult.get());
743
744 // First argument should be a pointer to a struct.
745 QualType PtrArgType = PtrArgResult.get()->getType();
746 if (!PtrArgType->isPointerType() ||
747 !PtrArgType->getPointeeType()->isRecordType()) {
748 S.Diag(PtrArgResult.get()->getBeginLoc(),
749 diag::err_expected_struct_pointer_argument)
750 << 1 << TheCall->getDirectCallee() << PtrArgType;
751 return ExprError();
752 }
753 QualType Pointee = PtrArgType->getPointeeType();
754 const RecordDecl *RD = Pointee->getAsRecordDecl();
755 // Try to instantiate the class template as appropriate; otherwise, access to
756 // its data() may lead to a crash.
757 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
758 diag::err_incomplete_type))
759 return ExprError();
760 // Second argument is a callable, but we can't fully validate it until we try
761 // calling it.
762 QualType FnArgType = TheCall->getArg(1)->getType();
763 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
764 !FnArgType->isBlockPointerType() &&
765 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
766 auto *BT = FnArgType->getAs<BuiltinType>();
767 switch (BT ? BT->getKind() : BuiltinType::Void) {
768 case BuiltinType::Dependent:
769 case BuiltinType::Overload:
770 case BuiltinType::BoundMember:
771 case BuiltinType::PseudoObject:
772 case BuiltinType::UnknownAny:
773 case BuiltinType::BuiltinFn:
774 // This might be a callable.
775 break;
776
777 default:
778 S.Diag(TheCall->getArg(1)->getBeginLoc(),
779 diag::err_expected_callable_argument)
780 << 2 << TheCall->getDirectCallee() << FnArgType;
781 return ExprError();
782 }
783 }
784
785 BuiltinDumpStructGenerator Generator(S, TheCall);
786
787 // Wrap parentheses around the given pointer. This is not necessary for
788 // correct code generation, but it means that when we pretty-print the call
789 // arguments in our diagnostics we will produce '(&s)->n' instead of the
790 // incorrect '&s->n'.
791 Expr *PtrArg = PtrArgResult.get();
792 PtrArg = new (S.Context)
793 ParenExpr(PtrArg->getBeginLoc(),
794 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
795 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
796 return ExprError();
797
798 return Generator.buildWrapper();
799}
800
801static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
802 if (S.checkArgCount(BuiltinCall, 2))
803 return true;
804
805 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
806 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
807 Expr *Call = BuiltinCall->getArg(0);
808 Expr *Chain = BuiltinCall->getArg(1);
809
810 if (Call->getStmtClass() != Stmt::CallExprClass) {
811 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
812 << Call->getSourceRange();
813 return true;
814 }
815
816 auto CE = cast<CallExpr>(Call);
817 if (CE->getCallee()->getType()->isBlockPointerType()) {
818 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
819 << Call->getSourceRange();
820 return true;
821 }
822
823 const Decl *TargetDecl = CE->getCalleeDecl();
824 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
825 if (FD->getBuiltinID()) {
826 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
827 << Call->getSourceRange();
828 return true;
829 }
830
831 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
832 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
833 << Call->getSourceRange();
834 return true;
835 }
836
837 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
838 if (ChainResult.isInvalid())
839 return true;
840 if (!ChainResult.get()->getType()->isPointerType()) {
841 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
842 << Chain->getSourceRange();
843 return true;
844 }
845
846 QualType ReturnTy = CE->getCallReturnType(S.Context);
847 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
848 QualType BuiltinTy = S.Context.getFunctionType(
849 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
850 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
851
852 Builtin =
853 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
854
855 BuiltinCall->setType(CE->getType());
856 BuiltinCall->setValueKind(CE->getValueKind());
857 BuiltinCall->setObjectKind(CE->getObjectKind());
858 BuiltinCall->setCallee(Builtin);
859 BuiltinCall->setArg(1, ChainResult.get());
860
861 return false;
862}
863
864namespace {
865
866class ScanfDiagnosticFormatHandler
868 // Accepts the argument index (relative to the first destination index) of the
869 // argument whose size we want.
870 using ComputeSizeFunction =
871 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
872
873 // Accepts the argument index (relative to the first destination index), the
874 // destination size, and the source size).
875 using DiagnoseFunction =
876 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
877
878 ComputeSizeFunction ComputeSizeArgument;
879 DiagnoseFunction Diagnose;
880
881public:
882 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
883 DiagnoseFunction Diagnose)
884 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
885
886 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
887 const char *StartSpecifier,
888 unsigned specifierLen) override {
889 if (!FS.consumesDataArgument())
890 return true;
891
892 unsigned NulByte = 0;
893 switch ((FS.getConversionSpecifier().getKind())) {
894 default:
895 return true;
898 NulByte = 1;
899 break;
901 break;
902 }
903
904 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
905 if (FW.getHowSpecified() !=
906 analyze_format_string::OptionalAmount::HowSpecified::Constant)
907 return true;
908
909 unsigned SourceSize = FW.getConstantAmount() + NulByte;
910
911 std::optional<llvm::APSInt> DestSizeAPS =
912 ComputeSizeArgument(FS.getArgIndex());
913 if (!DestSizeAPS)
914 return true;
915
916 unsigned DestSize = DestSizeAPS->getZExtValue();
917
918 if (DestSize < SourceSize)
919 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
920
921 return true;
922 }
923};
924
925class EstimateSizeFormatHandler
927 size_t Size;
928 /// Whether the format string contains Linux kernel's format specifier
929 /// extension.
930 bool IsKernelCompatible = true;
931
932public:
933 EstimateSizeFormatHandler(StringRef Format)
934 : Size(std::min(Format.find(0), Format.size()) +
935 1 /* null byte always written by sprintf */) {}
936
937 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
938 const char *, unsigned SpecifierLen,
939 const TargetInfo &) override {
940
941 const size_t FieldWidth = computeFieldWidth(FS);
942 const size_t Precision = computePrecision(FS);
943
944 // The actual format.
945 switch (FS.getConversionSpecifier().getKind()) {
946 // Just a char.
949 Size += std::max(FieldWidth, (size_t)1);
950 break;
951 // Just an integer.
961 Size += std::max(FieldWidth, Precision);
962 break;
963
964 // %g style conversion switches between %f or %e style dynamically.
965 // %g removes trailing zeros, and does not print decimal point if there are
966 // no digits that follow it. Thus %g can print a single digit.
967 // FIXME: If it is alternative form:
968 // For g and G conversions, trailing zeros are not removed from the result.
971 Size += 1;
972 break;
973
974 // Floating point number in the form '[+]ddd.ddd'.
977 Size += std::max(FieldWidth, 1 /* integer part */ +
978 (Precision ? 1 + Precision
979 : 0) /* period + decimal */);
980 break;
981
982 // Floating point number in the form '[-]d.ddde[+-]dd'.
985 Size +=
986 std::max(FieldWidth,
987 1 /* integer part */ +
988 (Precision ? 1 + Precision : 0) /* period + decimal */ +
989 1 /* e or E letter */ + 2 /* exponent */);
990 break;
991
992 // Floating point number in the form '[-]0xh.hhhhp±dd'.
995 Size +=
996 std::max(FieldWidth,
997 2 /* 0x */ + 1 /* integer part */ +
998 (Precision ? 1 + Precision : 0) /* period + decimal */ +
999 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
1000 break;
1001
1002 // Just a string.
1005 Size += FieldWidth;
1006 break;
1007
1008 // Just a pointer in the form '0xddd'.
1010 // Linux kernel has its own extesion for `%p` specifier.
1011 // Kernel Document:
1012 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1013 IsKernelCompatible = false;
1014 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1015 break;
1016
1017 // A plain percent.
1019 Size += 1;
1020 break;
1021
1022 default:
1023 break;
1024 }
1025
1026 // If field width is specified, the sign/space is already accounted for
1027 // within the field width, so no additional size is needed.
1028 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1029 Size += 1;
1030
1031 if (FS.hasAlternativeForm()) {
1032 switch (FS.getConversionSpecifier().getKind()) {
1033 // For o conversion, it increases the precision, if and only if necessary,
1034 // to force the first digit of the result to be a zero
1035 // (if the value and precision are both 0, a single 0 is printed)
1037 // For b conversion, a nonzero result has 0b prefixed to it.
1039 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1040 // it.
1043 // Note: even when the prefix is added, if
1044 // (prefix_width <= FieldWidth - formatted_length) holds,
1045 // the prefix does not increase the format
1046 // size. e.g.(("%#3x", 0xf) is "0xf")
1047
1048 // If the result is zero, o, b, x, X adds nothing.
1049 break;
1050 // For a, A, e, E, f, F, g, and G conversions,
1051 // the result of converting a floating-point number always contains a
1052 // decimal-point
1061 Size += (Precision ? 0 : 1);
1062 break;
1063 // For other conversions, the behavior is undefined.
1064 default:
1065 break;
1066 }
1067 }
1068 assert(SpecifierLen <= Size && "no underflow");
1069 Size -= SpecifierLen;
1070 return true;
1071 }
1072
1073 size_t getSizeLowerBound() const { return Size; }
1074 bool isKernelCompatible() const { return IsKernelCompatible; }
1075
1076private:
1077 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1078 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1079 size_t FieldWidth = 0;
1081 FieldWidth = FW.getConstantAmount();
1082 return FieldWidth;
1083 }
1084
1085 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1086 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1087 size_t Precision = 0;
1088
1089 // See man 3 printf for default precision value based on the specifier.
1090 switch (FW.getHowSpecified()) {
1092 switch (FS.getConversionSpecifier().getKind()) {
1093 default:
1094 break;
1098 Precision = 1;
1099 break;
1106 Precision = 1;
1107 break;
1114 Precision = 6;
1115 break;
1117 Precision = 1;
1118 break;
1119 }
1120 break;
1122 Precision = FW.getConstantAmount();
1123 break;
1124 default:
1125 break;
1126 }
1127 return Precision;
1128 }
1129};
1130
1131} // namespace
1132
1133static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1134 StringRef &FormatStrRef, size_t &StrLen,
1135 ASTContext &Context) {
1136 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1137 Format && (Format->isOrdinary() || Format->isUTF8())) {
1138 FormatStrRef = Format->getString();
1139 const ConstantArrayType *T =
1140 Context.getAsConstantArrayType(Format->getType());
1141 assert(T && "String literal not of constant array type!");
1142 size_t TypeSize = T->getZExtSize();
1143 // In case there's a null byte somewhere.
1144 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1145 return true;
1146 }
1147 return false;
1148}
1149
1150void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1151 CallExpr *TheCall) {
1152 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1154 return;
1155
1156 bool UseDABAttr = false;
1157 const FunctionDecl *UseDecl = FD;
1158
1159 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1160 if (DABAttr) {
1161 UseDecl = DABAttr->getFunction();
1162 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1163 UseDABAttr = true;
1164 }
1165
1166 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1167
1168 if (!BuiltinID)
1169 return;
1170
1171 const TargetInfo &TI = getASTContext().getTargetInfo();
1172 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1173
1174 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1175 // If we refer to a diagnose_as_builtin attribute, we need to change the
1176 // argument index to refer to the arguments of the called function. Unless
1177 // the index is out of bounds, which presumably means it's a variadic
1178 // function.
1179 if (!UseDABAttr)
1180 return Index;
1181 unsigned DABIndices = DABAttr->argIndices_size();
1182 unsigned NewIndex = Index < DABIndices
1183 ? DABAttr->argIndices_begin()[Index]
1184 : Index - DABIndices + FD->getNumParams();
1185 if (NewIndex >= TheCall->getNumArgs())
1186 return std::nullopt;
1187 return NewIndex;
1188 };
1189
1190 auto ComputeExplicitObjectSizeArgument =
1191 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1192 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1193 if (!IndexOptional)
1194 return std::nullopt;
1195 unsigned NewIndex = *IndexOptional;
1196 Expr::EvalResult Result;
1197 Expr *SizeArg = TheCall->getArg(NewIndex);
1198 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1199 return std::nullopt;
1200 llvm::APSInt Integer = Result.Val.getInt();
1201 Integer.setIsUnsigned(true);
1202 return Integer;
1203 };
1204
1205 auto ComputeSizeArgument =
1206 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1207 // If the parameter has a pass_object_size attribute, then we should use its
1208 // (potentially) more strict checking mode. Otherwise, conservatively assume
1209 // type 0.
1210 int BOSType = 0;
1211 // This check can fail for variadic functions.
1212 if (Index < FD->getNumParams()) {
1213 if (const auto *POS =
1214 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1215 BOSType = POS->getType();
1216 }
1217
1218 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1219 if (!IndexOptional)
1220 return std::nullopt;
1221 unsigned NewIndex = *IndexOptional;
1222
1223 if (NewIndex >= TheCall->getNumArgs())
1224 return std::nullopt;
1225
1226 const Expr *ObjArg = TheCall->getArg(NewIndex);
1227 if (std::optional<uint64_t> ObjSize =
1228 ObjArg->tryEvaluateObjectSize(getASTContext(), BOSType)) {
1229 // Get the object size in the target's size_t width.
1230 return llvm::APSInt::getUnsigned(*ObjSize).extOrTrunc(SizeTypeWidth);
1231 }
1232 return std::nullopt;
1233 };
1234
1235 auto ComputeStrLenArgument =
1236 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1237 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1238 if (!IndexOptional)
1239 return std::nullopt;
1240 unsigned NewIndex = *IndexOptional;
1241
1242 const Expr *ObjArg = TheCall->getArg(NewIndex);
1243
1244 if (std::optional<uint64_t> Result =
1245 ObjArg->tryEvaluateStrLen(getASTContext())) {
1246 // Add 1 for null byte.
1247 return llvm::APSInt::getUnsigned(*Result + 1).extOrTrunc(SizeTypeWidth);
1248 }
1249 return std::nullopt;
1250 };
1251
1252 std::optional<llvm::APSInt> SourceSize;
1253 std::optional<llvm::APSInt> DestinationSize;
1254 unsigned DiagID = 0;
1255 bool IsChkVariant = false;
1256
1257 auto GetFunctionName = [&]() {
1258 std::string FunctionNameStr =
1259 getASTContext().BuiltinInfo.getName(BuiltinID);
1260 llvm::StringRef FunctionName = FunctionNameStr;
1261 // Skim off the details of whichever builtin was called to produce a better
1262 // diagnostic, as it's unlikely that the user wrote the __builtin
1263 // explicitly.
1264 if (IsChkVariant) {
1265 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1266 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1267 } else {
1268 FunctionName.consume_front("__builtin_");
1269 }
1270 return FunctionName.str();
1271 };
1272
1273 switch (BuiltinID) {
1274 default:
1275 return;
1276 case Builtin::BI__builtin_strcat:
1277 case Builtin::BIstrcat:
1278 case Builtin::BI__builtin_stpcpy:
1279 case Builtin::BIstpcpy:
1280 case Builtin::BI__builtin_strcpy:
1281 case Builtin::BIstrcpy: {
1282 DiagID = diag::warn_fortify_strlen_overflow;
1283 SourceSize = ComputeStrLenArgument(1);
1284 DestinationSize = ComputeSizeArgument(0);
1285 break;
1286 }
1287
1288 case Builtin::BI__builtin___strcat_chk:
1289 case Builtin::BI__builtin___stpcpy_chk:
1290 case Builtin::BI__builtin___strcpy_chk: {
1291 DiagID = diag::warn_fortify_strlen_overflow;
1292 SourceSize = ComputeStrLenArgument(1);
1293 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1294 IsChkVariant = true;
1295 break;
1296 }
1297
1298 case Builtin::BIscanf:
1299 case Builtin::BIfscanf:
1300 case Builtin::BIsscanf: {
1301 unsigned FormatIndex = 1;
1302 unsigned DataIndex = 2;
1303 if (BuiltinID == Builtin::BIscanf) {
1304 FormatIndex = 0;
1305 DataIndex = 1;
1306 }
1307
1308 const auto *FormatExpr =
1309 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1310
1311 StringRef FormatStrRef;
1312 size_t StrLen;
1313 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1314 return;
1315
1316 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1317 unsigned SourceSize) {
1318 DiagID = diag::warn_fortify_scanf_overflow;
1319 unsigned Index = ArgIndex + DataIndex;
1320 std::string FunctionName = GetFunctionName();
1321 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1322 PDiag(DiagID) << FunctionName << (Index + 1)
1323 << DestSize << SourceSize);
1324 };
1325
1326 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1327 return ComputeSizeArgument(Index + DataIndex);
1328 };
1329 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1330 const char *FormatBytes = FormatStrRef.data();
1332 FormatBytes + StrLen, getLangOpts(),
1333 Context.getTargetInfo());
1334
1335 // Unlike the other cases, in this one we have already issued the diagnostic
1336 // here, so no need to continue (because unlike the other cases, here the
1337 // diagnostic refers to the argument number).
1338 return;
1339 }
1340
1341 case Builtin::BIsprintf:
1342 case Builtin::BI__builtin___sprintf_chk: {
1343 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1344 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1345
1346 StringRef FormatStrRef;
1347 size_t StrLen;
1348 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1349 EstimateSizeFormatHandler H(FormatStrRef);
1350 const char *FormatBytes = FormatStrRef.data();
1352 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1353 Context.getTargetInfo(), false)) {
1354 DiagID = H.isKernelCompatible()
1355 ? diag::warn_format_overflow
1356 : diag::warn_format_overflow_non_kprintf;
1357 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1358 .extOrTrunc(SizeTypeWidth);
1359 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1360 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1361 IsChkVariant = true;
1362 } else {
1363 DestinationSize = ComputeSizeArgument(0);
1364 }
1365 break;
1366 }
1367 }
1368 return;
1369 }
1370 case Builtin::BI__builtin___memcpy_chk:
1371 case Builtin::BI__builtin___memmove_chk:
1372 case Builtin::BI__builtin___memset_chk:
1373 case Builtin::BI__builtin___strlcat_chk:
1374 case Builtin::BI__builtin___strlcpy_chk:
1375 case Builtin::BI__builtin___strncat_chk:
1376 case Builtin::BI__builtin___strncpy_chk:
1377 case Builtin::BI__builtin___stpncpy_chk:
1378 case Builtin::BI__builtin___memccpy_chk:
1379 case Builtin::BI__builtin___mempcpy_chk: {
1380 DiagID = diag::warn_builtin_chk_overflow;
1381 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1382 DestinationSize =
1383 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1384 IsChkVariant = true;
1385 break;
1386 }
1387
1388 case Builtin::BI__builtin___snprintf_chk:
1389 case Builtin::BI__builtin___vsnprintf_chk: {
1390 DiagID = diag::warn_builtin_chk_overflow;
1391 SourceSize = ComputeExplicitObjectSizeArgument(1);
1392 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1393 IsChkVariant = true;
1394 break;
1395 }
1396
1397 case Builtin::BIstrncat:
1398 case Builtin::BI__builtin_strncat:
1399 case Builtin::BIstrncpy:
1400 case Builtin::BI__builtin_strncpy:
1401 case Builtin::BIstpncpy:
1402 case Builtin::BI__builtin_stpncpy: {
1403 // Whether these functions overflow depends on the runtime strlen of the
1404 // string, not just the buffer size, so emitting the "always overflow"
1405 // diagnostic isn't quite right. We should still diagnose passing a buffer
1406 // size larger than the destination buffer though; this is a runtime abort
1407 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1408 DiagID = diag::warn_fortify_source_size_mismatch;
1409 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1410 DestinationSize = ComputeSizeArgument(0);
1411 break;
1412 }
1413
1414 case Builtin::BIbzero:
1415 case Builtin::BI__builtin_bzero:
1416 case Builtin::BImemcpy:
1417 case Builtin::BI__builtin_memcpy:
1418 case Builtin::BImemmove:
1419 case Builtin::BI__builtin_memmove:
1420 case Builtin::BImemset:
1421 case Builtin::BI__builtin_memset:
1422 case Builtin::BImempcpy:
1423 case Builtin::BI__builtin_mempcpy: {
1424 DiagID = diag::warn_fortify_source_overflow;
1425 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1426 DestinationSize = ComputeSizeArgument(0);
1427 break;
1428 }
1429 case Builtin::BIbcopy:
1430 case Builtin::BI__builtin_bcopy: {
1431 DiagID = diag::warn_fortify_source_overflow;
1432 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1433 DestinationSize = ComputeSizeArgument(1);
1434 break;
1435 }
1436 case Builtin::BIsnprintf:
1437 case Builtin::BI__builtin_snprintf:
1438 case Builtin::BIvsnprintf:
1439 case Builtin::BI__builtin_vsnprintf: {
1440 DiagID = diag::warn_fortify_source_size_mismatch;
1441 SourceSize = ComputeExplicitObjectSizeArgument(1);
1442 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1443 StringRef FormatStrRef;
1444 size_t StrLen;
1445 if (SourceSize &&
1446 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1447 EstimateSizeFormatHandler H(FormatStrRef);
1448 const char *FormatBytes = FormatStrRef.data();
1450 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1451 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1452 llvm::APSInt FormatSize =
1453 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1454 .extOrTrunc(SizeTypeWidth);
1455 if (FormatSize > *SourceSize && *SourceSize != 0) {
1456 unsigned TruncationDiagID =
1457 H.isKernelCompatible() ? diag::warn_format_truncation
1458 : diag::warn_format_truncation_non_kprintf;
1459 SmallString<16> SpecifiedSizeStr;
1460 SmallString<16> FormatSizeStr;
1461 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1462 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1463 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1464 PDiag(TruncationDiagID)
1465 << GetFunctionName() << SpecifiedSizeStr
1466 << FormatSizeStr);
1467 }
1468 }
1469 }
1470 DestinationSize = ComputeSizeArgument(0);
1471 const Expr *LenArg = TheCall->getArg(1)->IgnoreCasts();
1472 const Expr *Dest = TheCall->getArg(0)->IgnoreCasts();
1473 IdentifierInfo *FnInfo = FD->getIdentifier();
1474 CheckSizeofMemaccessArgument(LenArg, Dest, FnInfo);
1475 }
1476 }
1477
1478 if (!SourceSize || !DestinationSize ||
1479 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1480 return;
1481
1482 std::string FunctionName = GetFunctionName();
1483
1484 SmallString<16> DestinationStr;
1485 SmallString<16> SourceStr;
1486 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1487 SourceSize->toString(SourceStr, /*Radix=*/10);
1488 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1489 PDiag(DiagID)
1490 << FunctionName << DestinationStr << SourceStr);
1491}
1492
1493static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1494 Scope::ScopeFlags NeededScopeFlags,
1495 unsigned DiagID) {
1496 // Scopes aren't available during instantiation. Fortunately, builtin
1497 // functions cannot be template args so they cannot be formed through template
1498 // instantiation. Therefore checking once during the parse is sufficient.
1499 if (SemaRef.inTemplateInstantiation())
1500 return false;
1501
1502 Scope *S = SemaRef.getCurScope();
1503 while (S && !S->isSEHExceptScope())
1504 S = S->getParent();
1505 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1506 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1507 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1508 << DRE->getDecl()->getIdentifier();
1509 return true;
1510 }
1511
1512 return false;
1513}
1514
1515// In OpenCL, __builtin_alloca_* should return a pointer to address space
1516// that corresponds to the stack address space i.e private address space.
1517static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1518 QualType RT = TheCall->getType();
1519 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1520 "__builtin_alloca has invalid address space");
1521
1522 RT = RT->getPointeeType();
1524 TheCall->setType(S.Context.getPointerType(RT));
1525}
1526
1527static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1528 if (S.checkArgCountAtLeast(TheCall, 1))
1529 return true;
1530
1531 for (Expr *Arg : TheCall->arguments()) {
1532 // If argument is dependent on a template parameter, we can't resolve now.
1533 if (Arg->isTypeDependent() || Arg->isValueDependent())
1534 continue;
1535 // Reject void types.
1536 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1537 if (ArgTy->isVoidType())
1538 return S.Diag(Arg->getBeginLoc(), diag::err_param_with_void_type);
1539 }
1540
1541 TheCall->setType(S.Context.getSizeType());
1542 return false;
1543}
1544
1545namespace {
1546enum PointerAuthOpKind {
1547 PAO_Strip,
1548 PAO_Sign,
1549 PAO_Auth,
1550 PAO_SignGeneric,
1551 PAO_Discriminator,
1552 PAO_BlendPointer,
1553 PAO_BlendInteger
1554};
1555}
1556
1558 if (getLangOpts().PointerAuthIntrinsics)
1559 return false;
1560
1561 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1562 return true;
1563}
1564
1565static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1567}
1568
1569static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1570 // Convert it to type 'int'.
1571 if (convertArgumentToType(S, Arg, S.Context.IntTy))
1572 return true;
1573
1574 // Value-dependent expressions are okay; wait for template instantiation.
1575 if (Arg->isValueDependent())
1576 return false;
1577
1578 unsigned KeyValue;
1579 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1580}
1581
1583 // Attempt to constant-evaluate the expression.
1584 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1585 if (!KeyValue) {
1586 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1587 << 0 << Arg->getSourceRange();
1588 return true;
1589 }
1590
1591 // Ask the target to validate the key parameter.
1592 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1594 {
1595 llvm::raw_svector_ostream Str(Value);
1596 Str << *KeyValue;
1597 }
1598
1599 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1600 << Value << Arg->getSourceRange();
1601 return true;
1602 }
1603
1604 Result = KeyValue->getZExtValue();
1605 return false;
1606}
1607
1610 unsigned &IntVal) {
1611 if (!Arg) {
1612 IntVal = 0;
1613 return true;
1614 }
1615
1616 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
1617 if (!Result) {
1618 Diag(Arg->getExprLoc(), diag::err_ptrauth_arg_not_ice);
1619 return false;
1620 }
1621
1622 unsigned Max;
1623 bool IsAddrDiscArg = false;
1624
1625 switch (Kind) {
1627 Max = 1;
1628 IsAddrDiscArg = true;
1629 break;
1632 break;
1633 };
1634
1636 if (IsAddrDiscArg)
1637 Diag(Arg->getExprLoc(), diag::err_ptrauth_address_discrimination_invalid)
1638 << Result->getExtValue();
1639 else
1640 Diag(Arg->getExprLoc(), diag::err_ptrauth_extra_discriminator_invalid)
1641 << Result->getExtValue() << Max;
1642
1643 return false;
1644 };
1645
1646 IntVal = Result->getZExtValue();
1647 return true;
1648}
1649
1650static std::pair<const ValueDecl *, CharUnits>
1652 // Must evaluate as a pointer.
1654 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1655 return {nullptr, CharUnits()};
1656
1657 const auto *BaseDecl =
1658 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1659 if (!BaseDecl)
1660 return {nullptr, CharUnits()};
1661
1662 return {BaseDecl, Result.Val.getLValueOffset()};
1663}
1664
1665static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1666 bool RequireConstant = false) {
1667 if (Arg->hasPlaceholderType()) {
1669 if (R.isInvalid())
1670 return true;
1671 Arg = R.get();
1672 }
1673
1674 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1675 return OpKind != PAO_BlendInteger;
1676 };
1677 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1678 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1679 OpKind == PAO_SignGeneric;
1680 };
1681
1682 // Require the value to have the right range of type.
1683 QualType ExpectedTy;
1684 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1685 ExpectedTy = Arg->getType().getUnqualifiedType();
1686 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1687 ExpectedTy = S.Context.VoidPtrTy;
1688 } else if (AllowsInteger(OpKind) &&
1690 ExpectedTy = S.Context.getUIntPtrType();
1691
1692 } else {
1693 // Diagnose the failures.
1694 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1695 << unsigned(OpKind == PAO_Discriminator ? 1
1696 : OpKind == PAO_BlendPointer ? 2
1697 : OpKind == PAO_BlendInteger ? 3
1698 : 0)
1699 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1700 << Arg->getType() << Arg->getSourceRange();
1701 return true;
1702 }
1703
1704 // Convert to that type. This should just be an lvalue-to-rvalue
1705 // conversion.
1706 if (convertArgumentToType(S, Arg, ExpectedTy))
1707 return true;
1708
1709 if (!RequireConstant) {
1710 // Warn about null pointers for non-generic sign and auth operations.
1711 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1713 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1714 ? diag::warn_ptrauth_sign_null_pointer
1715 : diag::warn_ptrauth_auth_null_pointer)
1716 << Arg->getSourceRange();
1717 }
1718
1719 return false;
1720 }
1721
1722 // Perform special checking on the arguments to ptrauth_sign_constant.
1723
1724 // The main argument.
1725 if (OpKind == PAO_Sign) {
1726 // Require the value we're signing to have a special form.
1727 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1728 bool Invalid;
1729
1730 // Must be rooted in a declaration reference.
1731 if (!BaseDecl)
1732 Invalid = true;
1733
1734 // If it's a function declaration, we can't have an offset.
1735 else if (isa<FunctionDecl>(BaseDecl))
1736 Invalid = !Offset.isZero();
1737
1738 // Otherwise we're fine.
1739 else
1740 Invalid = false;
1741
1742 if (Invalid)
1743 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1744 return Invalid;
1745 }
1746
1747 // The discriminator argument.
1748 assert(OpKind == PAO_Discriminator);
1749
1750 // Must be a pointer or integer or blend thereof.
1751 Expr *Pointer = nullptr;
1752 Expr *Integer = nullptr;
1753 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1754 if (Call->getBuiltinCallee() ==
1755 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1756 Pointer = Call->getArg(0);
1757 Integer = Call->getArg(1);
1758 }
1759 }
1760 if (!Pointer && !Integer) {
1761 if (Arg->getType()->isPointerType())
1762 Pointer = Arg;
1763 else
1764 Integer = Arg;
1765 }
1766
1767 // Check the pointer.
1768 bool Invalid = false;
1769 if (Pointer) {
1770 assert(Pointer->getType()->isPointerType());
1771
1772 // TODO: if we're initializing a global, check that the address is
1773 // somehow related to what we're initializing. This probably will
1774 // never really be feasible and we'll have to catch it at link-time.
1775 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
1776 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
1777 Invalid = true;
1778 }
1779
1780 // Check the integer.
1781 if (Integer) {
1782 assert(Integer->getType()->isIntegerType());
1783 if (!Integer->isEvaluatable(S.Context))
1784 Invalid = true;
1785 }
1786
1787 if (Invalid)
1788 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
1789 return Invalid;
1790}
1791
1793 if (S.checkArgCount(Call, 2))
1794 return ExprError();
1796 return ExprError();
1797 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
1798 checkPointerAuthKey(S, Call->getArgs()[1]))
1799 return ExprError();
1800
1801 Call->setType(Call->getArgs()[0]->getType());
1802 return Call;
1803}
1804
1806 if (S.checkArgCount(Call, 2))
1807 return ExprError();
1809 return ExprError();
1810 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
1811 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
1812 return ExprError();
1813
1814 Call->setType(S.Context.getUIntPtrType());
1815 return Call;
1816}
1817
1819 if (S.checkArgCount(Call, 2))
1820 return ExprError();
1822 return ExprError();
1823 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
1824 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
1825 return ExprError();
1826
1827 Call->setType(S.Context.getUIntPtrType());
1828 return Call;
1829}
1830
1832 PointerAuthOpKind OpKind,
1833 bool RequireConstant) {
1834 if (S.checkArgCount(Call, 3))
1835 return ExprError();
1837 return ExprError();
1838 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
1839 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1840 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
1841 RequireConstant))
1842 return ExprError();
1843
1844 Call->setType(Call->getArgs()[0]->getType());
1845 return Call;
1846}
1847
1849 if (S.checkArgCount(Call, 5))
1850 return ExprError();
1852 return ExprError();
1853 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1854 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1855 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1856 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1857 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
1858 return ExprError();
1859
1860 Call->setType(Call->getArgs()[0]->getType());
1861 return Call;
1862}
1863
1865 if (S.checkArgCount(Call, 6))
1866 return ExprError();
1868 return ExprError();
1869 const Expr *AddendExpr = Call->getArg(5);
1870 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(S.Context);
1871 if (!AddendIsConstInt) {
1872 const Expr *Arg = Call->getArg(5)->IgnoreParenImpCasts();
1873 DeclRefExpr *DRE = cast<DeclRefExpr>(Call->getCallee()->IgnoreParenCasts());
1874 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1875 S.Diag(Arg->getBeginLoc(), diag::err_constant_integer_last_arg_type)
1876 << FDecl->getDeclName() << Arg->getSourceRange();
1877 }
1878 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1879 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1880 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1881 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1882 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator) ||
1883 !AddendIsConstInt)
1884 return ExprError();
1885
1886 Call->setType(Call->getArgs()[0]->getType());
1887 return Call;
1888}
1889
1892 return ExprError();
1893
1894 // We've already performed normal call type-checking.
1895 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
1896
1897 // Operand must be an ordinary or UTF-8 string literal.
1898 const auto *Literal = dyn_cast<StringLiteral>(Arg);
1899 if (!Literal || Literal->getCharByteWidth() != 1) {
1900 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
1901 << (Literal ? 1 : 0) << Arg->getSourceRange();
1902 return ExprError();
1903 }
1904
1905 return Call;
1906}
1907
1909 if (S.checkArgCount(Call, 1))
1910 return ExprError();
1911 Expr *FirstArg = Call->getArg(0);
1912 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(FirstArg);
1913 if (FirstValue.isInvalid())
1914 return ExprError();
1915 Call->setArg(0, FirstValue.get());
1916 QualType FirstArgType = FirstArg->getType();
1917 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
1918 FirstArgType = S.Context.getDecayedType(FirstArgType);
1919
1920 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
1921 if (!FirstArgRecord) {
1922 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1923 << /*isPolymorphic=*/0 << FirstArgType;
1924 return ExprError();
1925 }
1926 if (S.RequireCompleteType(
1927 FirstArg->getBeginLoc(), FirstArgType->getPointeeType(),
1928 diag::err_get_vtable_pointer_requires_complete_type)) {
1929 return ExprError();
1930 }
1931
1932 if (!FirstArgRecord->isPolymorphic()) {
1933 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1934 << /*isPolymorphic=*/1 << FirstArgRecord;
1935 return ExprError();
1936 }
1938 Call->setType(ReturnType);
1939 return Call;
1940}
1941
1943 if (S.checkArgCount(TheCall, 1))
1944 return ExprError();
1945
1946 // Compute __builtin_launder's parameter type from the argument.
1947 // The parameter type is:
1948 // * The type of the argument if it's not an array or function type,
1949 // Otherwise,
1950 // * The decayed argument type.
1951 QualType ParamTy = [&]() {
1952 QualType ArgTy = TheCall->getArg(0)->getType();
1953 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1954 return S.Context.getPointerType(Ty->getElementType());
1955 if (ArgTy->isFunctionType()) {
1956 return S.Context.getPointerType(ArgTy);
1957 }
1958 return ArgTy;
1959 }();
1960
1961 TheCall->setType(ParamTy);
1962
1963 auto DiagSelect = [&]() -> std::optional<unsigned> {
1964 if (!ParamTy->isPointerType())
1965 return 0;
1966 if (ParamTy->isFunctionPointerType())
1967 return 1;
1968 if (ParamTy->isVoidPointerType())
1969 return 2;
1970 return std::optional<unsigned>{};
1971 }();
1972 if (DiagSelect) {
1973 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1974 << *DiagSelect << TheCall->getSourceRange();
1975 return ExprError();
1976 }
1977
1978 // We either have an incomplete class type, or we have a class template
1979 // whose instantiation has not been forced. Example:
1980 //
1981 // template <class T> struct Foo { T value; };
1982 // Foo<int> *p = nullptr;
1983 // auto *d = __builtin_launder(p);
1984 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1985 diag::err_incomplete_type))
1986 return ExprError();
1987
1988 assert(ParamTy->getPointeeType()->isObjectType() &&
1989 "Unhandled non-object pointer case");
1990
1991 InitializedEntity Entity =
1993 ExprResult Arg =
1994 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1995 if (Arg.isInvalid())
1996 return ExprError();
1997 TheCall->setArg(0, Arg.get());
1998
1999 return TheCall;
2000}
2001
2003 if (S.checkArgCount(TheCall, 1))
2004 return ExprError();
2005
2007 if (Arg.isInvalid())
2008 return ExprError();
2009 QualType ParamTy = Arg.get()->getType();
2010 TheCall->setArg(0, Arg.get());
2011 TheCall->setType(S.Context.BoolTy);
2012
2013 // Only accept pointers to objects as arguments, which should have object
2014 // pointer or void pointer types.
2015 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2016 // LWG4138: Function pointer types not allowed
2017 if (PT->getPointeeType()->isFunctionType()) {
2018 S.Diag(TheCall->getArg(0)->getExprLoc(),
2019 diag::err_builtin_is_within_lifetime_invalid_arg)
2020 << 1;
2021 return ExprError();
2022 }
2023 // Disallow VLAs too since those shouldn't be able to
2024 // be a template parameter for `std::is_within_lifetime`
2025 if (PT->getPointeeType()->isVariableArrayType()) {
2026 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
2027 << 1 << "__builtin_is_within_lifetime";
2028 return ExprError();
2029 }
2030 } else {
2031 S.Diag(TheCall->getArg(0)->getExprLoc(),
2032 diag::err_builtin_is_within_lifetime_invalid_arg)
2033 << 0;
2034 return ExprError();
2035 }
2036 return TheCall;
2037}
2038
2040 if (S.checkArgCount(TheCall, 3))
2041 return ExprError();
2042
2043 QualType Dest = TheCall->getArg(0)->getType();
2044 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2045 S.Diag(TheCall->getArg(0)->getExprLoc(),
2046 diag::err_builtin_trivially_relocate_invalid_arg_type)
2047 << /*a pointer*/ 0;
2048 return ExprError();
2049 }
2050
2051 QualType T = Dest->getPointeeType();
2052 if (S.RequireCompleteType(TheCall->getBeginLoc(), T,
2053 diag::err_incomplete_type))
2054 return ExprError();
2055
2056 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2057 T->isIncompleteArrayType()) {
2058 S.Diag(TheCall->getArg(0)->getExprLoc(),
2059 diag::err_builtin_trivially_relocate_invalid_arg_type)
2060 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2061 return ExprError();
2062 }
2063
2064 TheCall->setType(Dest);
2065
2066 QualType Src = TheCall->getArg(1)->getType();
2067 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2068 S.Diag(TheCall->getArg(1)->getExprLoc(),
2069 diag::err_builtin_trivially_relocate_invalid_arg_type)
2070 << /*the same*/ 3;
2071 return ExprError();
2072 }
2073
2074 Expr *SizeExpr = TheCall->getArg(2);
2075 ExprResult Size = S.DefaultLvalueConversion(SizeExpr);
2076 if (Size.isInvalid())
2077 return ExprError();
2078
2079 Size = S.tryConvertExprToType(Size.get(), S.getASTContext().getSizeType());
2080 if (Size.isInvalid())
2081 return ExprError();
2082 SizeExpr = Size.get();
2083 TheCall->setArg(2, SizeExpr);
2084
2085 return TheCall;
2086}
2087
2088// Emit an error and return true if the current object format type is in the
2089// list of unsupported types.
2091 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2092 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2093 llvm::Triple::ObjectFormatType CurObjFormat =
2094 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2095 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2096 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2097 << TheCall->getSourceRange();
2098 return true;
2099 }
2100 return false;
2101}
2102
2103// Emit an error and return true if the current architecture is not in the list
2104// of supported architectures.
2105static bool
2107 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2108 llvm::Triple::ArchType CurArch =
2109 S.getASTContext().getTargetInfo().getTriple().getArch();
2110 if (llvm::is_contained(SupportedArchs, CurArch))
2111 return false;
2112 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2113 << TheCall->getSourceRange();
2114 return true;
2115}
2116
2117static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2118 SourceLocation CallSiteLoc);
2119
2120bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2121 CallExpr *TheCall) {
2122 switch (TI.getTriple().getArch()) {
2123 default:
2124 // Some builtins don't require additional checking, so just consider these
2125 // acceptable.
2126 return false;
2127 case llvm::Triple::arm:
2128 case llvm::Triple::armeb:
2129 case llvm::Triple::thumb:
2130 case llvm::Triple::thumbeb:
2131 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2132 case llvm::Triple::aarch64:
2133 case llvm::Triple::aarch64_32:
2134 case llvm::Triple::aarch64_be:
2135 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2136 case llvm::Triple::bpfeb:
2137 case llvm::Triple::bpfel:
2138 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2139 case llvm::Triple::dxil:
2140 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2141 case llvm::Triple::hexagon:
2142 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2143 case llvm::Triple::mips:
2144 case llvm::Triple::mipsel:
2145 case llvm::Triple::mips64:
2146 case llvm::Triple::mips64el:
2147 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2148 case llvm::Triple::spirv:
2149 case llvm::Triple::spirv32:
2150 case llvm::Triple::spirv64:
2151 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2152 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2153 return false;
2154 case llvm::Triple::systemz:
2155 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2156 case llvm::Triple::x86:
2157 case llvm::Triple::x86_64:
2158 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2159 case llvm::Triple::ppc:
2160 case llvm::Triple::ppcle:
2161 case llvm::Triple::ppc64:
2162 case llvm::Triple::ppc64le:
2163 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2164 case llvm::Triple::amdgcn:
2165 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2166 case llvm::Triple::riscv32:
2167 case llvm::Triple::riscv64:
2168 case llvm::Triple::riscv32be:
2169 case llvm::Triple::riscv64be:
2170 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2171 case llvm::Triple::loongarch32:
2172 case llvm::Triple::loongarch64:
2173 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2174 TheCall);
2175 case llvm::Triple::wasm32:
2176 case llvm::Triple::wasm64:
2177 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2178 case llvm::Triple::nvptx:
2179 case llvm::Triple::nvptx64:
2180 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2181 }
2182}
2183
2185 return T->isDependentType() ||
2186 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2187}
2188
2189// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2190// not a valid type, emit an error message and return true. Otherwise return
2191// false.
2192static bool
2195 int ArgOrdinal) {
2196 clang::QualType EltTy =
2197 ArgTy->isVectorType() ? ArgTy->getAs<VectorType>()->getElementType()
2198 : ArgTy->isMatrixType() ? ArgTy->getAs<MatrixType>()->getElementType()
2199 : ArgTy;
2200
2201 switch (ArgTyRestr) {
2203 if (!ArgTy->getAs<VectorType>() && !isValidMathElementType(ArgTy)) {
2204 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2205 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2206 << ArgTy;
2207 }
2208 break;
2210 if (!EltTy->isRealFloatingType()) {
2211 // FIXME: make diagnostic's wording correct for matrices
2212 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2213 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2214 << /* floating-point */ 1 << ArgTy;
2215 }
2216 break;
2218 if (!EltTy->isIntegerType()) {
2219 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2220 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2221 << /* no fp */ 0 << ArgTy;
2222 }
2223 break;
2225 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2226 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2227 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2228 << /* or fp */ 1 << ArgTy;
2229 }
2230 break;
2231 }
2232
2233 return false;
2234}
2235
2236/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2237/// This checks that the target supports the builtin and that the string
2238/// argument is constant and valid.
2239static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2240 const TargetInfo *AuxTI, unsigned BuiltinID) {
2241 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2242 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2243 "Expecting __builtin_cpu_...");
2244
2245 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2246 const TargetInfo *TheTI = &TI;
2247 auto SupportsBI = [=](const TargetInfo *TInfo) {
2248 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2249 (!IsCPUSupports && TInfo->supportsCpuIs()));
2250 };
2251 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2252 TheTI = AuxTI;
2253
2254 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2255 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2256 return S.Diag(TheCall->getBeginLoc(),
2257 TI.getTriple().isOSAIX()
2258 ? diag::err_builtin_aix_os_unsupported
2259 : diag::err_builtin_target_unsupported)
2260 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2261
2262 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2263 // Check if the argument is a string literal.
2264 if (!isa<StringLiteral>(Arg))
2265 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2266 << Arg->getSourceRange();
2267
2268 // Check the contents of the string.
2269 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2270 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2271 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2272 << Arg->getSourceRange();
2273 return false;
2274 }
2275 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2276 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2277 << Arg->getSourceRange();
2278 return false;
2279}
2280
2281/// Checks that __builtin_bswapg was called with a single argument, which is an
2282/// unsigned integer, and overrides the return value type to the integer type.
2283static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2284 if (S.checkArgCount(TheCall, 1))
2285 return true;
2286 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2287 if (ArgRes.isInvalid())
2288 return true;
2289
2290 Expr *Arg = ArgRes.get();
2291 TheCall->setArg(0, Arg);
2292 if (Arg->isTypeDependent())
2293 return false;
2294
2295 QualType ArgTy = Arg->getType();
2296
2297 if (!ArgTy->isIntegerType()) {
2298 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2299 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2300 << ArgTy;
2301 return true;
2302 }
2303 if (const auto *BT = dyn_cast<BitIntType>(ArgTy)) {
2304 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2305 BT->getNumBits() != 1) {
2306 S.Diag(Arg->getBeginLoc(), diag::err_bswapg_invalid_bit_width)
2307 << ArgTy << BT->getNumBits();
2308 return true;
2309 }
2310 }
2311 TheCall->setType(ArgTy);
2312 return false;
2313}
2314
2315/// Checks that __builtin_bitreverseg was called with a single argument, which
2316/// is an integer
2317static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2318 if (S.checkArgCount(TheCall, 1))
2319 return true;
2320 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2321 if (ArgRes.isInvalid())
2322 return true;
2323
2324 Expr *Arg = ArgRes.get();
2325 TheCall->setArg(0, Arg);
2326 if (Arg->isTypeDependent())
2327 return false;
2328
2329 QualType ArgTy = Arg->getType();
2330
2331 if (!ArgTy->isIntegerType()) {
2332 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2333 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2334 << ArgTy;
2335 return true;
2336 }
2337 TheCall->setType(ArgTy);
2338 return false;
2339}
2340
2341/// Checks that __builtin_popcountg was called with a single argument, which is
2342/// an unsigned integer.
2343static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2344 if (S.checkArgCount(TheCall, 1))
2345 return true;
2346
2347 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2348 if (ArgRes.isInvalid())
2349 return true;
2350
2351 Expr *Arg = ArgRes.get();
2352 TheCall->setArg(0, Arg);
2353
2354 QualType ArgTy = Arg->getType();
2355
2356 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2357 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2358 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2359 << ArgTy;
2360 return true;
2361 }
2362 return false;
2363}
2364
2365/// Checks the __builtin_stdc_* builtins that take a single unsigned integer
2366/// argument and return either int, bool, or the argument type.
2367static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall,
2368 QualType ReturnType) {
2369 if (S.checkArgCount(TheCall, 1))
2370 return true;
2371
2372 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2373 if (ArgRes.isInvalid())
2374 return true;
2375
2376 Expr *Arg = ArgRes.get();
2377 TheCall->setArg(0, Arg);
2378
2379 QualType ArgTy = Arg->getType();
2380 // C23 stdbit.h functions do not permit bool or enumeration types.
2381 if (ArgTy->isBooleanType() || ArgTy->isEnumeralType())
2382 return S.Diag(Arg->getBeginLoc(),
2383 diag::err_builtin_stdc_invalid_arg_type_bool_or_enum)
2384 << 1 /*1st argument*/ << ArgTy;
2385 if (!ArgTy->isUnsignedIntegerType())
2386 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_invalid_arg_type)
2387 << 1 /*1st argument*/ << ArgTy;
2388
2389 // For builtins returning unsigned int, verify the argument's bit width fits.
2390 // On targets where unsigned int is 16 bits, a large _BitInt argument could
2391 // produce a count that overflows the return type.
2392 if (!ReturnType.isNull() && ReturnType == S.Context.UnsignedIntTy) {
2393 uint64_t ArgWidth = S.Context.getIntWidth(ArgTy);
2394 uint64_t ReturnTypeWidth = S.Context.getIntWidth(S.Context.UnsignedIntTy);
2395 if (!llvm::isUIntN(ReturnTypeWidth, ArgWidth))
2396 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_result_overflow)
2397 << ArgTy;
2398 }
2399
2400 TheCall->setType(ReturnType.isNull() ? ArgTy : ReturnType);
2401 return false;
2402}
2403
2404/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2405/// an unsigned integer, and an optional second argument, which is promoted to
2406/// an 'int'.
2407static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2408 if (S.checkArgCountRange(TheCall, 1, 2))
2409 return true;
2410
2411 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2412 if (Arg0Res.isInvalid())
2413 return true;
2414
2415 Expr *Arg0 = Arg0Res.get();
2416 TheCall->setArg(0, Arg0);
2417
2418 QualType Arg0Ty = Arg0->getType();
2419
2420 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2421 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2422 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2423 << Arg0Ty;
2424 return true;
2425 }
2426
2427 if (TheCall->getNumArgs() > 1) {
2428 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2429 if (Arg1Res.isInvalid())
2430 return true;
2431
2432 Expr *Arg1 = Arg1Res.get();
2433 TheCall->setArg(1, Arg1);
2434
2435 QualType Arg1Ty = Arg1->getType();
2436
2437 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2438 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2439 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2440 return true;
2441 }
2442 }
2443
2444 return false;
2445}
2446
2448 unsigned ArgIndex;
2449 bool OnlyUnsigned;
2450
2452 QualType T) {
2453 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2454 << ArgIndex << /*scalar*/ 1
2455 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2456 << /*no fp*/ 0 << T;
2457 }
2458
2459public:
2460 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2461 : ContextualImplicitConverter(/*Suppress=*/false,
2462 /*SuppressConversion=*/true),
2463 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2464
2465 bool match(QualType T) override {
2466 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2467 }
2468
2470 QualType T) override {
2471 return emitError(S, Loc, T);
2472 }
2473
2475 QualType T) override {
2476 return emitError(S, Loc, T);
2477 }
2478
2480 QualType T,
2481 QualType ConvTy) override {
2482 return emitError(S, Loc, T);
2483 }
2484
2486 QualType ConvTy) override {
2487 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2488 }
2489
2491 QualType T) override {
2492 return emitError(S, Loc, T);
2493 }
2494
2496 QualType ConvTy) override {
2497 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2498 }
2499
2501 QualType T,
2502 QualType ConvTy) override {
2503 llvm_unreachable("conversion functions are permitted");
2504 }
2505};
2506
2507/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2508/// arguments, that the first argument is an unsigned integer type, and that
2509/// the second argument is an integer type.
2510static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2511 if (S.checkArgCount(TheCall, 2))
2512 return true;
2513
2514 // First argument (value to rotate) must be unsigned integer type.
2515 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2517 TheCall->getArg(0)->getBeginLoc(), TheCall->getArg(0), Arg0Converter);
2518 if (Arg0Res.isInvalid())
2519 return true;
2520
2521 Expr *Arg0 = Arg0Res.get();
2522 TheCall->setArg(0, Arg0);
2523
2524 QualType Arg0Ty = Arg0->getType();
2525 if (!Arg0Ty->isUnsignedIntegerType())
2526 return true;
2527
2528 // Second argument (rotation count) must be integer type.
2529 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2531 TheCall->getArg(1)->getBeginLoc(), TheCall->getArg(1), Arg1Converter);
2532 if (Arg1Res.isInvalid())
2533 return true;
2534
2535 Expr *Arg1 = Arg1Res.get();
2536 TheCall->setArg(1, Arg1);
2537
2538 QualType Arg1Ty = Arg1->getType();
2539 if (!Arg1Ty->isIntegerType())
2540 return true;
2541
2542 TheCall->setType(Arg0Ty);
2543 return false;
2544}
2545
2546static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2547 unsigned Pos, bool AllowConst,
2548 bool AllowAS) {
2549 QualType MaskTy = MaskArg->getType();
2550 if (!MaskTy->isExtVectorBoolType())
2551 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2552 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2553 << MaskTy;
2554
2555 QualType PtrTy = PtrArg->getType();
2556 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2557 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2558 << Pos << "scalar pointer";
2559
2560 QualType PointeeTy = PtrTy->getPointeeType();
2561 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2562 (!AllowConst && PointeeTy.isConstQualified()) ||
2563 (!AllowAS && PointeeTy.hasAddressSpace())) {
2566 return S.Diag(PtrArg->getExprLoc(),
2567 diag::err_typecheck_convert_incompatible)
2568 << PtrTy << Target << /*different qualifiers=*/5
2569 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2570 << PtrTy << Target;
2571 }
2572 return false;
2573}
2574
2575static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2576 bool TypeDependent = false;
2577 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2578 ExprResult Converted =
2580 if (Converted.isInvalid())
2581 return true;
2582 TheCall->setArg(Arg, Converted.get());
2583 TypeDependent |= Converted.get()->isTypeDependent();
2584 }
2585
2586 if (TypeDependent)
2587 TheCall->setType(S.Context.DependentTy);
2588 return false;
2589}
2590
2592 if (S.checkArgCountRange(TheCall, 2, 3))
2593 return ExprError();
2594
2595 if (ConvertMaskedBuiltinArgs(S, TheCall))
2596 return ExprError();
2597
2598 Expr *MaskArg = TheCall->getArg(0);
2599 Expr *PtrArg = TheCall->getArg(1);
2600 if (TheCall->isTypeDependent())
2601 return TheCall;
2602
2603 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2604 TheCall->getBuiltinCallee() ==
2605 Builtin::BI__builtin_masked_load))
2606 return ExprError();
2607
2608 QualType MaskTy = MaskArg->getType();
2609 QualType PtrTy = PtrArg->getType();
2610 QualType PointeeTy = PtrTy->getPointeeType();
2611 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2612
2614 MaskVecTy->getNumElements());
2615 if (TheCall->getNumArgs() == 3) {
2616 Expr *PassThruArg = TheCall->getArg(2);
2617 QualType PassThruTy = PassThruArg->getType();
2618 if (!S.Context.hasSameType(PassThruTy, RetTy))
2619 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2620 << /* third argument */ 3 << RetTy;
2621 }
2622
2623 TheCall->setType(RetTy);
2624 return TheCall;
2625}
2626
2628 if (S.checkArgCount(TheCall, 3))
2629 return ExprError();
2630
2631 if (ConvertMaskedBuiltinArgs(S, TheCall))
2632 return ExprError();
2633
2634 Expr *MaskArg = TheCall->getArg(0);
2635 Expr *ValArg = TheCall->getArg(1);
2636 Expr *PtrArg = TheCall->getArg(2);
2637 if (TheCall->isTypeDependent())
2638 return TheCall;
2639
2640 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2641 TheCall->getBuiltinCallee() ==
2642 Builtin::BI__builtin_masked_store))
2643 return ExprError();
2644
2645 QualType MaskTy = MaskArg->getType();
2646 QualType PtrTy = PtrArg->getType();
2647 QualType ValTy = ValArg->getType();
2648 if (!ValTy->isVectorType())
2649 return ExprError(
2650 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2651 << 2 << "vector");
2652
2653 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2654 const VectorType *ValVecTy = ValTy->getAs<VectorType>();
2655
2656 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements()) {
2657 return ExprError(
2658 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2660 TheCall->getBuiltinCallee())
2661 << MaskTy << ValTy);
2662 }
2663
2664 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
2665 PtrTy->getPointeeType().getUnqualifiedType()))
2666 return ExprError(S.Diag(TheCall->getBeginLoc(),
2667 diag::err_vec_builtin_incompatible_vector)
2668 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2669 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2670 TheCall->getArg(1)->getEndLoc()));
2671
2672 TheCall->setType(S.Context.VoidTy);
2673 return TheCall;
2674}
2675
2677 if (S.checkArgCountRange(TheCall, 3, 4))
2678 return ExprError();
2679
2680 if (ConvertMaskedBuiltinArgs(S, TheCall))
2681 return ExprError();
2682
2683 Expr *MaskArg = TheCall->getArg(0);
2684 Expr *IdxArg = TheCall->getArg(1);
2685 Expr *PtrArg = TheCall->getArg(2);
2686 if (TheCall->isTypeDependent())
2687 return TheCall;
2688
2689 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
2690 /*AllowAS=*/true))
2691 return ExprError();
2692
2693 QualType IdxTy = IdxArg->getType();
2694 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2695 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2696 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2697 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2698 << IdxTy;
2699
2700 QualType MaskTy = MaskArg->getType();
2701 QualType PtrTy = PtrArg->getType();
2702 QualType PointeeTy = PtrTy->getPointeeType();
2703 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2704 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2705 return ExprError(
2706 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2708 TheCall->getBuiltinCallee())
2709 << MaskTy << IdxTy);
2710
2712 MaskVecTy->getNumElements());
2713 if (TheCall->getNumArgs() == 4) {
2714 Expr *PassThruArg = TheCall->getArg(3);
2715 QualType PassThruTy = PassThruArg->getType();
2716 if (!S.Context.hasSameType(PassThruTy, RetTy))
2717 return S.Diag(PassThruArg->getExprLoc(),
2718 diag::err_vec_masked_load_store_ptr)
2719 << /* fourth argument */ 4 << RetTy;
2720 }
2721
2722 TheCall->setType(RetTy);
2723 return TheCall;
2724}
2725
2727 if (S.checkArgCount(TheCall, 4))
2728 return ExprError();
2729
2730 if (ConvertMaskedBuiltinArgs(S, TheCall))
2731 return ExprError();
2732
2733 Expr *MaskArg = TheCall->getArg(0);
2734 Expr *IdxArg = TheCall->getArg(1);
2735 Expr *ValArg = TheCall->getArg(2);
2736 Expr *PtrArg = TheCall->getArg(3);
2737 if (TheCall->isTypeDependent())
2738 return TheCall;
2739
2740 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
2741 /*AllowAS=*/true))
2742 return ExprError();
2743
2744 QualType IdxTy = IdxArg->getType();
2745 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2746 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2747 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2748 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2749 << IdxTy;
2750
2751 QualType ValTy = ValArg->getType();
2752 QualType MaskTy = MaskArg->getType();
2753 QualType PtrTy = PtrArg->getType();
2754
2755 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2756 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2757 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2758 return ExprError(
2759 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2761 TheCall->getBuiltinCallee())
2762 << MaskTy << IdxTy);
2763 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2764 return ExprError(
2765 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2767 TheCall->getBuiltinCallee())
2768 << MaskTy << ValTy);
2769
2770 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
2771 PtrTy->getPointeeType().getUnqualifiedType()))
2772 return ExprError(S.Diag(TheCall->getBeginLoc(),
2773 diag::err_vec_builtin_incompatible_vector)
2774 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2775 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2776 TheCall->getArg(1)->getEndLoc()));
2777
2778 TheCall->setType(S.Context.VoidTy);
2779 return TheCall;
2780}
2781
2783 SourceLocation Loc = TheCall->getBeginLoc();
2784 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2785 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2786
2787 if (Args.size() == 0) {
2788 S.Diag(TheCall->getBeginLoc(),
2789 diag::err_typecheck_call_too_few_args_at_least)
2790 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2791 << /*is_non_object=*/0 << TheCall->getSourceRange();
2792 return ExprError();
2793 }
2794
2795 QualType FuncT = Args[0]->getType();
2796
2797 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2798 if (Args.size() < 2) {
2799 S.Diag(TheCall->getBeginLoc(),
2800 diag::err_typecheck_call_too_few_args_at_least)
2801 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2802 << /*is_non_object=*/0 << TheCall->getSourceRange();
2803 return ExprError();
2804 }
2805
2806 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2807 QualType ObjectT = Args[1]->getType();
2808
2809 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
2810 return ExprError();
2811
2812 ExprResult ObjectArg = [&]() -> ExprResult {
2813 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2814 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2815 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2816 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2817 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2818 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2819 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
2820 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
2821 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
2822 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
2823 return Args[1];
2824 }
2825
2826 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2827 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2828 // reference_wrapper;
2829 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2830 if (RD->isInStdNamespace() &&
2831 RD->getDeclName().getAsString() == "reference_wrapper") {
2832 CXXScopeSpec SS;
2833 IdentifierInfo *GetName = &S.Context.Idents.get("get");
2834 UnqualifiedId GetID;
2835 GetID.setIdentifier(GetName, Loc);
2836
2838 S.getCurScope(), Args[1], Loc, tok::period, SS,
2839 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
2840
2841 if (MemExpr.isInvalid())
2842 return ExprError();
2843
2844 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
2845 }
2846 }
2847
2848 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
2849 // class T and t1 does not satisfy the previous two items;
2850
2851 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
2852 }();
2853
2854 if (ObjectArg.isInvalid())
2855 return ExprError();
2856
2857 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
2858 tok::periodstar, ObjectArg.get(), Args[0]);
2859 if (BinOp.isInvalid())
2860 return ExprError();
2861
2862 if (MPT->isMemberDataPointer())
2863 return BinOp;
2864
2865 auto *MemCall = new (S.Context)
2867
2868 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
2869 Args.drop_front(2), TheCall->getRParenLoc());
2870 }
2871 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
2872 Args.drop_front(), TheCall->getRParenLoc());
2873}
2874
2875// Performs a similar job to Sema::UsualUnaryConversions, but without any
2876// implicit promotion of integral/enumeration types.
2878 // First, convert to an r-value.
2880 if (Res.isInvalid())
2881 return ExprError();
2882
2883 // Promote floating-point types.
2884 return S.UsualUnaryFPConversions(Res.get());
2885}
2886
2888 if (const auto *TyA = VecTy->getAs<VectorType>())
2889 return TyA->getElementType();
2890 if (VecTy->isSizelessVectorType())
2891 return VecTy->getSizelessVectorEltType(Context);
2892 return QualType();
2893}
2894
2896Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2897 CallExpr *TheCall) {
2898 ExprResult TheCallResult(TheCall);
2899
2900 // Find out if any arguments are required to be integer constant expressions.
2901 unsigned ICEArguments = 0;
2903 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2905 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2906
2907 // If any arguments are required to be ICE's, check and diagnose.
2908 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2909 // Skip arguments not required to be ICE's.
2910 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2911
2912 llvm::APSInt Result;
2913 // If we don't have enough arguments, continue so we can issue better
2914 // diagnostic in checkArgCount(...)
2915 if (ArgNo < TheCall->getNumArgs() &&
2916 BuiltinConstantArg(TheCall, ArgNo, Result))
2917 return true;
2918 ICEArguments &= ~(1 << ArgNo);
2919 }
2920
2921 FPOptions FPO;
2922 switch (BuiltinID) {
2923 case Builtin::BI__builtin___get_unsafe_stack_start:
2924 case Builtin::BI__builtin___get_unsafe_stack_bottom:
2925 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
2926 << Context.BuiltinInfo.getQuotedName(BuiltinID)
2927 << "__safestack_get_unsafe_stack_bottom";
2928 break;
2929 case Builtin::BI__builtin___get_unsafe_stack_top:
2930 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
2931 << Context.BuiltinInfo.getQuotedName(BuiltinID)
2932 << "__safestack_get_unsafe_stack_top";
2933 break;
2934 case Builtin::BI__builtin___get_unsafe_stack_ptr:
2935 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
2936 << Context.BuiltinInfo.getQuotedName(BuiltinID)
2937 << "__safestack_get_unsafe_stack_ptr";
2938 break;
2939 case Builtin::BI__builtin_cpu_supports:
2940 case Builtin::BI__builtin_cpu_is:
2941 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2942 Context.getAuxTargetInfo(), BuiltinID))
2943 return ExprError();
2944 break;
2945 case Builtin::BI__builtin_cpu_init:
2946 if (!Context.getTargetInfo().supportsCpuInit()) {
2947 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2948 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2949 return ExprError();
2950 }
2951 break;
2952 case Builtin::BI__builtin___CFStringMakeConstantString:
2953 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2954 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2956 *this, BuiltinID, TheCall,
2957 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2958 return ExprError();
2959 assert(TheCall->getNumArgs() == 1 &&
2960 "Wrong # arguments to builtin CFStringMakeConstantString");
2961 if (ObjC().CheckObjCString(TheCall->getArg(0)))
2962 return ExprError();
2963 break;
2964 case Builtin::BI__builtin_ms_va_start:
2965 case Builtin::BI__builtin_stdarg_start:
2966 case Builtin::BI__builtin_va_start:
2967 case Builtin::BI__builtin_c23_va_start:
2968 if (BuiltinVAStart(BuiltinID, TheCall))
2969 return ExprError();
2970 break;
2971 case Builtin::BI__va_start: {
2972 switch (Context.getTargetInfo().getTriple().getArch()) {
2973 case llvm::Triple::aarch64:
2974 case llvm::Triple::arm:
2975 case llvm::Triple::thumb:
2976 if (BuiltinVAStartARMMicrosoft(TheCall))
2977 return ExprError();
2978 break;
2979 default:
2980 if (BuiltinVAStart(BuiltinID, TheCall))
2981 return ExprError();
2982 break;
2983 }
2984 break;
2985 }
2986
2987 // The acquire, release, and no fence variants are ARM and AArch64 only.
2988 case Builtin::BI_interlockedbittestandset_acq:
2989 case Builtin::BI_interlockedbittestandset_rel:
2990 case Builtin::BI_interlockedbittestandset_nf:
2991 case Builtin::BI_interlockedbittestandreset_acq:
2992 case Builtin::BI_interlockedbittestandreset_rel:
2993 case Builtin::BI_interlockedbittestandreset_nf:
2995 *this, TheCall,
2996 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2997 return ExprError();
2998 break;
2999
3000 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
3001 case Builtin::BI_bittest64:
3002 case Builtin::BI_bittestandcomplement64:
3003 case Builtin::BI_bittestandreset64:
3004 case Builtin::BI_bittestandset64:
3005 case Builtin::BI_interlockedbittestandreset64:
3006 case Builtin::BI_interlockedbittestandset64:
3008 *this, TheCall,
3009 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
3010 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
3011 return ExprError();
3012 break;
3013
3014 // The 64-bit acquire, release, and no fence variants are AArch64 only.
3015 case Builtin::BI_interlockedbittestandreset64_acq:
3016 case Builtin::BI_interlockedbittestandreset64_rel:
3017 case Builtin::BI_interlockedbittestandreset64_nf:
3018 case Builtin::BI_interlockedbittestandset64_acq:
3019 case Builtin::BI_interlockedbittestandset64_rel:
3020 case Builtin::BI_interlockedbittestandset64_nf:
3021 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
3022 return ExprError();
3023 break;
3024
3025 case Builtin::BI__builtin_set_flt_rounds:
3027 *this, TheCall,
3028 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
3029 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
3030 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
3031 llvm::Triple::ppc64le}))
3032 return ExprError();
3033 break;
3034
3035 case Builtin::BI__builtin_isgreater:
3036 case Builtin::BI__builtin_isgreaterequal:
3037 case Builtin::BI__builtin_isless:
3038 case Builtin::BI__builtin_islessequal:
3039 case Builtin::BI__builtin_islessgreater:
3040 case Builtin::BI__builtin_isunordered:
3041 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
3042 return ExprError();
3043 break;
3044 case Builtin::BI__builtin_fpclassify:
3045 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
3046 return ExprError();
3047 break;
3048 case Builtin::BI__builtin_isfpclass:
3049 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
3050 return ExprError();
3051 break;
3052 case Builtin::BI__builtin_isfinite:
3053 case Builtin::BI__builtin_isinf:
3054 case Builtin::BI__builtin_isinf_sign:
3055 case Builtin::BI__builtin_isnan:
3056 case Builtin::BI__builtin_issignaling:
3057 case Builtin::BI__builtin_isnormal:
3058 case Builtin::BI__builtin_issubnormal:
3059 case Builtin::BI__builtin_iszero:
3060 case Builtin::BI__builtin_signbit:
3061 case Builtin::BI__builtin_signbitf:
3062 case Builtin::BI__builtin_signbitl:
3063 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
3064 return ExprError();
3065 break;
3066 case Builtin::BI__builtin_shufflevector:
3067 return BuiltinShuffleVector(TheCall);
3068 // TheCall will be freed by the smart pointer here, but that's fine, since
3069 // BuiltinShuffleVector guts it, but then doesn't release it.
3070 case Builtin::BI__builtin_masked_load:
3071 case Builtin::BI__builtin_masked_expand_load:
3072 return BuiltinMaskedLoad(*this, TheCall);
3073 case Builtin::BI__builtin_masked_store:
3074 case Builtin::BI__builtin_masked_compress_store:
3075 return BuiltinMaskedStore(*this, TheCall);
3076 case Builtin::BI__builtin_masked_gather:
3077 return BuiltinMaskedGather(*this, TheCall);
3078 case Builtin::BI__builtin_masked_scatter:
3079 return BuiltinMaskedScatter(*this, TheCall);
3080 case Builtin::BI__builtin_invoke:
3081 return BuiltinInvoke(*this, TheCall);
3082 case Builtin::BI__builtin_prefetch:
3083 if (BuiltinPrefetch(TheCall))
3084 return ExprError();
3085 break;
3086 case Builtin::BI__builtin_alloca_with_align:
3087 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3088 if (BuiltinAllocaWithAlign(TheCall))
3089 return ExprError();
3090 [[fallthrough]];
3091 case Builtin::BI__builtin_alloca:
3092 case Builtin::BI__builtin_alloca_uninitialized:
3093 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
3094 << TheCall->getDirectCallee();
3095 if (getLangOpts().OpenCL) {
3096 builtinAllocaAddrSpace(*this, TheCall);
3097 }
3098 break;
3099 case Builtin::BI__builtin_infer_alloc_token:
3100 if (checkBuiltinInferAllocToken(*this, TheCall))
3101 return ExprError();
3102 break;
3103 case Builtin::BI__arithmetic_fence:
3104 if (BuiltinArithmeticFence(TheCall))
3105 return ExprError();
3106 break;
3107 case Builtin::BI__assume:
3108 case Builtin::BI__builtin_assume:
3109 if (BuiltinAssume(TheCall))
3110 return ExprError();
3111 break;
3112 case Builtin::BI__builtin_assume_aligned:
3113 if (BuiltinAssumeAligned(TheCall))
3114 return ExprError();
3115 break;
3116 case Builtin::BI__builtin_dynamic_object_size:
3117 case Builtin::BI__builtin_object_size:
3118 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
3119 return ExprError();
3120 break;
3121 case Builtin::BI__builtin_longjmp:
3122 if (BuiltinLongjmp(TheCall))
3123 return ExprError();
3124 break;
3125 case Builtin::BI__builtin_setjmp:
3126 if (BuiltinSetjmp(TheCall))
3127 return ExprError();
3128 break;
3129 case Builtin::BI__builtin_complex:
3130 if (BuiltinComplex(TheCall))
3131 return ExprError();
3132 break;
3133 case Builtin::BI__builtin_classify_type:
3134 case Builtin::BI__builtin_constant_p: {
3135 if (checkArgCount(TheCall, 1))
3136 return true;
3138 if (Arg.isInvalid()) return true;
3139 TheCall->setArg(0, Arg.get());
3140 TheCall->setType(Context.IntTy);
3141 break;
3142 }
3143 case Builtin::BI__builtin_launder:
3144 return BuiltinLaunder(*this, TheCall);
3145 case Builtin::BI__builtin_is_within_lifetime:
3146 return BuiltinIsWithinLifetime(*this, TheCall);
3147 case Builtin::BI__builtin_trivially_relocate:
3148 return BuiltinTriviallyRelocate(*this, TheCall);
3149 case Builtin::BI__builtin_clear_padding: {
3150 if (checkArgCount(TheCall, 1))
3151 return ExprError();
3152
3153 const Expr *PtrArg = TheCall->getArg(0);
3154 const QualType PtrArgType = PtrArg->getType();
3155 if (!PtrArgType->isPointerType()) {
3156 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
3157 << PtrArgType << "pointer" << 1 << 0 << 3 << 1 << PtrArgType
3158 << "pointer";
3159 return ExprError();
3160 }
3161 QualType PointeeType = PtrArgType->getPointeeType();
3162 if (PointeeType.isConstQualified()) {
3163 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_assign_const)
3164 << TheCall->getSourceRange() << 4 /*ConstUnknown*/;
3165 return ExprError();
3166 }
3167 if (RequireCompleteType(PtrArg->getBeginLoc(), PointeeType,
3168 diag::err_typecheck_decl_incomplete_type))
3169 return ExprError();
3170
3171 // For non trivially copyable types, we try to match gcc's behaviour.
3172 // i.e. __builtin_clear_padding(&var) is OK as long as var is a complete
3173 // object, either a local variable or a function parameter passed by value
3174 auto IsAddrOfDeclExpr = [&]() {
3175 const Expr *Inner = PtrArg->IgnoreParenNoopCasts(Context);
3176 const auto *UnaryOp = dyn_cast<UnaryOperator>(Inner);
3177 if (!UnaryOp || UnaryOp->getOpcode() != UO_AddrOf)
3178 return false;
3179
3180 const Expr *Operand =
3181 UnaryOp->getSubExpr()->IgnoreParenNoopCasts(Context);
3182 const auto *DeclRef = dyn_cast<DeclRefExpr>(Operand);
3183 if (!DeclRef)
3184 return false;
3185
3186 const auto *VarDecl = dyn_cast<::clang::VarDecl>(DeclRef->getDecl());
3187 if (!VarDecl || VarDecl->getType()->isReferenceType())
3188 return false;
3189
3190 // matching GCC behaviour
3191 // __builtin_clear_padding((X*)&var) is fine as long X is the type of var
3192 QualType VarQType = VarDecl->getType();
3193 return PointeeType.getTypePtr() == VarQType.getTypePtr() ||
3194 Context.hasSameUnqualifiedType(PointeeType, VarQType);
3195 };
3196
3197 if (!PointeeType.isTriviallyCopyableType(Context) &&
3198 !PointeeType->isAtomicType() // _Atomic is not copyable
3199 && !IsAddrOfDeclExpr()) {
3200 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_needs_trivial_copy)
3201 << PtrArg->getType() << PtrArg->getSourceRange();
3202 return ExprError();
3203 }
3204
3205 if (auto *Record = PointeeType->getAsRecordDecl();
3207 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_no_flexible_array)
3208 << PointeeType << PtrArg->getSourceRange();
3209 return ExprError();
3210 }
3211
3212 break;
3213 }
3214 case Builtin::BI__sync_fetch_and_add:
3215 case Builtin::BI__sync_fetch_and_add_1:
3216 case Builtin::BI__sync_fetch_and_add_2:
3217 case Builtin::BI__sync_fetch_and_add_4:
3218 case Builtin::BI__sync_fetch_and_add_8:
3219 case Builtin::BI__sync_fetch_and_add_16:
3220 case Builtin::BI__sync_fetch_and_sub:
3221 case Builtin::BI__sync_fetch_and_sub_1:
3222 case Builtin::BI__sync_fetch_and_sub_2:
3223 case Builtin::BI__sync_fetch_and_sub_4:
3224 case Builtin::BI__sync_fetch_and_sub_8:
3225 case Builtin::BI__sync_fetch_and_sub_16:
3226 case Builtin::BI__sync_fetch_and_or:
3227 case Builtin::BI__sync_fetch_and_or_1:
3228 case Builtin::BI__sync_fetch_and_or_2:
3229 case Builtin::BI__sync_fetch_and_or_4:
3230 case Builtin::BI__sync_fetch_and_or_8:
3231 case Builtin::BI__sync_fetch_and_or_16:
3232 case Builtin::BI__sync_fetch_and_and:
3233 case Builtin::BI__sync_fetch_and_and_1:
3234 case Builtin::BI__sync_fetch_and_and_2:
3235 case Builtin::BI__sync_fetch_and_and_4:
3236 case Builtin::BI__sync_fetch_and_and_8:
3237 case Builtin::BI__sync_fetch_and_and_16:
3238 case Builtin::BI__sync_fetch_and_xor:
3239 case Builtin::BI__sync_fetch_and_xor_1:
3240 case Builtin::BI__sync_fetch_and_xor_2:
3241 case Builtin::BI__sync_fetch_and_xor_4:
3242 case Builtin::BI__sync_fetch_and_xor_8:
3243 case Builtin::BI__sync_fetch_and_xor_16:
3244 case Builtin::BI__sync_fetch_and_nand:
3245 case Builtin::BI__sync_fetch_and_nand_1:
3246 case Builtin::BI__sync_fetch_and_nand_2:
3247 case Builtin::BI__sync_fetch_and_nand_4:
3248 case Builtin::BI__sync_fetch_and_nand_8:
3249 case Builtin::BI__sync_fetch_and_nand_16:
3250 case Builtin::BI__sync_add_and_fetch:
3251 case Builtin::BI__sync_add_and_fetch_1:
3252 case Builtin::BI__sync_add_and_fetch_2:
3253 case Builtin::BI__sync_add_and_fetch_4:
3254 case Builtin::BI__sync_add_and_fetch_8:
3255 case Builtin::BI__sync_add_and_fetch_16:
3256 case Builtin::BI__sync_sub_and_fetch:
3257 case Builtin::BI__sync_sub_and_fetch_1:
3258 case Builtin::BI__sync_sub_and_fetch_2:
3259 case Builtin::BI__sync_sub_and_fetch_4:
3260 case Builtin::BI__sync_sub_and_fetch_8:
3261 case Builtin::BI__sync_sub_and_fetch_16:
3262 case Builtin::BI__sync_and_and_fetch:
3263 case Builtin::BI__sync_and_and_fetch_1:
3264 case Builtin::BI__sync_and_and_fetch_2:
3265 case Builtin::BI__sync_and_and_fetch_4:
3266 case Builtin::BI__sync_and_and_fetch_8:
3267 case Builtin::BI__sync_and_and_fetch_16:
3268 case Builtin::BI__sync_or_and_fetch:
3269 case Builtin::BI__sync_or_and_fetch_1:
3270 case Builtin::BI__sync_or_and_fetch_2:
3271 case Builtin::BI__sync_or_and_fetch_4:
3272 case Builtin::BI__sync_or_and_fetch_8:
3273 case Builtin::BI__sync_or_and_fetch_16:
3274 case Builtin::BI__sync_xor_and_fetch:
3275 case Builtin::BI__sync_xor_and_fetch_1:
3276 case Builtin::BI__sync_xor_and_fetch_2:
3277 case Builtin::BI__sync_xor_and_fetch_4:
3278 case Builtin::BI__sync_xor_and_fetch_8:
3279 case Builtin::BI__sync_xor_and_fetch_16:
3280 case Builtin::BI__sync_nand_and_fetch:
3281 case Builtin::BI__sync_nand_and_fetch_1:
3282 case Builtin::BI__sync_nand_and_fetch_2:
3283 case Builtin::BI__sync_nand_and_fetch_4:
3284 case Builtin::BI__sync_nand_and_fetch_8:
3285 case Builtin::BI__sync_nand_and_fetch_16:
3286 case Builtin::BI__sync_val_compare_and_swap:
3287 case Builtin::BI__sync_val_compare_and_swap_1:
3288 case Builtin::BI__sync_val_compare_and_swap_2:
3289 case Builtin::BI__sync_val_compare_and_swap_4:
3290 case Builtin::BI__sync_val_compare_and_swap_8:
3291 case Builtin::BI__sync_val_compare_and_swap_16:
3292 case Builtin::BI__sync_bool_compare_and_swap:
3293 case Builtin::BI__sync_bool_compare_and_swap_1:
3294 case Builtin::BI__sync_bool_compare_and_swap_2:
3295 case Builtin::BI__sync_bool_compare_and_swap_4:
3296 case Builtin::BI__sync_bool_compare_and_swap_8:
3297 case Builtin::BI__sync_bool_compare_and_swap_16:
3298 case Builtin::BI__sync_lock_test_and_set:
3299 case Builtin::BI__sync_lock_test_and_set_1:
3300 case Builtin::BI__sync_lock_test_and_set_2:
3301 case Builtin::BI__sync_lock_test_and_set_4:
3302 case Builtin::BI__sync_lock_test_and_set_8:
3303 case Builtin::BI__sync_lock_test_and_set_16:
3304 case Builtin::BI__sync_lock_release:
3305 case Builtin::BI__sync_lock_release_1:
3306 case Builtin::BI__sync_lock_release_2:
3307 case Builtin::BI__sync_lock_release_4:
3308 case Builtin::BI__sync_lock_release_8:
3309 case Builtin::BI__sync_lock_release_16:
3310 case Builtin::BI__sync_swap:
3311 case Builtin::BI__sync_swap_1:
3312 case Builtin::BI__sync_swap_2:
3313 case Builtin::BI__sync_swap_4:
3314 case Builtin::BI__sync_swap_8:
3315 case Builtin::BI__sync_swap_16:
3316 return BuiltinAtomicOverloaded(TheCallResult);
3317 case Builtin::BI__sync_synchronize:
3318 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
3319 << TheCall->getCallee()->getSourceRange();
3320 break;
3321 case Builtin::BI__builtin_nontemporal_load:
3322 case Builtin::BI__builtin_nontemporal_store:
3323 return BuiltinNontemporalOverloaded(TheCallResult);
3324 case Builtin::BI__builtin_memcpy_inline: {
3325 clang::Expr *SizeOp = TheCall->getArg(2);
3326 // We warn about copying to or from `nullptr` pointers when `size` is
3327 // greater than 0. When `size` is value dependent we cannot evaluate its
3328 // value so we bail out.
3329 if (SizeOp->isValueDependent())
3330 break;
3331 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
3332 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3333 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
3334 }
3335 break;
3336 }
3337 case Builtin::BI__builtin_memset_inline: {
3338 clang::Expr *SizeOp = TheCall->getArg(2);
3339 // We warn about filling to `nullptr` pointers when `size` is greater than
3340 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3341 // out.
3342 if (SizeOp->isValueDependent())
3343 break;
3344 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
3345 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3346 break;
3347 }
3348#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3349 case Builtin::BI##ID: \
3350 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3351#include "clang/Basic/Builtins.inc"
3352 case Builtin::BI__annotation: {
3353 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3354 if (!TT.isOSWindows() && !TT.isUEFI()) {
3355 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
3356 << TheCall->getSourceRange();
3357 return ExprError();
3358 }
3359 if (BuiltinMSVCAnnotation(*this, TheCall))
3360 return ExprError();
3361 break;
3362 }
3363 case Builtin::BI__builtin_annotation:
3364 if (BuiltinAnnotation(*this, TheCall))
3365 return ExprError();
3366 break;
3367 case Builtin::BI__builtin_addressof:
3368 if (BuiltinAddressof(*this, TheCall))
3369 return ExprError();
3370 break;
3371 case Builtin::BI__builtin_function_start:
3372 if (BuiltinFunctionStart(*this, TheCall))
3373 return ExprError();
3374 break;
3375 case Builtin::BI__builtin_is_aligned:
3376 case Builtin::BI__builtin_align_up:
3377 case Builtin::BI__builtin_align_down:
3378 if (BuiltinAlignment(*this, TheCall, BuiltinID))
3379 return ExprError();
3380 break;
3381 case Builtin::BI__builtin_add_overflow:
3382 case Builtin::BI__builtin_sub_overflow:
3383 case Builtin::BI__builtin_mul_overflow:
3384 if (BuiltinOverflow(*this, TheCall, BuiltinID))
3385 return ExprError();
3386 break;
3387 case Builtin::BI__builtin_operator_new:
3388 case Builtin::BI__builtin_operator_delete: {
3389 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3390 ExprResult Res =
3391 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3392 return Res;
3393 }
3394 case Builtin::BI__builtin_dump_struct:
3395 return BuiltinDumpStruct(*this, TheCall);
3396 case Builtin::BI__builtin_expect_with_probability: {
3397 // We first want to ensure we are called with 3 arguments
3398 if (checkArgCount(TheCall, 3))
3399 return ExprError();
3400 // then check probability is constant float in range [0.0, 1.0]
3401 const Expr *ProbArg = TheCall->getArg(2);
3402 SmallVector<PartialDiagnosticAt, 8> Notes;
3403 Expr::EvalResult Eval;
3404 Eval.Diag = &Notes;
3405 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3406 !Eval.Val.isFloat()) {
3407 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3408 << ProbArg->getSourceRange();
3409 for (const PartialDiagnosticAt &PDiag : Notes)
3410 Diag(PDiag.first, PDiag.second);
3411 return ExprError();
3412 }
3413 llvm::APFloat Probability = Eval.Val.getFloat();
3414 bool LoseInfo = false;
3415 Probability.convert(llvm::APFloat::IEEEdouble(),
3416 llvm::RoundingMode::Dynamic, &LoseInfo);
3417 if (!(Probability >= llvm::APFloat(0.0) &&
3418 Probability <= llvm::APFloat(1.0))) {
3419 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3420 << ProbArg->getSourceRange();
3421 return ExprError();
3422 }
3423 break;
3424 }
3425 case Builtin::BI__builtin_preserve_access_index:
3426 if (BuiltinPreserveAI(*this, TheCall))
3427 return ExprError();
3428 break;
3429 case Builtin::BI__builtin_call_with_static_chain:
3430 if (BuiltinCallWithStaticChain(*this, TheCall))
3431 return ExprError();
3432 break;
3433 case Builtin::BI__exception_code:
3434 case Builtin::BI_exception_code:
3435 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3436 diag::err_seh___except_block))
3437 return ExprError();
3438 break;
3439 case Builtin::BI__exception_info:
3440 case Builtin::BI_exception_info:
3441 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3442 diag::err_seh___except_filter))
3443 return ExprError();
3444 break;
3445 case Builtin::BI__GetExceptionInfo:
3446 if (checkArgCount(TheCall, 1))
3447 return ExprError();
3448
3450 TheCall->getBeginLoc(),
3451 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3452 TheCall))
3453 return ExprError();
3454
3455 TheCall->setType(Context.VoidPtrTy);
3456 break;
3457 case Builtin::BIaddressof:
3458 case Builtin::BI__addressof:
3459 case Builtin::BIforward:
3460 case Builtin::BIforward_like:
3461 case Builtin::BImove:
3462 case Builtin::BImove_if_noexcept:
3463 case Builtin::BIas_const: {
3464 // These are all expected to be of the form
3465 // T &/&&/* f(U &/&&)
3466 // where T and U only differ in qualification.
3467 if (checkArgCount(TheCall, 1))
3468 return ExprError();
3469 QualType Param = FDecl->getParamDecl(0)->getType();
3470 QualType Result = FDecl->getReturnType();
3471 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3472 BuiltinID == Builtin::BI__addressof;
3473 if (!(Param->isReferenceType() &&
3474 (ReturnsPointer ? Result->isAnyPointerType()
3475 : Result->isReferenceType()) &&
3476 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3477 Result->getPointeeType()))) {
3478 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3479 << FDecl;
3480 return ExprError();
3481 }
3482 break;
3483 }
3484 case Builtin::BI__builtin_ptrauth_strip:
3485 return PointerAuthStrip(*this, TheCall);
3486 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3487 return PointerAuthBlendDiscriminator(*this, TheCall);
3488 case Builtin::BI__builtin_ptrauth_sign_constant:
3489 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3490 /*RequireConstant=*/true);
3491 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3492 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3493 /*RequireConstant=*/false);
3494 case Builtin::BI__builtin_ptrauth_auth:
3495 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3496 /*RequireConstant=*/false);
3497 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3498 return PointerAuthSignGenericData(*this, TheCall);
3499 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3500 return PointerAuthAuthAndResign(*this, TheCall);
3501 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3502 return PointerAuthAuthLoadRelativeAndSign(*this, TheCall);
3503 case Builtin::BI__builtin_ptrauth_string_discriminator:
3504 return PointerAuthStringDiscriminator(*this, TheCall);
3505
3506 case Builtin::BI__builtin_get_vtable_pointer:
3507 return GetVTablePointer(*this, TheCall);
3508
3509 // OpenCL v2.0, s6.13.16 - Pipe functions
3510 case Builtin::BIread_pipe:
3511 case Builtin::BIwrite_pipe:
3512 // Since those two functions are declared with var args, we need a semantic
3513 // check for the argument.
3514 if (OpenCL().checkBuiltinRWPipe(TheCall))
3515 return ExprError();
3516 break;
3517 case Builtin::BIreserve_read_pipe:
3518 case Builtin::BIreserve_write_pipe:
3519 case Builtin::BIwork_group_reserve_read_pipe:
3520 case Builtin::BIwork_group_reserve_write_pipe:
3521 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3522 return ExprError();
3523 break;
3524 case Builtin::BIsub_group_reserve_read_pipe:
3525 case Builtin::BIsub_group_reserve_write_pipe:
3526 if (OpenCL().checkSubgroupExt(TheCall) ||
3527 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3528 return ExprError();
3529 break;
3530 case Builtin::BIcommit_read_pipe:
3531 case Builtin::BIcommit_write_pipe:
3532 case Builtin::BIwork_group_commit_read_pipe:
3533 case Builtin::BIwork_group_commit_write_pipe:
3534 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3535 return ExprError();
3536 break;
3537 case Builtin::BIsub_group_commit_read_pipe:
3538 case Builtin::BIsub_group_commit_write_pipe:
3539 if (OpenCL().checkSubgroupExt(TheCall) ||
3540 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3541 return ExprError();
3542 break;
3543 case Builtin::BIget_pipe_num_packets:
3544 case Builtin::BIget_pipe_max_packets:
3545 if (OpenCL().checkBuiltinPipePackets(TheCall))
3546 return ExprError();
3547 break;
3548 case Builtin::BIto_global:
3549 case Builtin::BIto_local:
3550 case Builtin::BIto_private:
3551 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3552 return ExprError();
3553 break;
3554 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3555 case Builtin::BIenqueue_kernel:
3556 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3557 return ExprError();
3558 break;
3559 case Builtin::BIget_kernel_work_group_size:
3560 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3561 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3562 return ExprError();
3563 break;
3564 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3565 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3566 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3567 return ExprError();
3568 break;
3569 case Builtin::BI__builtin_os_log_format:
3570 Cleanup.setExprNeedsCleanups(true);
3571 [[fallthrough]];
3572 case Builtin::BI__builtin_os_log_format_buffer_size:
3573 if (BuiltinOSLogFormat(TheCall))
3574 return ExprError();
3575 break;
3576 case Builtin::BI__builtin_frame_address:
3577 case Builtin::BI__builtin_return_address: {
3578 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3579 return ExprError();
3580
3581 // -Wframe-address warning if non-zero passed to builtin
3582 // return/frame address.
3583 Expr::EvalResult Result;
3584 if (!TheCall->getArg(0)->isValueDependent() &&
3585 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3586 Result.Val.getInt() != 0)
3587 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3588 << ((BuiltinID == Builtin::BI__builtin_return_address)
3589 ? "__builtin_return_address"
3590 : "__builtin_frame_address")
3591 << TheCall->getSourceRange();
3592 break;
3593 }
3594
3595 case Builtin::BI__builtin_nondeterministic_value: {
3596 if (BuiltinNonDeterministicValue(TheCall))
3597 return ExprError();
3598 break;
3599 }
3600
3601 // __builtin_elementwise_abs restricts the element type to signed integers or
3602 // floating point types only.
3603 case Builtin::BI__builtin_elementwise_abs:
3606 return ExprError();
3607 break;
3608
3609 // These builtins restrict the element type to floating point
3610 // types only.
3611 case Builtin::BI__builtin_elementwise_acos:
3612 case Builtin::BI__builtin_elementwise_asin:
3613 case Builtin::BI__builtin_elementwise_atan:
3614 case Builtin::BI__builtin_elementwise_ceil:
3615 case Builtin::BI__builtin_elementwise_cos:
3616 case Builtin::BI__builtin_elementwise_cosh:
3617 case Builtin::BI__builtin_elementwise_exp:
3618 case Builtin::BI__builtin_elementwise_exp2:
3619 case Builtin::BI__builtin_elementwise_exp10:
3620 case Builtin::BI__builtin_elementwise_floor:
3621 case Builtin::BI__builtin_elementwise_log:
3622 case Builtin::BI__builtin_elementwise_log2:
3623 case Builtin::BI__builtin_elementwise_log10:
3624 case Builtin::BI__builtin_elementwise_roundeven:
3625 case Builtin::BI__builtin_elementwise_round:
3626 case Builtin::BI__builtin_elementwise_rint:
3627 case Builtin::BI__builtin_elementwise_nearbyint:
3628 case Builtin::BI__builtin_elementwise_sin:
3629 case Builtin::BI__builtin_elementwise_sinh:
3630 case Builtin::BI__builtin_elementwise_sqrt:
3631 case Builtin::BI__builtin_elementwise_tan:
3632 case Builtin::BI__builtin_elementwise_tanh:
3633 case Builtin::BI__builtin_elementwise_trunc:
3634 case Builtin::BI__builtin_elementwise_canonicalize:
3637 return ExprError();
3638 break;
3639 case Builtin::BI__builtin_elementwise_fma:
3640 if (BuiltinElementwiseTernaryMath(TheCall))
3641 return ExprError();
3642 break;
3643
3644 case Builtin::BI__builtin_elementwise_ldexp: {
3645 if (checkArgCount(TheCall, 2))
3646 return ExprError();
3647
3648 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
3649 if (A.isInvalid())
3650 return ExprError();
3651 QualType TyA = A.get()->getType();
3652 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
3654 return ExprError();
3655
3656 ExprResult Exp = UsualUnaryConversions(TheCall->getArg(1));
3657 if (Exp.isInvalid())
3658 return ExprError();
3659 QualType TyExp = Exp.get()->getType();
3660 if (checkMathBuiltinElementType(*this, Exp.get()->getBeginLoc(), TyExp,
3662 2))
3663 return ExprError();
3664
3665 // Check the two arguments are either scalars or vectors of equal length.
3666 const auto *Vec0 = TyA->getAs<VectorType>();
3667 const auto *Vec1 = TyExp->getAs<VectorType>();
3668 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3669 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3670 if (Arg0Length != Arg1Length) {
3671 Diag(Exp.get()->getBeginLoc(),
3672 diag::err_typecheck_vector_lengths_not_equal)
3673 << TyA << TyExp << A.get()->getSourceRange()
3674 << Exp.get()->getSourceRange();
3675 return ExprError();
3676 }
3677
3678 TheCall->setArg(0, A.get());
3679 TheCall->setArg(1, Exp.get());
3680 TheCall->setType(TyA);
3681 break;
3682 }
3683
3684 // These builtins restrict the element type to floating point
3685 // types only, and take in two arguments.
3686 case Builtin::BI__builtin_elementwise_minnum:
3687 case Builtin::BI__builtin_elementwise_maxnum:
3688 case Builtin::BI__builtin_elementwise_minimum:
3689 case Builtin::BI__builtin_elementwise_maximum:
3690 case Builtin::BI__builtin_elementwise_minimumnum:
3691 case Builtin::BI__builtin_elementwise_maximumnum:
3692 case Builtin::BI__builtin_elementwise_atan2:
3693 case Builtin::BI__builtin_elementwise_fmod:
3694 case Builtin::BI__builtin_elementwise_pow:
3695 if (BuiltinElementwiseMath(TheCall,
3697 return ExprError();
3698 break;
3699 // These builtins restrict the element type to integer
3700 // types only.
3701 case Builtin::BI__builtin_elementwise_add_sat:
3702 case Builtin::BI__builtin_elementwise_sub_sat:
3703 case Builtin::BI__builtin_elementwise_clmul:
3704 if (BuiltinElementwiseMath(TheCall,
3706 return ExprError();
3707 break;
3708 case Builtin::BI__builtin_elementwise_fshl:
3709 case Builtin::BI__builtin_elementwise_fshr:
3712 return ExprError();
3713 break;
3714 case Builtin::BI__builtin_elementwise_min:
3715 case Builtin::BI__builtin_elementwise_max: {
3716 if (BuiltinElementwiseMath(TheCall))
3717 return ExprError();
3718 Expr *Arg0 = TheCall->getArg(0);
3719 Expr *Arg1 = TheCall->getArg(1);
3720 QualType Ty0 = Arg0->getType();
3721 QualType Ty1 = Arg1->getType();
3722 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
3723 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
3724 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
3725 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
3726 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
3727 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin_no_suggestion)
3728 << Context.BuiltinInfo.getQuotedName(BuiltinID);
3729 break;
3730 }
3731 case Builtin::BI__builtin_elementwise_popcount:
3732 case Builtin::BI__builtin_elementwise_bitreverse:
3735 return ExprError();
3736 break;
3737 case Builtin::BI__builtin_elementwise_copysign: {
3738 if (checkArgCount(TheCall, 2))
3739 return ExprError();
3740
3741 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3742 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3743 if (Magnitude.isInvalid() || Sign.isInvalid())
3744 return ExprError();
3745
3746 QualType MagnitudeTy = Magnitude.get()->getType();
3747 QualType SignTy = Sign.get()->getType();
3749 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
3752 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
3754 return ExprError();
3755 }
3756
3757 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3758 return Diag(Sign.get()->getBeginLoc(),
3759 diag::err_typecheck_call_different_arg_types)
3760 << MagnitudeTy << SignTy;
3761 }
3762
3763 TheCall->setArg(0, Magnitude.get());
3764 TheCall->setArg(1, Sign.get());
3765 TheCall->setType(Magnitude.get()->getType());
3766 break;
3767 }
3768 case Builtin::BI__builtin_elementwise_clzg:
3769 case Builtin::BI__builtin_elementwise_ctzg:
3770 // These builtins can be unary or binary. Note for empty calls we call the
3771 // unary checker in order to not emit an error that says the function
3772 // expects 2 arguments, which would be misleading.
3773 if (TheCall->getNumArgs() <= 1) {
3776 return ExprError();
3777 } else if (BuiltinElementwiseMath(
3779 return ExprError();
3780 break;
3781 case Builtin::BI__builtin_reduce_max:
3782 case Builtin::BI__builtin_reduce_min: {
3783 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3784 return ExprError();
3785
3786 const Expr *Arg = TheCall->getArg(0);
3787 const auto *TyA = Arg->getType()->getAs<VectorType>();
3788
3789 QualType ElTy;
3790 if (TyA)
3791 ElTy = TyA->getElementType();
3792 else if (Arg->getType()->isSizelessVectorType())
3794
3795 if (ElTy.isNull()) {
3796 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3797 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3798 << Arg->getType();
3799 return ExprError();
3800 }
3801
3802 TheCall->setType(ElTy);
3803 break;
3804 }
3805 case Builtin::BI__builtin_reduce_maximum:
3806 case Builtin::BI__builtin_reduce_minimum: {
3807 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3808 return ExprError();
3809
3810 const Expr *Arg = TheCall->getArg(0);
3811 const auto *TyA = Arg->getType()->getAs<VectorType>();
3812
3813 QualType ElTy;
3814 if (TyA)
3815 ElTy = TyA->getElementType();
3816 else if (Arg->getType()->isSizelessVectorType())
3818
3819 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3820 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3821 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3822 << Arg->getType();
3823 return ExprError();
3824 }
3825
3826 TheCall->setType(ElTy);
3827 break;
3828 }
3829
3830 // These builtins support vectors of integers only.
3831 // TODO: ADD/MUL should support floating-point types.
3832 case Builtin::BI__builtin_reduce_add:
3833 case Builtin::BI__builtin_reduce_mul:
3834 case Builtin::BI__builtin_reduce_xor:
3835 case Builtin::BI__builtin_reduce_or:
3836 case Builtin::BI__builtin_reduce_and: {
3837 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3838 return ExprError();
3839
3840 const Expr *Arg = TheCall->getArg(0);
3841
3842 QualType ElTy = getVectorElementType(Context, Arg->getType());
3843 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3844 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3845 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3846 << Arg->getType();
3847 return ExprError();
3848 }
3849
3850 TheCall->setType(ElTy);
3851 break;
3852 }
3853
3854 case Builtin::BI__builtin_reduce_assoc_fadd:
3855 case Builtin::BI__builtin_reduce_in_order_fadd: {
3856 // For in-order reductions require the user to specify the start value.
3857 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
3858 if (InOrder ? checkArgCount(TheCall, 2) : checkArgCountRange(TheCall, 1, 2))
3859 return ExprError();
3860
3861 ExprResult Vec = UsualUnaryConversions(TheCall->getArg(0));
3862 if (Vec.isInvalid())
3863 return ExprError();
3864
3865 TheCall->setArg(0, Vec.get());
3866
3867 QualType ElTy = getVectorElementType(Context, Vec.get()->getType());
3868 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
3869 Diag(Vec.get()->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3870 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3871 << Vec.get()->getType();
3872 return ExprError();
3873 }
3874
3875 if (TheCall->getNumArgs() == 2) {
3876 ExprResult StartValue = UsualUnaryConversions(TheCall->getArg(1));
3877 if (StartValue.isInvalid())
3878 return ExprError();
3879
3880 if (!StartValue.get()->getType()->isRealFloatingType()) {
3881 Diag(StartValue.get()->getBeginLoc(),
3882 diag::err_builtin_invalid_arg_type)
3883 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
3884 << StartValue.get()->getType();
3885 return ExprError();
3886 }
3887 TheCall->setArg(1, StartValue.get());
3888 }
3889
3890 TheCall->setType(ElTy);
3891 break;
3892 }
3893
3894 case Builtin::BI__builtin_matrix_transpose:
3895 return BuiltinMatrixTranspose(TheCall, TheCallResult);
3896
3897 case Builtin::BI__builtin_matrix_column_major_load:
3898 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
3899
3900 case Builtin::BI__builtin_matrix_column_major_store:
3901 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
3902
3903 case Builtin::BI__builtin_verbose_trap:
3904 if (!checkBuiltinVerboseTrap(TheCall, *this))
3905 return ExprError();
3906 break;
3907
3908 case Builtin::BI__builtin_get_device_side_mangled_name: {
3909 auto Check = [](CallExpr *TheCall) {
3910 if (TheCall->getNumArgs() != 1)
3911 return false;
3912 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
3913 if (!DRE)
3914 return false;
3915 auto *D = DRE->getDecl();
3916 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
3917 return false;
3918 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3919 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3920 };
3921 if (!Check(TheCall)) {
3922 Diag(TheCall->getBeginLoc(),
3923 diag::err_hip_invalid_args_builtin_mangled_name);
3924 return ExprError();
3925 }
3926 break;
3927 }
3928 case Builtin::BI__builtin_bswapg:
3929 if (BuiltinBswapg(*this, TheCall))
3930 return ExprError();
3931 break;
3932 case Builtin::BI__builtin_bitreverseg:
3933 if (BuiltinBitreverseg(*this, TheCall))
3934 return ExprError();
3935 break;
3936 case Builtin::BI__builtin_popcountg:
3937 if (BuiltinPopcountg(*this, TheCall))
3938 return ExprError();
3939 break;
3940 case Builtin::BI__builtin_clzg:
3941 case Builtin::BI__builtin_ctzg:
3942 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
3943 return ExprError();
3944 break;
3945
3946 case Builtin::BI__builtin_stdc_rotate_left:
3947 case Builtin::BI__builtin_stdc_rotate_right:
3948 if (BuiltinRotateGeneric(*this, TheCall))
3949 return ExprError();
3950 break;
3951
3952 case Builtin::BI__builtin_stdc_memreverse8:
3953 case Builtin::BIstdc_memreverse8:
3954 case Builtin::BIstdc_memreverse8u8:
3955 case Builtin::BIstdc_memreverse8u16:
3956 case Builtin::BIstdc_memreverse8u32:
3957 case Builtin::BIstdc_memreverse8u64:
3958 if (Context.getTargetInfo().getCharWidth() != 8) {
3959 Diag(TheCall->getBeginLoc(), diag::err_builtin_requires_char_bit_8)
3960 << TheCall->getDirectCallee()->getName();
3961 return ExprError();
3962 }
3963 break;
3964
3965 case Builtin::BI__builtin_stdc_bit_floor:
3966 case Builtin::BI__builtin_stdc_bit_ceil:
3967 if (BuiltinStdCBuiltin(*this, TheCall, QualType()))
3968 return ExprError();
3969 break;
3970 case Builtin::BI__builtin_stdc_has_single_bit:
3971 if (BuiltinStdCBuiltin(*this, TheCall, Context.BoolTy))
3972 return ExprError();
3973 break;
3974 case Builtin::BI__builtin_stdc_leading_zeros:
3975 case Builtin::BI__builtin_stdc_leading_ones:
3976 case Builtin::BI__builtin_stdc_trailing_zeros:
3977 case Builtin::BI__builtin_stdc_trailing_ones:
3978 case Builtin::BI__builtin_stdc_first_leading_zero:
3979 case Builtin::BI__builtin_stdc_first_leading_one:
3980 case Builtin::BI__builtin_stdc_first_trailing_zero:
3981 case Builtin::BI__builtin_stdc_first_trailing_one:
3982 case Builtin::BI__builtin_stdc_count_zeros:
3983 case Builtin::BI__builtin_stdc_count_ones:
3984 case Builtin::BI__builtin_stdc_bit_width:
3985 if (BuiltinStdCBuiltin(*this, TheCall, Context.UnsignedIntTy))
3986 return ExprError();
3987 break;
3988
3989 case Builtin::BI__builtin_allow_runtime_check: {
3990 Expr *Arg = TheCall->getArg(0);
3991 // Check if the argument is a string literal.
3993 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3994 << Arg->getSourceRange();
3995 return ExprError();
3996 }
3997 break;
3998 }
3999
4000 case Builtin::BI__builtin_allow_sanitize_check: {
4001 if (checkArgCount(TheCall, 1))
4002 return ExprError();
4003
4004 Expr *Arg = TheCall->getArg(0);
4005 // Check if the argument is a string literal.
4006 const StringLiteral *SanitizerName =
4007 dyn_cast<StringLiteral>(Arg->IgnoreParenImpCasts());
4008 if (!SanitizerName) {
4009 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4010 << Arg->getSourceRange();
4011 return ExprError();
4012 }
4013 // Validate the sanitizer name.
4014 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
4015 .Cases({"address", "thread", "memory", "hwaddress",
4016 "kernel-address", "kernel-memory", "kernel-hwaddress"},
4017 true)
4018 .Default(false)) {
4019 Diag(TheCall->getBeginLoc(), diag::err_invalid_builtin_argument)
4020 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
4021 << Arg->getSourceRange();
4022 return ExprError();
4023 }
4024 break;
4025 }
4026 case Builtin::BI__builtin_counted_by_ref:
4027 if (BuiltinCountedByRef(TheCall))
4028 return ExprError();
4029 break;
4030 }
4031
4032 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
4033 return ExprError();
4034
4035 // Since the target specific builtins for each arch overlap, only check those
4036 // of the arch we are compiling for.
4037 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
4038 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
4039 assert(Context.getAuxTargetInfo() &&
4040 "Aux Target Builtin, but not an aux target?");
4041
4042 if (CheckTSBuiltinFunctionCall(
4043 *Context.getAuxTargetInfo(),
4044 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
4045 return ExprError();
4046 } else {
4047 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
4048 TheCall))
4049 return ExprError();
4050 }
4051 }
4052
4053 return TheCallResult;
4054}
4055
4056bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
4057 llvm::APSInt Result;
4058 // We can't check the value of a dependent argument.
4059 Expr *Arg = TheCall->getArg(ArgNum);
4060 if (Arg->isTypeDependent() || Arg->isValueDependent())
4061 return false;
4062
4063 // Check constant-ness first.
4064 if (BuiltinConstantArg(TheCall, ArgNum, Result))
4065 return true;
4066
4067 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
4068 if (Result.isShiftedMask() || (~Result).isShiftedMask())
4069 return false;
4070
4071 return Diag(TheCall->getBeginLoc(),
4072 diag::err_argument_not_contiguous_bit_field)
4073 << ArgNum << Arg->getSourceRange();
4074}
4075
4076bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
4077 unsigned FirstArg, FormatStringInfo *FSI) {
4078 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
4079 bool IsVariadic = false;
4080 if (const FunctionType *FnTy = D->getFunctionType())
4081 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
4082 else if (const auto *BD = dyn_cast<BlockDecl>(D))
4083 IsVariadic = BD->isVariadic();
4084 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
4085 IsVariadic = OMD->isVariadic();
4086
4087 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
4088 IsVariadic, FSI);
4089}
4090
4091bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
4092 bool HasImplicitThisParam, bool IsVariadic,
4093 FormatStringInfo *FSI) {
4094 if (FirstArg == 0)
4096 else if (IsVariadic)
4098 else
4100 FSI->FormatIdx = FormatIdx - 1;
4101 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
4102
4103 // The way the format attribute works in GCC, the implicit this argument
4104 // of member functions is counted. However, it doesn't appear in our own
4105 // lists, so decrement format_idx in that case.
4106 if (HasImplicitThisParam) {
4107 if(FSI->FormatIdx == 0)
4108 return false;
4109 --FSI->FormatIdx;
4110 if (FSI->FirstDataArg != 0)
4111 --FSI->FirstDataArg;
4112 }
4113 return true;
4114}
4115
4116/// Checks if a the given expression evaluates to null.
4117///
4118/// Returns true if the value evaluates to null.
4119static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4120 // Treat (smart) pointers constructed from nullptr as null, whether we can
4121 // const-evaluate them or not.
4122 // This must happen first: the smart pointer expr might have _Nonnull type!
4126 return true;
4127
4128 // If the expression has non-null type, it doesn't evaluate to null.
4129 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
4130 if (*nullability == NullabilityKind::NonNull)
4131 return false;
4132 }
4133
4134 // As a special case, transparent unions initialized with zero are
4135 // considered null for the purposes of the nonnull attribute.
4136 if (const RecordType *UT = Expr->getType()->getAsUnionType();
4137 UT &&
4138 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
4139 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
4140 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
4141 Expr = ILE->getInit(0);
4142 }
4143
4144 bool Result;
4145 return (!Expr->isValueDependent() &&
4147 !Result);
4148}
4149
4151 const Expr *ArgExpr,
4152 SourceLocation CallSiteLoc) {
4153 if (CheckNonNullExpr(S, ArgExpr))
4154 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4155 S.PDiag(diag::warn_null_arg)
4156 << ArgExpr->getSourceRange());
4157}
4158
4159/// Determine whether the given type has a non-null nullability annotation.
4161 if (auto nullability = type->getNullability())
4162 return *nullability == NullabilityKind::NonNull;
4163
4164 return false;
4165}
4166
4168 const NamedDecl *FDecl,
4169 const FunctionProtoType *Proto,
4171 SourceLocation CallSiteLoc) {
4172 assert((FDecl || Proto) && "Need a function declaration or prototype");
4173
4174 // Already checked by constant evaluator.
4176 return;
4177 // Check the attributes attached to the method/function itself.
4178 llvm::SmallBitVector NonNullArgs;
4179 if (FDecl) {
4180 // Handle the nonnull attribute on the function/method declaration itself.
4181 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4182 if (!NonNull->args_size()) {
4183 // Easy case: all pointer arguments are nonnull.
4184 for (const auto *Arg : Args)
4185 if (S.isValidPointerAttrType(Arg->getType()))
4186 CheckNonNullArgument(S, Arg, CallSiteLoc);
4187 return;
4188 }
4189
4190 for (const ParamIdx &Idx : NonNull->args()) {
4191 unsigned IdxAST = Idx.getASTIndex();
4192 if (IdxAST >= Args.size())
4193 continue;
4194 if (NonNullArgs.empty())
4195 NonNullArgs.resize(Args.size());
4196 NonNullArgs.set(IdxAST);
4197 }
4198 }
4199 }
4200
4201 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4202 // Handle the nonnull attribute on the parameters of the
4203 // function/method.
4205 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4206 parms = FD->parameters();
4207 else
4208 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4209
4210 unsigned ParamIndex = 0;
4211 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4212 I != E; ++I, ++ParamIndex) {
4213 const ParmVarDecl *PVD = *I;
4214 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
4215 if (NonNullArgs.empty())
4216 NonNullArgs.resize(Args.size());
4217
4218 NonNullArgs.set(ParamIndex);
4219 }
4220 }
4221 } else {
4222 // If we have a non-function, non-method declaration but no
4223 // function prototype, try to dig out the function prototype.
4224 if (!Proto) {
4225 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4226 QualType type = VD->getType().getNonReferenceType();
4227 if (auto pointerType = type->getAs<PointerType>())
4228 type = pointerType->getPointeeType();
4229 else if (auto blockType = type->getAs<BlockPointerType>())
4230 type = blockType->getPointeeType();
4231 // FIXME: data member pointers?
4232
4233 // Dig out the function prototype, if there is one.
4234 Proto = type->getAs<FunctionProtoType>();
4235 }
4236 }
4237
4238 // Fill in non-null argument information from the nullability
4239 // information on the parameter types (if we have them).
4240 if (Proto) {
4241 unsigned Index = 0;
4242 for (auto paramType : Proto->getParamTypes()) {
4243 if (isNonNullType(paramType)) {
4244 if (NonNullArgs.empty())
4245 NonNullArgs.resize(Args.size());
4246
4247 NonNullArgs.set(Index);
4248 }
4249
4250 ++Index;
4251 }
4252 }
4253 }
4254
4255 // Check for non-null arguments.
4256 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4257 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4258 if (NonNullArgs[ArgIndex])
4259 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
4260 }
4261}
4262
4263void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4264 StringRef ParamName, QualType ArgTy,
4265 QualType ParamTy) {
4266
4267 // If a function accepts a pointer or reference type
4268 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4269 return;
4270
4271 // If the parameter is a pointer type, get the pointee type for the
4272 // argument too. If the parameter is a reference type, don't try to get
4273 // the pointee type for the argument.
4274 if (ParamTy->isPointerType())
4275 ArgTy = ArgTy->getPointeeType();
4276
4277 // Remove reference or pointer
4278 ParamTy = ParamTy->getPointeeType();
4279
4280 // Find expected alignment, and the actual alignment of the passed object.
4281 // getTypeAlignInChars requires complete types
4282 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4283 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4284 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4285 return;
4286
4287 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4288 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4289
4290 // If the argument is less aligned than the parameter, there is a
4291 // potential alignment issue.
4292 if (ArgAlign < ParamAlign)
4293 Diag(Loc, diag::warn_param_mismatched_alignment)
4294 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4295 << ParamName << (FDecl != nullptr) << FDecl;
4296}
4297
4298void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4299 const Expr *ThisArg,
4301 if (!FD || Args.empty())
4302 return;
4303 auto GetArgAt = [&](int Idx) -> const Expr * {
4304 if (Idx == LifetimeCaptureByAttr::Global ||
4305 Idx == LifetimeCaptureByAttr::Unknown)
4306 return nullptr;
4307 if (IsMemberFunction && Idx == 0)
4308 return ThisArg;
4309 return Args[Idx - IsMemberFunction];
4310 };
4311 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4312 unsigned ArgIdx) {
4313 if (!Attr)
4314 return;
4315
4316 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4317 for (int CapturingParamIdx : Attr->params()) {
4318 if (CapturingParamIdx == LifetimeCaptureByAttr::Invalid)
4319 continue;
4320 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4321 // initialization codepath.
4322 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4324 continue;
4325 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4326 CapturingEntity CE{Capturing};
4327 // Ensure that 'Captured' outlives the 'Capturing' entity.
4328 checkCaptureByLifetime(*this, CE, Captured);
4329 }
4330 };
4331 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4332 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(),
4333 I + IsMemberFunction);
4334 // Check when the implicit object param is captured.
4335 if (IsMemberFunction) {
4336 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4337 if (!TSI)
4338 return;
4340 for (TypeLoc TL = TSI->getTypeLoc();
4341 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4342 TL = ATL.getModifiedLoc())
4343 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4344 }
4345}
4346
4348 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4349 bool IsMemberFunction, SourceLocation Loc,
4350 SourceRange Range, VariadicCallType CallType) {
4351
4352 if ((ThisArg && ThisArg->isInstantiationDependent()) ||
4353 llvm::any_of(Args, [](const Expr *E) {
4354 return E && E->isInstantiationDependent();
4355 }))
4356 return;
4357
4358 // Printf and scanf checking.
4359 llvm::SmallBitVector CheckedVarArgs;
4360 if (FDecl) {
4361 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4362 // Only create vector if there are format attributes.
4363 CheckedVarArgs.resize(Args.size());
4364 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
4365 CheckedVarArgs);
4366 }
4367
4368 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4369 CheckedVarArgs.resize(Args.size());
4370 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4371 CheckedVarArgs);
4372 }
4373 }
4374
4375 // Refuse POD arguments that weren't caught by the format string
4376 // checks above.
4377 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4378 if (CallType != VariadicCallType::DoesNotApply &&
4379 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4380 unsigned NumParams = Proto ? Proto->getNumParams()
4381 : isa_and_nonnull<FunctionDecl>(FDecl)
4382 ? cast<FunctionDecl>(FDecl)->getNumParams()
4383 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
4384 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4385 : 0;
4386
4387 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4388 // Args[ArgIdx] can be null in malformed code.
4389 if (const Expr *Arg = Args[ArgIdx]) {
4390 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4391 checkVariadicArgument(Arg, CallType);
4392 }
4393 }
4394 }
4395 if (FD)
4396 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4397 if (FDecl || Proto) {
4398 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4399
4400 // Type safety checking.
4401 if (FDecl) {
4402 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4403 CheckArgumentWithTypeTag(I, Args, Loc);
4404 }
4405 }
4406
4407 // Check that passed arguments match the alignment of original arguments.
4408 // Try to get the missing prototype from the declaration.
4409 if (!Proto && FDecl) {
4410 const auto *FT = FDecl->getFunctionType();
4411 if (isa_and_nonnull<FunctionProtoType>(FT))
4412 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4413 }
4414 if (Proto) {
4415 // For variadic functions, we may have more args than parameters.
4416 // For some K&R functions, we may have less args than parameters.
4417 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4418 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4419 bool IsScalableArg = false;
4420 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4421 // Args[ArgIdx] can be null in malformed code.
4422 if (const Expr *Arg = Args[ArgIdx]) {
4423 if (Arg->containsErrors())
4424 continue;
4425
4426 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4427 FDecl->hasLinkage() &&
4428 FDecl->getFormalLinkage() != Linkage::Internal &&
4430 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
4431
4432 QualType ParamTy = Proto->getParamType(ArgIdx);
4433 if (ParamTy->isSizelessVectorType())
4434 IsScalableArg = true;
4435 QualType ArgTy = Arg->getType();
4436 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4437 ArgTy, ParamTy);
4438 }
4439 }
4440
4441 // If the callee has an AArch64 SME attribute to indicate that it is an
4442 // __arm_streaming function, then the caller requires SME to be available.
4445 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
4446 llvm::StringMap<bool> CallerFeatureMap;
4447 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
4448 if (!CallerFeatureMap.contains("sme"))
4449 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4450 } else if (!Context.getTargetInfo().hasFeature("sme")) {
4451 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4452 }
4453 }
4454
4455 // If the call requires a streaming-mode change and has scalable vector
4456 // arguments or return values, then warn the user that the streaming and
4457 // non-streaming vector lengths may be different.
4458 // When both streaming and non-streaming vector lengths are defined and
4459 // mismatched, produce an error.
4460 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
4461 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4462 (IsScalableArg || IsScalableRet)) {
4463 bool IsCalleeStreaming =
4465 bool IsCalleeStreamingCompatible =
4466 ExtInfo.AArch64SMEAttributes &
4468 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
4469 if (!IsCalleeStreamingCompatible &&
4470 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4471 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4472 const LangOptions &LO = getLangOpts();
4473 unsigned VL = LO.VScaleMin * 128;
4474 unsigned SVL = LO.VScaleStreamingMin * 128;
4475 bool IsVLMismatch = VL && SVL && VL != SVL;
4476
4477 auto EmitDiag = [&](bool IsArg) {
4478 if (IsVLMismatch) {
4479 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4480 // Emit warning for streaming-compatible callers
4481 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
4482 << IsArg << IsCalleeStreaming << SVL << VL;
4483 else
4484 // Emit error otherwise
4485 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4486 << IsArg << SVL << VL;
4487 } else
4488 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4489 << IsArg;
4490 };
4491
4492 if (IsScalableArg)
4493 EmitDiag(true);
4494 if (IsScalableRet)
4495 EmitDiag(false);
4496 }
4497 }
4498
4499 FunctionType::ArmStateValue CalleeArmZAState =
4501 FunctionType::ArmStateValue CalleeArmZT0State =
4503 if (CalleeArmZAState != FunctionType::ARM_None ||
4504 CalleeArmZT0State != FunctionType::ARM_None) {
4505 bool CallerHasZAState = false;
4506 bool CallerHasZT0State = false;
4507 if (CallerFD) {
4508 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4509 if (Attr && Attr->isNewZA())
4510 CallerHasZAState = true;
4511 if (Attr && Attr->isNewZT0())
4512 CallerHasZT0State = true;
4513 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4514 CallerHasZAState |=
4516 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4518 CallerHasZT0State |=
4520 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4522 }
4523 }
4524
4525 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4526 Diag(Loc, diag::err_sme_za_call_no_za_state);
4527
4528 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4529 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4530
4531 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4532 CalleeArmZT0State != FunctionType::ARM_None) {
4533 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4534 Diag(Loc, diag::note_sme_use_preserves_za);
4535 }
4536 }
4537 }
4538
4539 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4540 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4541 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4542 if (!Arg->isValueDependent()) {
4543 Expr::EvalResult Align;
4544 if (Arg->EvaluateAsInt(Align, Context)) {
4545 const llvm::APSInt &I = Align.Val.getInt();
4546 if (!I.isPowerOf2())
4547 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4548 << Arg->getSourceRange();
4549
4550 if (I > Sema::MaximumAlignment)
4551 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4552 << Arg->getSourceRange() << Sema::MaximumAlignment;
4553 }
4554 }
4555 }
4556
4557 if (FD && FD->isVariadic() && getLangOpts().SYCLIsDevice &&
4559 SYCL().DiagIfDeviceCode(Loc, diag::err_variadic_device_fn)
4560 << diag::OffloadLang::SYCL;
4561
4562 if (FD)
4563 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4564}
4565
4566void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4567 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4568 DiagnoseUseOfDecl(Decl, Loc);
4569 }
4570}
4571
4572void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4574 const FunctionProtoType *Proto,
4575 SourceLocation Loc) {
4576 VariadicCallType CallType = Proto->isVariadic()
4579
4580 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4581 CheckArgAlignment(
4582 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4583 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4584
4585 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4586 Loc, SourceRange(), CallType);
4587}
4588
4590 const FunctionProtoType *Proto) {
4591 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4592 isa<CXXMethodDecl>(FDecl);
4593 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4594 IsMemberOperatorCall;
4595 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4596 TheCall->getCallee());
4597 Expr** Args = TheCall->getArgs();
4598 unsigned NumArgs = TheCall->getNumArgs();
4599
4600 Expr *ImplicitThis = nullptr;
4601 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4602 // If this is a call to a member operator, hide the first
4603 // argument from checkCall.
4604 // FIXME: Our choice of AST representation here is less than ideal.
4605 ImplicitThis = Args[0];
4606 ++Args;
4607 --NumArgs;
4608 } else if (IsMemberFunction && !FDecl->isStatic() &&
4610 ImplicitThis =
4611 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4612
4613 if (ImplicitThis) {
4614 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4615 // used.
4616 QualType ThisType = ImplicitThis->getType();
4617 if (!ThisType->isPointerType()) {
4618 assert(!ThisType->isReferenceType());
4619 ThisType = Context.getPointerType(ThisType);
4620 }
4621
4622 QualType ThisTypeFromDecl = Context.getPointerType(
4623 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4624
4625 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4626 ThisTypeFromDecl);
4627 }
4628
4629 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4630 IsMemberFunction, TheCall->getRParenLoc(),
4631 TheCall->getCallee()->getSourceRange(), CallType);
4632
4633 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4634 // None of the checks below are needed for functions that don't have
4635 // simple names (e.g., C++ conversion functions).
4636 if (!FnInfo)
4637 return false;
4638
4639 // Enforce TCB except for builtin calls, which are always allowed.
4640 if (FDecl->getBuiltinID() == 0)
4641 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4642
4643 CheckAbsoluteValueFunction(TheCall, FDecl);
4644 CheckMaxUnsignedZero(TheCall, FDecl);
4645 CheckInfNaNFunction(TheCall, FDecl);
4646
4647 if (getLangOpts().ObjC)
4648 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4649
4650 unsigned CMId = FDecl->getMemoryFunctionKind();
4651
4652 // Handle memory setting and copying functions.
4653 switch (CMId) {
4654 case 0:
4655 return false;
4656 case Builtin::BIstrlcpy: // fallthrough
4657 case Builtin::BIstrlcat:
4658 CheckStrlcpycatArguments(TheCall, FnInfo);
4659 break;
4660 case Builtin::BIstrncat:
4661 CheckStrncatArguments(TheCall, FnInfo);
4662 break;
4663 case Builtin::BIfree:
4664 CheckFreeArguments(TheCall);
4665 break;
4666 default:
4667 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4668 }
4669
4670 return false;
4671}
4672
4673bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4674 const FunctionProtoType *Proto) {
4675 QualType Ty;
4676 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4677 Ty = V->getType().getNonReferenceType();
4678 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4679 Ty = F->getType().getNonReferenceType();
4680 else
4681 return false;
4682
4683 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4684 !Ty->isFunctionProtoType())
4685 return false;
4686
4687 VariadicCallType CallType;
4688 if (!Proto || !Proto->isVariadic()) {
4690 } else if (Ty->isBlockPointerType()) {
4691 CallType = VariadicCallType::Block;
4692 } else { // Ty->isFunctionPointerType()
4693 CallType = VariadicCallType::Function;
4694 }
4695
4696 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4697 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4698 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4699 TheCall->getCallee()->getSourceRange(), CallType);
4700
4701 return false;
4702}
4703
4704bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4705 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4706 TheCall->getCallee());
4707 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4708 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4709 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4710 TheCall->getCallee()->getSourceRange(), CallType);
4711
4712 return false;
4713}
4714
4715static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4716 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4717 return false;
4718
4719 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4720 switch (Op) {
4721 case AtomicExpr::AO__c11_atomic_init:
4722 case AtomicExpr::AO__opencl_atomic_init:
4723 llvm_unreachable("There is no ordering argument for an init");
4724
4725 case AtomicExpr::AO__c11_atomic_load:
4726 case AtomicExpr::AO__opencl_atomic_load:
4727 case AtomicExpr::AO__hip_atomic_load:
4728 case AtomicExpr::AO__atomic_load_n:
4729 case AtomicExpr::AO__atomic_load:
4730 case AtomicExpr::AO__scoped_atomic_load_n:
4731 case AtomicExpr::AO__scoped_atomic_load:
4732 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4733 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4734
4735 case AtomicExpr::AO__c11_atomic_store:
4736 case AtomicExpr::AO__opencl_atomic_store:
4737 case AtomicExpr::AO__hip_atomic_store:
4738 case AtomicExpr::AO__atomic_store:
4739 case AtomicExpr::AO__atomic_store_n:
4740 case AtomicExpr::AO__scoped_atomic_store:
4741 case AtomicExpr::AO__scoped_atomic_store_n:
4742 case AtomicExpr::AO__atomic_clear:
4743 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4744 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4745 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4746
4747 default:
4748 return true;
4749 }
4750}
4751
4752ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4754 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4755 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4756 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4757 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4758 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4759 Op);
4760}
4761
4762/// Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_*
4763/// equivalents. Provide a fixit when the scope is a compile-time constant and
4764/// there is a direct mapping from the HIP builtin to a Clang builtin. The
4765/// compare_exchange builtins differ in how they accept the desired value, so
4766/// only a warning (without a fixit) is emitted for those.
4768 MultiExprArg Args,
4770 StringRef OldName;
4771 StringRef NewName;
4772 bool CanFixIt;
4773
4774 switch (Op) {
4775#define HIP_ATOMIC_FIXABLE(hip, scoped) \
4776 case AtomicExpr::AO__hip_atomic_##hip: \
4777 OldName = "__hip_atomic_" #hip; \
4778 NewName = "__scoped_atomic_" #scoped; \
4779 CanFixIt = true; \
4780 break;
4781 HIP_ATOMIC_FIXABLE(load, load_n)
4782 HIP_ATOMIC_FIXABLE(store, store_n)
4783 HIP_ATOMIC_FIXABLE(exchange, exchange_n)
4784 HIP_ATOMIC_FIXABLE(fetch_add, fetch_add)
4785 HIP_ATOMIC_FIXABLE(fetch_sub, fetch_sub)
4786 HIP_ATOMIC_FIXABLE(fetch_and, fetch_and)
4787 HIP_ATOMIC_FIXABLE(fetch_or, fetch_or)
4788 HIP_ATOMIC_FIXABLE(fetch_xor, fetch_xor)
4789 HIP_ATOMIC_FIXABLE(fetch_min, fetch_min)
4790 HIP_ATOMIC_FIXABLE(fetch_max, fetch_max)
4791#undef HIP_ATOMIC_FIXABLE
4792 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4793 OldName = "__hip_atomic_compare_exchange_weak";
4794 NewName = "__scoped_atomic_compare_exchange";
4795 CanFixIt = false;
4796 break;
4797 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4798 OldName = "__hip_atomic_compare_exchange_strong";
4799 NewName = "__scoped_atomic_compare_exchange";
4800 CanFixIt = false;
4801 break;
4802 default:
4803 llvm_unreachable("unhandled HIP atomic op");
4804 }
4805
4806 auto DB = S.Diag(ExprRange.getBegin(), diag::warn_hip_deprecated_builtin)
4807 << OldName << NewName;
4808 if (!CanFixIt)
4809 return;
4810
4811 DB << FixItHint::CreateReplacement(ExprRange, NewName);
4812
4813 Expr *Scope = Args[Args.size() - 1];
4814 std::optional<llvm::APSInt> ScopeVal =
4815 Scope->getIntegerConstantExpr(S.Context);
4816 if (!ScopeVal)
4817 return;
4818
4819 StringRef ScopeName;
4820 switch (ScopeVal->getZExtValue()) {
4822 ScopeName = "__MEMORY_SCOPE_SINGLE";
4823 break;
4825 ScopeName = "__MEMORY_SCOPE_WVFRNT";
4826 break;
4828 ScopeName = "__MEMORY_SCOPE_WRKGRP";
4829 break;
4831 ScopeName = "__MEMORY_SCOPE_DEVICE";
4832 break;
4834 ScopeName = "__MEMORY_SCOPE_SYSTEM";
4835 break;
4837 ScopeName = "__MEMORY_SCOPE_CLUSTR";
4838 break;
4839 default:
4840 return;
4841 }
4842
4844 CharSourceRange::getTokenRange(Scope->getSourceRange()), ScopeName);
4845}
4846
4848 SourceLocation RParenLoc, MultiExprArg Args,
4850 AtomicArgumentOrder ArgOrder) {
4851 // All the non-OpenCL operations take one of the following forms.
4852 // The OpenCL operations take the __c11 forms with one extra argument for
4853 // synchronization scope.
4854 enum {
4855 // C __c11_atomic_init(A *, C)
4856 Init,
4857
4858 // C __c11_atomic_load(A *, int)
4859 Load,
4860
4861 // void __atomic_load(A *, CP, int)
4862 LoadCopy,
4863
4864 // void __atomic_store(A *, CP, int)
4865 Copy,
4866
4867 // C __c11_atomic_add(A *, M, int)
4868 Arithmetic,
4869
4870 // C __atomic_exchange_n(A *, CP, int)
4871 Xchg,
4872
4873 // void __atomic_exchange(A *, C *, CP, int)
4874 GNUXchg,
4875
4876 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4877 C11CmpXchg,
4878
4879 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4880 GNUCmpXchg,
4881
4882 // bool __atomic_test_and_set(A *, int)
4883 TestAndSetByte,
4884
4885 // void __atomic_clear(A *, int)
4886 ClearByte,
4887 } Form = Init;
4888
4889 const unsigned NumForm = ClearByte + 1;
4890 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4891 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4892 // where:
4893 // C is an appropriate type,
4894 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4895 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4896 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4897 // the int parameters are for orderings.
4898
4899 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4900 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4901 "need to update code for modified forms");
4902 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4903 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4904 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4905 "need to update code for modified C11 atomics");
4906 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4907 Op <= AtomicExpr::AO__opencl_atomic_store;
4908 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4909 Op <= AtomicExpr::AO__hip_atomic_store;
4910 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4911 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4912 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4913 Op <= AtomicExpr::AO__c11_atomic_store) ||
4914 IsOpenCL;
4915 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4916 Op == AtomicExpr::AO__atomic_store_n ||
4917 Op == AtomicExpr::AO__atomic_exchange_n ||
4918 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4919 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4920 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4921 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4922 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4923 // Bit mask for extra allowed value types other than integers for atomic
4924 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4925 // allow floating point.
4926 enum ArithOpExtraValueType {
4927 AOEVT_None = 0,
4928 AOEVT_Pointer = 1,
4929 AOEVT_FP = 2,
4930 };
4931 unsigned ArithAllows = AOEVT_None;
4932
4933 switch (Op) {
4934 case AtomicExpr::AO__c11_atomic_init:
4935 case AtomicExpr::AO__opencl_atomic_init:
4936 Form = Init;
4937 break;
4938
4939 case AtomicExpr::AO__c11_atomic_load:
4940 case AtomicExpr::AO__opencl_atomic_load:
4941 case AtomicExpr::AO__hip_atomic_load:
4942 case AtomicExpr::AO__atomic_load_n:
4943 case AtomicExpr::AO__scoped_atomic_load_n:
4944 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4945 Form = Load;
4946 break;
4947
4948 case AtomicExpr::AO__atomic_load:
4949 case AtomicExpr::AO__scoped_atomic_load:
4950 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4951 Form = LoadCopy;
4952 break;
4953
4954 case AtomicExpr::AO__c11_atomic_store:
4955 case AtomicExpr::AO__opencl_atomic_store:
4956 case AtomicExpr::AO__hip_atomic_store:
4957 case AtomicExpr::AO__atomic_store:
4958 case AtomicExpr::AO__atomic_store_n:
4959 case AtomicExpr::AO__scoped_atomic_store:
4960 case AtomicExpr::AO__scoped_atomic_store_n:
4961 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4962 Form = Copy;
4963 break;
4964 case AtomicExpr::AO__atomic_fetch_add:
4965 case AtomicExpr::AO__atomic_fetch_sub:
4966 case AtomicExpr::AO__atomic_add_fetch:
4967 case AtomicExpr::AO__atomic_sub_fetch:
4968 case AtomicExpr::AO__scoped_atomic_fetch_add:
4969 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4970 case AtomicExpr::AO__scoped_atomic_add_fetch:
4971 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4972 case AtomicExpr::AO__c11_atomic_fetch_add:
4973 case AtomicExpr::AO__c11_atomic_fetch_sub:
4974 case AtomicExpr::AO__opencl_atomic_fetch_add:
4975 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4976 case AtomicExpr::AO__hip_atomic_fetch_add:
4977 case AtomicExpr::AO__hip_atomic_fetch_sub:
4978 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4979 Form = Arithmetic;
4980 break;
4981 case AtomicExpr::AO__atomic_fetch_max:
4982 case AtomicExpr::AO__atomic_fetch_min:
4983 case AtomicExpr::AO__atomic_max_fetch:
4984 case AtomicExpr::AO__atomic_min_fetch:
4985 case AtomicExpr::AO__scoped_atomic_fetch_max:
4986 case AtomicExpr::AO__scoped_atomic_fetch_min:
4987 case AtomicExpr::AO__scoped_atomic_max_fetch:
4988 case AtomicExpr::AO__scoped_atomic_min_fetch:
4989 case AtomicExpr::AO__c11_atomic_fetch_max:
4990 case AtomicExpr::AO__c11_atomic_fetch_min:
4991 case AtomicExpr::AO__opencl_atomic_fetch_max:
4992 case AtomicExpr::AO__opencl_atomic_fetch_min:
4993 case AtomicExpr::AO__hip_atomic_fetch_max:
4994 case AtomicExpr::AO__hip_atomic_fetch_min:
4995 ArithAllows = AOEVT_FP;
4996 Form = Arithmetic;
4997 break;
4998 case AtomicExpr::AO__c11_atomic_fetch_and:
4999 case AtomicExpr::AO__c11_atomic_fetch_or:
5000 case AtomicExpr::AO__c11_atomic_fetch_xor:
5001 case AtomicExpr::AO__hip_atomic_fetch_and:
5002 case AtomicExpr::AO__hip_atomic_fetch_or:
5003 case AtomicExpr::AO__hip_atomic_fetch_xor:
5004 case AtomicExpr::AO__c11_atomic_fetch_nand:
5005 case AtomicExpr::AO__opencl_atomic_fetch_and:
5006 case AtomicExpr::AO__opencl_atomic_fetch_or:
5007 case AtomicExpr::AO__opencl_atomic_fetch_xor:
5008 case AtomicExpr::AO__atomic_fetch_and:
5009 case AtomicExpr::AO__atomic_fetch_or:
5010 case AtomicExpr::AO__atomic_fetch_xor:
5011 case AtomicExpr::AO__atomic_fetch_nand:
5012 case AtomicExpr::AO__atomic_and_fetch:
5013 case AtomicExpr::AO__atomic_or_fetch:
5014 case AtomicExpr::AO__atomic_xor_fetch:
5015 case AtomicExpr::AO__atomic_nand_fetch:
5016 case AtomicExpr::AO__atomic_fetch_uinc:
5017 case AtomicExpr::AO__atomic_fetch_udec:
5018 case AtomicExpr::AO__scoped_atomic_fetch_and:
5019 case AtomicExpr::AO__scoped_atomic_fetch_or:
5020 case AtomicExpr::AO__scoped_atomic_fetch_xor:
5021 case AtomicExpr::AO__scoped_atomic_fetch_nand:
5022 case AtomicExpr::AO__scoped_atomic_and_fetch:
5023 case AtomicExpr::AO__scoped_atomic_or_fetch:
5024 case AtomicExpr::AO__scoped_atomic_xor_fetch:
5025 case AtomicExpr::AO__scoped_atomic_nand_fetch:
5026 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
5027 case AtomicExpr::AO__scoped_atomic_fetch_udec:
5028 Form = Arithmetic;
5029 break;
5030
5031 case AtomicExpr::AO__c11_atomic_exchange:
5032 case AtomicExpr::AO__hip_atomic_exchange:
5033 case AtomicExpr::AO__opencl_atomic_exchange:
5034 case AtomicExpr::AO__atomic_exchange_n:
5035 case AtomicExpr::AO__scoped_atomic_exchange_n:
5036 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5037 Form = Xchg;
5038 break;
5039
5040 case AtomicExpr::AO__atomic_exchange:
5041 case AtomicExpr::AO__scoped_atomic_exchange:
5042 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5043 Form = GNUXchg;
5044 break;
5045
5046 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5047 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5048 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5049 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5050 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5051 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5052 Form = C11CmpXchg;
5053 break;
5054
5055 case AtomicExpr::AO__atomic_compare_exchange:
5056 case AtomicExpr::AO__atomic_compare_exchange_n:
5057 case AtomicExpr::AO__scoped_atomic_compare_exchange:
5058 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
5059 ArithAllows = AOEVT_Pointer;
5060 Form = GNUCmpXchg;
5061 break;
5062
5063 case AtomicExpr::AO__atomic_test_and_set:
5064 Form = TestAndSetByte;
5065 break;
5066
5067 case AtomicExpr::AO__atomic_clear:
5068 Form = ClearByte;
5069 break;
5070 }
5071
5072 unsigned AdjustedNumArgs = NumArgs[Form];
5073 if ((IsOpenCL || IsHIP || IsScoped) &&
5074 Op != AtomicExpr::AO__opencl_atomic_init)
5075 ++AdjustedNumArgs;
5076 // Check we have the right number of arguments.
5077 if (Args.size() < AdjustedNumArgs) {
5078 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5079 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5080 << /*is non object*/ 0 << ExprRange;
5081 return ExprError();
5082 } else if (Args.size() > AdjustedNumArgs) {
5083 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5084 diag::err_typecheck_call_too_many_args)
5085 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5086 << /*is non object*/ 0 << ExprRange;
5087 return ExprError();
5088 }
5089
5090 // Inspect the first argument of the atomic operation.
5091 Expr *Ptr = Args[0];
5093 if (ConvertedPtr.isInvalid())
5094 return ExprError();
5095
5096 Ptr = ConvertedPtr.get();
5097 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5098 if (!pointerType) {
5099 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5100 << Ptr->getType() << 0 << Ptr->getSourceRange();
5101 return ExprError();
5102 }
5103
5104 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5105 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5106 QualType ValType = AtomTy; // 'C'
5107 if (IsC11) {
5108 if (!AtomTy->isAtomicType()) {
5109 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5110 << Ptr->getType() << Ptr->getSourceRange();
5111 return ExprError();
5112 }
5113 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5115 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5116 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5117 << Ptr->getSourceRange();
5118 return ExprError();
5119 }
5120 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5121 } else if (Form != Load && Form != LoadCopy) {
5122 if (ValType.isConstQualified()) {
5123 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5124 << Ptr->getType() << Ptr->getSourceRange();
5125 return ExprError();
5126 }
5127 }
5128
5129 if (Form != TestAndSetByte && Form != ClearByte) {
5130 // Pointer to object of size zero is not allowed.
5131 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
5132 diag::err_incomplete_type))
5133 return ExprError();
5134
5135 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
5136 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5137 << Ptr->getType() << 1 << Ptr->getSourceRange();
5138 return ExprError();
5139 }
5140 } else {
5141 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
5142 // non-const pointer type, including void* and pointers to incomplete
5143 // structs, but only access the first byte.
5144 AtomTy = Context.CharTy;
5145 AtomTy = AtomTy.withCVRQualifiers(
5146 pointerType->getPointeeType().getCVRQualifiers());
5147 QualType PointerQT = Context.getPointerType(AtomTy);
5148 pointerType = PointerQT->getAs<PointerType>();
5149 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
5150 ValType = AtomTy;
5151 }
5152
5153 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
5154 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5155 Diag(ExprRange.getBegin(),
5156 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5157 << 0 << Ptr->getType() << Ptr->getSourceRange();
5158 return ExprError();
5159 }
5160
5161 // For an arithmetic operation, the implied arithmetic must be well-formed.
5162 // For _n operations, the value type must also be a valid atomic type.
5163 if (Form == Arithmetic || IsN) {
5164 // GCC does not enforce these rules for GNU atomics, but we do to help catch
5165 // trivial type errors.
5166 auto IsAllowedValueType = [&](QualType ValType,
5167 unsigned AllowedType) -> bool {
5168 bool IsX87LongDouble =
5169 ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5170 &Context.getTargetInfo().getLongDoubleFormat() ==
5171 &llvm::APFloat::x87DoubleExtended();
5172 if (ValType->isIntegerType())
5173 return true;
5174 if (ValType->isPointerType())
5175 return AllowedType & AOEVT_Pointer;
5176 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
5177 return false;
5178 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5179 if (IsX87LongDouble)
5180 return false;
5181 return true;
5182 };
5183 if (!IsAllowedValueType(ValType, ArithAllows)) {
5184 auto DID = ArithAllows & AOEVT_FP
5185 ? (ArithAllows & AOEVT_Pointer
5186 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
5187 : diag::err_atomic_op_needs_atomic_int_or_fp)
5188 : (ArithAllows & AOEVT_Pointer
5189 ? diag::err_atomic_op_needs_atomic_int_or_ptr
5190 : diag::err_atomic_op_needs_atomic_int);
5191 Diag(ExprRange.getBegin(), DID)
5192 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5193 return ExprError();
5194 }
5195 if (IsC11 && ValType->isPointerType() &&
5197 diag::err_incomplete_type)) {
5198 return ExprError();
5199 }
5200 }
5201
5202 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5203 !AtomTy->isScalarType()) {
5204 // For GNU atomics, require a trivially-copyable type. This is not part of
5205 // the GNU atomics specification but we enforce it for consistency with
5206 // other atomics which generally all require a trivially-copyable type. This
5207 // is because atomics just copy bits.
5208 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5209 << Ptr->getType() << Ptr->getSourceRange();
5210 return ExprError();
5211 }
5212
5213 switch (ValType.getObjCLifetime()) {
5216 // okay
5217 break;
5218
5222 // FIXME: Can this happen? By this point, ValType should be known
5223 // to be trivially copyable.
5224 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5225 << ValType << Ptr->getSourceRange();
5226 return ExprError();
5227 }
5228
5229 // All atomic operations have an overload which takes a pointer to a volatile
5230 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
5231 // into the result or the other operands. Similarly atomic_load takes a
5232 // pointer to a const 'A'.
5233 ValType.removeLocalVolatile();
5234 ValType.removeLocalConst();
5235 QualType ResultType = ValType;
5236 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
5237 Form == ClearByte)
5238 ResultType = Context.VoidTy;
5239 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
5240 ResultType = Context.BoolTy;
5241
5242 // The type of a parameter passed 'by value'. In the GNU atomics, such
5243 // arguments are actually passed as pointers.
5244 QualType ByValType = ValType; // 'CP'
5245 bool IsPassedByAddress = false;
5246 if (!IsC11 && !IsHIP && !IsN) {
5247 ByValType = Ptr->getType();
5248 IsPassedByAddress = true;
5249 }
5250
5251 SmallVector<Expr *, 5> APIOrderedArgs;
5252 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5253 APIOrderedArgs.push_back(Args[0]);
5254 switch (Form) {
5255 case Init:
5256 case Load:
5257 APIOrderedArgs.push_back(Args[1]); // Val1/Order
5258 break;
5259 case LoadCopy:
5260 case Copy:
5261 case Arithmetic:
5262 case Xchg:
5263 APIOrderedArgs.push_back(Args[2]); // Val1
5264 APIOrderedArgs.push_back(Args[1]); // Order
5265 break;
5266 case GNUXchg:
5267 APIOrderedArgs.push_back(Args[2]); // Val1
5268 APIOrderedArgs.push_back(Args[3]); // Val2
5269 APIOrderedArgs.push_back(Args[1]); // Order
5270 break;
5271 case C11CmpXchg:
5272 APIOrderedArgs.push_back(Args[2]); // Val1
5273 APIOrderedArgs.push_back(Args[4]); // Val2
5274 APIOrderedArgs.push_back(Args[1]); // Order
5275 APIOrderedArgs.push_back(Args[3]); // OrderFail
5276 break;
5277 case GNUCmpXchg:
5278 APIOrderedArgs.push_back(Args[2]); // Val1
5279 APIOrderedArgs.push_back(Args[4]); // Val2
5280 APIOrderedArgs.push_back(Args[5]); // Weak
5281 APIOrderedArgs.push_back(Args[1]); // Order
5282 APIOrderedArgs.push_back(Args[3]); // OrderFail
5283 break;
5284 case TestAndSetByte:
5285 case ClearByte:
5286 APIOrderedArgs.push_back(Args[1]); // Order
5287 break;
5288 }
5289 } else
5290 APIOrderedArgs.append(Args.begin(), Args.end());
5291
5292 // The first argument's non-CV pointer type is used to deduce the type of
5293 // subsequent arguments, except for:
5294 // - weak flag (always converted to bool)
5295 // - memory order (always converted to int)
5296 // - scope (always converted to int)
5297 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5298 QualType Ty;
5299 if (i < NumVals[Form] + 1) {
5300 switch (i) {
5301 case 0:
5302 // The first argument is always a pointer. It has a fixed type.
5303 // It is always dereferenced, a nullptr is undefined.
5304 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5305 // Nothing else to do: we already know all we want about this pointer.
5306 continue;
5307 case 1:
5308 // The second argument is the non-atomic operand. For arithmetic, this
5309 // is always passed by value, and for a compare_exchange it is always
5310 // passed by address. For the rest, GNU uses by-address and C11 uses
5311 // by-value.
5312 assert(Form != Load);
5313 if (Form == Arithmetic && ValType->isPointerType())
5314 Ty = Context.getPointerDiffType();
5315 else if (Form == Init || Form == Arithmetic)
5316 Ty = ValType;
5317 else if (Form == Copy || Form == Xchg) {
5318 if (IsPassedByAddress) {
5319 // The value pointer is always dereferenced, a nullptr is undefined.
5320 CheckNonNullArgument(*this, APIOrderedArgs[i],
5321 ExprRange.getBegin());
5322 }
5323 Ty = ByValType;
5324 } else {
5325 Expr *ValArg = APIOrderedArgs[i];
5326 // The value pointer is always dereferenced, a nullptr is undefined.
5327 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5329 // Keep address space of non-atomic pointer type.
5330 if (const PointerType *PtrTy =
5331 ValArg->getType()->getAs<PointerType>()) {
5332 AS = PtrTy->getPointeeType().getAddressSpace();
5333 }
5334 Ty = Context.getPointerType(
5335 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5336 }
5337 break;
5338 case 2:
5339 // The third argument to compare_exchange / GNU exchange is the desired
5340 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5341 if (IsPassedByAddress)
5342 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5343 Ty = ByValType;
5344 break;
5345 case 3:
5346 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5347 Ty = Context.BoolTy;
5348 break;
5349 }
5350 } else {
5351 // The order(s) and scope are always converted to int.
5352 Ty = Context.IntTy;
5353 }
5354
5355 InitializedEntity Entity =
5357 ExprResult Arg = APIOrderedArgs[i];
5358 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5359 if (Arg.isInvalid())
5360 return true;
5361 APIOrderedArgs[i] = Arg.get();
5362 }
5363
5364 // Permute the arguments into a 'consistent' order.
5365 SmallVector<Expr*, 5> SubExprs;
5366 SubExprs.push_back(Ptr);
5367 switch (Form) {
5368 case Init:
5369 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5370 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5371 break;
5372 case Load:
5373 case TestAndSetByte:
5374 case ClearByte:
5375 SubExprs.push_back(APIOrderedArgs[1]); // Order
5376 break;
5377 case LoadCopy:
5378 case Copy:
5379 case Arithmetic:
5380 case Xchg:
5381 SubExprs.push_back(APIOrderedArgs[2]); // Order
5382 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5383 break;
5384 case GNUXchg:
5385 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5386 SubExprs.push_back(APIOrderedArgs[3]); // Order
5387 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5388 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5389 break;
5390 case C11CmpXchg:
5391 SubExprs.push_back(APIOrderedArgs[3]); // Order
5392 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5393 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5394 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5395 break;
5396 case GNUCmpXchg:
5397 SubExprs.push_back(APIOrderedArgs[4]); // Order
5398 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5399 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5400 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5401 SubExprs.push_back(APIOrderedArgs[3]); // Weak
5402 break;
5403 }
5404
5405 // If the memory orders are constants, check they are valid.
5406 if (SubExprs.size() >= 2 && Form != Init) {
5407 std::optional<llvm::APSInt> Success =
5408 SubExprs[1]->getIntegerConstantExpr(Context);
5409 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
5410 Diag(SubExprs[1]->getBeginLoc(),
5411 diag::warn_atomic_op_has_invalid_memory_order)
5412 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5413 << SubExprs[1]->getSourceRange();
5414 }
5415 if (SubExprs.size() >= 5) {
5416 if (std::optional<llvm::APSInt> Failure =
5417 SubExprs[3]->getIntegerConstantExpr(Context)) {
5418 if (!llvm::is_contained(
5419 {llvm::AtomicOrderingCABI::relaxed,
5420 llvm::AtomicOrderingCABI::consume,
5421 llvm::AtomicOrderingCABI::acquire,
5422 llvm::AtomicOrderingCABI::seq_cst},
5423 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5424 Diag(SubExprs[3]->getBeginLoc(),
5425 diag::warn_atomic_op_has_invalid_memory_order)
5426 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5427 }
5428 }
5429 }
5430 }
5431
5432 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5433 auto *Scope = Args[Args.size() - 1];
5434 if (std::optional<llvm::APSInt> Result =
5435 Scope->getIntegerConstantExpr(Context)) {
5436 if (!ScopeModel->isValid(Result->getZExtValue()))
5437 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
5438 << Scope->getSourceRange();
5439 }
5440 SubExprs.push_back(Scope);
5441 }
5442
5443 if (IsHIP)
5444 DiagnoseDeprecatedHIPAtomic(*this, ExprRange, Args, Op);
5445
5446 AtomicExpr *AE = new (Context)
5447 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5448
5449 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5450 Op == AtomicExpr::AO__c11_atomic_store ||
5451 Op == AtomicExpr::AO__opencl_atomic_load ||
5452 Op == AtomicExpr::AO__hip_atomic_load ||
5453 Op == AtomicExpr::AO__opencl_atomic_store ||
5454 Op == AtomicExpr::AO__hip_atomic_store) &&
5455 Context.AtomicUsesUnsupportedLibcall(AE))
5456 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5457 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5458 Op == AtomicExpr::AO__opencl_atomic_load ||
5459 Op == AtomicExpr::AO__hip_atomic_load)
5460 ? 0
5461 : 1);
5462
5463 if (ValType->isBitIntType()) {
5464 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5465 return ExprError();
5466 }
5467
5468 return AE;
5469}
5470
5471/// checkBuiltinArgument - Given a call to a builtin function, perform
5472/// normal type-checking on the given argument, updating the call in
5473/// place. This is useful when a builtin function requires custom
5474/// type-checking for some of its arguments but not necessarily all of
5475/// them.
5476///
5477/// Returns true on error.
5478static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5479 FunctionDecl *Fn = E->getDirectCallee();
5480 assert(Fn && "builtin call without direct callee!");
5481
5482 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5483 InitializedEntity Entity =
5485
5486 ExprResult Arg = E->getArg(ArgIndex);
5487 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5488 if (Arg.isInvalid())
5489 return true;
5490
5491 E->setArg(ArgIndex, Arg.get());
5492 return false;
5493}
5494
5495ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5496 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5497 Expr *Callee = TheCall->getCallee();
5498 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5499 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5500
5501 // Ensure that we have at least one argument to do type inference from.
5502 if (TheCall->getNumArgs() < 1) {
5503 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5504 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5505 << Callee->getSourceRange();
5506 return ExprError();
5507 }
5508
5509 // Inspect the first argument of the atomic builtin. This should always be
5510 // a pointer type, whose element is an integral scalar or pointer type.
5511 // Because it is a pointer type, we don't have to worry about any implicit
5512 // casts here.
5513 // FIXME: We don't allow floating point scalars as input.
5514 Expr *FirstArg = TheCall->getArg(0);
5515 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5516 if (FirstArgResult.isInvalid())
5517 return ExprError();
5518 FirstArg = FirstArgResult.get();
5519 TheCall->setArg(0, FirstArg);
5520
5521 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5522 if (!pointerType) {
5523 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5524 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5525 return ExprError();
5526 }
5527
5528 QualType ValType = pointerType->getPointeeType();
5529 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5530 !ValType->isBlockPointerType()) {
5531 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5532 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5533 return ExprError();
5534 }
5535 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5536 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5537 Diag(FirstArg->getBeginLoc(),
5538 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5539 << 1 << ValType << FirstArg->getSourceRange();
5540 return ExprError();
5541 }
5542
5543 if (ValType.isConstQualified()) {
5544 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5545 << FirstArg->getType() << FirstArg->getSourceRange();
5546 return ExprError();
5547 }
5548
5549 switch (ValType.getObjCLifetime()) {
5552 // okay
5553 break;
5554
5558 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5559 << ValType << FirstArg->getSourceRange();
5560 return ExprError();
5561 }
5562
5563 // Strip any qualifiers off ValType.
5564 ValType = ValType.getUnqualifiedType();
5565
5566 // The majority of builtins return a value, but a few have special return
5567 // types, so allow them to override appropriately below.
5568 QualType ResultType = ValType;
5569
5570 // We need to figure out which concrete builtin this maps onto. For example,
5571 // __sync_fetch_and_add with a 2 byte object turns into
5572 // __sync_fetch_and_add_2.
5573#define BUILTIN_ROW(x) \
5574 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5575 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5576
5577 static const unsigned BuiltinIndices[][5] = {
5578 BUILTIN_ROW(__sync_fetch_and_add),
5579 BUILTIN_ROW(__sync_fetch_and_sub),
5580 BUILTIN_ROW(__sync_fetch_and_or),
5581 BUILTIN_ROW(__sync_fetch_and_and),
5582 BUILTIN_ROW(__sync_fetch_and_xor),
5583 BUILTIN_ROW(__sync_fetch_and_nand),
5584
5585 BUILTIN_ROW(__sync_add_and_fetch),
5586 BUILTIN_ROW(__sync_sub_and_fetch),
5587 BUILTIN_ROW(__sync_and_and_fetch),
5588 BUILTIN_ROW(__sync_or_and_fetch),
5589 BUILTIN_ROW(__sync_xor_and_fetch),
5590 BUILTIN_ROW(__sync_nand_and_fetch),
5591
5592 BUILTIN_ROW(__sync_val_compare_and_swap),
5593 BUILTIN_ROW(__sync_bool_compare_and_swap),
5594 BUILTIN_ROW(__sync_lock_test_and_set),
5595 BUILTIN_ROW(__sync_lock_release),
5596 BUILTIN_ROW(__sync_swap)
5597 };
5598#undef BUILTIN_ROW
5599
5600 // Determine the index of the size.
5601 unsigned SizeIndex;
5602 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5603 case 1: SizeIndex = 0; break;
5604 case 2: SizeIndex = 1; break;
5605 case 4: SizeIndex = 2; break;
5606 case 8: SizeIndex = 3; break;
5607 case 16: SizeIndex = 4; break;
5608 default:
5609 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5610 << FirstArg->getType() << FirstArg->getSourceRange();
5611 return ExprError();
5612 }
5613
5614 // Each of these builtins has one pointer argument, followed by some number of
5615 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5616 // that we ignore. Find out which row of BuiltinIndices to read from as well
5617 // as the number of fixed args.
5618 unsigned BuiltinID = FDecl->getBuiltinID();
5619 unsigned BuiltinIndex, NumFixed = 1;
5620 bool WarnAboutSemanticsChange = false;
5621 switch (BuiltinID) {
5622 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5623 case Builtin::BI__sync_fetch_and_add:
5624 case Builtin::BI__sync_fetch_and_add_1:
5625 case Builtin::BI__sync_fetch_and_add_2:
5626 case Builtin::BI__sync_fetch_and_add_4:
5627 case Builtin::BI__sync_fetch_and_add_8:
5628 case Builtin::BI__sync_fetch_and_add_16:
5629 BuiltinIndex = 0;
5630 break;
5631
5632 case Builtin::BI__sync_fetch_and_sub:
5633 case Builtin::BI__sync_fetch_and_sub_1:
5634 case Builtin::BI__sync_fetch_and_sub_2:
5635 case Builtin::BI__sync_fetch_and_sub_4:
5636 case Builtin::BI__sync_fetch_and_sub_8:
5637 case Builtin::BI__sync_fetch_and_sub_16:
5638 BuiltinIndex = 1;
5639 break;
5640
5641 case Builtin::BI__sync_fetch_and_or:
5642 case Builtin::BI__sync_fetch_and_or_1:
5643 case Builtin::BI__sync_fetch_and_or_2:
5644 case Builtin::BI__sync_fetch_and_or_4:
5645 case Builtin::BI__sync_fetch_and_or_8:
5646 case Builtin::BI__sync_fetch_and_or_16:
5647 BuiltinIndex = 2;
5648 break;
5649
5650 case Builtin::BI__sync_fetch_and_and:
5651 case Builtin::BI__sync_fetch_and_and_1:
5652 case Builtin::BI__sync_fetch_and_and_2:
5653 case Builtin::BI__sync_fetch_and_and_4:
5654 case Builtin::BI__sync_fetch_and_and_8:
5655 case Builtin::BI__sync_fetch_and_and_16:
5656 BuiltinIndex = 3;
5657 break;
5658
5659 case Builtin::BI__sync_fetch_and_xor:
5660 case Builtin::BI__sync_fetch_and_xor_1:
5661 case Builtin::BI__sync_fetch_and_xor_2:
5662 case Builtin::BI__sync_fetch_and_xor_4:
5663 case Builtin::BI__sync_fetch_and_xor_8:
5664 case Builtin::BI__sync_fetch_and_xor_16:
5665 BuiltinIndex = 4;
5666 break;
5667
5668 case Builtin::BI__sync_fetch_and_nand:
5669 case Builtin::BI__sync_fetch_and_nand_1:
5670 case Builtin::BI__sync_fetch_and_nand_2:
5671 case Builtin::BI__sync_fetch_and_nand_4:
5672 case Builtin::BI__sync_fetch_and_nand_8:
5673 case Builtin::BI__sync_fetch_and_nand_16:
5674 BuiltinIndex = 5;
5675 WarnAboutSemanticsChange = true;
5676 break;
5677
5678 case Builtin::BI__sync_add_and_fetch:
5679 case Builtin::BI__sync_add_and_fetch_1:
5680 case Builtin::BI__sync_add_and_fetch_2:
5681 case Builtin::BI__sync_add_and_fetch_4:
5682 case Builtin::BI__sync_add_and_fetch_8:
5683 case Builtin::BI__sync_add_and_fetch_16:
5684 BuiltinIndex = 6;
5685 break;
5686
5687 case Builtin::BI__sync_sub_and_fetch:
5688 case Builtin::BI__sync_sub_and_fetch_1:
5689 case Builtin::BI__sync_sub_and_fetch_2:
5690 case Builtin::BI__sync_sub_and_fetch_4:
5691 case Builtin::BI__sync_sub_and_fetch_8:
5692 case Builtin::BI__sync_sub_and_fetch_16:
5693 BuiltinIndex = 7;
5694 break;
5695
5696 case Builtin::BI__sync_and_and_fetch:
5697 case Builtin::BI__sync_and_and_fetch_1:
5698 case Builtin::BI__sync_and_and_fetch_2:
5699 case Builtin::BI__sync_and_and_fetch_4:
5700 case Builtin::BI__sync_and_and_fetch_8:
5701 case Builtin::BI__sync_and_and_fetch_16:
5702 BuiltinIndex = 8;
5703 break;
5704
5705 case Builtin::BI__sync_or_and_fetch:
5706 case Builtin::BI__sync_or_and_fetch_1:
5707 case Builtin::BI__sync_or_and_fetch_2:
5708 case Builtin::BI__sync_or_and_fetch_4:
5709 case Builtin::BI__sync_or_and_fetch_8:
5710 case Builtin::BI__sync_or_and_fetch_16:
5711 BuiltinIndex = 9;
5712 break;
5713
5714 case Builtin::BI__sync_xor_and_fetch:
5715 case Builtin::BI__sync_xor_and_fetch_1:
5716 case Builtin::BI__sync_xor_and_fetch_2:
5717 case Builtin::BI__sync_xor_and_fetch_4:
5718 case Builtin::BI__sync_xor_and_fetch_8:
5719 case Builtin::BI__sync_xor_and_fetch_16:
5720 BuiltinIndex = 10;
5721 break;
5722
5723 case Builtin::BI__sync_nand_and_fetch:
5724 case Builtin::BI__sync_nand_and_fetch_1:
5725 case Builtin::BI__sync_nand_and_fetch_2:
5726 case Builtin::BI__sync_nand_and_fetch_4:
5727 case Builtin::BI__sync_nand_and_fetch_8:
5728 case Builtin::BI__sync_nand_and_fetch_16:
5729 BuiltinIndex = 11;
5730 WarnAboutSemanticsChange = true;
5731 break;
5732
5733 case Builtin::BI__sync_val_compare_and_swap:
5734 case Builtin::BI__sync_val_compare_and_swap_1:
5735 case Builtin::BI__sync_val_compare_and_swap_2:
5736 case Builtin::BI__sync_val_compare_and_swap_4:
5737 case Builtin::BI__sync_val_compare_and_swap_8:
5738 case Builtin::BI__sync_val_compare_and_swap_16:
5739 BuiltinIndex = 12;
5740 NumFixed = 2;
5741 break;
5742
5743 case Builtin::BI__sync_bool_compare_and_swap:
5744 case Builtin::BI__sync_bool_compare_and_swap_1:
5745 case Builtin::BI__sync_bool_compare_and_swap_2:
5746 case Builtin::BI__sync_bool_compare_and_swap_4:
5747 case Builtin::BI__sync_bool_compare_and_swap_8:
5748 case Builtin::BI__sync_bool_compare_and_swap_16:
5749 BuiltinIndex = 13;
5750 NumFixed = 2;
5751 ResultType = Context.BoolTy;
5752 break;
5753
5754 case Builtin::BI__sync_lock_test_and_set:
5755 case Builtin::BI__sync_lock_test_and_set_1:
5756 case Builtin::BI__sync_lock_test_and_set_2:
5757 case Builtin::BI__sync_lock_test_and_set_4:
5758 case Builtin::BI__sync_lock_test_and_set_8:
5759 case Builtin::BI__sync_lock_test_and_set_16:
5760 BuiltinIndex = 14;
5761 break;
5762
5763 case Builtin::BI__sync_lock_release:
5764 case Builtin::BI__sync_lock_release_1:
5765 case Builtin::BI__sync_lock_release_2:
5766 case Builtin::BI__sync_lock_release_4:
5767 case Builtin::BI__sync_lock_release_8:
5768 case Builtin::BI__sync_lock_release_16:
5769 BuiltinIndex = 15;
5770 NumFixed = 0;
5771 ResultType = Context.VoidTy;
5772 break;
5773
5774 case Builtin::BI__sync_swap:
5775 case Builtin::BI__sync_swap_1:
5776 case Builtin::BI__sync_swap_2:
5777 case Builtin::BI__sync_swap_4:
5778 case Builtin::BI__sync_swap_8:
5779 case Builtin::BI__sync_swap_16:
5780 BuiltinIndex = 16;
5781 break;
5782 }
5783
5784 // Now that we know how many fixed arguments we expect, first check that we
5785 // have at least that many.
5786 if (TheCall->getNumArgs() < 1+NumFixed) {
5787 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5788 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5789 << Callee->getSourceRange();
5790 return ExprError();
5791 }
5792
5793 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5794 << Callee->getSourceRange();
5795
5796 if (WarnAboutSemanticsChange) {
5797 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5798 << Callee->getSourceRange();
5799 }
5800
5801 // Get the decl for the concrete builtin from this, we can tell what the
5802 // concrete integer type we should convert to is.
5803 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5804 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5805 FunctionDecl *NewBuiltinDecl;
5806 if (NewBuiltinID == BuiltinID)
5807 NewBuiltinDecl = FDecl;
5808 else {
5809 // Perform builtin lookup to avoid redeclaring it.
5810 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5811 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5812 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5813 assert(Res.getFoundDecl());
5814 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5815 if (!NewBuiltinDecl)
5816 return ExprError();
5817 }
5818
5819 // The first argument --- the pointer --- has a fixed type; we
5820 // deduce the types of the rest of the arguments accordingly. Walk
5821 // the remaining arguments, converting them to the deduced value type.
5822 for (unsigned i = 0; i != NumFixed; ++i) {
5823 ExprResult Arg = TheCall->getArg(i+1);
5824
5825 // GCC does an implicit conversion to the pointer or integer ValType. This
5826 // can fail in some cases (1i -> int**), check for this error case now.
5827 // Initialize the argument.
5828 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5829 ValType, /*consume*/ false);
5830 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5831 if (Arg.isInvalid())
5832 return ExprError();
5833
5834 // Okay, we have something that *can* be converted to the right type. Check
5835 // to see if there is a potentially weird extension going on here. This can
5836 // happen when you do an atomic operation on something like an char* and
5837 // pass in 42. The 42 gets converted to char. This is even more strange
5838 // for things like 45.123 -> char, etc.
5839 // FIXME: Do this check.
5840 TheCall->setArg(i+1, Arg.get());
5841 }
5842
5843 // Create a new DeclRefExpr to refer to the new decl.
5844 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5845 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5846 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5847 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5848
5849 // Set the callee in the CallExpr.
5850 // FIXME: This loses syntactic information.
5851 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5852 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5853 CK_BuiltinFnToFnPtr);
5854 TheCall->setCallee(PromotedCall.get());
5855
5856 // Change the result type of the call to match the original value type. This
5857 // is arbitrary, but the codegen for these builtins ins design to handle it
5858 // gracefully.
5859 TheCall->setType(ResultType);
5860
5861 // Prohibit problematic uses of bit-precise integer types with atomic
5862 // builtins. The arguments would have already been converted to the first
5863 // argument's type, so only need to check the first argument.
5864 const auto *BitIntValType = ValType->getAs<BitIntType>();
5865 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
5866 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5867 return ExprError();
5868 }
5869
5870 return TheCallResult;
5871}
5872
5873ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5874 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5875 DeclRefExpr *DRE =
5877 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5878 unsigned BuiltinID = FDecl->getBuiltinID();
5879 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5880 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5881 "Unexpected nontemporal load/store builtin!");
5882 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5883 unsigned numArgs = isStore ? 2 : 1;
5884
5885 // Ensure that we have the proper number of arguments.
5886 if (checkArgCount(TheCall, numArgs))
5887 return ExprError();
5888
5889 // Inspect the last argument of the nontemporal builtin. This should always
5890 // be a pointer type, from which we imply the type of the memory access.
5891 // Because it is a pointer type, we don't have to worry about any implicit
5892 // casts here.
5893 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5894 ExprResult PointerArgResult =
5896
5897 if (PointerArgResult.isInvalid())
5898 return ExprError();
5899 PointerArg = PointerArgResult.get();
5900 TheCall->setArg(numArgs - 1, PointerArg);
5901
5902 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5903 if (!pointerType) {
5904 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5905 << PointerArg->getType() << PointerArg->getSourceRange();
5906 return ExprError();
5907 }
5908
5909 QualType ValType = pointerType->getPointeeType();
5910
5911 // Strip any qualifiers off ValType.
5912 ValType = ValType.getUnqualifiedType();
5913 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5914 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5915 !ValType->isVectorType()) {
5916 Diag(DRE->getBeginLoc(),
5917 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5918 << PointerArg->getType() << PointerArg->getSourceRange();
5919 return ExprError();
5920 }
5921
5922 if (!isStore) {
5923 TheCall->setType(ValType);
5924 return TheCallResult;
5925 }
5926
5927 ExprResult ValArg = TheCall->getArg(0);
5928 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5929 Context, ValType, /*consume*/ false);
5930 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5931 if (ValArg.isInvalid())
5932 return ExprError();
5933
5934 TheCall->setArg(0, ValArg.get());
5935 TheCall->setType(Context.VoidTy);
5936 return TheCallResult;
5937}
5938
5939/// CheckObjCString - Checks that the format string argument to the os_log()
5940/// and os_trace() functions is correct, and converts it to const char *.
5941ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5942 Arg = Arg->IgnoreParenCasts();
5943 auto *Literal = dyn_cast<StringLiteral>(Arg);
5944 if (!Literal) {
5945 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5946 Literal = ObjcLiteral->getString();
5947 }
5948 }
5949
5950 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5951 return ExprError(
5952 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5953 << Arg->getSourceRange());
5954 }
5955
5956 ExprResult Result(Literal);
5957 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5958 InitializedEntity Entity =
5960 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5961 return Result;
5962}
5963
5964/// Check that the user is calling the appropriate va_start builtin for the
5965/// target and calling convention.
5966static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5967 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5968 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5969 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5970 TT.getArch() == llvm::Triple::aarch64_32);
5971 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5972 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5973 if (IsX64 || IsAArch64) {
5974 CallingConv CC = CC_C;
5975 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5976 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5977 if (IsMSVAStart) {
5978 // Don't allow this in System V ABI functions.
5979 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5980 return S.Diag(Fn->getBeginLoc(),
5981 diag::err_ms_va_start_used_in_sysv_function);
5982 } else {
5983 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5984 // On x64 Windows, don't allow this in System V ABI functions.
5985 // (Yes, that means there's no corresponding way to support variadic
5986 // System V ABI functions on Windows.)
5987 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5988 (!IsWindowsOrUEFI && CC == CC_Win64))
5989 return S.Diag(Fn->getBeginLoc(),
5990 diag::err_va_start_used_in_wrong_abi_function)
5991 << !IsWindowsOrUEFI;
5992 }
5993 return false;
5994 }
5995
5996 if (IsMSVAStart)
5997 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5998 return false;
5999}
6000
6002 ParmVarDecl **LastParam = nullptr) {
6003 // Determine whether the current function, block, or obj-c method is variadic
6004 // and get its parameter list.
6005 bool IsVariadic = false;
6007 DeclContext *Caller = S.CurContext;
6008 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6009 IsVariadic = Block->isVariadic();
6010 Params = Block->parameters();
6011 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6012 IsVariadic = FD->isVariadic();
6013 Params = FD->parameters();
6014 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6015 IsVariadic = MD->isVariadic();
6016 // FIXME: This isn't correct for methods (results in bogus warning).
6017 Params = MD->parameters();
6018 } else if (isa<CapturedDecl>(Caller)) {
6019 // We don't support va_start in a CapturedDecl.
6020 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6021 return true;
6022 } else {
6023 // This must be some other declcontext that parses exprs.
6024 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6025 return true;
6026 }
6027
6028 if (!IsVariadic) {
6029 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6030 return true;
6031 }
6032
6033 if (LastParam)
6034 *LastParam = Params.empty() ? nullptr : Params.back();
6035
6036 return false;
6037}
6038
6039bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6040 Expr *Fn = TheCall->getCallee();
6041 if (checkVAStartABI(*this, BuiltinID, Fn))
6042 return true;
6043
6044 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
6045 // This builtin requires one argument (the va_list), allows two arguments,
6046 // but diagnoses more than two arguments. e.g.,
6047 // __builtin_c23_va_start(); // error
6048 // __builtin_c23_va_start(list); // ok
6049 // __builtin_c23_va_start(list, param); // ok
6050 // __builtin_c23_va_start(list, anything, anything); // error
6051 // This differs from the GCC behavior in that they accept the last case
6052 // with a warning, but it doesn't seem like a useful behavior to allow.
6053 if (checkArgCountRange(TheCall, 1, 2))
6054 return true;
6055 } else {
6056 // In C23 mode, va_start only needs one argument. However, the builtin still
6057 // requires two arguments (which matches the behavior of the GCC builtin),
6058 // <stdarg.h> passes `0` as the second argument in C23 mode.
6059 if (checkArgCount(TheCall, 2))
6060 return true;
6061 }
6062
6063 // Type-check the first argument normally.
6064 if (checkBuiltinArgument(*this, TheCall, 0))
6065 return true;
6066
6067 // Check that the current function is variadic, and get its last parameter.
6068 ParmVarDecl *LastParam;
6069 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6070 return true;
6071
6072 // Verify that the second argument to the builtin is the last non-variadic
6073 // argument of the current function or method. In C23 mode, if the call is
6074 // not to __builtin_c23_va_start, and the second argument is an integer
6075 // constant expression with value 0, then we don't bother with this check.
6076 // For __builtin_c23_va_start, we only perform the check for the second
6077 // argument being the last argument to the current function if there is a
6078 // second argument present.
6079 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
6080 TheCall->getNumArgs() < 2) {
6081 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6082 return false;
6083 }
6084
6085 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6086 if (std::optional<llvm::APSInt> Val =
6088 Val && LangOpts.C23 && *Val == 0 &&
6089 BuiltinID != Builtin::BI__builtin_c23_va_start) {
6090 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6091 return false;
6092 }
6093
6094 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
6095 // next block.
6096 QualType Type;
6097 SourceLocation ParamLoc;
6098 bool IsCRegister = false;
6099 bool SecondArgIsLastNonVariadicArgument = false;
6100 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6101 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6102 SecondArgIsLastNonVariadicArgument = PV == LastParam;
6103
6104 Type = PV->getType();
6105 ParamLoc = PV->getLocation();
6106 IsCRegister =
6107 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6108 }
6109 }
6110
6111 if (!SecondArgIsLastNonVariadicArgument)
6112 Diag(TheCall->getArg(1)->getBeginLoc(),
6113 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
6114 else if (IsCRegister || Type->isReferenceType() ||
6115 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6116 // Promotable integers are UB, but enumerations need a bit of
6117 // extra checking to see what their promotable type actually is.
6118 if (!Context.isPromotableIntegerType(Type))
6119 return false;
6120 const auto *ED = Type->getAsEnumDecl();
6121 if (!ED)
6122 return true;
6123 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
6124 }()) {
6125 unsigned Reason = 0;
6126 if (Type->isReferenceType()) Reason = 1;
6127 else if (IsCRegister) Reason = 2;
6128 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6129 Diag(ParamLoc, diag::note_parameter_type) << Type;
6130 }
6131
6132 return false;
6133}
6134
6135bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
6136 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6137 const LangOptions &LO = getLangOpts();
6138
6139 if (LO.CPlusPlus)
6140 return Arg->getType()
6142 .getTypePtr()
6143 ->getPointeeType()
6145
6146 // In C, allow aliasing through `char *`, this is required for AArch64 at
6147 // least.
6148 return true;
6149 };
6150
6151 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6152 // const char *named_addr);
6153
6154 Expr *Func = Call->getCallee();
6155
6156 if (Call->getNumArgs() < 3)
6157 return Diag(Call->getEndLoc(),
6158 diag::err_typecheck_call_too_few_args_at_least)
6159 << 0 /*function call*/ << 3 << Call->getNumArgs()
6160 << /*is non object*/ 0;
6161
6162 // Type-check the first argument normally.
6163 if (checkBuiltinArgument(*this, Call, 0))
6164 return true;
6165
6166 // Check that the current function is variadic.
6168 return true;
6169
6170 // __va_start on Windows does not validate the parameter qualifiers
6171
6172 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6173 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6174
6175 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6176 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6177
6178 const QualType &ConstCharPtrTy =
6179 Context.getPointerType(Context.CharTy.withConst());
6180 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6181 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6182 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6183 << 0 /* qualifier difference */
6184 << 3 /* parameter mismatch */
6185 << 2 << Arg1->getType() << ConstCharPtrTy;
6186
6187 const QualType SizeTy = Context.getSizeType();
6188 if (!Context.hasSameType(
6190 SizeTy))
6191 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6192 << Arg2->getType() << SizeTy << 1 /* different class */
6193 << 0 /* qualifier difference */
6194 << 3 /* parameter mismatch */
6195 << 3 << Arg2->getType() << SizeTy;
6196
6197 return false;
6198}
6199
6200bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
6201 if (checkArgCount(TheCall, 2))
6202 return true;
6203
6204 if (BuiltinID == Builtin::BI__builtin_isunordered &&
6205 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
6206 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6207 << 1 << 0 << TheCall->getSourceRange();
6208
6209 ExprResult OrigArg0 = TheCall->getArg(0);
6210 ExprResult OrigArg1 = TheCall->getArg(1);
6211
6212 // Do standard promotions between the two arguments, returning their common
6213 // type.
6214 QualType Res = UsualArithmeticConversions(
6215 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
6216 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6217 return true;
6218
6219 // Make sure any conversions are pushed back into the call; this is
6220 // type safe since unordered compare builtins are declared as "_Bool
6221 // foo(...)".
6222 TheCall->setArg(0, OrigArg0.get());
6223 TheCall->setArg(1, OrigArg1.get());
6224
6225 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6226 return false;
6227
6228 // If the common type isn't a real floating type, then the arguments were
6229 // invalid for this operation.
6230 if (Res.isNull() || !Res->isRealFloatingType())
6231 return Diag(OrigArg0.get()->getBeginLoc(),
6232 diag::err_typecheck_call_invalid_ordered_compare)
6233 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6234 << SourceRange(OrigArg0.get()->getBeginLoc(),
6235 OrigArg1.get()->getEndLoc());
6236
6237 return false;
6238}
6239
6240bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
6241 unsigned BuiltinID) {
6242 if (checkArgCount(TheCall, NumArgs))
6243 return true;
6244
6245 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
6246 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
6247 BuiltinID == Builtin::BI__builtin_isinf ||
6248 BuiltinID == Builtin::BI__builtin_isinf_sign))
6249 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6250 << 0 << 0 << TheCall->getSourceRange();
6251
6252 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
6253 BuiltinID == Builtin::BI__builtin_isunordered))
6254 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6255 << 1 << 0 << TheCall->getSourceRange();
6256
6257 bool IsFPClass = NumArgs == 2;
6258
6259 // Find out position of floating-point argument.
6260 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
6261
6262 // We can count on all parameters preceding the floating-point just being int.
6263 // Try all of those.
6264 for (unsigned i = 0; i < FPArgNo; ++i) {
6265 Expr *Arg = TheCall->getArg(i);
6266
6267 if (Arg->isTypeDependent())
6268 return false;
6269
6272
6273 if (Res.isInvalid())
6274 return true;
6275 TheCall->setArg(i, Res.get());
6276 }
6277
6278 Expr *OrigArg = TheCall->getArg(FPArgNo);
6279
6280 if (OrigArg->isTypeDependent())
6281 return false;
6282
6283 // Usual Unary Conversions will convert half to float, which we want for
6284 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6285 // type how it is, but do normal L->Rvalue conversions.
6286 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
6287 ExprResult Res = UsualUnaryConversions(OrigArg);
6288
6289 if (!Res.isUsable())
6290 return true;
6291 OrigArg = Res.get();
6292 } else {
6294
6295 if (!Res.isUsable())
6296 return true;
6297 OrigArg = Res.get();
6298 }
6299 TheCall->setArg(FPArgNo, OrigArg);
6300
6301 QualType VectorResultTy;
6302 QualType ElementTy = OrigArg->getType();
6303 // TODO: When all classification function are implemented with is_fpclass,
6304 // vector argument can be supported in all of them.
6305 if (ElementTy->isVectorType() && IsFPClass) {
6306 VectorResultTy = GetSignedVectorType(ElementTy);
6307 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6308 }
6309
6310 // This operation requires a non-_Complex floating-point number.
6311 if (!ElementTy->isRealFloatingType())
6312 return Diag(OrigArg->getBeginLoc(),
6313 diag::err_typecheck_call_invalid_unary_fp)
6314 << OrigArg->getType() << OrigArg->getSourceRange();
6315
6316 // __builtin_isfpclass has integer parameter that specify test mask. It is
6317 // passed in (...), so it should be analyzed completely here.
6318 if (IsFPClass)
6319 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
6320 return true;
6321
6322 // TODO: enable this code to all classification functions.
6323 if (IsFPClass) {
6324 QualType ResultTy;
6325 if (!VectorResultTy.isNull())
6326 ResultTy = VectorResultTy;
6327 else
6328 ResultTy = Context.IntTy;
6329 TheCall->setType(ResultTy);
6330 }
6331
6332 return false;
6333}
6334
6335bool Sema::BuiltinComplex(CallExpr *TheCall) {
6336 if (checkArgCount(TheCall, 2))
6337 return true;
6338
6339 bool Dependent = false;
6340 for (unsigned I = 0; I != 2; ++I) {
6341 Expr *Arg = TheCall->getArg(I);
6342 QualType T = Arg->getType();
6343 if (T->isDependentType()) {
6344 Dependent = true;
6345 continue;
6346 }
6347
6348 // Despite supporting _Complex int, GCC requires a real floating point type
6349 // for the operands of __builtin_complex.
6350 if (!T->isRealFloatingType()) {
6351 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6352 << Arg->getType() << Arg->getSourceRange();
6353 }
6354
6355 ExprResult Converted = DefaultLvalueConversion(Arg);
6356 if (Converted.isInvalid())
6357 return true;
6358 TheCall->setArg(I, Converted.get());
6359 }
6360
6361 if (Dependent) {
6362 TheCall->setType(Context.DependentTy);
6363 return false;
6364 }
6365
6366 Expr *Real = TheCall->getArg(0);
6367 Expr *Imag = TheCall->getArg(1);
6368 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6369 return Diag(Real->getBeginLoc(),
6370 diag::err_typecheck_call_different_arg_types)
6371 << Real->getType() << Imag->getType()
6372 << Real->getSourceRange() << Imag->getSourceRange();
6373 }
6374
6375 TheCall->setType(Context.getComplexType(Real->getType()));
6376 return false;
6377}
6378
6379/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6380// This is declared to take (...), so we have to check everything.
6382 unsigned NumArgs = TheCall->getNumArgs();
6383 if (NumArgs < 2)
6384 return ExprError(Diag(TheCall->getEndLoc(),
6385 diag::err_typecheck_call_too_few_args_at_least)
6386 << 0 /*function call*/ << 2 << NumArgs
6387 << /*is non object*/ 0 << TheCall->getSourceRange());
6388
6389 // Determine which of the following types of shufflevector we're checking:
6390 // 1) unary, vector mask: (lhs, mask)
6391 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6392 QualType ResType = TheCall->getArg(0)->getType();
6393 unsigned NumElements = 0;
6394
6395 if (!TheCall->getArg(0)->isTypeDependent() &&
6396 !TheCall->getArg(1)->isTypeDependent()) {
6397 QualType LHSType = TheCall->getArg(0)->getType();
6398 QualType RHSType = TheCall->getArg(1)->getType();
6399
6400 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6401 return ExprError(
6402 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6403 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6404 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6405 TheCall->getArg(1)->getEndLoc()));
6406
6407 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6408 unsigned NumResElements = NumArgs - 2;
6409
6410 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6411 // with mask. If so, verify that RHS is an integer vector type with the
6412 // same number of elts as lhs.
6413 if (NumArgs == 2) {
6414 if (!RHSType->hasIntegerRepresentation() ||
6415 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
6416 return ExprError(Diag(TheCall->getBeginLoc(),
6417 diag::err_vec_builtin_incompatible_vector)
6418 << TheCall->getDirectCallee()
6419 << /*isMoreThanTwoArgs*/ false
6420 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6421 TheCall->getArg(1)->getEndLoc()));
6422 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6423 return ExprError(Diag(TheCall->getBeginLoc(),
6424 diag::err_vec_builtin_incompatible_vector)
6425 << TheCall->getDirectCallee()
6426 << /*isMoreThanTwoArgs*/ false
6427 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6428 TheCall->getArg(1)->getEndLoc()));
6429 } else if (NumElements != NumResElements) {
6430 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6431 ResType = ResType->isExtVectorType()
6432 ? Context.getExtVectorType(EltType, NumResElements)
6433 : Context.getVectorType(EltType, NumResElements,
6435 }
6436 }
6437
6438 for (unsigned I = 2; I != NumArgs; ++I) {
6439 Expr *Arg = TheCall->getArg(I);
6440 if (Arg->isTypeDependent() || Arg->isValueDependent())
6441 continue;
6442
6443 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
6444 if (!Result)
6445 return ExprError(Diag(TheCall->getBeginLoc(),
6446 diag::err_shufflevector_nonconstant_argument)
6447 << Arg->getSourceRange());
6448
6449 // Allow -1 which will be translated to undef in the IR.
6450 if (Result->isSigned() && Result->isAllOnes())
6451 ;
6452 else if (Result->getActiveBits() > 64 ||
6453 Result->getZExtValue() >= NumElements * 2)
6454 return ExprError(Diag(TheCall->getBeginLoc(),
6455 diag::err_shufflevector_argument_too_large)
6456 << Arg->getSourceRange());
6457
6458 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
6459 }
6460
6461 auto *Result = new (Context) ShuffleVectorExpr(
6462 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6463 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6464
6465 // All moved to Result.
6466 TheCall->shrinkNumArgs(0);
6467 return Result;
6468}
6469
6471 SourceLocation BuiltinLoc,
6472 SourceLocation RParenLoc) {
6475 QualType DstTy = TInfo->getType();
6476 QualType SrcTy = E->getType();
6477
6478 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6479 return ExprError(Diag(BuiltinLoc,
6480 diag::err_convertvector_non_vector)
6481 << E->getSourceRange());
6482 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6483 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
6484 << "second"
6485 << "__builtin_convertvector");
6486
6487 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6488 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6489 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6490 if (SrcElts != DstElts)
6491 return ExprError(Diag(BuiltinLoc,
6492 diag::err_convertvector_incompatible_vector)
6493 << E->getSourceRange());
6494 }
6495
6496 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
6497 RParenLoc, CurFPFeatureOverrides());
6498}
6499
6500bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6501 unsigned NumArgs = TheCall->getNumArgs();
6502
6503 if (NumArgs > 3)
6504 return Diag(TheCall->getEndLoc(),
6505 diag::err_typecheck_call_too_many_args_at_most)
6506 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6507 << TheCall->getSourceRange();
6508
6509 // Argument 0 is checked for us and the remaining arguments must be
6510 // constant integers.
6511 for (unsigned i = 1; i != NumArgs; ++i)
6512 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6513 return true;
6514
6515 return false;
6516}
6517
6518bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6519 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6520 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6521 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6522 if (checkArgCount(TheCall, 1))
6523 return true;
6524 Expr *Arg = TheCall->getArg(0);
6525 if (Arg->isInstantiationDependent())
6526 return false;
6527
6528 QualType ArgTy = Arg->getType();
6529 if (!ArgTy->hasFloatingRepresentation())
6530 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6531 << ArgTy;
6532 if (Arg->isLValue()) {
6533 ExprResult FirstArg = DefaultLvalueConversion(Arg);
6534 TheCall->setArg(0, FirstArg.get());
6535 }
6536 TheCall->setType(TheCall->getArg(0)->getType());
6537 return false;
6538}
6539
6540bool Sema::BuiltinAssume(CallExpr *TheCall) {
6541 Expr *Arg = TheCall->getArg(0);
6542 if (Arg->isInstantiationDependent()) return false;
6543
6544 if (Arg->HasSideEffects(Context))
6545 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6546 << Arg->getSourceRange()
6547 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6548
6549 return false;
6550}
6551
6552bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6553 // The alignment must be a constant integer.
6554 Expr *Arg = TheCall->getArg(1);
6555
6556 // We can't check the value of a dependent argument.
6557 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6558 if (const auto *UE =
6559 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6560 if (UE->getKind() == UETT_AlignOf ||
6561 UE->getKind() == UETT_PreferredAlignOf)
6562 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6563 << Arg->getSourceRange();
6564
6565 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6566
6567 if (!Result.isPowerOf2())
6568 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6569 << Arg->getSourceRange();
6570
6571 if (Result < Context.getCharWidth())
6572 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6573 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6574
6575 if (Result > std::numeric_limits<int32_t>::max())
6576 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6577 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6578 }
6579
6580 return false;
6581}
6582
6583bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6584 if (checkArgCountRange(TheCall, 2, 3))
6585 return true;
6586
6587 unsigned NumArgs = TheCall->getNumArgs();
6588 Expr *FirstArg = TheCall->getArg(0);
6589
6590 {
6591 ExprResult FirstArgResult =
6593 if (!FirstArgResult.get()->getType()->isPointerType()) {
6594 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
6595 << TheCall->getSourceRange();
6596 return true;
6597 }
6598 TheCall->setArg(0, FirstArgResult.get());
6599 }
6600
6601 // The alignment must be a constant integer.
6602 Expr *SecondArg = TheCall->getArg(1);
6603
6604 // We can't check the value of a dependent argument.
6605 if (!SecondArg->isValueDependent()) {
6606 llvm::APSInt Result;
6607 if (BuiltinConstantArg(TheCall, 1, Result))
6608 return true;
6609
6610 if (!Result.isPowerOf2())
6611 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6612 << SecondArg->getSourceRange();
6613
6615 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6616 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6617
6618 TheCall->setArg(1,
6620 }
6621
6622 if (NumArgs > 2) {
6623 Expr *ThirdArg = TheCall->getArg(2);
6624 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
6625 return true;
6626 TheCall->setArg(2, ThirdArg);
6627 }
6628
6629 return false;
6630}
6631
6632bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6633 unsigned BuiltinID =
6634 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6635 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6636
6637 unsigned NumArgs = TheCall->getNumArgs();
6638 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6639 if (NumArgs < NumRequiredArgs) {
6640 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6641 << 0 /* function call */ << NumRequiredArgs << NumArgs
6642 << /*is non object*/ 0 << TheCall->getSourceRange();
6643 }
6644 if (NumArgs >= NumRequiredArgs + 0x100) {
6645 return Diag(TheCall->getEndLoc(),
6646 diag::err_typecheck_call_too_many_args_at_most)
6647 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6648 << /*is non object*/ 0 << TheCall->getSourceRange();
6649 }
6650 unsigned i = 0;
6651
6652 // For formatting call, check buffer arg.
6653 if (!IsSizeCall) {
6654 ExprResult Arg(TheCall->getArg(i));
6655 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6656 Context, Context.VoidPtrTy, false);
6657 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6658 if (Arg.isInvalid())
6659 return true;
6660 TheCall->setArg(i, Arg.get());
6661 i++;
6662 }
6663
6664 // Check string literal arg.
6665 unsigned FormatIdx = i;
6666 {
6667 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6668 if (Arg.isInvalid())
6669 return true;
6670 TheCall->setArg(i, Arg.get());
6671 i++;
6672 }
6673
6674 // Make sure variadic args are scalar.
6675 unsigned FirstDataArg = i;
6676 while (i < NumArgs) {
6678 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6679 if (Arg.isInvalid())
6680 return true;
6681 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6682 if (ArgSize.getQuantity() >= 0x100) {
6683 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6684 << i << (int)ArgSize.getQuantity() << 0xff
6685 << TheCall->getSourceRange();
6686 }
6687 TheCall->setArg(i, Arg.get());
6688 i++;
6689 }
6690
6691 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6692 // call to avoid duplicate diagnostics.
6693 if (!IsSizeCall) {
6694 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6695 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6696 bool Success = CheckFormatArguments(
6697 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
6699 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
6700 if (!Success)
6701 return true;
6702 }
6703
6704 if (IsSizeCall) {
6705 TheCall->setType(Context.getSizeType());
6706 } else {
6707 TheCall->setType(Context.VoidPtrTy);
6708 }
6709 return false;
6710}
6711
6712bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6713 llvm::APSInt &Result) {
6714 Expr *Arg = TheCall->getArg(ArgNum);
6715
6716 if (Arg->isTypeDependent() || Arg->isValueDependent())
6717 return false;
6718
6719 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
6720 if (!R) {
6721 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6722 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6723 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6724 << FDecl->getDeclName() << Arg->getSourceRange();
6725 }
6726 Result = *R;
6727
6728 return false;
6729}
6730
6731bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6732 int High, bool RangeIsError) {
6734 return false;
6735 llvm::APSInt Result;
6736
6737 // We can't check the value of a dependent argument.
6738 Expr *Arg = TheCall->getArg(ArgNum);
6739 if (Arg->isTypeDependent() || Arg->isValueDependent())
6740 return false;
6741
6742 // Check constant-ness first.
6743 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6744 return true;
6745
6746 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6747 if (RangeIsError)
6748 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6749 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6750 else
6751 // Defer the warning until we know if the code will be emitted so that
6752 // dead code can ignore this.
6753 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6754 PDiag(diag::warn_argument_invalid_range)
6755 << toString(Result, 10) << Low << High
6756 << Arg->getSourceRange());
6757 }
6758
6759 return false;
6760}
6761
6762bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6763 unsigned Num) {
6764 llvm::APSInt Result;
6765
6766 // We can't check the value of a dependent argument.
6767 Expr *Arg = TheCall->getArg(ArgNum);
6768 if (Arg->isTypeDependent() || Arg->isValueDependent())
6769 return false;
6770
6771 // Check constant-ness first.
6772 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6773 return true;
6774
6775 if (Result.getSExtValue() % Num != 0)
6776 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6777 << Num << Arg->getSourceRange();
6778
6779 return false;
6780}
6781
6782bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6783 llvm::APSInt Result;
6784
6785 // We can't check the value of a dependent argument.
6786 Expr *Arg = TheCall->getArg(ArgNum);
6787 if (Arg->isTypeDependent() || Arg->isValueDependent())
6788 return false;
6789
6790 // Check constant-ness first.
6791 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6792 return true;
6793
6794 if (Result.isPowerOf2())
6795 return false;
6796
6797 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6798 << Arg->getSourceRange();
6799}
6800
6801static bool IsShiftedByte(llvm::APSInt Value) {
6802 if (Value.isNegative())
6803 return false;
6804
6805 // Check if it's a shifted byte, by shifting it down
6806 while (true) {
6807 // If the value fits in the bottom byte, the check passes.
6808 if (Value < 0x100)
6809 return true;
6810
6811 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6812 // fails.
6813 if ((Value & 0xFF) != 0)
6814 return false;
6815
6816 // If the bottom 8 bits are all 0, but something above that is nonzero,
6817 // then shifting the value right by 8 bits won't affect whether it's a
6818 // shifted byte or not. So do that, and go round again.
6819 Value >>= 8;
6820 }
6821}
6822
6823bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6824 unsigned ArgBits) {
6825 llvm::APSInt Result;
6826
6827 // We can't check the value of a dependent argument.
6828 Expr *Arg = TheCall->getArg(ArgNum);
6829 if (Arg->isTypeDependent() || Arg->isValueDependent())
6830 return false;
6831
6832 // Check constant-ness first.
6833 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6834 return true;
6835
6836 // Truncate to the given size.
6837 Result = Result.getLoBits(ArgBits);
6838 Result.setIsUnsigned(true);
6839
6840 if (IsShiftedByte(Result))
6841 return false;
6842
6843 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6844 << Arg->getSourceRange();
6845}
6846
6848 unsigned ArgNum,
6849 unsigned ArgBits) {
6850 llvm::APSInt Result;
6851
6852 // We can't check the value of a dependent argument.
6853 Expr *Arg = TheCall->getArg(ArgNum);
6854 if (Arg->isTypeDependent() || Arg->isValueDependent())
6855 return false;
6856
6857 // Check constant-ness first.
6858 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6859 return true;
6860
6861 // Truncate to the given size.
6862 Result = Result.getLoBits(ArgBits);
6863 Result.setIsUnsigned(true);
6864
6865 // Check to see if it's in either of the required forms.
6866 if (IsShiftedByte(Result) ||
6867 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6868 return false;
6869
6870 return Diag(TheCall->getBeginLoc(),
6871 diag::err_argument_not_shifted_byte_or_xxff)
6872 << Arg->getSourceRange();
6873}
6874
6875bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6876 if (!Context.getTargetInfo().hasSjLjLowering())
6877 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6878 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6879
6880 Expr *Arg = TheCall->getArg(1);
6881 llvm::APSInt Result;
6882
6883 // TODO: This is less than ideal. Overload this to take a value.
6884 if (BuiltinConstantArg(TheCall, 1, Result))
6885 return true;
6886
6887 if (Result != 1)
6888 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6889 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6890
6891 return false;
6892}
6893
6894bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6895 if (!Context.getTargetInfo().hasSjLjLowering())
6896 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6897 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6898 return false;
6899}
6900
6901bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6902 if (checkArgCount(TheCall, 1))
6903 return true;
6904
6905 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
6906 if (ArgRes.isInvalid())
6907 return true;
6908
6909 // For simplicity, we support only limited expressions for the argument.
6910 // Specifically a flexible array member or a pointer with counted_by:
6911 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
6912 // complex casting, which really shouldn't be a huge problem.
6913 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6914 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
6915 return Diag(Arg->getBeginLoc(),
6916 diag::err_builtin_counted_by_ref_invalid_arg)
6917 << Arg->getSourceRange();
6918
6919 if (Arg->HasSideEffects(Context))
6920 return Diag(Arg->getBeginLoc(),
6921 diag::err_builtin_counted_by_ref_has_side_effects)
6922 << Arg->getSourceRange();
6923
6924 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
6925 const auto *CATy =
6926 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6927
6928 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6929 // Member has counted_by attribute - return pointer to count field
6930 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
6931 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
6932 TheCall->setType(Context.getPointerType(CountFD->getType()));
6933 return false;
6934 }
6935 }
6936
6937 // FAMs and pointers without counted_by return void*
6938 QualType MemberTy = ME->getMemberDecl()->getType();
6939 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
6940 return Diag(Arg->getBeginLoc(),
6941 diag::err_builtin_counted_by_ref_invalid_arg)
6942 << Arg->getSourceRange();
6943 } else {
6944 return Diag(Arg->getBeginLoc(),
6945 diag::err_builtin_counted_by_ref_invalid_arg)
6946 << Arg->getSourceRange();
6947 }
6948
6949 TheCall->setType(Context.getPointerType(Context.VoidTy));
6950 return false;
6951}
6952
6953/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6954/// It allows leaking and modification of bounds safety information.
6955bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6957 const CallExpr *CE =
6958 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
6959 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6960 return false;
6961
6962 switch (K) {
6965 Diag(E->getExprLoc(),
6966 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6967 << 0 << E->getSourceRange();
6968 break;
6970 Diag(E->getExprLoc(),
6971 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6972 << 1 << E->getSourceRange();
6973 break;
6975 Diag(E->getExprLoc(),
6976 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6977 << 2 << E->getSourceRange();
6978 break;
6980 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6981 << 0 << E->getSourceRange();
6982 break;
6984 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6985 << 1 << E->getSourceRange();
6986 break;
6987 }
6988
6989 return true;
6990}
6991
6992namespace {
6993
6994class UncoveredArgHandler {
6995 enum { Unknown = -1, AllCovered = -2 };
6996
6997 signed FirstUncoveredArg = Unknown;
6998 SmallVector<const Expr *, 4> DiagnosticExprs;
6999
7000public:
7001 UncoveredArgHandler() = default;
7002
7003 bool hasUncoveredArg() const {
7004 return (FirstUncoveredArg >= 0);
7005 }
7006
7007 unsigned getUncoveredArg() const {
7008 assert(hasUncoveredArg() && "no uncovered argument");
7009 return FirstUncoveredArg;
7010 }
7011
7012 void setAllCovered() {
7013 // A string has been found with all arguments covered, so clear out
7014 // the diagnostics.
7015 DiagnosticExprs.clear();
7016 FirstUncoveredArg = AllCovered;
7017 }
7018
7019 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7020 assert(NewFirstUncoveredArg >= 0 && "Outside range");
7021
7022 // Don't update if a previous string covers all arguments.
7023 if (FirstUncoveredArg == AllCovered)
7024 return;
7025
7026 // UncoveredArgHandler tracks the highest uncovered argument index
7027 // and with it all the strings that match this index.
7028 if (NewFirstUncoveredArg == FirstUncoveredArg)
7029 DiagnosticExprs.push_back(StrExpr);
7030 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7031 DiagnosticExprs.clear();
7032 DiagnosticExprs.push_back(StrExpr);
7033 FirstUncoveredArg = NewFirstUncoveredArg;
7034 }
7035 }
7036
7037 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7038};
7039
7040enum StringLiteralCheckType {
7041 SLCT_NotALiteral,
7042 SLCT_UncheckedLiteral,
7043 SLCT_CheckedLiteral
7044};
7045
7046} // namespace
7047
7048static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7049 BinaryOperatorKind BinOpKind,
7050 bool AddendIsRight) {
7051 unsigned BitWidth = Offset.getBitWidth();
7052 unsigned AddendBitWidth = Addend.getBitWidth();
7053 // There might be negative interim results.
7054 if (Addend.isUnsigned()) {
7055 Addend = Addend.zext(++AddendBitWidth);
7056 Addend.setIsSigned(true);
7057 }
7058 // Adjust the bit width of the APSInts.
7059 if (AddendBitWidth > BitWidth) {
7060 Offset = Offset.sext(AddendBitWidth);
7061 BitWidth = AddendBitWidth;
7062 } else if (BitWidth > AddendBitWidth) {
7063 Addend = Addend.sext(BitWidth);
7064 }
7065
7066 bool Ov = false;
7067 llvm::APSInt ResOffset = Offset;
7068 if (BinOpKind == BO_Add)
7069 ResOffset = Offset.sadd_ov(Addend, Ov);
7070 else {
7071 assert(AddendIsRight && BinOpKind == BO_Sub &&
7072 "operator must be add or sub with addend on the right");
7073 ResOffset = Offset.ssub_ov(Addend, Ov);
7074 }
7075
7076 // We add an offset to a pointer here so we should support an offset as big as
7077 // possible.
7078 if (Ov) {
7079 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7080 "index (intermediate) result too big");
7081 Offset = Offset.sext(2 * BitWidth);
7082 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7083 return;
7084 }
7085
7086 Offset = std::move(ResOffset);
7087}
7088
7089namespace {
7090
7091// This is a wrapper class around StringLiteral to support offsetted string
7092// literals as format strings. It takes the offset into account when returning
7093// the string and its length or the source locations to display notes correctly.
7094class FormatStringLiteral {
7095 const StringLiteral *FExpr;
7096 int64_t Offset;
7097
7098public:
7099 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7100 : FExpr(fexpr), Offset(Offset) {}
7101
7102 const StringLiteral *getFormatString() const { return FExpr; }
7103
7104 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
7105
7106 unsigned getByteLength() const {
7107 return FExpr->getByteLength() - getCharByteWidth() * Offset;
7108 }
7109
7110 unsigned getLength() const { return FExpr->getLength() - Offset; }
7111 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7112
7113 StringLiteralKind getKind() const { return FExpr->getKind(); }
7114
7115 QualType getType() const { return FExpr->getType(); }
7116
7117 bool isAscii() const { return FExpr->isOrdinary(); }
7118 bool isWide() const { return FExpr->isWide(); }
7119 bool isUTF8() const { return FExpr->isUTF8(); }
7120 bool isUTF16() const { return FExpr->isUTF16(); }
7121 bool isUTF32() const { return FExpr->isUTF32(); }
7122 bool isPascal() const { return FExpr->isPascal(); }
7123
7124 SourceLocation getLocationOfByte(
7125 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7126 const TargetInfo &Target, unsigned *StartToken = nullptr,
7127 unsigned *StartTokenByteOffset = nullptr) const {
7128 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7129 StartToken, StartTokenByteOffset);
7130 }
7131
7132 SourceLocation getBeginLoc() const LLVM_READONLY {
7133 return FExpr->getBeginLoc().getLocWithOffset(Offset);
7134 }
7135
7136 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7137};
7138
7139} // namespace
7140
7141static void CheckFormatString(
7142 Sema &S, const FormatStringLiteral *FExpr,
7143 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
7145 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
7146 bool inFunctionCall, VariadicCallType CallType,
7147 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7148 bool IgnoreStringsWithoutSpecifiers);
7149
7150static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7151 const Expr *E);
7152
7153// Determine if an expression is a string literal or constant string.
7154// If this function returns false on the arguments to a function expecting a
7155// format string, we will usually need to emit a warning.
7156// True string literals are then checked by CheckFormatString.
7157static StringLiteralCheckType
7158checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
7159 const Expr *E, ArrayRef<const Expr *> Args,
7160 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
7161 unsigned firstDataArg, FormatStringType Type,
7162 VariadicCallType CallType, bool InFunctionCall,
7163 llvm::SmallBitVector &CheckedVarArgs,
7164 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
7165 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
7166 bool IgnoreStringsWithoutSpecifiers = false) {
7168 return SLCT_NotALiteral;
7169tryAgain:
7170 assert(Offset.isSigned() && "invalid offset");
7171
7172 if (E->isTypeDependent() || E->isValueDependent())
7173 return SLCT_NotALiteral;
7174
7175 E = E->IgnoreParenCasts();
7176
7178 // Technically -Wformat-nonliteral does not warn about this case.
7179 // The behavior of printf and friends in this case is implementation
7180 // dependent. Ideally if the format string cannot be null then
7181 // it should have a 'nonnull' attribute in the function prototype.
7182 return SLCT_UncheckedLiteral;
7183
7184 switch (E->getStmtClass()) {
7185 case Stmt::InitListExprClass:
7186 // Handle expressions like {"foobar"}.
7187 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
7188 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7189 format_idx, firstDataArg, Type, CallType,
7190 /*InFunctionCall*/ false, CheckedVarArgs,
7191 UncoveredArg, Offset, CallerFormatParamIdx,
7192 IgnoreStringsWithoutSpecifiers);
7193 }
7194 return SLCT_NotALiteral;
7195 case Stmt::BinaryConditionalOperatorClass:
7196 case Stmt::ConditionalOperatorClass: {
7197 // The expression is a literal if both sub-expressions were, and it was
7198 // completely checked only if both sub-expressions were checked.
7201
7202 // Determine whether it is necessary to check both sub-expressions, for
7203 // example, because the condition expression is a constant that can be
7204 // evaluated at compile time.
7205 bool CheckLeft = true, CheckRight = true;
7206
7207 bool Cond;
7208 if (C->getCond()->EvaluateAsBooleanCondition(
7210 if (Cond)
7211 CheckRight = false;
7212 else
7213 CheckLeft = false;
7214 }
7215
7216 // We need to maintain the offsets for the right and the left hand side
7217 // separately to check if every possible indexed expression is a valid
7218 // string literal. They might have different offsets for different string
7219 // literals in the end.
7220 StringLiteralCheckType Left;
7221 if (!CheckLeft)
7222 Left = SLCT_UncheckedLiteral;
7223 else {
7224 Left = checkFormatStringExpr(S, ReferenceFormatString, C->getTrueExpr(),
7225 Args, APK, format_idx, firstDataArg, Type,
7226 CallType, InFunctionCall, CheckedVarArgs,
7227 UncoveredArg, Offset, CallerFormatParamIdx,
7228 IgnoreStringsWithoutSpecifiers);
7229 if (Left == SLCT_NotALiteral || !CheckRight) {
7230 return Left;
7231 }
7232 }
7233
7234 StringLiteralCheckType Right = checkFormatStringExpr(
7235 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
7236 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7237 UncoveredArg, Offset, CallerFormatParamIdx,
7238 IgnoreStringsWithoutSpecifiers);
7239
7240 return (CheckLeft && Left < Right) ? Left : Right;
7241 }
7242
7243 case Stmt::ImplicitCastExprClass:
7244 E = cast<ImplicitCastExpr>(E)->getSubExpr();
7245 goto tryAgain;
7246
7247 case Stmt::OpaqueValueExprClass:
7248 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7249 E = src;
7250 goto tryAgain;
7251 }
7252 return SLCT_NotALiteral;
7253
7254 case Stmt::PredefinedExprClass:
7255 // While __func__, etc., are technically not string literals, they
7256 // cannot contain format specifiers and thus are not a security
7257 // liability.
7258 return SLCT_UncheckedLiteral;
7259
7260 case Stmt::DeclRefExprClass: {
7261 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7262
7263 // As an exception, do not flag errors for variables binding to
7264 // const string literals.
7265 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7266 bool isConstant = false;
7267 QualType T = DR->getType();
7268
7269 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7270 isConstant = AT->getElementType().isConstant(S.Context);
7271 } else if (const PointerType *PT = T->getAs<PointerType>()) {
7272 isConstant = T.isConstant(S.Context) &&
7273 PT->getPointeeType().isConstant(S.Context);
7274 } else if (T->isObjCObjectPointerType()) {
7275 // In ObjC, there is usually no "const ObjectPointer" type,
7276 // so don't check if the pointee type is constant.
7277 isConstant = T.isConstant(S.Context);
7278 }
7279
7280 if (isConstant) {
7281 if (const Expr *Init = VD->getAnyInitializer()) {
7282 // Look through initializers like const char c[] = { "foo" }
7283 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7284 if (InitList->isStringLiteralInit())
7285 Init = InitList->getInit(0)->IgnoreParenImpCasts();
7286 }
7287 return checkFormatStringExpr(
7288 S, ReferenceFormatString, Init, Args, APK, format_idx,
7289 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7290 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7291 }
7292 }
7293
7294 // When the format argument is an argument of this function, and this
7295 // function also has the format attribute, there are several interactions
7296 // for which there shouldn't be a warning. For instance, when calling
7297 // v*printf from a function that has the printf format attribute, we
7298 // should not emit a warning about using `fmt`, even though it's not
7299 // constant, because the arguments have already been checked for the
7300 // caller of `logmessage`:
7301 //
7302 // __attribute__((format(printf, 1, 2)))
7303 // void logmessage(char const *fmt, ...) {
7304 // va_list ap;
7305 // va_start(ap, fmt);
7306 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7307 // ...
7308 // }
7309 //
7310 // Another interaction that we need to support is using a format string
7311 // specified by the format_matches attribute:
7312 //
7313 // __attribute__((format_matches(printf, 1, "%s %d")))
7314 // void logmessage(char const *fmt, const char *a, int b) {
7315 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7316 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7317 // ...
7318 // }
7319 //
7320 // Yet another interaction that we need to support is calling a variadic
7321 // format function from a format function that has fixed arguments. For
7322 // instance:
7323 //
7324 // __attribute__((format(printf, 1, 2)))
7325 // void logstring(char const *fmt, char const *str) {
7326 // printf(fmt, str); /* do not emit a warning about "fmt" */
7327 // }
7328 //
7329 // Same (and perhaps more relatably) for the variadic template case:
7330 //
7331 // template<typename... Args>
7332 // __attribute__((format(printf, 1, 2)))
7333 // void log(const char *fmt, Args&&... args) {
7334 // printf(fmt, forward<Args>(args)...);
7335 // /* do not emit a warning about "fmt" */
7336 // }
7337 //
7338 // Due to implementation difficulty, we only check the format, not the
7339 // format arguments, in all cases.
7340 //
7341 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
7342 if (CallerFormatParamIdx)
7343 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7344 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
7345 for (const auto *PVFormatMatches :
7346 D->specific_attrs<FormatMatchesAttr>()) {
7347 Sema::FormatStringInfo CalleeFSI;
7348 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
7349 0, &CalleeFSI))
7350 continue;
7351 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7352 // If using the wrong type of format string, emit a diagnostic
7353 // here and stop checking to avoid irrelevant diagnostics.
7354 if (Type != S.GetFormatStringType(PVFormatMatches)) {
7355 S.Diag(Args[format_idx]->getBeginLoc(),
7356 diag::warn_format_string_type_incompatible)
7357 << PVFormatMatches->getType()->getName()
7359 if (!InFunctionCall) {
7360 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
7361 diag::note_format_string_defined);
7362 }
7363 return SLCT_UncheckedLiteral;
7364 }
7365 return checkFormatStringExpr(
7366 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
7367 Args, APK, format_idx, firstDataArg, Type, CallType,
7368 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7369 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7370 }
7371 }
7372
7373 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7374 Sema::FormatStringInfo CallerFSI;
7375 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
7376 PVFormat->getFirstArg(), &CallerFSI))
7377 continue;
7378 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7379 // We also check if the formats are compatible.
7380 // We can't pass a 'scanf' string to a 'printf' function.
7381 if (Type != S.GetFormatStringType(PVFormat)) {
7382 S.Diag(Args[format_idx]->getBeginLoc(),
7383 diag::warn_format_string_type_incompatible)
7384 << PVFormat->getType()->getName()
7386 if (!InFunctionCall) {
7387 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
7388 }
7389 return SLCT_UncheckedLiteral;
7390 }
7391 // Lastly, check that argument passing kinds transition in a
7392 // way that makes sense:
7393 // from a caller with FAPK_VAList, allow FAPK_VAList
7394 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7395 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7396 // from a caller with FAPK_Variadic, allow FAPK_VAList
7397 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
7402 return SLCT_UncheckedLiteral;
7403 }
7404 }
7405 }
7406 }
7407 }
7408 }
7409
7410 return SLCT_NotALiteral;
7411 }
7412
7413 case Stmt::CallExprClass:
7414 case Stmt::CXXMemberCallExprClass: {
7415 const CallExpr *CE = cast<CallExpr>(E);
7416 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7417 bool IsFirst = true;
7418 StringLiteralCheckType CommonResult;
7419 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7420 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7421 StringLiteralCheckType Result = checkFormatStringExpr(
7422 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7423 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7424 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7425 if (IsFirst) {
7426 CommonResult = Result;
7427 IsFirst = false;
7428 }
7429 }
7430 if (!IsFirst)
7431 return CommonResult;
7432
7433 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7434 unsigned BuiltinID = FD->getBuiltinID();
7435 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7436 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7437 const Expr *Arg = CE->getArg(0);
7438 return checkFormatStringExpr(
7439 S, ReferenceFormatString, Arg, Args, APK, format_idx,
7440 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7441 UncoveredArg, Offset, CallerFormatParamIdx,
7442 IgnoreStringsWithoutSpecifiers);
7443 }
7444 }
7445 }
7446 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
7447 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7448 format_idx, firstDataArg, Type, CallType,
7449 /*InFunctionCall*/ false, CheckedVarArgs,
7450 UncoveredArg, Offset, CallerFormatParamIdx,
7451 IgnoreStringsWithoutSpecifiers);
7452 return SLCT_NotALiteral;
7453 }
7454 case Stmt::ObjCMessageExprClass: {
7455 const auto *ME = cast<ObjCMessageExpr>(E);
7456 if (const auto *MD = ME->getMethodDecl()) {
7457 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7458 // As a special case heuristic, if we're using the method -[NSBundle
7459 // localizedStringForKey:value:table:], ignore any key strings that lack
7460 // format specifiers. The idea is that if the key doesn't have any
7461 // format specifiers then its probably just a key to map to the
7462 // localized strings. If it does have format specifiers though, then its
7463 // likely that the text of the key is the format string in the
7464 // programmer's language, and should be checked.
7465 const ObjCInterfaceDecl *IFace;
7466 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7467 IFace->getIdentifier()->isStr("NSBundle") &&
7468 MD->getSelector().isKeywordSelector(
7469 {"localizedStringForKey", "value", "table"})) {
7470 IgnoreStringsWithoutSpecifiers = true;
7471 }
7472
7473 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7474 return checkFormatStringExpr(
7475 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7476 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7477 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7478 }
7479 }
7480
7481 return SLCT_NotALiteral;
7482 }
7483 case Stmt::ObjCStringLiteralClass:
7484 case Stmt::StringLiteralClass: {
7485 const StringLiteral *StrE = nullptr;
7486
7487 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7488 StrE = ObjCFExpr->getString();
7489 else
7490 StrE = cast<StringLiteral>(E);
7491
7492 if (StrE) {
7493 if (Offset.isNegative() || Offset > StrE->getLength()) {
7494 // TODO: It would be better to have an explicit warning for out of
7495 // bounds literals.
7496 return SLCT_NotALiteral;
7497 }
7498 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7499 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
7500 format_idx, firstDataArg, Type, InFunctionCall,
7501 CallType, CheckedVarArgs, UncoveredArg,
7502 IgnoreStringsWithoutSpecifiers);
7503 return SLCT_CheckedLiteral;
7504 }
7505
7506 return SLCT_NotALiteral;
7507 }
7508 case Stmt::BinaryOperatorClass: {
7509 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7510
7511 // A string literal + an int offset is still a string literal.
7512 if (BinOp->isAdditiveOp()) {
7513 Expr::EvalResult LResult, RResult;
7514
7515 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7516 LResult, S.Context, Expr::SE_NoSideEffects,
7518 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7519 RResult, S.Context, Expr::SE_NoSideEffects,
7521
7522 if (LIsInt != RIsInt) {
7523 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7524
7525 if (LIsInt) {
7526 if (BinOpKind == BO_Add) {
7527 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7528 E = BinOp->getRHS();
7529 goto tryAgain;
7530 }
7531 } else {
7532 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7533 E = BinOp->getLHS();
7534 goto tryAgain;
7535 }
7536 }
7537 }
7538
7539 return SLCT_NotALiteral;
7540 }
7541 case Stmt::UnaryOperatorClass: {
7542 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7543 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7544 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7545 Expr::EvalResult IndexResult;
7546 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7549 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7550 /*RHS is int*/ true);
7551 E = ASE->getBase();
7552 goto tryAgain;
7553 }
7554 }
7555
7556 return SLCT_NotALiteral;
7557 }
7558
7559 default:
7560 return SLCT_NotALiteral;
7561 }
7562}
7563
7564// If this expression can be evaluated at compile-time,
7565// check if the result is a StringLiteral and return it
7566// otherwise return nullptr
7568 const Expr *E) {
7570 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
7571 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7572 if (isa_and_nonnull<StringLiteral>(LVE))
7573 return LVE;
7574 }
7575 return nullptr;
7576}
7577
7579 switch (FST) {
7581 return "scanf";
7583 return "printf";
7585 return "NSString";
7587 return "strftime";
7589 return "strfmon";
7591 return "kprintf";
7593 return "freebsd_kprintf";
7595 return "os_log";
7596 default:
7597 return "<unknown>";
7598 }
7599}
7600
7602 return llvm::StringSwitch<FormatStringType>(Flavor)
7603 .Cases({"gnu_scanf", "scanf"}, FormatStringType::Scanf)
7604 .Cases({"gnu_printf", "printf", "printf0", "syslog"},
7606 .Cases({"NSString", "CFString"}, FormatStringType::NSString)
7607 .Cases({"gnu_strftime", "strftime"}, FormatStringType::Strftime)
7608 .Cases({"gnu_strfmon", "strfmon"}, FormatStringType::Strfmon)
7609 .Cases({"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7611 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
7612 .Case("os_trace", FormatStringType::OSLog)
7613 .Case("os_log", FormatStringType::OSLog)
7614 .Default(FormatStringType::Unknown);
7615}
7616
7618 return GetFormatStringType(Format->getType()->getName());
7619}
7620
7621FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7622 return GetFormatStringType(Format->getType()->getName());
7623}
7624
7625bool Sema::CheckFormatArguments(const FormatAttr *Format,
7626 ArrayRef<const Expr *> Args, bool IsCXXMember,
7627 VariadicCallType CallType, SourceLocation Loc,
7628 SourceRange Range,
7629 llvm::SmallBitVector &CheckedVarArgs) {
7630 FormatStringInfo FSI;
7631 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
7632 IsCXXMember,
7633 CallType != VariadicCallType::DoesNotApply, &FSI))
7634 return CheckFormatArguments(
7635 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
7636 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
7637 return false;
7638}
7639
7640bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7641 ArrayRef<const Expr *> Args, bool IsCXXMember,
7642 VariadicCallType CallType, SourceLocation Loc,
7643 SourceRange Range,
7644 llvm::SmallBitVector &CheckedVarArgs) {
7645 FormatStringInfo FSI;
7646 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
7647 &FSI)) {
7648 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7649 return CheckFormatArguments(Args, FSI.ArgPassingKind,
7650 Format->getFormatString(), FSI.FormatIdx,
7651 FSI.FirstDataArg, GetFormatStringType(Format),
7652 CallType, Loc, Range, CheckedVarArgs);
7653 }
7654 return false;
7655}
7656
7659 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7660 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7661 SourceLocation Loc) {
7662 if (S->getDiagnostics().isIgnored(diag::warn_missing_format_attribute, Loc))
7663 return false;
7664
7665 DeclContext *DC = S->CurContext;
7666 if (!isa<ObjCMethodDecl>(DC) && !isa<FunctionDecl>(DC) && !isa<BlockDecl>(DC))
7667 return false;
7668 Decl *Caller = cast<Decl>(DC)->getCanonicalDecl();
7669
7670 unsigned NumCallerParams = getFunctionOrMethodNumParams(Caller);
7671
7672 // Find the offset to convert between attribute and parameter indexes.
7673 unsigned CallerArgumentIndexOffset =
7674 hasImplicitObjectParameter(Caller) ? 2 : 1;
7675
7676 unsigned FirstArgumentIndex = -1;
7677 switch (APK) {
7680 // As an extension, clang allows the format attribute on non-variadic
7681 // functions.
7682 // Caller must have fixed arguments to pass them to a fixed or variadic
7683 // function. Try to match caller and callee arguments. If successful, then
7684 // emit a diag with the caller idx, otherwise we can't determine the callee
7685 // arguments.
7686 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7687 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7688 // There aren't enough arguments in the caller to pass to callee.
7689 return false;
7690 }
7691 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7692 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7693 const auto *Arg =
7694 dyn_cast<DeclRefExpr>(Args[CalleeIdx]->IgnoreParenCasts());
7695 if (!Arg)
7696 return false;
7697 const auto *Param = dyn_cast<ParmVarDecl>(Arg->getDecl());
7698 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7699 return false;
7700 }
7701 FirstArgumentIndex =
7702 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7703 break;
7704 }
7706 // Caller arguments are either variadic or a va_list.
7707 FirstArgumentIndex = isFunctionOrMethodVariadic(Caller)
7708 ? (NumCallerParams + CallerArgumentIndexOffset)
7709 : 0;
7710 break;
7712 // The callee has a format_matches attribute. We will emit that instead.
7713 if (!ReferenceFormatString)
7714 return false;
7715 break;
7716 }
7717
7718 // Emit the diagnostic and fixit.
7719 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7720 StringRef FormatTypeName = S->GetFormatStringTypeName(FormatType);
7721 NamedDecl *ND = dyn_cast<NamedDecl>(Caller);
7722 do {
7723 std::string Attr, Fixit;
7724 llvm::raw_string_ostream AttrOS(Attr);
7726 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7727 << FirstArgumentIndex << ")";
7728 } else {
7729 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7730 << ", \"";
7731 AttrOS.write_escaped(ReferenceFormatString->getString());
7732 AttrOS << "\")";
7733 }
7734 AttrOS.flush();
7735 auto DB = S->Diag(Loc, diag::warn_missing_format_attribute) << Attr;
7736 if (ND)
7737 DB << ND;
7738 else
7739 DB << "block";
7740
7741 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7742 if (isa<BlockDecl>(Caller))
7743 break;
7744
7745 SourceLocation SL;
7746 llvm::raw_string_ostream IS(Fixit);
7747 // The attribute goes at the start of the declaration in C/C++ functions
7748 // and methods, but after the declaration for Objective-C methods.
7749 if (isa<ObjCMethodDecl>(Caller)) {
7750 IS << ' ';
7751 SL = Caller->getEndLoc();
7752 }
7753 const LangOptions &LO = S->getLangOpts();
7754 if (LO.C23 || LO.CPlusPlus11)
7755 IS << "[[gnu::" << Attr << "]]";
7756 else if (LO.ObjC || LO.GNUMode)
7757 IS << "__attribute__((" << Attr << "))";
7758 else
7759 break;
7760 if (!isa<ObjCMethodDecl>(Caller)) {
7761 IS << ' ';
7762 SL = Caller->getBeginLoc();
7763 }
7764 IS.flush();
7765
7766 DB << FixItHint::CreateInsertion(SL, Fixit);
7767 } while (false);
7768
7769 // Add implicit format or format_matches attribute.
7771 Caller->addAttr(FormatAttr::CreateImplicit(
7772 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7773 FormatStringIndex, FirstArgumentIndex));
7774 } else {
7775 Caller->addAttr(FormatMatchesAttr::CreateImplicit(
7776 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7777 FormatStringIndex, ReferenceFormatString));
7778 }
7779
7780 {
7781 auto DB = S->Diag(Caller->getLocation(), diag::note_entity_declared_at);
7782 if (ND)
7783 DB << ND;
7784 else
7785 DB << "block";
7786 }
7787 return true;
7788}
7789
7790bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7792 StringLiteral *ReferenceFormatString,
7793 unsigned format_idx, unsigned firstDataArg,
7795 VariadicCallType CallType, SourceLocation Loc,
7796 SourceRange Range,
7797 llvm::SmallBitVector &CheckedVarArgs) {
7798 // CHECK: printf/scanf-like function is called with no format string.
7799 if (format_idx >= Args.size()) {
7800 Diag(Loc, diag::warn_missing_format_string) << Range;
7801 return false;
7802 }
7803
7804 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7805
7806 // CHECK: format string is not a string literal.
7807 //
7808 // Dynamically generated format strings are difficult to
7809 // automatically vet at compile time. Requiring that format strings
7810 // are string literals: (1) permits the checking of format strings by
7811 // the compiler and thereby (2) can practically remove the source of
7812 // many format string exploits.
7813
7814 // Format string can be either ObjC string (e.g. @"%d") or
7815 // C string (e.g. "%d")
7816 // ObjC string uses the same format specifiers as C string, so we can use
7817 // the same format string checking logic for both ObjC and C strings.
7818 UncoveredArgHandler UncoveredArg;
7819 std::optional<unsigned> CallerParamIdx;
7820 StringLiteralCheckType CT = checkFormatStringExpr(
7821 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
7822 firstDataArg, Type, CallType,
7823 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
7824 /*no string offset*/ llvm::APSInt(64, false) = 0, &CallerParamIdx);
7825
7826 // Generate a diagnostic where an uncovered argument is detected.
7827 if (UncoveredArg.hasUncoveredArg()) {
7828 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7829 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7830 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7831 }
7832
7833 if (CT != SLCT_NotALiteral)
7834 // Literal format string found, check done!
7835 return CT == SLCT_CheckedLiteral;
7836
7837 // Do not emit diag when the string param is a macro expansion and the
7838 // format is either NSString or CFString. This is a hack to prevent
7839 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7840 // which are usually used in place of NS and CF string literals.
7841 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7843 SourceMgr.isInSystemMacro(FormatLoc))
7844 return false;
7845
7846 if (CallerParamIdx && CheckMissingFormatAttribute(
7847 this, Args, APK, ReferenceFormatString, format_idx,
7848 firstDataArg, Type, *CallerParamIdx, Loc))
7849 return false;
7850
7851 // Strftime is particular as it always uses a single 'time' argument,
7852 // so it is safe to pass a non-literal string.
7854 return false;
7855
7856 // If there are no arguments specified, warn with -Wformat-security, otherwise
7857 // warn only with -Wformat-nonliteral.
7858 if (Args.size() == firstDataArg) {
7859 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7860 << OrigFormatExpr->getSourceRange();
7861 switch (Type) {
7862 default:
7863 break;
7867 Diag(FormatLoc, diag::note_format_security_fixit)
7868 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7869 break;
7871 Diag(FormatLoc, diag::note_format_security_fixit)
7872 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7873 break;
7874 }
7875 } else {
7876 Diag(FormatLoc, diag::warn_format_nonliteral)
7877 << OrigFormatExpr->getSourceRange();
7878 }
7879 return false;
7880}
7881
7882namespace {
7883
7884class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7885protected:
7886 Sema &S;
7887 const FormatStringLiteral *FExpr;
7888 const Expr *OrigFormatExpr;
7889 const FormatStringType FSType;
7890 const unsigned FirstDataArg;
7891 const unsigned NumDataArgs;
7892 const char *Beg; // Start of format string.
7893 const Sema::FormatArgumentPassingKind ArgPassingKind;
7894 ArrayRef<const Expr *> Args;
7895 unsigned FormatIdx;
7896 llvm::SmallBitVector CoveredArgs;
7897 bool usesPositionalArgs = false;
7898 bool atFirstArg = true;
7899 bool inFunctionCall;
7900 VariadicCallType CallType;
7901 llvm::SmallBitVector &CheckedVarArgs;
7902 UncoveredArgHandler &UncoveredArg;
7903
7904public:
7905 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7906 const Expr *origFormatExpr, const FormatStringType type,
7907 unsigned firstDataArg, unsigned numDataArgs,
7908 const char *beg, Sema::FormatArgumentPassingKind APK,
7909 ArrayRef<const Expr *> Args, unsigned formatIdx,
7910 bool inFunctionCall, VariadicCallType callType,
7911 llvm::SmallBitVector &CheckedVarArgs,
7912 UncoveredArgHandler &UncoveredArg)
7913 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7914 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7915 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7916 inFunctionCall(inFunctionCall), CallType(callType),
7917 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7918 CoveredArgs.resize(numDataArgs);
7919 CoveredArgs.reset();
7920 }
7921
7922 bool HasFormatArguments() const {
7923 return ArgPassingKind == Sema::FAPK_Fixed ||
7924 ArgPassingKind == Sema::FAPK_Variadic;
7925 }
7926
7927 void DoneProcessing();
7928
7929 void HandleIncompleteSpecifier(const char *startSpecifier,
7930 unsigned specifierLen) override;
7931
7932 void HandleInvalidLengthModifier(
7933 const analyze_format_string::FormatSpecifier &FS,
7934 const analyze_format_string::ConversionSpecifier &CS,
7935 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
7936
7937 void HandleNonStandardLengthModifier(
7938 const analyze_format_string::FormatSpecifier &FS,
7939 const char *startSpecifier, unsigned specifierLen);
7940
7941 void HandleNonStandardConversionSpecifier(
7942 const analyze_format_string::ConversionSpecifier &CS,
7943 const char *startSpecifier, unsigned specifierLen);
7944
7945 void HandlePosition(const char *startPos, unsigned posLen) override;
7946
7947 void HandleInvalidPosition(const char *startSpecifier, unsigned specifierLen,
7949
7950 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7951
7952 void HandleNullChar(const char *nullCharacter) override;
7953
7954 template <typename Range>
7955 static void
7956 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7957 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7958 bool IsStringLocation, Range StringRange,
7959 ArrayRef<FixItHint> Fixit = {});
7960
7961protected:
7962 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7963 const char *startSpec,
7964 unsigned specifierLen,
7965 const char *csStart, unsigned csLen);
7966
7967 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7968 const char *startSpec,
7969 unsigned specifierLen);
7970
7971 SourceRange getFormatStringRange();
7972 CharSourceRange getSpecifierRange(const char *startSpecifier,
7973 unsigned specifierLen);
7974 SourceLocation getLocationOfByte(const char *x);
7975
7976 const Expr *getDataArg(unsigned i) const;
7977
7978 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7979 const analyze_format_string::ConversionSpecifier &CS,
7980 const char *startSpecifier, unsigned specifierLen,
7981 unsigned argIndex);
7982
7983 bool CheckUnsupportedType(const analyze_format_string::ArgType &AT,
7984 const Expr *E, const char *startSpecifier,
7985 unsigned specifierLen);
7986
7987 template <typename Range>
7988 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7989 bool IsStringLocation, Range StringRange,
7990 ArrayRef<FixItHint> Fixit = {});
7991};
7992
7993} // namespace
7994
7995SourceRange CheckFormatHandler::getFormatStringRange() {
7996 return OrigFormatExpr->getSourceRange();
7997}
7998
8000CheckFormatHandler::getSpecifierRange(const char *startSpecifier,
8001 unsigned specifierLen) {
8002 SourceLocation Start = getLocationOfByte(startSpecifier);
8003 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
8004
8005 // Advance the end SourceLocation by one due to half-open ranges.
8006 End = End.getLocWithOffset(1);
8007
8008 return CharSourceRange::getCharRange(Start, End);
8009}
8010
8011SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8012 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8014}
8015
8016void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8017 unsigned specifierLen) {
8018 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8019 getLocationOfByte(startSpecifier),
8020 /*IsStringLocation*/ true,
8021 getSpecifierRange(startSpecifier, specifierLen));
8022}
8023
8024bool CheckFormatHandler::CheckUnsupportedType(
8025 const analyze_format_string::ArgType &AT, const Expr *E,
8026 const char *StartSpecifier, unsigned SpecifierLen) {
8027 if (!AT.isUnsupported())
8028 return false;
8029
8030 EmitFormatDiagnostic(S.PDiag(diag::warn_format_unsupported_type)
8032 E->getExprLoc(), /*IsStringLocation=*/false,
8033 getSpecifierRange(StartSpecifier, SpecifierLen));
8034 return true;
8035}
8036
8037void CheckFormatHandler::HandleInvalidLengthModifier(
8040 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8041 using namespace analyze_format_string;
8042
8043 const LengthModifier &LM = FS.getLengthModifier();
8044 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8045
8046 // See if we know how to fix this length modifier.
8047 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8048 if (FixedLM) {
8049 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8050 getLocationOfByte(LM.getStart()),
8051 /*IsStringLocation*/ true,
8052 getSpecifierRange(startSpecifier, specifierLen));
8053
8054 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8055 << FixedLM->toString()
8056 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8057
8058 } else {
8059 FixItHint Hint;
8060 if (DiagID == diag::warn_format_nonsensical_length)
8061 Hint = FixItHint::CreateRemoval(LMRange);
8062
8063 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8064 getLocationOfByte(LM.getStart()),
8065 /*IsStringLocation*/ true,
8066 getSpecifierRange(startSpecifier, specifierLen), Hint);
8067 }
8068}
8069
8070void CheckFormatHandler::HandleNonStandardLengthModifier(
8072 const char *startSpecifier, unsigned specifierLen) {
8073 using namespace analyze_format_string;
8074
8075 const LengthModifier &LM = FS.getLengthModifier();
8076 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8077
8078 // See if we know how to fix this length modifier.
8079 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8080 if (FixedLM) {
8081 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8082 << LM.toString() << 0,
8083 getLocationOfByte(LM.getStart()),
8084 /*IsStringLocation*/ true,
8085 getSpecifierRange(startSpecifier, specifierLen));
8086
8087 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8088 << FixedLM->toString()
8089 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8090
8091 } else {
8092 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8093 << LM.toString() << 0,
8094 getLocationOfByte(LM.getStart()),
8095 /*IsStringLocation*/ true,
8096 getSpecifierRange(startSpecifier, specifierLen));
8097 }
8098}
8099
8100void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8102 const char *startSpecifier, unsigned specifierLen) {
8103 using namespace analyze_format_string;
8104
8105 // See if we know how to fix this conversion specifier.
8106 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8107 if (FixedCS) {
8108 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8109 << CS.toString() << /*conversion specifier*/ 1,
8110 getLocationOfByte(CS.getStart()),
8111 /*IsStringLocation*/ true,
8112 getSpecifierRange(startSpecifier, specifierLen));
8113
8114 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8115 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8116 << FixedCS->toString()
8117 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8118 } else {
8119 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8120 << CS.toString() << /*conversion specifier*/ 1,
8121 getLocationOfByte(CS.getStart()),
8122 /*IsStringLocation*/ true,
8123 getSpecifierRange(startSpecifier, specifierLen));
8124 }
8125}
8126
8127void CheckFormatHandler::HandlePosition(const char *startPos, unsigned posLen) {
8128 if (!S.getDiagnostics().isIgnored(
8129 diag::warn_format_non_standard_positional_arg, SourceLocation()))
8130 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8131 getLocationOfByte(startPos),
8132 /*IsStringLocation*/ true,
8133 getSpecifierRange(startPos, posLen));
8134}
8135
8136void CheckFormatHandler::HandleInvalidPosition(
8137 const char *startSpecifier, unsigned specifierLen,
8139 if (!S.getDiagnostics().isIgnored(
8140 diag::warn_format_invalid_positional_specifier, SourceLocation()))
8141 EmitFormatDiagnostic(
8142 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
8143 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
8144 getSpecifierRange(startSpecifier, specifierLen));
8145}
8146
8147void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8148 unsigned posLen) {
8149 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
8150 SourceLocation()))
8151 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8152 getLocationOfByte(startPos),
8153 /*IsStringLocation*/ true,
8154 getSpecifierRange(startPos, posLen));
8155}
8156
8157void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8158 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8159 // The presence of a null character is likely an error.
8160 EmitFormatDiagnostic(
8161 S.PDiag(diag::warn_printf_format_string_contains_null_char),
8162 getLocationOfByte(nullCharacter), /*IsStringLocation*/ true,
8163 getFormatStringRange());
8164 }
8165}
8166
8167// Note that this may return NULL if there was an error parsing or building
8168// one of the argument expressions.
8169const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8170 return Args[FirstDataArg + i];
8171}
8172
8173void CheckFormatHandler::DoneProcessing() {
8174 // Does the number of data arguments exceed the number of
8175 // format conversions in the format string?
8176 if (HasFormatArguments()) {
8177 // Find any arguments that weren't covered.
8178 CoveredArgs.flip();
8179 signed notCoveredArg = CoveredArgs.find_first();
8180 if (notCoveredArg >= 0) {
8181 assert((unsigned)notCoveredArg < NumDataArgs);
8182 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8183 } else {
8184 UncoveredArg.setAllCovered();
8185 }
8186 }
8187}
8188
8189void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8190 const Expr *ArgExpr) {
8191 assert(hasUncoveredArg() && !DiagnosticExprs.empty() && "Invalid state");
8192
8193 if (!ArgExpr)
8194 return;
8195
8196 SourceLocation Loc = ArgExpr->getBeginLoc();
8197
8198 if (S.getSourceManager().isInSystemMacro(Loc))
8199 return;
8200
8201 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8202 for (auto E : DiagnosticExprs)
8203 PDiag << E->getSourceRange();
8204
8205 CheckFormatHandler::EmitFormatDiagnostic(
8206 S, IsFunctionCall, DiagnosticExprs[0], PDiag, Loc,
8207 /*IsStringLocation*/ false, DiagnosticExprs[0]->getSourceRange());
8208}
8209
8210bool CheckFormatHandler::HandleInvalidConversionSpecifier(
8211 unsigned argIndex, SourceLocation Loc, const char *startSpec,
8212 unsigned specifierLen, const char *csStart, unsigned csLen) {
8213 bool keepGoing = true;
8214 if (argIndex < NumDataArgs) {
8215 // Consider the argument coverered, even though the specifier doesn't
8216 // make sense.
8217 CoveredArgs.set(argIndex);
8218 } else {
8219 // If argIndex exceeds the number of data arguments we
8220 // don't issue a warning because that is just a cascade of warnings (and
8221 // they may have intended '%%' anyway). We don't want to continue processing
8222 // the format string after this point, however, as we will like just get
8223 // gibberish when trying to match arguments.
8224 keepGoing = false;
8225 }
8226
8227 StringRef Specifier(csStart, csLen);
8228
8229 // If the specifier in non-printable, it could be the first byte of a UTF-8
8230 // sequence. In that case, print the UTF-8 code point. If not, print the byte
8231 // hex value.
8232 std::string CodePointStr;
8233 if (!llvm::sys::locale::isPrint(*csStart)) {
8234 llvm::UTF32 CodePoint;
8235 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8236 const llvm::UTF8 *E = reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8237 llvm::ConversionResult Result =
8238 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8239
8240 if (Result != llvm::conversionOK) {
8241 unsigned char FirstChar = *csStart;
8242 CodePoint = (llvm::UTF32)FirstChar;
8243 }
8244
8245 llvm::raw_string_ostream OS(CodePointStr);
8246 if (CodePoint < 256)
8247 OS << "\\x" << llvm::format("%02x", CodePoint);
8248 else if (CodePoint <= 0xFFFF)
8249 OS << "\\u" << llvm::format("%04x", CodePoint);
8250 else
8251 OS << "\\U" << llvm::format("%08x", CodePoint);
8252 Specifier = CodePointStr;
8253 }
8254
8255 EmitFormatDiagnostic(
8256 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8257 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8258
8259 return keepGoing;
8260}
8261
8262void CheckFormatHandler::HandlePositionalNonpositionalArgs(
8263 SourceLocation Loc, const char *startSpec, unsigned specifierLen) {
8264 EmitFormatDiagnostic(
8265 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), Loc,
8266 /*isStringLoc*/ true, getSpecifierRange(startSpec, specifierLen));
8267}
8268
8269bool CheckFormatHandler::CheckNumArgs(
8272 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8273
8274 if (HasFormatArguments() && argIndex >= NumDataArgs) {
8275 PartialDiagnostic PDiag =
8277 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8278 << (argIndex + 1) << NumDataArgs)
8279 : S.PDiag(diag::warn_printf_insufficient_data_args);
8280 EmitFormatDiagnostic(PDiag, getLocationOfByte(CS.getStart()),
8281 /*IsStringLocation*/ true,
8282 getSpecifierRange(startSpecifier, specifierLen));
8283
8284 // Since more arguments than conversion tokens are given, by extension
8285 // all arguments are covered, so mark this as so.
8286 UncoveredArg.setAllCovered();
8287 return false;
8288 }
8289 return true;
8290}
8291
8292template <typename Range>
8293void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8294 SourceLocation Loc,
8295 bool IsStringLocation,
8296 Range StringRange,
8297 ArrayRef<FixItHint> FixIt) {
8298 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, Loc,
8299 IsStringLocation, StringRange, FixIt);
8300}
8301
8302/// If the format string is not within the function call, emit a note
8303/// so that the function call and string are in diagnostic messages.
8304///
8305/// \param InFunctionCall if true, the format string is within the function
8306/// call and only one diagnostic message will be produced. Otherwise, an
8307/// extra note will be emitted pointing to location of the format string.
8308///
8309/// \param ArgumentExpr the expression that is passed as the format string
8310/// argument in the function call. Used for getting locations when two
8311/// diagnostics are emitted.
8312///
8313/// \param PDiag the callee should already have provided any strings for the
8314/// diagnostic message. This function only adds locations and fixits
8315/// to diagnostics.
8316///
8317/// \param Loc primary location for diagnostic. If two diagnostics are
8318/// required, one will be at Loc and a new SourceLocation will be created for
8319/// the other one.
8320///
8321/// \param IsStringLocation if true, Loc points to the format string should be
8322/// used for the note. Otherwise, Loc points to the argument list and will
8323/// be used with PDiag.
8324///
8325/// \param StringRange some or all of the string to highlight. This is
8326/// templated so it can accept either a CharSourceRange or a SourceRange.
8327///
8328/// \param FixIt optional fix it hint for the format string.
8329template <typename Range>
8330void CheckFormatHandler::EmitFormatDiagnostic(
8331 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8332 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8333 Range StringRange, ArrayRef<FixItHint> FixIt) {
8334 if (InFunctionCall) {
8335 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8336 D << StringRange;
8337 D << FixIt;
8338 } else {
8339 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8340 << ArgumentExpr->getSourceRange();
8341
8343 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8344 diag::note_format_string_defined);
8345
8346 Note << StringRange;
8347 Note << FixIt;
8348 }
8349}
8350
8351//===--- CHECK: Printf format string checking -----------------------------===//
8352
8353namespace {
8354
8355class CheckPrintfHandler : public CheckFormatHandler {
8356public:
8357 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8358 const Expr *origFormatExpr, const FormatStringType type,
8359 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8360 const char *beg, Sema::FormatArgumentPassingKind APK,
8361 ArrayRef<const Expr *> Args, unsigned formatIdx,
8362 bool inFunctionCall, VariadicCallType CallType,
8363 llvm::SmallBitVector &CheckedVarArgs,
8364 UncoveredArgHandler &UncoveredArg)
8365 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8366 numDataArgs, beg, APK, Args, formatIdx,
8367 inFunctionCall, CallType, CheckedVarArgs,
8368 UncoveredArg) {}
8369
8370 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8371
8372 /// Returns true if '%@' specifiers are allowed in the format string.
8373 bool allowsObjCArg() const {
8374 return FSType == FormatStringType::NSString ||
8375 FSType == FormatStringType::OSLog ||
8376 FSType == FormatStringType::OSTrace;
8377 }
8378
8379 bool HandleInvalidPrintfConversionSpecifier(
8380 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8381 unsigned specifierLen) override;
8382
8383 void handleInvalidMaskType(StringRef MaskType) override;
8384
8385 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8386 const char *startSpecifier, unsigned specifierLen,
8387 const TargetInfo &Target) override;
8388 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8389 const char *StartSpecifier, unsigned SpecifierLen,
8390 const Expr *E);
8391
8392 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt,
8393 unsigned k, const char *startSpecifier,
8394 unsigned specifierLen);
8395 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8396 const analyze_printf::OptionalAmount &Amt,
8397 unsigned type, const char *startSpecifier,
8398 unsigned specifierLen);
8399 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8400 const analyze_printf::OptionalFlag &flag,
8401 const char *startSpecifier, unsigned specifierLen);
8402 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8403 const analyze_printf::OptionalFlag &ignoredFlag,
8404 const analyze_printf::OptionalFlag &flag,
8405 const char *startSpecifier, unsigned specifierLen);
8406 bool checkForCStrMembers(const analyze_printf::ArgType &AT, const Expr *E);
8407
8408 void HandleEmptyObjCModifierFlag(const char *startFlag,
8409 unsigned flagLen) override;
8410
8411 void HandleInvalidObjCModifierFlag(const char *startFlag,
8412 unsigned flagLen) override;
8413
8414 void
8415 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8416 const char *flagsEnd,
8417 const char *conversionPosition) override;
8418};
8419
8420/// Keeps around the information needed to verify that two specifiers are
8421/// compatible.
8422class EquatableFormatArgument {
8423public:
8424 enum SpecifierSensitivity : unsigned {
8425 SS_None,
8426 SS_Private,
8427 SS_Public,
8428 SS_Sensitive
8429 };
8430
8431 enum FormatArgumentRole : unsigned {
8432 FAR_Data,
8433 FAR_FieldWidth,
8434 FAR_Precision,
8435 FAR_Auxiliary, // FreeBSD kernel %b and %D
8436 };
8437
8438private:
8439 analyze_format_string::ArgType ArgType;
8440 analyze_format_string::LengthModifier LengthMod;
8441 StringRef SpecifierLetter;
8442 CharSourceRange Range;
8443 SourceLocation ElementLoc;
8444 FormatArgumentRole Role : 2;
8445 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8446 unsigned Position : 14;
8447 unsigned ModifierFor : 14; // not set for FAR_Data
8448
8449 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8450 bool InFunctionCall) const;
8451
8452public:
8453 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8454 analyze_format_string::LengthModifier LengthMod,
8455 StringRef SpecifierLetter,
8456 analyze_format_string::ArgType ArgType,
8457 FormatArgumentRole Role,
8458 SpecifierSensitivity Sensitivity, unsigned Position,
8459 unsigned ModifierFor)
8460 : ArgType(ArgType), LengthMod(LengthMod),
8461 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8462 Role(Role), Sensitivity(Sensitivity), Position(Position),
8463 ModifierFor(ModifierFor) {}
8464
8465 unsigned getPosition() const { return Position; }
8466 SourceLocation getSourceLocation() const { return ElementLoc; }
8467 CharSourceRange getSourceRange() const { return Range; }
8468 analyze_format_string::LengthModifier getLengthModifier() const {
8469 return LengthMod;
8470 }
8471 void setModifierFor(unsigned V) { ModifierFor = V; }
8472
8473 std::string buildFormatSpecifier() const {
8474 std::string result;
8475 llvm::raw_string_ostream(result)
8476 << getLengthModifier().toString() << SpecifierLetter;
8477 return result;
8478 }
8479
8480 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8481 const Expr *FmtExpr, bool InFunctionCall) const;
8482};
8483
8484/// Turns format strings into lists of EquatableSpecifier objects.
8485class DecomposePrintfHandler : public CheckPrintfHandler {
8486 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8487 bool HadError;
8488
8489 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8490 const Expr *origFormatExpr,
8491 const FormatStringType type, unsigned firstDataArg,
8492 unsigned numDataArgs, bool isObjC, const char *beg,
8494 ArrayRef<const Expr *> Args, unsigned formatIdx,
8495 bool inFunctionCall, VariadicCallType CallType,
8496 llvm::SmallBitVector &CheckedVarArgs,
8497 UncoveredArgHandler &UncoveredArg,
8498 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8499 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8500 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8501 inFunctionCall, CallType, CheckedVarArgs,
8502 UncoveredArg),
8503 Specs(Specs), HadError(false) {}
8504
8505public:
8506 static bool
8507 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8508 FormatStringType type, bool IsObjC, bool InFunctionCall,
8509 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8510
8511 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8512 const char *startSpecifier,
8513 unsigned specifierLen,
8514 const TargetInfo &Target) override;
8515};
8516
8517} // namespace
8518
8519bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8520 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8521 unsigned specifierLen) {
8524
8525 return HandleInvalidConversionSpecifier(
8526 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
8527 specifierLen, CS.getStart(), CS.getLength());
8528}
8529
8530void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8531 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8532}
8533
8534// Error out if struct or complex type argments are passed to os_log.
8536 QualType T) {
8537 if (FSType != FormatStringType::OSLog)
8538 return false;
8539 return T->isRecordType() || T->isComplexType();
8540}
8541
8542bool CheckPrintfHandler::HandleAmount(
8543 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8544 const char *startSpecifier, unsigned specifierLen) {
8545 if (Amt.hasDataArgument()) {
8546 if (HasFormatArguments()) {
8547 unsigned argIndex = Amt.getArgIndex();
8548 if (argIndex >= NumDataArgs) {
8549 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8550 << k,
8551 getLocationOfByte(Amt.getStart()),
8552 /*IsStringLocation*/ true,
8553 getSpecifierRange(startSpecifier, specifierLen));
8554 // Don't do any more checking. We will just emit
8555 // spurious errors.
8556 return false;
8557 }
8558
8559 // Type check the data argument. It should be an 'int'.
8560 // Although not in conformance with C99, we also allow the argument to be
8561 // an 'unsigned int' as that is a reasonably safe case. GCC also
8562 // doesn't emit a warning for that case.
8563 CoveredArgs.set(argIndex);
8564 const Expr *Arg = getDataArg(argIndex);
8565 if (!Arg)
8566 return false;
8567
8568 QualType T = Arg->getType();
8569
8570 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8571 assert(AT.isValid());
8572
8573 if (!AT.matchesType(S.Context, T)) {
8574 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8575 ? diag::err_printf_asterisk_wrong_type
8576 : diag::warn_printf_asterisk_wrong_type;
8577 EmitFormatDiagnostic(S.PDiag(DiagID)
8579 << T << Arg->getSourceRange(),
8580 getLocationOfByte(Amt.getStart()),
8581 /*IsStringLocation*/ true,
8582 getSpecifierRange(startSpecifier, specifierLen));
8583 // Don't do any more checking. We will just emit
8584 // spurious errors.
8585 return false;
8586 }
8587 }
8588 }
8589 return true;
8590}
8591
8592void CheckPrintfHandler::HandleInvalidAmount(
8594 const analyze_printf::OptionalAmount &Amt, unsigned type,
8595 const char *startSpecifier, unsigned specifierLen) {
8598
8599 FixItHint fixit =
8602 getSpecifierRange(Amt.getStart(), Amt.getConstantLength()))
8603 : FixItHint();
8604
8605 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8606 << type << CS.toString(),
8607 getLocationOfByte(Amt.getStart()),
8608 /*IsStringLocation*/ true,
8609 getSpecifierRange(startSpecifier, specifierLen), fixit);
8610}
8611
8612void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8613 const analyze_printf::OptionalFlag &flag,
8614 const char *startSpecifier,
8615 unsigned specifierLen) {
8616 // Warn about pointless flag with a fixit removal.
8619 EmitFormatDiagnostic(
8620 S.PDiag(diag::warn_printf_nonsensical_flag)
8621 << flag.toString() << CS.toString(),
8622 getLocationOfByte(flag.getPosition()),
8623 /*IsStringLocation*/ true,
8624 getSpecifierRange(startSpecifier, specifierLen),
8625 FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1)));
8626}
8627
8628void CheckPrintfHandler::HandleIgnoredFlag(
8630 const analyze_printf::OptionalFlag &ignoredFlag,
8631 const analyze_printf::OptionalFlag &flag, const char *startSpecifier,
8632 unsigned specifierLen) {
8633 // Warn about ignored flag with a fixit removal.
8634 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8635 << ignoredFlag.toString() << flag.toString(),
8636 getLocationOfByte(ignoredFlag.getPosition()),
8637 /*IsStringLocation*/ true,
8638 getSpecifierRange(startSpecifier, specifierLen),
8640 getSpecifierRange(ignoredFlag.getPosition(), 1)));
8641}
8642
8643void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8644 unsigned flagLen) {
8645 // Warn about an empty flag.
8646 EmitFormatDiagnostic(
8647 S.PDiag(diag::warn_printf_empty_objc_flag), getLocationOfByte(startFlag),
8648 /*IsStringLocation*/ true, getSpecifierRange(startFlag, flagLen));
8649}
8650
8651void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8652 unsigned flagLen) {
8653 // Warn about an invalid flag.
8654 auto Range = getSpecifierRange(startFlag, flagLen);
8655 StringRef flag(startFlag, flagLen);
8656 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8657 getLocationOfByte(startFlag),
8658 /*IsStringLocation*/ true, Range,
8660}
8661
8662void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8663 const char *flagsStart, const char *flagsEnd,
8664 const char *conversionPosition) {
8665 // Warn about using '[...]' without a '@' conversion.
8666 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8667 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8668 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8669 getLocationOfByte(conversionPosition),
8670 /*IsStringLocation*/ true, Range,
8672}
8673
8674void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8675 const Expr *FmtExpr,
8676 bool InFunctionCall) const {
8677 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
8678 ElementLoc, true, Range);
8679}
8680
8681bool EquatableFormatArgument::VerifyCompatible(
8682 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8683 bool InFunctionCall) const {
8685 if (Role != Other.Role) {
8686 // diagnose and stop
8687 EmitDiagnostic(
8688 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8689 FmtExpr, InFunctionCall);
8690 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8691 return false;
8692 }
8693
8694 if (Role != FAR_Data) {
8695 if (ModifierFor != Other.ModifierFor) {
8696 // diagnose and stop
8697 EmitDiagnostic(S,
8698 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
8699 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8700 FmtExpr, InFunctionCall);
8701 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8702 return false;
8703 }
8704 return true;
8705 }
8706
8707 bool HadError = false;
8708 if (Sensitivity != Other.Sensitivity) {
8709 // diagnose and continue
8710 EmitDiagnostic(S,
8711 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
8712 << Sensitivity << Other.Sensitivity,
8713 FmtExpr, InFunctionCall);
8714 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8715 << 0 << Other.Range;
8716 }
8717
8718 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
8719 case MK::Match:
8720 break;
8721
8722 case MK::MatchPromotion:
8723 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8724 // MatchPromotion is treated as a failure by format_matches.
8725 case MK::NoMatch:
8726 case MK::NoMatchTypeConfusion:
8727 case MK::NoMatchPromotionTypeConfusion:
8728 EmitDiagnostic(S,
8729 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
8730 << buildFormatSpecifier()
8731 << Other.buildFormatSpecifier(),
8732 FmtExpr, InFunctionCall);
8733 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8734 << 0 << Other.Range;
8735 break;
8736
8737 case MK::NoMatchPedantic:
8738 EmitDiagnostic(S,
8739 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
8740 << buildFormatSpecifier()
8741 << Other.buildFormatSpecifier(),
8742 FmtExpr, InFunctionCall);
8743 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8744 << 0 << Other.Range;
8745 break;
8746
8747 case MK::NoMatchSignedness:
8748 EmitDiagnostic(S,
8749 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
8750 << buildFormatSpecifier()
8751 << Other.buildFormatSpecifier(),
8752 FmtExpr, InFunctionCall);
8753 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8754 << 0 << Other.Range;
8755 break;
8756 }
8757 return !HadError;
8758}
8759
8760bool DecomposePrintfHandler::GetSpecifiers(
8761 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8762 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8764 StringRef Data = FSL->getString();
8765 const char *Str = Data.data();
8766 llvm::SmallBitVector BV;
8767 UncoveredArgHandler UA;
8768 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8769 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8770 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8771 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8772 UA, Args);
8773
8775 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
8777 H.DoneProcessing();
8778 if (H.HadError)
8779 return false;
8780
8781 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
8782 const EquatableFormatArgument &B) {
8783 return A.getPosition() < B.getPosition();
8784 });
8785 return true;
8786}
8787
8788bool DecomposePrintfHandler::HandlePrintfSpecifier(
8789 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8790 unsigned specifierLen, const TargetInfo &Target) {
8791 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8792 specifierLen, Target)) {
8793 HadError = true;
8794 return false;
8795 }
8796
8797 // Do not add any specifiers to the list for %%. This is possibly incorrect
8798 // if using a precision/width with a data argument, but that combination is
8799 // meaningless and we wouldn't know which format to attach the
8800 // precision/width to.
8801 const auto &CS = FS.getConversionSpecifier();
8803 return true;
8804
8805 // have to patch these to have the right ModifierFor if they are used
8806 const unsigned Unset = ~0;
8807 unsigned FieldWidthIndex = Unset;
8808 unsigned PrecisionIndex = Unset;
8809
8810 // field width?
8811 const auto &FieldWidth = FS.getFieldWidth();
8812 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8813 FieldWidthIndex = Specs.size();
8814 Specs.emplace_back(
8815 getSpecifierRange(startSpecifier, specifierLen),
8816 getLocationOfByte(FieldWidth.getStart()),
8817 analyze_format_string::LengthModifier(), FieldWidth.getCharacters(),
8818 FieldWidth.getArgType(S.Context),
8819 EquatableFormatArgument::FAR_FieldWidth,
8820 EquatableFormatArgument::SS_None,
8821 FieldWidth.usesPositionalArg() ? FieldWidth.getPositionalArgIndex() - 1
8822 : FieldWidthIndex,
8823 0);
8824 }
8825 // precision?
8826 const auto &Precision = FS.getPrecision();
8827 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8828 PrecisionIndex = Specs.size();
8829 Specs.emplace_back(
8830 getSpecifierRange(startSpecifier, specifierLen),
8831 getLocationOfByte(Precision.getStart()),
8832 analyze_format_string::LengthModifier(), Precision.getCharacters(),
8833 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
8834 EquatableFormatArgument::SS_None,
8835 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8836 : PrecisionIndex,
8837 0);
8838 }
8839
8840 // this specifier
8841 unsigned SpecIndex =
8842 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8843 if (FieldWidthIndex != Unset)
8844 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8845 if (PrecisionIndex != Unset)
8846 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8847
8848 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8849 if (FS.isPrivate())
8850 Sensitivity = EquatableFormatArgument::SS_Private;
8851 else if (FS.isPublic())
8852 Sensitivity = EquatableFormatArgument::SS_Public;
8853 else if (FS.isSensitive())
8854 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8855 else
8856 Sensitivity = EquatableFormatArgument::SS_None;
8857
8858 Specs.emplace_back(
8859 getSpecifierRange(startSpecifier, specifierLen),
8860 getLocationOfByte(CS.getStart()), FS.getLengthModifier(),
8861 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
8862 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
8863
8864 // auxiliary argument?
8867 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8868 getLocationOfByte(CS.getStart()),
8870 CS.getCharacters(),
8872 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
8873 SpecIndex + 1, SpecIndex);
8874 }
8875 return true;
8876}
8877
8878// Determines if the specified is a C++ class or struct containing
8879// a member with the specified name and kind (e.g. a CXXMethodDecl named
8880// "c_str()").
8881template<typename MemberKind>
8883CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8884 auto *RD = Ty->getAsCXXRecordDecl();
8886
8887 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8888 return Results;
8889
8890 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8892 R.suppressDiagnostics();
8893
8894 // We just need to include all members of the right kind turned up by the
8895 // filter, at this point.
8896 if (S.LookupQualifiedName(R, RD))
8897 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8898 NamedDecl *decl = (*I)->getUnderlyingDecl();
8899 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8900 Results.insert(FK);
8901 }
8902 return Results;
8903}
8904
8905/// Check if we could call '.c_str()' on an object.
8906///
8907/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8908/// allow the call, or if it would be ambiguous).
8910 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8911
8912 MethodSet Results =
8913 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8914 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8915 MI != ME; ++MI)
8916 if ((*MI)->getMinRequiredArguments() == 0)
8917 return true;
8918 return false;
8919}
8920
8921// Check if a (w)string was passed when a (w)char* was needed, and offer a
8922// better diagnostic if so. AT is assumed to be valid.
8923// Returns true when a c_str() conversion method is found.
8924bool CheckPrintfHandler::checkForCStrMembers(
8925 const analyze_printf::ArgType &AT, const Expr *E) {
8926 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8927
8928 MethodSet Results =
8930
8931 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8932 MI != ME; ++MI) {
8933 const CXXMethodDecl *Method = *MI;
8934 if (Method->getMinRequiredArguments() == 0 &&
8935 AT.matchesType(S.Context, Method->getReturnType())) {
8936 // FIXME: Suggest parens if the expression needs them.
8938 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8939 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8940 return true;
8941 }
8942 }
8943
8944 return false;
8945}
8946
8947bool CheckPrintfHandler::HandlePrintfSpecifier(
8948 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8949 unsigned specifierLen, const TargetInfo &Target) {
8950 using namespace analyze_format_string;
8951 using namespace analyze_printf;
8952
8953 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8954
8955 if (FS.consumesDataArgument()) {
8956 if (atFirstArg) {
8957 atFirstArg = false;
8958 usesPositionalArgs = FS.usesPositionalArg();
8959 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
8960 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8961 startSpecifier, specifierLen);
8962 return false;
8963 }
8964 }
8965
8966 // First check if the field width, precision, and conversion specifier
8967 // have matching data arguments.
8968 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, startSpecifier,
8969 specifierLen)) {
8970 return false;
8971 }
8972
8973 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, startSpecifier,
8974 specifierLen)) {
8975 return false;
8976 }
8977
8978 if (!CS.consumesDataArgument()) {
8979 // FIXME: Technically specifying a precision or field width here
8980 // makes no sense. Worth issuing a warning at some point.
8981 return true;
8982 }
8983
8984 // Consume the argument.
8985 unsigned argIndex = FS.getArgIndex();
8986 if (argIndex < NumDataArgs) {
8987 // The check to see if the argIndex is valid will come later.
8988 // We set the bit here because we may exit early from this
8989 // function if we encounter some other error.
8990 CoveredArgs.set(argIndex);
8991 }
8992
8993 // FreeBSD kernel extensions.
8994 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8995 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8996 // We need at least two arguments.
8997 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8998 return false;
8999
9000 if (HasFormatArguments()) {
9001 // Claim the second argument.
9002 CoveredArgs.set(argIndex + 1);
9003
9004 // Type check the first argument (int for %b, pointer for %D)
9005 const Expr *Ex = getDataArg(argIndex);
9006 const analyze_printf::ArgType &AT =
9007 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
9008 ? ArgType(S.Context.IntTy)
9009 : ArgType::CPointerTy;
9010 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9011 EmitFormatDiagnostic(
9012 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9013 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9014 << false << Ex->getSourceRange(),
9015 Ex->getBeginLoc(), /*IsStringLocation*/ false,
9016 getSpecifierRange(startSpecifier, specifierLen));
9017
9018 // Type check the second argument (char * for both %b and %D)
9019 Ex = getDataArg(argIndex + 1);
9021 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9022 EmitFormatDiagnostic(
9023 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9024 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9025 << false << Ex->getSourceRange(),
9026 Ex->getBeginLoc(), /*IsStringLocation*/ false,
9027 getSpecifierRange(startSpecifier, specifierLen));
9028 }
9029 return true;
9030 }
9031
9032 // Check for using an Objective-C specific conversion specifier
9033 // in a non-ObjC literal.
9034 if (!allowsObjCArg() && CS.isObjCArg()) {
9035 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9036 specifierLen);
9037 }
9038
9039 // %P can only be used with os_log.
9040 if (FSType != FormatStringType::OSLog &&
9041 CS.getKind() == ConversionSpecifier::PArg) {
9042 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9043 specifierLen);
9044 }
9045
9046 // %n is not allowed with os_log.
9047 if (FSType == FormatStringType::OSLog &&
9048 CS.getKind() == ConversionSpecifier::nArg) {
9049 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9050 getLocationOfByte(CS.getStart()),
9051 /*IsStringLocation*/ false,
9052 getSpecifierRange(startSpecifier, specifierLen));
9053
9054 return true;
9055 }
9056
9057 // Only scalars are allowed for os_trace.
9058 if (FSType == FormatStringType::OSTrace &&
9059 (CS.getKind() == ConversionSpecifier::PArg ||
9060 CS.getKind() == ConversionSpecifier::sArg ||
9061 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9062 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9063 specifierLen);
9064 }
9065
9066 // Check for use of public/private annotation outside of os_log().
9067 if (FSType != FormatStringType::OSLog) {
9068 if (FS.isPublic().isSet()) {
9069 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9070 << "public",
9071 getLocationOfByte(FS.isPublic().getPosition()),
9072 /*IsStringLocation*/ false,
9073 getSpecifierRange(startSpecifier, specifierLen));
9074 }
9075 if (FS.isPrivate().isSet()) {
9076 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9077 << "private",
9078 getLocationOfByte(FS.isPrivate().getPosition()),
9079 /*IsStringLocation*/ false,
9080 getSpecifierRange(startSpecifier, specifierLen));
9081 }
9082 }
9083
9084 const llvm::Triple &Triple = Target.getTriple();
9085 if (CS.getKind() == ConversionSpecifier::nArg &&
9086 (Triple.isAndroid() || Triple.isOSFuchsia())) {
9087 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9088 getLocationOfByte(CS.getStart()),
9089 /*IsStringLocation*/ false,
9090 getSpecifierRange(startSpecifier, specifierLen));
9091 }
9092
9093 // Check for invalid use of field width
9094 if (!FS.hasValidFieldWidth()) {
9095 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9096 startSpecifier, specifierLen);
9097 }
9098
9099 // Check for invalid use of precision
9100 if (!FS.hasValidPrecision()) {
9101 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9102 startSpecifier, specifierLen);
9103 }
9104
9105 // Precision is mandatory for %P specifier.
9106 if (CS.getKind() == ConversionSpecifier::PArg &&
9108 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9109 getLocationOfByte(startSpecifier),
9110 /*IsStringLocation*/ false,
9111 getSpecifierRange(startSpecifier, specifierLen));
9112 }
9113
9114 // Check each flag does not conflict with any other component.
9116 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9117 if (!FS.hasValidLeadingZeros())
9118 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9119 if (!FS.hasValidPlusPrefix())
9120 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9121 if (!FS.hasValidSpacePrefix())
9122 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9123 if (!FS.hasValidAlternativeForm())
9124 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9125 if (!FS.hasValidLeftJustified())
9126 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9127
9128 // Check that flags are not ignored by another flag
9129 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9130 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9131 startSpecifier, specifierLen);
9132 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9133 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9134 startSpecifier, specifierLen);
9135
9136 // Check the length modifier is valid with the given conversion specifier.
9138 S.getLangOpts()))
9139 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9140 diag::warn_format_nonsensical_length);
9141 else if (!FS.hasStandardLengthModifier())
9142 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9144 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9145 diag::warn_format_non_standard_conversion_spec);
9146
9148 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9149
9150 // The remaining checks depend on the data arguments.
9151 if (!HasFormatArguments())
9152 return true;
9153
9154 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9155 return false;
9156
9157 const Expr *Arg = getDataArg(argIndex);
9158 if (!Arg)
9159 return true;
9160
9161 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9162}
9163
9164static bool requiresParensToAddCast(const Expr *E) {
9165 // FIXME: We should have a general way to reason about operator
9166 // precedence and whether parens are actually needed here.
9167 // Take care of a few common cases where they aren't.
9168 const Expr *Inside = E->IgnoreImpCasts();
9169 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9170 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9171
9172 switch (Inside->getStmtClass()) {
9173 case Stmt::ArraySubscriptExprClass:
9174 case Stmt::CallExprClass:
9175 case Stmt::CharacterLiteralClass:
9176 case Stmt::CXXBoolLiteralExprClass:
9177 case Stmt::DeclRefExprClass:
9178 case Stmt::FloatingLiteralClass:
9179 case Stmt::IntegerLiteralClass:
9180 case Stmt::MemberExprClass:
9181 case Stmt::ObjCArrayLiteralClass:
9182 case Stmt::ObjCBoolLiteralExprClass:
9183 case Stmt::ObjCBoxedExprClass:
9184 case Stmt::ObjCDictionaryLiteralClass:
9185 case Stmt::ObjCEncodeExprClass:
9186 case Stmt::ObjCIvarRefExprClass:
9187 case Stmt::ObjCMessageExprClass:
9188 case Stmt::ObjCPropertyRefExprClass:
9189 case Stmt::ObjCStringLiteralClass:
9190 case Stmt::ObjCSubscriptRefExprClass:
9191 case Stmt::ParenExprClass:
9192 case Stmt::StringLiteralClass:
9193 case Stmt::UnaryOperatorClass:
9194 return false;
9195 default:
9196 return true;
9197 }
9198}
9199
9200static std::pair<QualType, StringRef>
9201shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy,
9202 const Expr *E) {
9203 // Use a 'while' to peel off layers of typedefs.
9204 QualType TyTy = IntendedTy;
9205 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9206 StringRef Name = UserTy->getDecl()->getName();
9207 QualType CastTy = llvm::StringSwitch<QualType>(Name)
9208 .Case("CFIndex", Context.getNSIntegerType())
9209 .Case("NSInteger", Context.getNSIntegerType())
9210 .Case("NSUInteger", Context.getNSUIntegerType())
9211 .Case("SInt32", Context.IntTy)
9212 .Case("UInt32", Context.UnsignedIntTy)
9213 .Default(QualType());
9214
9215 if (!CastTy.isNull())
9216 return std::make_pair(CastTy, Name);
9217
9218 TyTy = UserTy->desugar();
9219 }
9220
9221 // Strip parens if necessary.
9222 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9223 return shouldNotPrintDirectly(Context, PE->getSubExpr()->getType(),
9224 PE->getSubExpr());
9225
9226 // If this is a conditional expression, then its result type is constructed
9227 // via usual arithmetic conversions and thus there might be no necessary
9228 // typedef sugar there. Recurse to operands to check for NSInteger &
9229 // Co. usage condition.
9230 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9231 QualType TrueTy, FalseTy;
9232 StringRef TrueName, FalseName;
9233
9234 std::tie(TrueTy, TrueName) = shouldNotPrintDirectly(
9235 Context, CO->getTrueExpr()->getType(), CO->getTrueExpr());
9236 std::tie(FalseTy, FalseName) = shouldNotPrintDirectly(
9237 Context, CO->getFalseExpr()->getType(), CO->getFalseExpr());
9238
9239 if (TrueTy == FalseTy)
9240 return std::make_pair(TrueTy, TrueName);
9241 else if (TrueTy.isNull())
9242 return std::make_pair(FalseTy, FalseName);
9243 else if (FalseTy.isNull())
9244 return std::make_pair(TrueTy, TrueName);
9245 }
9246
9247 return std::make_pair(QualType(), StringRef());
9248}
9249
9250/// Return true if \p ICE is an implicit argument promotion of an arithmetic
9251/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9252/// type do not count.
9254 const ImplicitCastExpr *ICE) {
9255 QualType From = ICE->getSubExpr()->getType();
9256 QualType To = ICE->getType();
9257 // It's an integer promotion if the destination type is the promoted
9258 // source type.
9259 if (ICE->getCastKind() == CK_IntegralCast &&
9261 S.Context.getPromotedIntegerType(From) == To)
9262 return true;
9263 // Look through vector types, since we do default argument promotion for
9264 // those in OpenCL.
9265 if (const auto *VecTy = From->getAs<ExtVectorType>())
9266 From = VecTy->getElementType();
9267 if (const auto *VecTy = To->getAs<ExtVectorType>())
9268 To = VecTy->getElementType();
9269 // It's a floating promotion if the source type is a lower rank.
9270 return ICE->getCastKind() == CK_FloatingCast &&
9271 S.Context.getFloatingTypeOrder(From, To) < 0;
9272}
9273
9276 DiagnosticsEngine &Diags, SourceLocation Loc) {
9278 if (Diags.isIgnored(
9279 diag::warn_format_conversion_argument_type_mismatch_signedness,
9280 Loc) ||
9281 Diags.isIgnored(
9282 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9283 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9285 }
9286 }
9287 return Match;
9288}
9289
9290bool CheckPrintfHandler::checkFormatExpr(
9291 const analyze_printf::PrintfSpecifier &FS, const char *StartSpecifier,
9292 unsigned SpecifierLen, const Expr *E) {
9293 using namespace analyze_format_string;
9294 using namespace analyze_printf;
9295
9296 // Now type check the data expression that matches the
9297 // format specifier.
9298 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9299 if (!AT.isValid())
9300 return true;
9301
9302 QualType ExprTy = E->getType();
9303 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9304 ExprTy = TET->getUnderlyingExpr()->getType();
9305 }
9306
9307 if (const OverflowBehaviorType *OBT =
9308 dyn_cast<OverflowBehaviorType>(ExprTy.getCanonicalType()))
9309 ExprTy = OBT->getUnderlyingType();
9310
9311 // When using the format attribute in C++, you can receive a function or an
9312 // array that will necessarily decay to a pointer when passed to the final
9313 // format consumer. Apply decay before type comparison.
9314 if (ExprTy->canDecayToPointerType())
9315 ExprTy = S.Context.getDecayedType(ExprTy);
9316
9317 // Diagnose attempts to print a boolean value as a character. Unlike other
9318 // -Wformat diagnostics, this is fine from a type perspective, but it still
9319 // doesn't make sense.
9322 const CharSourceRange &CSR =
9323 getSpecifierRange(StartSpecifier, SpecifierLen);
9324 SmallString<4> FSString;
9325 llvm::raw_svector_ostream os(FSString);
9326 FS.toString(os);
9327 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9328 << FSString,
9329 E->getExprLoc(), false, CSR);
9330 return true;
9331 }
9332
9333 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9334 // dumping raw class data (like is-a pointer), not actual data.
9336 ExprTy->isObjCObjectPointerType()) {
9337 const CharSourceRange &CSR =
9338 getSpecifierRange(StartSpecifier, SpecifierLen);
9339 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
9340 E->getExprLoc(), false, CSR);
9341 return true;
9342 }
9343
9344 if (CheckUnsupportedType(AT, E, StartSpecifier, SpecifierLen))
9345 return true;
9346
9347 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9349 ArgType::MatchKind OrigMatch = Match;
9350
9352 if (Match == ArgType::Match)
9353 return true;
9354
9355 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9356 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9357
9358 // Look through argument promotions for our error message's reported type.
9359 // This includes the integral and floating promotions, but excludes array
9360 // and function pointer decay (seeing that an argument intended to be a
9361 // string has type 'char [6]' is probably more confusing than 'char *') and
9362 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9363 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9364 if (isArithmeticArgumentPromotion(S, ICE)) {
9365 E = ICE->getSubExpr();
9366 ExprTy = E->getType();
9367
9368 // Check if we didn't match because of an implicit cast from a 'char'
9369 // or 'short' to an 'int'. This is done because printf is a varargs
9370 // function.
9371 if (ICE->getType() == S.Context.IntTy ||
9372 ICE->getType() == S.Context.UnsignedIntTy) {
9373 // All further checking is done on the subexpression
9374 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
9375 if (OrigMatch == ArgType::NoMatchSignedness &&
9376 ImplicitMatch != ArgType::NoMatchSignedness)
9377 // If the original match was a signedness match this match on the
9378 // implicit cast type also need to be signedness match otherwise we
9379 // might introduce new unexpected warnings from -Wformat-signedness.
9380 return true;
9381 ImplicitMatch = handleFormatSignedness(
9382 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
9383 if (ImplicitMatch == ArgType::Match)
9384 return true;
9385 }
9386 }
9387 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9388 // Special case for 'a', which has type 'int' in C.
9389 // Note, however, that we do /not/ want to treat multibyte constants like
9390 // 'MooV' as characters! This form is deprecated but still exists. In
9391 // addition, don't treat expressions as of type 'char' if one byte length
9392 // modifier is provided.
9393 if (ExprTy == S.Context.IntTy &&
9395 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
9396 ExprTy = S.Context.CharTy;
9397 // To improve check results, we consider a character literal in C
9398 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9399 // more likely a type confusion situation, so we will suggest to
9400 // use '%hhd' instead by discarding the MatchPromotion.
9401 if (Match == ArgType::MatchPromotion)
9403 }
9404 }
9405 if (Match == ArgType::MatchPromotion) {
9406 // WG14 N2562 only clarified promotions in *printf
9407 // For NSLog in ObjC, just preserve -Wformat behavior
9408 if (!S.getLangOpts().ObjC &&
9409 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9410 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9411 return true;
9413 }
9414 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9415 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9416 Match = ImplicitMatch;
9417 assert(Match != ArgType::MatchPromotion);
9418
9419 // Look through unscoped enums to their underlying type.
9420 bool IsEnum = false;
9421 bool IsScopedEnum = false;
9422 QualType IntendedTy = ExprTy;
9423 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9424 IntendedTy = ED->getIntegerType();
9425 if (!ED->isScoped()) {
9426 ExprTy = IntendedTy;
9427 // This controls whether we're talking about the underlying type or not,
9428 // which we only want to do when it's an unscoped enum.
9429 IsEnum = true;
9430 } else {
9431 IsScopedEnum = true;
9432 }
9433 }
9434
9435 // %C in an Objective-C context prints a unichar, not a wchar_t.
9436 // If the argument is an integer of some kind, believe the %C and suggest
9437 // a cast instead of changing the conversion specifier.
9438 if (isObjCContext() &&
9441 !ExprTy->isCharType()) {
9442 // 'unichar' is defined as a typedef of unsigned short, but we should
9443 // prefer using the typedef if it is visible.
9444 IntendedTy = S.Context.UnsignedShortTy;
9445
9446 // While we are here, check if the value is an IntegerLiteral that happens
9447 // to be within the valid range.
9448 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9449 const llvm::APInt &V = IL->getValue();
9450 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9451 return true;
9452 }
9453
9454 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9456 if (S.LookupName(Result, S.getCurScope())) {
9457 NamedDecl *ND = Result.getFoundDecl();
9458 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9459 if (TD->getUnderlyingType() == IntendedTy)
9460 IntendedTy =
9462 /*Qualifier=*/std::nullopt, TD);
9463 }
9464 }
9465 }
9466
9467 // Special-case some of Darwin's platform-independence types by suggesting
9468 // casts to primitive types that are known to be large enough.
9469 bool ShouldNotPrintDirectly = false;
9470 StringRef CastTyName;
9471 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9472 QualType CastTy;
9473 std::tie(CastTy, CastTyName) =
9474 shouldNotPrintDirectly(S.Context, IntendedTy, E);
9475 if (!CastTy.isNull()) {
9476 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9477 // (long in ASTContext). Only complain to pedants or when they're the
9478 // underlying type of a scoped enum (which always needs a cast).
9479 if (!IsScopedEnum &&
9480 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9481 (AT.isSizeT() || AT.isPtrdiffT()) &&
9482 AT.matchesType(S.Context, CastTy))
9484 IntendedTy = CastTy;
9485 ShouldNotPrintDirectly = true;
9486 }
9487 }
9488
9489 // We may be able to offer a FixItHint if it is a supported type.
9490 PrintfSpecifier fixedFS = FS;
9491 bool Success =
9492 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9493
9494 if (Success) {
9495 // Get the fix string from the fixed format specifier
9496 SmallString<16> buf;
9497 llvm::raw_svector_ostream os(buf);
9498 fixedFS.toString(os);
9499
9500 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9501
9502 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9503 unsigned Diag;
9504 switch (Match) {
9505 case ArgType::Match:
9508 llvm_unreachable("expected non-matching");
9510 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9511 break;
9513 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9514 break;
9516 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9517 break;
9518 case ArgType::NoMatch:
9519 Diag = diag::warn_format_conversion_argument_type_mismatch;
9520 break;
9521 }
9522
9523 // In this case, the specifier is wrong and should be changed to match
9524 // the argument.
9525 EmitFormatDiagnostic(S.PDiag(Diag)
9527 << IntendedTy << IsEnum << E->getSourceRange(),
9528 E->getBeginLoc(),
9529 /*IsStringLocation*/ false, SpecRange,
9530 FixItHint::CreateReplacement(SpecRange, os.str()));
9531 } else {
9532 // The canonical type for formatting this value is different from the
9533 // actual type of the expression. (This occurs, for example, with Darwin's
9534 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9535 // should be printed as 'long' for 64-bit compatibility.)
9536 // Rather than emitting a normal format/argument mismatch, we want to
9537 // add a cast to the recommended type (and correct the format string
9538 // if necessary). We should also do so for scoped enumerations.
9539 SmallString<16> CastBuf;
9540 llvm::raw_svector_ostream CastFix(CastBuf);
9541 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9542 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9543 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9544
9546 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
9547 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
9548 E->getExprLoc());
9549 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9550 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9551
9552 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9553 // If there's already a cast present, just replace it.
9554 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9555 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9556
9557 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9558 // If the expression has high enough precedence,
9559 // just write the C-style cast.
9560 Hints.push_back(
9561 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9562 } else {
9563 // Otherwise, add parens around the expression as well as the cast.
9564 CastFix << "(";
9565 Hints.push_back(
9566 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9567
9568 // We don't use getLocForEndOfToken because it returns invalid source
9569 // locations for macro expansions (by design).
9573 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9574 }
9575
9576 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9577 // The expression has a type that should not be printed directly.
9578 // We extract the name from the typedef because we don't want to show
9579 // the underlying type in the diagnostic.
9580 StringRef Name;
9581 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9582 Name = TypedefTy->getDecl()->getName();
9583 else
9584 Name = CastTyName;
9585 unsigned Diag = Match == ArgType::NoMatchPedantic
9586 ? diag::warn_format_argument_needs_cast_pedantic
9587 : diag::warn_format_argument_needs_cast;
9588 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9589 << E->getSourceRange(),
9590 E->getBeginLoc(), /*IsStringLocation=*/false,
9591 SpecRange, Hints);
9592 } else {
9593 // In this case, the expression could be printed using a different
9594 // specifier, but we've decided that the specifier is probably correct
9595 // and we should cast instead. Just use the normal warning message.
9596
9597 unsigned Diag =
9598 IsScopedEnum
9599 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9600 : diag::warn_format_conversion_argument_type_mismatch;
9601
9602 EmitFormatDiagnostic(
9603 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9604 << IsEnum << E->getSourceRange(),
9605 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9606 }
9607 }
9608 } else {
9609 const CharSourceRange &CSR =
9610 getSpecifierRange(StartSpecifier, SpecifierLen);
9611 // Since the warning for passing non-POD types to variadic functions
9612 // was deferred until now, we emit a warning for non-POD
9613 // arguments here.
9614 bool EmitTypeMismatch = false;
9615 // Record and complex type arguments cannot be code generated for os_log
9616 // and would crash CodeGen, so they are rejected with a hard error emitted
9617 // after the switch below.
9618 bool EmitOSLogError = false;
9619 switch (S.isValidVarArgType(ExprTy)) {
9620 case VarArgKind::Valid:
9622 unsigned Diag;
9623 switch (Match) {
9624 case ArgType::Match:
9627 llvm_unreachable("expected non-matching");
9629 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9630 break;
9632 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9633 break;
9635 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9636 break;
9637 case ArgType::NoMatch:
9638 EmitOSLogError = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy);
9639 Diag = diag::warn_format_conversion_argument_type_mismatch;
9640 break;
9641 }
9642
9643 if (!EmitOSLogError)
9644 EmitFormatDiagnostic(
9645 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9646 << IsEnum << CSR << E->getSourceRange(),
9647 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9648 break;
9649 }
9652 if (CallType == VariadicCallType::DoesNotApply) {
9653 EmitTypeMismatch = true;
9654 } else if (isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)) {
9655 // Emit a hard error rather than the -Wnon-pod-varargs warning, which
9656 // does not stop compilation.
9657 EmitOSLogError = true;
9658 } else {
9659 EmitFormatDiagnostic(
9660 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9661 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9662 << AT.getRepresentativeTypeName(S.Context) << CSR
9663 << E->getSourceRange(),
9664 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9665 checkForCStrMembers(AT, E);
9666 }
9667 break;
9668
9670 if (CallType == VariadicCallType::DoesNotApply)
9671 EmitTypeMismatch = true;
9672 else if (ExprTy->isObjCObjectType())
9673 EmitFormatDiagnostic(
9674 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9675 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9676 << AT.getRepresentativeTypeName(S.Context) << CSR
9677 << E->getSourceRange(),
9678 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9679 else
9680 // FIXME: If this is an initializer list, suggest removing the braces
9681 // or inserting a cast to the target type.
9682 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9683 << isa<InitListExpr>(E) << ExprTy << CallType
9685 break;
9686 }
9687
9688 if (EmitOSLogError)
9689 EmitFormatDiagnostic(
9690 S.PDiag(diag::err_format_conversion_argument_type_mismatch)
9691 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9692 << CSR << E->getSourceRange(),
9693 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9694
9695 if (EmitTypeMismatch) {
9696 // The function is not variadic, so we do not generate warnings about
9697 // being allowed to pass that object as a variadic argument. Instead,
9698 // since there are inherently no printf specifiers for types which cannot
9699 // be passed as variadic arguments, emit a plain old specifier mismatch
9700 // argument.
9701 EmitFormatDiagnostic(
9702 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9703 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
9704 << E->getSourceRange(),
9705 E->getBeginLoc(), false, CSR);
9706 }
9707
9708 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9709 "format string specifier index out of range");
9710 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9711 }
9712
9713 return true;
9714}
9715
9716//===--- CHECK: Scanf format string checking ------------------------------===//
9717
9718namespace {
9719
9720class CheckScanfHandler : public CheckFormatHandler {
9721public:
9722 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9723 const Expr *origFormatExpr, FormatStringType type,
9724 unsigned firstDataArg, unsigned numDataArgs,
9725 const char *beg, Sema::FormatArgumentPassingKind APK,
9726 ArrayRef<const Expr *> Args, unsigned formatIdx,
9727 bool inFunctionCall, VariadicCallType CallType,
9728 llvm::SmallBitVector &CheckedVarArgs,
9729 UncoveredArgHandler &UncoveredArg)
9730 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9731 numDataArgs, beg, APK, Args, formatIdx,
9732 inFunctionCall, CallType, CheckedVarArgs,
9733 UncoveredArg) {}
9734
9735 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9736 const char *startSpecifier,
9737 unsigned specifierLen) override;
9738
9739 bool
9740 HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9741 const char *startSpecifier,
9742 unsigned specifierLen) override;
9743
9744 void HandleIncompleteScanList(const char *start, const char *end) override;
9745};
9746
9747} // namespace
9748
9749void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9750 const char *end) {
9751 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9752 getLocationOfByte(end), /*IsStringLocation*/ true,
9753 getSpecifierRange(start, end - start));
9754}
9755
9756bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9757 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9758 unsigned specifierLen) {
9761
9762 return HandleInvalidConversionSpecifier(
9763 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
9764 specifierLen, CS.getStart(), CS.getLength());
9765}
9766
9767bool CheckScanfHandler::HandleScanfSpecifier(
9768 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9769 unsigned specifierLen) {
9770 using namespace analyze_scanf;
9771 using namespace analyze_format_string;
9772
9773 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9774
9775 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9776 // be used to decide if we are using positional arguments consistently.
9777 if (FS.consumesDataArgument()) {
9778 if (atFirstArg) {
9779 atFirstArg = false;
9780 usesPositionalArgs = FS.usesPositionalArg();
9781 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9782 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9783 startSpecifier, specifierLen);
9784 return false;
9785 }
9786 }
9787
9788 // Check if the field with is non-zero.
9789 const OptionalAmount &Amt = FS.getFieldWidth();
9791 if (Amt.getConstantAmount() == 0) {
9792 const CharSourceRange &R =
9793 getSpecifierRange(Amt.getStart(), Amt.getConstantLength());
9794 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9795 getLocationOfByte(Amt.getStart()),
9796 /*IsStringLocation*/ true, R,
9798 }
9799 }
9800
9801 if (!FS.consumesDataArgument()) {
9802 // FIXME: Technically specifying a precision or field width here
9803 // makes no sense. Worth issuing a warning at some point.
9804 return true;
9805 }
9806
9807 // Consume the argument.
9808 unsigned argIndex = FS.getArgIndex();
9809 if (argIndex < NumDataArgs) {
9810 // The check to see if the argIndex is valid will come later.
9811 // We set the bit here because we may exit early from this
9812 // function if we encounter some other error.
9813 CoveredArgs.set(argIndex);
9814 }
9815
9816 // Check the length modifier is valid with the given conversion specifier.
9818 S.getLangOpts()))
9819 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9820 diag::warn_format_nonsensical_length);
9821 else if (!FS.hasStandardLengthModifier())
9822 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9824 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9825 diag::warn_format_non_standard_conversion_spec);
9826
9828 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9829
9830 // The remaining checks depend on the data arguments.
9831 if (!HasFormatArguments())
9832 return true;
9833
9834 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9835 return false;
9836
9837 // Check that the argument type matches the format specifier.
9838 const Expr *Ex = getDataArg(argIndex);
9839 if (!Ex)
9840 return true;
9841
9843
9844 if (!AT.isValid()) {
9845 return true;
9846 }
9847
9848 if (CheckUnsupportedType(AT, Ex, startSpecifier, specifierLen))
9849 return true;
9850
9852 AT.matchesType(S.Context, Ex->getType());
9855 return true;
9858
9859 ScanfSpecifier fixedFS = FS;
9860 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9861 S.getLangOpts(), S.Context);
9862
9863 unsigned Diag =
9864 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9865 : Signedness
9866 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9867 : diag::warn_format_conversion_argument_type_mismatch;
9868
9869 if (Success) {
9870 // Get the fix string from the fixed format specifier.
9871 SmallString<128> buf;
9872 llvm::raw_svector_ostream os(buf);
9873 fixedFS.toString(os);
9874
9875 EmitFormatDiagnostic(
9877 << Ex->getType() << false << Ex->getSourceRange(),
9878 Ex->getBeginLoc(),
9879 /*IsStringLocation*/ false,
9880 getSpecifierRange(startSpecifier, specifierLen),
9882 getSpecifierRange(startSpecifier, specifierLen), os.str()));
9883 } else {
9884 EmitFormatDiagnostic(S.PDiag(Diag)
9886 << Ex->getType() << false << Ex->getSourceRange(),
9887 Ex->getBeginLoc(),
9888 /*IsStringLocation*/ false,
9889 getSpecifierRange(startSpecifier, specifierLen));
9890 }
9891
9892 return true;
9893}
9894
9895static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9897 const StringLiteral *Fmt,
9899 const Expr *FmtExpr, bool InFunctionCall) {
9900 bool HadError = false;
9901 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9902 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9903 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9904 // In positional-style format strings, the same specifier can appear
9905 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9906 // are sorted by getPosition(), and we process each range of equal
9907 // getPosition() values as one group.
9908 // RefArgs are taken from a string literal that was given to
9909 // attribute(format_matches), and if we got this far, we have already
9910 // verified that if it has positional specifiers that appear in multiple
9911 // locations, then they are all mutually compatible. What's left for us to
9912 // do is verify that all specifiers with the same position in FmtArgs are
9913 // compatible with the RefArgs specifiers. We check each specifier from
9914 // FmtArgs against the first member of the RefArgs group.
9915 for (; FmtIter < FmtEnd; ++FmtIter) {
9916 // Clang does not diagnose missing format specifiers in positional-style
9917 // strings (TODO: which it probably should do, as it is UB to skip over a
9918 // format argument). Skip specifiers if needed.
9919 if (FmtIter->getPosition() < RefIter->getPosition())
9920 continue;
9921
9922 // Delimits a new getPosition() value.
9923 if (FmtIter->getPosition() > RefIter->getPosition())
9924 break;
9925
9926 HadError |=
9927 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
9928 }
9929
9930 // Jump RefIter to the start of the next group.
9931 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
9932 return Arg.getPosition() != RefIter->getPosition();
9933 });
9934 }
9935
9936 if (FmtIter < FmtEnd) {
9937 CheckFormatHandler::EmitFormatDiagnostic(
9938 S, InFunctionCall, FmtExpr,
9939 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
9940 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
9941 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
9942 } else if (RefIter < RefEnd) {
9943 CheckFormatHandler::EmitFormatDiagnostic(
9944 S, InFunctionCall, FmtExpr,
9945 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
9946 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
9947 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
9948 << 1 << RefIter->getSourceRange();
9949 }
9950 return !HadError;
9951}
9952
9954 Sema &S, const FormatStringLiteral *FExpr,
9955 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
9957 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
9958 bool inFunctionCall, VariadicCallType CallType,
9959 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
9960 bool IgnoreStringsWithoutSpecifiers) {
9961 // CHECK: is the format string a wide literal?
9962 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9963 CheckFormatHandler::EmitFormatDiagnostic(
9964 S, inFunctionCall, Args[format_idx],
9965 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9966 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9967 return;
9968 }
9969
9970 // Str - The format string. NOTE: this is NOT null-terminated!
9971 StringRef StrRef = FExpr->getString();
9972 const char *Str = StrRef.data();
9973 // Account for cases where the string literal is truncated in a declaration.
9974 const ConstantArrayType *T =
9975 S.Context.getAsConstantArrayType(FExpr->getType());
9976 assert(T && "String literal not of constant array type!");
9977 size_t TypeSize = T->getZExtSize();
9978 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9979 const unsigned numDataArgs = Args.size() - firstDataArg;
9980
9981 if (IgnoreStringsWithoutSpecifiers &&
9983 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9984 return;
9985
9986 // Emit a warning if the string literal is truncated and does not contain an
9987 // embedded null character.
9988 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9989 CheckFormatHandler::EmitFormatDiagnostic(
9990 S, inFunctionCall, Args[format_idx],
9991 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9992 FExpr->getBeginLoc(),
9993 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9994 return;
9995 }
9996
9997 // CHECK: empty format string?
9998 if (StrLen == 0 && numDataArgs > 0) {
9999 CheckFormatHandler::EmitFormatDiagnostic(
10000 S, inFunctionCall, Args[format_idx],
10001 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10002 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10003 return;
10004 }
10005
10010 bool IsObjC =
10012 if (ReferenceFormatString == nullptr) {
10013 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10014 numDataArgs, IsObjC, Str, APK, Args, format_idx,
10015 inFunctionCall, CallType, CheckedVarArgs,
10016 UncoveredArg);
10017
10019 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
10022 H.DoneProcessing();
10023 } else {
10025 Type, ReferenceFormatString, FExpr->getFormatString(),
10026 inFunctionCall ? nullptr : Args[format_idx]);
10027 }
10028 } else if (Type == FormatStringType::Scanf) {
10029 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10030 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
10031 CallType, CheckedVarArgs, UncoveredArg);
10032
10034 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10035 H.DoneProcessing();
10036 } // TODO: handle other formats
10037}
10038
10040 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
10041 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
10046 return true;
10047
10048 bool IsObjC =
10051 FormatStringLiteral RefLit = AuthoritativeFormatString;
10052 FormatStringLiteral TestLit = TestedFormatString;
10053 const Expr *Arg;
10054 bool DiagAtStringLiteral;
10055 if (FunctionCallArg) {
10056 Arg = FunctionCallArg;
10057 DiagAtStringLiteral = false;
10058 } else {
10059 Arg = TestedFormatString;
10060 DiagAtStringLiteral = true;
10061 }
10062 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
10063 AuthoritativeFormatString, Type,
10064 IsObjC, true, RefArgs) &&
10065 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
10066 DiagAtStringLiteral, FmtArgs)) {
10067 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
10068 TestedFormatString, FmtArgs, Arg,
10069 DiagAtStringLiteral);
10070 }
10071 return false;
10072}
10073
10075 const StringLiteral *Str) {
10080 return true;
10081
10082 FormatStringLiteral RefLit = Str;
10084 bool IsObjC =
10086 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
10087 true, Args))
10088 return false;
10089
10090 // Group arguments by getPosition() value, and check that each member of the
10091 // group is compatible with the first member. This verifies that when
10092 // positional arguments are used multiple times (such as %2$i %2$d), all uses
10093 // are mutually compatible. As an optimization, don't test the first member
10094 // against itself.
10095 bool HadError = false;
10096 auto Iter = Args.begin();
10097 auto End = Args.end();
10098 while (Iter != End) {
10099 const auto &FirstInGroup = *Iter;
10100 for (++Iter;
10101 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
10102 ++Iter) {
10103 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
10104 }
10105 }
10106 return !HadError;
10107}
10108
10110 // Str - The format string. NOTE: this is NOT null-terminated!
10111 StringRef StrRef = FExpr->getString();
10112 const char *Str = StrRef.data();
10113 // Account for cases where the string literal is truncated in a declaration.
10114 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10115 assert(T && "String literal not of constant array type!");
10116 size_t TypeSize = T->getZExtSize();
10117 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10119 Str, Str + StrLen, getLangOpts(), Context.getTargetInfo());
10120}
10121
10122//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10123
10124// Returns the related absolute value function that is larger, of 0 if one
10125// does not exist.
10126static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10127 switch (AbsFunction) {
10128 default:
10129 return 0;
10130
10131 case Builtin::BI__builtin_abs:
10132 return Builtin::BI__builtin_labs;
10133 case Builtin::BI__builtin_labs:
10134 return Builtin::BI__builtin_llabs;
10135 case Builtin::BI__builtin_llabs:
10136 return 0;
10137
10138 case Builtin::BI__builtin_fabsf:
10139 return Builtin::BI__builtin_fabs;
10140 case Builtin::BI__builtin_fabs:
10141 return Builtin::BI__builtin_fabsl;
10142 case Builtin::BI__builtin_fabsl:
10143 return 0;
10144
10145 case Builtin::BI__builtin_cabsf:
10146 return Builtin::BI__builtin_cabs;
10147 case Builtin::BI__builtin_cabs:
10148 return Builtin::BI__builtin_cabsl;
10149 case Builtin::BI__builtin_cabsl:
10150 return 0;
10151
10152 case Builtin::BIabs:
10153 return Builtin::BIlabs;
10154 case Builtin::BIlabs:
10155 return Builtin::BIllabs;
10156 case Builtin::BIllabs:
10157 return 0;
10158
10159 case Builtin::BIfabsf:
10160 return Builtin::BIfabs;
10161 case Builtin::BIfabs:
10162 return Builtin::BIfabsl;
10163 case Builtin::BIfabsl:
10164 return 0;
10165
10166 case Builtin::BIcabsf:
10167 return Builtin::BIcabs;
10168 case Builtin::BIcabs:
10169 return Builtin::BIcabsl;
10170 case Builtin::BIcabsl:
10171 return 0;
10172 }
10173}
10174
10175// Returns the argument type of the absolute value function.
10177 unsigned AbsType) {
10178 if (AbsType == 0)
10179 return QualType();
10180
10182 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10184 return QualType();
10185
10187 if (!FT)
10188 return QualType();
10189
10190 if (FT->getNumParams() != 1)
10191 return QualType();
10192
10193 return FT->getParamType(0);
10194}
10195
10196// Returns the best absolute value function, or zero, based on type and
10197// current absolute value function.
10198static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10199 unsigned AbsFunctionKind) {
10200 unsigned BestKind = 0;
10201 uint64_t ArgSize = Context.getTypeSize(ArgType);
10202 for (unsigned Kind = AbsFunctionKind; Kind != 0;
10203 Kind = getLargerAbsoluteValueFunction(Kind)) {
10204 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10205 if (Context.getTypeSize(ParamType) >= ArgSize) {
10206 if (BestKind == 0)
10207 BestKind = Kind;
10208 else if (Context.hasSameType(ParamType, ArgType)) {
10209 BestKind = Kind;
10210 break;
10211 }
10212 }
10213 }
10214 return BestKind;
10215}
10216
10222
10224 if (T->isIntegralOrEnumerationType())
10225 return AVK_Integer;
10226 if (T->isRealFloatingType())
10227 return AVK_Floating;
10228 if (T->isAnyComplexType())
10229 return AVK_Complex;
10230
10231 llvm_unreachable("Type not integer, floating, or complex");
10232}
10233
10234// Changes the absolute value function to a different type. Preserves whether
10235// the function is a builtin.
10236static unsigned changeAbsFunction(unsigned AbsKind,
10237 AbsoluteValueKind ValueKind) {
10238 switch (ValueKind) {
10239 case AVK_Integer:
10240 switch (AbsKind) {
10241 default:
10242 return 0;
10243 case Builtin::BI__builtin_fabsf:
10244 case Builtin::BI__builtin_fabs:
10245 case Builtin::BI__builtin_fabsl:
10246 case Builtin::BI__builtin_cabsf:
10247 case Builtin::BI__builtin_cabs:
10248 case Builtin::BI__builtin_cabsl:
10249 return Builtin::BI__builtin_abs;
10250 case Builtin::BIfabsf:
10251 case Builtin::BIfabs:
10252 case Builtin::BIfabsl:
10253 case Builtin::BIcabsf:
10254 case Builtin::BIcabs:
10255 case Builtin::BIcabsl:
10256 return Builtin::BIabs;
10257 }
10258 case AVK_Floating:
10259 switch (AbsKind) {
10260 default:
10261 return 0;
10262 case Builtin::BI__builtin_abs:
10263 case Builtin::BI__builtin_labs:
10264 case Builtin::BI__builtin_llabs:
10265 case Builtin::BI__builtin_cabsf:
10266 case Builtin::BI__builtin_cabs:
10267 case Builtin::BI__builtin_cabsl:
10268 return Builtin::BI__builtin_fabsf;
10269 case Builtin::BIabs:
10270 case Builtin::BIlabs:
10271 case Builtin::BIllabs:
10272 case Builtin::BIcabsf:
10273 case Builtin::BIcabs:
10274 case Builtin::BIcabsl:
10275 return Builtin::BIfabsf;
10276 }
10277 case AVK_Complex:
10278 switch (AbsKind) {
10279 default:
10280 return 0;
10281 case Builtin::BI__builtin_abs:
10282 case Builtin::BI__builtin_labs:
10283 case Builtin::BI__builtin_llabs:
10284 case Builtin::BI__builtin_fabsf:
10285 case Builtin::BI__builtin_fabs:
10286 case Builtin::BI__builtin_fabsl:
10287 return Builtin::BI__builtin_cabsf;
10288 case Builtin::BIabs:
10289 case Builtin::BIlabs:
10290 case Builtin::BIllabs:
10291 case Builtin::BIfabsf:
10292 case Builtin::BIfabs:
10293 case Builtin::BIfabsl:
10294 return Builtin::BIcabsf;
10295 }
10296 }
10297 llvm_unreachable("Unable to convert function");
10298}
10299
10300static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10301 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10302 if (!FnInfo)
10303 return 0;
10304
10305 switch (FDecl->getBuiltinID()) {
10306 default:
10307 return 0;
10308 case Builtin::BI__builtin_abs:
10309 case Builtin::BI__builtin_fabs:
10310 case Builtin::BI__builtin_fabsf:
10311 case Builtin::BI__builtin_fabsl:
10312 case Builtin::BI__builtin_labs:
10313 case Builtin::BI__builtin_llabs:
10314 case Builtin::BI__builtin_cabs:
10315 case Builtin::BI__builtin_cabsf:
10316 case Builtin::BI__builtin_cabsl:
10317 case Builtin::BIabs:
10318 case Builtin::BIlabs:
10319 case Builtin::BIllabs:
10320 case Builtin::BIfabs:
10321 case Builtin::BIfabsf:
10322 case Builtin::BIfabsl:
10323 case Builtin::BIcabs:
10324 case Builtin::BIcabsf:
10325 case Builtin::BIcabsl:
10326 return FDecl->getBuiltinID();
10327 }
10328 llvm_unreachable("Unknown Builtin type");
10329}
10330
10331// If the replacement is valid, emit a note with replacement function.
10332// Additionally, suggest including the proper header if not already included.
10334 unsigned AbsKind, QualType ArgType) {
10335 bool EmitHeaderHint = true;
10336 const char *HeaderName = nullptr;
10337 std::string FunctionName;
10338 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10339 FunctionName = "std::abs";
10340 if (ArgType->isIntegralOrEnumerationType()) {
10341 HeaderName = "cstdlib";
10342 } else if (ArgType->isRealFloatingType()) {
10343 HeaderName = "cmath";
10344 } else {
10345 llvm_unreachable("Invalid Type");
10346 }
10347
10348 // Lookup all std::abs
10349 if (NamespaceDecl *Std = S.getStdNamespace()) {
10350 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10351 R.suppressDiagnostics();
10352 S.LookupQualifiedName(R, Std);
10353
10354 for (const auto *I : R) {
10355 const FunctionDecl *FDecl = nullptr;
10356 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10357 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10358 } else {
10359 FDecl = dyn_cast<FunctionDecl>(I);
10360 }
10361 if (!FDecl)
10362 continue;
10363
10364 // Found std::abs(), check that they are the right ones.
10365 if (FDecl->getNumParams() != 1)
10366 continue;
10367
10368 // Check that the parameter type can handle the argument.
10369 QualType ParamType = FDecl->getParamDecl(0)->getType();
10370 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10371 S.Context.getTypeSize(ArgType) <=
10372 S.Context.getTypeSize(ParamType)) {
10373 // Found a function, don't need the header hint.
10374 EmitHeaderHint = false;
10375 break;
10376 }
10377 }
10378 }
10379 } else {
10380 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10381 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10382
10383 if (HeaderName) {
10384 DeclarationName DN(&S.Context.Idents.get(FunctionName));
10385 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10386 R.suppressDiagnostics();
10387 S.LookupName(R, S.getCurScope());
10388
10389 if (R.isSingleResult()) {
10390 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10391 if (FD && FD->getBuiltinID() == AbsKind) {
10392 EmitHeaderHint = false;
10393 } else {
10394 return;
10395 }
10396 } else if (!R.empty()) {
10397 return;
10398 }
10399 }
10400 }
10401
10402 S.Diag(Loc, diag::note_replace_abs_function)
10403 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10404
10405 if (!HeaderName)
10406 return;
10407
10408 if (!EmitHeaderHint)
10409 return;
10410
10411 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10412 << FunctionName;
10413}
10414
10415template <std::size_t StrLen>
10416static bool IsStdFunction(const FunctionDecl *FDecl,
10417 const char (&Str)[StrLen]) {
10418 if (!FDecl)
10419 return false;
10420 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10421 return false;
10422 if (!FDecl->isInStdNamespace())
10423 return false;
10424
10425 return true;
10426}
10427
10428enum class MathCheck { NaN, Inf };
10429static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10430 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10431 return llvm::is_contained(names, calleeName);
10432 };
10433
10434 switch (Check) {
10435 case MathCheck::NaN:
10436 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10437 "__builtin_nanf16", "__builtin_nanf128"});
10438 case MathCheck::Inf:
10439 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10440 "__builtin_inff16", "__builtin_inff128"});
10441 }
10442 llvm_unreachable("unknown MathCheck");
10443}
10444
10445static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10446 if (FDecl->getName() != "infinity")
10447 return false;
10448
10449 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
10450 const CXXRecordDecl *RDecl = MDecl->getParent();
10451 if (RDecl->getName() != "numeric_limits")
10452 return false;
10453
10454 if (const NamespaceDecl *NSDecl =
10455 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
10456 return NSDecl->isStdNamespace();
10457 }
10458
10459 return false;
10460}
10461
10462void Sema::CheckInfNaNFunction(const CallExpr *Call,
10463 const FunctionDecl *FDecl) {
10464 if (!FDecl->getIdentifier())
10465 return;
10466
10467 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
10468 if (FPO.getNoHonorNaNs() &&
10469 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
10471 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10472 << 1 << 0 << Call->getSourceRange();
10473 return;
10474 }
10475
10476 if (FPO.getNoHonorInfs() &&
10477 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
10478 IsInfinityFunction(FDecl) ||
10480 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10481 << 0 << 0 << Call->getSourceRange();
10482 }
10483}
10484
10485void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10486 const FunctionDecl *FDecl) {
10487 if (Call->getNumArgs() != 1)
10488 return;
10489
10490 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10491 bool IsStdAbs = IsStdFunction(FDecl, "abs");
10492 if (AbsKind == 0 && !IsStdAbs)
10493 return;
10494
10495 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10496 QualType ParamType = Call->getArg(0)->getType();
10497
10498 // Unsigned types cannot be negative. Suggest removing the absolute value
10499 // function call.
10500 if (ArgType->isUnsignedIntegerType()) {
10501 std::string FunctionName =
10502 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10503 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10504 Diag(Call->getExprLoc(), diag::note_remove_abs)
10505 << FunctionName
10506 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10507 return;
10508 }
10509
10510 // Taking the absolute value of a pointer is very suspicious, they probably
10511 // wanted to index into an array, dereference a pointer, call a function, etc.
10512 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10513 unsigned DiagType = 0;
10514 if (ArgType->isFunctionType())
10515 DiagType = 1;
10516 else if (ArgType->isArrayType())
10517 DiagType = 2;
10518
10519 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10520 return;
10521 }
10522
10523 // std::abs has overloads which prevent most of the absolute value problems
10524 // from occurring.
10525 if (IsStdAbs)
10526 return;
10527
10528 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10529 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10530
10531 // The argument and parameter are the same kind. Check if they are the right
10532 // size.
10533 if (ArgValueKind == ParamValueKind) {
10534 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10535 return;
10536
10537 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10538 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10539 << FDecl << ArgType << ParamType;
10540
10541 if (NewAbsKind == 0)
10542 return;
10543
10544 emitReplacement(*this, Call->getExprLoc(),
10545 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10546 return;
10547 }
10548
10549 // ArgValueKind != ParamValueKind
10550 // The wrong type of absolute value function was used. Attempt to find the
10551 // proper one.
10552 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10553 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10554 if (NewAbsKind == 0)
10555 return;
10556
10557 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10558 << FDecl << ParamValueKind << ArgValueKind;
10559
10560 emitReplacement(*this, Call->getExprLoc(),
10561 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10562}
10563
10564//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10565void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10566 const FunctionDecl *FDecl) {
10567 if (!Call || !FDecl) return;
10568
10569 // Ignore template specializations and macros.
10570 if (inTemplateInstantiation()) return;
10571 if (Call->getExprLoc().isMacroID()) return;
10572
10573 // Only care about the one template argument, two function parameter std::max
10574 if (Call->getNumArgs() != 2) return;
10575 if (!IsStdFunction(FDecl, "max")) return;
10576 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10577 if (!ArgList) return;
10578 if (ArgList->size() != 1) return;
10579
10580 // Check that template type argument is unsigned integer.
10581 const auto& TA = ArgList->get(0);
10582 if (TA.getKind() != TemplateArgument::Type) return;
10583 QualType ArgType = TA.getAsType();
10584 if (!ArgType->isUnsignedIntegerType()) return;
10585
10586 // See if either argument is a literal zero.
10587 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10588 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10589 if (!MTE) return false;
10590 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10591 if (!Num) return false;
10592 if (Num->getValue() != 0) return false;
10593 return true;
10594 };
10595
10596 const Expr *FirstArg = Call->getArg(0);
10597 const Expr *SecondArg = Call->getArg(1);
10598 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10599 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10600
10601 // Only warn when exactly one argument is zero.
10602 if (IsFirstArgZero == IsSecondArgZero) return;
10603
10604 SourceRange FirstRange = FirstArg->getSourceRange();
10605 SourceRange SecondRange = SecondArg->getSourceRange();
10606
10607 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10608
10609 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10610 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10611
10612 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10613 SourceRange RemovalRange;
10614 if (IsFirstArgZero) {
10615 RemovalRange = SourceRange(FirstRange.getBegin(),
10616 SecondRange.getBegin().getLocWithOffset(-1));
10617 } else {
10618 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10619 SecondRange.getEnd());
10620 }
10621
10622 Diag(Call->getExprLoc(), diag::note_remove_max_call)
10623 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10624 << FixItHint::CreateRemoval(RemovalRange);
10625}
10626
10627//===--- CHECK: Standard memory functions ---------------------------------===//
10628
10629/// Takes the expression passed to the size_t parameter of functions
10630/// such as memcmp, strncat, etc and warns if it's a comparison.
10631///
10632/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10634 const IdentifierInfo *FnName,
10635 SourceLocation FnLoc,
10636 SourceLocation RParenLoc) {
10637 const auto *Size = dyn_cast<BinaryOperator>(E);
10638 if (!Size)
10639 return false;
10640
10641 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10642 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10643 return false;
10644
10645 SourceRange SizeRange = Size->getSourceRange();
10646 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10647 << SizeRange << FnName;
10648 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10649 << FnName
10651 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10652 << FixItHint::CreateRemoval(RParenLoc);
10653 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10654 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10656 ")");
10657
10658 return true;
10659}
10660
10661/// Determine whether the given type is or contains a dynamic class type
10662/// (e.g., whether it has a vtable).
10664 bool &IsContained) {
10665 // Look through array types while ignoring qualifiers.
10666 const Type *Ty = T->getBaseElementTypeUnsafe();
10667 IsContained = false;
10668
10669 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10670 RD = RD ? RD->getDefinition() : nullptr;
10671 if (!RD || RD->isInvalidDecl())
10672 return nullptr;
10673
10674 if (RD->isDynamicClass())
10675 return RD;
10676
10677 // Check all the fields. If any bases were dynamic, the class is dynamic.
10678 // It's impossible for a class to transitively contain itself by value, so
10679 // infinite recursion is impossible.
10680 for (auto *FD : RD->fields()) {
10681 bool SubContained;
10682 if (const CXXRecordDecl *ContainedRD =
10683 getContainedDynamicClass(FD->getType(), SubContained)) {
10684 IsContained = true;
10685 return ContainedRD;
10686 }
10687 }
10688
10689 return nullptr;
10690}
10691
10693 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10694 if (Unary->getKind() == UETT_SizeOf)
10695 return Unary;
10696 return nullptr;
10697}
10698
10699/// If E is a sizeof expression, returns its argument expression,
10700/// otherwise returns NULL.
10701static const Expr *getSizeOfExprArg(const Expr *E) {
10703 if (!SizeOf->isArgumentType())
10704 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10705 return nullptr;
10706}
10707
10708/// If E is a sizeof expression, returns its argument type.
10711 return SizeOf->getTypeOfArgument();
10712 return QualType();
10713}
10714
10715namespace {
10716
10717struct SearchNonTrivialToInitializeField
10718 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10719 using Super =
10720 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10721
10722 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10723
10724 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10725 SourceLocation SL) {
10726 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10727 asDerived().visitArray(PDIK, AT, SL);
10728 return;
10729 }
10730
10731 Super::visitWithKind(PDIK, FT, SL);
10732 }
10733
10734 void visitARCStrong(QualType FT, SourceLocation SL) {
10735 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10736 }
10737 void visitARCWeak(QualType FT, SourceLocation SL) {
10738 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10739 }
10740 void visitStruct(QualType FT, SourceLocation SL) {
10741 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10742 visit(FD->getType(), FD->getLocation());
10743 }
10744 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10745 const ArrayType *AT, SourceLocation SL) {
10746 visit(getContext().getBaseElementType(AT), SL);
10747 }
10748 void visitTrivial(QualType FT, SourceLocation SL) {}
10749
10750 static void diag(QualType RT, const Expr *E, Sema &S) {
10751 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10752 }
10753
10754 ASTContext &getContext() { return S.getASTContext(); }
10755
10756 const Expr *E;
10757 Sema &S;
10758};
10759
10760struct SearchNonTrivialToCopyField
10761 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10762 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10763
10764 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10765
10766 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10767 SourceLocation SL) {
10768 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10769 asDerived().visitArray(PCK, AT, SL);
10770 return;
10771 }
10772
10773 Super::visitWithKind(PCK, FT, SL);
10774 }
10775
10776 void visitARCStrong(QualType FT, SourceLocation SL) {
10777 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10778 }
10779 void visitARCWeak(QualType FT, SourceLocation SL) {
10780 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10781 }
10782 void visitPtrAuth(QualType FT, SourceLocation SL) {
10783 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10784 }
10785 void visitStruct(QualType FT, SourceLocation SL) {
10786 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10787 visit(FD->getType(), FD->getLocation());
10788 }
10789 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10790 SourceLocation SL) {
10791 visit(getContext().getBaseElementType(AT), SL);
10792 }
10793 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10794 SourceLocation SL) {}
10795 void visitTrivial(QualType FT, SourceLocation SL) {}
10796 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10797
10798 static void diag(QualType RT, const Expr *E, Sema &S) {
10799 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10800 }
10801
10802 ASTContext &getContext() { return S.getASTContext(); }
10803
10804 const Expr *E;
10805 Sema &S;
10806};
10807
10808}
10809
10810/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10811static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10812 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10813
10814 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10815 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10816 return false;
10817
10818 return doesExprLikelyComputeSize(BO->getLHS()) ||
10819 doesExprLikelyComputeSize(BO->getRHS());
10820 }
10821
10822 return getAsSizeOfExpr(SizeofExpr) != nullptr;
10823}
10824
10825/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10826///
10827/// \code
10828/// #define MACRO 0
10829/// foo(MACRO);
10830/// foo(0);
10831/// \endcode
10832///
10833/// This should return true for the first call to foo, but not for the second
10834/// (regardless of whether foo is a macro or function).
10836 SourceLocation CallLoc,
10837 SourceLocation ArgLoc) {
10838 if (!CallLoc.isMacroID())
10839 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10840
10841 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10842 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10843}
10844
10845/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10846/// last two arguments transposed.
10847static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10848 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10849 return;
10850
10851 const Expr *SizeArg =
10852 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10853
10854 auto isLiteralZero = [](const Expr *E) {
10855 return (isa<IntegerLiteral>(E) &&
10856 cast<IntegerLiteral>(E)->getValue() == 0) ||
10858 cast<CharacterLiteral>(E)->getValue() == 0);
10859 };
10860
10861 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10862 SourceLocation CallLoc = Call->getRParenLoc();
10864 if (isLiteralZero(SizeArg) &&
10865 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10866
10867 SourceLocation DiagLoc = SizeArg->getExprLoc();
10868
10869 // Some platforms #define bzero to __builtin_memset. See if this is the
10870 // case, and if so, emit a better diagnostic.
10871 if (BId == Builtin::BIbzero ||
10873 CallLoc, SM, S.getLangOpts()) == "bzero")) {
10874 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10875 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10876 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10877 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10878 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10879 }
10880 return;
10881 }
10882
10883 // If the second argument to a memset is a sizeof expression and the third
10884 // isn't, this is also likely an error. This should catch
10885 // 'memset(buf, sizeof(buf), 0xff)'.
10886 if (BId == Builtin::BImemset &&
10887 doesExprLikelyComputeSize(Call->getArg(1)) &&
10888 !doesExprLikelyComputeSize(Call->getArg(2))) {
10889 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10890 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10891 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10892 return;
10893 }
10894}
10895
10896void Sema::CheckMemaccessArguments(const CallExpr *Call,
10897 unsigned BId,
10898 IdentifierInfo *FnName) {
10899 assert(BId != 0);
10900
10901 // It is possible to have a non-standard definition of memset. Validate
10902 // we have enough arguments, and if not, abort further checking.
10903 unsigned ExpectedNumArgs =
10904 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10905 if (Call->getNumArgs() < ExpectedNumArgs)
10906 return;
10907
10908 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10909 BId == Builtin::BIstrndup ? 1 : 2);
10910 unsigned LenArg =
10911 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10912 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10913
10914 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10915 Call->getBeginLoc(), Call->getRParenLoc()))
10916 return;
10917
10918 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10919 CheckMemaccessSize(*this, BId, Call);
10920
10921 // We have special checking when the length is a sizeof expression.
10922 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10923
10924 // Although widely used, 'bzero' is not a standard function. Be more strict
10925 // with the argument types before allowing diagnostics and only allow the
10926 // form bzero(ptr, sizeof(...)).
10927 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10928 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10929 return;
10930
10931 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10932 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10933 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10934
10935 QualType DestTy = Dest->getType();
10936 QualType PointeeTy;
10937 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10938 PointeeTy = DestPtrTy->getPointeeType();
10939
10940 // Never warn about void type pointers. This can be used to suppress
10941 // false positives.
10942 if (PointeeTy->isVoidType())
10943 continue;
10944
10945 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10946 // actually comparing the expressions for equality. Because computing the
10947 // expression IDs can be expensive, we only do this if the diagnostic is
10948 // enabled.
10949 if (CheckSizeofMemaccessArgument(LenExpr, Dest, FnName))
10950 break;
10951
10952 // Also check for cases where the sizeof argument is the exact same
10953 // type as the memory argument, and where it points to a user-defined
10954 // record type.
10955 if (SizeOfArgTy != QualType()) {
10956 if (PointeeTy->isRecordType() &&
10957 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10958 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10959 PDiag(diag::warn_sizeof_pointer_type_memaccess)
10960 << FnName << SizeOfArgTy << ArgIdx
10961 << PointeeTy << Dest->getSourceRange()
10962 << LenExpr->getSourceRange());
10963 break;
10964 }
10965 }
10966 } else if (DestTy->isArrayType()) {
10967 PointeeTy = DestTy;
10968 }
10969
10970 if (PointeeTy == QualType())
10971 continue;
10972
10973 // Always complain about dynamic classes.
10974 bool IsContained;
10975 if (const CXXRecordDecl *ContainedRD =
10976 getContainedDynamicClass(PointeeTy, IsContained)) {
10977
10978 unsigned OperationType = 0;
10979 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10980 // "overwritten" if we're warning about the destination for any call
10981 // but memcmp; otherwise a verb appropriate to the call.
10982 if (ArgIdx != 0 || IsCmp) {
10983 if (BId == Builtin::BImemcpy)
10984 OperationType = 1;
10985 else if(BId == Builtin::BImemmove)
10986 OperationType = 2;
10987 else if (IsCmp)
10988 OperationType = 3;
10989 }
10990
10991 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10992 PDiag(diag::warn_dyn_class_memaccess)
10993 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10994 << IsContained << ContainedRD << OperationType
10995 << Call->getCallee()->getSourceRange());
10996 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10997 BId != Builtin::BImemset)
10999 Dest->getExprLoc(), Dest,
11000 PDiag(diag::warn_arc_object_memaccess)
11001 << ArgIdx << FnName << PointeeTy
11002 << Call->getCallee()->getSourceRange());
11003 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
11004
11005 // FIXME: Do not consider incomplete types even though they may be
11006 // completed later. GCC does not diagnose such code, but we may want to
11007 // consider diagnosing it in the future, perhaps under a different, but
11008 // related, diagnostic group.
11009 bool NonTriviallyCopyableCXXRecord =
11010 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
11011 !PointeeTy.isTriviallyCopyableType(Context);
11012
11013 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11015 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11016 PDiag(diag::warn_cstruct_memaccess)
11017 << ArgIdx << FnName << PointeeTy << 0);
11018 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
11019 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11020 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11021 // FIXME: Limiting this warning to dest argument until we decide
11022 // whether it's valid for source argument too.
11023 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11024 PDiag(diag::warn_cxxstruct_memaccess)
11025 << FnName << PointeeTy);
11026 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11028 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11029 PDiag(diag::warn_cstruct_memaccess)
11030 << ArgIdx << FnName << PointeeTy << 1);
11031 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
11032 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11033 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11034 // FIXME: Limiting this warning to dest argument until we decide
11035 // whether it's valid for source argument too.
11036 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11037 PDiag(diag::warn_cxxstruct_memaccess)
11038 << FnName << PointeeTy);
11039 } else {
11040 continue;
11041 }
11042 } else
11043 continue;
11044
11046 Dest->getExprLoc(), Dest,
11047 PDiag(diag::note_bad_memaccess_silence)
11048 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
11049 break;
11050 }
11051}
11052
11053bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
11054 IdentifierInfo *FnName) {
11055 llvm::FoldingSetNodeID SizeOfArgID;
11056 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
11057 if (!SizeOfArg)
11058 return false;
11059 // Computing this warning is expensive, so we only do so if the warning is
11060 // enabled.
11061 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
11062 SizeOfArg->getExprLoc()))
11063 return false;
11064 QualType DestTy = Dest->getType();
11065 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
11066 if (!DestPtrTy)
11067 return false;
11068
11069 QualType PointeeTy = DestPtrTy->getPointeeType();
11070
11071 if (SizeOfArgID == llvm::FoldingSetNodeID())
11072 SizeOfArg->Profile(SizeOfArgID, Context, true);
11073
11074 llvm::FoldingSetNodeID DestID;
11075 Dest->Profile(DestID, Context, true);
11076 if (DestID == SizeOfArgID) {
11077 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11078 // over sizeof(src) as well.
11079 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11080 StringRef ReadableName = FnName->getName();
11081
11082 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest);
11083 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
11084 ActionIdx = 1; // If its an address-of operator, just remove it.
11085 if (!PointeeTy->isIncompleteType() &&
11086 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
11087 ActionIdx = 2; // If the pointee's size is sizeof(char),
11088 // suggest an explicit length.
11089
11090 // If the function is defined as a builtin macro, do not show macro
11091 // expansion.
11092 SourceLocation SL = SizeOfArg->getExprLoc();
11093 SourceRange DSR = Dest->getSourceRange();
11094 SourceRange SSR = SizeOfArg->getSourceRange();
11095 SourceManager &SM = getSourceManager();
11096
11097 if (SM.isMacroArgExpansion(SL)) {
11098 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
11099 SL = SM.getSpellingLoc(SL);
11100 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
11101 SM.getSpellingLoc(DSR.getEnd()));
11102 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
11103 SM.getSpellingLoc(SSR.getEnd()));
11104 }
11105
11106 DiagRuntimeBehavior(SL, SizeOfArg,
11107 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
11108 << ReadableName << PointeeTy << DestTy << DSR
11109 << SSR);
11110 DiagRuntimeBehavior(SL, SizeOfArg,
11111 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
11112 << ActionIdx << SSR);
11113 return true;
11114 }
11115 return false;
11116}
11117
11118// A little helper routine: ignore addition and subtraction of integer literals.
11119// This intentionally does not ignore all integer constant expressions because
11120// we don't want to remove sizeof().
11121static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11122 Ex = Ex->IgnoreParenCasts();
11123
11124 while (true) {
11125 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11126 if (!BO || !BO->isAdditiveOp())
11127 break;
11128
11129 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11130 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11131
11132 if (isa<IntegerLiteral>(RHS))
11133 Ex = LHS;
11134 else if (isa<IntegerLiteral>(LHS))
11135 Ex = RHS;
11136 else
11137 break;
11138 }
11139
11140 return Ex;
11141}
11142
11144 ASTContext &Context) {
11145 // Only handle constant-sized or VLAs, but not flexible members.
11146 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11147 // Only issue the FIXIT for arrays of size > 1.
11148 if (CAT->getZExtSize() <= 1)
11149 return false;
11150 } else if (!Ty->isVariableArrayType()) {
11151 return false;
11152 }
11153 return true;
11154}
11155
11156void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11157 IdentifierInfo *FnName) {
11158
11159 // Don't crash if the user has the wrong number of arguments
11160 unsigned NumArgs = Call->getNumArgs();
11161 if ((NumArgs != 3) && (NumArgs != 4))
11162 return;
11163
11164 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11165 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11166 const Expr *CompareWithSrc = nullptr;
11167
11168 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11169 Call->getBeginLoc(), Call->getRParenLoc()))
11170 return;
11171
11172 // Look for 'strlcpy(dst, x, sizeof(x))'
11173 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11174 CompareWithSrc = Ex;
11175 else {
11176 // Look for 'strlcpy(dst, x, strlen(x))'
11177 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11178 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11179 SizeCall->getNumArgs() == 1)
11180 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11181 }
11182 }
11183
11184 if (!CompareWithSrc)
11185 return;
11186
11187 // Determine if the argument to sizeof/strlen is equal to the source
11188 // argument. In principle there's all kinds of things you could do
11189 // here, for instance creating an == expression and evaluating it with
11190 // EvaluateAsBooleanCondition, but this uses a more direct technique:
11191 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11192 if (!SrcArgDRE)
11193 return;
11194
11195 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11196 if (!CompareWithSrcDRE ||
11197 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11198 return;
11199
11200 const Expr *OriginalSizeArg = Call->getArg(2);
11201 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11202 << OriginalSizeArg->getSourceRange() << FnName;
11203
11204 // Output a FIXIT hint if the destination is an array (rather than a
11205 // pointer to an array). This could be enhanced to handle some
11206 // pointers if we know the actual size, like if DstArg is 'array+2'
11207 // we could say 'sizeof(array)-2'.
11208 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11210 return;
11211
11212 SmallString<128> sizeString;
11213 llvm::raw_svector_ostream OS(sizeString);
11214 OS << "sizeof(";
11215 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11216 OS << ")";
11217
11218 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11219 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11220 OS.str());
11221}
11222
11223/// Check if two expressions refer to the same declaration.
11224static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11225 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11226 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11227 return D1->getDecl() == D2->getDecl();
11228 return false;
11229}
11230
11231static const Expr *getStrlenExprArg(const Expr *E) {
11232 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11233 const FunctionDecl *FD = CE->getDirectCallee();
11234 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11235 return nullptr;
11236 return CE->getArg(0)->IgnoreParenCasts();
11237 }
11238 return nullptr;
11239}
11240
11241void Sema::CheckStrncatArguments(const CallExpr *CE,
11242 const IdentifierInfo *FnName) {
11243 // Don't crash if the user has the wrong number of arguments.
11244 if (CE->getNumArgs() < 3)
11245 return;
11246 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11247 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11248 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11249
11250 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11251 CE->getRParenLoc()))
11252 return;
11253
11254 // Identify common expressions, which are wrongly used as the size argument
11255 // to strncat and may lead to buffer overflows.
11256 unsigned PatternType = 0;
11257 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11258 // - sizeof(dst)
11259 if (referToTheSameDecl(SizeOfArg, DstArg))
11260 PatternType = 1;
11261 // - sizeof(src)
11262 else if (referToTheSameDecl(SizeOfArg, SrcArg))
11263 PatternType = 2;
11264 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11265 if (BE->getOpcode() == BO_Sub) {
11266 const Expr *L = BE->getLHS()->IgnoreParenCasts();
11267 const Expr *R = BE->getRHS()->IgnoreParenCasts();
11268 // - sizeof(dst) - strlen(dst)
11269 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11271 PatternType = 1;
11272 // - sizeof(src) - (anything)
11273 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11274 PatternType = 2;
11275 }
11276 }
11277
11278 if (PatternType == 0)
11279 return;
11280
11281 // Generate the diagnostic.
11282 SourceLocation SL = LenArg->getBeginLoc();
11283 SourceRange SR = LenArg->getSourceRange();
11284 SourceManager &SM = getSourceManager();
11285
11286 // If the function is defined as a builtin macro, do not show macro expansion.
11287 if (SM.isMacroArgExpansion(SL)) {
11288 SL = SM.getSpellingLoc(SL);
11289 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11290 SM.getSpellingLoc(SR.getEnd()));
11291 }
11292
11293 // Check if the destination is an array (rather than a pointer to an array).
11294 QualType DstTy = DstArg->getType();
11295 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11296 Context);
11297 if (!isKnownSizeArray) {
11298 if (PatternType == 1)
11299 Diag(SL, diag::warn_strncat_wrong_size) << SR;
11300 else
11301 Diag(SL, diag::warn_strncat_src_size) << SR;
11302 return;
11303 }
11304
11305 if (PatternType == 1)
11306 Diag(SL, diag::warn_strncat_large_size) << SR;
11307 else
11308 Diag(SL, diag::warn_strncat_src_size) << SR;
11309
11310 SmallString<128> sizeString;
11311 llvm::raw_svector_ostream OS(sizeString);
11312 OS << "sizeof(";
11313 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11314 OS << ") - ";
11315 OS << "strlen(";
11316 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11317 OS << ") - 1";
11318
11319 Diag(SL, diag::note_strncat_wrong_size)
11320 << FixItHint::CreateReplacement(SR, OS.str());
11321}
11322
11323namespace {
11324void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11325 const UnaryOperator *UnaryExpr, const Decl *D) {
11327 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11328 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11329 return;
11330 }
11331}
11332
11333void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11334 const UnaryOperator *UnaryExpr) {
11335 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11336 const Decl *D = Lvalue->getDecl();
11337 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11338 if (!DD->getType()->isReferenceType())
11339 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11340 }
11341 }
11342
11343 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11344 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11345 Lvalue->getMemberDecl());
11346}
11347
11348void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11349 const UnaryOperator *UnaryExpr) {
11350 const auto *Lambda = dyn_cast<LambdaExpr>(
11352 if (!Lambda)
11353 return;
11354
11355 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11356 << CalleeName << 2 /*object: lambda expression*/;
11357}
11358
11359void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11360 const DeclRefExpr *Lvalue) {
11361 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11362 if (Var == nullptr)
11363 return;
11364
11365 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11366 << CalleeName << 0 /*object: */ << Var;
11367}
11368
11369void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11370 const CastExpr *Cast) {
11371 SmallString<128> SizeString;
11372 llvm::raw_svector_ostream OS(SizeString);
11373
11374 clang::CastKind Kind = Cast->getCastKind();
11375 if (Kind == clang::CK_BitCast &&
11376 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11377 return;
11378 if (Kind == clang::CK_IntegralToPointer &&
11380 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11381 return;
11382
11383 switch (Cast->getCastKind()) {
11384 case clang::CK_BitCast:
11385 case clang::CK_IntegralToPointer:
11386 case clang::CK_FunctionToPointerDecay:
11387 OS << '\'';
11388 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11389 OS << '\'';
11390 break;
11391 default:
11392 return;
11393 }
11394
11395 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11396 << CalleeName << 0 /*object: */ << OS.str();
11397}
11398} // namespace
11399
11400void Sema::CheckFreeArguments(const CallExpr *E) {
11401 const std::string CalleeName =
11402 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11403
11404 { // Prefer something that doesn't involve a cast to make things simpler.
11405 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11406 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11407 switch (UnaryExpr->getOpcode()) {
11408 case UnaryOperator::Opcode::UO_AddrOf:
11409 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11410 case UnaryOperator::Opcode::UO_Plus:
11411 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11412 default:
11413 break;
11414 }
11415
11416 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11417 if (Lvalue->getType()->isArrayType())
11418 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11419
11420 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11421 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11422 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11423 return;
11424 }
11425
11426 if (isa<BlockExpr>(Arg)) {
11427 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11428 << CalleeName << 1 /*object: block*/;
11429 return;
11430 }
11431 }
11432 // Maybe the cast was important, check after the other cases.
11433 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11434 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11435}
11436
11437void
11438Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11439 SourceLocation ReturnLoc,
11440 bool isObjCMethod,
11441 const AttrVec *Attrs,
11442 const FunctionDecl *FD) {
11443 // Check if the return value is null but should not be.
11444 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11445 (!isObjCMethod && isNonNullType(lhsType))) &&
11446 CheckNonNullExpr(*this, RetValExp))
11447 Diag(ReturnLoc, diag::warn_null_ret)
11448 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11449
11450 // C++11 [basic.stc.dynamic.allocation]p4:
11451 // If an allocation function declared with a non-throwing
11452 // exception-specification fails to allocate storage, it shall return
11453 // a null pointer. Any other allocation function that fails to allocate
11454 // storage shall indicate failure only by throwing an exception [...]
11455 if (FD) {
11457 if (Op == OO_New || Op == OO_Array_New) {
11458 const FunctionProtoType *Proto
11459 = FD->getType()->castAs<FunctionProtoType>();
11460 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11461 CheckNonNullExpr(*this, RetValExp))
11462 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11463 << FD << getLangOpts().CPlusPlus11;
11464 }
11465 }
11466
11467 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11468 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
11469 }
11470
11471 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11472 // here prevent the user from using a PPC MMA type as trailing return type.
11473 if (Context.getTargetInfo().getTriple().isPPC64())
11474 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11475}
11476
11478 const Expr *RHS, BinaryOperatorKind Opcode) {
11479 if (!BinaryOperator::isEqualityOp(Opcode))
11480 return;
11481
11482 // Match and capture subexpressions such as "(float) X == 0.1".
11483 const FloatingLiteral *FPLiteral;
11484 const CastExpr *FPCast;
11485 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11486 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11487 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11488 return FPLiteral && FPCast;
11489 };
11490
11491 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11492 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11493 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11494 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11495 TargetTy->isFloatingPoint()) {
11496 bool Lossy;
11497 llvm::APFloat TargetC = FPLiteral->getValue();
11498 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11499 llvm::APFloat::rmNearestTiesToEven, &Lossy);
11500 if (Lossy) {
11501 // If the literal cannot be represented in the source type, then a
11502 // check for == is always false and check for != is always true.
11503 Diag(Loc, diag::warn_float_compare_literal)
11504 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11505 << LHS->getSourceRange() << RHS->getSourceRange();
11506 return;
11507 }
11508 }
11509 }
11510
11511 // Match a more general floating-point equality comparison (-Wfloat-equal).
11512 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11513 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11514
11515 // Special case: check for x == x (which is OK).
11516 // Do not emit warnings for such cases.
11517 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11518 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11519 if (DRL->getDecl() == DRR->getDecl())
11520 return;
11521
11522 // Special case: check for comparisons against literals that can be exactly
11523 // represented by APFloat. In such cases, do not emit a warning. This
11524 // is a heuristic: often comparison against such literals are used to
11525 // detect if a value in a variable has not changed. This clearly can
11526 // lead to false negatives.
11527 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11528 if (FLL->isExact())
11529 return;
11530 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11531 if (FLR->isExact())
11532 return;
11533
11534 // Check for comparisons with builtin types.
11535 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
11536 CL && CL->getBuiltinCallee())
11537 return;
11538
11539 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
11540 CR && CR->getBuiltinCallee())
11541 return;
11542
11543 // Emit the diagnostic.
11544 Diag(Loc, diag::warn_floatingpoint_eq)
11545 << LHS->getSourceRange() << RHS->getSourceRange();
11546}
11547
11548//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11549//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11550
11551namespace {
11552
11553/// Structure recording the 'active' range of an integer-valued
11554/// expression.
11555struct IntRange {
11556 /// The number of bits active in the int. Note that this includes exactly one
11557 /// sign bit if !NonNegative.
11558 unsigned Width;
11559
11560 /// True if the int is known not to have negative values. If so, all leading
11561 /// bits before Width are known zero, otherwise they are known to be the
11562 /// same as the MSB within Width.
11563 bool NonNegative;
11564
11565 IntRange(unsigned Width, bool NonNegative)
11566 : Width(Width), NonNegative(NonNegative) {}
11567
11568 /// Number of bits excluding the sign bit.
11569 unsigned valueBits() const {
11570 return NonNegative ? Width : Width - 1;
11571 }
11572
11573 /// Returns the range of the bool type.
11574 static IntRange forBoolType() {
11575 return IntRange(1, true);
11576 }
11577
11578 /// Returns the range of an opaque value of the given integral type.
11579 static IntRange forValueOfType(ASTContext &C, QualType T) {
11580 return forValueOfCanonicalType(C,
11582 }
11583
11584 /// Returns the range of an opaque value of a canonical integral type.
11585 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11586 assert(T->isCanonicalUnqualified());
11587
11588 if (const auto *VT = dyn_cast<VectorType>(T))
11589 T = VT->getElementType().getTypePtr();
11590 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11591 T = MT->getElementType().getTypePtr();
11592 if (const auto *CT = dyn_cast<ComplexType>(T))
11593 T = CT->getElementType().getTypePtr();
11594 if (const auto *AT = dyn_cast<AtomicType>(T))
11595 T = AT->getValueType().getTypePtr();
11596 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11597 T = OBT->getUnderlyingType().getTypePtr();
11598
11599 if (!C.getLangOpts().CPlusPlus) {
11600 // For enum types in C code, use the underlying datatype.
11601 if (const auto *ED = T->getAsEnumDecl())
11602 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
11603 } else if (auto *Enum = T->getAsEnumDecl()) {
11604 // For enum types in C++, use the known bit width of the enumerators.
11605 // In C++11, enums can have a fixed underlying type. Use this type to
11606 // compute the range.
11607 if (Enum->isFixed()) {
11608 return IntRange(C.getIntWidth(QualType(T, 0)),
11609 !Enum->getIntegerType()->isSignedIntegerType());
11610 }
11611
11612 unsigned NumPositive = Enum->getNumPositiveBits();
11613 unsigned NumNegative = Enum->getNumNegativeBits();
11614
11615 if (NumNegative == 0)
11616 return IntRange(NumPositive, true/*NonNegative*/);
11617 else
11618 return IntRange(std::max(NumPositive + 1, NumNegative),
11619 false/*NonNegative*/);
11620 }
11621
11622 if (const auto *EIT = dyn_cast<BitIntType>(T))
11623 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11624
11625 const BuiltinType *BT = cast<BuiltinType>(T);
11626 assert(BT->isInteger());
11627
11628 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11629 }
11630
11631 /// Returns the "target" range of a canonical integral type, i.e.
11632 /// the range of values expressible in the type.
11633 ///
11634 /// This matches forValueOfCanonicalType except that enums have the
11635 /// full range of their type, not the range of their enumerators.
11636 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11637 assert(T->isCanonicalUnqualified());
11638
11639 if (const VectorType *VT = dyn_cast<VectorType>(T))
11640 T = VT->getElementType().getTypePtr();
11641 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11642 T = MT->getElementType().getTypePtr();
11643 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11644 T = CT->getElementType().getTypePtr();
11645 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11646 T = AT->getValueType().getTypePtr();
11647 if (const auto *ED = T->getAsEnumDecl())
11648 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
11649 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11650 T = OBT->getUnderlyingType().getTypePtr();
11651
11652 if (const auto *EIT = dyn_cast<BitIntType>(T))
11653 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11654
11655 const BuiltinType *BT = cast<BuiltinType>(T);
11656 assert(BT->isInteger());
11657
11658 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11659 }
11660
11661 /// Returns the supremum of two ranges: i.e. their conservative merge.
11662 static IntRange join(IntRange L, IntRange R) {
11663 bool Unsigned = L.NonNegative && R.NonNegative;
11664 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11665 L.NonNegative && R.NonNegative);
11666 }
11667
11668 /// Return the range of a bitwise-AND of the two ranges.
11669 static IntRange bit_and(IntRange L, IntRange R) {
11670 unsigned Bits = std::max(L.Width, R.Width);
11671 bool NonNegative = false;
11672 if (L.NonNegative) {
11673 Bits = std::min(Bits, L.Width);
11674 NonNegative = true;
11675 }
11676 if (R.NonNegative) {
11677 Bits = std::min(Bits, R.Width);
11678 NonNegative = true;
11679 }
11680 return IntRange(Bits, NonNegative);
11681 }
11682
11683 /// Return the range of a sum of the two ranges.
11684 static IntRange sum(IntRange L, IntRange R) {
11685 bool Unsigned = L.NonNegative && R.NonNegative;
11686 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11687 Unsigned);
11688 }
11689
11690 /// Return the range of a difference of the two ranges.
11691 static IntRange difference(IntRange L, IntRange R) {
11692 // We need a 1-bit-wider range if:
11693 // 1) LHS can be negative: least value can be reduced.
11694 // 2) RHS can be negative: greatest value can be increased.
11695 bool CanWiden = !L.NonNegative || !R.NonNegative;
11696 bool Unsigned = L.NonNegative && R.Width == 0;
11697 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11698 !Unsigned,
11699 Unsigned);
11700 }
11701
11702 /// Return the range of a product of the two ranges.
11703 static IntRange product(IntRange L, IntRange R) {
11704 // If both LHS and RHS can be negative, we can form
11705 // -2^L * -2^R = 2^(L + R)
11706 // which requires L + R + 1 value bits to represent.
11707 bool CanWiden = !L.NonNegative && !R.NonNegative;
11708 bool Unsigned = L.NonNegative && R.NonNegative;
11709 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11710 Unsigned);
11711 }
11712
11713 /// Return the range of a remainder operation between the two ranges.
11714 static IntRange rem(IntRange L, IntRange R) {
11715 // The result of a remainder can't be larger than the result of
11716 // either side. The sign of the result is the sign of the LHS.
11717 bool Unsigned = L.NonNegative;
11718 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11719 Unsigned);
11720 }
11721};
11722
11723} // namespace
11724
11725static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11726 if (value.isSigned() && value.isNegative())
11727 return IntRange(value.getSignificantBits(), false);
11728
11729 if (value.getBitWidth() > MaxWidth)
11730 value = value.trunc(MaxWidth);
11731
11732 // isNonNegative() just checks the sign bit without considering
11733 // signedness.
11734 return IntRange(value.getActiveBits(), true);
11735}
11736
11737static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11738 if (result.isInt())
11739 return GetValueRange(result.getInt(), MaxWidth);
11740
11741 if (result.isVector()) {
11742 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
11743 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11744 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
11745 R = IntRange::join(R, El);
11746 }
11747 return R;
11748 }
11749
11750 if (result.isComplexInt()) {
11751 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
11752 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
11753 return IntRange::join(R, I);
11754 }
11755
11756 // This can happen with lossless casts to intptr_t of "based" lvalues.
11757 // Assume it might use arbitrary bits.
11758 // FIXME: The only reason we need to pass the type in here is to get
11759 // the sign right on this one case. It would be nice if APValue
11760 // preserved this.
11761 assert(result.isLValue() || result.isAddrLabelDiff());
11762 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11763}
11764
11765static QualType GetExprType(const Expr *E) {
11766 QualType Ty = E->getType();
11767 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11768 Ty = AtomicRHS->getValueType();
11769 return Ty;
11770}
11771
11772/// Attempts to estimate an approximate range for the given integer expression.
11773/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11774/// reliable estimation cannot be determined.
11775///
11776/// \param MaxWidth The width to which the value will be truncated.
11777/// \param InConstantContext If \c true, interpret the expression within a
11778/// constant context.
11779/// \param Approximate If \c true, provide a likely range of values by assuming
11780/// that arithmetic on narrower types remains within those types.
11781/// If \c false, return a range that includes all possible values
11782/// resulting from the expression.
11783/// \returns A range of values that the expression might take, or
11784/// std::nullopt if a reliable estimation cannot be determined.
11785static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11786 unsigned MaxWidth,
11787 bool InConstantContext,
11788 bool Approximate) {
11789 E = E->IgnoreParens();
11790
11791 // Try a full evaluation first.
11792 Expr::EvalResult result;
11793 if (E->EvaluateAsRValue(result, C, InConstantContext))
11794 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
11795
11796 // I think we only want to look through implicit casts here; if the
11797 // user has an explicit widening cast, we should treat the value as
11798 // being of the new, wider type.
11799 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11800 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11801 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11802 Approximate);
11803
11804 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11805
11806 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11807 CE->getCastKind() == CK_BooleanToSignedIntegral;
11808
11809 // Assume that non-integer casts can span the full range of the type.
11810 if (!isIntegerCast)
11811 return OutputTypeRange;
11812
11813 std::optional<IntRange> SubRange = TryGetExprRange(
11814 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
11815 InConstantContext, Approximate);
11816 if (!SubRange)
11817 return std::nullopt;
11818
11819 // Bail out if the subexpr's range is as wide as the cast type.
11820 if (SubRange->Width >= OutputTypeRange.Width)
11821 return OutputTypeRange;
11822
11823 // Otherwise, we take the smaller width, and we're non-negative if
11824 // either the output type or the subexpr is.
11825 return IntRange(SubRange->Width,
11826 SubRange->NonNegative || OutputTypeRange.NonNegative);
11827 }
11828
11829 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11830 // If we can fold the condition, just take that operand.
11831 bool CondResult;
11832 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11833 return TryGetExprRange(
11834 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
11835 InConstantContext, Approximate);
11836
11837 // Otherwise, conservatively merge.
11838 // TryGetExprRange requires an integer expression, but a throw expression
11839 // results in a void type.
11840 Expr *TrueExpr = CO->getTrueExpr();
11841 if (TrueExpr->getType()->isVoidType())
11842 return std::nullopt;
11843
11844 std::optional<IntRange> L =
11845 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
11846 if (!L)
11847 return std::nullopt;
11848
11849 Expr *FalseExpr = CO->getFalseExpr();
11850 if (FalseExpr->getType()->isVoidType())
11851 return std::nullopt;
11852
11853 std::optional<IntRange> R =
11854 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
11855 if (!R)
11856 return std::nullopt;
11857
11858 return IntRange::join(*L, *R);
11859 }
11860
11861 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11862 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11863
11864 switch (BO->getOpcode()) {
11865 case BO_Cmp:
11866 llvm_unreachable("builtin <=> should have class type");
11867
11868 // Boolean-valued operations are single-bit and positive.
11869 case BO_LAnd:
11870 case BO_LOr:
11871 case BO_LT:
11872 case BO_GT:
11873 case BO_LE:
11874 case BO_GE:
11875 case BO_EQ:
11876 case BO_NE:
11877 return IntRange::forBoolType();
11878
11879 // The type of the assignments is the type of the LHS, so the RHS
11880 // is not necessarily the same type.
11881 case BO_MulAssign:
11882 case BO_DivAssign:
11883 case BO_RemAssign:
11884 case BO_AddAssign:
11885 case BO_SubAssign:
11886 case BO_XorAssign:
11887 case BO_OrAssign:
11888 // TODO: bitfields?
11889 return IntRange::forValueOfType(C, GetExprType(E));
11890
11891 // Simple assignments just pass through the RHS, which will have
11892 // been coerced to the LHS type.
11893 case BO_Assign:
11894 // TODO: bitfields?
11895 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11896 Approximate);
11897
11898 // Operations with opaque sources are black-listed.
11899 case BO_PtrMemD:
11900 case BO_PtrMemI:
11901 return IntRange::forValueOfType(C, GetExprType(E));
11902
11903 // Bitwise-and uses the *infinum* of the two source ranges.
11904 case BO_And:
11905 case BO_AndAssign:
11906 Combine = IntRange::bit_and;
11907 break;
11908
11909 // Left shift gets black-listed based on a judgement call.
11910 case BO_Shl:
11911 // ...except that we want to treat '1 << (blah)' as logically
11912 // positive. It's an important idiom.
11913 if (IntegerLiteral *I
11914 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11915 if (I->getValue() == 1) {
11916 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11917 return IntRange(R.Width, /*NonNegative*/ true);
11918 }
11919 }
11920 [[fallthrough]];
11921
11922 case BO_ShlAssign:
11923 return IntRange::forValueOfType(C, GetExprType(E));
11924
11925 // Right shift by a constant can narrow its left argument.
11926 case BO_Shr:
11927 case BO_ShrAssign: {
11928 std::optional<IntRange> L = TryGetExprRange(
11929 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11930 if (!L)
11931 return std::nullopt;
11932
11933 // If the shift amount is a positive constant, drop the width by
11934 // that much.
11935 if (std::optional<llvm::APSInt> shift =
11936 BO->getRHS()->getIntegerConstantExpr(C)) {
11937 if (shift->isNonNegative()) {
11938 if (shift->uge(L->Width))
11939 L->Width = (L->NonNegative ? 0 : 1);
11940 else
11941 L->Width -= shift->getZExtValue();
11942 }
11943 }
11944
11945 return L;
11946 }
11947
11948 // Comma acts as its right operand.
11949 case BO_Comma:
11950 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11951 Approximate);
11952
11953 case BO_Add:
11954 if (!Approximate)
11955 Combine = IntRange::sum;
11956 break;
11957
11958 case BO_Sub:
11959 if (BO->getLHS()->getType()->isPointerType())
11960 return IntRange::forValueOfType(C, GetExprType(E));
11961 if (!Approximate)
11962 Combine = IntRange::difference;
11963 break;
11964
11965 case BO_Mul:
11966 if (!Approximate)
11967 Combine = IntRange::product;
11968 break;
11969
11970 // The width of a division result is mostly determined by the size
11971 // of the LHS.
11972 case BO_Div: {
11973 // Don't 'pre-truncate' the operands.
11974 unsigned opWidth = C.getIntWidth(GetExprType(E));
11975 std::optional<IntRange> L = TryGetExprRange(
11976 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11977 if (!L)
11978 return std::nullopt;
11979
11980 // If the divisor is constant, use that.
11981 if (std::optional<llvm::APSInt> divisor =
11982 BO->getRHS()->getIntegerConstantExpr(C)) {
11983 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11984 if (log2 >= L->Width)
11985 L->Width = (L->NonNegative ? 0 : 1);
11986 else
11987 L->Width = std::min(L->Width - log2, MaxWidth);
11988 return L;
11989 }
11990
11991 // Otherwise, just use the LHS's width.
11992 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11993 // could be -1.
11994 std::optional<IntRange> R = TryGetExprRange(
11995 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11996 if (!R)
11997 return std::nullopt;
11998
11999 return IntRange(L->Width, L->NonNegative && R->NonNegative);
12000 }
12001
12002 case BO_Rem:
12003 Combine = IntRange::rem;
12004 break;
12005
12006 // The default behavior is okay for these.
12007 case BO_Xor:
12008 case BO_Or:
12009 break;
12010 }
12011
12012 // Combine the two ranges, but limit the result to the type in which we
12013 // performed the computation.
12014 QualType T = GetExprType(E);
12015 unsigned opWidth = C.getIntWidth(T);
12016 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
12017 InConstantContext, Approximate);
12018 if (!L)
12019 return std::nullopt;
12020
12021 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
12022 InConstantContext, Approximate);
12023 if (!R)
12024 return std::nullopt;
12025
12026 IntRange C = Combine(*L, *R);
12027 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
12028 C.Width = std::min(C.Width, MaxWidth);
12029 return C;
12030 }
12031
12032 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12033 switch (UO->getOpcode()) {
12034 // Boolean-valued operations are white-listed.
12035 case UO_LNot:
12036 return IntRange::forBoolType();
12037
12038 // Operations with opaque sources are black-listed.
12039 case UO_Deref:
12040 case UO_AddrOf: // should be impossible
12041 return IntRange::forValueOfType(C, GetExprType(E));
12042
12043 case UO_Minus: {
12044 if (E->getType()->isUnsignedIntegerType()) {
12045 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12046 Approximate);
12047 }
12048
12049 std::optional<IntRange> SubRange = TryGetExprRange(
12050 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12051
12052 if (!SubRange)
12053 return std::nullopt;
12054
12055 // If the range was previously non-negative, we need an extra bit for the
12056 // sign bit. Otherwise, we need an extra bit because the negation of the
12057 // most-negative value is one bit wider than that value.
12058 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
12059 }
12060
12061 case UO_Not: {
12062 if (E->getType()->isUnsignedIntegerType()) {
12063 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12064 Approximate);
12065 }
12066
12067 std::optional<IntRange> SubRange = TryGetExprRange(
12068 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12069
12070 if (!SubRange)
12071 return std::nullopt;
12072
12073 // The width increments by 1 if the sub-expression cannot be negative
12074 // since it now can be.
12075 return IntRange(
12076 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
12077 false);
12078 }
12079
12080 default:
12081 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12082 Approximate);
12083 }
12084 }
12085
12086 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12087 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
12088 Approximate);
12089
12090 if (const auto *BitField = E->getSourceBitField())
12091 return IntRange(BitField->getBitWidthValue(),
12092 BitField->getType()->isUnsignedIntegerOrEnumerationType());
12093
12094 if (GetExprType(E)->isVoidType())
12095 return std::nullopt;
12096
12097 return IntRange::forValueOfType(C, GetExprType(E));
12098}
12099
12100static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12101 bool InConstantContext,
12102 bool Approximate) {
12103 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
12104 Approximate);
12105}
12106
12107/// Checks whether the given value, which currently has the given
12108/// source semantics, has the same value when coerced through the
12109/// target semantics.
12110static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12111 const llvm::fltSemantics &Src,
12112 const llvm::fltSemantics &Tgt) {
12113 llvm::APFloat truncated = value;
12114
12115 bool ignored;
12116 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
12117 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
12118
12119 return truncated.bitwiseIsEqual(value);
12120}
12121
12122/// Checks whether the given value, which currently has the given
12123/// source semantics, has the same value when coerced through the
12124/// target semantics.
12125///
12126/// The value might be a vector of floats (or a complex number).
12127static bool IsSameFloatAfterCast(const APValue &value,
12128 const llvm::fltSemantics &Src,
12129 const llvm::fltSemantics &Tgt) {
12130 if (value.isFloat())
12131 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
12132
12133 if (value.isVector()) {
12134 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12135 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
12136 return false;
12137 return true;
12138 }
12139
12140 if (value.isMatrix()) {
12141 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
12142 if (!IsSameFloatAfterCast(value.getMatrixElt(i), Src, Tgt))
12143 return false;
12144 return true;
12145 }
12146
12147 assert(value.isComplexFloat());
12148 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
12149 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
12150}
12151
12152static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12153 bool IsListInit = false);
12154
12155static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
12156 // Suppress cases where we are comparing against an enum constant.
12157 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
12158 if (isa<EnumConstantDecl>(DR->getDecl()))
12159 return true;
12160
12161 // Suppress cases where the value is expanded from a macro, unless that macro
12162 // is how a language represents a boolean literal. This is the case in both C
12163 // and Objective-C.
12164 SourceLocation BeginLoc = E->getBeginLoc();
12165 if (BeginLoc.isMacroID()) {
12166 StringRef MacroName = Lexer::getImmediateMacroName(
12167 BeginLoc, S.getSourceManager(), S.getLangOpts());
12168 return MacroName != "YES" && MacroName != "NO" &&
12169 MacroName != "true" && MacroName != "false";
12170 }
12171
12172 return false;
12173}
12174
12175static bool isKnownToHaveUnsignedValue(const Expr *E) {
12176 return E->getType()->isIntegerType() &&
12177 (!E->getType()->isSignedIntegerType() ||
12179}
12180
12181namespace {
12182/// The promoted range of values of a type. In general this has the
12183/// following structure:
12184///
12185/// |-----------| . . . |-----------|
12186/// ^ ^ ^ ^
12187/// Min HoleMin HoleMax Max
12188///
12189/// ... where there is only a hole if a signed type is promoted to unsigned
12190/// (in which case Min and Max are the smallest and largest representable
12191/// values).
12192struct PromotedRange {
12193 // Min, or HoleMax if there is a hole.
12194 llvm::APSInt PromotedMin;
12195 // Max, or HoleMin if there is a hole.
12196 llvm::APSInt PromotedMax;
12197
12198 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12199 if (R.Width == 0)
12200 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12201 else if (R.Width >= BitWidth && !Unsigned) {
12202 // Promotion made the type *narrower*. This happens when promoting
12203 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12204 // Treat all values of 'signed int' as being in range for now.
12205 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12206 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12207 } else {
12208 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12209 .extOrTrunc(BitWidth);
12210 PromotedMin.setIsUnsigned(Unsigned);
12211
12212 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12213 .extOrTrunc(BitWidth);
12214 PromotedMax.setIsUnsigned(Unsigned);
12215 }
12216 }
12217
12218 // Determine whether this range is contiguous (has no hole).
12219 bool isContiguous() const { return PromotedMin <= PromotedMax; }
12220
12221 // Where a constant value is within the range.
12222 enum ComparisonResult {
12223 LT = 0x1,
12224 LE = 0x2,
12225 GT = 0x4,
12226 GE = 0x8,
12227 EQ = 0x10,
12228 NE = 0x20,
12229 InRangeFlag = 0x40,
12230
12231 Less = LE | LT | NE,
12232 Min = LE | InRangeFlag,
12233 InRange = InRangeFlag,
12234 Max = GE | InRangeFlag,
12235 Greater = GE | GT | NE,
12236
12237 OnlyValue = LE | GE | EQ | InRangeFlag,
12238 InHole = NE
12239 };
12240
12241 ComparisonResult compare(const llvm::APSInt &Value) const {
12242 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12243 Value.isUnsigned() == PromotedMin.isUnsigned());
12244 if (!isContiguous()) {
12245 assert(Value.isUnsigned() && "discontiguous range for signed compare");
12246 if (Value.isMinValue()) return Min;
12247 if (Value.isMaxValue()) return Max;
12248 if (Value >= PromotedMin) return InRange;
12249 if (Value <= PromotedMax) return InRange;
12250 return InHole;
12251 }
12252
12253 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12254 case -1: return Less;
12255 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12256 case 1:
12257 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12258 case -1: return InRange;
12259 case 0: return Max;
12260 case 1: return Greater;
12261 }
12262 }
12263
12264 llvm_unreachable("impossible compare result");
12265 }
12266
12267 static std::optional<StringRef>
12268 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12269 if (Op == BO_Cmp) {
12270 ComparisonResult LTFlag = LT, GTFlag = GT;
12271 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12272
12273 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12274 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12275 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12276 return std::nullopt;
12277 }
12278
12279 ComparisonResult TrueFlag, FalseFlag;
12280 if (Op == BO_EQ) {
12281 TrueFlag = EQ;
12282 FalseFlag = NE;
12283 } else if (Op == BO_NE) {
12284 TrueFlag = NE;
12285 FalseFlag = EQ;
12286 } else {
12287 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12288 TrueFlag = LT;
12289 FalseFlag = GE;
12290 } else {
12291 TrueFlag = GT;
12292 FalseFlag = LE;
12293 }
12294 if (Op == BO_GE || Op == BO_LE)
12295 std::swap(TrueFlag, FalseFlag);
12296 }
12297 if (R & TrueFlag)
12298 return StringRef("true");
12299 if (R & FalseFlag)
12300 return StringRef("false");
12301 return std::nullopt;
12302 }
12303};
12304}
12305
12306static bool HasEnumType(const Expr *E) {
12307 // Strip off implicit integral promotions.
12308 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12309 if (ICE->getCastKind() != CK_IntegralCast &&
12310 ICE->getCastKind() != CK_NoOp)
12311 break;
12312 E = ICE->getSubExpr();
12313 }
12314
12315 return E->getType()->isEnumeralType();
12316}
12317
12319 // The values of this enumeration are used in the diagnostics
12320 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12321 enum ConstantValueKind {
12322 Miscellaneous = 0,
12323 LiteralTrue,
12324 LiteralFalse
12325 };
12326 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12327 return BL->getValue() ? ConstantValueKind::LiteralTrue
12328 : ConstantValueKind::LiteralFalse;
12329 return ConstantValueKind::Miscellaneous;
12330}
12331
12334 const llvm::APSInt &Value,
12335 bool RhsConstant) {
12337 return false;
12338
12339 Expr *OriginalOther = Other;
12340
12341 Constant = Constant->IgnoreParenImpCasts();
12342 Other = Other->IgnoreParenImpCasts();
12343
12344 // Suppress warnings on tautological comparisons between values of the same
12345 // enumeration type. There are only two ways we could warn on this:
12346 // - If the constant is outside the range of representable values of
12347 // the enumeration. In such a case, we should warn about the cast
12348 // to enumeration type, not about the comparison.
12349 // - If the constant is the maximum / minimum in-range value. For an
12350 // enumeratin type, such comparisons can be meaningful and useful.
12351 if (Constant->getType()->isEnumeralType() &&
12352 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12353 return false;
12354
12355 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12356 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
12357 if (!OtherValueRange)
12358 return false;
12359
12360 QualType OtherT = Other->getType();
12361 if (const auto *AT = OtherT->getAs<AtomicType>())
12362 OtherT = AT->getValueType();
12363 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12364
12365 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12366 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12367 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12368 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
12369 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12370
12371 // Whether we're treating Other as being a bool because of the form of
12372 // expression despite it having another type (typically 'int' in C).
12373 bool OtherIsBooleanDespiteType =
12374 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12375 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12376 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12377
12378 // Check if all values in the range of possible values of this expression
12379 // lead to the same comparison outcome.
12380 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12381 Value.isUnsigned());
12382 auto Cmp = OtherPromotedValueRange.compare(Value);
12383 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12384 if (!Result)
12385 return false;
12386
12387 // Also consider the range determined by the type alone. This allows us to
12388 // classify the warning under the proper diagnostic group.
12389 bool TautologicalTypeCompare = false;
12390 {
12391 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12392 Value.isUnsigned());
12393 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12394 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12395 RhsConstant)) {
12396 TautologicalTypeCompare = true;
12397 Cmp = TypeCmp;
12399 }
12400 }
12401
12402 // Don't warn if the non-constant operand actually always evaluates to the
12403 // same value.
12404 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12405 return false;
12406
12407 // Suppress the diagnostic for an in-range comparison if the constant comes
12408 // from a macro or enumerator. We don't want to diagnose
12409 //
12410 // some_long_value <= INT_MAX
12411 //
12412 // when sizeof(int) == sizeof(long).
12413 bool InRange = Cmp & PromotedRange::InRangeFlag;
12414 if (InRange && IsEnumConstOrFromMacro(S, Constant))
12415 return false;
12416
12417 // A comparison of an unsigned bit-field against 0 is really a type problem,
12418 // even though at the type level the bit-field might promote to 'signed int'.
12419 if (Other->refersToBitField() && InRange && Value == 0 &&
12420 Other->getType()->isUnsignedIntegerOrEnumerationType())
12421 TautologicalTypeCompare = true;
12422
12423 // If this is a comparison to an enum constant, include that
12424 // constant in the diagnostic.
12425 const EnumConstantDecl *ED = nullptr;
12426 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
12427 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12428
12429 // Should be enough for uint128 (39 decimal digits)
12430 SmallString<64> PrettySourceValue;
12431 llvm::raw_svector_ostream OS(PrettySourceValue);
12432 if (ED) {
12433 OS << '\'' << *ED << "' (" << Value << ")";
12434 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12435 Constant->IgnoreParenImpCasts())) {
12436 OS << (BL->getValue() ? "YES" : "NO");
12437 } else {
12438 OS << Value;
12439 }
12440
12441 if (!TautologicalTypeCompare) {
12442 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12443 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12444 << E->getOpcodeStr() << OS.str() << *Result
12445 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12446 return true;
12447 }
12448
12449 if (IsObjCSignedCharBool) {
12451 S.PDiag(diag::warn_tautological_compare_objc_bool)
12452 << OS.str() << *Result);
12453 return true;
12454 }
12455
12456 // FIXME: We use a somewhat different formatting for the in-range cases and
12457 // cases involving boolean values for historical reasons. We should pick a
12458 // consistent way of presenting these diagnostics.
12459 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12460
12462 E->getOperatorLoc(), E,
12463 S.PDiag(!InRange ? diag::warn_out_of_range_compare
12464 : diag::warn_tautological_bool_compare)
12465 << OS.str() << classifyConstantValue(Constant) << OtherT
12466 << OtherIsBooleanDespiteType << *Result
12467 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12468 } else {
12469 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12470 unsigned Diag =
12471 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12472 ? (HasEnumType(OriginalOther)
12473 ? diag::warn_unsigned_enum_always_true_comparison
12474 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12475 : diag::warn_unsigned_always_true_comparison)
12476 : diag::warn_tautological_constant_compare;
12477
12478 S.Diag(E->getOperatorLoc(), Diag)
12479 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12480 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12481 }
12482
12483 return true;
12484}
12485
12486/// Analyze the operands of the given comparison. Implements the
12487/// fallback case from AnalyzeComparison.
12492
12493/// Implements -Wsign-compare.
12494///
12495/// \param E the binary operator to check for warnings
12497 // The type the comparison is being performed in.
12498 QualType T = E->getLHS()->getType();
12499
12500 // Only analyze comparison operators where both sides have been converted to
12501 // the same type.
12502 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12503 return AnalyzeImpConvsInComparison(S, E);
12504
12505 // Don't analyze value-dependent comparisons directly.
12506 if (E->isValueDependent())
12507 return AnalyzeImpConvsInComparison(S, E);
12508
12509 Expr *LHS = E->getLHS();
12510 Expr *RHS = E->getRHS();
12511
12512 if (T->isIntegralType(S.Context)) {
12513 std::optional<llvm::APSInt> RHSValue =
12515 std::optional<llvm::APSInt> LHSValue =
12517
12518 // We don't care about expressions whose result is a constant.
12519 if (RHSValue && LHSValue)
12520 return AnalyzeImpConvsInComparison(S, E);
12521
12522 // We only care about expressions where just one side is literal
12523 if ((bool)RHSValue ^ (bool)LHSValue) {
12524 // Is the constant on the RHS or LHS?
12525 const bool RhsConstant = (bool)RHSValue;
12526 Expr *Const = RhsConstant ? RHS : LHS;
12527 Expr *Other = RhsConstant ? LHS : RHS;
12528 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12529
12530 // Check whether an integer constant comparison results in a value
12531 // of 'true' or 'false'.
12532 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12533 return AnalyzeImpConvsInComparison(S, E);
12534 }
12535 }
12536
12537 if (!T->hasUnsignedIntegerRepresentation()) {
12538 // We don't do anything special if this isn't an unsigned integral
12539 // comparison: we're only interested in integral comparisons, and
12540 // signed comparisons only happen in cases we don't care to warn about.
12541 return AnalyzeImpConvsInComparison(S, E);
12542 }
12543
12544 LHS = LHS->IgnoreParenImpCasts();
12545 RHS = RHS->IgnoreParenImpCasts();
12546
12547 if (!S.getLangOpts().CPlusPlus) {
12548 // Avoid warning about comparison of integers with different signs when
12549 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12550 // the type of `E`.
12551 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12552 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12553 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12554 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12555 }
12556
12557 // Check to see if one of the (unmodified) operands is of different
12558 // signedness.
12559 Expr *signedOperand, *unsignedOperand;
12561 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12562 "unsigned comparison between two signed integer expressions?");
12563 signedOperand = LHS;
12564 unsignedOperand = RHS;
12565 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12566 signedOperand = RHS;
12567 unsignedOperand = LHS;
12568 } else {
12569 return AnalyzeImpConvsInComparison(S, E);
12570 }
12571
12572 // Otherwise, calculate the effective range of the signed operand.
12573 std::optional<IntRange> signedRange =
12575 /*Approximate=*/true);
12576 if (!signedRange)
12577 return;
12578
12579 // Go ahead and analyze implicit conversions in the operands. Note
12580 // that we skip the implicit conversions on both sides.
12583
12584 // If the signed range is non-negative, -Wsign-compare won't fire.
12585 if (signedRange->NonNegative)
12586 return;
12587
12588 // For (in)equality comparisons, if the unsigned operand is a
12589 // constant which cannot collide with a overflowed signed operand,
12590 // then reinterpreting the signed operand as unsigned will not
12591 // change the result of the comparison.
12592 if (E->isEqualityOp()) {
12593 unsigned comparisonWidth = S.Context.getIntWidth(T);
12594 std::optional<IntRange> unsignedRange = TryGetExprRange(
12595 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
12596 /*Approximate=*/true);
12597 if (!unsignedRange)
12598 return;
12599
12600 // We should never be unable to prove that the unsigned operand is
12601 // non-negative.
12602 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12603
12604 if (unsignedRange->Width < comparisonWidth)
12605 return;
12606 }
12607
12609 S.PDiag(diag::warn_mixed_sign_comparison)
12610 << LHS->getType() << RHS->getType()
12611 << LHS->getSourceRange() << RHS->getSourceRange());
12612}
12613
12614/// Analyzes an attempt to assign the given value to a bitfield.
12615///
12616/// Returns true if there was something fishy about the attempt.
12618 SourceLocation InitLoc) {
12619 assert(Bitfield->isBitField());
12620 if (Bitfield->isInvalidDecl())
12621 return false;
12622
12623 // White-list bool bitfields.
12624 QualType BitfieldType = Bitfield->getType();
12625 if (BitfieldType->isBooleanType())
12626 return false;
12627
12628 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12629 // If the underlying enum type was not explicitly specified as an unsigned
12630 // type and the enum contain only positive values, MSVC++ will cause an
12631 // inconsistency by storing this as a signed type.
12632 if (S.getLangOpts().CPlusPlus11 &&
12633 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12634 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12635 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12636 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12637 << BitfieldEnumDecl;
12638 }
12639 }
12640
12641 // Ignore value- or type-dependent expressions.
12642 if (Bitfield->getBitWidth()->isValueDependent() ||
12643 Bitfield->getBitWidth()->isTypeDependent() ||
12644 Init->isValueDependent() ||
12645 Init->isTypeDependent())
12646 return false;
12647
12648 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12649 unsigned FieldWidth = Bitfield->getBitWidthValue();
12650
12652 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12654 // The RHS is not constant. If the RHS has an enum type, make sure the
12655 // bitfield is wide enough to hold all the values of the enum without
12656 // truncation.
12657 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12658 const PreferredTypeAttr *PTAttr = nullptr;
12659 if (!ED) {
12660 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12661 if (PTAttr)
12662 ED = PTAttr->getType()->getAsEnumDecl();
12663 }
12664 if (ED) {
12665 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12666
12667 // Enum types are implicitly signed on Windows, so check if there are any
12668 // negative enumerators to see if the enum was intended to be signed or
12669 // not.
12670 bool SignedEnum = ED->getNumNegativeBits() > 0;
12671
12672 // Check for surprising sign changes when assigning enum values to a
12673 // bitfield of different signedness. If the bitfield is signed and we
12674 // have exactly the right number of bits to store this unsigned enum,
12675 // suggest changing the enum to an unsigned type. This typically happens
12676 // on Windows where unfixed enums always use an underlying type of 'int'.
12677 unsigned DiagID = 0;
12678 if (SignedEnum && !SignedBitfield) {
12679 DiagID =
12680 PTAttr == nullptr
12681 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12682 : diag::
12683 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12684 } else if (SignedBitfield && !SignedEnum &&
12685 ED->getNumPositiveBits() == FieldWidth) {
12686 DiagID =
12687 PTAttr == nullptr
12688 ? diag::warn_signed_bitfield_enum_conversion
12689 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12690 }
12691 if (DiagID) {
12692 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12693 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12694 SourceRange TypeRange =
12695 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12696 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12697 << SignedEnum << TypeRange;
12698 if (PTAttr)
12699 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12700 << ED;
12701 }
12702
12703 // Compute the required bitwidth. If the enum has negative values, we need
12704 // one more bit than the normal number of positive bits to represent the
12705 // sign bit.
12706 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12707 ED->getNumNegativeBits())
12708 : ED->getNumPositiveBits();
12709
12710 // Check the bitwidth.
12711 if (BitsNeeded > FieldWidth) {
12712 Expr *WidthExpr = Bitfield->getBitWidth();
12713 auto DiagID =
12714 PTAttr == nullptr
12715 ? diag::warn_bitfield_too_small_for_enum
12716 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12717 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12718 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12719 << BitsNeeded << ED << WidthExpr->getSourceRange();
12720 if (PTAttr)
12721 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12722 << ED;
12723 }
12724 }
12725
12726 return false;
12727 }
12728
12729 llvm::APSInt Value = Result.Val.getInt();
12730
12731 unsigned OriginalWidth = Value.getBitWidth();
12732
12733 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12734 // false positives where the user is demonstrating they intend to use the
12735 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12736 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12737 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12738 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12739 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12740 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
12741 S.findMacroSpelling(MaybeMacroLoc, "true"))
12742 return false;
12743 }
12744
12745 if (!Value.isSigned() || Value.isNegative())
12746 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12747 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12748 OriginalWidth = Value.getSignificantBits();
12749
12750 if (OriginalWidth <= FieldWidth)
12751 return false;
12752
12753 // Compute the value which the bitfield will contain.
12754 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12755 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12756
12757 // Check whether the stored value is equal to the original value.
12758 TruncatedValue = TruncatedValue.extend(OriginalWidth);
12759 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12760 return false;
12761
12762 std::string PrettyValue = toString(Value, 10);
12763 std::string PrettyTrunc = toString(TruncatedValue, 10);
12764
12765 S.Diag(InitLoc, OneAssignedToOneBitBitfield
12766 ? diag::warn_impcast_single_bit_bitield_precision_constant
12767 : diag::warn_impcast_bitfield_precision_constant)
12768 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12769 << Init->getSourceRange();
12770
12771 return true;
12772}
12773
12774/// Analyze the given simple or compound assignment for warning-worthy
12775/// operations.
12777 // Just recurse on the LHS.
12779
12780 // We want to recurse on the RHS as normal unless we're assigning to
12781 // a bitfield.
12782 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12783 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12784 E->getOperatorLoc())) {
12785 // Recurse, ignoring any implicit conversions on the RHS.
12787 E->getOperatorLoc());
12788 }
12789 }
12790
12791 // Set context flag for overflow behavior type assignment analysis, use RAII
12792 // pattern to handle nested assignments.
12793 llvm::SaveAndRestore OBTAssignmentContext(
12795
12797
12798 // Diagnose implicitly sequentially-consistent atomic assignment.
12799 if (E->getLHS()->getType()->isAtomicType())
12800 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12801}
12802
12803/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12804static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12805 QualType T, SourceLocation CContext, unsigned diag,
12806 bool PruneControlFlow = false) {
12807 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12808 // address space annotations isn't really useful. The warnings aren't because
12809 // you're converting a `private int` to `unsigned int`, it is because you're
12810 // conerting `int` to `unsigned int`.
12811 if (SourceType.hasAddressSpace())
12812 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
12813 if (T.hasAddressSpace())
12815 if (PruneControlFlow) {
12817 S.PDiag(diag)
12818 << SourceType << T << E->getSourceRange()
12819 << SourceRange(CContext));
12820 return;
12821 }
12822 S.Diag(E->getExprLoc(), diag)
12823 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12824}
12825
12826/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12827static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
12828 SourceLocation CContext, unsigned diag,
12829 bool PruneControlFlow = false) {
12830 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
12831}
12832
12833/// Diagnose an implicit cast from a floating point value to an integer value.
12834static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
12835 SourceLocation CContext) {
12836 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12837 bool PruneWarnings = S.inTemplateInstantiation();
12838
12839 const Expr *InnerE = E->IgnoreParenImpCasts();
12840 // We also want to warn on, e.g., "int i = -1.234"
12841 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
12842 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12843 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12844
12845 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12846
12847 llvm::APFloat Value(0.0);
12848 bool IsConstant =
12850 if (!IsConstant) {
12851 if (S.ObjC().isSignedCharBool(T)) {
12853 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12854 << E->getType());
12855 }
12856
12857 return DiagnoseImpCast(S, E, T, CContext,
12858 diag::warn_impcast_float_integer, PruneWarnings);
12859 }
12860
12861 bool isExact = false;
12862
12863 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12864 T->hasUnsignedIntegerRepresentation());
12865 llvm::APFloat::opStatus Result = Value.convertToInteger(
12866 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12867
12868 // FIXME: Force the precision of the source value down so we don't print
12869 // digits which are usually useless (we don't really care here if we
12870 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12871 // would automatically print the shortest representation, but it's a bit
12872 // tricky to implement.
12873 SmallString<16> PrettySourceValue;
12874 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12875 precision = (precision * 59 + 195) / 196;
12876 Value.toString(PrettySourceValue, precision);
12877
12878 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
12880 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12881 << PrettySourceValue);
12882 }
12883
12884 if (Result == llvm::APFloat::opOK && isExact) {
12885 if (IsLiteral) return;
12886 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12887 PruneWarnings);
12888 }
12889
12890 // Conversion of a floating-point value to a non-bool integer where the
12891 // integral part cannot be represented by the integer type is undefined.
12892 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12893 return DiagnoseImpCast(
12894 S, E, T, CContext,
12895 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12896 : diag::warn_impcast_float_to_integer_out_of_range,
12897 PruneWarnings);
12898
12899 unsigned DiagID = 0;
12900 if (IsLiteral) {
12901 // Warn on floating point literal to integer.
12902 DiagID = diag::warn_impcast_literal_float_to_integer;
12903 } else if (IntegerValue == 0) {
12904 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
12905 return DiagnoseImpCast(S, E, T, CContext,
12906 diag::warn_impcast_float_integer, PruneWarnings);
12907 }
12908 // Warn on non-zero to zero conversion.
12909 DiagID = diag::warn_impcast_float_to_integer_zero;
12910 } else {
12911 if (IntegerValue.isUnsigned()) {
12912 if (!IntegerValue.isMaxValue()) {
12913 return DiagnoseImpCast(S, E, T, CContext,
12914 diag::warn_impcast_float_integer, PruneWarnings);
12915 }
12916 } else { // IntegerValue.isSigned()
12917 if (!IntegerValue.isMaxSignedValue() &&
12918 !IntegerValue.isMinSignedValue()) {
12919 return DiagnoseImpCast(S, E, T, CContext,
12920 diag::warn_impcast_float_integer, PruneWarnings);
12921 }
12922 }
12923 // Warn on evaluatable floating point expression to integer conversion.
12924 DiagID = diag::warn_impcast_float_to_integer;
12925 }
12926
12927 SmallString<16> PrettyTargetValue;
12928 if (IsBool)
12929 PrettyTargetValue = Value.isZero() ? "false" : "true";
12930 else
12931 IntegerValue.toString(PrettyTargetValue);
12932
12933 if (PruneWarnings) {
12935 S.PDiag(DiagID)
12936 << E->getType() << T.getUnqualifiedType()
12937 << PrettySourceValue << PrettyTargetValue
12938 << E->getSourceRange() << SourceRange(CContext));
12939 } else {
12940 S.Diag(E->getExprLoc(), DiagID)
12941 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12942 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12943 }
12944}
12945
12946/// Analyze the given compound assignment for the possible losing of
12947/// floating-point precision.
12949 assert(isa<CompoundAssignOperator>(E) &&
12950 "Must be compound assignment operation");
12951 // Recurse on the LHS and RHS in here
12954
12955 if (E->getLHS()->getType()->isAtomicType())
12956 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12957
12958 // Now check the outermost expression
12959 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12960 const auto *RBT = cast<CompoundAssignOperator>(E)
12961 ->getComputationResultType()
12962 ->getAs<BuiltinType>();
12963
12964 // The below checks assume source is floating point.
12965 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12966
12967 // If source is floating point but target is an integer.
12968 if (ResultBT->isInteger())
12969 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12970 E->getExprLoc(), diag::warn_impcast_float_integer);
12971
12972 if (!ResultBT->isFloatingPoint())
12973 return;
12974
12975 // If both source and target are floating points, warn about losing precision.
12977 QualType(ResultBT, 0), QualType(RBT, 0));
12978 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12979 // warn about dropping FP rank.
12980 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12981 diag::warn_impcast_float_result_precision);
12982}
12983
12984static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12985 IntRange Range) {
12986 if (!Range.Width) return "0";
12987
12988 llvm::APSInt ValueInRange = Value;
12989 ValueInRange.setIsSigned(!Range.NonNegative);
12990 ValueInRange = ValueInRange.trunc(Range.Width);
12991 return toString(ValueInRange, 10);
12992}
12993
12994static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
12995 bool ToBool) {
12996 if (!isa<ImplicitCastExpr>(Ex))
12997 return false;
12998
12999 const Expr *InnerE = Ex->IgnoreParenImpCasts();
13001 const Type *Source =
13003 if (Target->isDependentType())
13004 return false;
13005
13006 const auto *FloatCandidateBT =
13007 dyn_cast<BuiltinType>(ToBool ? Source : Target);
13008 const Type *BoolCandidateType = ToBool ? Target : Source;
13009
13010 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
13011 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
13012}
13013
13014static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
13015 SourceLocation CC) {
13016 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
13017 const Expr *CurrA = TheCall->getArg(I);
13018 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
13019 continue;
13020
13021 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
13022 S, TheCall->getArg(I - 1), false));
13023 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
13024 S, TheCall->getArg(I + 1), false));
13025 if (IsSwapped) {
13026 // Warn on this floating-point to bool conversion.
13028 CurrA->getType(), CC,
13029 diag::warn_impcast_floating_point_to_bool);
13030 }
13031 }
13032}
13033
13035 SourceLocation CC) {
13036 // Don't warn on functions which have return type nullptr_t.
13037 if (isa<CallExpr>(E))
13038 return;
13039
13040 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
13041 const Expr *NewE = E->IgnoreParenImpCasts();
13042 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
13043 bool HasNullPtrType = NewE->getType()->isNullPtrType();
13044 if (!IsGNUNullExpr && !HasNullPtrType)
13045 return;
13046
13047 // Return if target type is a safe conversion.
13048 if (T->isAnyPointerType() || T->isBlockPointerType() ||
13049 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
13050 return;
13051
13052 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
13053 E->getExprLoc()))
13054 return;
13055
13057
13058 // Venture through the macro stacks to get to the source of macro arguments.
13059 // The new location is a better location than the complete location that was
13060 // passed in.
13061 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
13063
13064 // __null is usually wrapped in a macro. Go up a macro if that is the case.
13065 if (IsGNUNullExpr && Loc.isMacroID()) {
13066 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13067 Loc, S.SourceMgr, S.getLangOpts());
13068 if (MacroName == "NULL")
13070 }
13071
13072 // Only warn if the null and context location are in the same macro expansion.
13073 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
13074 return;
13075
13076 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
13077 << HasNullPtrType << T << SourceRange(CC)
13079 S.getFixItZeroLiteralForType(T, Loc));
13080}
13081
13082// Helper function to filter out cases for constant width constant conversion.
13083// Don't warn on char array initialization or for non-decimal values.
13085 SourceLocation CC) {
13086 // If initializing from a constant, and the constant starts with '0',
13087 // then it is a binary, octal, or hexadecimal. Allow these constants
13088 // to fill all the bits, even if there is a sign change.
13089 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
13090 const char FirstLiteralCharacter =
13091 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
13092 if (FirstLiteralCharacter == '0')
13093 return false;
13094 }
13095
13096 // If the CC location points to a '{', and the type is char, then assume
13097 // assume it is an array initialization.
13098 if (CC.isValid() && T->isCharType()) {
13099 const char FirstContextCharacter =
13101 if (FirstContextCharacter == '{')
13102 return false;
13103 }
13104
13105 return true;
13106}
13107
13109 const auto *IL = dyn_cast<IntegerLiteral>(E);
13110 if (!IL) {
13111 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
13112 if (UO->getOpcode() == UO_Minus)
13113 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13114 }
13115 }
13116
13117 return IL;
13118}
13119
13121 E = E->IgnoreParenImpCasts();
13122 SourceLocation ExprLoc = E->getExprLoc();
13123
13124 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13125 BinaryOperator::Opcode Opc = BO->getOpcode();
13127 // Do not diagnose unsigned shifts.
13128 if (Opc == BO_Shl) {
13129 const auto *LHS = getIntegerLiteral(BO->getLHS());
13130 const auto *RHS = getIntegerLiteral(BO->getRHS());
13131 if (LHS && LHS->getValue() == 0)
13132 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13133 else if (!E->isValueDependent() && LHS && RHS &&
13134 RHS->getValue().isNonNegative() &&
13136 S.Diag(ExprLoc, diag::warn_left_shift_always)
13137 << (Result.Val.getInt() != 0);
13138 else if (E->getType()->isSignedIntegerType())
13139 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
13142 ") != 0");
13143 }
13144 }
13145
13146 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13147 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13148 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13149 if (!LHS || !RHS)
13150 return;
13151 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13152 (RHS->getValue() == 0 || RHS->getValue() == 1))
13153 // Do not diagnose common idioms.
13154 return;
13155 if (LHS->getValue() != 0 && RHS->getValue() != 0)
13156 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13157 }
13158}
13159
13161 const Type *Target, Expr *E,
13162 QualType T,
13163 SourceLocation CC) {
13164 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
13165 Source != Target);
13166
13167 // Lone surrogates have a distinct representation in UTF-32.
13168 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
13169 // so don't warn on such conversion.
13170 if (Source->isChar16Type() && Target->isChar32Type())
13171 return;
13172
13176 llvm::APSInt Value(32);
13177 Value = Result.Val.getInt();
13178 bool IsASCII = Value <= 0x7F;
13179 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
13180 bool ConversionPreservesSemantics =
13181 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
13182
13183 if (!ConversionPreservesSemantics) {
13184 auto IsSingleCodeUnitCP = [](const QualType &T,
13185 const llvm::APSInt &Value) {
13186 if (T->isChar8Type())
13187 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
13188 if (T->isChar16Type())
13189 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
13190 assert(T->isChar32Type());
13191 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
13192 };
13193
13194 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
13195 << E->getType() << T
13196 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
13197 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
13198 }
13199 } else {
13200 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
13202 DiagnoseImpCast(S, E, T, CC,
13203 LosesPrecision ? diag::warn_impcast_unicode_precision
13204 : diag::warn_impcast_unicode_char_type);
13205 }
13206}
13207
13209 From = Context.getCanonicalType(From);
13210 To = Context.getCanonicalType(To);
13211 QualType MaybePointee = From->getPointeeType();
13212 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13213 From = MaybePointee;
13214 MaybePointee = To->getPointeeType();
13215 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13216 To = MaybePointee;
13217
13218 if (const auto *FromFn = From->getAs<FunctionType>()) {
13219 if (const auto *ToFn = To->getAs<FunctionType>()) {
13220 if (FromFn->getCFIUncheckedCalleeAttr() &&
13221 !ToFn->getCFIUncheckedCalleeAttr())
13222 return true;
13223 }
13224 }
13225 return false;
13226}
13227
13229 bool *ICContext, bool IsListInit) {
13230 if (E->isTypeDependent() || E->isValueDependent()) return;
13231
13232 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
13233 const Type *Target = Context.getCanonicalType(T).getTypePtr();
13234 if (Source == Target) return;
13235 if (Target->isDependentType()) return;
13236
13237 // If the conversion context location is invalid don't complain. We also
13238 // don't want to emit a warning if the issue occurs from the expansion of
13239 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13240 // delay this check as long as possible. Once we detect we are in that
13241 // scenario, we just return.
13242 if (CC.isInvalid())
13243 return;
13244
13245 if (Source->isAtomicType())
13246 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13247
13248 // Diagnose implicit casts to bool.
13249 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13250 if (isa<StringLiteral>(E))
13251 // Warn on string literal to bool. Checks for string literals in logical
13252 // and expressions, for instance, assert(0 && "error here"), are
13253 // prevented by a check in AnalyzeImplicitConversions().
13254 return DiagnoseImpCast(*this, E, T, CC,
13255 diag::warn_impcast_string_literal_to_bool);
13258 // This covers the literal expressions that evaluate to Objective-C
13259 // objects.
13260 return DiagnoseImpCast(*this, E, T, CC,
13261 diag::warn_impcast_objective_c_literal_to_bool);
13262 }
13263 if (Source->isPointerType() || Source->canDecayToPointerType()) {
13264 // Warn on pointer to bool conversion that is always true.
13266 SourceRange(CC));
13267 }
13268 }
13269
13271
13272 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13273 // is a typedef for signed char (macOS), then that constant value has to be 1
13274 // or 0.
13275 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
13278 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13280 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13281 << toString(Result.Val.getInt(), 10));
13282 }
13283 return;
13284 }
13285 }
13286
13287 // Check implicit casts from Objective-C collection literals to specialized
13288 // collection types, e.g., NSArray<NSString *> *.
13289 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13290 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
13291 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13292 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
13293
13294 // Strip complex types.
13295 if (isa<ComplexType>(Source)) {
13296 if (!isa<ComplexType>(Target)) {
13297 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13298 return;
13299
13300 if (!getLangOpts().CPlusPlus && Target->isVectorType()) {
13301 return DiagnoseImpCast(*this, E, T, CC,
13302 diag::err_impcast_incompatible_type);
13303 }
13304
13305 return DiagnoseImpCast(*this, E, T, CC,
13307 ? diag::err_impcast_complex_scalar
13308 : diag::warn_impcast_complex_scalar);
13309 }
13310
13311 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13312 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13313 }
13314
13315 // Strip vector types.
13316 if (isa<VectorType>(Source)) {
13317 if (Target->isSveVLSBuiltinType() &&
13318 (ARM().areCompatibleSveTypes(QualType(Target, 0),
13319 QualType(Source, 0)) ||
13320 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
13321 QualType(Source, 0))))
13322 return;
13323
13324 if (Target->isRVVVLSBuiltinType() &&
13325 (Context.areCompatibleRVVTypes(QualType(Target, 0),
13326 QualType(Source, 0)) ||
13327 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
13328 QualType(Source, 0))))
13329 return;
13330
13331 if (!isa<VectorType>(Target)) {
13332 if (SourceMgr.isInSystemMacro(CC))
13333 return;
13334 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
13335 }
13336 if (getLangOpts().HLSL &&
13337 Target->castAs<VectorType>()->getNumElements() <
13338 Source->castAs<VectorType>()->getNumElements()) {
13339 // Diagnose vector truncation but don't return. We may also want to
13340 // diagnose an element conversion.
13341 DiagnoseImpCast(*this, E, T, CC,
13342 diag::warn_hlsl_impcast_vector_truncation);
13343 }
13344
13345 // If the vector cast is cast between two vectors of the same size, it is
13346 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13347 if (!getLangOpts().HLSL &&
13348 Context.getTypeSize(Source) == Context.getTypeSize(Target))
13349 return;
13350
13351 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13352 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13353 }
13354 if (const auto *VecTy = dyn_cast<VectorType>(Target))
13355 Target = VecTy->getElementType().getTypePtr();
13356
13357 // Strip matrix types.
13358 if (isa<ConstantMatrixType>(Source)) {
13359 if (Target->isScalarType())
13360 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_matrix_scalar);
13361
13364 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13365 // Diagnose Matrix truncation but don't return. We may also want to
13366 // diagnose an element conversion.
13367 DiagnoseImpCast(*this, E, T, CC,
13368 diag::warn_hlsl_impcast_matrix_truncation);
13369 }
13370
13371 Source = cast<ConstantMatrixType>(Source)->getElementType().getTypePtr();
13372 Target = cast<ConstantMatrixType>(Target)->getElementType().getTypePtr();
13373 }
13374 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Target))
13375 Target = MatTy->getElementType().getTypePtr();
13376
13377 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13378 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13379
13380 // Strip SVE vector types
13381 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13382 // Need the original target type for vector type checks
13383 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13384 // Handle conversion from scalable to fixed when msve-vector-bits is
13385 // specified
13386 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
13387 QualType(Source, 0)) ||
13388 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
13389 QualType(Source, 0)))
13390 return;
13391
13392 // If the vector cast is cast between two vectors of the same size, it is
13393 // a bitcast, not a conversion.
13394 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
13395 return;
13396
13397 Source = SourceBT->getSveEltType(Context).getTypePtr();
13398 }
13399
13400 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13401 Target = TargetBT->getSveEltType(Context).getTypePtr();
13402
13403 // If the source is floating point...
13404 if (SourceBT && SourceBT->isFloatingPoint()) {
13405 // ...and the target is floating point...
13406 if (TargetBT && TargetBT->isFloatingPoint()) {
13407 // ...then warn if we're dropping FP rank.
13408
13410 QualType(SourceBT, 0), QualType(TargetBT, 0));
13411 if (Order > 0) {
13412 // Don't warn about float constants that are precisely
13413 // representable in the target type.
13414 Expr::EvalResult result;
13415 if (E->EvaluateAsRValue(result, Context)) {
13416 // Value might be a float, a float vector, or a float complex.
13418 result.Val,
13419 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13420 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13421 return;
13422 }
13423
13424 if (SourceMgr.isInSystemMacro(CC))
13425 return;
13426
13427 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
13428 }
13429 // ... or possibly if we're increasing rank, too
13430 else if (Order < 0) {
13431 if (SourceMgr.isInSystemMacro(CC))
13432 return;
13433
13434 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
13435 }
13436 return;
13437 }
13438
13439 // If the target is integral, always warn.
13440 if (TargetBT && TargetBT->isInteger()) {
13441 if (SourceMgr.isInSystemMacro(CC))
13442 return;
13443
13444 DiagnoseFloatingImpCast(*this, E, T, CC);
13445 }
13446
13447 // Detect the case where a call result is converted from floating-point to
13448 // to bool, and the final argument to the call is converted from bool, to
13449 // discover this typo:
13450 //
13451 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13452 //
13453 // FIXME: This is an incredibly special case; is there some more general
13454 // way to detect this class of misplaced-parentheses bug?
13455 if (Target->isBooleanType() && isa<CallExpr>(E)) {
13456 // Check last argument of function call to see if it is an
13457 // implicit cast from a type matching the type the result
13458 // is being cast to.
13459 CallExpr *CEx = cast<CallExpr>(E);
13460 if (unsigned NumArgs = CEx->getNumArgs()) {
13461 Expr *LastA = CEx->getArg(NumArgs - 1);
13462 Expr *InnerE = LastA->IgnoreParenImpCasts();
13463 if (isa<ImplicitCastExpr>(LastA) &&
13464 InnerE->getType()->isBooleanType()) {
13465 // Warn on this floating-point to bool conversion
13466 DiagnoseImpCast(*this, E, T, CC,
13467 diag::warn_impcast_floating_point_to_bool);
13468 }
13469 }
13470 }
13471 return;
13472 }
13473
13474 // Valid casts involving fixed point types should be accounted for here.
13475 if (Source->isFixedPointType()) {
13476 if (Target->isUnsaturatedFixedPointType()) {
13480 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13481 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
13482 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
13483 if (Value > MaxVal || Value < MinVal) {
13485 PDiag(diag::warn_impcast_fixed_point_range)
13486 << Value.toString() << T
13487 << E->getSourceRange()
13488 << clang::SourceRange(CC));
13489 return;
13490 }
13491 }
13492 } else if (Target->isIntegerType()) {
13496 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13497
13498 bool Overflowed;
13499 llvm::APSInt IntResult = FXResult.convertToInt(
13500 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
13501 &Overflowed);
13502
13503 if (Overflowed) {
13505 PDiag(diag::warn_impcast_fixed_point_range)
13506 << FXResult.toString() << T
13507 << E->getSourceRange()
13508 << clang::SourceRange(CC));
13509 return;
13510 }
13511 }
13512 }
13513 } else if (Target->isUnsaturatedFixedPointType()) {
13514 if (Source->isIntegerType()) {
13518 llvm::APSInt Value = Result.Val.getInt();
13519
13520 bool Overflowed;
13521 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13522 Value, Context.getFixedPointSemantics(T), &Overflowed);
13523
13524 if (Overflowed) {
13526 PDiag(diag::warn_impcast_fixed_point_range)
13527 << toString(Value, /*Radix=*/10) << T
13528 << E->getSourceRange()
13529 << clang::SourceRange(CC));
13530 return;
13531 }
13532 }
13533 }
13534 }
13535
13536 // If we are casting an integer type to a floating point type without
13537 // initialization-list syntax, we might lose accuracy if the floating
13538 // point type has a narrower significand than the integer type.
13539 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13540 TargetBT->isFloatingType() && !IsListInit) {
13541 // Determine the number of precision bits in the source integer type.
13542 std::optional<IntRange> SourceRange =
13544 /*Approximate=*/true);
13545 if (!SourceRange)
13546 return;
13547 unsigned int SourcePrecision = SourceRange->Width;
13548
13549 // Determine the number of precision bits in the
13550 // target floating point type.
13551 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13552 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13553
13554 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13555 SourcePrecision > TargetPrecision) {
13556
13557 if (std::optional<llvm::APSInt> SourceInt =
13559 // If the source integer is a constant, convert it to the target
13560 // floating point type. Issue a warning if the value changes
13561 // during the whole conversion.
13562 llvm::APFloat TargetFloatValue(
13563 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13564 llvm::APFloat::opStatus ConversionStatus =
13565 TargetFloatValue.convertFromAPInt(
13566 *SourceInt, SourceBT->isSignedInteger(),
13567 llvm::APFloat::rmNearestTiesToEven);
13568
13569 if (ConversionStatus != llvm::APFloat::opOK) {
13570 SmallString<32> PrettySourceValue;
13571 SourceInt->toString(PrettySourceValue, 10);
13572 SmallString<32> PrettyTargetValue;
13573 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13574
13576 E->getExprLoc(), E,
13577 PDiag(diag::warn_impcast_integer_float_precision_constant)
13578 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13579 << E->getSourceRange() << clang::SourceRange(CC));
13580 }
13581 } else {
13582 // Otherwise, the implicit conversion may lose precision.
13583 DiagnoseImpCast(*this, E, T, CC,
13584 diag::warn_impcast_integer_float_precision);
13585 }
13586 }
13587 }
13588
13589 DiagnoseNullConversion(*this, E, T, CC);
13590
13592
13593 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13594 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
13595 return;
13596 }
13597
13598 if (Target->isBooleanType())
13599 DiagnoseIntInBoolContext(*this, E);
13600
13602 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
13603 << QualType(Source, 0) << QualType(Target, 0);
13604 }
13605
13606 if (!Source->isIntegerType() || !Target->isIntegerType())
13607 return;
13608
13609 // TODO: remove this early return once the false positives for constant->bool
13610 // in templates, macros, etc, are reduced or removed.
13611 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13612 return;
13613
13614 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
13615 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13617 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13618 << E->getType());
13619 }
13620 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13621 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
13622 if (!LikelySourceRange)
13623 return;
13624
13625 IntRange SourceTypeRange =
13626 IntRange::forTargetOfCanonicalType(Context, Source);
13627 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
13628
13629 if (LikelySourceRange->Width > TargetRange.Width) {
13630 // Check if target is a wrapping OBT - if so, don't warn about constant
13631 // conversion as this type may be used intentionally with implicit
13632 // truncation, especially during assignments.
13633 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13634 if (TargetOBT->isWrapKind()) {
13635 return;
13636 }
13637 }
13638
13639 // Check if source expression has an explicit __ob_wrap cast because if so,
13640 // wrapping was explicitly requested and we shouldn't warn
13641 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
13642 if (SourceOBT->isWrapKind()) {
13643 return;
13644 }
13645 }
13646
13647 // If the source is a constant, use a default-on diagnostic.
13648 // TODO: this should happen for bitfield stores, too.
13652 llvm::APSInt Value(32);
13653 Value = Result.Val.getInt();
13654
13655 if (SourceMgr.isInSystemMacro(CC))
13656 return;
13657
13658 std::string PrettySourceValue = toString(Value, 10);
13659 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13660
13662 PDiag(diag::warn_impcast_integer_precision_constant)
13663 << PrettySourceValue << PrettyTargetValue
13664 << E->getType() << T << E->getSourceRange()
13665 << SourceRange(CC));
13666 return;
13667 }
13668
13669 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13670 if (SourceMgr.isInSystemMacro(CC))
13671 return;
13672
13673 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
13674 if (UO->getOpcode() == UO_Minus)
13675 return DiagnoseImpCast(
13676 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
13677 }
13678
13679 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
13680 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
13681 /* pruneControlFlow */ true);
13682 return DiagnoseImpCast(*this, E, T, CC,
13683 diag::warn_impcast_integer_precision);
13684 }
13685
13686 if (TargetRange.Width > SourceTypeRange.Width) {
13687 if (auto *UO = dyn_cast<UnaryOperator>(E))
13688 if (UO->getOpcode() == UO_Minus)
13689 if (Source->isUnsignedIntegerType()) {
13690 if (Target->isUnsignedIntegerType())
13691 return DiagnoseImpCast(*this, E, T, CC,
13692 diag::warn_impcast_high_order_zero_bits);
13693 if (Target->isSignedIntegerType())
13694 return DiagnoseImpCast(*this, E, T, CC,
13695 diag::warn_impcast_nonnegative_result);
13696 }
13697 }
13698
13699 if (TargetRange.Width == LikelySourceRange->Width &&
13700 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13701 Source->isSignedIntegerType()) {
13702 // Warn when doing a signed to signed conversion, warn if the positive
13703 // source value is exactly the width of the target type, which will
13704 // cause a negative value to be stored.
13705
13708 !SourceMgr.isInSystemMacro(CC)) {
13709 llvm::APSInt Value = Result.Val.getInt();
13710 if (isSameWidthConstantConversion(*this, E, T, CC)) {
13711 std::string PrettySourceValue = toString(Value, 10);
13712 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13713
13714 Diag(E->getExprLoc(),
13715 PDiag(diag::warn_impcast_integer_precision_constant)
13716 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13717 << E->getSourceRange() << SourceRange(CC));
13718 return;
13719 }
13720 }
13721
13722 // Fall through for non-constants to give a sign conversion warning.
13723 }
13724
13725 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
13726 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13727 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13728 LikelySourceRange->Width == TargetRange.Width))) {
13729 if (SourceMgr.isInSystemMacro(CC))
13730 return;
13731
13732 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13733 TargetBT->isInteger() &&
13734 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13735 return;
13736 }
13737
13738 unsigned DiagID = diag::warn_impcast_integer_sign;
13739
13740 // Traditionally, gcc has warned about this under -Wsign-compare.
13741 // We also want to warn about it in -Wconversion.
13742 // So if -Wconversion is off, use a completely identical diagnostic
13743 // in the sign-compare group.
13744 // The conditional-checking code will
13745 if (ICContext) {
13746 DiagID = diag::warn_impcast_integer_sign_conditional;
13747 *ICContext = true;
13748 }
13749
13750 DiagnoseImpCast(*this, E, T, CC, DiagID);
13751 }
13752
13753 // If we're implicitly converting from an integer into an enumeration, that
13754 // is valid in C but invalid in C++.
13755 QualType SourceType = E->getEnumCoercedType(Context);
13756 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13757 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
13758 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
13759
13760 // Diagnose conversions between different enumeration types.
13761 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13762 // type, to give us better diagnostics.
13763 Source = Context.getCanonicalType(SourceType).getTypePtr();
13764
13765 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13766 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13767 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13768 TargetEnum->getDecl()->hasNameForLinkage() &&
13769 SourceEnum != TargetEnum) {
13770 if (SourceMgr.isInSystemMacro(CC))
13771 return;
13772
13773 return DiagnoseImpCast(*this, E, SourceType, T, CC,
13774 diag::warn_impcast_different_enum_types);
13775 }
13776}
13777
13779 SourceLocation CC, QualType T);
13780
13782 SourceLocation CC, bool &ICContext) {
13783 E = E->IgnoreParenImpCasts();
13784 // Diagnose incomplete type for second or third operand in C.
13785 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13786 S.RequireCompleteExprType(E, diag::err_incomplete_type);
13787
13788 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13789 return CheckConditionalOperator(S, CO, CC, T);
13790
13792 if (E->getType() != T)
13793 return S.CheckImplicitConversion(E, T, CC, &ICContext);
13794}
13795
13797 SourceLocation CC, QualType T) {
13799
13800 Expr *TrueExpr = E->getTrueExpr();
13801 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13802 TrueExpr = BCO->getCommon();
13803
13804 bool Suspicious = false;
13805 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13806 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13807
13808 if (T->isBooleanType())
13810
13811 // If -Wconversion would have warned about either of the candidates
13812 // for a signedness conversion to the context type...
13813 if (!Suspicious) return;
13814
13815 // ...but it's currently ignored...
13816 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13817 return;
13818
13819 // ...then check whether it would have warned about either of the
13820 // candidates for a signedness conversion to the condition type.
13821 if (E->getType() == T) return;
13822
13823 Suspicious = false;
13824 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
13825 &Suspicious);
13826 if (!Suspicious)
13828 E->getType(), CC, &Suspicious);
13829}
13830
13831/// Check conversion of given expression to boolean.
13832/// Input argument E is a logical expression.
13834 // Run the bool-like conversion checks only for C since there bools are
13835 // still not used as the return type from "boolean" operators or as the input
13836 // type for conditional operators.
13837 if (S.getLangOpts().CPlusPlus)
13838 return;
13840 return;
13842}
13843
13844namespace {
13845struct AnalyzeImplicitConversionsWorkItem {
13846 Expr *E;
13847 SourceLocation CC;
13848 bool IsListInit;
13849};
13850}
13851
13853 Sema &S, Expr *E, QualType T, SourceLocation CC,
13854 bool ExtraCheckForImplicitConversion,
13856 E = E->IgnoreParenImpCasts();
13857 WorkList.push_back({E, CC, false});
13858
13859 if (ExtraCheckForImplicitConversion && E->getType() != T)
13860 S.CheckImplicitConversion(E, T, CC);
13861}
13862
13863/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13864/// that should be visited are added to WorkList.
13866 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13868 Expr *OrigE = Item.E;
13869 SourceLocation CC = Item.CC;
13870
13871 QualType T = OrigE->getType();
13872 Expr *E = OrigE->IgnoreParenImpCasts();
13873
13874 // Propagate whether we are in a C++ list initialization expression.
13875 // If so, we do not issue warnings for implicit int-float conversion
13876 // precision loss, because C++11 narrowing already handles it.
13877 //
13878 // HLSL's initialization lists are special, so they shouldn't observe the C++
13879 // behavior here.
13880 bool IsListInit =
13881 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
13882 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
13883
13884 if (E->isTypeDependent() || E->isValueDependent())
13885 return;
13886
13887 Expr *SourceExpr = E;
13888 // Examine, but don't traverse into the source expression of an
13889 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13890 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13891 // evaluate it in the context of checking the specific conversion to T though.
13892 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13893 if (auto *Src = OVE->getSourceExpr())
13894 SourceExpr = Src;
13895
13896 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13897 if (UO->getOpcode() == UO_Not &&
13898 UO->getSubExpr()->isKnownToHaveBooleanValue())
13899 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13900 << OrigE->getSourceRange() << T->isBooleanType()
13901 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13902
13903 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
13904 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13905 BO->getLHS()->isKnownToHaveBooleanValue() &&
13906 BO->getRHS()->isKnownToHaveBooleanValue() &&
13907 BO->getLHS()->HasSideEffects(S.Context) &&
13908 BO->getRHS()->HasSideEffects(S.Context)) {
13910 const LangOptions &LO = S.getLangOpts();
13911 SourceLocation BLoc = BO->getOperatorLoc();
13912 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
13913 StringRef SR = clang::Lexer::getSourceText(
13914 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
13915 // To reduce false positives, only issue the diagnostic if the operator
13916 // is explicitly spelled as a punctuator. This suppresses the diagnostic
13917 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
13918 // in C, along with other macro spellings the user might invent.
13919 if (SR.str() == "&" || SR.str() == "|") {
13920
13921 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13922 << (BO->getOpcode() == BO_And ? "&" : "|")
13923 << OrigE->getSourceRange()
13925 BO->getOperatorLoc(),
13926 (BO->getOpcode() == BO_And ? "&&" : "||"));
13927 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13928 }
13929 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
13930 /// Analyze the given comma operator. The basic idea behind the analysis
13931 /// is to analyze the left and right operands slightly differently. The
13932 /// left operand needs to check whether the operand itself has an implicit
13933 /// conversion, but not whether the left operand induces an implicit
13934 /// conversion for the entire comma expression itself. This is similar to
13935 /// how CheckConditionalOperand behaves; it's as-if the correct operand
13936 /// were directly used for the implicit conversion check.
13937 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
13938 /*ExtraCheckForImplicitConversion=*/false, WorkList);
13939 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
13940 /*ExtraCheckForImplicitConversion=*/true, WorkList);
13941 return;
13942 }
13943 }
13944
13945 // For conditional operators, we analyze the arguments as if they
13946 // were being fed directly into the output.
13947 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13948 CheckConditionalOperator(S, CO, CC, T);
13949 return;
13950 }
13951
13952 // Check implicit argument conversions for function calls.
13953 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
13955
13956 // Go ahead and check any implicit conversions we might have skipped.
13957 // The non-canonical typecheck is just an optimization;
13958 // CheckImplicitConversion will filter out dead implicit conversions.
13959 if (SourceExpr->getType() != T)
13960 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
13961
13962 // Now continue drilling into this expression.
13963
13964 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13965 // The bound subexpressions in a PseudoObjectExpr are not reachable
13966 // as transitive children.
13967 // FIXME: Use a more uniform representation for this.
13968 for (auto *SE : POE->semantics())
13969 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13970 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13971 }
13972
13973 // Skip past explicit casts.
13974 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13975 E = CE->getSubExpr();
13976 // In the special case of a C++ function-style cast with braces,
13977 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
13978 // initializer. This InitListExpr basically belongs to the cast itself, so
13979 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
13981 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
13982 if (InitListE->getNumInits() == 1) {
13983 E = InitListE->getInit(0);
13984 }
13985 }
13986 }
13987 E = E->IgnoreParenImpCasts();
13988 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13989 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13990 WorkList.push_back({E, CC, IsListInit});
13991 return;
13992 }
13993
13994 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
13995 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
13996 // The base expression is only used to initialize the parameter for
13997 // arguments to `inout` parameters, so we only traverse down the base
13998 // expression for `inout` cases.
13999 if (OutArgE->isInOut())
14000 WorkList.push_back(
14001 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
14002 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
14003 return;
14004 }
14005
14006 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14007 // Do a somewhat different check with comparison operators.
14008 if (BO->isComparisonOp())
14009 return AnalyzeComparison(S, BO);
14010
14011 // And with simple assignments.
14012 if (BO->getOpcode() == BO_Assign)
14013 return AnalyzeAssignment(S, BO);
14014 // And with compound assignments.
14015 if (BO->isAssignmentOp())
14016 return AnalyzeCompoundAssignment(S, BO);
14017 }
14018
14019 // These break the otherwise-useful invariant below. Fortunately,
14020 // we don't really need to recurse into them, because any internal
14021 // expressions should have been analyzed already when they were
14022 // built into statements.
14023 if (isa<StmtExpr>(E)) return;
14024
14025 // Don't descend into unevaluated contexts.
14026 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
14027
14028 // Now just recurse over the expression's children.
14029 CC = E->getExprLoc();
14030 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
14031 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
14032 for (Stmt *SubStmt : E->children()) {
14033 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
14034 if (!ChildExpr)
14035 continue;
14036
14037 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
14038 if (ChildExpr == CSE->getOperand())
14039 // Do not recurse over a CoroutineSuspendExpr's operand.
14040 // The operand is also a subexpression of getCommonExpr(), and
14041 // recursing into it directly would produce duplicate diagnostics.
14042 continue;
14043
14044 if (IsLogicalAndOperator &&
14046 // Ignore checking string literals that are in logical and operators.
14047 // This is a common pattern for asserts.
14048 continue;
14049 WorkList.push_back({ChildExpr, CC, IsListInit});
14050 }
14051
14052 if (BO && BO->isLogicalOp()) {
14053 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
14054 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14055 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14056
14057 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
14058 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14059 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14060 }
14061
14062 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
14063 if (U->getOpcode() == UO_LNot) {
14064 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
14065 } else if (U->getOpcode() != UO_AddrOf) {
14066 if (U->getSubExpr()->getType()->isAtomicType())
14067 S.Diag(U->getSubExpr()->getBeginLoc(),
14068 diag::warn_atomic_implicit_seq_cst);
14069 }
14070 }
14071}
14072
14073/// AnalyzeImplicitConversions - Find and report any interesting
14074/// implicit conversions in the given expression. There are a couple
14075/// of competing diagnostics here, -Wconversion and -Wsign-compare.
14077 bool IsListInit/*= false*/) {
14079 WorkList.push_back({OrigE, CC, IsListInit});
14080 while (!WorkList.empty())
14081 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
14082}
14083
14084// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
14085// Returns true when emitting a warning about taking the address of a reference.
14086static bool CheckForReference(Sema &SemaRef, const Expr *E,
14087 const PartialDiagnostic &PD) {
14088 E = E->IgnoreParenImpCasts();
14089
14090 const FunctionDecl *FD = nullptr;
14091
14092 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14093 if (!DRE->getDecl()->getType()->isReferenceType())
14094 return false;
14095 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14096 if (!M->getMemberDecl()->getType()->isReferenceType())
14097 return false;
14098 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
14099 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
14100 return false;
14101 FD = Call->getDirectCallee();
14102 } else {
14103 return false;
14104 }
14105
14106 SemaRef.Diag(E->getExprLoc(), PD);
14107
14108 // If possible, point to location of function.
14109 if (FD) {
14110 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
14111 }
14112
14113 return true;
14114}
14115
14116// Returns true if the SourceLocation is expanded from any macro body.
14117// Returns false if the SourceLocation is invalid, is from not in a macro
14118// expansion, or is from expanded from a top-level macro argument.
14120 if (Loc.isInvalid())
14121 return false;
14122
14123 while (Loc.isMacroID()) {
14124 if (SM.isMacroBodyExpansion(Loc))
14125 return true;
14126 Loc = SM.getImmediateMacroCallerLoc(Loc);
14127 }
14128
14129 return false;
14130}
14131
14134 bool IsEqual, SourceRange Range) {
14135 if (!E)
14136 return;
14137
14138 // Don't warn inside macros.
14139 if (E->getExprLoc().isMacroID()) {
14141 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
14142 IsInAnyMacroBody(SM, Range.getBegin()))
14143 return;
14144 }
14145 E = E->IgnoreImpCasts();
14146
14147 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14148
14149 if (isa<CXXThisExpr>(E)) {
14150 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14151 : diag::warn_this_bool_conversion;
14152 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14153 return;
14154 }
14155
14156 bool IsAddressOf = false;
14157
14158 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
14159 if (UO->getOpcode() != UO_AddrOf)
14160 return;
14161 IsAddressOf = true;
14162 E = UO->getSubExpr();
14163 }
14164
14165 if (IsAddressOf) {
14166 unsigned DiagID = IsCompare
14167 ? diag::warn_address_of_reference_null_compare
14168 : diag::warn_address_of_reference_bool_conversion;
14169 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14170 << IsEqual;
14171 if (CheckForReference(*this, E, PD)) {
14172 return;
14173 }
14174 }
14175
14176 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14177 bool IsParam = isa<NonNullAttr>(NonnullAttr);
14178 std::string Str;
14179 llvm::raw_string_ostream S(Str);
14180 E->printPretty(S, nullptr, getPrintingPolicy());
14181 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14182 : diag::warn_cast_nonnull_to_bool;
14183 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
14184 << E->getSourceRange() << Range << IsEqual;
14185 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
14186 };
14187
14188 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14189 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
14190 if (auto *Callee = Call->getDirectCallee()) {
14191 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14192 ComplainAboutNonnullParamOrCall(A);
14193 return;
14194 }
14195 }
14196 }
14197
14198 // Complain if we are converting a lambda expression to a boolean value
14199 // outside of instantiation.
14200 if (!inTemplateInstantiation()) {
14201 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
14202 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
14203 MRecordDecl && MRecordDecl->isLambda()) {
14204 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
14205 << /*LambdaPointerConversionOperatorType=*/3
14206 << MRecordDecl->getSourceRange() << Range << IsEqual;
14207 return;
14208 }
14209 }
14210 }
14211
14212 // Expect to find a single Decl. Skip anything more complicated.
14213 ValueDecl *D = nullptr;
14214 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
14215 D = R->getDecl();
14216 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14217 D = M->getMemberDecl();
14218 }
14219
14220 // Weak Decls can be null.
14221 if (!D || D->isWeak())
14222 return;
14223
14224 // Check for parameter decl with nonnull attribute
14225 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
14226 if (getCurFunction() &&
14227 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
14228 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14229 ComplainAboutNonnullParamOrCall(A);
14230 return;
14231 }
14232
14233 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
14234 // Skip function template not specialized yet.
14236 return;
14237 auto ParamIter = llvm::find(FD->parameters(), PV);
14238 assert(ParamIter != FD->param_end());
14239 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
14240
14241 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14242 if (!NonNull->args_size()) {
14243 ComplainAboutNonnullParamOrCall(NonNull);
14244 return;
14245 }
14246
14247 for (const ParamIdx &ArgNo : NonNull->args()) {
14248 if (ArgNo.getASTIndex() == ParamNo) {
14249 ComplainAboutNonnullParamOrCall(NonNull);
14250 return;
14251 }
14252 }
14253 }
14254 }
14255 }
14256 }
14257
14258 QualType T = D->getType();
14259 const bool IsArray = T->isArrayType();
14260 const bool IsFunction = T->isFunctionType();
14261
14262 // Address of function is used to silence the function warning.
14263 if (IsAddressOf && IsFunction) {
14264 return;
14265 }
14266
14267 // Found nothing.
14268 if (!IsAddressOf && !IsFunction && !IsArray)
14269 return;
14270
14271 // Pretty print the expression for the diagnostic.
14272 std::string Str;
14273 llvm::raw_string_ostream S(Str);
14274 E->printPretty(S, nullptr, getPrintingPolicy());
14275
14276 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14277 : diag::warn_impcast_pointer_to_bool;
14278 enum {
14279 AddressOf,
14280 FunctionPointer,
14281 ArrayPointer
14282 } DiagType;
14283 if (IsAddressOf)
14284 DiagType = AddressOf;
14285 else if (IsFunction)
14286 DiagType = FunctionPointer;
14287 else if (IsArray)
14288 DiagType = ArrayPointer;
14289 else
14290 llvm_unreachable("Could not determine diagnostic.");
14291 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14292 << Range << IsEqual;
14293
14294 if (!IsFunction)
14295 return;
14296
14297 // Suggest '&' to silence the function warning.
14298 Diag(E->getExprLoc(), diag::note_function_warning_silence)
14300
14301 // Check to see if '()' fixit should be emitted.
14302 QualType ReturnType;
14303 UnresolvedSet<4> NonTemplateOverloads;
14304 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14305 if (ReturnType.isNull())
14306 return;
14307
14308 if (IsCompare) {
14309 // There are two cases here. If there is null constant, the only suggest
14310 // for a pointer return type. If the null is 0, then suggest if the return
14311 // type is a pointer or an integer type.
14312 if (!ReturnType->isPointerType()) {
14313 if (NullKind == Expr::NPCK_ZeroExpression ||
14314 NullKind == Expr::NPCK_ZeroLiteral) {
14315 if (!ReturnType->isIntegerType())
14316 return;
14317 } else {
14318 return;
14319 }
14320 }
14321 } else { // !IsCompare
14322 // For function to bool, only suggest if the function pointer has bool
14323 // return type.
14324 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14325 return;
14326 }
14327 Diag(E->getExprLoc(), diag::note_function_to_function_call)
14329}
14330
14332 SourceLocation CC) {
14333 QualType Source = E->getType();
14334 QualType Target = T;
14335
14336 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14337 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14338 // Overflow behavior type is being stripped - issue warning
14339 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14340 Target->isUnsignedIntegerType()) {
14341 // For unsigned wrap to unsigned conversions, use pedantic version
14342 unsigned DiagId =
14344 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14345 : diag::warn_impcast_overflow_behavior_pedantic;
14346 DiagnoseImpCast(*this, E, T, CC, DiagId);
14347 } else {
14348 unsigned DiagId = InOverflowBehaviorAssignmentContext
14349 ? diag::warn_impcast_overflow_behavior_assignment
14350 : diag::warn_impcast_overflow_behavior;
14351 DiagnoseImpCast(*this, E, T, CC, DiagId);
14352 }
14353 }
14354 }
14355
14356 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14357 if (TargetOBT->isWrapKind()) {
14358 return true;
14359 }
14360 }
14361
14362 return false;
14363}
14364
14365void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14366 // Don't diagnose in unevaluated contexts.
14368 return;
14369
14370 // Don't diagnose for value- or type-dependent expressions.
14371 if (E->isTypeDependent() || E->isValueDependent())
14372 return;
14373
14374 // Check for array bounds violations in cases where the check isn't triggered
14375 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14376 // ArraySubscriptExpr is on the RHS of a variable initialization.
14377 CheckArrayAccess(E);
14378
14379 // This is not the right CC for (e.g.) a variable initialization.
14380 AnalyzeImplicitConversions(*this, E, CC);
14381}
14382
14383void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14384 ::CheckBoolLikeConversion(*this, E, CC);
14385}
14386
14387void Sema::CheckForIntOverflow (const Expr *E) {
14388 // Use a work list to deal with nested struct initializers.
14389 SmallVector<const Expr *, 2> Exprs(1, E);
14390
14391 do {
14392 const Expr *OriginalE = Exprs.pop_back_val();
14393 const Expr *E = OriginalE->IgnoreParenCasts();
14394
14395 if (isa<BinaryOperator>(E) ||
14396 (isa<UnaryOperator>(E) && cast<UnaryOperator>(E)->canOverflow())) {
14398 continue;
14399 }
14400
14401 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
14402 Exprs.append(InitList->inits().begin(), InitList->inits().end());
14403 else if (isa<ObjCBoxedExpr>(OriginalE))
14405 else if (const auto *Call = dyn_cast<CallExpr>(E))
14406 Exprs.append(Call->arg_begin(), Call->arg_end());
14407 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
14408 Exprs.append(Message->arg_begin(), Message->arg_end());
14409 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
14410 Exprs.append(Construct->arg_begin(), Construct->arg_end());
14411 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
14412 Exprs.push_back(Temporary->getSubExpr());
14413 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
14414 Exprs.push_back(Array->getIdx());
14415 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
14416 Exprs.push_back(Compound->getInitializer());
14417 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
14418 New && New->isArray()) {
14419 if (auto ArraySize = New->getArraySize())
14420 Exprs.push_back(*ArraySize);
14421 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
14422 Exprs.push_back(MTE->getSubExpr());
14423 } while (!Exprs.empty());
14424}
14425
14426namespace {
14427
14428/// Visitor for expressions which looks for unsequenced operations on the
14429/// same object.
14430class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14431 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14432
14433 /// A tree of sequenced regions within an expression. Two regions are
14434 /// unsequenced if one is an ancestor or a descendent of the other. When we
14435 /// finish processing an expression with sequencing, such as a comma
14436 /// expression, we fold its tree nodes into its parent, since they are
14437 /// unsequenced with respect to nodes we will visit later.
14438 class SequenceTree {
14439 struct Value {
14440 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14441 unsigned Parent : 31;
14442 LLVM_PREFERRED_TYPE(bool)
14443 unsigned Merged : 1;
14444 };
14445 SmallVector<Value, 8> Values;
14446
14447 public:
14448 /// A region within an expression which may be sequenced with respect
14449 /// to some other region.
14450 class Seq {
14451 friend class SequenceTree;
14452
14453 unsigned Index;
14454
14455 explicit Seq(unsigned N) : Index(N) {}
14456
14457 public:
14458 Seq() : Index(0) {}
14459 };
14460
14461 SequenceTree() { Values.push_back(Value(0)); }
14462 Seq root() const { return Seq(0); }
14463
14464 /// Create a new sequence of operations, which is an unsequenced
14465 /// subset of \p Parent. This sequence of operations is sequenced with
14466 /// respect to other children of \p Parent.
14467 Seq allocate(Seq Parent) {
14468 Values.push_back(Value(Parent.Index));
14469 return Seq(Values.size() - 1);
14470 }
14471
14472 /// Merge a sequence of operations into its parent.
14473 void merge(Seq S) {
14474 Values[S.Index].Merged = true;
14475 }
14476
14477 /// Determine whether two operations are unsequenced. This operation
14478 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14479 /// should have been merged into its parent as appropriate.
14480 bool isUnsequenced(Seq Cur, Seq Old) {
14481 unsigned C = representative(Cur.Index);
14482 unsigned Target = representative(Old.Index);
14483 while (C >= Target) {
14484 if (C == Target)
14485 return true;
14486 C = Values[C].Parent;
14487 }
14488 return false;
14489 }
14490
14491 private:
14492 /// Pick a representative for a sequence.
14493 unsigned representative(unsigned K) {
14494 if (Values[K].Merged)
14495 // Perform path compression as we go.
14496 return Values[K].Parent = representative(Values[K].Parent);
14497 return K;
14498 }
14499 };
14500
14501 /// An object for which we can track unsequenced uses.
14502 using Object = const NamedDecl *;
14503
14504 /// Different flavors of object usage which we track. We only track the
14505 /// least-sequenced usage of each kind.
14506 enum UsageKind {
14507 /// A read of an object. Multiple unsequenced reads are OK.
14508 UK_Use,
14509
14510 /// A modification of an object which is sequenced before the value
14511 /// computation of the expression, such as ++n in C++.
14512 UK_ModAsValue,
14513
14514 /// A modification of an object which is not sequenced before the value
14515 /// computation of the expression, such as n++.
14516 UK_ModAsSideEffect,
14517
14518 UK_Count = UK_ModAsSideEffect + 1
14519 };
14520
14521 /// Bundle together a sequencing region and the expression corresponding
14522 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14523 struct Usage {
14524 const Expr *UsageExpr = nullptr;
14525 SequenceTree::Seq Seq;
14526
14527 Usage() = default;
14528 };
14529
14530 struct UsageInfo {
14531 Usage Uses[UK_Count];
14532
14533 /// Have we issued a diagnostic for this object already?
14534 bool Diagnosed = false;
14535
14536 UsageInfo();
14537 };
14538 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14539
14540 Sema &SemaRef;
14541
14542 /// Sequenced regions within the expression.
14543 SequenceTree Tree;
14544
14545 /// Declaration modifications and references which we have seen.
14546 UsageInfoMap UsageMap;
14547
14548 /// The region we are currently within.
14549 SequenceTree::Seq Region;
14550
14551 /// Filled in with declarations which were modified as a side-effect
14552 /// (that is, post-increment operations).
14553 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14554
14555 /// Expressions to check later. We defer checking these to reduce
14556 /// stack usage.
14557 SmallVectorImpl<const Expr *> &WorkList;
14558
14559 /// RAII object wrapping the visitation of a sequenced subexpression of an
14560 /// expression. At the end of this process, the side-effects of the evaluation
14561 /// become sequenced with respect to the value computation of the result, so
14562 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14563 /// UK_ModAsValue.
14564 struct SequencedSubexpression {
14565 SequencedSubexpression(SequenceChecker &Self)
14566 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14567 Self.ModAsSideEffect = &ModAsSideEffect;
14568 }
14569
14570 ~SequencedSubexpression() {
14571 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14572 // Add a new usage with usage kind UK_ModAsValue, and then restore
14573 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14574 // the previous one was empty).
14575 UsageInfo &UI = Self.UsageMap[M.first];
14576 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14577 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14578 SideEffectUsage = M.second;
14579 }
14580 Self.ModAsSideEffect = OldModAsSideEffect;
14581 }
14582
14583 SequenceChecker &Self;
14584 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14585 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14586 };
14587
14588 /// RAII object wrapping the visitation of a subexpression which we might
14589 /// choose to evaluate as a constant. If any subexpression is evaluated and
14590 /// found to be non-constant, this allows us to suppress the evaluation of
14591 /// the outer expression.
14592 class EvaluationTracker {
14593 public:
14594 EvaluationTracker(SequenceChecker &Self)
14595 : Self(Self), Prev(Self.EvalTracker) {
14596 Self.EvalTracker = this;
14597 }
14598
14599 ~EvaluationTracker() {
14600 Self.EvalTracker = Prev;
14601 if (Prev)
14602 Prev->EvalOK &= EvalOK;
14603 }
14604
14605 bool evaluate(const Expr *E, bool &Result) {
14606 if (!EvalOK || E->isValueDependent())
14607 return false;
14608 EvalOK = E->EvaluateAsBooleanCondition(
14609 Result, Self.SemaRef.Context,
14610 Self.SemaRef.isConstantEvaluatedContext());
14611 return EvalOK;
14612 }
14613
14614 private:
14615 SequenceChecker &Self;
14616 EvaluationTracker *Prev;
14617 bool EvalOK = true;
14618 } *EvalTracker = nullptr;
14619
14620 /// Find the object which is produced by the specified expression,
14621 /// if any.
14622 Object getObject(const Expr *E, bool Mod) const {
14623 E = E->IgnoreParenCasts();
14624 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14625 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14626 return getObject(UO->getSubExpr(), Mod);
14627 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14628 if (BO->getOpcode() == BO_Comma)
14629 return getObject(BO->getRHS(), Mod);
14630 if (Mod && BO->isAssignmentOp())
14631 return getObject(BO->getLHS(), Mod);
14632 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14633 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14634 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14635 return ME->getMemberDecl();
14636 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14637 // FIXME: If this is a reference, map through to its value.
14638 return DRE->getDecl();
14639 return nullptr;
14640 }
14641
14642 /// Note that an object \p O was modified or used by an expression
14643 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14644 /// the object \p O as obtained via the \p UsageMap.
14645 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14646 // Get the old usage for the given object and usage kind.
14647 Usage &U = UI.Uses[UK];
14648 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14649 // If we have a modification as side effect and are in a sequenced
14650 // subexpression, save the old Usage so that we can restore it later
14651 // in SequencedSubexpression::~SequencedSubexpression.
14652 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14653 ModAsSideEffect->push_back(std::make_pair(O, U));
14654 // Then record the new usage with the current sequencing region.
14655 U.UsageExpr = UsageExpr;
14656 U.Seq = Region;
14657 }
14658 }
14659
14660 /// Check whether a modification or use of an object \p O in an expression
14661 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14662 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14663 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14664 /// usage and false we are checking for a mod-use unsequenced usage.
14665 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14666 UsageKind OtherKind, bool IsModMod) {
14667 if (UI.Diagnosed)
14668 return;
14669
14670 const Usage &U = UI.Uses[OtherKind];
14671 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14672 return;
14673
14674 const Expr *Mod = U.UsageExpr;
14675 const Expr *ModOrUse = UsageExpr;
14676 if (OtherKind == UK_Use)
14677 std::swap(Mod, ModOrUse);
14678
14679 SemaRef.DiagRuntimeBehavior(
14680 Mod->getExprLoc(), {Mod, ModOrUse},
14681 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14682 : diag::warn_unsequenced_mod_use)
14683 << O << SourceRange(ModOrUse->getExprLoc()));
14684 UI.Diagnosed = true;
14685 }
14686
14687 // A note on note{Pre, Post}{Use, Mod}:
14688 //
14689 // (It helps to follow the algorithm with an expression such as
14690 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14691 // operations before C++17 and both are well-defined in C++17).
14692 //
14693 // When visiting a node which uses/modify an object we first call notePreUse
14694 // or notePreMod before visiting its sub-expression(s). At this point the
14695 // children of the current node have not yet been visited and so the eventual
14696 // uses/modifications resulting from the children of the current node have not
14697 // been recorded yet.
14698 //
14699 // We then visit the children of the current node. After that notePostUse or
14700 // notePostMod is called. These will 1) detect an unsequenced modification
14701 // as side effect (as in "k++ + k") and 2) add a new usage with the
14702 // appropriate usage kind.
14703 //
14704 // We also have to be careful that some operation sequences modification as
14705 // side effect as well (for example: || or ,). To account for this we wrap
14706 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14707 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14708 // which record usages which are modifications as side effect, and then
14709 // downgrade them (or more accurately restore the previous usage which was a
14710 // modification as side effect) when exiting the scope of the sequenced
14711 // subexpression.
14712
14713 void notePreUse(Object O, const Expr *UseExpr) {
14714 UsageInfo &UI = UsageMap[O];
14715 // Uses conflict with other modifications.
14716 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14717 }
14718
14719 void notePostUse(Object O, const Expr *UseExpr) {
14720 UsageInfo &UI = UsageMap[O];
14721 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14722 /*IsModMod=*/false);
14723 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14724 }
14725
14726 void notePreMod(Object O, const Expr *ModExpr) {
14727 UsageInfo &UI = UsageMap[O];
14728 // Modifications conflict with other modifications and with uses.
14729 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14730 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14731 }
14732
14733 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14734 UsageInfo &UI = UsageMap[O];
14735 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14736 /*IsModMod=*/true);
14737 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14738 }
14739
14740public:
14741 SequenceChecker(Sema &S, const Expr *E,
14742 SmallVectorImpl<const Expr *> &WorkList)
14743 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14744 Visit(E);
14745 // Silence a -Wunused-private-field since WorkList is now unused.
14746 // TODO: Evaluate if it can be used, and if not remove it.
14747 (void)this->WorkList;
14748 }
14749
14750 void VisitStmt(const Stmt *S) {
14751 // Skip all statements which aren't expressions for now.
14752 }
14753
14754 void VisitExpr(const Expr *E) {
14755 // By default, just recurse to evaluated subexpressions.
14756 Base::VisitStmt(E);
14757 }
14758
14759 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14760 for (auto *Sub : CSE->children()) {
14761 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
14762 if (!ChildExpr)
14763 continue;
14764
14765 if (ChildExpr == CSE->getOperand())
14766 // Do not recurse over a CoroutineSuspendExpr's operand.
14767 // The operand is also a subexpression of getCommonExpr(), and
14768 // recursing into it directly could confuse object management
14769 // for the sake of sequence tracking.
14770 continue;
14771
14772 Visit(Sub);
14773 }
14774 }
14775
14776 void VisitCastExpr(const CastExpr *E) {
14777 Object O = Object();
14778 if (E->getCastKind() == CK_LValueToRValue)
14779 O = getObject(E->getSubExpr(), false);
14780
14781 if (O)
14782 notePreUse(O, E);
14783 VisitExpr(E);
14784 if (O)
14785 notePostUse(O, E);
14786 }
14787
14788 void VisitSequencedExpressions(const Expr *SequencedBefore,
14789 const Expr *SequencedAfter) {
14790 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14791 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14792 SequenceTree::Seq OldRegion = Region;
14793
14794 {
14795 SequencedSubexpression SeqBefore(*this);
14796 Region = BeforeRegion;
14797 Visit(SequencedBefore);
14798 }
14799
14800 Region = AfterRegion;
14801 Visit(SequencedAfter);
14802
14803 Region = OldRegion;
14804
14805 Tree.merge(BeforeRegion);
14806 Tree.merge(AfterRegion);
14807 }
14808
14809 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14810 // C++17 [expr.sub]p1:
14811 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14812 // expression E1 is sequenced before the expression E2.
14813 if (SemaRef.getLangOpts().CPlusPlus17)
14814 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14815 else {
14816 Visit(ASE->getLHS());
14817 Visit(ASE->getRHS());
14818 }
14819 }
14820
14821 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14822 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14823 void VisitBinPtrMem(const BinaryOperator *BO) {
14824 // C++17 [expr.mptr.oper]p4:
14825 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14826 // the expression E1 is sequenced before the expression E2.
14827 if (SemaRef.getLangOpts().CPlusPlus17)
14828 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14829 else {
14830 Visit(BO->getLHS());
14831 Visit(BO->getRHS());
14832 }
14833 }
14834
14835 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14836 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14837 void VisitBinShlShr(const BinaryOperator *BO) {
14838 // C++17 [expr.shift]p4:
14839 // The expression E1 is sequenced before the expression E2.
14840 if (SemaRef.getLangOpts().CPlusPlus17)
14841 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14842 else {
14843 Visit(BO->getLHS());
14844 Visit(BO->getRHS());
14845 }
14846 }
14847
14848 void VisitBinComma(const BinaryOperator *BO) {
14849 // C++11 [expr.comma]p1:
14850 // Every value computation and side effect associated with the left
14851 // expression is sequenced before every value computation and side
14852 // effect associated with the right expression.
14853 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14854 }
14855
14856 void VisitBinAssign(const BinaryOperator *BO) {
14857 SequenceTree::Seq RHSRegion;
14858 SequenceTree::Seq LHSRegion;
14859 if (SemaRef.getLangOpts().CPlusPlus17) {
14860 RHSRegion = Tree.allocate(Region);
14861 LHSRegion = Tree.allocate(Region);
14862 } else {
14863 RHSRegion = Region;
14864 LHSRegion = Region;
14865 }
14866 SequenceTree::Seq OldRegion = Region;
14867
14868 // C++11 [expr.ass]p1:
14869 // [...] the assignment is sequenced after the value computation
14870 // of the right and left operands, [...]
14871 //
14872 // so check it before inspecting the operands and update the
14873 // map afterwards.
14874 Object O = getObject(BO->getLHS(), /*Mod=*/true);
14875 if (O)
14876 notePreMod(O, BO);
14877
14878 if (SemaRef.getLangOpts().CPlusPlus17) {
14879 // C++17 [expr.ass]p1:
14880 // [...] The right operand is sequenced before the left operand. [...]
14881 {
14882 SequencedSubexpression SeqBefore(*this);
14883 Region = RHSRegion;
14884 Visit(BO->getRHS());
14885 }
14886
14887 Region = LHSRegion;
14888 Visit(BO->getLHS());
14889
14890 if (O && isa<CompoundAssignOperator>(BO))
14891 notePostUse(O, BO);
14892
14893 } else {
14894 // C++11 does not specify any sequencing between the LHS and RHS.
14895 Region = LHSRegion;
14896 Visit(BO->getLHS());
14897
14898 if (O && isa<CompoundAssignOperator>(BO))
14899 notePostUse(O, BO);
14900
14901 Region = RHSRegion;
14902 Visit(BO->getRHS());
14903 }
14904
14905 // C++11 [expr.ass]p1:
14906 // the assignment is sequenced [...] before the value computation of the
14907 // assignment expression.
14908 // C11 6.5.16/3 has no such rule.
14909 Region = OldRegion;
14910 if (O)
14911 notePostMod(O, BO,
14912 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14913 : UK_ModAsSideEffect);
14914 if (SemaRef.getLangOpts().CPlusPlus17) {
14915 Tree.merge(RHSRegion);
14916 Tree.merge(LHSRegion);
14917 }
14918 }
14919
14920 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14921 VisitBinAssign(CAO);
14922 }
14923
14924 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14925 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14926 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14927 Object O = getObject(UO->getSubExpr(), true);
14928 if (!O)
14929 return VisitExpr(UO);
14930
14931 notePreMod(O, UO);
14932 Visit(UO->getSubExpr());
14933 // C++11 [expr.pre.incr]p1:
14934 // the expression ++x is equivalent to x+=1
14935 notePostMod(O, UO,
14936 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14937 : UK_ModAsSideEffect);
14938 }
14939
14940 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14941 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14942 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14943 Object O = getObject(UO->getSubExpr(), true);
14944 if (!O)
14945 return VisitExpr(UO);
14946
14947 notePreMod(O, UO);
14948 Visit(UO->getSubExpr());
14949 notePostMod(O, UO, UK_ModAsSideEffect);
14950 }
14951
14952 void VisitBinLOr(const BinaryOperator *BO) {
14953 // C++11 [expr.log.or]p2:
14954 // If the second expression is evaluated, every value computation and
14955 // side effect associated with the first expression is sequenced before
14956 // every value computation and side effect associated with the
14957 // second expression.
14958 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14959 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14960 SequenceTree::Seq OldRegion = Region;
14961
14962 EvaluationTracker Eval(*this);
14963 {
14964 SequencedSubexpression Sequenced(*this);
14965 Region = LHSRegion;
14966 Visit(BO->getLHS());
14967 }
14968
14969 // C++11 [expr.log.or]p1:
14970 // [...] the second operand is not evaluated if the first operand
14971 // evaluates to true.
14972 bool EvalResult = false;
14973 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14974 bool ShouldVisitRHS = !EvalOK || !EvalResult;
14975 if (ShouldVisitRHS) {
14976 Region = RHSRegion;
14977 Visit(BO->getRHS());
14978 }
14979
14980 Region = OldRegion;
14981 Tree.merge(LHSRegion);
14982 Tree.merge(RHSRegion);
14983 }
14984
14985 void VisitBinLAnd(const BinaryOperator *BO) {
14986 // C++11 [expr.log.and]p2:
14987 // If the second expression is evaluated, every value computation and
14988 // side effect associated with the first expression is sequenced before
14989 // every value computation and side effect associated with the
14990 // second expression.
14991 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14992 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14993 SequenceTree::Seq OldRegion = Region;
14994
14995 EvaluationTracker Eval(*this);
14996 {
14997 SequencedSubexpression Sequenced(*this);
14998 Region = LHSRegion;
14999 Visit(BO->getLHS());
15000 }
15001
15002 // C++11 [expr.log.and]p1:
15003 // [...] the second operand is not evaluated if the first operand is false.
15004 bool EvalResult = false;
15005 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15006 bool ShouldVisitRHS = !EvalOK || EvalResult;
15007 if (ShouldVisitRHS) {
15008 Region = RHSRegion;
15009 Visit(BO->getRHS());
15010 }
15011
15012 Region = OldRegion;
15013 Tree.merge(LHSRegion);
15014 Tree.merge(RHSRegion);
15015 }
15016
15017 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
15018 // C++11 [expr.cond]p1:
15019 // [...] Every value computation and side effect associated with the first
15020 // expression is sequenced before every value computation and side effect
15021 // associated with the second or third expression.
15022 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
15023
15024 // No sequencing is specified between the true and false expression.
15025 // However since exactly one of both is going to be evaluated we can
15026 // consider them to be sequenced. This is needed to avoid warning on
15027 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
15028 // both the true and false expressions because we can't evaluate x.
15029 // This will still allow us to detect an expression like (pre C++17)
15030 // "(x ? y += 1 : y += 2) = y".
15031 //
15032 // We don't wrap the visitation of the true and false expression with
15033 // SequencedSubexpression because we don't want to downgrade modifications
15034 // as side effect in the true and false expressions after the visition
15035 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
15036 // not warn between the two "y++", but we should warn between the "y++"
15037 // and the "y".
15038 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
15039 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
15040 SequenceTree::Seq OldRegion = Region;
15041
15042 EvaluationTracker Eval(*this);
15043 {
15044 SequencedSubexpression Sequenced(*this);
15045 Region = ConditionRegion;
15046 Visit(CO->getCond());
15047 }
15048
15049 // C++11 [expr.cond]p1:
15050 // [...] The first expression is contextually converted to bool (Clause 4).
15051 // It is evaluated and if it is true, the result of the conditional
15052 // expression is the value of the second expression, otherwise that of the
15053 // third expression. Only one of the second and third expressions is
15054 // evaluated. [...]
15055 bool EvalResult = false;
15056 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
15057 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
15058 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
15059 if (ShouldVisitTrueExpr) {
15060 Region = TrueRegion;
15061 Visit(CO->getTrueExpr());
15062 }
15063 if (ShouldVisitFalseExpr) {
15064 Region = FalseRegion;
15065 Visit(CO->getFalseExpr());
15066 }
15067
15068 Region = OldRegion;
15069 Tree.merge(ConditionRegion);
15070 Tree.merge(TrueRegion);
15071 Tree.merge(FalseRegion);
15072 }
15073
15074 void VisitCallExpr(const CallExpr *CE) {
15075 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
15076
15077 if (CE->isUnevaluatedBuiltinCall(Context))
15078 return;
15079
15080 // C++11 [intro.execution]p15:
15081 // When calling a function [...], every value computation and side effect
15082 // associated with any argument expression, or with the postfix expression
15083 // designating the called function, is sequenced before execution of every
15084 // expression or statement in the body of the function [and thus before
15085 // the value computation of its result].
15086 SequencedSubexpression Sequenced(*this);
15087 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
15088 // C++17 [expr.call]p5
15089 // The postfix-expression is sequenced before each expression in the
15090 // expression-list and any default argument. [...]
15091 SequenceTree::Seq CalleeRegion;
15092 SequenceTree::Seq OtherRegion;
15093 if (SemaRef.getLangOpts().CPlusPlus17) {
15094 CalleeRegion = Tree.allocate(Region);
15095 OtherRegion = Tree.allocate(Region);
15096 } else {
15097 CalleeRegion = Region;
15098 OtherRegion = Region;
15099 }
15100 SequenceTree::Seq OldRegion = Region;
15101
15102 // Visit the callee expression first.
15103 Region = CalleeRegion;
15104 if (SemaRef.getLangOpts().CPlusPlus17) {
15105 SequencedSubexpression Sequenced(*this);
15106 Visit(CE->getCallee());
15107 } else {
15108 Visit(CE->getCallee());
15109 }
15110
15111 // Then visit the argument expressions.
15112 Region = OtherRegion;
15113 for (const Expr *Argument : CE->arguments())
15114 Visit(Argument);
15115
15116 Region = OldRegion;
15117 if (SemaRef.getLangOpts().CPlusPlus17) {
15118 Tree.merge(CalleeRegion);
15119 Tree.merge(OtherRegion);
15120 }
15121 });
15122 }
15123
15124 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
15125 // C++17 [over.match.oper]p2:
15126 // [...] the operator notation is first transformed to the equivalent
15127 // function-call notation as summarized in Table 12 (where @ denotes one
15128 // of the operators covered in the specified subclause). However, the
15129 // operands are sequenced in the order prescribed for the built-in
15130 // operator (Clause 8).
15131 //
15132 // From the above only overloaded binary operators and overloaded call
15133 // operators have sequencing rules in C++17 that we need to handle
15134 // separately.
15135 if (!SemaRef.getLangOpts().CPlusPlus17 ||
15136 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15137 return VisitCallExpr(CXXOCE);
15138
15139 enum {
15140 NoSequencing,
15141 LHSBeforeRHS,
15142 RHSBeforeLHS,
15143 LHSBeforeRest
15144 } SequencingKind;
15145 switch (CXXOCE->getOperator()) {
15146 case OO_Equal:
15147 case OO_PlusEqual:
15148 case OO_MinusEqual:
15149 case OO_StarEqual:
15150 case OO_SlashEqual:
15151 case OO_PercentEqual:
15152 case OO_CaretEqual:
15153 case OO_AmpEqual:
15154 case OO_PipeEqual:
15155 case OO_LessLessEqual:
15156 case OO_GreaterGreaterEqual:
15157 SequencingKind = RHSBeforeLHS;
15158 break;
15159
15160 case OO_LessLess:
15161 case OO_GreaterGreater:
15162 case OO_AmpAmp:
15163 case OO_PipePipe:
15164 case OO_Comma:
15165 case OO_ArrowStar:
15166 case OO_Subscript:
15167 SequencingKind = LHSBeforeRHS;
15168 break;
15169
15170 case OO_Call:
15171 SequencingKind = LHSBeforeRest;
15172 break;
15173
15174 default:
15175 SequencingKind = NoSequencing;
15176 break;
15177 }
15178
15179 if (SequencingKind == NoSequencing)
15180 return VisitCallExpr(CXXOCE);
15181
15182 // This is a call, so all subexpressions are sequenced before the result.
15183 SequencedSubexpression Sequenced(*this);
15184
15185 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
15186 assert(SemaRef.getLangOpts().CPlusPlus17 &&
15187 "Should only get there with C++17 and above!");
15188 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15189 "Should only get there with an overloaded binary operator"
15190 " or an overloaded call operator!");
15191
15192 if (SequencingKind == LHSBeforeRest) {
15193 assert(CXXOCE->getOperator() == OO_Call &&
15194 "We should only have an overloaded call operator here!");
15195
15196 // This is very similar to VisitCallExpr, except that we only have the
15197 // C++17 case. The postfix-expression is the first argument of the
15198 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15199 // are in the following arguments.
15200 //
15201 // Note that we intentionally do not visit the callee expression since
15202 // it is just a decayed reference to a function.
15203 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
15204 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
15205 SequenceTree::Seq OldRegion = Region;
15206
15207 assert(CXXOCE->getNumArgs() >= 1 &&
15208 "An overloaded call operator must have at least one argument"
15209 " for the postfix-expression!");
15210 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15211 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15212 CXXOCE->getNumArgs() - 1);
15213
15214 // Visit the postfix-expression first.
15215 {
15216 Region = PostfixExprRegion;
15217 SequencedSubexpression Sequenced(*this);
15218 Visit(PostfixExpr);
15219 }
15220
15221 // Then visit the argument expressions.
15222 Region = ArgsRegion;
15223 for (const Expr *Arg : Args)
15224 Visit(Arg);
15225
15226 Region = OldRegion;
15227 Tree.merge(PostfixExprRegion);
15228 Tree.merge(ArgsRegion);
15229 } else {
15230 assert(CXXOCE->getNumArgs() == 2 &&
15231 "Should only have two arguments here!");
15232 assert((SequencingKind == LHSBeforeRHS ||
15233 SequencingKind == RHSBeforeLHS) &&
15234 "Unexpected sequencing kind!");
15235
15236 // We do not visit the callee expression since it is just a decayed
15237 // reference to a function.
15238 const Expr *E1 = CXXOCE->getArg(0);
15239 const Expr *E2 = CXXOCE->getArg(1);
15240 if (SequencingKind == RHSBeforeLHS)
15241 std::swap(E1, E2);
15242
15243 return VisitSequencedExpressions(E1, E2);
15244 }
15245 });
15246 }
15247
15248 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15249 // This is a call, so all subexpressions are sequenced before the result.
15250 SequencedSubexpression Sequenced(*this);
15251
15252 if (!CCE->isListInitialization())
15253 return VisitExpr(CCE);
15254
15255 // In C++11, list initializations are sequenced.
15256 SequenceExpressionsInOrder(
15257 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
15258 }
15259
15260 void VisitInitListExpr(const InitListExpr *ILE) {
15261 if (!SemaRef.getLangOpts().CPlusPlus11)
15262 return VisitExpr(ILE);
15263
15264 // In C++11, list initializations are sequenced.
15265 SequenceExpressionsInOrder(ILE->inits());
15266 }
15267
15268 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
15269 // C++20 parenthesized list initializations are sequenced. See C++20
15270 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
15271 SequenceExpressionsInOrder(PLIE->getInitExprs());
15272 }
15273
15274private:
15275 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
15277 SequenceTree::Seq Parent = Region;
15278 for (const Expr *E : ExpressionList) {
15279 if (!E)
15280 continue;
15281 Region = Tree.allocate(Parent);
15282 Elts.push_back(Region);
15283 Visit(E);
15284 }
15285
15286 // Forget that the initializers are sequenced.
15287 Region = Parent;
15288 for (unsigned I = 0; I < Elts.size(); ++I)
15289 Tree.merge(Elts[I]);
15290 }
15291};
15292
15293SequenceChecker::UsageInfo::UsageInfo() = default;
15294
15295} // namespace
15296
15297void Sema::CheckUnsequencedOperations(const Expr *E) {
15298 SmallVector<const Expr *, 8> WorkList;
15299 WorkList.push_back(E);
15300 while (!WorkList.empty()) {
15301 const Expr *Item = WorkList.pop_back_val();
15302 SequenceChecker(*this, Item, WorkList);
15303 }
15304}
15305
15306void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15307 bool IsConstexpr) {
15308 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15309 IsConstexpr || isa<ConstantExpr>(E));
15310 CheckImplicitConversions(E, CheckLoc);
15311 if (!E->isInstantiationDependent())
15312 CheckUnsequencedOperations(E);
15313 if (!IsConstexpr && !E->isValueDependent())
15314 CheckForIntOverflow(E);
15315}
15316
15317void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15318 FieldDecl *BitField,
15319 Expr *Init) {
15320 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
15321}
15322
15324 SourceLocation Loc) {
15325 if (!PType->isVariablyModifiedType())
15326 return;
15327 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
15328 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
15329 return;
15330 }
15331 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
15332 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
15333 return;
15334 }
15335 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
15336 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
15337 return;
15338 }
15339
15340 const ArrayType *AT = S.Context.getAsArrayType(PType);
15341 if (!AT)
15342 return;
15343
15346 return;
15347 }
15348
15349 S.Diag(Loc, diag::err_array_star_in_function_definition);
15350}
15351
15353 bool CheckParameterNames) {
15354 bool HasInvalidParm = false;
15355 for (ParmVarDecl *Param : Parameters) {
15356 assert(Param && "null in a parameter list");
15357 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15358 // function declarator that is part of a function definition of
15359 // that function shall not have incomplete type.
15360 //
15361 // C++23 [dcl.fct.def.general]/p2
15362 // The type of a parameter [...] for a function definition
15363 // shall not be a (possibly cv-qualified) class type that is incomplete
15364 // or abstract within the function body unless the function is deleted.
15365 if (!Param->isInvalidDecl() &&
15366 (RequireCompleteType(Param->getLocation(), Param->getType(),
15367 diag::err_typecheck_decl_incomplete_type) ||
15368 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
15369 diag::err_abstract_type_in_decl,
15371 Param->setInvalidDecl();
15372 HasInvalidParm = true;
15373 }
15374
15375 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15376 // declaration of each parameter shall include an identifier.
15377 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15378 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15379 // Diagnose this as an extension in C17 and earlier.
15380 if (!getLangOpts().C23)
15381 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
15382 }
15383
15384 // C99 6.7.5.3p12:
15385 // If the function declarator is not part of a definition of that
15386 // function, parameters may have incomplete type and may use the [*]
15387 // notation in their sequences of declarator specifiers to specify
15388 // variable length array types.
15389 QualType PType = Param->getOriginalType();
15390 // FIXME: This diagnostic should point the '[*]' if source-location
15391 // information is added for it.
15392 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15393
15394 // If the parameter is a c++ class type and it has to be destructed in the
15395 // callee function, declare the destructor so that it can be called by the
15396 // callee function. Do not perform any direct access check on the dtor here.
15397 if (!Param->isInvalidDecl()) {
15398 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15399 if (!ClassDecl->isInvalidDecl() &&
15400 !ClassDecl->hasIrrelevantDestructor() &&
15401 !ClassDecl->isDependentContext() &&
15402 ClassDecl->isParamDestroyedInCallee()) {
15404 MarkFunctionReferenced(Param->getLocation(), Destructor);
15405 DiagnoseUseOfDecl(Destructor, Param->getLocation());
15406 }
15407 }
15408 }
15409
15410 // Parameters with the pass_object_size attribute only need to be marked
15411 // constant at function definitions. Because we lack information about
15412 // whether we're on a declaration or definition when we're instantiating the
15413 // attribute, we need to check for constness here.
15414 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15415 if (!Param->getType().isConstQualified())
15416 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15417 << Attr->getSpelling() << 1;
15418
15419 // Check for parameter names shadowing fields from the class.
15420 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15421 // The owning context for the parameter should be the function, but we
15422 // want to see if this function's declaration context is a record.
15423 DeclContext *DC = Param->getDeclContext();
15424 if (DC && DC->isFunctionOrMethod()) {
15425 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15426 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15427 RD, /*DeclIsField*/ false);
15428 }
15429 }
15430
15431 if (!Param->isInvalidDecl() &&
15432 Param->getOriginalType()->isWebAssemblyTableType()) {
15433 Param->setInvalidDecl();
15434 HasInvalidParm = true;
15435 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
15436 }
15437 }
15438
15439 return HasInvalidParm;
15440}
15441
15442std::optional<std::pair<
15444 *E,
15446 &Ctx);
15447
15448/// Compute the alignment and offset of the base class object given the
15449/// derived-to-base cast expression and the alignment and offset of the derived
15450/// class object.
15451static std::pair<CharUnits, CharUnits>
15453 CharUnits BaseAlignment, CharUnits Offset,
15454 ASTContext &Ctx) {
15455 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15456 ++PathI) {
15457 const CXXBaseSpecifier *Base = *PathI;
15458 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15459 if (Base->isVirtual()) {
15460 // The complete object may have a lower alignment than the non-virtual
15461 // alignment of the base, in which case the base may be misaligned. Choose
15462 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15463 // conservative lower bound of the complete object alignment.
15464 CharUnits NonVirtualAlignment =
15466 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15467 Offset = CharUnits::Zero();
15468 } else {
15469 const ASTRecordLayout &RL =
15470 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15471 Offset += RL.getBaseClassOffset(BaseDecl);
15472 }
15473 DerivedType = Base->getType();
15474 }
15475
15476 return std::make_pair(BaseAlignment, Offset);
15477}
15478
15479/// Compute the alignment and offset of a binary additive operator.
15480static std::optional<std::pair<CharUnits, CharUnits>>
15482 bool IsSub, ASTContext &Ctx) {
15483 QualType PointeeType = PtrE->getType()->getPointeeType();
15484
15485 if (!PointeeType->isConstantSizeType())
15486 return std::nullopt;
15487
15488 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15489
15490 if (!P)
15491 return std::nullopt;
15492
15493 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15494 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15495 CharUnits Offset = EltSize * IdxRes->getExtValue();
15496 if (IsSub)
15497 Offset = -Offset;
15498 return std::make_pair(P->first, P->second + Offset);
15499 }
15500
15501 // If the integer expression isn't a constant expression, compute the lower
15502 // bound of the alignment using the alignment and offset of the pointer
15503 // expression and the element size.
15504 return std::make_pair(
15505 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15506 CharUnits::Zero());
15507}
15508
15509/// This helper function takes an lvalue expression and returns the alignment of
15510/// a VarDecl and a constant offset from the VarDecl.
15511std::optional<std::pair<
15512 CharUnits,
15514 ASTContext &Ctx) {
15515 E = E->IgnoreParens();
15516 switch (E->getStmtClass()) {
15517 default:
15518 break;
15519 case Stmt::CStyleCastExprClass:
15520 case Stmt::CXXStaticCastExprClass:
15521 case Stmt::ImplicitCastExprClass: {
15522 auto *CE = cast<CastExpr>(E);
15523 const Expr *From = CE->getSubExpr();
15524 switch (CE->getCastKind()) {
15525 default:
15526 break;
15527 case CK_NoOp:
15528 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15529 case CK_UncheckedDerivedToBase:
15530 case CK_DerivedToBase: {
15531 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15532 if (!P)
15533 break;
15534 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15535 P->second, Ctx);
15536 }
15537 }
15538 break;
15539 }
15540 case Stmt::ArraySubscriptExprClass: {
15541 auto *ASE = cast<ArraySubscriptExpr>(E);
15543 false, Ctx);
15544 }
15545 case Stmt::DeclRefExprClass: {
15546 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15547 // FIXME: If VD is captured by copy or is an escaping __block variable,
15548 // use the alignment of VD's type.
15549 if (!VD->getType()->isReferenceType()) {
15550 // Dependent alignment cannot be resolved -> bail out.
15551 if (VD->hasDependentAlignment())
15552 break;
15553 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15554 }
15555 if (VD->hasInit())
15556 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15557 }
15558 break;
15559 }
15560 case Stmt::MemberExprClass: {
15561 auto *ME = cast<MemberExpr>(E);
15562 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15563 if (!FD || FD->getType()->isReferenceType() ||
15564 FD->getParent()->isInvalidDecl())
15565 break;
15566 std::optional<std::pair<CharUnits, CharUnits>> P;
15567 if (ME->isArrow())
15568 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15569 else
15570 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15571 if (!P)
15572 break;
15573 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15574 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15575 return std::make_pair(P->first,
15576 P->second + CharUnits::fromQuantity(Offset));
15577 }
15578 case Stmt::UnaryOperatorClass: {
15579 auto *UO = cast<UnaryOperator>(E);
15580 switch (UO->getOpcode()) {
15581 default:
15582 break;
15583 case UO_Deref:
15585 }
15586 break;
15587 }
15588 case Stmt::BinaryOperatorClass: {
15589 auto *BO = cast<BinaryOperator>(E);
15590 auto Opcode = BO->getOpcode();
15591 switch (Opcode) {
15592 default:
15593 break;
15594 case BO_Comma:
15596 }
15597 break;
15598 }
15599 }
15600 return std::nullopt;
15601}
15602
15603/// This helper function takes a pointer expression and returns the alignment of
15604/// a VarDecl and a constant offset from the VarDecl.
15605std::optional<std::pair<
15607 *E,
15609 &Ctx) {
15610 E = E->IgnoreParens();
15611 switch (E->getStmtClass()) {
15612 default:
15613 break;
15614 case Stmt::CStyleCastExprClass:
15615 case Stmt::CXXStaticCastExprClass:
15616 case Stmt::ImplicitCastExprClass: {
15617 auto *CE = cast<CastExpr>(E);
15618 const Expr *From = CE->getSubExpr();
15619 switch (CE->getCastKind()) {
15620 default:
15621 break;
15622 case CK_NoOp:
15623 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15624 case CK_ArrayToPointerDecay:
15625 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15626 case CK_UncheckedDerivedToBase:
15627 case CK_DerivedToBase: {
15628 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15629 if (!P)
15630 break;
15632 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15633 }
15634 }
15635 break;
15636 }
15637 case Stmt::CXXThisExprClass: {
15638 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15640 return std::make_pair(Alignment, CharUnits::Zero());
15641 }
15642 case Stmt::UnaryOperatorClass: {
15643 auto *UO = cast<UnaryOperator>(E);
15644 if (UO->getOpcode() == UO_AddrOf)
15646 break;
15647 }
15648 case Stmt::BinaryOperatorClass: {
15649 auto *BO = cast<BinaryOperator>(E);
15650 auto Opcode = BO->getOpcode();
15651 switch (Opcode) {
15652 default:
15653 break;
15654 case BO_Add:
15655 case BO_Sub: {
15656 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15657 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15658 std::swap(LHS, RHS);
15659 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15660 Ctx);
15661 }
15662 case BO_Comma:
15663 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15664 }
15665 break;
15666 }
15667 }
15668 return std::nullopt;
15669}
15670
15672 // See if we can compute the alignment of a VarDecl and an offset from it.
15673 std::optional<std::pair<CharUnits, CharUnits>> P =
15675
15676 if (P)
15677 return P->first.alignmentAtOffset(P->second);
15678
15679 // If that failed, return the type's alignment.
15681}
15682
15684 // This is actually a lot of work to potentially be doing on every
15685 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15686 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15687 return;
15688
15689 // Ignore dependent types.
15690 if (T->isDependentType() || Op->getType()->isDependentType())
15691 return;
15692
15693 // Require that the destination be a pointer type.
15694 const PointerType *DestPtr = T->getAs<PointerType>();
15695 if (!DestPtr) return;
15696
15697 // If the destination has alignment 1, we're done.
15698 QualType DestPointee = DestPtr->getPointeeType();
15699 if (DestPointee->isIncompleteType()) return;
15700 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15701 if (DestAlign.isOne()) return;
15702
15703 // Require that the source be a pointer type.
15704 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15705 if (!SrcPtr) return;
15706 QualType SrcPointee = SrcPtr->getPointeeType();
15707
15708 // Explicitly allow casts from cv void*. We already implicitly
15709 // allowed casts to cv void*, since they have alignment 1.
15710 // Also allow casts involving incomplete types, which implicitly
15711 // includes 'void'.
15712 if (SrcPointee->isIncompleteType()) return;
15713
15714 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15715
15716 if (SrcAlign >= DestAlign) return;
15717
15718 Diag(TRange.getBegin(), diag::warn_cast_align)
15719 << Op->getType() << T
15720 << static_cast<unsigned>(SrcAlign.getQuantity())
15721 << static_cast<unsigned>(DestAlign.getQuantity())
15722 << TRange << Op->getSourceRange();
15723}
15724
15725void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15726 const ArraySubscriptExpr *ASE,
15727 bool AllowOnePastEnd, bool IndexNegated) {
15728 // Already diagnosed by the constant evaluator.
15730 return;
15731
15732 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15733 if (IndexExpr->isValueDependent())
15734 return;
15735
15736 const Type *EffectiveType =
15738 BaseExpr = BaseExpr->IgnoreParenCasts();
15739 const ConstantArrayType *ArrayTy =
15740 Context.getAsConstantArrayType(BaseExpr->getType());
15741
15743 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15744
15745 const Type *BaseType =
15746 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15747 bool IsUnboundedArray =
15748 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15749 Context, StrictFlexArraysLevel,
15750 /*IgnoreTemplateOrMacroSubstitution=*/true);
15751 if (EffectiveType->isDependentType() ||
15752 (!IsUnboundedArray && BaseType->isDependentType()))
15753 return;
15754
15756 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15757 return;
15758
15759 llvm::APSInt index = Result.Val.getInt();
15760 if (IndexNegated) {
15761 index.setIsUnsigned(false);
15762 index = -index;
15763 }
15764
15765 if (IsUnboundedArray) {
15766 if (EffectiveType->isFunctionType())
15767 return;
15768 if (index.isUnsigned() || !index.isNegative()) {
15769 const auto &ASTC = getASTContext();
15770 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15771 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15772 if (index.getBitWidth() < AddrBits)
15773 index = index.zext(AddrBits);
15774 std::optional<CharUnits> ElemCharUnits =
15775 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15776 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15777 // pointer) bounds-checking isn't meaningful.
15778 if (!ElemCharUnits || ElemCharUnits->isZero())
15779 return;
15780 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15781 // If index has more active bits than address space, we already know
15782 // we have a bounds violation to warn about. Otherwise, compute
15783 // address of (index + 1)th element, and warn about bounds violation
15784 // only if that address exceeds address space.
15785 if (index.getActiveBits() <= AddrBits) {
15786 bool Overflow;
15787 llvm::APInt Product(index);
15788 Product += 1;
15789 Product = Product.umul_ov(ElemBytes, Overflow);
15790 if (!Overflow && Product.getActiveBits() <= AddrBits)
15791 return;
15792 }
15793
15794 // Need to compute max possible elements in address space, since that
15795 // is included in diag message.
15796 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15797 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15798 MaxElems += 1;
15799 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15800 MaxElems = MaxElems.udiv(ElemBytes);
15801
15802 unsigned DiagID =
15803 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15804 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15805
15806 // Diag message shows element size in bits and in "bytes" (platform-
15807 // dependent CharUnits)
15808 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15809 PDiag(DiagID) << index << AddrBits
15810 << (unsigned)ASTC.toBits(*ElemCharUnits)
15811 << ElemBytes << MaxElems
15812 << MaxElems.getZExtValue()
15813 << IndexExpr->getSourceRange());
15814
15815 const NamedDecl *ND = nullptr;
15816 // Try harder to find a NamedDecl to point at in the note.
15817 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15818 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15819 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15820 ND = DRE->getDecl();
15821 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15822 ND = ME->getMemberDecl();
15823
15824 if (ND)
15825 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15826 PDiag(diag::note_array_declared_here) << ND);
15827 }
15828 return;
15829 }
15830
15831 if (index.isUnsigned() || !index.isNegative()) {
15832 // It is possible that the type of the base expression after
15833 // IgnoreParenCasts is incomplete, even though the type of the base
15834 // expression before IgnoreParenCasts is complete (see PR39746 for an
15835 // example). In this case we have no information about whether the array
15836 // access exceeds the array bounds. However we can still diagnose an array
15837 // access which precedes the array bounds.
15838 if (BaseType->isIncompleteType())
15839 return;
15840
15841 llvm::APInt size = ArrayTy->getSize();
15842
15843 if (BaseType != EffectiveType) {
15844 // Make sure we're comparing apples to apples when comparing index to
15845 // size.
15846 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15847 uint64_t array_typesize = Context.getTypeSize(BaseType);
15848
15849 // Handle ptrarith_typesize being zero, such as when casting to void*.
15850 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
15851 if (!ptrarith_typesize)
15852 ptrarith_typesize = Context.getCharWidth();
15853
15854 if (ptrarith_typesize != array_typesize) {
15855 // There's a cast to a different size type involved.
15856 uint64_t ratio = array_typesize / ptrarith_typesize;
15857
15858 // TODO: Be smarter about handling cases where array_typesize is not a
15859 // multiple of ptrarith_typesize.
15860 if (ptrarith_typesize * ratio == array_typesize)
15861 size *= llvm::APInt(size.getBitWidth(), ratio);
15862 }
15863 }
15864
15865 if (size.getBitWidth() > index.getBitWidth())
15866 index = index.zext(size.getBitWidth());
15867 else if (size.getBitWidth() < index.getBitWidth())
15868 size = size.zext(index.getBitWidth());
15869
15870 // For array subscripting the index must be less than size, but for pointer
15871 // arithmetic also allow the index (offset) to be equal to size since
15872 // computing the next address after the end of the array is legal and
15873 // commonly done e.g. in C++ iterators and range-based for loops.
15874 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15875 return;
15876
15877 // Suppress the warning if the subscript expression (as identified by the
15878 // ']' location) and the index expression are both from macro expansions
15879 // within a system header.
15880 if (ASE) {
15881 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15882 ASE->getRBracketLoc());
15883 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15884 SourceLocation IndexLoc =
15885 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15886 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15887 return;
15888 }
15889 }
15890
15891 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15892 : diag::warn_ptr_arith_exceeds_bounds;
15893 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
15894 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
15895
15896 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15897 PDiag(DiagID)
15898 << index << ArrayTy->desugar() << CastMsg
15899 << CastMsgTy << IndexExpr->getSourceRange());
15900 } else {
15901 unsigned DiagID = diag::warn_array_index_precedes_bounds;
15902 if (!ASE) {
15903 DiagID = diag::warn_ptr_arith_precedes_bounds;
15904 if (index.isNegative()) index = -index;
15905 }
15906
15907 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15908 PDiag(DiagID) << index << IndexExpr->getSourceRange());
15909 }
15910
15911 const NamedDecl *ND = nullptr;
15912 // Try harder to find a NamedDecl to point at in the note.
15913 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15914 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15915 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15916 ND = DRE->getDecl();
15917 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15918 ND = ME->getMemberDecl();
15919
15920 if (ND)
15921 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15922 PDiag(diag::note_array_declared_here) << ND);
15923}
15924
15925void Sema::CheckArrayAccess(const Expr *expr) {
15926 int AllowOnePastEnd = 0;
15927 while (expr) {
15928 expr = expr->IgnoreParenImpCasts();
15929 switch (expr->getStmtClass()) {
15930 case Stmt::ArraySubscriptExprClass: {
15931 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15932 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15933 AllowOnePastEnd > 0);
15934 expr = ASE->getBase();
15935 break;
15936 }
15937 case Stmt::MemberExprClass: {
15938 expr = cast<MemberExpr>(expr)->getBase();
15939 break;
15940 }
15941 case Stmt::CXXMemberCallExprClass: {
15942 expr = cast<CXXMemberCallExpr>(expr)->getImplicitObjectArgument();
15943 break;
15944 }
15945 case Stmt::ArraySectionExprClass: {
15946 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
15947 // FIXME: We should probably be checking all of the elements to the
15948 // 'length' here as well.
15949 if (ASE->getLowerBound())
15950 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15951 /*ASE=*/nullptr, AllowOnePastEnd > 0);
15952 return;
15953 }
15954 case Stmt::UnaryOperatorClass: {
15955 // Only unwrap the * and & unary operators
15956 const UnaryOperator *UO = cast<UnaryOperator>(expr);
15957 expr = UO->getSubExpr();
15958 switch (UO->getOpcode()) {
15959 case UO_AddrOf:
15960 AllowOnePastEnd++;
15961 break;
15962 case UO_Deref:
15963 AllowOnePastEnd--;
15964 break;
15965 default:
15966 return;
15967 }
15968 break;
15969 }
15970 case Stmt::ConditionalOperatorClass: {
15971 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15972 if (const Expr *lhs = cond->getLHS())
15973 CheckArrayAccess(lhs);
15974 if (const Expr *rhs = cond->getRHS())
15975 CheckArrayAccess(rhs);
15976 return;
15977 }
15978 case Stmt::CXXOperatorCallExprClass: {
15979 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15980 for (const auto *Arg : OCE->arguments())
15981 CheckArrayAccess(Arg);
15982 return;
15983 }
15984 default:
15985 return;
15986 }
15987 }
15988}
15989
15991 Expr *RHS, bool isProperty) {
15992 // Check if RHS is an Objective-C object literal, which also can get
15993 // immediately zapped in a weak reference. Note that we explicitly
15994 // allow ObjCStringLiterals, since those are designed to never really die.
15995 RHS = RHS->IgnoreParenImpCasts();
15996
15997 // This enum needs to match with the 'select' in
15998 // warn_objc_arc_literal_assign (off-by-1).
16000 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
16001 return false;
16002
16003 S.Diag(Loc, diag::warn_arc_literal_assign)
16004 << (unsigned) Kind
16005 << (isProperty ? 0 : 1)
16006 << RHS->getSourceRange();
16007
16008 return true;
16009}
16010
16013 Expr *RHS, bool isProperty) {
16014 // Strip off any implicit cast added to get to the one ARC-specific.
16015 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16016 if (cast->getCastKind() == CK_ARCConsumeObject) {
16017 S.Diag(Loc, diag::warn_arc_retained_assign)
16019 << (isProperty ? 0 : 1)
16020 << RHS->getSourceRange();
16021 return true;
16022 }
16023 RHS = cast->getSubExpr();
16024 }
16025
16026 if (LT == Qualifiers::OCL_Weak &&
16027 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16028 return true;
16029
16030 return false;
16031}
16032
16034 QualType LHS, Expr *RHS) {
16036
16038 return false;
16039
16040 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16041 return true;
16042
16043 return false;
16044}
16045
16047 Expr *LHS, Expr *RHS) {
16048 QualType LHSType;
16049 // PropertyRef on LHS type need be directly obtained from
16050 // its declaration as it has a PseudoType.
16052 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16053 if (PRE && !PRE->isImplicitProperty()) {
16054 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16055 if (PD)
16056 LHSType = PD->getType();
16057 }
16058
16059 if (LHSType.isNull())
16060 LHSType = LHS->getType();
16061
16063
16064 if (LT == Qualifiers::OCL_Weak) {
16065 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16067 }
16068
16069 if (checkUnsafeAssigns(Loc, LHSType, RHS))
16070 return;
16071
16072 // FIXME. Check for other life times.
16073 if (LT != Qualifiers::OCL_None)
16074 return;
16075
16076 if (PRE) {
16077 if (PRE->isImplicitProperty())
16078 return;
16079 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16080 if (!PD)
16081 return;
16082
16083 unsigned Attributes = PD->getPropertyAttributes();
16084 if (Attributes & ObjCPropertyAttribute::kind_assign) {
16085 // when 'assign' attribute was not explicitly specified
16086 // by user, ignore it and rely on property type itself
16087 // for lifetime info.
16088 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16089 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16090 LHSType->isObjCRetainableType())
16091 return;
16092
16093 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16094 if (cast->getCastKind() == CK_ARCConsumeObject) {
16095 Diag(Loc, diag::warn_arc_retained_property_assign)
16096 << RHS->getSourceRange();
16097 return;
16098 }
16099 RHS = cast->getSubExpr();
16100 }
16101 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16102 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16103 return;
16104 }
16105 }
16106}
16107
16108//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16109
16110static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16111 SourceLocation StmtLoc,
16112 const NullStmt *Body) {
16113 // Do not warn if the body is a macro that expands to nothing, e.g:
16114 //
16115 // #define CALL(x)
16116 // if (condition)
16117 // CALL(0);
16118 if (Body->hasLeadingEmptyMacro())
16119 return false;
16120
16121 // Get line numbers of statement and body.
16122 bool StmtLineInvalid;
16123 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16124 &StmtLineInvalid);
16125 if (StmtLineInvalid)
16126 return false;
16127
16128 bool BodyLineInvalid;
16129 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16130 &BodyLineInvalid);
16131 if (BodyLineInvalid)
16132 return false;
16133
16134 // Warn if null statement and body are on the same line.
16135 if (StmtLine != BodyLine)
16136 return false;
16137
16138 return true;
16139}
16140
16142 const Stmt *Body,
16143 unsigned DiagID) {
16144 // Since this is a syntactic check, don't emit diagnostic for template
16145 // instantiations, this just adds noise.
16147 return;
16148
16149 // The body should be a null statement.
16150 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16151 if (!NBody)
16152 return;
16153
16154 // Do the usual checks.
16155 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16156 return;
16157
16158 Diag(NBody->getSemiLoc(), DiagID);
16159 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16160}
16161
16163 const Stmt *PossibleBody) {
16164 assert(!CurrentInstantiationScope); // Ensured by caller
16165
16166 SourceLocation StmtLoc;
16167 const Stmt *Body;
16168 unsigned DiagID;
16169 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16170 StmtLoc = FS->getRParenLoc();
16171 Body = FS->getBody();
16172 DiagID = diag::warn_empty_for_body;
16173 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16174 StmtLoc = WS->getRParenLoc();
16175 Body = WS->getBody();
16176 DiagID = diag::warn_empty_while_body;
16177 } else
16178 return; // Neither `for' nor `while'.
16179
16180 // The body should be a null statement.
16181 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16182 if (!NBody)
16183 return;
16184
16185 // Skip expensive checks if diagnostic is disabled.
16186 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16187 return;
16188
16189 // Do the usual checks.
16190 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16191 return;
16192
16193 // `for(...);' and `while(...);' are popular idioms, so in order to keep
16194 // noise level low, emit diagnostics only if for/while is followed by a
16195 // CompoundStmt, e.g.:
16196 // for (int i = 0; i < n; i++);
16197 // {
16198 // a(i);
16199 // }
16200 // or if for/while is followed by a statement with more indentation
16201 // than for/while itself:
16202 // for (int i = 0; i < n; i++);
16203 // a(i);
16204 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16205 if (!ProbableTypo) {
16206 bool BodyColInvalid;
16207 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16208 PossibleBody->getBeginLoc(), &BodyColInvalid);
16209 if (BodyColInvalid)
16210 return;
16211
16212 bool StmtColInvalid;
16213 unsigned StmtCol =
16214 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16215 if (StmtColInvalid)
16216 return;
16217
16218 if (BodyCol > StmtCol)
16219 ProbableTypo = true;
16220 }
16221
16222 if (ProbableTypo) {
16223 Diag(NBody->getSemiLoc(), DiagID);
16224 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16225 }
16226}
16227
16228//===--- CHECK: Warn on self move with std::move. -------------------------===//
16229
16230void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16231 SourceLocation OpLoc) {
16232 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16233 return;
16234
16236 return;
16237
16238 // Strip parens and casts away.
16239 LHSExpr = LHSExpr->IgnoreParenImpCasts();
16240 RHSExpr = RHSExpr->IgnoreParenImpCasts();
16241
16242 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
16243 // which we can treat as an inlined std::move
16244 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
16245 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
16246 RHSExpr = CE->getArg(0);
16247 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
16248 CXXSCE && CXXSCE->isXValue())
16249 RHSExpr = CXXSCE->getSubExpr();
16250 else
16251 return;
16252
16253 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16254 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16255
16256 // Two DeclRefExpr's, check that the decls are the same.
16257 if (LHSDeclRef && RHSDeclRef) {
16258 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16259 return;
16260 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16261 RHSDeclRef->getDecl()->getCanonicalDecl())
16262 return;
16263
16264 auto D = Diag(OpLoc, diag::warn_self_move)
16265 << LHSExpr->getType() << LHSExpr->getSourceRange()
16266 << RHSExpr->getSourceRange();
16267 if (const FieldDecl *F =
16269 D << 1 << F
16270 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
16271 else
16272 D << 0;
16273 return;
16274 }
16275
16276 // Member variables require a different approach to check for self moves.
16277 // MemberExpr's are the same if every nested MemberExpr refers to the same
16278 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16279 // the base Expr's are CXXThisExpr's.
16280 const Expr *LHSBase = LHSExpr;
16281 const Expr *RHSBase = RHSExpr;
16282 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16283 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16284 if (!LHSME || !RHSME)
16285 return;
16286
16287 while (LHSME && RHSME) {
16288 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16289 RHSME->getMemberDecl()->getCanonicalDecl())
16290 return;
16291
16292 LHSBase = LHSME->getBase();
16293 RHSBase = RHSME->getBase();
16294 LHSME = dyn_cast<MemberExpr>(LHSBase);
16295 RHSME = dyn_cast<MemberExpr>(RHSBase);
16296 }
16297
16298 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16299 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16300 if (LHSDeclRef && RHSDeclRef) {
16301 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16302 return;
16303 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16304 RHSDeclRef->getDecl()->getCanonicalDecl())
16305 return;
16306
16307 Diag(OpLoc, diag::warn_self_move)
16308 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16309 << RHSExpr->getSourceRange();
16310 return;
16311 }
16312
16313 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16314 Diag(OpLoc, diag::warn_self_move)
16315 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16316 << RHSExpr->getSourceRange();
16317}
16318
16319//===--- Layout compatibility ----------------------------------------------//
16320
16321static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16322
16323/// Check if two enumeration types are layout-compatible.
16324static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16325 const EnumDecl *ED2) {
16326 // C++11 [dcl.enum] p8:
16327 // Two enumeration types are layout-compatible if they have the same
16328 // underlying type.
16329 return ED1->isComplete() && ED2->isComplete() &&
16330 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16331}
16332
16333/// Check if two fields are layout-compatible.
16334/// Can be used on union members, which are exempt from alignment requirement
16335/// of common initial sequence.
16336static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16337 const FieldDecl *Field2,
16338 bool AreUnionMembers = false) {
16339#ifndef NDEBUG
16340 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16341 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16342 assert(((Field1Parent->isStructureOrClassType() &&
16343 Field2Parent->isStructureOrClassType()) ||
16344 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16345 "Can't evaluate layout compatibility between a struct field and a "
16346 "union field.");
16347 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16348 (AreUnionMembers && Field1Parent->isUnionType())) &&
16349 "AreUnionMembers should be 'true' for union fields (only).");
16350#endif
16351
16352 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16353 return false;
16354
16355 if (Field1->isBitField() != Field2->isBitField())
16356 return false;
16357
16358 if (Field1->isBitField()) {
16359 // Make sure that the bit-fields are the same length.
16360 unsigned Bits1 = Field1->getBitWidthValue();
16361 unsigned Bits2 = Field2->getBitWidthValue();
16362
16363 if (Bits1 != Bits2)
16364 return false;
16365 }
16366
16367 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16368 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16369 return false;
16370
16371 if (!AreUnionMembers &&
16372 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16373 return false;
16374
16375 return true;
16376}
16377
16378/// Check if two standard-layout structs are layout-compatible.
16379/// (C++11 [class.mem] p17)
16380static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16381 const RecordDecl *RD2) {
16382 // Get to the class where the fields are declared
16383 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
16384 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16385
16386 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
16387 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16388
16389 // Check the fields.
16390 return llvm::equal(RD1->fields(), RD2->fields(),
16391 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16392 return isLayoutCompatible(C, F1, F2);
16393 });
16394}
16395
16396/// Check if two standard-layout unions are layout-compatible.
16397/// (C++11 [class.mem] p18)
16398static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16399 const RecordDecl *RD2) {
16400 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16401 RD2->fields());
16402
16403 for (auto *Field1 : RD1->fields()) {
16404 auto I = UnmatchedFields.begin();
16405 auto E = UnmatchedFields.end();
16406
16407 for ( ; I != E; ++I) {
16408 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
16409 bool Result = UnmatchedFields.erase(*I);
16410 (void) Result;
16411 assert(Result);
16412 break;
16413 }
16414 }
16415 if (I == E)
16416 return false;
16417 }
16418
16419 return UnmatchedFields.empty();
16420}
16421
16422static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16423 const RecordDecl *RD2) {
16424 if (RD1->isUnion() != RD2->isUnion())
16425 return false;
16426
16427 if (RD1->isUnion())
16428 return isLayoutCompatibleUnion(C, RD1, RD2);
16429 else
16430 return isLayoutCompatibleStruct(C, RD1, RD2);
16431}
16432
16433/// Check if two types are layout-compatible in C++11 sense.
16434static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16435 if (T1.isNull() || T2.isNull())
16436 return false;
16437
16438 // C++20 [basic.types] p11:
16439 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16440 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16441 // or layout-compatible standard-layout class types (11.4).
16444
16445 if (C.hasSameType(T1, T2))
16446 return true;
16447
16448 const Type::TypeClass TC1 = T1->getTypeClass();
16449 const Type::TypeClass TC2 = T2->getTypeClass();
16450
16451 if (TC1 != TC2)
16452 return false;
16453
16454 if (TC1 == Type::Enum)
16455 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
16456 if (TC1 == Type::Record) {
16457 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16458 return false;
16459
16461 T2->castAsRecordDecl());
16462 }
16463
16464 return false;
16465}
16466
16468 return isLayoutCompatible(getASTContext(), T1, T2);
16469}
16470
16471//===-------------- Pointer interconvertibility ----------------------------//
16472
16474 const TypeSourceInfo *Derived) {
16475 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16476 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16477
16478 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16479 getASTContext().hasSameType(BaseT, DerivedT))
16480 return true;
16481
16482 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
16483 return false;
16484
16485 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16486 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16487 return true;
16488
16489 return false;
16490}
16491
16492//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16493
16494/// Given a type tag expression find the type tag itself.
16495///
16496/// \param TypeExpr Type tag expression, as it appears in user's code.
16497///
16498/// \param VD Declaration of an identifier that appears in a type tag.
16499///
16500/// \param MagicValue Type tag magic value.
16501///
16502/// \param isConstantEvaluated whether the evalaution should be performed in
16503
16504/// constant context.
16505static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16506 const ValueDecl **VD, uint64_t *MagicValue,
16507 bool isConstantEvaluated) {
16508 while(true) {
16509 if (!TypeExpr)
16510 return false;
16511
16512 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16513
16514 switch (TypeExpr->getStmtClass()) {
16515 case Stmt::UnaryOperatorClass: {
16516 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16517 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16518 TypeExpr = UO->getSubExpr();
16519 continue;
16520 }
16521 return false;
16522 }
16523
16524 case Stmt::DeclRefExprClass: {
16525 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16526 *VD = DRE->getDecl();
16527 return true;
16528 }
16529
16530 case Stmt::IntegerLiteralClass: {
16531 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16532 llvm::APInt MagicValueAPInt = IL->getValue();
16533 if (MagicValueAPInt.getActiveBits() <= 64) {
16534 *MagicValue = MagicValueAPInt.getZExtValue();
16535 return true;
16536 } else
16537 return false;
16538 }
16539
16540 case Stmt::BinaryConditionalOperatorClass:
16541 case Stmt::ConditionalOperatorClass: {
16542 const AbstractConditionalOperator *ACO =
16544 bool Result;
16545 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16546 isConstantEvaluated)) {
16547 if (Result)
16548 TypeExpr = ACO->getTrueExpr();
16549 else
16550 TypeExpr = ACO->getFalseExpr();
16551 continue;
16552 }
16553 return false;
16554 }
16555
16556 case Stmt::BinaryOperatorClass: {
16557 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16558 if (BO->getOpcode() == BO_Comma) {
16559 TypeExpr = BO->getRHS();
16560 continue;
16561 }
16562 return false;
16563 }
16564
16565 default:
16566 return false;
16567 }
16568 }
16569}
16570
16571/// Retrieve the C type corresponding to type tag TypeExpr.
16572///
16573/// \param TypeExpr Expression that specifies a type tag.
16574///
16575/// \param MagicValues Registered magic values.
16576///
16577/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16578/// kind.
16579///
16580/// \param TypeInfo Information about the corresponding C type.
16581///
16582/// \param isConstantEvaluated whether the evalaution should be performed in
16583/// constant context.
16584///
16585/// \returns true if the corresponding C type was found.
16587 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16588 const ASTContext &Ctx,
16589 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16590 *MagicValues,
16591 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16592 bool isConstantEvaluated) {
16593 FoundWrongKind = false;
16594
16595 // Variable declaration that has type_tag_for_datatype attribute.
16596 const ValueDecl *VD = nullptr;
16597
16598 uint64_t MagicValue;
16599
16600 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16601 return false;
16602
16603 if (VD) {
16604 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16605 if (I->getArgumentKind() != ArgumentKind) {
16606 FoundWrongKind = true;
16607 return false;
16608 }
16609 TypeInfo.Type = I->getMatchingCType();
16610 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16611 TypeInfo.MustBeNull = I->getMustBeNull();
16612 return true;
16613 }
16614 return false;
16615 }
16616
16617 if (!MagicValues)
16618 return false;
16619
16620 llvm::DenseMap<Sema::TypeTagMagicValue,
16622 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16623 if (I == MagicValues->end())
16624 return false;
16625
16626 TypeInfo = I->second;
16627 return true;
16628}
16629
16631 uint64_t MagicValue, QualType Type,
16632 bool LayoutCompatible,
16633 bool MustBeNull) {
16634 if (!TypeTagForDatatypeMagicValues)
16635 TypeTagForDatatypeMagicValues.reset(
16636 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16637
16638 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16639 (*TypeTagForDatatypeMagicValues)[Magic] =
16640 TypeTagData(Type, LayoutCompatible, MustBeNull);
16641}
16642
16643static bool IsSameCharType(QualType T1, QualType T2) {
16644 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16645 if (!BT1)
16646 return false;
16647
16648 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16649 if (!BT2)
16650 return false;
16651
16652 BuiltinType::Kind T1Kind = BT1->getKind();
16653 BuiltinType::Kind T2Kind = BT2->getKind();
16654
16655 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16656 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16657 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16658 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16659}
16660
16661void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16662 const ArrayRef<const Expr *> ExprArgs,
16663 SourceLocation CallSiteLoc) {
16664 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16665 bool IsPointerAttr = Attr->getIsPointer();
16666
16667 // Retrieve the argument representing the 'type_tag'.
16668 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16669 if (TypeTagIdxAST >= ExprArgs.size()) {
16670 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16671 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16672 return;
16673 }
16674 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16675 bool FoundWrongKind;
16676 TypeTagData TypeInfo;
16677 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16678 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16679 TypeInfo, isConstantEvaluatedContext())) {
16680 if (FoundWrongKind)
16681 Diag(TypeTagExpr->getExprLoc(),
16682 diag::warn_type_tag_for_datatype_wrong_kind)
16683 << TypeTagExpr->getSourceRange();
16684 return;
16685 }
16686
16687 // Retrieve the argument representing the 'arg_idx'.
16688 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16689 if (ArgumentIdxAST >= ExprArgs.size()) {
16690 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16691 << 1 << Attr->getArgumentIdx().getSourceIndex();
16692 return;
16693 }
16694 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16695 if (IsPointerAttr) {
16696 // Skip implicit cast of pointer to `void *' (as a function argument).
16697 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16698 if (ICE->getType()->isVoidPointerType() &&
16699 ICE->getCastKind() == CK_BitCast)
16700 ArgumentExpr = ICE->getSubExpr();
16701 }
16702 QualType ArgumentType = ArgumentExpr->getType();
16703
16704 // Passing a `void*' pointer shouldn't trigger a warning.
16705 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16706 return;
16707
16708 if (TypeInfo.MustBeNull) {
16709 // Type tag with matching void type requires a null pointer.
16710 if (!ArgumentExpr->isNullPointerConstant(Context,
16712 Diag(ArgumentExpr->getExprLoc(),
16713 diag::warn_type_safety_null_pointer_required)
16714 << ArgumentKind->getName()
16715 << ArgumentExpr->getSourceRange()
16716 << TypeTagExpr->getSourceRange();
16717 }
16718 return;
16719 }
16720
16721 QualType RequiredType = TypeInfo.Type;
16722 if (IsPointerAttr)
16723 RequiredType = Context.getPointerType(RequiredType);
16724
16725 bool mismatch = false;
16726 if (!TypeInfo.LayoutCompatible) {
16727 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16728
16729 // C++11 [basic.fundamental] p1:
16730 // Plain char, signed char, and unsigned char are three distinct types.
16731 //
16732 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16733 // char' depending on the current char signedness mode.
16734 if (mismatch)
16735 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16736 RequiredType->getPointeeType())) ||
16737 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16738 mismatch = false;
16739 } else
16740 if (IsPointerAttr)
16741 mismatch = !isLayoutCompatible(Context,
16742 ArgumentType->getPointeeType(),
16743 RequiredType->getPointeeType());
16744 else
16745 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16746
16747 if (mismatch)
16748 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16749 << ArgumentType << ArgumentKind
16750 << TypeInfo.LayoutCompatible << RequiredType
16751 << ArgumentExpr->getSourceRange()
16752 << TypeTagExpr->getSourceRange();
16753}
16754
16755void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16756 CharUnits Alignment) {
16757 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
16758 Alignment);
16759}
16760
16762 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16763 const NamedDecl *ND = m.RD;
16764 if (ND->getName().empty()) {
16765 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16766 ND = TD;
16767 }
16768 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16769 << m.MD << ND << m.E->getSourceRange();
16770 }
16772}
16773
16775 E = E->IgnoreParens();
16776 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16777 return;
16778 if (isa<UnaryOperator>(E) &&
16779 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16780 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16781 if (isa<MemberExpr>(Op)) {
16782 auto &MisalignedMembersForExpr =
16784 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
16785 if (MA != MisalignedMembersForExpr.end() &&
16786 (T->isDependentType() || T->isIntegerType() ||
16787 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16788 Context.getTypeAlignInChars(
16789 T->getPointeeType()) <= MA->Alignment))))
16790 MisalignedMembersForExpr.erase(MA);
16791 }
16792 }
16793}
16794
16796 Expr *E,
16797 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16798 Action) {
16799 const auto *ME = dyn_cast<MemberExpr>(E);
16800 if (!ME)
16801 return;
16802
16803 // No need to check expressions with an __unaligned-qualified type.
16804 if (E->getType().getQualifiers().hasUnaligned())
16805 return;
16806
16807 // For a chain of MemberExpr like "a.b.c.d" this list
16808 // will keep FieldDecl's like [d, c, b].
16809 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16810 const MemberExpr *TopME = nullptr;
16811 bool AnyIsPacked = false;
16812 do {
16813 QualType BaseType = ME->getBase()->getType();
16814 if (BaseType->isDependentType())
16815 return;
16816 if (ME->isArrow())
16817 BaseType = BaseType->getPointeeType();
16818 auto *RD = BaseType->castAsRecordDecl();
16819 if (RD->isInvalidDecl())
16820 return;
16821
16822 ValueDecl *MD = ME->getMemberDecl();
16823 auto *FD = dyn_cast<FieldDecl>(MD);
16824 // We do not care about non-data members.
16825 if (!FD || FD->isInvalidDecl())
16826 return;
16827
16828 AnyIsPacked =
16829 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16830 ReverseMemberChain.push_back(FD);
16831
16832 TopME = ME;
16833 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16834 } while (ME);
16835 assert(TopME && "We did not compute a topmost MemberExpr!");
16836
16837 // Not the scope of this diagnostic.
16838 if (!AnyIsPacked)
16839 return;
16840
16841 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16842 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16843 // TODO: The innermost base of the member expression may be too complicated.
16844 // For now, just disregard these cases. This is left for future
16845 // improvement.
16846 if (!DRE && !isa<CXXThisExpr>(TopBase))
16847 return;
16848
16849 // Alignment expected by the whole expression.
16850 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16851
16852 // No need to do anything else with this case.
16853 if (ExpectedAlignment.isOne())
16854 return;
16855
16856 // Synthesize offset of the whole access.
16857 CharUnits Offset;
16858 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16859 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16860
16861 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16862 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16863 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
16864
16865 // The base expression of the innermost MemberExpr may give
16866 // stronger guarantees than the class containing the member.
16867 if (DRE && !TopME->isArrow()) {
16868 const ValueDecl *VD = DRE->getDecl();
16869 if (!VD->getType()->isReferenceType())
16870 CompleteObjectAlignment =
16871 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16872 }
16873
16874 // Check if the synthesized offset fulfills the alignment.
16875 if (!Offset.isMultipleOf(ExpectedAlignment) ||
16876 // It may fulfill the offset it but the effective alignment may still be
16877 // lower than the expected expression alignment.
16878 CompleteObjectAlignment < ExpectedAlignment) {
16879 // If this happens, we want to determine a sensible culprit of this.
16880 // Intuitively, watching the chain of member expressions from right to
16881 // left, we start with the required alignment (as required by the field
16882 // type) but some packed attribute in that chain has reduced the alignment.
16883 // It may happen that another packed structure increases it again. But if
16884 // we are here such increase has not been enough. So pointing the first
16885 // FieldDecl that either is packed or else its RecordDecl is,
16886 // seems reasonable.
16887 FieldDecl *FD = nullptr;
16888 CharUnits Alignment;
16889 for (FieldDecl *FDI : ReverseMemberChain) {
16890 if (FDI->hasAttr<PackedAttr>() ||
16891 FDI->getParent()->hasAttr<PackedAttr>()) {
16892 FD = FDI;
16893 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
16894 Context.getTypeAlignInChars(
16895 Context.getCanonicalTagType(FD->getParent())));
16896 break;
16897 }
16898 }
16899 assert(FD && "We did not find a packed FieldDecl!");
16900 Action(E, FD->getParent(), FD, Alignment);
16901 }
16902}
16903
16904void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16905 using namespace std::placeholders;
16906
16908 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16909 _2, _3, _4));
16910}
16911
16913 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16914 if (checkArgCount(TheCall, 1))
16915 return true;
16916
16917 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
16918 if (A.isInvalid())
16919 return true;
16920
16921 TheCall->setArg(0, A.get());
16922 QualType TyA = A.get()->getType();
16923
16924 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
16925 ArgTyRestr, 1))
16926 return true;
16927
16928 TheCall->setType(TyA);
16929 return false;
16930}
16931
16932bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
16933 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16934 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
16935 TheCall->setType(*Res);
16936 return false;
16937 }
16938 return true;
16939}
16940
16942 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
16943 if (!Res)
16944 return true;
16945
16946 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
16947 TheCall->setType(VecTy0->getElementType());
16948 else
16949 TheCall->setType(*Res);
16950
16951 return false;
16952}
16953
16955 SourceLocation Loc) {
16957 R = RHS->getEnumCoercedType(S.Context);
16958 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
16960 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
16961 << LHS->getSourceRange() << RHS->getSourceRange()
16962 << /*Arithmetic Between*/ 0 << L << R;
16963 }
16964 return false;
16965}
16966
16967/// Check if all arguments have the same type. If the types don't match, emit an
16968/// error message and return true. Otherwise return false.
16969///
16970/// For scalars we directly compare their unqualified types. But even if we
16971/// compare unqualified vector types, a difference in qualifiers in the element
16972/// types can make the vector types be considered not equal. For example,
16973/// vector of 4 'const float' values vs vector of 4 'float' values.
16974/// So we compare unqualified types of their elements and number of elements.
16976 ArrayRef<Expr *> Args) {
16977 assert(!Args.empty() && "Should have at least one argument.");
16978
16979 Expr *Arg0 = Args.front();
16980 QualType Ty0 = Arg0->getType();
16981
16982 auto EmitError = [&](Expr *ArgI) {
16983 SemaRef.Diag(Arg0->getBeginLoc(),
16984 diag::err_typecheck_call_different_arg_types)
16985 << Arg0->getType() << ArgI->getType();
16986 };
16987
16988 // Compare scalar types.
16989 if (!Ty0->isVectorType()) {
16990 for (Expr *ArgI : Args.drop_front())
16991 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
16992 EmitError(ArgI);
16993 return true;
16994 }
16995
16996 return false;
16997 }
16998
16999 // Compare vector types.
17000 const auto *Vec0 = Ty0->castAs<VectorType>();
17001 for (Expr *ArgI : Args.drop_front()) {
17002 const auto *VecI = ArgI->getType()->getAs<VectorType>();
17003 if (!VecI ||
17004 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
17005 VecI->getElementType()) ||
17006 Vec0->getNumElements() != VecI->getNumElements()) {
17007 EmitError(ArgI);
17008 return true;
17009 }
17010 }
17011
17012 return false;
17013}
17014
17015std::optional<QualType>
17017 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17018 if (checkArgCount(TheCall, 2))
17019 return std::nullopt;
17020
17022 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
17023 return std::nullopt;
17024
17025 Expr *Args[2];
17026 for (int I = 0; I < 2; ++I) {
17027 ExprResult Converted =
17028 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
17029 if (Converted.isInvalid())
17030 return std::nullopt;
17031 Args[I] = Converted.get();
17032 }
17033
17034 SourceLocation LocA = Args[0]->getBeginLoc();
17035 QualType TyA = Args[0]->getType();
17036
17037 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
17038 return std::nullopt;
17039
17040 if (checkBuiltinVectorMathArgTypes(*this, Args))
17041 return std::nullopt;
17042
17043 TheCall->setArg(0, Args[0]);
17044 TheCall->setArg(1, Args[1]);
17045 return TyA;
17046}
17047
17049 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17050 if (checkArgCount(TheCall, 3))
17051 return true;
17052
17053 SourceLocation Loc = TheCall->getExprLoc();
17054 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
17055 TheCall->getArg(1), Loc) ||
17056 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
17057 TheCall->getArg(2), Loc))
17058 return true;
17059
17060 Expr *Args[3];
17061 for (int I = 0; I < 3; ++I) {
17062 ExprResult Converted =
17063 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
17064 if (Converted.isInvalid())
17065 return true;
17066 Args[I] = Converted.get();
17067 }
17068
17069 int ArgOrdinal = 1;
17070 for (Expr *Arg : Args) {
17071 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
17072 ArgTyRestr, ArgOrdinal++))
17073 return true;
17074 }
17075
17076 if (checkBuiltinVectorMathArgTypes(*this, Args))
17077 return true;
17078
17079 for (int I = 0; I < 3; ++I)
17080 TheCall->setArg(I, Args[I]);
17081
17082 TheCall->setType(Args[0]->getType());
17083 return false;
17084}
17085
17086bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17087 if (checkArgCount(TheCall, 1))
17088 return true;
17089
17090 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17091 if (A.isInvalid())
17092 return true;
17093
17094 TheCall->setArg(0, A.get());
17095 return false;
17096}
17097
17098bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
17099 if (checkArgCount(TheCall, 1))
17100 return true;
17101
17102 ExprResult Arg = TheCall->getArg(0);
17103 QualType TyArg = Arg.get()->getType();
17104
17105 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
17106 return Diag(TheCall->getArg(0)->getBeginLoc(),
17107 diag::err_builtin_invalid_arg_type)
17108 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
17109
17110 TheCall->setType(TyArg);
17111 return false;
17112}
17113
17114ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
17115 ExprResult CallResult) {
17116 if (checkArgCount(TheCall, 1))
17117 return ExprError();
17118
17119 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17120 if (MatrixArg.isInvalid())
17121 return MatrixArg;
17122 Expr *Matrix = MatrixArg.get();
17123
17124 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17125 if (!MType) {
17126 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17127 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
17128 << Matrix->getType();
17129 return ExprError();
17130 }
17131
17132 // Create returned matrix type by swapping rows and columns of the argument
17133 // matrix type.
17134 QualType ResultType = Context.getConstantMatrixType(
17135 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17136
17137 // Change the return type to the type of the returned matrix.
17138 TheCall->setType(ResultType);
17139
17140 // Update call argument to use the possibly converted matrix argument.
17141 TheCall->setArg(0, Matrix);
17142 return CallResult;
17143}
17144
17145// Get and verify the matrix dimensions.
17146static std::optional<unsigned>
17148 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
17149 if (!Value) {
17150 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17151 << Name;
17152 return {};
17153 }
17154 uint64_t Dim = Value->getZExtValue();
17155 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
17156 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17157 << Name << S.Context.getLangOpts().MaxMatrixDimension;
17158 return {};
17159 }
17160 return Dim;
17161}
17162
17163ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17164 ExprResult CallResult) {
17165 if (!getLangOpts().MatrixTypes) {
17166 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17167 return ExprError();
17168 }
17169
17170 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17172 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17173 << /*column*/ 1 << /*load*/ 0;
17174 return ExprError();
17175 }
17176
17177 if (checkArgCount(TheCall, 4))
17178 return ExprError();
17179
17180 unsigned PtrArgIdx = 0;
17181 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17182 Expr *RowsExpr = TheCall->getArg(1);
17183 Expr *ColumnsExpr = TheCall->getArg(2);
17184 Expr *StrideExpr = TheCall->getArg(3);
17185
17186 bool ArgError = false;
17187
17188 // Check pointer argument.
17189 {
17191 if (PtrConv.isInvalid())
17192 return PtrConv;
17193 PtrExpr = PtrConv.get();
17194 TheCall->setArg(0, PtrExpr);
17195 if (PtrExpr->isTypeDependent()) {
17196 TheCall->setType(Context.DependentTy);
17197 return TheCall;
17198 }
17199 }
17200
17201 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17202 QualType ElementTy;
17203 if (!PtrTy) {
17204 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17205 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
17206 << PtrExpr->getType();
17207 ArgError = true;
17208 } else {
17209 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17210
17212 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17213 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
17214 << /* no fp */ 0 << PtrExpr->getType();
17215 ArgError = true;
17216 }
17217 }
17218
17219 // Apply default Lvalue conversions and convert the expression to size_t.
17220 auto ApplyArgumentConversions = [this](Expr *E) {
17222 if (Conv.isInvalid())
17223 return Conv;
17224
17225 return tryConvertExprToType(Conv.get(), Context.getSizeType());
17226 };
17227
17228 // Apply conversion to row and column expressions.
17229 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17230 if (!RowsConv.isInvalid()) {
17231 RowsExpr = RowsConv.get();
17232 TheCall->setArg(1, RowsExpr);
17233 } else
17234 RowsExpr = nullptr;
17235
17236 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17237 if (!ColumnsConv.isInvalid()) {
17238 ColumnsExpr = ColumnsConv.get();
17239 TheCall->setArg(2, ColumnsExpr);
17240 } else
17241 ColumnsExpr = nullptr;
17242
17243 // If any part of the result matrix type is still pending, just use
17244 // Context.DependentTy, until all parts are resolved.
17245 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17246 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17247 TheCall->setType(Context.DependentTy);
17248 return CallResult;
17249 }
17250
17251 // Check row and column dimensions.
17252 std::optional<unsigned> MaybeRows;
17253 if (RowsExpr)
17254 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17255
17256 std::optional<unsigned> MaybeColumns;
17257 if (ColumnsExpr)
17258 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17259
17260 // Check stride argument.
17261 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17262 if (StrideConv.isInvalid())
17263 return ExprError();
17264 StrideExpr = StrideConv.get();
17265 TheCall->setArg(3, StrideExpr);
17266
17267 if (MaybeRows) {
17268 if (std::optional<llvm::APSInt> Value =
17269 StrideExpr->getIntegerConstantExpr(Context)) {
17270 uint64_t Stride = Value->getZExtValue();
17271 if (Stride < *MaybeRows) {
17272 Diag(StrideExpr->getBeginLoc(),
17273 diag::err_builtin_matrix_stride_too_small);
17274 ArgError = true;
17275 }
17276 }
17277 }
17278
17279 if (ArgError || !MaybeRows || !MaybeColumns)
17280 return ExprError();
17281
17282 TheCall->setType(
17283 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17284 return CallResult;
17285}
17286
17287ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17288 ExprResult CallResult) {
17289 if (!getLangOpts().MatrixTypes) {
17290 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17291 return ExprError();
17292 }
17293
17294 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17296 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17297 << /*column*/ 1 << /*store*/ 1;
17298 return ExprError();
17299 }
17300
17301 if (checkArgCount(TheCall, 3))
17302 return ExprError();
17303
17304 unsigned PtrArgIdx = 1;
17305 Expr *MatrixExpr = TheCall->getArg(0);
17306 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17307 Expr *StrideExpr = TheCall->getArg(2);
17308
17309 bool ArgError = false;
17310
17311 {
17312 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17313 if (MatrixConv.isInvalid())
17314 return MatrixConv;
17315 MatrixExpr = MatrixConv.get();
17316 TheCall->setArg(0, MatrixExpr);
17317 }
17318 if (MatrixExpr->isTypeDependent()) {
17319 TheCall->setType(Context.DependentTy);
17320 return TheCall;
17321 }
17322
17323 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17324 if (!MatrixTy) {
17325 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17326 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17327 ArgError = true;
17328 }
17329
17330 {
17332 if (PtrConv.isInvalid())
17333 return PtrConv;
17334 PtrExpr = PtrConv.get();
17335 TheCall->setArg(1, PtrExpr);
17336 if (PtrExpr->isTypeDependent()) {
17337 TheCall->setType(Context.DependentTy);
17338 return TheCall;
17339 }
17340 }
17341
17342 // Check pointer argument.
17343 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17344 if (!PtrTy) {
17345 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17346 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17347 << PtrExpr->getType();
17348 ArgError = true;
17349 } else {
17350 QualType ElementTy = PtrTy->getPointeeType();
17351 if (ElementTy.isConstQualified()) {
17352 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17353 ArgError = true;
17354 }
17355 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17356 if (MatrixTy &&
17357 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17358 Diag(PtrExpr->getBeginLoc(),
17359 diag::err_builtin_matrix_pointer_arg_mismatch)
17360 << ElementTy << MatrixTy->getElementType();
17361 ArgError = true;
17362 }
17363 }
17364
17365 // Apply default Lvalue conversions and convert the stride expression to
17366 // size_t.
17367 {
17368 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17369 if (StrideConv.isInvalid())
17370 return StrideConv;
17371
17372 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17373 if (StrideConv.isInvalid())
17374 return StrideConv;
17375 StrideExpr = StrideConv.get();
17376 TheCall->setArg(2, StrideExpr);
17377 }
17378
17379 // Check stride argument.
17380 if (MatrixTy) {
17381 if (std::optional<llvm::APSInt> Value =
17382 StrideExpr->getIntegerConstantExpr(Context)) {
17383 uint64_t Stride = Value->getZExtValue();
17384 if (Stride < MatrixTy->getNumRows()) {
17385 Diag(StrideExpr->getBeginLoc(),
17386 diag::err_builtin_matrix_stride_too_small);
17387 ArgError = true;
17388 }
17389 }
17390 }
17391
17392 if (ArgError)
17393 return ExprError();
17394
17395 return CallResult;
17396}
17397
17399 const NamedDecl *Callee) {
17400 // This warning does not make sense in code that has no runtime behavior.
17402 return;
17403
17404 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17405
17406 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17407 return;
17408
17409 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17410 // all TCBs the callee is a part of.
17411 llvm::StringSet<> CalleeTCBs;
17412 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17413 CalleeTCBs.insert(A->getTCBName());
17414 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17415 CalleeTCBs.insert(A->getTCBName());
17416
17417 // Go through the TCBs the caller is a part of and emit warnings if Caller
17418 // is in a TCB that the Callee is not.
17419 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17420 StringRef CallerTCB = A->getTCBName();
17421 if (CalleeTCBs.count(CallerTCB) == 0) {
17422 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17423 << Callee << CallerTCB;
17424 }
17425 }
17426}
Defines the clang::ASTContext interface.
#define V(N, I)
Provides definitions for the various language-specific address spaces.
Defines the Diagnostic-related interfaces.
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:630
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
std::shared_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token's formatting.
unsigned IsFirst
Indicates that this is the first token of the file.
TokenType getType() const
Returns the token's type, e.g.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Result
Implement __builtin_bit_cast and related operations.
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:51
llvm::MachO::Record Record
Definition MachO.h:31
#define SM(sm)
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)
llvm::json::Object Object
llvm::json::Array Array
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis functions specific to BPF.
static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout unions are layout-compatible.
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 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 checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind, bool RequireConstant=false)
static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall)
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 builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall)
static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call)
static bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType, QualType T)
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 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 bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, Expr *Other, const llvm::APSInt &Value, bool RhsConstant)
static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex, bool ToBool)
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, const IdentifierInfo *FnName, SourceLocation FnLoc, SourceLocation RParenLoc)
Takes the expression passed to the size_t parameter of functions such as memcmp, strncat,...
static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall)
static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_stdc_rotate_{left,right} was called with two arguments, that the first argument...
static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref, ArrayRef< EquatableFormatArgument > RefArgs, const StringLiteral *Fmt, ArrayRef< EquatableFormatArgument > FmtArgs, const Expr *FmtExpr, bool InFunctionCall)
static bool BuiltinBswapg(Sema &S, CallExpr *TheCall)
Checks that __builtin_bswapg was called with a single argument, which is an unsigned integer,...
static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall)
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 void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, bool inFunctionCall, VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, bool IgnoreStringsWithoutSpecifiers)
static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall)
Check the number of arguments and set the result type to the argument type.
static bool CheckForReference(Sema &SemaRef, const Expr *E, const PartialDiagnostic &PD)
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 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
static bool isKnownToHaveUnsignedValue(const Expr *E)
static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef, ArrayRef< Expr * > Args)
Check if all arguments have the same type.
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)
static ExprResult BuiltinMaskedStore(Sema &S, CallExpr *TheCall)
AbsoluteValueKind
@ AVK_Complex
@ AVK_Floating
@ AVK_Integer
static const Expr * getStrlenExprArg(const Expr *E)
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check)
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 isValidMathElementType(QualType T)
static void DiagnoseDeprecatedHIPAtomic(Sema &S, SourceRange ExprRange, MultiExprArg Args, AtomicExpr::AtomicOp Op)
Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_* equivalents.
static bool IsSameCharType(QualType T1, QualType T2)
static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E)
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall)
static bool isArgumentExpandedFromMacro(SourceManager &SM, SourceLocation CallLoc, SourceLocation ArgLoc)
Check if the ArgLoc originated from a macro passed to the call at CallLoc.
static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth)
static const IntegerLiteral * getIntegerLiteral(Expr *E)
#define HIP_ATOMIC_FIXABLE(hip, scoped)
static bool CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall, ArrayRef< llvm::Triple::ArchType > SupportedArchs)
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 std::pair< const ValueDecl *, CharUnits > findConstantBaseAndOffset(Sema &S, Expr *E)
static QualType getVectorElementType(ASTContext &Context, QualType VecTy)
static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E)
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
static std::optional< IntRange > TryGetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, bool InConstantContext, bool Approximate)
Attempts to estimate an approximate range for the given integer expression.
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
static ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall)
static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall, SourceLocation CC)
static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall)
Checks that __builtin_bitreverseg was called with a single argument, which is an integer.
static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool &ICContext)
static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall)
static bool CheckMissingFormatAttribute(Sema *S, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, StringLiteral *ReferenceFormatString, unsigned FormatIdx, unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx, SourceLocation Loc)
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 void CheckCommaOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool ExtraCheckForImplicitConversion, llvm::SmallVectorImpl< AnalyzeImplicitConversionsWorkItem > &WorkList)
static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T, SourceLocation CContext)
Diagnose an implicit cast from a floating point value to an integer value.
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 isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2)
Check if two types are layout-compatible in C++11 sense.
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 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool IsInfinityFunction(const FunctionDecl *FDecl)
static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType, QualType T, SourceLocation CContext, unsigned diag, bool PruneControlFlow=false)
Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr * > Args, SourceLocation CallSiteLoc)
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction)
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 ExprResult BuiltinMaskedScatter(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 ExprResult GetVTablePointer(Sema &S, CallExpr *Call)
static bool requiresParensToAddCast(const Expr *E)
static bool HasEnumType(const Expr *E)
static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call)
static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall)
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
static StringLiteralCheckType checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString, const Expr *E, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset, std::optional< unsigned > *CallerFormatParamIdx=nullptr, bool IgnoreStringsWithoutSpecifiers=false)
static std::optional< unsigned > getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S)
static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty)
static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call)
static bool ProcessFormatStringLiteral(const Expr *FormatExpr, StringRef &FormatStrRef, size_t &StrLen, ASTContext &Context)
static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout structs are layout-compatible.
static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall)
Checks that __builtin_popcountg was called with a single argument, which is an unsigned integer.
static const Expr * getSizeOfExprArg(const Expr *E)
If E is a sizeof expression, returns its argument expression, otherwise returns NULL.
static void DiagnoseIntInBoolContext(Sema &S, Expr *E)
static bool CheckBuiltinTargetNotInUnsupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall, ArrayRef< llvm::Triple::ObjectFormatType > UnsupportedObjectFormatTypes)
static void DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source, const Type *Target, Expr *E, QualType T, SourceLocation CC)
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 bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg, unsigned Pos, bool AllowConst, bool AllowAS)
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 ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call, PointerAuthOpKind OpKind, bool RequireConstant)
static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S)
static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr, int ArgOrdinal)
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 QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall)
static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall)
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 ExprResult PointerAuthAuthLoadRelativeAndSign(Sema &S, CallExpr *Call)
static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall, QualType ReturnType)
Checks the __builtin_stdc_* builtins that take a single unsigned integer argument and return either i...
static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
static bool isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE)
Return true if ICE is an implicit argument promotion of an arithmetic type.
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 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 BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
This file declares semantic analysis for DirectX constructs.
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis functions specific to Hexagon.
This file declares semantic analysis functions specific to LoongArch.
This file declares semantic analysis functions specific to MIPS.
This file declares semantic analysis functions specific to NVPTX.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis routines for OpenCL.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SPIRV constructs.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to SystemZ.
This file declares semantic analysis functions specific to Wasm.
This file declares semantic analysis functions specific to X86.
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.
C Language Family Type Representation.
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
C Language Family Type Representation.
__DEVICE__ int min(int __a, int __b)
@ GE_None
No error.
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatch
The conversion specifier and the argument types are incompatible.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ MatchPromotion
The conversion specifier and the argument type are compatible because of default argument promotions.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
@ NoMatchTypeConfusion
The conversion specifier and the argument type are compatible, but still seems likely to be an error.
@ NoMatchPromotionTypeConfusion
The conversion specifier and the argument type are compatible but still seems likely to be an error.
unsigned getLength() const
const char * getStart() const
StringRef toString() const
const char * getStart() const
HowSpecified getHowSpecified() const
unsigned getConstantAmount() const
unsigned getConstantLength() const
bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx, bool IsObjCLiteral)
Changes the specifier and length according to a QualType, retaining any flags or options.
void toString(raw_ostream &os) const
Sema::SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when the only matching conversion function is explicit.
Sema::SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when the expression has incomplete class type.
Sema::SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for one of the candidate conversions.
Sema::SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when there are multiple possible conversion functions.
Sema::SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
Sema::SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
Sema::SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for the explicit conversion function.
bool match(QualType T) override
Determine whether the specified type is a valid destination type for this conversion.
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
void toString(raw_ostream &os) const
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
APSInt & getInt()
Definition APValue.h:508
bool isVector() const
Definition APValue.h:491
APSInt & getComplexIntImag()
Definition APValue.h:546
bool isComplexInt() const
Definition APValue.h:488
bool isFloat() const
Definition APValue.h:486
bool isComplexFloat() const
Definition APValue.h:489
APValue & getVectorElt(unsigned I)
Definition APValue.h:582
unsigned getVectorLength() const
Definition APValue.h:590
bool isLValue() const
Definition APValue.h:490
bool isInt() const
Definition APValue.h:485
APValue & getMatrixElt(unsigned Idx)
Definition APValue.h:606
APSInt & getComplexIntReal()
Definition APValue.h:538
APFloat & getComplexFloatImag()
Definition APValue.h:562
APFloat & getComplexFloatReal()
Definition APValue.h:554
APFloat & getFloat()
Definition APValue.h:522
bool isMatrix() const
Definition APValue.h:492
unsigned getMatrixNumElements() const
Definition APValue.h:603
bool isAddrLabelDiff() const
Definition APValue.h:497
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
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
IdentifierTable & Idents
Definition ASTContext.h:802
Builtin::Context & BuiltinInfo
Definition ASTContext.h:804
const LangOptions & getLangOpts() const
Definition ASTContext.h:959
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.
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
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType CharTy
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:855
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.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
CanQualType UnsignedIntTy
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
CanQualType UnsignedShortTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:921
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 getCanonicalTagType(const TagDecl *TD) const
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
@ GE_None
No error.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getNonVirtualAlignment() const
getNonVirtualAlignment - Get the non-virtual alignment (in chars) of an object, which is the alignmen...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4359
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4537
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4543
SourceLocation getQuestionLoc() const
Definition Expr.h:4386
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4549
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Expr * getBase()
Get base of the array section.
Definition Expr.h:7300
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7304
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2727
SourceLocation getRBracketLoc() const
Definition Expr.h:2775
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2756
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3786
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3800
QualType getElementType() const
Definition TypeBase.h:3798
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6931
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:7080
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:7062
Attr - This represents one attribute.
Definition Attr.h:46
const char * getSpelling() const
Type source information for an attributed type.
Definition TypeLoc.h:1008
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1022
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4177
Expr * getLHS() const
Definition Expr.h:4094
SourceLocation getOperatorLoc() const
Definition Expr.h:4086
SourceLocation getExprLoc() const
Definition Expr.h:4085
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2140
Expr * getRHS() const
Definition Expr.h:4096
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4130
Opcode getOpcode() const
Definition Expr.h:4089
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4141
BinaryOperatorKind Opcode
Definition Expr.h:4049
Pointer to a block type.
Definition TypeBase.h:3606
This class is used for builtin types like 'int'.
Definition TypeBase.h:3228
bool isInteger() const
Definition TypeBase.h:3289
bool isFloatingPoint() const
Definition TypeBase.h:3301
bool isSignedInteger() const
Definition TypeBase.h:3293
bool isUnsignedInteger() const
Definition TypeBase.h:3297
Kind getKind() const
Definition TypeBase.h:3276
std::string getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:85
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:383
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition Builtins.cpp:80
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition Expr.h:3975
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition ExprCXX.h:1634
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1692
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2965
Represents a C++ destructor within a class.
Definition DeclCXX.h:2895
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:85
SourceLocation getExprLoc() const LLVM_READONLY
Definition ExprCXX.h:158
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:115
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5141
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5181
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:1230
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1219
bool isDynamicClass() const
Definition DeclCXX.h:574
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2949
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3153
SourceLocation getBeginLoc() const
Definition Expr.h:3283
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3166
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1598
arg_iterator arg_begin()
Definition Expr.h:3206
arg_iterator arg_end()
Definition Expr.h:3209
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3132
bool isCallToStdMove() const
Definition Expr.cpp:3651
Expr * getCallee()
Definition Expr.h:3096
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3140
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3242
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3143
arg_range arguments()
Definition Expr.h:3201
SourceLocation getEndLoc() const
Definition Expr.h:3302
SourceLocation getRParenLoc() const
Definition Expr.h:3280
Decl * getCalleeDecl()
Definition Expr.h:3126
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:1603
void setCallee(Expr *F)
Definition Expr.h:3098
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition Expr.h:3185
QualType withConst() const
Retrieves a version of this type with const applied.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3682
path_iterator path_begin()
Definition Expr.h:3752
CastKind getCastKind() const
Definition Expr.h:3726
path_iterator path_end()
Definition Expr.h:3753
Expr * getSubExpr()
Definition Expr.h:3732
Represents a byte-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
ConditionalOperator - The ?
Definition Expr.h:4397
Expr * getLHS() const
Definition Expr.h:4431
Expr * getRHS() const
Definition Expr.h:4432
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3824
QualType desugar() const
Definition TypeBase.h:3925
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3880
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4451
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4473
static ConvertVectorExpr * Create(const ASTContext &C, Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType, ExprValueKind VK, ExprObjectKind OK, SourceLocation BuiltinLoc, SourceLocation RParenLoc, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5683
Expr * getOperand() const
Definition ExprCXX.h:5320
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool isStdNamespace() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2386
bool isFunctionOrMethod() const
Definition DeclBase.h:2174
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
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:494
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1369
ValueDecl * getDecl()
Definition Expr.h:1344
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1474
SourceLocation getBeginLoc() const
Definition Expr.h:1355
SourceLocation getLocation() const
Definition Expr.h:1352
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:450
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:443
T * getAttr() const
Definition DeclBase.h:581
void addAttr(Attr *A)
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:561
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
bool isInvalidDecl() const
Definition DeclBase.h:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:991
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:435
The name of a declaration.
std::string getAsString() const
Retrieve the human-readable string for this name.
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2003
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:233
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:960
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3445
Represents an enum.
Definition Decl.h:4033
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4265
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4206
This represents one expression.
Definition Expr.h:112
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,...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3126
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:681
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition Expr.h:678
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3104
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) 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:3099
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3087
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
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:3095
bool isFlexibleArrayMemberLike(const 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:212
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...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4238
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:837
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:841
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
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 * IgnoreCasts() LLVM_READONLY
Skip past any casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3083
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3091
std::optional< uint64_t > tryEvaluateStrLen(const ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
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:3697
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:223
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3079
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:808
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:817
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:820
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:810
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:4077
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:272
std::optional< uint64_t > tryEvaluateObjectSize(const ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:464
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:467
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
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:232
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:138
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition TypeBase.h:4331
Represents a member of a struct/union/class.
Definition Decl.h:3182
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3285
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4748
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3418
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3298
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:80
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:141
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:130
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:104
llvm::APFloat getValue() const
Definition Expr.h:1672
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2898
Represents a function declaration or definition.
Definition Decl.h:2018
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4549
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2815
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3738
param_iterator param_end()
Definition Decl.h:2805
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3841
QualType getReturnType() const
Definition Decl.h:2863
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2792
param_iterator param_begin()
Definition Decl.h:2804
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3109
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4305
bool isStatic() const
Definition Decl.h:2947
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4120
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4106
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3802
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5371
unsigned getNumParams() const
Definition TypeBase.h:5649
QualType getParamType(unsigned i) const
Definition TypeBase.h:5651
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5775
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5660
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5770
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5656
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4567
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4876
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4872
QualType getReturnType() const
Definition TypeBase.h:4907
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:3859
Describes an C or C++ initializer list.
Definition Expr.h:5305
ArrayRef< Expr * > inits() const
Definition Expr.h:5358
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:981
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
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:1074
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1110
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:508
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1157
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:881
Represents the results of name lookup.
Definition Lookup.h:147
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4401
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4422
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
Expr * getBase() const
Definition Expr.h:3447
bool isArrow() const
Definition Expr.h:3554
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3717
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1207
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1943
Represent a C++ namespace.
Definition Decl.h:592
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition Stmt.h:1713
bool hasLeadingEmptyMacro() const
Definition Stmt.h:1727
SourceLocation getSemiLoc() const
Definition Stmt.h:1724
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
QualType getType() const
Definition DeclObjC.h:804
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition DeclObjC.h:827
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:815
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition ExprObjC.h:648
ObjCPropertyDecl * getExplicitProperty() const
Definition ExprObjC.h:737
bool isImplicitProperty() const
Definition ExprObjC.h:734
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:84
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2188
Represents a parameter to a function.
Definition Decl.h:1808
Pointer-authentication qualifiers.
Definition TypeBase.h:152
@ MaxDiscriminator
The maximum supported pointer-authentication discriminator.
Definition TypeBase.h:232
bool isAddressDiscriminated() const
Definition TypeBase.h:265
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
QualType getPointeeType() const
Definition TypeBase.h:3402
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6807
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5198
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8531
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2966
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1468
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1229
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8447
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8573
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8487
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1453
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition TypeBase.h:8499
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
void removeLocalVolatile()
Definition TypeBase.h:8563
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1194
void removeLocalConst()
Definition TypeBase.h:8555
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8520
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8568
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1719
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8493
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1347
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1457
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
bool hasUnaligned() const
Definition TypeBase.h:511
Represents a struct/union/class.
Definition Decl.h:4347
bool hasFlexibleArrayMember() const
Definition Decl.h:4380
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4433
field_range fields() const
Definition Decl.h:4550
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4425
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
bool isSEHExceptScope() const
Determine whether this scope is a SEH '__except' block.
Definition Scope.h:598
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
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
bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1034
@ ArmStreaming
Intrinsic is only available in normal mode.
Definition SemaARM.h:37
@ ArmStreamingCompatible
Intrinsic is only available in Streaming-SVE mode.
Definition SemaARM.h:38
bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1117
bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Definition SemaBPF.cpp:105
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
bool CheckDirectXBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaMIPS.cpp:25
bool CheckNVPTXBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaNVPTX.cpp:21
void checkArrayLiteral(QualType TargetType, ObjCArrayLiteral *ArrayLiteral)
Check an Objective-C array literal being converted to the given target type.
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
void adornBoolConversionDiagWithTernaryFixit(const Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder)
bool isSignedCharBool(QualType Ty)
void DiagnoseCStringFormatDirectiveInCFAPI(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...
void checkDictionaryLiteral(QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaPPC.cpp:113
void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg)
Definition SemaPPC.cpp:32
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition SemaPPC.cpp:422
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSPIRVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
SemaDiagnosticBuilder DiagIfDeviceCode(SourceLocation Loc, unsigned DiagID)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as device c...
Definition SemaSYCL.cpp:30
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaWasm.cpp:289
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaX86.cpp:535
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10409
ContextualImplicitConverter(bool Suppress=false, bool SuppressConversion=false)
Definition Sema.h:10414
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
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...
bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const
Returns true if From is a function or pointer to a function with the cfi_unchecked_callee attribute b...
SemaAMDGPU & AMDGPU()
Definition Sema.h:1448
bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is a constant expression represen...
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...
bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum, unsigned Multiple)
BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr TheCall is a constant expr...
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13148
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1141
std::optional< QualType > BuiltinVectorMath(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Unary Operators. 'Tok' is the token for the operator.
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition Sema.cpp:2755
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9420
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9428
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9465
bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount)
Checks that a call expression's argument count is at most the desired number.
bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind, unsigned &IntVal)
bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum)
Returns true if the argument consists of one contiguous run of 1s with any number of 0s on either sid...
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.
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
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....
void CheckFloatComparison(SourceLocation Loc, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
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...
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:7012
bool CheckFormatStringsCompatible(FormatStringType FST, const StringLiteral *AuthoritativeFormatString, const StringLiteral *TestedFormatString, const Expr *FunctionCallArg=nullptr)
Verify that two format strings (as understood by attribute(format) and attribute(format_matches) are ...
bool IsCXXTriviallyRelocatableType(QualType T)
Determines if a type is trivially relocatable according to the C++26 rules.
bool CheckOverflowBehaviorTypeConversion(Expr *E, QualType T, SourceLocation CC)
Check for overflow behavior type related implicit conversion diagnostics.
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2077
SemaHexagon & Hexagon()
Definition Sema.h:1488
SemaSYCL & SYCL()
Definition Sema.h:1558
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:1725
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition SemaExpr.cpp:839
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition Sema.h:1578
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
ASTContext & Context
Definition Sema.h:1308
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:226
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
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...
void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC, bool *ICContext=nullptr, bool IsListInit=false)
SemaObjC & ObjC()
Definition Sema.h:1518
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1373
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:760
ASTContext & getASTContext() const
Definition Sema.h:939
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)
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:762
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2637
bool BuiltinVectorToScalarMath(CallExpr *TheCall)
bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum, llvm::APSInt &Result)
BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr TheCall is a constant expression.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1212
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
AtomicArgumentOrder
Definition Sema.h:2744
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low, int High, bool RangeIsError=true)
BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr TheCall is a constant express...
bool IsLayoutCompatible(QualType T1, QualType T2) const
const LangOptions & getLangOpts() const
Definition Sema.h:932
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
SemaBPF & BPF()
Definition Sema.h:1463
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.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
SemaDirectX & DirectX()
Definition Sema.h:1478
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:1306
static const uint64_t MaximumAlignment
Definition Sema.h:1235
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:958
SemaHLSL & HLSL()
Definition Sema.h:1483
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1503
SemaRISCV & RISCV()
Definition Sema.h:1548
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.
EltwiseBuiltinArgTyRestriction
Definition Sema.h:2810
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7048
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1737
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1341
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition Sema.h:2717
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15531
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:2410
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl)
The main callback when the parser finds something like expression .
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:644
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
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:1446
bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount)
Checks that a call expression's argument count is at least the desired number.
SemaOpenCL & OpenCL()
Definition Sema.h:1528
FormatArgumentPassingKind
Definition Sema.h:2647
@ FAPK_Elsewhere
Definition Sema.h:2651
@ FAPK_Fixed
Definition Sema.h:2648
@ FAPK_Variadic
Definition Sema.h:2649
@ FAPK_VAList
Definition Sema.h:2650
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8263
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14054
SourceManager & getSourceManager() const
Definition Sema.h:937
static FormatStringType GetFormatStringType(StringRef FormatFlavor)
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount, unsigned MaxArgCount)
Checks that a call expression's argument count is in the desired range.
bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str)
Verify that one format string (as understood by attribute(format)) is self-consistent; for instance,...
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 PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
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 CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Binary Operators. 'Tok' is the token for the operator.
bool isConstantEvaluatedContext() const
Definition Sema.h:2639
bool BuiltinElementwiseTernaryMath(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::FloatTy)
bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount)
Checks that a call expression's argument count is the desired number.
ExprResult BuiltinShuffleVector(CallExpr *TheCall)
BuiltinShuffleVector - Handle __builtin_shufflevector.
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
SemaPPC & PPC()
Definition Sema.h:1538
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1267
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx, unsigned FirstArg, FormatStringInfo *FSI)
Given a function and its FormatAttr or FormatMatchesAttr info, attempts to populate the FormatStringI...
SemaSystemZ & SystemZ()
Definition Sema.h:1568
bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of TheCall is a constant expression re...
SourceManager & SourceMgr
Definition Sema.h:1311
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:789
DiagnosticsEngine & Diags
Definition Sema.h:1310
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
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...
SemaNVPTX & NVPTX()
Definition Sema.h:1513
void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction, const Expr *ThisArg, ArrayRef< const Expr * > Args)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:631
bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum)
BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a constant expression representing ...
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,...
@ AbstractParamType
Definition Sema.h:6312
SemaSPIRV & SPIRV()
Definition Sema.h:1553
ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder=AtomicArgumentOrder::API)
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
SemaLoongArch & LoongArch()
Definition Sema.h:1493
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6500
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.
SemaWasm & Wasm()
Definition Sema.h:1573
SemaARM & ARM()
Definition Sema.h:1453
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
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:4649
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.
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.
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.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
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:304
StmtClass getStmtClass() const
Definition Stmt.h:1503
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
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:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1805
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1979
bool isUTF8() const
Definition Expr.h:1924
bool isWide() const
Definition Expr.h:1923
bool isPascal() const
Definition Expr.h:1928
unsigned getLength() const
Definition Expr.h:1915
StringLiteralKind getKind() const
Definition Expr.h:1918
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:1332
bool isUTF32() const
Definition Expr.h:1926
unsigned getByteLength() const
Definition Expr.h:1914
StringRef getString() const
Definition Expr.h:1873
bool isUTF16() const
Definition Expr.h:1925
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.h:1980
bool isOrdinary() const
Definition Expr.h:1922
unsigned getCharByteWidth() const
Definition Expr.h:1916
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3860
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3840
bool isUnion() const
Definition Decl.h:3950
Exposes information about the current target.
Definition TargetInfo.h:227
virtual bool supportsCpuSupports() const
virtual bool validateCpuIs(StringRef Name) const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
IntType getSizeType() const
Definition TargetInfo.h:389
virtual bool validateCpuSupports(StringRef Name) const
virtual bool supportsCpuIs() const
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
@ Type
The template argument is a type.
The base class of all kinds of template declarations (e.g., class, function, etc.).
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:154
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2735
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6282
A container of type source information.
Definition TypeBase.h:8418
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8429
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isBlockPointerType() const
Definition TypeBase.h:8704
bool isVoidType() const
Definition TypeBase.h:9050
bool isBooleanType() const
Definition TypeBase.h:9187
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2289
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9237
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:824
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2266
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2355
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2173
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9217
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
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:2119
bool isVoidPointerType() const
Definition Type.cpp:749
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2517
bool isArrayType() const
Definition TypeBase.h:8783
bool isCharType() const
Definition Type.cpp:2193
bool isFunctionPointerType() const
Definition TypeBase.h:8751
bool isPointerType() const
Definition TypeBase.h:8684
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9094
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
bool isEnumeralType() const
Definition TypeBase.h:8815
bool isScalarType() const
Definition TypeBase.h:9156
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1958
bool isVariableArrayType() const
Definition TypeBase.h:8795
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2701
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isExtVectorType() const
Definition TypeBase.h:8827
bool isExtVectorBoolType() const
Definition TypeBase.h:8831
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2740
bool isBitIntType() const
Definition TypeBase.h:8959
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9019
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8807
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2310
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3183
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2651
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9230
bool isMemberPointerType() const
Definition TypeBase.h:8765
bool isAtomicType() const
Definition TypeBase.h:8876
bool isFunctionProtoType() const
Definition TypeBase.h:2661
bool isMatrixType() const
Definition TypeBase.h:8847
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3201
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2864
bool isUnscopedEnumerationType() const
Definition Type.cpp:2186
bool isObjCObjectType() const
Definition TypeBase.h:8867
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9330
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9193
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2570
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2527
bool isFunctionType() const
Definition TypeBase.h:8680
bool isObjCObjectPointerType() const
Definition TypeBase.h:8863
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2397
bool isStructureOrClassType() const
Definition Type.cpp:743
bool isVectorType() const
Definition TypeBase.h:8823
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2405
bool isFloatingType() const
Definition Type.cpp:2389
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:2332
bool isAnyPointerType() const
Definition TypeBase.h:8692
TypeClass getTypeClass() const
Definition TypeBase.h:2445
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2471
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
bool isNullPtrType() const
Definition TypeBase.h:9087
bool isRecordType() const
Definition TypeBase.h:8811
bool isObjCRetainableType() const
Definition Type.cpp:5431
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2663
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5152
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2728
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3584
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2631
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
Expr * getSubExpr() const
Definition Expr.h:2291
Opcode getOpcode() const
Definition Expr.h:2286
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2368
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1039
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1127
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3417
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5577
Represents a variable declaration or definition.
Definition Decl.h:924
Represents a GCC generic vector type.
Definition TypeBase.h:4239
unsigned getNumElements() const
Definition TypeBase.h:4254
QualType getElementType() const
Definition TypeBase.h:4253
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2707
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
std::optional< ConversionSpecifier > getStandardSpecifier() const
const OptionalAmount & getFieldWidth() const
bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const
const LengthModifier & getLengthModifier() const
bool hasValidLengthModifier(const TargetInfo &Target, const LangOptions &LO) const
std::optional< LengthModifier > getCorrectedLengthModifier() const
Represents the length modifier in a format string in scanf/printf.
ArgType getArgType(ASTContext &Ctx) const
Class representing optional flags with location and representation information.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
const OptionalFlag & isPrivate() const
const OptionalAmount & getPrecision() const
const OptionalFlag & hasSpacePrefix() const
const OptionalFlag & isSensitive() const
const OptionalFlag & isLeftJustified() const
const OptionalFlag & hasLeadingZeros() const
const OptionalFlag & hasAlternativeForm() const
const PrintfConversionSpecifier & getConversionSpecifier() const
const OptionalFlag & hasPlusPrefix() const
const OptionalFlag & hasThousandsGrouping() const
ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const
Returns the builtin type that a data argument paired with this format specifier should have.
const OptionalFlag & isPublic() const
const ScanfConversionSpecifier & getConversionSpecifier() const
ArgType getArgType(ASTContext &Ctx) const
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition SPIR.cpp:35
Definition SPIR.cpp:47
Common components of both fprintf and fscanf format strings.
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)
Pieces specific to fprintf format strings.
Pieces specific to fscanf format strings.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< PointerType > pointerType
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
ComparisonResult
Indicates the result of a tentative comparison.
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition Types.cpp:237
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ 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:1521
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1506
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1499
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1513
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2789
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1467
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1528
llvm::ImmutableSet< T > join(llvm::ImmutableSet< T > A, llvm::ImmutableSet< T > B, typename llvm::ImmutableSet< T >::Factory &F)
Computes the union of two ImmutableSets.
Definition Utils.h:39
void checkCaptureByLifetime(Sema &SemaRef, const CapturingEntity &Entity, Expr *Init)
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition FixIt.h:32
RangeSelector merge(RangeSelector First, RangeSelector Second)
Selects the merge of the two ranges, i.e.
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
Expr * IgnoreElidableImplicitConstructorSingleStep(Expr *E)
Definition IgnoreExpr.h:115
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
VariadicCallType
Definition Sema.h:513
bool hasSpecificAttr(const Container &container)
@ Arithmetic
An arithmetic operation.
Definition Sema.h:663
@ Comparison
A comparison.
Definition Sema.h:667
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:351
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:24
@ Success
Annotation was successful.
Definition Parser.h:65
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:150
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
PointerAuthDiscArgKind
Definition Sema.h:594
std::string FormatUTFCodeUnitAsCodepoint(unsigned Value, QualType T)
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:125
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:258
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition JsonSupport.h:21
SemaARM::ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD)
Definition SemaARM.cpp:552
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
bool isFunctionOrMethodVariadic(const Decl *D)
Definition Attr.h:112
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:564
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:499
CastKind
CastKind - The kind of operation required for a conversion.
BuiltinCountedByRefKind
Definition Sema.h:521
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool hasImplicitObjectParameter(const Decl *D)
Definition Attr.h:126
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
for(const auto &A :T->param_types())
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition IgnoreExpr.h:144
unsigned getFunctionOrMethodNumParams(const Decl *D)
getFunctionOrMethodNumParams - Return number of function or method parameters.
Definition Attr.h:64
StringLiteralKind
Definition Expr.h:1769
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
@ CC_Win64
Definition Specifiers.h:286
@ CC_X86_64SysV
Definition Specifiers.h:287
@ Generic
not a target-specific vector type
Definition TypeBase.h:4200
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5991
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5984
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1763
unsigned long uint64_t
long int64_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:652
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:654
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:640
Extra information about a function prototype.
Definition TypeBase.h:5456
unsigned Indentation
The number of spaces to use to indent each line.
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13327
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13353
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13343
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13294
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6906
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2659
#define log2(__x)
Definition tgmath.h:970