Thanks to visit codestin.com
Credit goes to clang.llvm.org

clang 22.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/TypeLoc.h"
46#include "clang/Basic/LLVM.h"
57#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
59#include "clang/Sema/Lookup.h"
61#include "clang/Sema/Scope.h"
63#include "clang/Sema/Sema.h"
65#include "clang/Sema/SemaARM.h"
66#include "clang/Sema/SemaBPF.h"
68#include "clang/Sema/SemaHLSL.h"
71#include "clang/Sema/SemaMIPS.h"
73#include "clang/Sema/SemaObjC.h"
75#include "clang/Sema/SemaPPC.h"
79#include "clang/Sema/SemaWasm.h"
80#include "clang/Sema/SemaX86.h"
81#include "llvm/ADT/APFloat.h"
82#include "llvm/ADT/APInt.h"
83#include "llvm/ADT/APSInt.h"
84#include "llvm/ADT/ArrayRef.h"
85#include "llvm/ADT/DenseMap.h"
86#include "llvm/ADT/FoldingSet.h"
87#include "llvm/ADT/STLExtras.h"
88#include "llvm/ADT/STLForwardCompat.h"
89#include "llvm/ADT/SmallBitVector.h"
90#include "llvm/ADT/SmallPtrSet.h"
91#include "llvm/ADT/SmallString.h"
92#include "llvm/ADT/SmallVector.h"
93#include "llvm/ADT/StringExtras.h"
94#include "llvm/ADT/StringRef.h"
95#include "llvm/ADT/StringSet.h"
96#include "llvm/ADT/StringSwitch.h"
97#include "llvm/Support/AtomicOrdering.h"
98#include "llvm/Support/Compiler.h"
99#include "llvm/Support/ConvertUTF.h"
100#include "llvm/Support/ErrorHandling.h"
101#include "llvm/Support/Format.h"
102#include "llvm/Support/Locale.h"
103#include "llvm/Support/MathExtras.h"
104#include "llvm/Support/SaveAndRestore.h"
105#include "llvm/Support/raw_ostream.h"
106#include "llvm/TargetParser/RISCVTargetParser.h"
107#include "llvm/TargetParser/Triple.h"
108#include <algorithm>
109#include <cassert>
110#include <cctype>
111#include <cstddef>
112#include <cstdint>
113#include <functional>
114#include <limits>
115#include <optional>
116#include <string>
117#include <tuple>
118#include <utility>
119
120using namespace clang;
121using namespace sema;
122
124 unsigned ByteNo) const {
125 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
126 Context.getTargetInfo());
127}
128
129static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
131 return (A << 8) | B;
132}
133
134bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
135 unsigned ArgCount = Call->getNumArgs();
136 if (ArgCount >= MinArgCount)
137 return false;
138
139 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
140 << 0 /*function call*/ << MinArgCount << ArgCount
141 << /*is non object*/ 0 << Call->getSourceRange();
142}
143
144bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
145 unsigned ArgCount = Call->getNumArgs();
146 if (ArgCount <= MaxArgCount)
147 return false;
148 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)
149 << 0 /*function call*/ << MaxArgCount << ArgCount
150 << /*is non object*/ 0 << Call->getSourceRange();
151}
152
153bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
154 unsigned MaxArgCount) {
155 return checkArgCountAtLeast(Call, MinArgCount) ||
156 checkArgCountAtMost(Call, MaxArgCount);
157}
158
159bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
160 unsigned ArgCount = Call->getNumArgs();
161 if (ArgCount == DesiredArgCount)
162 return false;
163
164 if (checkArgCountAtLeast(Call, DesiredArgCount))
165 return true;
166 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
167
168 // Highlight all the excess arguments.
169 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
170 Call->getArg(ArgCount - 1)->getEndLoc());
171
172 return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
173 << 0 /*function call*/ << DesiredArgCount << ArgCount
174 << /*is non object*/ 0 << Range;
175}
176
178 bool HasError = false;
179
180 for (const Expr *Arg : Call->arguments()) {
181 if (Arg->isValueDependent())
182 continue;
183
184 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
185 int DiagMsgKind = -1;
186 // Arguments must be pointers to constant strings and cannot use '$'.
187 if (!ArgString.has_value())
188 DiagMsgKind = 0;
189 else if (ArgString->find('$') != std::string::npos)
190 DiagMsgKind = 1;
191
192 if (DiagMsgKind >= 0) {
193 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
194 << DiagMsgKind << Arg->getSourceRange();
195 HasError = true;
196 }
197 }
198
199 return !HasError;
200}
201
203 if (Value->isTypeDependent())
204 return false;
205
206 InitializedEntity Entity =
208 ExprResult Result =
210 if (Result.isInvalid())
211 return true;
212 Value = Result.get();
213 return false;
214}
215
216/// Check that the first argument to __builtin_annotation is an integer
217/// and the second argument is a non-wide string literal.
218static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
219 if (S.checkArgCount(TheCall, 2))
220 return true;
221
222 // First argument should be an integer.
223 Expr *ValArg = TheCall->getArg(0);
224 QualType Ty = ValArg->getType();
225 if (!Ty->isIntegerType()) {
226 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
227 << ValArg->getSourceRange();
228 return true;
229 }
230
231 // Second argument should be a constant string.
232 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
233 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
234 if (!Literal || !Literal->isOrdinary()) {
235 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
236 << StrArg->getSourceRange();
237 return true;
238 }
239
240 TheCall->setType(Ty);
241 return false;
242}
243
244static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
245 // We need at least one argument.
246 if (TheCall->getNumArgs() < 1) {
247 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
248 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
249 << TheCall->getCallee()->getSourceRange();
250 return true;
251 }
252
253 // All arguments should be wide string literals.
254 for (Expr *Arg : TheCall->arguments()) {
255 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
256 if (!Literal || !Literal->isWide()) {
257 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
258 << Arg->getSourceRange();
259 return true;
260 }
261 }
262
263 return false;
264}
265
266/// Check that the argument to __builtin_addressof is a glvalue, and set the
267/// result type to the corresponding pointer type.
268static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
269 if (S.checkArgCount(TheCall, 1))
270 return true;
271
272 ExprResult Arg(TheCall->getArg(0));
273 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
274 if (ResultType.isNull())
275 return true;
276
277 TheCall->setArg(0, Arg.get());
278 TheCall->setType(ResultType);
279 return false;
280}
281
282/// Check that the argument to __builtin_function_start is a function.
283static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
284 if (S.checkArgCount(TheCall, 1))
285 return true;
286
287 if (TheCall->getArg(0)->containsErrors())
288 return true;
289
291 if (Arg.isInvalid())
292 return true;
293
294 TheCall->setArg(0, Arg.get());
295 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
297
298 if (!FD) {
299 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
300 << TheCall->getSourceRange();
301 return true;
302 }
303
304 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
305 TheCall->getBeginLoc());
306}
307
308/// Check the number of arguments and set the result type to
309/// the argument type.
310static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
311 if (S.checkArgCount(TheCall, 1))
312 return true;
313
314 TheCall->setType(TheCall->getArg(0)->getType());
315 return false;
316}
317
318/// Check that the value argument for __builtin_is_aligned(value, alignment) and
319/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
320/// type (but not a function pointer) and that the alignment is a power-of-two.
321static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
322 if (S.checkArgCount(TheCall, 2))
323 return true;
324
325 clang::Expr *Source = TheCall->getArg(0);
326 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
327
328 auto IsValidIntegerType = [](QualType Ty) {
329 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
330 };
331 QualType SrcTy = Source->getType();
332 // We should also be able to use it with arrays (but not functions!).
333 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
334 SrcTy = S.Context.getDecayedType(SrcTy);
335 }
336 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
337 SrcTy->isFunctionPointerType()) {
338 // FIXME: this is not quite the right error message since we don't allow
339 // floating point types, or member pointers.
340 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
341 << SrcTy;
342 return true;
343 }
344
345 clang::Expr *AlignOp = TheCall->getArg(1);
346 if (!IsValidIntegerType(AlignOp->getType())) {
347 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
348 << AlignOp->getType();
349 return true;
350 }
351 Expr::EvalResult AlignResult;
352 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
353 // We can't check validity of alignment if it is value dependent.
354 if (!AlignOp->isValueDependent() &&
355 AlignOp->EvaluateAsInt(AlignResult, S.Context,
357 llvm::APSInt AlignValue = AlignResult.Val.getInt();
358 llvm::APSInt MaxValue(
359 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
360 if (AlignValue < 1) {
361 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
362 return true;
363 }
364 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
365 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
366 << toString(MaxValue, 10);
367 return true;
368 }
369 if (!AlignValue.isPowerOf2()) {
370 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
371 return true;
372 }
373 if (AlignValue == 1) {
374 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
375 << IsBooleanAlignBuiltin;
376 }
377 }
378
381 SourceLocation(), Source);
382 if (SrcArg.isInvalid())
383 return true;
384 TheCall->setArg(0, SrcArg.get());
385 ExprResult AlignArg =
387 S.Context, AlignOp->getType(), false),
388 SourceLocation(), AlignOp);
389 if (AlignArg.isInvalid())
390 return true;
391 TheCall->setArg(1, AlignArg.get());
392 // For align_up/align_down, the return type is the same as the (potentially
393 // decayed) argument type including qualifiers. For is_aligned(), the result
394 // is always bool.
395 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
396 return false;
397}
398
399static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
400 if (S.checkArgCount(TheCall, 3))
401 return true;
402
403 std::pair<unsigned, const char *> Builtins[] = {
404 { Builtin::BI__builtin_add_overflow, "ckd_add" },
405 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
406 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
407 };
408
409 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
410 const char *> &P) {
411 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
413 S.getSourceManager(), S.getLangOpts()) == P.second;
414 });
415
416 auto ValidCkdIntType = [](QualType QT) {
417 // A valid checked integer type is an integer type other than a plain char,
418 // bool, a bit-precise type, or an enumeration type.
419 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
420 return (BT->getKind() >= BuiltinType::Short &&
421 BT->getKind() <= BuiltinType::Int128) || (
422 BT->getKind() >= BuiltinType::UShort &&
423 BT->getKind() <= BuiltinType::UInt128) ||
424 BT->getKind() == BuiltinType::UChar ||
425 BT->getKind() == BuiltinType::SChar;
426 return false;
427 };
428
429 // First two arguments should be integers.
430 for (unsigned I = 0; I < 2; ++I) {
432 if (Arg.isInvalid()) return true;
433 TheCall->setArg(I, Arg.get());
434
435 QualType Ty = Arg.get()->getType();
436 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
437 if (!IsValid) {
438 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
439 << CkdOperation << Ty << Arg.get()->getSourceRange();
440 return true;
441 }
442 }
443
444 // Third argument should be a pointer to a non-const integer.
445 // IRGen correctly handles volatile, restrict, and address spaces, and
446 // the other qualifiers aren't possible.
447 {
449 if (Arg.isInvalid()) return true;
450 TheCall->setArg(2, Arg.get());
451
452 QualType Ty = Arg.get()->getType();
453 const auto *PtrTy = Ty->getAs<PointerType>();
454 if (!PtrTy ||
455 !PtrTy->getPointeeType()->isIntegerType() ||
456 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
457 PtrTy->getPointeeType().isConstQualified()) {
458 S.Diag(Arg.get()->getBeginLoc(),
459 diag::err_overflow_builtin_must_be_ptr_int)
460 << CkdOperation << Ty << Arg.get()->getSourceRange();
461 return true;
462 }
463 }
464
465 // Disallow signed bit-precise integer args larger than 128 bits to mul
466 // function until we improve backend support.
467 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
468 for (unsigned I = 0; I < 3; ++I) {
469 const auto Arg = TheCall->getArg(I);
470 // Third argument will be a pointer.
471 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
472 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
473 S.getASTContext().getIntWidth(Ty) > 128)
474 return S.Diag(Arg->getBeginLoc(),
475 diag::err_overflow_builtin_bit_int_max_size)
476 << 128;
477 }
478 }
479
480 return false;
481}
482
483namespace {
484struct BuiltinDumpStructGenerator {
485 Sema &S;
486 CallExpr *TheCall;
487 SourceLocation Loc = TheCall->getBeginLoc();
488 SmallVector<Expr *, 32> Actions;
489 DiagnosticErrorTrap ErrorTracker;
490 PrintingPolicy Policy;
491
492 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
493 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
494 Policy(S.Context.getPrintingPolicy()) {
495 Policy.AnonymousTagLocations = false;
496 }
497
498 Expr *makeOpaqueValueExpr(Expr *Inner) {
499 auto *OVE = new (S.Context)
500 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
501 Inner->getObjectKind(), Inner);
502 Actions.push_back(OVE);
503 return OVE;
504 }
505
506 Expr *getStringLiteral(llvm::StringRef Str) {
508 // Wrap the literal in parentheses to attach a source location.
509 return new (S.Context) ParenExpr(Loc, Loc, Lit);
510 }
511
512 bool callPrintFunction(llvm::StringRef Format,
513 llvm::ArrayRef<Expr *> Exprs = {}) {
514 SmallVector<Expr *, 8> Args;
515 assert(TheCall->getNumArgs() >= 2);
516 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
517 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
518 Args.push_back(getStringLiteral(Format));
519 llvm::append_range(Args, Exprs);
520
521 // Register a note to explain why we're performing the call.
522 Sema::CodeSynthesisContext Ctx;
524 Ctx.PointOfInstantiation = Loc;
525 Ctx.CallArgs = Args.data();
526 Ctx.NumCallArgs = Args.size();
528
529 ExprResult RealCall =
530 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
531 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
532
534 if (!RealCall.isInvalid())
535 Actions.push_back(RealCall.get());
536 // Bail out if we've hit any errors, even if we managed to build the
537 // call. We don't want to produce more than one error.
538 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
539 }
540
541 Expr *getIndentString(unsigned Depth) {
542 if (!Depth)
543 return nullptr;
544
545 llvm::SmallString<32> Indent;
546 Indent.resize(Depth * Policy.Indentation, ' ');
547 return getStringLiteral(Indent);
548 }
549
550 Expr *getTypeString(QualType T) {
551 return getStringLiteral(T.getAsString(Policy));
552 }
553
554 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
555 llvm::raw_svector_ostream OS(Str);
556
557 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
558 // than trying to print a single character.
559 if (auto *BT = T->getAs<BuiltinType>()) {
560 switch (BT->getKind()) {
561 case BuiltinType::Bool:
562 OS << "%d";
563 return true;
564 case BuiltinType::Char_U:
565 case BuiltinType::UChar:
566 OS << "%hhu";
567 return true;
568 case BuiltinType::Char_S:
569 case BuiltinType::SChar:
570 OS << "%hhd";
571 return true;
572 default:
573 break;
574 }
575 }
576
577 analyze_printf::PrintfSpecifier Specifier;
578 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
579 // We were able to guess how to format this.
580 if (Specifier.getConversionSpecifier().getKind() ==
581 analyze_printf::PrintfConversionSpecifier::sArg) {
582 // Wrap double-quotes around a '%s' specifier and limit its maximum
583 // length. Ideally we'd also somehow escape special characters in the
584 // contents but printf doesn't support that.
585 // FIXME: '%s' formatting is not safe in general.
586 OS << '"';
587 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
588 Specifier.toString(OS);
589 OS << '"';
590 // FIXME: It would be nice to include a '...' if the string doesn't fit
591 // in the length limit.
592 } else {
593 Specifier.toString(OS);
594 }
595 return true;
596 }
597
598 if (T->isPointerType()) {
599 // Format all pointers with '%p'.
600 OS << "%p";
601 return true;
602 }
603
604 return false;
605 }
606
607 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
608 Expr *IndentLit = getIndentString(Depth);
609 Expr *TypeLit = getTypeString(S.Context.getCanonicalTagType(RD));
610 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
611 : callPrintFunction("%s", {TypeLit}))
612 return true;
613
614 return dumpRecordValue(RD, E, IndentLit, Depth);
615 }
616
617 // Dump a record value. E should be a pointer or lvalue referring to an RD.
618 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
619 unsigned Depth) {
620 // FIXME: Decide what to do if RD is a union. At least we should probably
621 // turn off printing `const char*` members with `%s`, because that is very
622 // likely to crash if that's not the active member. Whatever we decide, we
623 // should document it.
624
625 // Build an OpaqueValueExpr so we can refer to E more than once without
626 // triggering re-evaluation.
627 Expr *RecordArg = makeOpaqueValueExpr(E);
628 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
629
630 if (callPrintFunction(" {\n"))
631 return true;
632
633 // Dump each base class, regardless of whether they're aggregates.
634 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
635 for (const auto &Base : CXXRD->bases()) {
636 QualType BaseType =
637 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
638 : S.Context.getLValueReferenceType(Base.getType());
640 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
641 RecordArg);
642 if (BasePtr.isInvalid() ||
643 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
644 Depth + 1))
645 return true;
646 }
647 }
648
649 Expr *FieldIndentArg = getIndentString(Depth + 1);
650
651 // Dump each field.
652 for (auto *D : RD->decls()) {
653 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
654 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
655 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
656 continue;
657
658 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
659 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
660 getTypeString(FD->getType()),
661 getStringLiteral(FD->getName())};
662
663 if (FD->isBitField()) {
664 Format += ": %zu ";
665 QualType SizeT = S.Context.getSizeType();
666 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
667 FD->getBitWidthValue());
668 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
669 }
670
671 Format += "=";
672
675 CXXScopeSpec(), Loc, IFD,
676 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
678 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
680 DeclarationNameInfo(FD->getDeclName(), Loc));
681 if (Field.isInvalid())
682 return true;
683
684 auto *InnerRD = FD->getType()->getAsRecordDecl();
685 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
686 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
687 // Recursively print the values of members of aggregate record type.
688 if (callPrintFunction(Format, Args) ||
689 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
690 return true;
691 } else {
692 Format += " ";
693 if (appendFormatSpecifier(FD->getType(), Format)) {
694 // We know how to print this field.
695 Args.push_back(Field.get());
696 } else {
697 // We don't know how to print this field. Print out its address
698 // with a format specifier that a smart tool will be able to
699 // recognize and treat specially.
700 Format += "*%p";
701 ExprResult FieldAddr =
702 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
703 if (FieldAddr.isInvalid())
704 return true;
705 Args.push_back(FieldAddr.get());
706 }
707 Format += "\n";
708 if (callPrintFunction(Format, Args))
709 return true;
710 }
711 }
712
713 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
714 : callPrintFunction("}\n");
715 }
716
717 Expr *buildWrapper() {
718 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
720 TheCall->setType(Wrapper->getType());
721 TheCall->setValueKind(Wrapper->getValueKind());
722 return Wrapper;
723 }
724};
725} // namespace
726
728 if (S.checkArgCountAtLeast(TheCall, 2))
729 return ExprError();
730
731 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
732 if (PtrArgResult.isInvalid())
733 return ExprError();
734 TheCall->setArg(0, PtrArgResult.get());
735
736 // First argument should be a pointer to a struct.
737 QualType PtrArgType = PtrArgResult.get()->getType();
738 if (!PtrArgType->isPointerType() ||
739 !PtrArgType->getPointeeType()->isRecordType()) {
740 S.Diag(PtrArgResult.get()->getBeginLoc(),
741 diag::err_expected_struct_pointer_argument)
742 << 1 << TheCall->getDirectCallee() << PtrArgType;
743 return ExprError();
744 }
745 QualType Pointee = PtrArgType->getPointeeType();
746 const RecordDecl *RD = Pointee->getAsRecordDecl();
747 // Try to instantiate the class template as appropriate; otherwise, access to
748 // its data() may lead to a crash.
749 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
750 diag::err_incomplete_type))
751 return ExprError();
752 // Second argument is a callable, but we can't fully validate it until we try
753 // calling it.
754 QualType FnArgType = TheCall->getArg(1)->getType();
755 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
756 !FnArgType->isBlockPointerType() &&
757 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
758 auto *BT = FnArgType->getAs<BuiltinType>();
759 switch (BT ? BT->getKind() : BuiltinType::Void) {
760 case BuiltinType::Dependent:
761 case BuiltinType::Overload:
762 case BuiltinType::BoundMember:
763 case BuiltinType::PseudoObject:
764 case BuiltinType::UnknownAny:
765 case BuiltinType::BuiltinFn:
766 // This might be a callable.
767 break;
768
769 default:
770 S.Diag(TheCall->getArg(1)->getBeginLoc(),
771 diag::err_expected_callable_argument)
772 << 2 << TheCall->getDirectCallee() << FnArgType;
773 return ExprError();
774 }
775 }
776
777 BuiltinDumpStructGenerator Generator(S, TheCall);
778
779 // Wrap parentheses around the given pointer. This is not necessary for
780 // correct code generation, but it means that when we pretty-print the call
781 // arguments in our diagnostics we will produce '(&s)->n' instead of the
782 // incorrect '&s->n'.
783 Expr *PtrArg = PtrArgResult.get();
784 PtrArg = new (S.Context)
785 ParenExpr(PtrArg->getBeginLoc(),
786 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
787 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
788 return ExprError();
789
790 return Generator.buildWrapper();
791}
792
793static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
794 if (S.checkArgCount(BuiltinCall, 2))
795 return true;
796
797 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
798 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
799 Expr *Call = BuiltinCall->getArg(0);
800 Expr *Chain = BuiltinCall->getArg(1);
801
802 if (Call->getStmtClass() != Stmt::CallExprClass) {
803 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
804 << Call->getSourceRange();
805 return true;
806 }
807
808 auto CE = cast<CallExpr>(Call);
809 if (CE->getCallee()->getType()->isBlockPointerType()) {
810 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
811 << Call->getSourceRange();
812 return true;
813 }
814
815 const Decl *TargetDecl = CE->getCalleeDecl();
816 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
817 if (FD->getBuiltinID()) {
818 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
819 << Call->getSourceRange();
820 return true;
821 }
822
823 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
824 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
825 << Call->getSourceRange();
826 return true;
827 }
828
829 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
830 if (ChainResult.isInvalid())
831 return true;
832 if (!ChainResult.get()->getType()->isPointerType()) {
833 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
834 << Chain->getSourceRange();
835 return true;
836 }
837
838 QualType ReturnTy = CE->getCallReturnType(S.Context);
839 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
840 QualType BuiltinTy = S.Context.getFunctionType(
841 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
842 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
843
844 Builtin =
845 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
846
847 BuiltinCall->setType(CE->getType());
848 BuiltinCall->setValueKind(CE->getValueKind());
849 BuiltinCall->setObjectKind(CE->getObjectKind());
850 BuiltinCall->setCallee(Builtin);
851 BuiltinCall->setArg(1, ChainResult.get());
852
853 return false;
854}
855
856namespace {
857
858class ScanfDiagnosticFormatHandler
860 // Accepts the argument index (relative to the first destination index) of the
861 // argument whose size we want.
862 using ComputeSizeFunction =
863 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
864
865 // Accepts the argument index (relative to the first destination index), the
866 // destination size, and the source size).
867 using DiagnoseFunction =
868 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
869
870 ComputeSizeFunction ComputeSizeArgument;
871 DiagnoseFunction Diagnose;
872
873public:
874 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
875 DiagnoseFunction Diagnose)
876 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
877
878 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
879 const char *StartSpecifier,
880 unsigned specifierLen) override {
881 if (!FS.consumesDataArgument())
882 return true;
883
884 unsigned NulByte = 0;
885 switch ((FS.getConversionSpecifier().getKind())) {
886 default:
887 return true;
890 NulByte = 1;
891 break;
893 break;
894 }
895
896 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
897 if (FW.getHowSpecified() !=
898 analyze_format_string::OptionalAmount::HowSpecified::Constant)
899 return true;
900
901 unsigned SourceSize = FW.getConstantAmount() + NulByte;
902
903 std::optional<llvm::APSInt> DestSizeAPS =
904 ComputeSizeArgument(FS.getArgIndex());
905 if (!DestSizeAPS)
906 return true;
907
908 unsigned DestSize = DestSizeAPS->getZExtValue();
909
910 if (DestSize < SourceSize)
911 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
912
913 return true;
914 }
915};
916
917class EstimateSizeFormatHandler
919 size_t Size;
920 /// Whether the format string contains Linux kernel's format specifier
921 /// extension.
922 bool IsKernelCompatible = true;
923
924public:
925 EstimateSizeFormatHandler(StringRef Format)
926 : Size(std::min(Format.find(0), Format.size()) +
927 1 /* null byte always written by sprintf */) {}
928
929 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
930 const char *, unsigned SpecifierLen,
931 const TargetInfo &) override {
932
933 const size_t FieldWidth = computeFieldWidth(FS);
934 const size_t Precision = computePrecision(FS);
935
936 // The actual format.
937 switch (FS.getConversionSpecifier().getKind()) {
938 // Just a char.
941 Size += std::max(FieldWidth, (size_t)1);
942 break;
943 // Just an integer.
953 Size += std::max(FieldWidth, Precision);
954 break;
955
956 // %g style conversion switches between %f or %e style dynamically.
957 // %g removes trailing zeros, and does not print decimal point if there are
958 // no digits that follow it. Thus %g can print a single digit.
959 // FIXME: If it is alternative form:
960 // For g and G conversions, trailing zeros are not removed from the result.
963 Size += 1;
964 break;
965
966 // Floating point number in the form '[+]ddd.ddd'.
969 Size += std::max(FieldWidth, 1 /* integer part */ +
970 (Precision ? 1 + Precision
971 : 0) /* period + decimal */);
972 break;
973
974 // Floating point number in the form '[-]d.ddde[+-]dd'.
977 Size +=
978 std::max(FieldWidth,
979 1 /* integer part */ +
980 (Precision ? 1 + Precision : 0) /* period + decimal */ +
981 1 /* e or E letter */ + 2 /* exponent */);
982 break;
983
984 // Floating point number in the form '[-]0xh.hhhhp±dd'.
987 Size +=
988 std::max(FieldWidth,
989 2 /* 0x */ + 1 /* integer part */ +
990 (Precision ? 1 + Precision : 0) /* period + decimal */ +
991 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
992 break;
993
994 // Just a string.
997 Size += FieldWidth;
998 break;
999
1000 // Just a pointer in the form '0xddd'.
1002 // Linux kernel has its own extesion for `%p` specifier.
1003 // Kernel Document:
1004 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1005 IsKernelCompatible = false;
1006 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1007 break;
1008
1009 // A plain percent.
1011 Size += 1;
1012 break;
1013
1014 default:
1015 break;
1016 }
1017
1018 // If field width is specified, the sign/space is already accounted for
1019 // within the field width, so no additional size is needed.
1020 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1021 Size += 1;
1022
1023 if (FS.hasAlternativeForm()) {
1024 switch (FS.getConversionSpecifier().getKind()) {
1025 // For o conversion, it increases the precision, if and only if necessary,
1026 // to force the first digit of the result to be a zero
1027 // (if the value and precision are both 0, a single 0 is printed)
1029 // For b conversion, a nonzero result has 0b prefixed to it.
1031 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1032 // it.
1035 // Note: even when the prefix is added, if
1036 // (prefix_width <= FieldWidth - formatted_length) holds,
1037 // the prefix does not increase the format
1038 // size. e.g.(("%#3x", 0xf) is "0xf")
1039
1040 // If the result is zero, o, b, x, X adds nothing.
1041 break;
1042 // For a, A, e, E, f, F, g, and G conversions,
1043 // the result of converting a floating-point number always contains a
1044 // decimal-point
1053 Size += (Precision ? 0 : 1);
1054 break;
1055 // For other conversions, the behavior is undefined.
1056 default:
1057 break;
1058 }
1059 }
1060 assert(SpecifierLen <= Size && "no underflow");
1061 Size -= SpecifierLen;
1062 return true;
1063 }
1064
1065 size_t getSizeLowerBound() const { return Size; }
1066 bool isKernelCompatible() const { return IsKernelCompatible; }
1067
1068private:
1069 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1070 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1071 size_t FieldWidth = 0;
1073 FieldWidth = FW.getConstantAmount();
1074 return FieldWidth;
1075 }
1076
1077 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1078 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1079 size_t Precision = 0;
1080
1081 // See man 3 printf for default precision value based on the specifier.
1082 switch (FW.getHowSpecified()) {
1084 switch (FS.getConversionSpecifier().getKind()) {
1085 default:
1086 break;
1090 Precision = 1;
1091 break;
1098 Precision = 1;
1099 break;
1106 Precision = 6;
1107 break;
1109 Precision = 1;
1110 break;
1111 }
1112 break;
1114 Precision = FW.getConstantAmount();
1115 break;
1116 default:
1117 break;
1118 }
1119 return Precision;
1120 }
1121};
1122
1123} // namespace
1124
1125static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1126 StringRef &FormatStrRef, size_t &StrLen,
1127 ASTContext &Context) {
1128 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1129 Format && (Format->isOrdinary() || Format->isUTF8())) {
1130 FormatStrRef = Format->getString();
1131 const ConstantArrayType *T =
1132 Context.getAsConstantArrayType(Format->getType());
1133 assert(T && "String literal not of constant array type!");
1134 size_t TypeSize = T->getZExtSize();
1135 // In case there's a null byte somewhere.
1136 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1137 return true;
1138 }
1139 return false;
1140}
1141
1142void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1143 CallExpr *TheCall) {
1144 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1146 return;
1147
1148 bool UseDABAttr = false;
1149 const FunctionDecl *UseDecl = FD;
1150
1151 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1152 if (DABAttr) {
1153 UseDecl = DABAttr->getFunction();
1154 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1155 UseDABAttr = true;
1156 }
1157
1158 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1159
1160 if (!BuiltinID)
1161 return;
1162
1163 const TargetInfo &TI = getASTContext().getTargetInfo();
1164 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1165
1166 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1167 // If we refer to a diagnose_as_builtin attribute, we need to change the
1168 // argument index to refer to the arguments of the called function. Unless
1169 // the index is out of bounds, which presumably means it's a variadic
1170 // function.
1171 if (!UseDABAttr)
1172 return Index;
1173 unsigned DABIndices = DABAttr->argIndices_size();
1174 unsigned NewIndex = Index < DABIndices
1175 ? DABAttr->argIndices_begin()[Index]
1176 : Index - DABIndices + FD->getNumParams();
1177 if (NewIndex >= TheCall->getNumArgs())
1178 return std::nullopt;
1179 return NewIndex;
1180 };
1181
1182 auto ComputeExplicitObjectSizeArgument =
1183 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1184 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1185 if (!IndexOptional)
1186 return std::nullopt;
1187 unsigned NewIndex = *IndexOptional;
1188 Expr::EvalResult Result;
1189 Expr *SizeArg = TheCall->getArg(NewIndex);
1190 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1191 return std::nullopt;
1192 llvm::APSInt Integer = Result.Val.getInt();
1193 Integer.setIsUnsigned(true);
1194 return Integer;
1195 };
1196
1197 auto ComputeSizeArgument =
1198 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1199 // If the parameter has a pass_object_size attribute, then we should use its
1200 // (potentially) more strict checking mode. Otherwise, conservatively assume
1201 // type 0.
1202 int BOSType = 0;
1203 // This check can fail for variadic functions.
1204 if (Index < FD->getNumParams()) {
1205 if (const auto *POS =
1206 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1207 BOSType = POS->getType();
1208 }
1209
1210 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1211 if (!IndexOptional)
1212 return std::nullopt;
1213 unsigned NewIndex = *IndexOptional;
1214
1215 if (NewIndex >= TheCall->getNumArgs())
1216 return std::nullopt;
1217
1218 const Expr *ObjArg = TheCall->getArg(NewIndex);
1220 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
1221 return std::nullopt;
1222
1223 // Get the object size in the target's size_t width.
1224 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
1225 };
1226
1227 auto ComputeStrLenArgument =
1228 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1229 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1230 if (!IndexOptional)
1231 return std::nullopt;
1232 unsigned NewIndex = *IndexOptional;
1233
1234 const Expr *ObjArg = TheCall->getArg(NewIndex);
1236 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
1237 return std::nullopt;
1238 // Add 1 for null byte.
1239 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
1240 };
1241
1242 std::optional<llvm::APSInt> SourceSize;
1243 std::optional<llvm::APSInt> DestinationSize;
1244 unsigned DiagID = 0;
1245 bool IsChkVariant = false;
1246
1247 auto GetFunctionName = [&]() {
1248 std::string FunctionNameStr =
1249 getASTContext().BuiltinInfo.getName(BuiltinID);
1250 llvm::StringRef FunctionName = FunctionNameStr;
1251 // Skim off the details of whichever builtin was called to produce a better
1252 // diagnostic, as it's unlikely that the user wrote the __builtin
1253 // explicitly.
1254 if (IsChkVariant) {
1255 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1256 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1257 } else {
1258 FunctionName.consume_front("__builtin_");
1259 }
1260 return FunctionName.str();
1261 };
1262
1263 switch (BuiltinID) {
1264 default:
1265 return;
1266 case Builtin::BI__builtin_stpcpy:
1267 case Builtin::BIstpcpy:
1268 case Builtin::BI__builtin_strcpy:
1269 case Builtin::BIstrcpy: {
1270 DiagID = diag::warn_fortify_strlen_overflow;
1271 SourceSize = ComputeStrLenArgument(1);
1272 DestinationSize = ComputeSizeArgument(0);
1273 break;
1274 }
1275
1276 case Builtin::BI__builtin___stpcpy_chk:
1277 case Builtin::BI__builtin___strcpy_chk: {
1278 DiagID = diag::warn_fortify_strlen_overflow;
1279 SourceSize = ComputeStrLenArgument(1);
1280 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1281 IsChkVariant = true;
1282 break;
1283 }
1284
1285 case Builtin::BIscanf:
1286 case Builtin::BIfscanf:
1287 case Builtin::BIsscanf: {
1288 unsigned FormatIndex = 1;
1289 unsigned DataIndex = 2;
1290 if (BuiltinID == Builtin::BIscanf) {
1291 FormatIndex = 0;
1292 DataIndex = 1;
1293 }
1294
1295 const auto *FormatExpr =
1296 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1297
1298 StringRef FormatStrRef;
1299 size_t StrLen;
1300 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1301 return;
1302
1303 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1304 unsigned SourceSize) {
1305 DiagID = diag::warn_fortify_scanf_overflow;
1306 unsigned Index = ArgIndex + DataIndex;
1307 std::string FunctionName = GetFunctionName();
1308 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1309 PDiag(DiagID) << FunctionName << (Index + 1)
1310 << DestSize << SourceSize);
1311 };
1312
1313 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1314 return ComputeSizeArgument(Index + DataIndex);
1315 };
1316 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1317 const char *FormatBytes = FormatStrRef.data();
1319 FormatBytes + StrLen, getLangOpts(),
1320 Context.getTargetInfo());
1321
1322 // Unlike the other cases, in this one we have already issued the diagnostic
1323 // here, so no need to continue (because unlike the other cases, here the
1324 // diagnostic refers to the argument number).
1325 return;
1326 }
1327
1328 case Builtin::BIsprintf:
1329 case Builtin::BI__builtin___sprintf_chk: {
1330 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1331 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1332
1333 StringRef FormatStrRef;
1334 size_t StrLen;
1335 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1336 EstimateSizeFormatHandler H(FormatStrRef);
1337 const char *FormatBytes = FormatStrRef.data();
1339 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1340 Context.getTargetInfo(), false)) {
1341 DiagID = H.isKernelCompatible()
1342 ? diag::warn_format_overflow
1343 : diag::warn_format_overflow_non_kprintf;
1344 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1345 .extOrTrunc(SizeTypeWidth);
1346 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1347 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1348 IsChkVariant = true;
1349 } else {
1350 DestinationSize = ComputeSizeArgument(0);
1351 }
1352 break;
1353 }
1354 }
1355 return;
1356 }
1357 case Builtin::BI__builtin___memcpy_chk:
1358 case Builtin::BI__builtin___memmove_chk:
1359 case Builtin::BI__builtin___memset_chk:
1360 case Builtin::BI__builtin___strlcat_chk:
1361 case Builtin::BI__builtin___strlcpy_chk:
1362 case Builtin::BI__builtin___strncat_chk:
1363 case Builtin::BI__builtin___strncpy_chk:
1364 case Builtin::BI__builtin___stpncpy_chk:
1365 case Builtin::BI__builtin___memccpy_chk:
1366 case Builtin::BI__builtin___mempcpy_chk: {
1367 DiagID = diag::warn_builtin_chk_overflow;
1368 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1369 DestinationSize =
1370 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1371 IsChkVariant = true;
1372 break;
1373 }
1374
1375 case Builtin::BI__builtin___snprintf_chk:
1376 case Builtin::BI__builtin___vsnprintf_chk: {
1377 DiagID = diag::warn_builtin_chk_overflow;
1378 SourceSize = ComputeExplicitObjectSizeArgument(1);
1379 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1380 IsChkVariant = true;
1381 break;
1382 }
1383
1384 case Builtin::BIstrncat:
1385 case Builtin::BI__builtin_strncat:
1386 case Builtin::BIstrncpy:
1387 case Builtin::BI__builtin_strncpy:
1388 case Builtin::BIstpncpy:
1389 case Builtin::BI__builtin_stpncpy: {
1390 // Whether these functions overflow depends on the runtime strlen of the
1391 // string, not just the buffer size, so emitting the "always overflow"
1392 // diagnostic isn't quite right. We should still diagnose passing a buffer
1393 // size larger than the destination buffer though; this is a runtime abort
1394 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1395 DiagID = diag::warn_fortify_source_size_mismatch;
1396 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1397 DestinationSize = ComputeSizeArgument(0);
1398 break;
1399 }
1400
1401 case Builtin::BImemcpy:
1402 case Builtin::BI__builtin_memcpy:
1403 case Builtin::BImemmove:
1404 case Builtin::BI__builtin_memmove:
1405 case Builtin::BImemset:
1406 case Builtin::BI__builtin_memset:
1407 case Builtin::BImempcpy:
1408 case Builtin::BI__builtin_mempcpy: {
1409 DiagID = diag::warn_fortify_source_overflow;
1410 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1411 DestinationSize = ComputeSizeArgument(0);
1412 break;
1413 }
1414 case Builtin::BIsnprintf:
1415 case Builtin::BI__builtin_snprintf:
1416 case Builtin::BIvsnprintf:
1417 case Builtin::BI__builtin_vsnprintf: {
1418 DiagID = diag::warn_fortify_source_size_mismatch;
1419 SourceSize = ComputeExplicitObjectSizeArgument(1);
1420 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1421 StringRef FormatStrRef;
1422 size_t StrLen;
1423 if (SourceSize &&
1424 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1425 EstimateSizeFormatHandler H(FormatStrRef);
1426 const char *FormatBytes = FormatStrRef.data();
1428 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1429 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1430 llvm::APSInt FormatSize =
1431 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1432 .extOrTrunc(SizeTypeWidth);
1433 if (FormatSize > *SourceSize && *SourceSize != 0) {
1434 unsigned TruncationDiagID =
1435 H.isKernelCompatible() ? diag::warn_format_truncation
1436 : diag::warn_format_truncation_non_kprintf;
1437 SmallString<16> SpecifiedSizeStr;
1438 SmallString<16> FormatSizeStr;
1439 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1440 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1441 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1442 PDiag(TruncationDiagID)
1443 << GetFunctionName() << SpecifiedSizeStr
1444 << FormatSizeStr);
1445 }
1446 }
1447 }
1448 DestinationSize = ComputeSizeArgument(0);
1449 }
1450 }
1451
1452 if (!SourceSize || !DestinationSize ||
1453 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1454 return;
1455
1456 std::string FunctionName = GetFunctionName();
1457
1458 SmallString<16> DestinationStr;
1459 SmallString<16> SourceStr;
1460 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1461 SourceSize->toString(SourceStr, /*Radix=*/10);
1462 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1463 PDiag(DiagID)
1464 << FunctionName << DestinationStr << SourceStr);
1465}
1466
1467static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1468 Scope::ScopeFlags NeededScopeFlags,
1469 unsigned DiagID) {
1470 // Scopes aren't available during instantiation. Fortunately, builtin
1471 // functions cannot be template args so they cannot be formed through template
1472 // instantiation. Therefore checking once during the parse is sufficient.
1473 if (SemaRef.inTemplateInstantiation())
1474 return false;
1475
1476 Scope *S = SemaRef.getCurScope();
1477 while (S && !S->isSEHExceptScope())
1478 S = S->getParent();
1479 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1480 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1481 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1482 << DRE->getDecl()->getIdentifier();
1483 return true;
1484 }
1485
1486 return false;
1487}
1488
1489// In OpenCL, __builtin_alloca_* should return a pointer to address space
1490// that corresponds to the stack address space i.e private address space.
1491static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1492 QualType RT = TheCall->getType();
1493 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1494 "__builtin_alloca has invalid address space");
1495
1496 RT = RT->getPointeeType();
1498 TheCall->setType(S.Context.getPointerType(RT));
1499}
1500
1501namespace {
1502enum PointerAuthOpKind {
1503 PAO_Strip,
1504 PAO_Sign,
1505 PAO_Auth,
1506 PAO_SignGeneric,
1507 PAO_Discriminator,
1508 PAO_BlendPointer,
1509 PAO_BlendInteger
1510};
1511}
1512
1514 if (getLangOpts().PointerAuthIntrinsics)
1515 return false;
1516
1517 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1518 return true;
1519}
1520
1521static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1523}
1524
1525static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1526 // Convert it to type 'int'.
1527 if (convertArgumentToType(S, Arg, S.Context.IntTy))
1528 return true;
1529
1530 // Value-dependent expressions are okay; wait for template instantiation.
1531 if (Arg->isValueDependent())
1532 return false;
1533
1534 unsigned KeyValue;
1535 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1536}
1537
1539 // Attempt to constant-evaluate the expression.
1540 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1541 if (!KeyValue) {
1542 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1543 << 0 << Arg->getSourceRange();
1544 return true;
1545 }
1546
1547 // Ask the target to validate the key parameter.
1548 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1550 {
1551 llvm::raw_svector_ostream Str(Value);
1552 Str << *KeyValue;
1553 }
1554
1555 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1556 << Value << Arg->getSourceRange();
1557 return true;
1558 }
1559
1560 Result = KeyValue->getZExtValue();
1561 return false;
1562}
1563
1566 unsigned &IntVal) {
1567 if (!Arg) {
1568 IntVal = 0;
1569 return true;
1570 }
1571
1572 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
1573 if (!Result) {
1574 Diag(Arg->getExprLoc(), diag::err_ptrauth_arg_not_ice);
1575 return false;
1576 }
1577
1578 unsigned Max;
1579 bool IsAddrDiscArg = false;
1580
1581 switch (Kind) {
1583 Max = 1;
1584 IsAddrDiscArg = true;
1585 break;
1588 break;
1589 };
1590
1592 if (IsAddrDiscArg)
1593 Diag(Arg->getExprLoc(), diag::err_ptrauth_address_discrimination_invalid)
1594 << Result->getExtValue();
1595 else
1596 Diag(Arg->getExprLoc(), diag::err_ptrauth_extra_discriminator_invalid)
1597 << Result->getExtValue() << Max;
1598
1599 return false;
1600 };
1601
1602 IntVal = Result->getZExtValue();
1603 return true;
1604}
1605
1606static std::pair<const ValueDecl *, CharUnits>
1608 // Must evaluate as a pointer.
1609 Expr::EvalResult Result;
1610 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1611 return {nullptr, CharUnits()};
1612
1613 const auto *BaseDecl =
1614 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1615 if (!BaseDecl)
1616 return {nullptr, CharUnits()};
1617
1618 return {BaseDecl, Result.Val.getLValueOffset()};
1619}
1620
1621static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1622 bool RequireConstant = false) {
1623 if (Arg->hasPlaceholderType()) {
1625 if (R.isInvalid())
1626 return true;
1627 Arg = R.get();
1628 }
1629
1630 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1631 return OpKind != PAO_BlendInteger;
1632 };
1633 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1634 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1635 OpKind == PAO_SignGeneric;
1636 };
1637
1638 // Require the value to have the right range of type.
1639 QualType ExpectedTy;
1640 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1641 ExpectedTy = Arg->getType().getUnqualifiedType();
1642 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1643 ExpectedTy = S.Context.VoidPtrTy;
1644 } else if (AllowsInteger(OpKind) &&
1646 ExpectedTy = S.Context.getUIntPtrType();
1647
1648 } else {
1649 // Diagnose the failures.
1650 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1651 << unsigned(OpKind == PAO_Discriminator ? 1
1652 : OpKind == PAO_BlendPointer ? 2
1653 : OpKind == PAO_BlendInteger ? 3
1654 : 0)
1655 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1656 << Arg->getType() << Arg->getSourceRange();
1657 return true;
1658 }
1659
1660 // Convert to that type. This should just be an lvalue-to-rvalue
1661 // conversion.
1662 if (convertArgumentToType(S, Arg, ExpectedTy))
1663 return true;
1664
1665 if (!RequireConstant) {
1666 // Warn about null pointers for non-generic sign and auth operations.
1667 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1669 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1670 ? diag::warn_ptrauth_sign_null_pointer
1671 : diag::warn_ptrauth_auth_null_pointer)
1672 << Arg->getSourceRange();
1673 }
1674
1675 return false;
1676 }
1677
1678 // Perform special checking on the arguments to ptrauth_sign_constant.
1679
1680 // The main argument.
1681 if (OpKind == PAO_Sign) {
1682 // Require the value we're signing to have a special form.
1683 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1684 bool Invalid;
1685
1686 // Must be rooted in a declaration reference.
1687 if (!BaseDecl)
1688 Invalid = true;
1689
1690 // If it's a function declaration, we can't have an offset.
1691 else if (isa<FunctionDecl>(BaseDecl))
1692 Invalid = !Offset.isZero();
1693
1694 // Otherwise we're fine.
1695 else
1696 Invalid = false;
1697
1698 if (Invalid)
1699 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1700 return Invalid;
1701 }
1702
1703 // The discriminator argument.
1704 assert(OpKind == PAO_Discriminator);
1705
1706 // Must be a pointer or integer or blend thereof.
1707 Expr *Pointer = nullptr;
1708 Expr *Integer = nullptr;
1709 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1710 if (Call->getBuiltinCallee() ==
1711 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1712 Pointer = Call->getArg(0);
1713 Integer = Call->getArg(1);
1714 }
1715 }
1716 if (!Pointer && !Integer) {
1717 if (Arg->getType()->isPointerType())
1718 Pointer = Arg;
1719 else
1720 Integer = Arg;
1721 }
1722
1723 // Check the pointer.
1724 bool Invalid = false;
1725 if (Pointer) {
1726 assert(Pointer->getType()->isPointerType());
1727
1728 // TODO: if we're initializing a global, check that the address is
1729 // somehow related to what we're initializing. This probably will
1730 // never really be feasible and we'll have to catch it at link-time.
1731 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
1732 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
1733 Invalid = true;
1734 }
1735
1736 // Check the integer.
1737 if (Integer) {
1738 assert(Integer->getType()->isIntegerType());
1739 if (!Integer->isEvaluatable(S.Context))
1740 Invalid = true;
1741 }
1742
1743 if (Invalid)
1744 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
1745 return Invalid;
1746}
1747
1749 if (S.checkArgCount(Call, 2))
1750 return ExprError();
1752 return ExprError();
1753 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
1754 checkPointerAuthKey(S, Call->getArgs()[1]))
1755 return ExprError();
1756
1757 Call->setType(Call->getArgs()[0]->getType());
1758 return Call;
1759}
1760
1762 if (S.checkArgCount(Call, 2))
1763 return ExprError();
1765 return ExprError();
1766 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
1767 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
1768 return ExprError();
1769
1770 Call->setType(S.Context.getUIntPtrType());
1771 return Call;
1772}
1773
1775 if (S.checkArgCount(Call, 2))
1776 return ExprError();
1778 return ExprError();
1779 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
1780 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
1781 return ExprError();
1782
1783 Call->setType(S.Context.getUIntPtrType());
1784 return Call;
1785}
1786
1788 PointerAuthOpKind OpKind,
1789 bool RequireConstant) {
1790 if (S.checkArgCount(Call, 3))
1791 return ExprError();
1793 return ExprError();
1794 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
1795 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1796 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
1797 RequireConstant))
1798 return ExprError();
1799
1800 Call->setType(Call->getArgs()[0]->getType());
1801 return Call;
1802}
1803
1805 if (S.checkArgCount(Call, 5))
1806 return ExprError();
1808 return ExprError();
1809 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1810 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1811 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1812 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1813 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
1814 return ExprError();
1815
1816 Call->setType(Call->getArgs()[0]->getType());
1817 return Call;
1818}
1819
1822 return ExprError();
1823
1824 // We've already performed normal call type-checking.
1825 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
1826
1827 // Operand must be an ordinary or UTF-8 string literal.
1828 const auto *Literal = dyn_cast<StringLiteral>(Arg);
1829 if (!Literal || Literal->getCharByteWidth() != 1) {
1830 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
1831 << (Literal ? 1 : 0) << Arg->getSourceRange();
1832 return ExprError();
1833 }
1834
1835 return Call;
1836}
1837
1839 if (S.checkArgCount(Call, 1))
1840 return ExprError();
1841 Expr *FirstArg = Call->getArg(0);
1842 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(FirstArg);
1843 if (FirstValue.isInvalid())
1844 return ExprError();
1845 Call->setArg(0, FirstValue.get());
1846 QualType FirstArgType = FirstArg->getType();
1847 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
1848 FirstArgType = S.Context.getDecayedType(FirstArgType);
1849
1850 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
1851 if (!FirstArgRecord) {
1852 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1853 << /*isPolymorphic=*/0 << FirstArgType;
1854 return ExprError();
1855 }
1856 if (S.RequireCompleteType(
1857 FirstArg->getBeginLoc(), FirstArgType->getPointeeType(),
1858 diag::err_get_vtable_pointer_requires_complete_type)) {
1859 return ExprError();
1860 }
1861
1862 if (!FirstArgRecord->isPolymorphic()) {
1863 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1864 << /*isPolymorphic=*/1 << FirstArgRecord;
1865 return ExprError();
1866 }
1868 Call->setType(ReturnType);
1869 return Call;
1870}
1871
1873 if (S.checkArgCount(TheCall, 1))
1874 return ExprError();
1875
1876 // Compute __builtin_launder's parameter type from the argument.
1877 // The parameter type is:
1878 // * The type of the argument if it's not an array or function type,
1879 // Otherwise,
1880 // * The decayed argument type.
1881 QualType ParamTy = [&]() {
1882 QualType ArgTy = TheCall->getArg(0)->getType();
1883 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1884 return S.Context.getPointerType(Ty->getElementType());
1885 if (ArgTy->isFunctionType()) {
1886 return S.Context.getPointerType(ArgTy);
1887 }
1888 return ArgTy;
1889 }();
1890
1891 TheCall->setType(ParamTy);
1892
1893 auto DiagSelect = [&]() -> std::optional<unsigned> {
1894 if (!ParamTy->isPointerType())
1895 return 0;
1896 if (ParamTy->isFunctionPointerType())
1897 return 1;
1898 if (ParamTy->isVoidPointerType())
1899 return 2;
1900 return std::optional<unsigned>{};
1901 }();
1902 if (DiagSelect) {
1903 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1904 << *DiagSelect << TheCall->getSourceRange();
1905 return ExprError();
1906 }
1907
1908 // We either have an incomplete class type, or we have a class template
1909 // whose instantiation has not been forced. Example:
1910 //
1911 // template <class T> struct Foo { T value; };
1912 // Foo<int> *p = nullptr;
1913 // auto *d = __builtin_launder(p);
1914 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1915 diag::err_incomplete_type))
1916 return ExprError();
1917
1918 assert(ParamTy->getPointeeType()->isObjectType() &&
1919 "Unhandled non-object pointer case");
1920
1921 InitializedEntity Entity =
1923 ExprResult Arg =
1924 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1925 if (Arg.isInvalid())
1926 return ExprError();
1927 TheCall->setArg(0, Arg.get());
1928
1929 return TheCall;
1930}
1931
1933 if (S.checkArgCount(TheCall, 1))
1934 return ExprError();
1935
1937 if (Arg.isInvalid())
1938 return ExprError();
1939 QualType ParamTy = Arg.get()->getType();
1940 TheCall->setArg(0, Arg.get());
1941 TheCall->setType(S.Context.BoolTy);
1942
1943 // Only accept pointers to objects as arguments, which should have object
1944 // pointer or void pointer types.
1945 if (const auto *PT = ParamTy->getAs<PointerType>()) {
1946 // LWG4138: Function pointer types not allowed
1947 if (PT->getPointeeType()->isFunctionType()) {
1948 S.Diag(TheCall->getArg(0)->getExprLoc(),
1949 diag::err_builtin_is_within_lifetime_invalid_arg)
1950 << 1;
1951 return ExprError();
1952 }
1953 // Disallow VLAs too since those shouldn't be able to
1954 // be a template parameter for `std::is_within_lifetime`
1955 if (PT->getPointeeType()->isVariableArrayType()) {
1956 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
1957 << 1 << "__builtin_is_within_lifetime";
1958 return ExprError();
1959 }
1960 } else {
1961 S.Diag(TheCall->getArg(0)->getExprLoc(),
1962 diag::err_builtin_is_within_lifetime_invalid_arg)
1963 << 0;
1964 return ExprError();
1965 }
1966 return TheCall;
1967}
1968
1970 if (S.checkArgCount(TheCall, 3))
1971 return ExprError();
1972
1973 QualType Dest = TheCall->getArg(0)->getType();
1974 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
1975 S.Diag(TheCall->getArg(0)->getExprLoc(),
1976 diag::err_builtin_trivially_relocate_invalid_arg_type)
1977 << /*a pointer*/ 0;
1978 return ExprError();
1979 }
1980
1981 QualType T = Dest->getPointeeType();
1982 if (S.RequireCompleteType(TheCall->getBeginLoc(), T,
1983 diag::err_incomplete_type))
1984 return ExprError();
1985
1986 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
1987 T->isIncompleteArrayType()) {
1988 S.Diag(TheCall->getArg(0)->getExprLoc(),
1989 diag::err_builtin_trivially_relocate_invalid_arg_type)
1990 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
1991 return ExprError();
1992 }
1993
1994 TheCall->setType(Dest);
1995
1996 QualType Src = TheCall->getArg(1)->getType();
1997 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
1998 S.Diag(TheCall->getArg(1)->getExprLoc(),
1999 diag::err_builtin_trivially_relocate_invalid_arg_type)
2000 << /*the same*/ 3;
2001 return ExprError();
2002 }
2003
2004 Expr *SizeExpr = TheCall->getArg(2);
2005 ExprResult Size = S.DefaultLvalueConversion(SizeExpr);
2006 if (Size.isInvalid())
2007 return ExprError();
2008
2009 Size = S.tryConvertExprToType(Size.get(), S.getASTContext().getSizeType());
2010 if (Size.isInvalid())
2011 return ExprError();
2012 SizeExpr = Size.get();
2013 TheCall->setArg(2, SizeExpr);
2014
2015 return TheCall;
2016}
2017
2018// Emit an error and return true if the current object format type is in the
2019// list of unsupported types.
2021 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2022 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2023 llvm::Triple::ObjectFormatType CurObjFormat =
2024 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2025 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2026 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2027 << TheCall->getSourceRange();
2028 return true;
2029 }
2030 return false;
2031}
2032
2033// Emit an error and return true if the current architecture is not in the list
2034// of supported architectures.
2035static bool
2037 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2038 llvm::Triple::ArchType CurArch =
2039 S.getASTContext().getTargetInfo().getTriple().getArch();
2040 if (llvm::is_contained(SupportedArchs, CurArch))
2041 return false;
2042 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2043 << TheCall->getSourceRange();
2044 return true;
2045}
2046
2047static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2048 SourceLocation CallSiteLoc);
2049
2050bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2051 CallExpr *TheCall) {
2052 switch (TI.getTriple().getArch()) {
2053 default:
2054 // Some builtins don't require additional checking, so just consider these
2055 // acceptable.
2056 return false;
2057 case llvm::Triple::arm:
2058 case llvm::Triple::armeb:
2059 case llvm::Triple::thumb:
2060 case llvm::Triple::thumbeb:
2061 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2062 case llvm::Triple::aarch64:
2063 case llvm::Triple::aarch64_32:
2064 case llvm::Triple::aarch64_be:
2065 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2066 case llvm::Triple::bpfeb:
2067 case llvm::Triple::bpfel:
2068 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2069 case llvm::Triple::dxil:
2070 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2071 case llvm::Triple::hexagon:
2072 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2073 case llvm::Triple::mips:
2074 case llvm::Triple::mipsel:
2075 case llvm::Triple::mips64:
2076 case llvm::Triple::mips64el:
2077 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2078 case llvm::Triple::spirv:
2079 case llvm::Triple::spirv32:
2080 case llvm::Triple::spirv64:
2081 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2082 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2083 return false;
2084 case llvm::Triple::systemz:
2085 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2086 case llvm::Triple::x86:
2087 case llvm::Triple::x86_64:
2088 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2089 case llvm::Triple::ppc:
2090 case llvm::Triple::ppcle:
2091 case llvm::Triple::ppc64:
2092 case llvm::Triple::ppc64le:
2093 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2094 case llvm::Triple::amdgcn:
2095 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2096 case llvm::Triple::riscv32:
2097 case llvm::Triple::riscv64:
2098 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2099 case llvm::Triple::loongarch32:
2100 case llvm::Triple::loongarch64:
2101 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2102 TheCall);
2103 case llvm::Triple::wasm32:
2104 case llvm::Triple::wasm64:
2105 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2106 case llvm::Triple::nvptx:
2107 case llvm::Triple::nvptx64:
2108 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2109 }
2110}
2111
2112// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2113// not a valid type, emit an error message and return true. Otherwise return
2114// false.
2115static bool
2118 int ArgOrdinal) {
2119 QualType EltTy = ArgTy;
2120 if (auto *VecTy = EltTy->getAs<VectorType>())
2121 EltTy = VecTy->getElementType();
2122
2123 switch (ArgTyRestr) {
2125 if (!ArgTy->getAs<VectorType>() &&
2127 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2128 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2129 << ArgTy;
2130 }
2131 break;
2133 if (!EltTy->isRealFloatingType()) {
2134 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2135 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2136 << /* floating-point */ 1 << ArgTy;
2137 }
2138 break;
2140 if (!EltTy->isIntegerType()) {
2141 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2142 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2143 << /* no fp */ 0 << ArgTy;
2144 }
2145 break;
2147 if (EltTy->isUnsignedIntegerType()) {
2148 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2149 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2150 << /* or fp */ 1 << ArgTy;
2151 }
2152 break;
2153 }
2154
2155 return false;
2156}
2157
2158/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2159/// This checks that the target supports the builtin and that the string
2160/// argument is constant and valid.
2161static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2162 const TargetInfo *AuxTI, unsigned BuiltinID) {
2163 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2164 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2165 "Expecting __builtin_cpu_...");
2166
2167 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2168 const TargetInfo *TheTI = &TI;
2169 auto SupportsBI = [=](const TargetInfo *TInfo) {
2170 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2171 (!IsCPUSupports && TInfo->supportsCpuIs()));
2172 };
2173 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2174 TheTI = AuxTI;
2175
2176 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2177 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2178 return S.Diag(TheCall->getBeginLoc(),
2179 TI.getTriple().isOSAIX()
2180 ? diag::err_builtin_aix_os_unsupported
2181 : diag::err_builtin_target_unsupported)
2182 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2183
2184 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2185 // Check if the argument is a string literal.
2186 if (!isa<StringLiteral>(Arg))
2187 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2188 << Arg->getSourceRange();
2189
2190 // Check the contents of the string.
2191 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2192 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2193 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2194 << Arg->getSourceRange();
2195 return false;
2196 }
2197 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2198 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2199 << Arg->getSourceRange();
2200 return false;
2201}
2202
2203/// Checks that __builtin_popcountg was called with a single argument, which is
2204/// an unsigned integer.
2205static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2206 if (S.checkArgCount(TheCall, 1))
2207 return true;
2208
2209 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2210 if (ArgRes.isInvalid())
2211 return true;
2212
2213 Expr *Arg = ArgRes.get();
2214 TheCall->setArg(0, Arg);
2215
2216 QualType ArgTy = Arg->getType();
2217
2218 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2219 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2220 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2221 << ArgTy;
2222 return true;
2223 }
2224 return false;
2225}
2226
2227/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2228/// an unsigned integer, and an optional second argument, which is promoted to
2229/// an 'int'.
2230static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2231 if (S.checkArgCountRange(TheCall, 1, 2))
2232 return true;
2233
2234 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2235 if (Arg0Res.isInvalid())
2236 return true;
2237
2238 Expr *Arg0 = Arg0Res.get();
2239 TheCall->setArg(0, Arg0);
2240
2241 QualType Arg0Ty = Arg0->getType();
2242
2243 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2244 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2245 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2246 << Arg0Ty;
2247 return true;
2248 }
2249
2250 if (TheCall->getNumArgs() > 1) {
2251 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2252 if (Arg1Res.isInvalid())
2253 return true;
2254
2255 Expr *Arg1 = Arg1Res.get();
2256 TheCall->setArg(1, Arg1);
2257
2258 QualType Arg1Ty = Arg1->getType();
2259
2260 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2261 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2262 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2263 return true;
2264 }
2265 }
2266
2267 return false;
2268}
2269
2270static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2271 unsigned Pos) {
2272 QualType MaskTy = MaskArg->getType();
2273 if (!MaskTy->isExtVectorBoolType())
2274 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2275 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2276 << MaskTy;
2277
2278 QualType PtrTy = PtrArg->getType();
2279 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2280 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2281 << Pos << "scalar pointer";
2282 return false;
2283}
2284
2286 if (S.checkArgCountRange(TheCall, 2, 3))
2287 return ExprError();
2288
2289 Expr *MaskArg = TheCall->getArg(0);
2290 Expr *PtrArg = TheCall->getArg(1);
2291 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2))
2292 return ExprError();
2293
2294 QualType MaskTy = MaskArg->getType();
2295 QualType PtrTy = PtrArg->getType();
2296 QualType PointeeTy = PtrTy->getPointeeType();
2297 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2298
2299 QualType RetTy =
2300 S.Context.getExtVectorType(PointeeTy, MaskVecTy->getNumElements());
2301 if (TheCall->getNumArgs() == 3) {
2302 Expr *PassThruArg = TheCall->getArg(2);
2303 QualType PassThruTy = PassThruArg->getType();
2304 if (!S.Context.hasSameType(PassThruTy, RetTy))
2305 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2306 << /* third argument */ 3 << RetTy;
2307 }
2308
2309 TheCall->setType(RetTy);
2310 return TheCall;
2311}
2312
2314 if (S.checkArgCount(TheCall, 3))
2315 return ExprError();
2316
2317 Expr *MaskArg = TheCall->getArg(0);
2318 Expr *ValArg = TheCall->getArg(1);
2319 Expr *PtrArg = TheCall->getArg(2);
2320
2321 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3))
2322 return ExprError();
2323
2324 QualType MaskTy = MaskArg->getType();
2325 QualType PtrTy = PtrArg->getType();
2326 QualType ValTy = ValArg->getType();
2327 if (!ValTy->isVectorType())
2328 return ExprError(
2329 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2330 << 2 << "vector");
2331
2332 QualType PointeeTy = PtrTy->getPointeeType();
2333 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2334 QualType RetTy =
2335 S.Context.getExtVectorType(PointeeTy, MaskVecTy->getNumElements());
2336
2337 if (!S.Context.hasSameType(ValTy, RetTy))
2338 return ExprError(S.Diag(TheCall->getBeginLoc(),
2339 diag::err_vec_builtin_incompatible_vector)
2340 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2341 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2342 TheCall->getArg(1)->getEndLoc()));
2343
2344 TheCall->setType(S.Context.VoidTy);
2345 return TheCall;
2346}
2347
2349 if (S.checkArgCountRange(TheCall, 3, 4))
2350 return ExprError();
2351
2352 Expr *MaskArg = TheCall->getArg(0);
2353 Expr *IdxArg = TheCall->getArg(1);
2354 Expr *PtrArg = TheCall->getArg(2);
2355 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3))
2356 return ExprError();
2357
2358 QualType IdxTy = IdxArg->getType();
2359 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2360 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2361 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2362 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2363 << IdxTy;
2364
2365 QualType MaskTy = MaskArg->getType();
2366 QualType PtrTy = PtrArg->getType();
2367 QualType PointeeTy = PtrTy->getPointeeType();
2368 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2369 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2370 return ExprError(
2371 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2373 TheCall->getBuiltinCallee())
2374 << MaskTy << IdxTy);
2375
2376 QualType RetTy =
2377 S.Context.getExtVectorType(PointeeTy, MaskVecTy->getNumElements());
2378 if (TheCall->getNumArgs() == 4) {
2379 Expr *PassThruArg = TheCall->getArg(3);
2380 QualType PassThruTy = PassThruArg->getType();
2381 if (!S.Context.hasSameType(PassThruTy, RetTy))
2382 return S.Diag(PassThruArg->getExprLoc(),
2383 diag::err_vec_masked_load_store_ptr)
2384 << /* fourth argument */ 4 << RetTy;
2385 }
2386
2387 TheCall->setType(RetTy);
2388 return TheCall;
2389}
2390
2392 if (S.checkArgCount(TheCall, 4))
2393 return ExprError();
2394
2395 Expr *MaskArg = TheCall->getArg(0);
2396 Expr *IdxArg = TheCall->getArg(1);
2397 Expr *ValArg = TheCall->getArg(2);
2398 Expr *PtrArg = TheCall->getArg(3);
2399
2400 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3))
2401 return ExprError();
2402
2403 QualType IdxTy = IdxArg->getType();
2404 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2405 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2406 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2407 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2408 << IdxTy;
2409
2410 QualType ValTy = ValArg->getType();
2411 QualType MaskTy = MaskArg->getType();
2412 QualType PtrTy = PtrArg->getType();
2413 QualType PointeeTy = PtrTy->getPointeeType();
2414
2415 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2416 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2417 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2418 return ExprError(
2419 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2421 TheCall->getBuiltinCallee())
2422 << MaskTy << IdxTy);
2423 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2424 return ExprError(
2425 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2427 TheCall->getBuiltinCallee())
2428 << MaskTy << ValTy);
2429
2430 QualType ArgTy =
2431 S.Context.getExtVectorType(PointeeTy, MaskVecTy->getNumElements());
2432 if (!S.Context.hasSameType(ValTy, ArgTy))
2433 return ExprError(S.Diag(TheCall->getBeginLoc(),
2434 diag::err_vec_builtin_incompatible_vector)
2435 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2436 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2437 TheCall->getArg(1)->getEndLoc()));
2438
2439 TheCall->setType(S.Context.VoidTy);
2440 return TheCall;
2441}
2442
2444 SourceLocation Loc = TheCall->getBeginLoc();
2445 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2446 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2447
2448 if (Args.size() == 0) {
2449 S.Diag(TheCall->getBeginLoc(),
2450 diag::err_typecheck_call_too_few_args_at_least)
2451 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2452 << /*is_non_object=*/0 << TheCall->getSourceRange();
2453 return ExprError();
2454 }
2455
2456 QualType FuncT = Args[0]->getType();
2457
2458 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2459 if (Args.size() < 2) {
2460 S.Diag(TheCall->getBeginLoc(),
2461 diag::err_typecheck_call_too_few_args_at_least)
2462 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2463 << /*is_non_object=*/0 << TheCall->getSourceRange();
2464 return ExprError();
2465 }
2466
2467 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2468 QualType ObjectT = Args[1]->getType();
2469
2470 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
2471 return ExprError();
2472
2473 ExprResult ObjectArg = [&]() -> ExprResult {
2474 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2475 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2476 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2477 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2478 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2479 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2480 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
2481 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
2482 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
2483 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
2484 return Args[1];
2485 }
2486
2487 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2488 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2489 // reference_wrapper;
2490 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2491 if (RD->isInStdNamespace() &&
2492 RD->getDeclName().getAsString() == "reference_wrapper") {
2493 CXXScopeSpec SS;
2494 IdentifierInfo *GetName = &S.Context.Idents.get("get");
2495 UnqualifiedId GetID;
2496 GetID.setIdentifier(GetName, Loc);
2497
2499 S.getCurScope(), Args[1], Loc, tok::period, SS,
2500 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
2501
2502 if (MemExpr.isInvalid())
2503 return ExprError();
2504
2505 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
2506 }
2507 }
2508
2509 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
2510 // class T and t1 does not satisfy the previous two items;
2511
2512 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
2513 }();
2514
2515 if (ObjectArg.isInvalid())
2516 return ExprError();
2517
2518 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
2519 tok::periodstar, ObjectArg.get(), Args[0]);
2520 if (BinOp.isInvalid())
2521 return ExprError();
2522
2523 if (MPT->isMemberDataPointer())
2524 return BinOp;
2525
2526 auto *MemCall = new (S.Context)
2528
2529 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
2530 Args.drop_front(2), TheCall->getRParenLoc());
2531 }
2532 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
2533 Args.drop_front(), TheCall->getRParenLoc());
2534}
2535
2537Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2538 CallExpr *TheCall) {
2539 ExprResult TheCallResult(TheCall);
2540
2541 // Find out if any arguments are required to be integer constant expressions.
2542 unsigned ICEArguments = 0;
2544 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2546 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2547
2548 // If any arguments are required to be ICE's, check and diagnose.
2549 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2550 // Skip arguments not required to be ICE's.
2551 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2552
2553 llvm::APSInt Result;
2554 // If we don't have enough arguments, continue so we can issue better
2555 // diagnostic in checkArgCount(...)
2556 if (ArgNo < TheCall->getNumArgs() &&
2557 BuiltinConstantArg(TheCall, ArgNo, Result))
2558 return true;
2559 ICEArguments &= ~(1 << ArgNo);
2560 }
2561
2562 FPOptions FPO;
2563 switch (BuiltinID) {
2564 case Builtin::BI__builtin_cpu_supports:
2565 case Builtin::BI__builtin_cpu_is:
2566 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2567 Context.getAuxTargetInfo(), BuiltinID))
2568 return ExprError();
2569 break;
2570 case Builtin::BI__builtin_cpu_init:
2571 if (!Context.getTargetInfo().supportsCpuInit()) {
2572 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2573 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2574 return ExprError();
2575 }
2576 break;
2577 case Builtin::BI__builtin___CFStringMakeConstantString:
2578 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2579 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2581 *this, BuiltinID, TheCall,
2582 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2583 return ExprError();
2584 assert(TheCall->getNumArgs() == 1 &&
2585 "Wrong # arguments to builtin CFStringMakeConstantString");
2586 if (ObjC().CheckObjCString(TheCall->getArg(0)))
2587 return ExprError();
2588 break;
2589 case Builtin::BI__builtin_ms_va_start:
2590 case Builtin::BI__builtin_stdarg_start:
2591 case Builtin::BI__builtin_va_start:
2592 case Builtin::BI__builtin_c23_va_start:
2593 if (BuiltinVAStart(BuiltinID, TheCall))
2594 return ExprError();
2595 break;
2596 case Builtin::BI__va_start: {
2597 switch (Context.getTargetInfo().getTriple().getArch()) {
2598 case llvm::Triple::aarch64:
2599 case llvm::Triple::arm:
2600 case llvm::Triple::thumb:
2601 if (BuiltinVAStartARMMicrosoft(TheCall))
2602 return ExprError();
2603 break;
2604 default:
2605 if (BuiltinVAStart(BuiltinID, TheCall))
2606 return ExprError();
2607 break;
2608 }
2609 break;
2610 }
2611
2612 // The acquire, release, and no fence variants are ARM and AArch64 only.
2613 case Builtin::BI_interlockedbittestandset_acq:
2614 case Builtin::BI_interlockedbittestandset_rel:
2615 case Builtin::BI_interlockedbittestandset_nf:
2616 case Builtin::BI_interlockedbittestandreset_acq:
2617 case Builtin::BI_interlockedbittestandreset_rel:
2618 case Builtin::BI_interlockedbittestandreset_nf:
2620 *this, TheCall,
2621 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2622 return ExprError();
2623 break;
2624
2625 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2626 case Builtin::BI_bittest64:
2627 case Builtin::BI_bittestandcomplement64:
2628 case Builtin::BI_bittestandreset64:
2629 case Builtin::BI_bittestandset64:
2630 case Builtin::BI_interlockedbittestandreset64:
2631 case Builtin::BI_interlockedbittestandset64:
2633 *this, TheCall,
2634 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2635 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2636 return ExprError();
2637 break;
2638
2639 // The 64-bit acquire, release, and no fence variants are AArch64 only.
2640 case Builtin::BI_interlockedbittestandreset64_acq:
2641 case Builtin::BI_interlockedbittestandreset64_rel:
2642 case Builtin::BI_interlockedbittestandreset64_nf:
2643 case Builtin::BI_interlockedbittestandset64_acq:
2644 case Builtin::BI_interlockedbittestandset64_rel:
2645 case Builtin::BI_interlockedbittestandset64_nf:
2646 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
2647 return ExprError();
2648 break;
2649
2650 case Builtin::BI__builtin_set_flt_rounds:
2652 *this, TheCall,
2653 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
2654 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
2655 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
2656 llvm::Triple::ppc64le}))
2657 return ExprError();
2658 break;
2659
2660 case Builtin::BI__builtin_isgreater:
2661 case Builtin::BI__builtin_isgreaterequal:
2662 case Builtin::BI__builtin_isless:
2663 case Builtin::BI__builtin_islessequal:
2664 case Builtin::BI__builtin_islessgreater:
2665 case Builtin::BI__builtin_isunordered:
2666 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2667 return ExprError();
2668 break;
2669 case Builtin::BI__builtin_fpclassify:
2670 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
2671 return ExprError();
2672 break;
2673 case Builtin::BI__builtin_isfpclass:
2674 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
2675 return ExprError();
2676 break;
2677 case Builtin::BI__builtin_isfinite:
2678 case Builtin::BI__builtin_isinf:
2679 case Builtin::BI__builtin_isinf_sign:
2680 case Builtin::BI__builtin_isnan:
2681 case Builtin::BI__builtin_issignaling:
2682 case Builtin::BI__builtin_isnormal:
2683 case Builtin::BI__builtin_issubnormal:
2684 case Builtin::BI__builtin_iszero:
2685 case Builtin::BI__builtin_signbit:
2686 case Builtin::BI__builtin_signbitf:
2687 case Builtin::BI__builtin_signbitl:
2688 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
2689 return ExprError();
2690 break;
2691 case Builtin::BI__builtin_shufflevector:
2692 return BuiltinShuffleVector(TheCall);
2693 // TheCall will be freed by the smart pointer here, but that's fine, since
2694 // BuiltinShuffleVector guts it, but then doesn't release it.
2695 case Builtin::BI__builtin_masked_load:
2696 case Builtin::BI__builtin_masked_expand_load:
2697 return BuiltinMaskedLoad(*this, TheCall);
2698 case Builtin::BI__builtin_masked_store:
2699 case Builtin::BI__builtin_masked_compress_store:
2700 return BuiltinMaskedStore(*this, TheCall);
2701 case Builtin::BI__builtin_masked_gather:
2702 return BuiltinMaskedGather(*this, TheCall);
2703 case Builtin::BI__builtin_masked_scatter:
2704 return BuiltinMaskedScatter(*this, TheCall);
2705 case Builtin::BI__builtin_invoke:
2706 return BuiltinInvoke(*this, TheCall);
2707 case Builtin::BI__builtin_prefetch:
2708 if (BuiltinPrefetch(TheCall))
2709 return ExprError();
2710 break;
2711 case Builtin::BI__builtin_alloca_with_align:
2712 case Builtin::BI__builtin_alloca_with_align_uninitialized:
2713 if (BuiltinAllocaWithAlign(TheCall))
2714 return ExprError();
2715 [[fallthrough]];
2716 case Builtin::BI__builtin_alloca:
2717 case Builtin::BI__builtin_alloca_uninitialized:
2718 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
2719 << TheCall->getDirectCallee();
2720 if (getLangOpts().OpenCL) {
2721 builtinAllocaAddrSpace(*this, TheCall);
2722 }
2723 break;
2724 case Builtin::BI__arithmetic_fence:
2725 if (BuiltinArithmeticFence(TheCall))
2726 return ExprError();
2727 break;
2728 case Builtin::BI__assume:
2729 case Builtin::BI__builtin_assume:
2730 if (BuiltinAssume(TheCall))
2731 return ExprError();
2732 break;
2733 case Builtin::BI__builtin_assume_aligned:
2734 if (BuiltinAssumeAligned(TheCall))
2735 return ExprError();
2736 break;
2737 case Builtin::BI__builtin_dynamic_object_size:
2738 case Builtin::BI__builtin_object_size:
2739 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
2740 return ExprError();
2741 break;
2742 case Builtin::BI__builtin_longjmp:
2743 if (BuiltinLongjmp(TheCall))
2744 return ExprError();
2745 break;
2746 case Builtin::BI__builtin_setjmp:
2747 if (BuiltinSetjmp(TheCall))
2748 return ExprError();
2749 break;
2750 case Builtin::BI__builtin_classify_type:
2751 if (checkArgCount(TheCall, 1))
2752 return true;
2753 TheCall->setType(Context.IntTy);
2754 break;
2755 case Builtin::BI__builtin_complex:
2756 if (BuiltinComplex(TheCall))
2757 return ExprError();
2758 break;
2759 case Builtin::BI__builtin_constant_p: {
2760 if (checkArgCount(TheCall, 1))
2761 return true;
2763 if (Arg.isInvalid()) return true;
2764 TheCall->setArg(0, Arg.get());
2765 TheCall->setType(Context.IntTy);
2766 break;
2767 }
2768 case Builtin::BI__builtin_launder:
2769 return BuiltinLaunder(*this, TheCall);
2770 case Builtin::BI__builtin_is_within_lifetime:
2771 return BuiltinIsWithinLifetime(*this, TheCall);
2772 case Builtin::BI__builtin_trivially_relocate:
2773 return BuiltinTriviallyRelocate(*this, TheCall);
2774
2775 case Builtin::BI__sync_fetch_and_add:
2776 case Builtin::BI__sync_fetch_and_add_1:
2777 case Builtin::BI__sync_fetch_and_add_2:
2778 case Builtin::BI__sync_fetch_and_add_4:
2779 case Builtin::BI__sync_fetch_and_add_8:
2780 case Builtin::BI__sync_fetch_and_add_16:
2781 case Builtin::BI__sync_fetch_and_sub:
2782 case Builtin::BI__sync_fetch_and_sub_1:
2783 case Builtin::BI__sync_fetch_and_sub_2:
2784 case Builtin::BI__sync_fetch_and_sub_4:
2785 case Builtin::BI__sync_fetch_and_sub_8:
2786 case Builtin::BI__sync_fetch_and_sub_16:
2787 case Builtin::BI__sync_fetch_and_or:
2788 case Builtin::BI__sync_fetch_and_or_1:
2789 case Builtin::BI__sync_fetch_and_or_2:
2790 case Builtin::BI__sync_fetch_and_or_4:
2791 case Builtin::BI__sync_fetch_and_or_8:
2792 case Builtin::BI__sync_fetch_and_or_16:
2793 case Builtin::BI__sync_fetch_and_and:
2794 case Builtin::BI__sync_fetch_and_and_1:
2795 case Builtin::BI__sync_fetch_and_and_2:
2796 case Builtin::BI__sync_fetch_and_and_4:
2797 case Builtin::BI__sync_fetch_and_and_8:
2798 case Builtin::BI__sync_fetch_and_and_16:
2799 case Builtin::BI__sync_fetch_and_xor:
2800 case Builtin::BI__sync_fetch_and_xor_1:
2801 case Builtin::BI__sync_fetch_and_xor_2:
2802 case Builtin::BI__sync_fetch_and_xor_4:
2803 case Builtin::BI__sync_fetch_and_xor_8:
2804 case Builtin::BI__sync_fetch_and_xor_16:
2805 case Builtin::BI__sync_fetch_and_nand:
2806 case Builtin::BI__sync_fetch_and_nand_1:
2807 case Builtin::BI__sync_fetch_and_nand_2:
2808 case Builtin::BI__sync_fetch_and_nand_4:
2809 case Builtin::BI__sync_fetch_and_nand_8:
2810 case Builtin::BI__sync_fetch_and_nand_16:
2811 case Builtin::BI__sync_add_and_fetch:
2812 case Builtin::BI__sync_add_and_fetch_1:
2813 case Builtin::BI__sync_add_and_fetch_2:
2814 case Builtin::BI__sync_add_and_fetch_4:
2815 case Builtin::BI__sync_add_and_fetch_8:
2816 case Builtin::BI__sync_add_and_fetch_16:
2817 case Builtin::BI__sync_sub_and_fetch:
2818 case Builtin::BI__sync_sub_and_fetch_1:
2819 case Builtin::BI__sync_sub_and_fetch_2:
2820 case Builtin::BI__sync_sub_and_fetch_4:
2821 case Builtin::BI__sync_sub_and_fetch_8:
2822 case Builtin::BI__sync_sub_and_fetch_16:
2823 case Builtin::BI__sync_and_and_fetch:
2824 case Builtin::BI__sync_and_and_fetch_1:
2825 case Builtin::BI__sync_and_and_fetch_2:
2826 case Builtin::BI__sync_and_and_fetch_4:
2827 case Builtin::BI__sync_and_and_fetch_8:
2828 case Builtin::BI__sync_and_and_fetch_16:
2829 case Builtin::BI__sync_or_and_fetch:
2830 case Builtin::BI__sync_or_and_fetch_1:
2831 case Builtin::BI__sync_or_and_fetch_2:
2832 case Builtin::BI__sync_or_and_fetch_4:
2833 case Builtin::BI__sync_or_and_fetch_8:
2834 case Builtin::BI__sync_or_and_fetch_16:
2835 case Builtin::BI__sync_xor_and_fetch:
2836 case Builtin::BI__sync_xor_and_fetch_1:
2837 case Builtin::BI__sync_xor_and_fetch_2:
2838 case Builtin::BI__sync_xor_and_fetch_4:
2839 case Builtin::BI__sync_xor_and_fetch_8:
2840 case Builtin::BI__sync_xor_and_fetch_16:
2841 case Builtin::BI__sync_nand_and_fetch:
2842 case Builtin::BI__sync_nand_and_fetch_1:
2843 case Builtin::BI__sync_nand_and_fetch_2:
2844 case Builtin::BI__sync_nand_and_fetch_4:
2845 case Builtin::BI__sync_nand_and_fetch_8:
2846 case Builtin::BI__sync_nand_and_fetch_16:
2847 case Builtin::BI__sync_val_compare_and_swap:
2848 case Builtin::BI__sync_val_compare_and_swap_1:
2849 case Builtin::BI__sync_val_compare_and_swap_2:
2850 case Builtin::BI__sync_val_compare_and_swap_4:
2851 case Builtin::BI__sync_val_compare_and_swap_8:
2852 case Builtin::BI__sync_val_compare_and_swap_16:
2853 case Builtin::BI__sync_bool_compare_and_swap:
2854 case Builtin::BI__sync_bool_compare_and_swap_1:
2855 case Builtin::BI__sync_bool_compare_and_swap_2:
2856 case Builtin::BI__sync_bool_compare_and_swap_4:
2857 case Builtin::BI__sync_bool_compare_and_swap_8:
2858 case Builtin::BI__sync_bool_compare_and_swap_16:
2859 case Builtin::BI__sync_lock_test_and_set:
2860 case Builtin::BI__sync_lock_test_and_set_1:
2861 case Builtin::BI__sync_lock_test_and_set_2:
2862 case Builtin::BI__sync_lock_test_and_set_4:
2863 case Builtin::BI__sync_lock_test_and_set_8:
2864 case Builtin::BI__sync_lock_test_and_set_16:
2865 case Builtin::BI__sync_lock_release:
2866 case Builtin::BI__sync_lock_release_1:
2867 case Builtin::BI__sync_lock_release_2:
2868 case Builtin::BI__sync_lock_release_4:
2869 case Builtin::BI__sync_lock_release_8:
2870 case Builtin::BI__sync_lock_release_16:
2871 case Builtin::BI__sync_swap:
2872 case Builtin::BI__sync_swap_1:
2873 case Builtin::BI__sync_swap_2:
2874 case Builtin::BI__sync_swap_4:
2875 case Builtin::BI__sync_swap_8:
2876 case Builtin::BI__sync_swap_16:
2877 return BuiltinAtomicOverloaded(TheCallResult);
2878 case Builtin::BI__sync_synchronize:
2879 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
2880 << TheCall->getCallee()->getSourceRange();
2881 break;
2882 case Builtin::BI__builtin_nontemporal_load:
2883 case Builtin::BI__builtin_nontemporal_store:
2884 return BuiltinNontemporalOverloaded(TheCallResult);
2885 case Builtin::BI__builtin_memcpy_inline: {
2886 clang::Expr *SizeOp = TheCall->getArg(2);
2887 // We warn about copying to or from `nullptr` pointers when `size` is
2888 // greater than 0. When `size` is value dependent we cannot evaluate its
2889 // value so we bail out.
2890 if (SizeOp->isValueDependent())
2891 break;
2892 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
2893 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2894 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
2895 }
2896 break;
2897 }
2898 case Builtin::BI__builtin_memset_inline: {
2899 clang::Expr *SizeOp = TheCall->getArg(2);
2900 // We warn about filling to `nullptr` pointers when `size` is greater than
2901 // 0. When `size` is value dependent we cannot evaluate its value so we bail
2902 // out.
2903 if (SizeOp->isValueDependent())
2904 break;
2905 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
2906 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2907 break;
2908 }
2909#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
2910 case Builtin::BI##ID: \
2911 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
2912#include "clang/Basic/Builtins.inc"
2913 case Builtin::BI__annotation:
2914 if (BuiltinMSVCAnnotation(*this, TheCall))
2915 return ExprError();
2916 break;
2917 case Builtin::BI__builtin_annotation:
2918 if (BuiltinAnnotation(*this, TheCall))
2919 return ExprError();
2920 break;
2921 case Builtin::BI__builtin_addressof:
2922 if (BuiltinAddressof(*this, TheCall))
2923 return ExprError();
2924 break;
2925 case Builtin::BI__builtin_function_start:
2926 if (BuiltinFunctionStart(*this, TheCall))
2927 return ExprError();
2928 break;
2929 case Builtin::BI__builtin_is_aligned:
2930 case Builtin::BI__builtin_align_up:
2931 case Builtin::BI__builtin_align_down:
2932 if (BuiltinAlignment(*this, TheCall, BuiltinID))
2933 return ExprError();
2934 break;
2935 case Builtin::BI__builtin_add_overflow:
2936 case Builtin::BI__builtin_sub_overflow:
2937 case Builtin::BI__builtin_mul_overflow:
2938 if (BuiltinOverflow(*this, TheCall, BuiltinID))
2939 return ExprError();
2940 break;
2941 case Builtin::BI__builtin_operator_new:
2942 case Builtin::BI__builtin_operator_delete: {
2943 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
2944 ExprResult Res =
2945 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
2946 return Res;
2947 }
2948 case Builtin::BI__builtin_dump_struct:
2949 return BuiltinDumpStruct(*this, TheCall);
2950 case Builtin::BI__builtin_expect_with_probability: {
2951 // We first want to ensure we are called with 3 arguments
2952 if (checkArgCount(TheCall, 3))
2953 return ExprError();
2954 // then check probability is constant float in range [0.0, 1.0]
2955 const Expr *ProbArg = TheCall->getArg(2);
2956 SmallVector<PartialDiagnosticAt, 8> Notes;
2957 Expr::EvalResult Eval;
2958 Eval.Diag = &Notes;
2959 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2960 !Eval.Val.isFloat()) {
2961 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2962 << ProbArg->getSourceRange();
2963 for (const PartialDiagnosticAt &PDiag : Notes)
2964 Diag(PDiag.first, PDiag.second);
2965 return ExprError();
2966 }
2967 llvm::APFloat Probability = Eval.Val.getFloat();
2968 bool LoseInfo = false;
2969 Probability.convert(llvm::APFloat::IEEEdouble(),
2970 llvm::RoundingMode::Dynamic, &LoseInfo);
2971 if (!(Probability >= llvm::APFloat(0.0) &&
2972 Probability <= llvm::APFloat(1.0))) {
2973 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2974 << ProbArg->getSourceRange();
2975 return ExprError();
2976 }
2977 break;
2978 }
2979 case Builtin::BI__builtin_preserve_access_index:
2980 if (BuiltinPreserveAI(*this, TheCall))
2981 return ExprError();
2982 break;
2983 case Builtin::BI__builtin_call_with_static_chain:
2984 if (BuiltinCallWithStaticChain(*this, TheCall))
2985 return ExprError();
2986 break;
2987 case Builtin::BI__exception_code:
2988 case Builtin::BI_exception_code:
2989 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2990 diag::err_seh___except_block))
2991 return ExprError();
2992 break;
2993 case Builtin::BI__exception_info:
2994 case Builtin::BI_exception_info:
2995 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2996 diag::err_seh___except_filter))
2997 return ExprError();
2998 break;
2999 case Builtin::BI__GetExceptionInfo:
3000 if (checkArgCount(TheCall, 1))
3001 return ExprError();
3002
3004 TheCall->getBeginLoc(),
3005 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3006 TheCall))
3007 return ExprError();
3008
3009 TheCall->setType(Context.VoidPtrTy);
3010 break;
3011 case Builtin::BIaddressof:
3012 case Builtin::BI__addressof:
3013 case Builtin::BIforward:
3014 case Builtin::BIforward_like:
3015 case Builtin::BImove:
3016 case Builtin::BImove_if_noexcept:
3017 case Builtin::BIas_const: {
3018 // These are all expected to be of the form
3019 // T &/&&/* f(U &/&&)
3020 // where T and U only differ in qualification.
3021 if (checkArgCount(TheCall, 1))
3022 return ExprError();
3023 QualType Param = FDecl->getParamDecl(0)->getType();
3024 QualType Result = FDecl->getReturnType();
3025 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3026 BuiltinID == Builtin::BI__addressof;
3027 if (!(Param->isReferenceType() &&
3028 (ReturnsPointer ? Result->isAnyPointerType()
3029 : Result->isReferenceType()) &&
3030 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3031 Result->getPointeeType()))) {
3032 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3033 << FDecl;
3034 return ExprError();
3035 }
3036 break;
3037 }
3038 case Builtin::BI__builtin_ptrauth_strip:
3039 return PointerAuthStrip(*this, TheCall);
3040 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3041 return PointerAuthBlendDiscriminator(*this, TheCall);
3042 case Builtin::BI__builtin_ptrauth_sign_constant:
3043 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3044 /*RequireConstant=*/true);
3045 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3046 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3047 /*RequireConstant=*/false);
3048 case Builtin::BI__builtin_ptrauth_auth:
3049 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3050 /*RequireConstant=*/false);
3051 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3052 return PointerAuthSignGenericData(*this, TheCall);
3053 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3054 return PointerAuthAuthAndResign(*this, TheCall);
3055 case Builtin::BI__builtin_ptrauth_string_discriminator:
3056 return PointerAuthStringDiscriminator(*this, TheCall);
3057
3058 case Builtin::BI__builtin_get_vtable_pointer:
3059 return GetVTablePointer(*this, TheCall);
3060
3061 // OpenCL v2.0, s6.13.16 - Pipe functions
3062 case Builtin::BIread_pipe:
3063 case Builtin::BIwrite_pipe:
3064 // Since those two functions are declared with var args, we need a semantic
3065 // check for the argument.
3066 if (OpenCL().checkBuiltinRWPipe(TheCall))
3067 return ExprError();
3068 break;
3069 case Builtin::BIreserve_read_pipe:
3070 case Builtin::BIreserve_write_pipe:
3071 case Builtin::BIwork_group_reserve_read_pipe:
3072 case Builtin::BIwork_group_reserve_write_pipe:
3073 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3074 return ExprError();
3075 break;
3076 case Builtin::BIsub_group_reserve_read_pipe:
3077 case Builtin::BIsub_group_reserve_write_pipe:
3078 if (OpenCL().checkSubgroupExt(TheCall) ||
3079 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3080 return ExprError();
3081 break;
3082 case Builtin::BIcommit_read_pipe:
3083 case Builtin::BIcommit_write_pipe:
3084 case Builtin::BIwork_group_commit_read_pipe:
3085 case Builtin::BIwork_group_commit_write_pipe:
3086 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3087 return ExprError();
3088 break;
3089 case Builtin::BIsub_group_commit_read_pipe:
3090 case Builtin::BIsub_group_commit_write_pipe:
3091 if (OpenCL().checkSubgroupExt(TheCall) ||
3092 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3093 return ExprError();
3094 break;
3095 case Builtin::BIget_pipe_num_packets:
3096 case Builtin::BIget_pipe_max_packets:
3097 if (OpenCL().checkBuiltinPipePackets(TheCall))
3098 return ExprError();
3099 break;
3100 case Builtin::BIto_global:
3101 case Builtin::BIto_local:
3102 case Builtin::BIto_private:
3103 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3104 return ExprError();
3105 break;
3106 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3107 case Builtin::BIenqueue_kernel:
3108 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3109 return ExprError();
3110 break;
3111 case Builtin::BIget_kernel_work_group_size:
3112 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3113 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3114 return ExprError();
3115 break;
3116 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3117 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3118 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3119 return ExprError();
3120 break;
3121 case Builtin::BI__builtin_os_log_format:
3122 Cleanup.setExprNeedsCleanups(true);
3123 [[fallthrough]];
3124 case Builtin::BI__builtin_os_log_format_buffer_size:
3125 if (BuiltinOSLogFormat(TheCall))
3126 return ExprError();
3127 break;
3128 case Builtin::BI__builtin_frame_address:
3129 case Builtin::BI__builtin_return_address: {
3130 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3131 return ExprError();
3132
3133 // -Wframe-address warning if non-zero passed to builtin
3134 // return/frame address.
3135 Expr::EvalResult Result;
3136 if (!TheCall->getArg(0)->isValueDependent() &&
3137 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3138 Result.Val.getInt() != 0)
3139 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3140 << ((BuiltinID == Builtin::BI__builtin_return_address)
3141 ? "__builtin_return_address"
3142 : "__builtin_frame_address")
3143 << TheCall->getSourceRange();
3144 break;
3145 }
3146
3147 case Builtin::BI__builtin_nondeterministic_value: {
3148 if (BuiltinNonDeterministicValue(TheCall))
3149 return ExprError();
3150 break;
3151 }
3152
3153 // __builtin_elementwise_abs restricts the element type to signed integers or
3154 // floating point types only.
3155 case Builtin::BI__builtin_elementwise_abs:
3158 return ExprError();
3159 break;
3160
3161 // These builtins restrict the element type to floating point
3162 // types only.
3163 case Builtin::BI__builtin_elementwise_acos:
3164 case Builtin::BI__builtin_elementwise_asin:
3165 case Builtin::BI__builtin_elementwise_atan:
3166 case Builtin::BI__builtin_elementwise_ceil:
3167 case Builtin::BI__builtin_elementwise_cos:
3168 case Builtin::BI__builtin_elementwise_cosh:
3169 case Builtin::BI__builtin_elementwise_exp:
3170 case Builtin::BI__builtin_elementwise_exp2:
3171 case Builtin::BI__builtin_elementwise_exp10:
3172 case Builtin::BI__builtin_elementwise_floor:
3173 case Builtin::BI__builtin_elementwise_log:
3174 case Builtin::BI__builtin_elementwise_log2:
3175 case Builtin::BI__builtin_elementwise_log10:
3176 case Builtin::BI__builtin_elementwise_roundeven:
3177 case Builtin::BI__builtin_elementwise_round:
3178 case Builtin::BI__builtin_elementwise_rint:
3179 case Builtin::BI__builtin_elementwise_nearbyint:
3180 case Builtin::BI__builtin_elementwise_sin:
3181 case Builtin::BI__builtin_elementwise_sinh:
3182 case Builtin::BI__builtin_elementwise_sqrt:
3183 case Builtin::BI__builtin_elementwise_tan:
3184 case Builtin::BI__builtin_elementwise_tanh:
3185 case Builtin::BI__builtin_elementwise_trunc:
3186 case Builtin::BI__builtin_elementwise_canonicalize:
3189 return ExprError();
3190 break;
3191 case Builtin::BI__builtin_elementwise_fma:
3192 if (BuiltinElementwiseTernaryMath(TheCall))
3193 return ExprError();
3194 break;
3195
3196 // These builtins restrict the element type to floating point
3197 // types only, and take in two arguments.
3198 case Builtin::BI__builtin_elementwise_minnum:
3199 case Builtin::BI__builtin_elementwise_maxnum:
3200 case Builtin::BI__builtin_elementwise_minimum:
3201 case Builtin::BI__builtin_elementwise_maximum:
3202 case Builtin::BI__builtin_elementwise_minimumnum:
3203 case Builtin::BI__builtin_elementwise_maximumnum:
3204 case Builtin::BI__builtin_elementwise_atan2:
3205 case Builtin::BI__builtin_elementwise_fmod:
3206 case Builtin::BI__builtin_elementwise_pow:
3207 if (BuiltinElementwiseMath(TheCall,
3209 return ExprError();
3210 break;
3211 // These builtins restrict the element type to integer
3212 // types only.
3213 case Builtin::BI__builtin_elementwise_add_sat:
3214 case Builtin::BI__builtin_elementwise_sub_sat:
3215 if (BuiltinElementwiseMath(TheCall,
3217 return ExprError();
3218 break;
3219 case Builtin::BI__builtin_elementwise_fshl:
3220 case Builtin::BI__builtin_elementwise_fshr:
3223 return ExprError();
3224 break;
3225 case Builtin::BI__builtin_elementwise_min:
3226 case Builtin::BI__builtin_elementwise_max:
3227 if (BuiltinElementwiseMath(TheCall))
3228 return ExprError();
3229 break;
3230 case Builtin::BI__builtin_elementwise_popcount:
3231 case Builtin::BI__builtin_elementwise_bitreverse:
3234 return ExprError();
3235 break;
3236 case Builtin::BI__builtin_elementwise_copysign: {
3237 if (checkArgCount(TheCall, 2))
3238 return ExprError();
3239
3240 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3241 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3242 if (Magnitude.isInvalid() || Sign.isInvalid())
3243 return ExprError();
3244
3245 QualType MagnitudeTy = Magnitude.get()->getType();
3246 QualType SignTy = Sign.get()->getType();
3248 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
3251 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
3253 return ExprError();
3254 }
3255
3256 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3257 return Diag(Sign.get()->getBeginLoc(),
3258 diag::err_typecheck_call_different_arg_types)
3259 << MagnitudeTy << SignTy;
3260 }
3261
3262 TheCall->setArg(0, Magnitude.get());
3263 TheCall->setArg(1, Sign.get());
3264 TheCall->setType(Magnitude.get()->getType());
3265 break;
3266 }
3267 case Builtin::BI__builtin_elementwise_clzg:
3268 case Builtin::BI__builtin_elementwise_ctzg:
3269 // These builtins can be unary or binary. Note for empty calls we call the
3270 // unary checker in order to not emit an error that says the function
3271 // expects 2 arguments, which would be misleading.
3272 if (TheCall->getNumArgs() <= 1) {
3275 return ExprError();
3276 } else if (BuiltinElementwiseMath(
3278 return ExprError();
3279 break;
3280 case Builtin::BI__builtin_reduce_max:
3281 case Builtin::BI__builtin_reduce_min: {
3282 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3283 return ExprError();
3284
3285 const Expr *Arg = TheCall->getArg(0);
3286 const auto *TyA = Arg->getType()->getAs<VectorType>();
3287
3288 QualType ElTy;
3289 if (TyA)
3290 ElTy = TyA->getElementType();
3291 else if (Arg->getType()->isSizelessVectorType())
3293
3294 if (ElTy.isNull()) {
3295 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3296 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3297 << Arg->getType();
3298 return ExprError();
3299 }
3300
3301 TheCall->setType(ElTy);
3302 break;
3303 }
3304 case Builtin::BI__builtin_reduce_maximum:
3305 case Builtin::BI__builtin_reduce_minimum: {
3306 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3307 return ExprError();
3308
3309 const Expr *Arg = TheCall->getArg(0);
3310 const auto *TyA = Arg->getType()->getAs<VectorType>();
3311
3312 QualType ElTy;
3313 if (TyA)
3314 ElTy = TyA->getElementType();
3315 else if (Arg->getType()->isSizelessVectorType())
3317
3318 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3319 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3320 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3321 << Arg->getType();
3322 return ExprError();
3323 }
3324
3325 TheCall->setType(ElTy);
3326 break;
3327 }
3328
3329 // These builtins support vectors of integers only.
3330 // TODO: ADD/MUL should support floating-point types.
3331 case Builtin::BI__builtin_reduce_add:
3332 case Builtin::BI__builtin_reduce_mul:
3333 case Builtin::BI__builtin_reduce_xor:
3334 case Builtin::BI__builtin_reduce_or:
3335 case Builtin::BI__builtin_reduce_and: {
3336 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3337 return ExprError();
3338
3339 const Expr *Arg = TheCall->getArg(0);
3340 const auto *TyA = Arg->getType()->getAs<VectorType>();
3341
3342 QualType ElTy;
3343 if (TyA)
3344 ElTy = TyA->getElementType();
3345 else if (Arg->getType()->isSizelessVectorType())
3347
3348 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3349 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3350 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3351 << Arg->getType();
3352 return ExprError();
3353 }
3354
3355 TheCall->setType(ElTy);
3356 break;
3357 }
3358
3359 case Builtin::BI__builtin_matrix_transpose:
3360 return BuiltinMatrixTranspose(TheCall, TheCallResult);
3361
3362 case Builtin::BI__builtin_matrix_column_major_load:
3363 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
3364
3365 case Builtin::BI__builtin_matrix_column_major_store:
3366 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
3367
3368 case Builtin::BI__builtin_verbose_trap:
3369 if (!checkBuiltinVerboseTrap(TheCall, *this))
3370 return ExprError();
3371 break;
3372
3373 case Builtin::BI__builtin_get_device_side_mangled_name: {
3374 auto Check = [](CallExpr *TheCall) {
3375 if (TheCall->getNumArgs() != 1)
3376 return false;
3377 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
3378 if (!DRE)
3379 return false;
3380 auto *D = DRE->getDecl();
3381 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
3382 return false;
3383 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3384 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3385 };
3386 if (!Check(TheCall)) {
3387 Diag(TheCall->getBeginLoc(),
3388 diag::err_hip_invalid_args_builtin_mangled_name);
3389 return ExprError();
3390 }
3391 break;
3392 }
3393 case Builtin::BI__builtin_popcountg:
3394 if (BuiltinPopcountg(*this, TheCall))
3395 return ExprError();
3396 break;
3397 case Builtin::BI__builtin_clzg:
3398 case Builtin::BI__builtin_ctzg:
3399 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
3400 return ExprError();
3401 break;
3402
3403 case Builtin::BI__builtin_allow_runtime_check: {
3404 Expr *Arg = TheCall->getArg(0);
3405 // Check if the argument is a string literal.
3407 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3408 << Arg->getSourceRange();
3409 return ExprError();
3410 }
3411 break;
3412 }
3413 case Builtin::BI__builtin_counted_by_ref:
3414 if (BuiltinCountedByRef(TheCall))
3415 return ExprError();
3416 break;
3417 }
3418
3419 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
3420 return ExprError();
3421
3422 // Since the target specific builtins for each arch overlap, only check those
3423 // of the arch we are compiling for.
3424 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
3425 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
3426 assert(Context.getAuxTargetInfo() &&
3427 "Aux Target Builtin, but not an aux target?");
3428
3429 if (CheckTSBuiltinFunctionCall(
3430 *Context.getAuxTargetInfo(),
3431 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
3432 return ExprError();
3433 } else {
3434 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
3435 TheCall))
3436 return ExprError();
3437 }
3438 }
3439
3440 return TheCallResult;
3441}
3442
3443bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3444 llvm::APSInt Result;
3445 // We can't check the value of a dependent argument.
3446 Expr *Arg = TheCall->getArg(ArgNum);
3447 if (Arg->isTypeDependent() || Arg->isValueDependent())
3448 return false;
3449
3450 // Check constant-ness first.
3451 if (BuiltinConstantArg(TheCall, ArgNum, Result))
3452 return true;
3453
3454 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3455 if (Result.isShiftedMask() || (~Result).isShiftedMask())
3456 return false;
3457
3458 return Diag(TheCall->getBeginLoc(),
3459 diag::err_argument_not_contiguous_bit_field)
3460 << ArgNum << Arg->getSourceRange();
3461}
3462
3463bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
3464 unsigned FirstArg, FormatStringInfo *FSI) {
3465 bool IsCXXMember = false;
3466 if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
3467 IsCXXMember = MD->isInstance();
3468 bool IsVariadic = false;
3469 if (const FunctionType *FnTy = D->getFunctionType())
3470 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
3471 else if (const auto *BD = dyn_cast<BlockDecl>(D))
3472 IsVariadic = BD->isVariadic();
3473 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
3474 IsVariadic = OMD->isVariadic();
3475
3476 return getFormatStringInfo(FormatIdx, FirstArg, IsCXXMember, IsVariadic, FSI);
3477}
3478
3479bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
3480 bool IsCXXMember, bool IsVariadic,
3481 FormatStringInfo *FSI) {
3482 if (FirstArg == 0)
3484 else if (IsVariadic)
3486 else
3488 FSI->FormatIdx = FormatIdx - 1;
3489 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
3490
3491 // The way the format attribute works in GCC, the implicit this argument
3492 // of member functions is counted. However, it doesn't appear in our own
3493 // lists, so decrement format_idx in that case.
3494 if (IsCXXMember) {
3495 if(FSI->FormatIdx == 0)
3496 return false;
3497 --FSI->FormatIdx;
3498 if (FSI->FirstDataArg != 0)
3499 --FSI->FirstDataArg;
3500 }
3501 return true;
3502}
3503
3504/// Checks if a the given expression evaluates to null.
3505///
3506/// Returns true if the value evaluates to null.
3507static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3508 // Treat (smart) pointers constructed from nullptr as null, whether we can
3509 // const-evaluate them or not.
3510 // This must happen first: the smart pointer expr might have _Nonnull type!
3514 return true;
3515
3516 // If the expression has non-null type, it doesn't evaluate to null.
3517 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
3518 if (*nullability == NullabilityKind::NonNull)
3519 return false;
3520 }
3521
3522 // As a special case, transparent unions initialized with zero are
3523 // considered null for the purposes of the nonnull attribute.
3524 if (const RecordType *UT = Expr->getType()->getAsUnionType();
3525 UT && UT->getOriginalDecl()
3526 ->getMostRecentDecl()
3527 ->hasAttr<TransparentUnionAttr>()) {
3528 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
3529 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
3530 Expr = ILE->getInit(0);
3531 }
3532
3533 bool Result;
3534 return (!Expr->isValueDependent() &&
3536 !Result);
3537}
3538
3540 const Expr *ArgExpr,
3541 SourceLocation CallSiteLoc) {
3542 if (CheckNonNullExpr(S, ArgExpr))
3543 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3544 S.PDiag(diag::warn_null_arg)
3545 << ArgExpr->getSourceRange());
3546}
3547
3548/// Determine whether the given type has a non-null nullability annotation.
3550 if (auto nullability = type->getNullability())
3551 return *nullability == NullabilityKind::NonNull;
3552
3553 return false;
3554}
3555
3557 const NamedDecl *FDecl,
3558 const FunctionProtoType *Proto,
3560 SourceLocation CallSiteLoc) {
3561 assert((FDecl || Proto) && "Need a function declaration or prototype");
3562
3563 // Already checked by constant evaluator.
3565 return;
3566 // Check the attributes attached to the method/function itself.
3567 llvm::SmallBitVector NonNullArgs;
3568 if (FDecl) {
3569 // Handle the nonnull attribute on the function/method declaration itself.
3570 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3571 if (!NonNull->args_size()) {
3572 // Easy case: all pointer arguments are nonnull.
3573 for (const auto *Arg : Args)
3574 if (S.isValidPointerAttrType(Arg->getType()))
3575 CheckNonNullArgument(S, Arg, CallSiteLoc);
3576 return;
3577 }
3578
3579 for (const ParamIdx &Idx : NonNull->args()) {
3580 unsigned IdxAST = Idx.getASTIndex();
3581 if (IdxAST >= Args.size())
3582 continue;
3583 if (NonNullArgs.empty())
3584 NonNullArgs.resize(Args.size());
3585 NonNullArgs.set(IdxAST);
3586 }
3587 }
3588 }
3589
3590 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3591 // Handle the nonnull attribute on the parameters of the
3592 // function/method.
3594 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3595 parms = FD->parameters();
3596 else
3597 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3598
3599 unsigned ParamIndex = 0;
3600 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3601 I != E; ++I, ++ParamIndex) {
3602 const ParmVarDecl *PVD = *I;
3603 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
3604 if (NonNullArgs.empty())
3605 NonNullArgs.resize(Args.size());
3606
3607 NonNullArgs.set(ParamIndex);
3608 }
3609 }
3610 } else {
3611 // If we have a non-function, non-method declaration but no
3612 // function prototype, try to dig out the function prototype.
3613 if (!Proto) {
3614 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3615 QualType type = VD->getType().getNonReferenceType();
3616 if (auto pointerType = type->getAs<PointerType>())
3617 type = pointerType->getPointeeType();
3618 else if (auto blockType = type->getAs<BlockPointerType>())
3619 type = blockType->getPointeeType();
3620 // FIXME: data member pointers?
3621
3622 // Dig out the function prototype, if there is one.
3623 Proto = type->getAs<FunctionProtoType>();
3624 }
3625 }
3626
3627 // Fill in non-null argument information from the nullability
3628 // information on the parameter types (if we have them).
3629 if (Proto) {
3630 unsigned Index = 0;
3631 for (auto paramType : Proto->getParamTypes()) {
3632 if (isNonNullType(paramType)) {
3633 if (NonNullArgs.empty())
3634 NonNullArgs.resize(Args.size());
3635
3636 NonNullArgs.set(Index);
3637 }
3638
3639 ++Index;
3640 }
3641 }
3642 }
3643
3644 // Check for non-null arguments.
3645 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3646 ArgIndex != ArgIndexEnd; ++ArgIndex) {
3647 if (NonNullArgs[ArgIndex])
3648 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
3649 }
3650}
3651
3652void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
3653 StringRef ParamName, QualType ArgTy,
3654 QualType ParamTy) {
3655
3656 // If a function accepts a pointer or reference type
3657 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
3658 return;
3659
3660 // If the parameter is a pointer type, get the pointee type for the
3661 // argument too. If the parameter is a reference type, don't try to get
3662 // the pointee type for the argument.
3663 if (ParamTy->isPointerType())
3664 ArgTy = ArgTy->getPointeeType();
3665
3666 // Remove reference or pointer
3667 ParamTy = ParamTy->getPointeeType();
3668
3669 // Find expected alignment, and the actual alignment of the passed object.
3670 // getTypeAlignInChars requires complete types
3671 if (ArgTy.isNull() || ParamTy->isDependentType() ||
3672 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
3673 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
3674 return;
3675
3676 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
3677 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
3678
3679 // If the argument is less aligned than the parameter, there is a
3680 // potential alignment issue.
3681 if (ArgAlign < ParamAlign)
3682 Diag(Loc, diag::warn_param_mismatched_alignment)
3683 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
3684 << ParamName << (FDecl != nullptr) << FDecl;
3685}
3686
3687void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
3688 const Expr *ThisArg,
3690 if (!FD || Args.empty())
3691 return;
3692 auto GetArgAt = [&](int Idx) -> const Expr * {
3693 if (Idx == LifetimeCaptureByAttr::Global ||
3694 Idx == LifetimeCaptureByAttr::Unknown)
3695 return nullptr;
3696 if (IsMemberFunction && Idx == 0)
3697 return ThisArg;
3698 return Args[Idx - IsMemberFunction];
3699 };
3700 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
3701 unsigned ArgIdx) {
3702 if (!Attr)
3703 return;
3704
3705 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
3706 for (int CapturingParamIdx : Attr->params()) {
3707 // lifetime_capture_by(this) case is handled in the lifetimebound expr
3708 // initialization codepath.
3709 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
3711 continue;
3712 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
3713 CapturingEntity CE{Capturing};
3714 // Ensure that 'Captured' outlives the 'Capturing' entity.
3715 checkCaptureByLifetime(*this, CE, Captured);
3716 }
3717 };
3718 for (unsigned I = 0; I < FD->getNumParams(); ++I)
3719 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(),
3720 I + IsMemberFunction);
3721 // Check when the implicit object param is captured.
3722 if (IsMemberFunction) {
3723 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
3724 if (!TSI)
3725 return;
3727 for (TypeLoc TL = TSI->getTypeLoc();
3728 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
3729 TL = ATL.getModifiedLoc())
3730 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
3731 }
3732}
3733
3735 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3736 bool IsMemberFunction, SourceLocation Loc,
3737 SourceRange Range, VariadicCallType CallType) {
3738 // FIXME: We should check as much as we can in the template definition.
3739 if (CurContext->isDependentContext())
3740 return;
3741
3742 // Printf and scanf checking.
3743 llvm::SmallBitVector CheckedVarArgs;
3744 if (FDecl) {
3745 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
3746 // Only create vector if there are format attributes.
3747 CheckedVarArgs.resize(Args.size());
3748 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
3749 CheckedVarArgs);
3750 }
3751
3752 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3753 CheckedVarArgs.resize(Args.size());
3754 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3755 CheckedVarArgs);
3756 }
3757 }
3758
3759 // Refuse POD arguments that weren't caught by the format string
3760 // checks above.
3761 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3762 if (CallType != VariadicCallType::DoesNotApply &&
3763 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3764 unsigned NumParams = Proto ? Proto->getNumParams()
3765 : isa_and_nonnull<FunctionDecl>(FDecl)
3766 ? cast<FunctionDecl>(FDecl)->getNumParams()
3767 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
3768 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3769 : 0;
3770
3771 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3772 // Args[ArgIdx] can be null in malformed code.
3773 if (const Expr *Arg = Args[ArgIdx]) {
3774 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3775 checkVariadicArgument(Arg, CallType);
3776 }
3777 }
3778 }
3779 if (FD)
3780 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
3781 if (FDecl || Proto) {
3782 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
3783
3784 // Type safety checking.
3785 if (FDecl) {
3786 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
3787 CheckArgumentWithTypeTag(I, Args, Loc);
3788 }
3789 }
3790
3791 // Check that passed arguments match the alignment of original arguments.
3792 // Try to get the missing prototype from the declaration.
3793 if (!Proto && FDecl) {
3794 const auto *FT = FDecl->getFunctionType();
3795 if (isa_and_nonnull<FunctionProtoType>(FT))
3796 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
3797 }
3798 if (Proto) {
3799 // For variadic functions, we may have more args than parameters.
3800 // For some K&R functions, we may have less args than parameters.
3801 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
3802 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
3803 bool IsScalableArg = false;
3804 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
3805 // Args[ArgIdx] can be null in malformed code.
3806 if (const Expr *Arg = Args[ArgIdx]) {
3807 if (Arg->containsErrors())
3808 continue;
3809
3810 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
3811 FDecl->hasLinkage() &&
3812 FDecl->getFormalLinkage() != Linkage::Internal &&
3814 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
3815
3816 QualType ParamTy = Proto->getParamType(ArgIdx);
3817 if (ParamTy->isSizelessVectorType())
3818 IsScalableArg = true;
3819 QualType ArgTy = Arg->getType();
3820 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
3821 ArgTy, ParamTy);
3822 }
3823 }
3824
3825 // If the callee has an AArch64 SME attribute to indicate that it is an
3826 // __arm_streaming function, then the caller requires SME to be available.
3829 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
3830 llvm::StringMap<bool> CallerFeatureMap;
3831 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
3832 if (!CallerFeatureMap.contains("sme"))
3833 Diag(Loc, diag::err_sme_call_in_non_sme_target);
3834 } else if (!Context.getTargetInfo().hasFeature("sme")) {
3835 Diag(Loc, diag::err_sme_call_in_non_sme_target);
3836 }
3837 }
3838
3839 // If the call requires a streaming-mode change and has scalable vector
3840 // arguments or return values, then warn the user that the streaming and
3841 // non-streaming vector lengths may be different.
3842 // When both streaming and non-streaming vector lengths are defined and
3843 // mismatched, produce an error.
3844 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
3845 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
3846 (IsScalableArg || IsScalableRet)) {
3847 bool IsCalleeStreaming =
3849 bool IsCalleeStreamingCompatible =
3850 ExtInfo.AArch64SMEAttributes &
3852 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
3853 if (!IsCalleeStreamingCompatible &&
3854 (CallerFnType == SemaARM::ArmStreamingCompatible ||
3855 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
3856 const LangOptions &LO = getLangOpts();
3857 unsigned VL = LO.VScaleMin * 128;
3858 unsigned SVL = LO.VScaleStreamingMin * 128;
3859 bool IsVLMismatch = VL && SVL && VL != SVL;
3860
3861 auto EmitDiag = [&](bool IsArg) {
3862 if (IsVLMismatch) {
3863 if (CallerFnType == SemaARM::ArmStreamingCompatible)
3864 // Emit warning for streaming-compatible callers
3865 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
3866 << IsArg << IsCalleeStreaming << SVL << VL;
3867 else
3868 // Emit error otherwise
3869 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
3870 << IsArg << SVL << VL;
3871 } else
3872 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
3873 << IsArg;
3874 };
3875
3876 if (IsScalableArg)
3877 EmitDiag(true);
3878 if (IsScalableRet)
3879 EmitDiag(false);
3880 }
3881 }
3882
3883 FunctionType::ArmStateValue CalleeArmZAState =
3885 FunctionType::ArmStateValue CalleeArmZT0State =
3887 if (CalleeArmZAState != FunctionType::ARM_None ||
3888 CalleeArmZT0State != FunctionType::ARM_None) {
3889 bool CallerHasZAState = false;
3890 bool CallerHasZT0State = false;
3891 if (CallerFD) {
3892 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
3893 if (Attr && Attr->isNewZA())
3894 CallerHasZAState = true;
3895 if (Attr && Attr->isNewZT0())
3896 CallerHasZT0State = true;
3897 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
3898 CallerHasZAState |=
3900 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
3902 CallerHasZT0State |=
3904 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
3906 }
3907 }
3908
3909 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
3910 Diag(Loc, diag::err_sme_za_call_no_za_state);
3911
3912 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
3913 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
3914
3915 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
3916 CalleeArmZT0State != FunctionType::ARM_None) {
3917 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
3918 Diag(Loc, diag::note_sme_use_preserves_za);
3919 }
3920 }
3921 }
3922
3923 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
3924 auto *AA = FDecl->getAttr<AllocAlignAttr>();
3925 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
3926 if (!Arg->isValueDependent()) {
3927 Expr::EvalResult Align;
3928 if (Arg->EvaluateAsInt(Align, Context)) {
3929 const llvm::APSInt &I = Align.Val.getInt();
3930 if (!I.isPowerOf2())
3931 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
3932 << Arg->getSourceRange();
3933
3934 if (I > Sema::MaximumAlignment)
3935 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
3936 << Arg->getSourceRange() << Sema::MaximumAlignment;
3937 }
3938 }
3939 }
3940
3941 if (FD)
3942 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
3943}
3944
3945void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
3946 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
3947 DiagnoseUseOfDecl(Decl, Loc);
3948 }
3949}
3950
3951void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
3953 const FunctionProtoType *Proto,
3954 SourceLocation Loc) {
3955 VariadicCallType CallType = Proto->isVariadic()
3958
3959 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
3960 CheckArgAlignment(
3961 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
3962 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
3963
3964 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3965 Loc, SourceRange(), CallType);
3966}
3967
3969 const FunctionProtoType *Proto) {
3970 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3971 isa<CXXMethodDecl>(FDecl);
3972 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3973 IsMemberOperatorCall;
3974 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3975 TheCall->getCallee());
3976 Expr** Args = TheCall->getArgs();
3977 unsigned NumArgs = TheCall->getNumArgs();
3978
3979 Expr *ImplicitThis = nullptr;
3980 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
3981 // If this is a call to a member operator, hide the first
3982 // argument from checkCall.
3983 // FIXME: Our choice of AST representation here is less than ideal.
3984 ImplicitThis = Args[0];
3985 ++Args;
3986 --NumArgs;
3987 } else if (IsMemberFunction && !FDecl->isStatic() &&
3989 ImplicitThis =
3990 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3991
3992 if (ImplicitThis) {
3993 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
3994 // used.
3995 QualType ThisType = ImplicitThis->getType();
3996 if (!ThisType->isPointerType()) {
3997 assert(!ThisType->isReferenceType());
3998 ThisType = Context.getPointerType(ThisType);
3999 }
4000
4001 QualType ThisTypeFromDecl = Context.getPointerType(
4002 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4003
4004 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4005 ThisTypeFromDecl);
4006 }
4007
4008 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4009 IsMemberFunction, TheCall->getRParenLoc(),
4010 TheCall->getCallee()->getSourceRange(), CallType);
4011
4012 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4013 // None of the checks below are needed for functions that don't have
4014 // simple names (e.g., C++ conversion functions).
4015 if (!FnInfo)
4016 return false;
4017
4018 // Enforce TCB except for builtin calls, which are always allowed.
4019 if (FDecl->getBuiltinID() == 0)
4020 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4021
4022 CheckAbsoluteValueFunction(TheCall, FDecl);
4023 CheckMaxUnsignedZero(TheCall, FDecl);
4024 CheckInfNaNFunction(TheCall, FDecl);
4025
4026 if (getLangOpts().ObjC)
4027 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4028
4029 unsigned CMId = FDecl->getMemoryFunctionKind();
4030
4031 // Handle memory setting and copying functions.
4032 switch (CMId) {
4033 case 0:
4034 return false;
4035 case Builtin::BIstrlcpy: // fallthrough
4036 case Builtin::BIstrlcat:
4037 CheckStrlcpycatArguments(TheCall, FnInfo);
4038 break;
4039 case Builtin::BIstrncat:
4040 CheckStrncatArguments(TheCall, FnInfo);
4041 break;
4042 case Builtin::BIfree:
4043 CheckFreeArguments(TheCall);
4044 break;
4045 default:
4046 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4047 }
4048
4049 return false;
4050}
4051
4052bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4053 const FunctionProtoType *Proto) {
4054 QualType Ty;
4055 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4056 Ty = V->getType().getNonReferenceType();
4057 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4058 Ty = F->getType().getNonReferenceType();
4059 else
4060 return false;
4061
4062 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4063 !Ty->isFunctionProtoType())
4064 return false;
4065
4066 VariadicCallType CallType;
4067 if (!Proto || !Proto->isVariadic()) {
4069 } else if (Ty->isBlockPointerType()) {
4070 CallType = VariadicCallType::Block;
4071 } else { // Ty->isFunctionPointerType()
4072 CallType = VariadicCallType::Function;
4073 }
4074
4075 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4076 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4077 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4078 TheCall->getCallee()->getSourceRange(), CallType);
4079
4080 return false;
4081}
4082
4083bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4084 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4085 TheCall->getCallee());
4086 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4087 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4088 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4089 TheCall->getCallee()->getSourceRange(), CallType);
4090
4091 return false;
4092}
4093
4094static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4095 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4096 return false;
4097
4098 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4099 switch (Op) {
4100 case AtomicExpr::AO__c11_atomic_init:
4101 case AtomicExpr::AO__opencl_atomic_init:
4102 llvm_unreachable("There is no ordering argument for an init");
4103
4104 case AtomicExpr::AO__c11_atomic_load:
4105 case AtomicExpr::AO__opencl_atomic_load:
4106 case AtomicExpr::AO__hip_atomic_load:
4107 case AtomicExpr::AO__atomic_load_n:
4108 case AtomicExpr::AO__atomic_load:
4109 case AtomicExpr::AO__scoped_atomic_load_n:
4110 case AtomicExpr::AO__scoped_atomic_load:
4111 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4112 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4113
4114 case AtomicExpr::AO__c11_atomic_store:
4115 case AtomicExpr::AO__opencl_atomic_store:
4116 case AtomicExpr::AO__hip_atomic_store:
4117 case AtomicExpr::AO__atomic_store:
4118 case AtomicExpr::AO__atomic_store_n:
4119 case AtomicExpr::AO__scoped_atomic_store:
4120 case AtomicExpr::AO__scoped_atomic_store_n:
4121 case AtomicExpr::AO__atomic_clear:
4122 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4123 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4124 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4125
4126 default:
4127 return true;
4128 }
4129}
4130
4131ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4133 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4134 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4135 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4136 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4137 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4138 Op);
4139}
4140
4142 SourceLocation RParenLoc, MultiExprArg Args,
4144 AtomicArgumentOrder ArgOrder) {
4145 // All the non-OpenCL operations take one of the following forms.
4146 // The OpenCL operations take the __c11 forms with one extra argument for
4147 // synchronization scope.
4148 enum {
4149 // C __c11_atomic_init(A *, C)
4150 Init,
4151
4152 // C __c11_atomic_load(A *, int)
4153 Load,
4154
4155 // void __atomic_load(A *, CP, int)
4156 LoadCopy,
4157
4158 // void __atomic_store(A *, CP, int)
4159 Copy,
4160
4161 // C __c11_atomic_add(A *, M, int)
4162 Arithmetic,
4163
4164 // C __atomic_exchange_n(A *, CP, int)
4165 Xchg,
4166
4167 // void __atomic_exchange(A *, C *, CP, int)
4168 GNUXchg,
4169
4170 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4171 C11CmpXchg,
4172
4173 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4174 GNUCmpXchg,
4175
4176 // bool __atomic_test_and_set(A *, int)
4177 TestAndSetByte,
4178
4179 // void __atomic_clear(A *, int)
4180 ClearByte,
4181 } Form = Init;
4182
4183 const unsigned NumForm = ClearByte + 1;
4184 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4185 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4186 // where:
4187 // C is an appropriate type,
4188 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4189 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4190 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4191 // the int parameters are for orderings.
4192
4193 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4194 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4195 "need to update code for modified forms");
4196 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4197 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4198 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4199 "need to update code for modified C11 atomics");
4200 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4201 Op <= AtomicExpr::AO__opencl_atomic_store;
4202 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4203 Op <= AtomicExpr::AO__hip_atomic_store;
4204 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4205 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4206 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4207 Op <= AtomicExpr::AO__c11_atomic_store) ||
4208 IsOpenCL;
4209 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4210 Op == AtomicExpr::AO__atomic_store_n ||
4211 Op == AtomicExpr::AO__atomic_exchange_n ||
4212 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4213 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4214 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4215 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4216 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4217 // Bit mask for extra allowed value types other than integers for atomic
4218 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4219 // allow floating point.
4220 enum ArithOpExtraValueType {
4221 AOEVT_None = 0,
4222 AOEVT_Pointer = 1,
4223 AOEVT_FP = 2,
4224 };
4225 unsigned ArithAllows = AOEVT_None;
4226
4227 switch (Op) {
4228 case AtomicExpr::AO__c11_atomic_init:
4229 case AtomicExpr::AO__opencl_atomic_init:
4230 Form = Init;
4231 break;
4232
4233 case AtomicExpr::AO__c11_atomic_load:
4234 case AtomicExpr::AO__opencl_atomic_load:
4235 case AtomicExpr::AO__hip_atomic_load:
4236 case AtomicExpr::AO__atomic_load_n:
4237 case AtomicExpr::AO__scoped_atomic_load_n:
4238 Form = Load;
4239 break;
4240
4241 case AtomicExpr::AO__atomic_load:
4242 case AtomicExpr::AO__scoped_atomic_load:
4243 Form = LoadCopy;
4244 break;
4245
4246 case AtomicExpr::AO__c11_atomic_store:
4247 case AtomicExpr::AO__opencl_atomic_store:
4248 case AtomicExpr::AO__hip_atomic_store:
4249 case AtomicExpr::AO__atomic_store:
4250 case AtomicExpr::AO__atomic_store_n:
4251 case AtomicExpr::AO__scoped_atomic_store:
4252 case AtomicExpr::AO__scoped_atomic_store_n:
4253 Form = Copy;
4254 break;
4255 case AtomicExpr::AO__atomic_fetch_add:
4256 case AtomicExpr::AO__atomic_fetch_sub:
4257 case AtomicExpr::AO__atomic_add_fetch:
4258 case AtomicExpr::AO__atomic_sub_fetch:
4259 case AtomicExpr::AO__scoped_atomic_fetch_add:
4260 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4261 case AtomicExpr::AO__scoped_atomic_add_fetch:
4262 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4263 case AtomicExpr::AO__c11_atomic_fetch_add:
4264 case AtomicExpr::AO__c11_atomic_fetch_sub:
4265 case AtomicExpr::AO__opencl_atomic_fetch_add:
4266 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4267 case AtomicExpr::AO__hip_atomic_fetch_add:
4268 case AtomicExpr::AO__hip_atomic_fetch_sub:
4269 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4270 Form = Arithmetic;
4271 break;
4272 case AtomicExpr::AO__atomic_fetch_max:
4273 case AtomicExpr::AO__atomic_fetch_min:
4274 case AtomicExpr::AO__atomic_max_fetch:
4275 case AtomicExpr::AO__atomic_min_fetch:
4276 case AtomicExpr::AO__scoped_atomic_fetch_max:
4277 case AtomicExpr::AO__scoped_atomic_fetch_min:
4278 case AtomicExpr::AO__scoped_atomic_max_fetch:
4279 case AtomicExpr::AO__scoped_atomic_min_fetch:
4280 case AtomicExpr::AO__c11_atomic_fetch_max:
4281 case AtomicExpr::AO__c11_atomic_fetch_min:
4282 case AtomicExpr::AO__opencl_atomic_fetch_max:
4283 case AtomicExpr::AO__opencl_atomic_fetch_min:
4284 case AtomicExpr::AO__hip_atomic_fetch_max:
4285 case AtomicExpr::AO__hip_atomic_fetch_min:
4286 ArithAllows = AOEVT_FP;
4287 Form = Arithmetic;
4288 break;
4289 case AtomicExpr::AO__c11_atomic_fetch_and:
4290 case AtomicExpr::AO__c11_atomic_fetch_or:
4291 case AtomicExpr::AO__c11_atomic_fetch_xor:
4292 case AtomicExpr::AO__hip_atomic_fetch_and:
4293 case AtomicExpr::AO__hip_atomic_fetch_or:
4294 case AtomicExpr::AO__hip_atomic_fetch_xor:
4295 case AtomicExpr::AO__c11_atomic_fetch_nand:
4296 case AtomicExpr::AO__opencl_atomic_fetch_and:
4297 case AtomicExpr::AO__opencl_atomic_fetch_or:
4298 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4299 case AtomicExpr::AO__atomic_fetch_and:
4300 case AtomicExpr::AO__atomic_fetch_or:
4301 case AtomicExpr::AO__atomic_fetch_xor:
4302 case AtomicExpr::AO__atomic_fetch_nand:
4303 case AtomicExpr::AO__atomic_and_fetch:
4304 case AtomicExpr::AO__atomic_or_fetch:
4305 case AtomicExpr::AO__atomic_xor_fetch:
4306 case AtomicExpr::AO__atomic_nand_fetch:
4307 case AtomicExpr::AO__scoped_atomic_fetch_and:
4308 case AtomicExpr::AO__scoped_atomic_fetch_or:
4309 case AtomicExpr::AO__scoped_atomic_fetch_xor:
4310 case AtomicExpr::AO__scoped_atomic_fetch_nand:
4311 case AtomicExpr::AO__scoped_atomic_and_fetch:
4312 case AtomicExpr::AO__scoped_atomic_or_fetch:
4313 case AtomicExpr::AO__scoped_atomic_xor_fetch:
4314 case AtomicExpr::AO__scoped_atomic_nand_fetch:
4315 Form = Arithmetic;
4316 break;
4317
4318 case AtomicExpr::AO__c11_atomic_exchange:
4319 case AtomicExpr::AO__hip_atomic_exchange:
4320 case AtomicExpr::AO__opencl_atomic_exchange:
4321 case AtomicExpr::AO__atomic_exchange_n:
4322 case AtomicExpr::AO__scoped_atomic_exchange_n:
4323 Form = Xchg;
4324 break;
4325
4326 case AtomicExpr::AO__atomic_exchange:
4327 case AtomicExpr::AO__scoped_atomic_exchange:
4328 Form = GNUXchg;
4329 break;
4330
4331 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4332 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4333 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4334 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4335 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4336 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4337 Form = C11CmpXchg;
4338 break;
4339
4340 case AtomicExpr::AO__atomic_compare_exchange:
4341 case AtomicExpr::AO__atomic_compare_exchange_n:
4342 case AtomicExpr::AO__scoped_atomic_compare_exchange:
4343 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
4344 Form = GNUCmpXchg;
4345 break;
4346
4347 case AtomicExpr::AO__atomic_test_and_set:
4348 Form = TestAndSetByte;
4349 break;
4350
4351 case AtomicExpr::AO__atomic_clear:
4352 Form = ClearByte;
4353 break;
4354 }
4355
4356 unsigned AdjustedNumArgs = NumArgs[Form];
4357 if ((IsOpenCL || IsHIP || IsScoped) &&
4358 Op != AtomicExpr::AO__opencl_atomic_init)
4359 ++AdjustedNumArgs;
4360 // Check we have the right number of arguments.
4361 if (Args.size() < AdjustedNumArgs) {
4362 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4363 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4364 << /*is non object*/ 0 << ExprRange;
4365 return ExprError();
4366 } else if (Args.size() > AdjustedNumArgs) {
4367 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4368 diag::err_typecheck_call_too_many_args)
4369 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4370 << /*is non object*/ 0 << ExprRange;
4371 return ExprError();
4372 }
4373
4374 // Inspect the first argument of the atomic operation.
4375 Expr *Ptr = Args[0];
4377 if (ConvertedPtr.isInvalid())
4378 return ExprError();
4379
4380 Ptr = ConvertedPtr.get();
4381 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4382 if (!pointerType) {
4383 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4384 << Ptr->getType() << 0 << Ptr->getSourceRange();
4385 return ExprError();
4386 }
4387
4388 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4389 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4390 QualType ValType = AtomTy; // 'C'
4391 if (IsC11) {
4392 if (!AtomTy->isAtomicType()) {
4393 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4394 << Ptr->getType() << Ptr->getSourceRange();
4395 return ExprError();
4396 }
4397 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4399 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4400 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4401 << Ptr->getSourceRange();
4402 return ExprError();
4403 }
4404 ValType = AtomTy->castAs<AtomicType>()->getValueType();
4405 } else if (Form != Load && Form != LoadCopy) {
4406 if (ValType.isConstQualified()) {
4407 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4408 << Ptr->getType() << Ptr->getSourceRange();
4409 return ExprError();
4410 }
4411 }
4412
4413 if (Form != TestAndSetByte && Form != ClearByte) {
4414 // Pointer to object of size zero is not allowed.
4415 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
4416 diag::err_incomplete_type))
4417 return ExprError();
4418
4419 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
4420 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4421 << Ptr->getType() << 1 << Ptr->getSourceRange();
4422 return ExprError();
4423 }
4424 } else {
4425 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
4426 // non-const pointer type, including void* and pointers to incomplete
4427 // structs, but only access the first byte.
4428 AtomTy = Context.CharTy;
4429 AtomTy = AtomTy.withCVRQualifiers(
4430 pointerType->getPointeeType().getCVRQualifiers());
4431 QualType PointerQT = Context.getPointerType(AtomTy);
4432 pointerType = PointerQT->getAs<PointerType>();
4433 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
4434 ValType = AtomTy;
4435 }
4436
4437 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
4438 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4439 Diag(ExprRange.getBegin(),
4440 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4441 << 0 << Ptr->getType() << Ptr->getSourceRange();
4442 return ExprError();
4443 }
4444
4445 // For an arithmetic operation, the implied arithmetic must be well-formed.
4446 if (Form == Arithmetic) {
4447 // GCC does not enforce these rules for GNU atomics, but we do to help catch
4448 // trivial type errors.
4449 auto IsAllowedValueType = [&](QualType ValType,
4450 unsigned AllowedType) -> bool {
4451 if (ValType->isIntegerType())
4452 return true;
4453 if (ValType->isPointerType())
4454 return AllowedType & AOEVT_Pointer;
4455 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
4456 return false;
4457 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
4458 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
4459 &Context.getTargetInfo().getLongDoubleFormat() ==
4460 &llvm::APFloat::x87DoubleExtended())
4461 return false;
4462 return true;
4463 };
4464 if (!IsAllowedValueType(ValType, ArithAllows)) {
4465 auto DID = ArithAllows & AOEVT_FP
4466 ? (ArithAllows & AOEVT_Pointer
4467 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
4468 : diag::err_atomic_op_needs_atomic_int_or_fp)
4469 : diag::err_atomic_op_needs_atomic_int;
4470 Diag(ExprRange.getBegin(), DID)
4471 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4472 return ExprError();
4473 }
4474 if (IsC11 && ValType->isPointerType() &&
4476 diag::err_incomplete_type)) {
4477 return ExprError();
4478 }
4479 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4480 // For __atomic_*_n operations, the value type must be a scalar integral or
4481 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4482 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4483 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4484 return ExprError();
4485 }
4486
4487 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4488 !AtomTy->isScalarType()) {
4489 // For GNU atomics, require a trivially-copyable type. This is not part of
4490 // the GNU atomics specification but we enforce it for consistency with
4491 // other atomics which generally all require a trivially-copyable type. This
4492 // is because atomics just copy bits.
4493 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4494 << Ptr->getType() << Ptr->getSourceRange();
4495 return ExprError();
4496 }
4497
4498 switch (ValType.getObjCLifetime()) {
4501 // okay
4502 break;
4503
4507 // FIXME: Can this happen? By this point, ValType should be known
4508 // to be trivially copyable.
4509 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4510 << ValType << Ptr->getSourceRange();
4511 return ExprError();
4512 }
4513
4514 // All atomic operations have an overload which takes a pointer to a volatile
4515 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4516 // into the result or the other operands. Similarly atomic_load takes a
4517 // pointer to a const 'A'.
4518 ValType.removeLocalVolatile();
4519 ValType.removeLocalConst();
4520 QualType ResultType = ValType;
4521 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
4522 Form == ClearByte)
4523 ResultType = Context.VoidTy;
4524 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
4525 ResultType = Context.BoolTy;
4526
4527 // The type of a parameter passed 'by value'. In the GNU atomics, such
4528 // arguments are actually passed as pointers.
4529 QualType ByValType = ValType; // 'CP'
4530 bool IsPassedByAddress = false;
4531 if (!IsC11 && !IsHIP && !IsN) {
4532 ByValType = Ptr->getType();
4533 IsPassedByAddress = true;
4534 }
4535
4536 SmallVector<Expr *, 5> APIOrderedArgs;
4537 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4538 APIOrderedArgs.push_back(Args[0]);
4539 switch (Form) {
4540 case Init:
4541 case Load:
4542 APIOrderedArgs.push_back(Args[1]); // Val1/Order
4543 break;
4544 case LoadCopy:
4545 case Copy:
4546 case Arithmetic:
4547 case Xchg:
4548 APIOrderedArgs.push_back(Args[2]); // Val1
4549 APIOrderedArgs.push_back(Args[1]); // Order
4550 break;
4551 case GNUXchg:
4552 APIOrderedArgs.push_back(Args[2]); // Val1
4553 APIOrderedArgs.push_back(Args[3]); // Val2
4554 APIOrderedArgs.push_back(Args[1]); // Order
4555 break;
4556 case C11CmpXchg:
4557 APIOrderedArgs.push_back(Args[2]); // Val1
4558 APIOrderedArgs.push_back(Args[4]); // Val2
4559 APIOrderedArgs.push_back(Args[1]); // Order
4560 APIOrderedArgs.push_back(Args[3]); // OrderFail
4561 break;
4562 case GNUCmpXchg:
4563 APIOrderedArgs.push_back(Args[2]); // Val1
4564 APIOrderedArgs.push_back(Args[4]); // Val2
4565 APIOrderedArgs.push_back(Args[5]); // Weak
4566 APIOrderedArgs.push_back(Args[1]); // Order
4567 APIOrderedArgs.push_back(Args[3]); // OrderFail
4568 break;
4569 case TestAndSetByte:
4570 case ClearByte:
4571 APIOrderedArgs.push_back(Args[1]); // Order
4572 break;
4573 }
4574 } else
4575 APIOrderedArgs.append(Args.begin(), Args.end());
4576
4577 // The first argument's non-CV pointer type is used to deduce the type of
4578 // subsequent arguments, except for:
4579 // - weak flag (always converted to bool)
4580 // - memory order (always converted to int)
4581 // - scope (always converted to int)
4582 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4583 QualType Ty;
4584 if (i < NumVals[Form] + 1) {
4585 switch (i) {
4586 case 0:
4587 // The first argument is always a pointer. It has a fixed type.
4588 // It is always dereferenced, a nullptr is undefined.
4589 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4590 // Nothing else to do: we already know all we want about this pointer.
4591 continue;
4592 case 1:
4593 // The second argument is the non-atomic operand. For arithmetic, this
4594 // is always passed by value, and for a compare_exchange it is always
4595 // passed by address. For the rest, GNU uses by-address and C11 uses
4596 // by-value.
4597 assert(Form != Load);
4598 if (Form == Arithmetic && ValType->isPointerType())
4599 Ty = Context.getPointerDiffType();
4600 else if (Form == Init || Form == Arithmetic)
4601 Ty = ValType;
4602 else if (Form == Copy || Form == Xchg) {
4603 if (IsPassedByAddress) {
4604 // The value pointer is always dereferenced, a nullptr is undefined.
4605 CheckNonNullArgument(*this, APIOrderedArgs[i],
4606 ExprRange.getBegin());
4607 }
4608 Ty = ByValType;
4609 } else {
4610 Expr *ValArg = APIOrderedArgs[i];
4611 // The value pointer is always dereferenced, a nullptr is undefined.
4612 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4614 // Keep address space of non-atomic pointer type.
4615 if (const PointerType *PtrTy =
4616 ValArg->getType()->getAs<PointerType>()) {
4617 AS = PtrTy->getPointeeType().getAddressSpace();
4618 }
4619 Ty = Context.getPointerType(
4620 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4621 }
4622 break;
4623 case 2:
4624 // The third argument to compare_exchange / GNU exchange is the desired
4625 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4626 if (IsPassedByAddress)
4627 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4628 Ty = ByValType;
4629 break;
4630 case 3:
4631 // The fourth argument to GNU compare_exchange is a 'weak' flag.
4632 Ty = Context.BoolTy;
4633 break;
4634 }
4635 } else {
4636 // The order(s) and scope are always converted to int.
4637 Ty = Context.IntTy;
4638 }
4639
4640 InitializedEntity Entity =
4642 ExprResult Arg = APIOrderedArgs[i];
4643 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4644 if (Arg.isInvalid())
4645 return true;
4646 APIOrderedArgs[i] = Arg.get();
4647 }
4648
4649 // Permute the arguments into a 'consistent' order.
4650 SmallVector<Expr*, 5> SubExprs;
4651 SubExprs.push_back(Ptr);
4652 switch (Form) {
4653 case Init:
4654 // Note, AtomicExpr::getVal1() has a special case for this atomic.
4655 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4656 break;
4657 case Load:
4658 case TestAndSetByte:
4659 case ClearByte:
4660 SubExprs.push_back(APIOrderedArgs[1]); // Order
4661 break;
4662 case LoadCopy:
4663 case Copy:
4664 case Arithmetic:
4665 case Xchg:
4666 SubExprs.push_back(APIOrderedArgs[2]); // Order
4667 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4668 break;
4669 case GNUXchg:
4670 // Note, AtomicExpr::getVal2() has a special case for this atomic.
4671 SubExprs.push_back(APIOrderedArgs[3]); // Order
4672 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4673 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4674 break;
4675 case C11CmpXchg:
4676 SubExprs.push_back(APIOrderedArgs[3]); // Order
4677 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4678 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4679 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4680 break;
4681 case GNUCmpXchg:
4682 SubExprs.push_back(APIOrderedArgs[4]); // Order
4683 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4684 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4685 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4686 SubExprs.push_back(APIOrderedArgs[3]); // Weak
4687 break;
4688 }
4689
4690 // If the memory orders are constants, check they are valid.
4691 if (SubExprs.size() >= 2 && Form != Init) {
4692 std::optional<llvm::APSInt> Success =
4693 SubExprs[1]->getIntegerConstantExpr(Context);
4694 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
4695 Diag(SubExprs[1]->getBeginLoc(),
4696 diag::warn_atomic_op_has_invalid_memory_order)
4697 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
4698 << SubExprs[1]->getSourceRange();
4699 }
4700 if (SubExprs.size() >= 5) {
4701 if (std::optional<llvm::APSInt> Failure =
4702 SubExprs[3]->getIntegerConstantExpr(Context)) {
4703 if (!llvm::is_contained(
4704 {llvm::AtomicOrderingCABI::relaxed,
4705 llvm::AtomicOrderingCABI::consume,
4706 llvm::AtomicOrderingCABI::acquire,
4707 llvm::AtomicOrderingCABI::seq_cst},
4708 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
4709 Diag(SubExprs[3]->getBeginLoc(),
4710 diag::warn_atomic_op_has_invalid_memory_order)
4711 << /*failure=*/2 << SubExprs[3]->getSourceRange();
4712 }
4713 }
4714 }
4715 }
4716
4717 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4718 auto *Scope = Args[Args.size() - 1];
4719 if (std::optional<llvm::APSInt> Result =
4720 Scope->getIntegerConstantExpr(Context)) {
4721 if (!ScopeModel->isValid(Result->getZExtValue()))
4722 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
4723 << Scope->getSourceRange();
4724 }
4725 SubExprs.push_back(Scope);
4726 }
4727
4728 AtomicExpr *AE = new (Context)
4729 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4730
4731 if ((Op == AtomicExpr::AO__c11_atomic_load ||
4732 Op == AtomicExpr::AO__c11_atomic_store ||
4733 Op == AtomicExpr::AO__opencl_atomic_load ||
4734 Op == AtomicExpr::AO__hip_atomic_load ||
4735 Op == AtomicExpr::AO__opencl_atomic_store ||
4736 Op == AtomicExpr::AO__hip_atomic_store) &&
4737 Context.AtomicUsesUnsupportedLibcall(AE))
4738 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4739 << ((Op == AtomicExpr::AO__c11_atomic_load ||
4740 Op == AtomicExpr::AO__opencl_atomic_load ||
4741 Op == AtomicExpr::AO__hip_atomic_load)
4742 ? 0
4743 : 1);
4744
4745 if (ValType->isBitIntType()) {
4746 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
4747 return ExprError();
4748 }
4749
4750 return AE;
4751}
4752
4753/// checkBuiltinArgument - Given a call to a builtin function, perform
4754/// normal type-checking on the given argument, updating the call in
4755/// place. This is useful when a builtin function requires custom
4756/// type-checking for some of its arguments but not necessarily all of
4757/// them.
4758///
4759/// Returns true on error.
4760static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4761 FunctionDecl *Fn = E->getDirectCallee();
4762 assert(Fn && "builtin call without direct callee!");
4763
4764 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4765 InitializedEntity Entity =
4767
4768 ExprResult Arg = E->getArg(ArgIndex);
4769 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4770 if (Arg.isInvalid())
4771 return true;
4772
4773 E->setArg(ArgIndex, Arg.get());
4774 return false;
4775}
4776
4777ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
4778 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4779 Expr *Callee = TheCall->getCallee();
4780 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4781 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4782
4783 // Ensure that we have at least one argument to do type inference from.
4784 if (TheCall->getNumArgs() < 1) {
4785 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4786 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
4787 << Callee->getSourceRange();
4788 return ExprError();
4789 }
4790
4791 // Inspect the first argument of the atomic builtin. This should always be
4792 // a pointer type, whose element is an integral scalar or pointer type.
4793 // Because it is a pointer type, we don't have to worry about any implicit
4794 // casts here.
4795 // FIXME: We don't allow floating point scalars as input.
4796 Expr *FirstArg = TheCall->getArg(0);
4797 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4798 if (FirstArgResult.isInvalid())
4799 return ExprError();
4800 FirstArg = FirstArgResult.get();
4801 TheCall->setArg(0, FirstArg);
4802
4803 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4804 if (!pointerType) {
4805 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4806 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4807 return ExprError();
4808 }
4809
4810 QualType ValType = pointerType->getPointeeType();
4811 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4812 !ValType->isBlockPointerType()) {
4813 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4814 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4815 return ExprError();
4816 }
4817 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
4818 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4819 Diag(FirstArg->getBeginLoc(),
4820 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4821 << 1 << ValType << FirstArg->getSourceRange();
4822 return ExprError();
4823 }
4824
4825 if (ValType.isConstQualified()) {
4826 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4827 << FirstArg->getType() << FirstArg->getSourceRange();
4828 return ExprError();
4829 }
4830
4831 switch (ValType.getObjCLifetime()) {
4834 // okay
4835 break;
4836
4840 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4841 << ValType << FirstArg->getSourceRange();
4842 return ExprError();
4843 }
4844
4845 // Strip any qualifiers off ValType.
4846 ValType = ValType.getUnqualifiedType();
4847
4848 // The majority of builtins return a value, but a few have special return
4849 // types, so allow them to override appropriately below.
4850 QualType ResultType = ValType;
4851
4852 // We need to figure out which concrete builtin this maps onto. For example,
4853 // __sync_fetch_and_add with a 2 byte object turns into
4854 // __sync_fetch_and_add_2.
4855#define BUILTIN_ROW(x) \
4856 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4857 Builtin::BI##x##_8, Builtin::BI##x##_16 }
4858
4859 static const unsigned BuiltinIndices[][5] = {
4860 BUILTIN_ROW(__sync_fetch_and_add),
4861 BUILTIN_ROW(__sync_fetch_and_sub),
4862 BUILTIN_ROW(__sync_fetch_and_or),
4863 BUILTIN_ROW(__sync_fetch_and_and),
4864 BUILTIN_ROW(__sync_fetch_and_xor),
4865 BUILTIN_ROW(__sync_fetch_and_nand),
4866
4867 BUILTIN_ROW(__sync_add_and_fetch),
4868 BUILTIN_ROW(__sync_sub_and_fetch),
4869 BUILTIN_ROW(__sync_and_and_fetch),
4870 BUILTIN_ROW(__sync_or_and_fetch),
4871 BUILTIN_ROW(__sync_xor_and_fetch),
4872 BUILTIN_ROW(__sync_nand_and_fetch),
4873
4874 BUILTIN_ROW(__sync_val_compare_and_swap),
4875 BUILTIN_ROW(__sync_bool_compare_and_swap),
4876 BUILTIN_ROW(__sync_lock_test_and_set),
4877 BUILTIN_ROW(__sync_lock_release),
4878 BUILTIN_ROW(__sync_swap)
4879 };
4880#undef BUILTIN_ROW
4881
4882 // Determine the index of the size.
4883 unsigned SizeIndex;
4884 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4885 case 1: SizeIndex = 0; break;
4886 case 2: SizeIndex = 1; break;
4887 case 4: SizeIndex = 2; break;
4888 case 8: SizeIndex = 3; break;
4889 case 16: SizeIndex = 4; break;
4890 default:
4891 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4892 << FirstArg->getType() << FirstArg->getSourceRange();
4893 return ExprError();
4894 }
4895
4896 // Each of these builtins has one pointer argument, followed by some number of
4897 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4898 // that we ignore. Find out which row of BuiltinIndices to read from as well
4899 // as the number of fixed args.
4900 unsigned BuiltinID = FDecl->getBuiltinID();
4901 unsigned BuiltinIndex, NumFixed = 1;
4902 bool WarnAboutSemanticsChange = false;
4903 switch (BuiltinID) {
4904 default: llvm_unreachable("Unknown overloaded atomic builtin!");
4905 case Builtin::BI__sync_fetch_and_add:
4906 case Builtin::BI__sync_fetch_and_add_1:
4907 case Builtin::BI__sync_fetch_and_add_2:
4908 case Builtin::BI__sync_fetch_and_add_4:
4909 case Builtin::BI__sync_fetch_and_add_8:
4910 case Builtin::BI__sync_fetch_and_add_16:
4911 BuiltinIndex = 0;
4912 break;
4913
4914 case Builtin::BI__sync_fetch_and_sub:
4915 case Builtin::BI__sync_fetch_and_sub_1:
4916 case Builtin::BI__sync_fetch_and_sub_2:
4917 case Builtin::BI__sync_fetch_and_sub_4:
4918 case Builtin::BI__sync_fetch_and_sub_8:
4919 case Builtin::BI__sync_fetch_and_sub_16:
4920 BuiltinIndex = 1;
4921 break;
4922
4923 case Builtin::BI__sync_fetch_and_or:
4924 case Builtin::BI__sync_fetch_and_or_1:
4925 case Builtin::BI__sync_fetch_and_or_2:
4926 case Builtin::BI__sync_fetch_and_or_4:
4927 case Builtin::BI__sync_fetch_and_or_8:
4928 case Builtin::BI__sync_fetch_and_or_16:
4929 BuiltinIndex = 2;
4930 break;
4931
4932 case Builtin::BI__sync_fetch_and_and:
4933 case Builtin::BI__sync_fetch_and_and_1:
4934 case Builtin::BI__sync_fetch_and_and_2:
4935 case Builtin::BI__sync_fetch_and_and_4:
4936 case Builtin::BI__sync_fetch_and_and_8:
4937 case Builtin::BI__sync_fetch_and_and_16:
4938 BuiltinIndex = 3;
4939 break;
4940
4941 case Builtin::BI__sync_fetch_and_xor:
4942 case Builtin::BI__sync_fetch_and_xor_1:
4943 case Builtin::BI__sync_fetch_and_xor_2:
4944 case Builtin::BI__sync_fetch_and_xor_4:
4945 case Builtin::BI__sync_fetch_and_xor_8:
4946 case Builtin::BI__sync_fetch_and_xor_16:
4947 BuiltinIndex = 4;
4948 break;
4949
4950 case Builtin::BI__sync_fetch_and_nand:
4951 case Builtin::BI__sync_fetch_and_nand_1:
4952 case Builtin::BI__sync_fetch_and_nand_2:
4953 case Builtin::BI__sync_fetch_and_nand_4:
4954 case Builtin::BI__sync_fetch_and_nand_8:
4955 case Builtin::BI__sync_fetch_and_nand_16:
4956 BuiltinIndex = 5;
4957 WarnAboutSemanticsChange = true;
4958 break;
4959
4960 case Builtin::BI__sync_add_and_fetch:
4961 case Builtin::BI__sync_add_and_fetch_1:
4962 case Builtin::BI__sync_add_and_fetch_2:
4963 case Builtin::BI__sync_add_and_fetch_4:
4964 case Builtin::BI__sync_add_and_fetch_8:
4965 case Builtin::BI__sync_add_and_fetch_16:
4966 BuiltinIndex = 6;
4967 break;
4968
4969 case Builtin::BI__sync_sub_and_fetch:
4970 case Builtin::BI__sync_sub_and_fetch_1:
4971 case Builtin::BI__sync_sub_and_fetch_2:
4972 case Builtin::BI__sync_sub_and_fetch_4:
4973 case Builtin::BI__sync_sub_and_fetch_8:
4974 case Builtin::BI__sync_sub_and_fetch_16:
4975 BuiltinIndex = 7;
4976 break;
4977
4978 case Builtin::BI__sync_and_and_fetch:
4979 case Builtin::BI__sync_and_and_fetch_1:
4980 case Builtin::BI__sync_and_and_fetch_2:
4981 case Builtin::BI__sync_and_and_fetch_4:
4982 case Builtin::BI__sync_and_and_fetch_8:
4983 case Builtin::BI__sync_and_and_fetch_16:
4984 BuiltinIndex = 8;
4985 break;
4986
4987 case Builtin::BI__sync_or_and_fetch:
4988 case Builtin::BI__sync_or_and_fetch_1:
4989 case Builtin::BI__sync_or_and_fetch_2:
4990 case Builtin::BI__sync_or_and_fetch_4:
4991 case Builtin::BI__sync_or_and_fetch_8:
4992 case Builtin::BI__sync_or_and_fetch_16:
4993 BuiltinIndex = 9;
4994 break;
4995
4996 case Builtin::BI__sync_xor_and_fetch:
4997 case Builtin::BI__sync_xor_and_fetch_1:
4998 case Builtin::BI__sync_xor_and_fetch_2:
4999 case Builtin::BI__sync_xor_and_fetch_4:
5000 case Builtin::BI__sync_xor_and_fetch_8:
5001 case Builtin::BI__sync_xor_and_fetch_16:
5002 BuiltinIndex = 10;
5003 break;
5004
5005 case Builtin::BI__sync_nand_and_fetch:
5006 case Builtin::BI__sync_nand_and_fetch_1:
5007 case Builtin::BI__sync_nand_and_fetch_2:
5008 case Builtin::BI__sync_nand_and_fetch_4:
5009 case Builtin::BI__sync_nand_and_fetch_8:
5010 case Builtin::BI__sync_nand_and_fetch_16:
5011 BuiltinIndex = 11;
5012 WarnAboutSemanticsChange = true;
5013 break;
5014
5015 case Builtin::BI__sync_val_compare_and_swap:
5016 case Builtin::BI__sync_val_compare_and_swap_1:
5017 case Builtin::BI__sync_val_compare_and_swap_2:
5018 case Builtin::BI__sync_val_compare_and_swap_4:
5019 case Builtin::BI__sync_val_compare_and_swap_8:
5020 case Builtin::BI__sync_val_compare_and_swap_16:
5021 BuiltinIndex = 12;
5022 NumFixed = 2;
5023 break;
5024
5025 case Builtin::BI__sync_bool_compare_and_swap:
5026 case Builtin::BI__sync_bool_compare_and_swap_1:
5027 case Builtin::BI__sync_bool_compare_and_swap_2:
5028 case Builtin::BI__sync_bool_compare_and_swap_4:
5029 case Builtin::BI__sync_bool_compare_and_swap_8:
5030 case Builtin::BI__sync_bool_compare_and_swap_16:
5031 BuiltinIndex = 13;
5032 NumFixed = 2;
5033 ResultType = Context.BoolTy;
5034 break;
5035
5036 case Builtin::BI__sync_lock_test_and_set:
5037 case Builtin::BI__sync_lock_test_and_set_1:
5038 case Builtin::BI__sync_lock_test_and_set_2:
5039 case Builtin::BI__sync_lock_test_and_set_4:
5040 case Builtin::BI__sync_lock_test_and_set_8:
5041 case Builtin::BI__sync_lock_test_and_set_16:
5042 BuiltinIndex = 14;
5043 break;
5044
5045 case Builtin::BI__sync_lock_release:
5046 case Builtin::BI__sync_lock_release_1:
5047 case Builtin::BI__sync_lock_release_2:
5048 case Builtin::BI__sync_lock_release_4:
5049 case Builtin::BI__sync_lock_release_8:
5050 case Builtin::BI__sync_lock_release_16:
5051 BuiltinIndex = 15;
5052 NumFixed = 0;
5053 ResultType = Context.VoidTy;
5054 break;
5055
5056 case Builtin::BI__sync_swap:
5057 case Builtin::BI__sync_swap_1:
5058 case Builtin::BI__sync_swap_2:
5059 case Builtin::BI__sync_swap_4:
5060 case Builtin::BI__sync_swap_8:
5061 case Builtin::BI__sync_swap_16:
5062 BuiltinIndex = 16;
5063 break;
5064 }
5065
5066 // Now that we know how many fixed arguments we expect, first check that we
5067 // have at least that many.
5068 if (TheCall->getNumArgs() < 1+NumFixed) {
5069 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5070 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5071 << Callee->getSourceRange();
5072 return ExprError();
5073 }
5074
5075 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5076 << Callee->getSourceRange();
5077
5078 if (WarnAboutSemanticsChange) {
5079 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5080 << Callee->getSourceRange();
5081 }
5082
5083 // Get the decl for the concrete builtin from this, we can tell what the
5084 // concrete integer type we should convert to is.
5085 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5086 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5087 FunctionDecl *NewBuiltinDecl;
5088 if (NewBuiltinID == BuiltinID)
5089 NewBuiltinDecl = FDecl;
5090 else {
5091 // Perform builtin lookup to avoid redeclaring it.
5092 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5093 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5094 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5095 assert(Res.getFoundDecl());
5096 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5097 if (!NewBuiltinDecl)
5098 return ExprError();
5099 }
5100
5101 // The first argument --- the pointer --- has a fixed type; we
5102 // deduce the types of the rest of the arguments accordingly. Walk
5103 // the remaining arguments, converting them to the deduced value type.
5104 for (unsigned i = 0; i != NumFixed; ++i) {
5105 ExprResult Arg = TheCall->getArg(i+1);
5106
5107 // GCC does an implicit conversion to the pointer or integer ValType. This
5108 // can fail in some cases (1i -> int**), check for this error case now.
5109 // Initialize the argument.
5110 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5111 ValType, /*consume*/ false);
5112 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5113 if (Arg.isInvalid())
5114 return ExprError();
5115
5116 // Okay, we have something that *can* be converted to the right type. Check
5117 // to see if there is a potentially weird extension going on here. This can
5118 // happen when you do an atomic operation on something like an char* and
5119 // pass in 42. The 42 gets converted to char. This is even more strange
5120 // for things like 45.123 -> char, etc.
5121 // FIXME: Do this check.
5122 TheCall->setArg(i+1, Arg.get());
5123 }
5124
5125 // Create a new DeclRefExpr to refer to the new decl.
5126 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5127 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5128 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5129 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5130
5131 // Set the callee in the CallExpr.
5132 // FIXME: This loses syntactic information.
5133 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5134 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5135 CK_BuiltinFnToFnPtr);
5136 TheCall->setCallee(PromotedCall.get());
5137
5138 // Change the result type of the call to match the original value type. This
5139 // is arbitrary, but the codegen for these builtins ins design to handle it
5140 // gracefully.
5141 TheCall->setType(ResultType);
5142
5143 // Prohibit problematic uses of bit-precise integer types with atomic
5144 // builtins. The arguments would have already been converted to the first
5145 // argument's type, so only need to check the first argument.
5146 const auto *BitIntValType = ValType->getAs<BitIntType>();
5147 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
5148 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5149 return ExprError();
5150 }
5151
5152 return TheCallResult;
5153}
5154
5155ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5156 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5157 DeclRefExpr *DRE =
5159 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5160 unsigned BuiltinID = FDecl->getBuiltinID();
5161 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5162 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5163 "Unexpected nontemporal load/store builtin!");
5164 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5165 unsigned numArgs = isStore ? 2 : 1;
5166
5167 // Ensure that we have the proper number of arguments.
5168 if (checkArgCount(TheCall, numArgs))
5169 return ExprError();
5170
5171 // Inspect the last argument of the nontemporal builtin. This should always
5172 // be a pointer type, from which we imply the type of the memory access.
5173 // Because it is a pointer type, we don't have to worry about any implicit
5174 // casts here.
5175 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5176 ExprResult PointerArgResult =
5178
5179 if (PointerArgResult.isInvalid())
5180 return ExprError();
5181 PointerArg = PointerArgResult.get();
5182 TheCall->setArg(numArgs - 1, PointerArg);
5183
5184 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5185 if (!pointerType) {
5186 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5187 << PointerArg->getType() << PointerArg->getSourceRange();
5188 return ExprError();
5189 }
5190
5191 QualType ValType = pointerType->getPointeeType();
5192
5193 // Strip any qualifiers off ValType.
5194 ValType = ValType.getUnqualifiedType();
5195 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5196 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5197 !ValType->isVectorType()) {
5198 Diag(DRE->getBeginLoc(),
5199 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5200 << PointerArg->getType() << PointerArg->getSourceRange();
5201 return ExprError();
5202 }
5203
5204 if (!isStore) {
5205 TheCall->setType(ValType);
5206 return TheCallResult;
5207 }
5208
5209 ExprResult ValArg = TheCall->getArg(0);
5210 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5211 Context, ValType, /*consume*/ false);
5212 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5213 if (ValArg.isInvalid())
5214 return ExprError();
5215
5216 TheCall->setArg(0, ValArg.get());
5217 TheCall->setType(Context.VoidTy);
5218 return TheCallResult;
5219}
5220
5221/// CheckObjCString - Checks that the format string argument to the os_log()
5222/// and os_trace() functions is correct, and converts it to const char *.
5223ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5224 Arg = Arg->IgnoreParenCasts();
5225 auto *Literal = dyn_cast<StringLiteral>(Arg);
5226 if (!Literal) {
5227 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5228 Literal = ObjcLiteral->getString();
5229 }
5230 }
5231
5232 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5233 return ExprError(
5234 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5235 << Arg->getSourceRange());
5236 }
5237
5238 ExprResult Result(Literal);
5239 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5240 InitializedEntity Entity =
5242 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5243 return Result;
5244}
5245
5246/// Check that the user is calling the appropriate va_start builtin for the
5247/// target and calling convention.
5248static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5249 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5250 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5251 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5252 TT.getArch() == llvm::Triple::aarch64_32);
5253 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5254 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5255 if (IsX64 || IsAArch64) {
5256 CallingConv CC = CC_C;
5257 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5258 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5259 if (IsMSVAStart) {
5260 // Don't allow this in System V ABI functions.
5261 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5262 return S.Diag(Fn->getBeginLoc(),
5263 diag::err_ms_va_start_used_in_sysv_function);
5264 } else {
5265 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5266 // On x64 Windows, don't allow this in System V ABI functions.
5267 // (Yes, that means there's no corresponding way to support variadic
5268 // System V ABI functions on Windows.)
5269 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5270 (!IsWindowsOrUEFI && CC == CC_Win64))
5271 return S.Diag(Fn->getBeginLoc(),
5272 diag::err_va_start_used_in_wrong_abi_function)
5273 << !IsWindowsOrUEFI;
5274 }
5275 return false;
5276 }
5277
5278 if (IsMSVAStart)
5279 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5280 return false;
5281}
5282
5284 ParmVarDecl **LastParam = nullptr) {
5285 // Determine whether the current function, block, or obj-c method is variadic
5286 // and get its parameter list.
5287 bool IsVariadic = false;
5289 DeclContext *Caller = S.CurContext;
5290 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5291 IsVariadic = Block->isVariadic();
5292 Params = Block->parameters();
5293 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5294 IsVariadic = FD->isVariadic();
5295 Params = FD->parameters();
5296 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5297 IsVariadic = MD->isVariadic();
5298 // FIXME: This isn't correct for methods (results in bogus warning).
5299 Params = MD->parameters();
5300 } else if (isa<CapturedDecl>(Caller)) {
5301 // We don't support va_start in a CapturedDecl.
5302 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5303 return true;
5304 } else {
5305 // This must be some other declcontext that parses exprs.
5306 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5307 return true;
5308 }
5309
5310 if (!IsVariadic) {
5311 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5312 return true;
5313 }
5314
5315 if (LastParam)
5316 *LastParam = Params.empty() ? nullptr : Params.back();
5317
5318 return false;
5319}
5320
5321bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5322 Expr *Fn = TheCall->getCallee();
5323 if (checkVAStartABI(*this, BuiltinID, Fn))
5324 return true;
5325
5326 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
5327 // This builtin requires one argument (the va_list), allows two arguments,
5328 // but diagnoses more than two arguments. e.g.,
5329 // __builtin_c23_va_start(); // error
5330 // __builtin_c23_va_start(list); // ok
5331 // __builtin_c23_va_start(list, param); // ok
5332 // __builtin_c23_va_start(list, anything, anything); // error
5333 // This differs from the GCC behavior in that they accept the last case
5334 // with a warning, but it doesn't seem like a useful behavior to allow.
5335 if (checkArgCountRange(TheCall, 1, 2))
5336 return true;
5337 } else {
5338 // In C23 mode, va_start only needs one argument. However, the builtin still
5339 // requires two arguments (which matches the behavior of the GCC builtin),
5340 // <stdarg.h> passes `0` as the second argument in C23 mode.
5341 if (checkArgCount(TheCall, 2))
5342 return true;
5343 }
5344
5345 // Type-check the first argument normally.
5346 if (checkBuiltinArgument(*this, TheCall, 0))
5347 return true;
5348
5349 // Check that the current function is variadic, and get its last parameter.
5350 ParmVarDecl *LastParam;
5351 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5352 return true;
5353
5354 // Verify that the second argument to the builtin is the last non-variadic
5355 // argument of the current function or method. In C23 mode, if the call is
5356 // not to __builtin_c23_va_start, and the second argument is an integer
5357 // constant expression with value 0, then we don't bother with this check.
5358 // For __builtin_c23_va_start, we only perform the check for the second
5359 // argument being the last argument to the current function if there is a
5360 // second argument present.
5361 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
5362 TheCall->getNumArgs() < 2) {
5363 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5364 return false;
5365 }
5366
5367 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5368 if (std::optional<llvm::APSInt> Val =
5370 Val && LangOpts.C23 && *Val == 0 &&
5371 BuiltinID != Builtin::BI__builtin_c23_va_start) {
5372 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5373 return false;
5374 }
5375
5376 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
5377 // next block.
5378 QualType Type;
5379 SourceLocation ParamLoc;
5380 bool IsCRegister = false;
5381 bool SecondArgIsLastNonVariadicArgument = false;
5382 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5383 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5384 SecondArgIsLastNonVariadicArgument = PV == LastParam;
5385
5386 Type = PV->getType();
5387 ParamLoc = PV->getLocation();
5388 IsCRegister =
5389 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5390 }
5391 }
5392
5393 if (!SecondArgIsLastNonVariadicArgument)
5394 Diag(TheCall->getArg(1)->getBeginLoc(),
5395 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
5396 else if (IsCRegister || Type->isReferenceType() ||
5397 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5398 // Promotable integers are UB, but enumerations need a bit of
5399 // extra checking to see what their promotable type actually is.
5400 if (!Context.isPromotableIntegerType(Type))
5401 return false;
5402 const auto *ED = Type->getAsEnumDecl();
5403 if (!ED)
5404 return true;
5405 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
5406 }()) {
5407 unsigned Reason = 0;
5408 if (Type->isReferenceType()) Reason = 1;
5409 else if (IsCRegister) Reason = 2;
5410 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5411 Diag(ParamLoc, diag::note_parameter_type) << Type;
5412 }
5413
5414 return false;
5415}
5416
5417bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
5418 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
5419 const LangOptions &LO = getLangOpts();
5420
5421 if (LO.CPlusPlus)
5422 return Arg->getType()
5424 .getTypePtr()
5425 ->getPointeeType()
5427
5428 // In C, allow aliasing through `char *`, this is required for AArch64 at
5429 // least.
5430 return true;
5431 };
5432
5433 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5434 // const char *named_addr);
5435
5436 Expr *Func = Call->getCallee();
5437
5438 if (Call->getNumArgs() < 3)
5439 return Diag(Call->getEndLoc(),
5440 diag::err_typecheck_call_too_few_args_at_least)
5441 << 0 /*function call*/ << 3 << Call->getNumArgs()
5442 << /*is non object*/ 0;
5443
5444 // Type-check the first argument normally.
5445 if (checkBuiltinArgument(*this, Call, 0))
5446 return true;
5447
5448 // Check that the current function is variadic.
5450 return true;
5451
5452 // __va_start on Windows does not validate the parameter qualifiers
5453
5454 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5455 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5456
5457 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5458 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5459
5460 const QualType &ConstCharPtrTy =
5461 Context.getPointerType(Context.CharTy.withConst());
5462 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
5463 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5464 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5465 << 0 /* qualifier difference */
5466 << 3 /* parameter mismatch */
5467 << 2 << Arg1->getType() << ConstCharPtrTy;
5468
5469 const QualType SizeTy = Context.getSizeType();
5470 if (!Context.hasSameType(
5472 SizeTy))
5473 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5474 << Arg2->getType() << SizeTy << 1 /* different class */
5475 << 0 /* qualifier difference */
5476 << 3 /* parameter mismatch */
5477 << 3 << Arg2->getType() << SizeTy;
5478
5479 return false;
5480}
5481
5482bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
5483 if (checkArgCount(TheCall, 2))
5484 return true;
5485
5486 if (BuiltinID == Builtin::BI__builtin_isunordered &&
5487 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
5488 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5489 << 1 << 0 << TheCall->getSourceRange();
5490
5491 ExprResult OrigArg0 = TheCall->getArg(0);
5492 ExprResult OrigArg1 = TheCall->getArg(1);
5493
5494 // Do standard promotions between the two arguments, returning their common
5495 // type.
5496 QualType Res = UsualArithmeticConversions(
5497 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
5498 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5499 return true;
5500
5501 // Make sure any conversions are pushed back into the call; this is
5502 // type safe since unordered compare builtins are declared as "_Bool
5503 // foo(...)".
5504 TheCall->setArg(0, OrigArg0.get());
5505 TheCall->setArg(1, OrigArg1.get());
5506
5507 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5508 return false;
5509
5510 // If the common type isn't a real floating type, then the arguments were
5511 // invalid for this operation.
5512 if (Res.isNull() || !Res->isRealFloatingType())
5513 return Diag(OrigArg0.get()->getBeginLoc(),
5514 diag::err_typecheck_call_invalid_ordered_compare)
5515 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5516 << SourceRange(OrigArg0.get()->getBeginLoc(),
5517 OrigArg1.get()->getEndLoc());
5518
5519 return false;
5520}
5521
5522bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
5523 unsigned BuiltinID) {
5524 if (checkArgCount(TheCall, NumArgs))
5525 return true;
5526
5527 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
5528 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
5529 BuiltinID == Builtin::BI__builtin_isinf ||
5530 BuiltinID == Builtin::BI__builtin_isinf_sign))
5531 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5532 << 0 << 0 << TheCall->getSourceRange();
5533
5534 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
5535 BuiltinID == Builtin::BI__builtin_isunordered))
5536 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5537 << 1 << 0 << TheCall->getSourceRange();
5538
5539 bool IsFPClass = NumArgs == 2;
5540
5541 // Find out position of floating-point argument.
5542 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
5543
5544 // We can count on all parameters preceding the floating-point just being int.
5545 // Try all of those.
5546 for (unsigned i = 0; i < FPArgNo; ++i) {
5547 Expr *Arg = TheCall->getArg(i);
5548
5549 if (Arg->isTypeDependent())
5550 return false;
5551
5554
5555 if (Res.isInvalid())
5556 return true;
5557 TheCall->setArg(i, Res.get());
5558 }
5559
5560 Expr *OrigArg = TheCall->getArg(FPArgNo);
5561
5562 if (OrigArg->isTypeDependent())
5563 return false;
5564
5565 // Usual Unary Conversions will convert half to float, which we want for
5566 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5567 // type how it is, but do normal L->Rvalue conversions.
5568 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
5569 ExprResult Res = UsualUnaryConversions(OrigArg);
5570
5571 if (!Res.isUsable())
5572 return true;
5573 OrigArg = Res.get();
5574 } else {
5576
5577 if (!Res.isUsable())
5578 return true;
5579 OrigArg = Res.get();
5580 }
5581 TheCall->setArg(FPArgNo, OrigArg);
5582
5583 QualType VectorResultTy;
5584 QualType ElementTy = OrigArg->getType();
5585 // TODO: When all classification function are implemented with is_fpclass,
5586 // vector argument can be supported in all of them.
5587 if (ElementTy->isVectorType() && IsFPClass) {
5588 VectorResultTy = GetSignedVectorType(ElementTy);
5589 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
5590 }
5591
5592 // This operation requires a non-_Complex floating-point number.
5593 if (!ElementTy->isRealFloatingType())
5594 return Diag(OrigArg->getBeginLoc(),
5595 diag::err_typecheck_call_invalid_unary_fp)
5596 << OrigArg->getType() << OrigArg->getSourceRange();
5597
5598 // __builtin_isfpclass has integer parameter that specify test mask. It is
5599 // passed in (...), so it should be analyzed completely here.
5600 if (IsFPClass)
5601 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
5602 return true;
5603
5604 // TODO: enable this code to all classification functions.
5605 if (IsFPClass) {
5606 QualType ResultTy;
5607 if (!VectorResultTy.isNull())
5608 ResultTy = VectorResultTy;
5609 else
5610 ResultTy = Context.IntTy;
5611 TheCall->setType(ResultTy);
5612 }
5613
5614 return false;
5615}
5616
5617bool Sema::BuiltinComplex(CallExpr *TheCall) {
5618 if (checkArgCount(TheCall, 2))
5619 return true;
5620
5621 bool Dependent = false;
5622 for (unsigned I = 0; I != 2; ++I) {
5623 Expr *Arg = TheCall->getArg(I);
5624 QualType T = Arg->getType();
5625 if (T->isDependentType()) {
5626 Dependent = true;
5627 continue;
5628 }
5629
5630 // Despite supporting _Complex int, GCC requires a real floating point type
5631 // for the operands of __builtin_complex.
5632 if (!T->isRealFloatingType()) {
5633 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
5634 << Arg->getType() << Arg->getSourceRange();
5635 }
5636
5637 ExprResult Converted = DefaultLvalueConversion(Arg);
5638 if (Converted.isInvalid())
5639 return true;
5640 TheCall->setArg(I, Converted.get());
5641 }
5642
5643 if (Dependent) {
5644 TheCall->setType(Context.DependentTy);
5645 return false;
5646 }
5647
5648 Expr *Real = TheCall->getArg(0);
5649 Expr *Imag = TheCall->getArg(1);
5650 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
5651 return Diag(Real->getBeginLoc(),
5652 diag::err_typecheck_call_different_arg_types)
5653 << Real->getType() << Imag->getType()
5654 << Real->getSourceRange() << Imag->getSourceRange();
5655 }
5656
5657 TheCall->setType(Context.getComplexType(Real->getType()));
5658 return false;
5659}
5660
5661/// BuiltinShuffleVector - Handle __builtin_shufflevector.
5662// This is declared to take (...), so we have to check everything.
5664 unsigned NumArgs = TheCall->getNumArgs();
5665 if (NumArgs < 2)
5666 return ExprError(Diag(TheCall->getEndLoc(),
5667 diag::err_typecheck_call_too_few_args_at_least)
5668 << 0 /*function call*/ << 2 << NumArgs
5669 << /*is non object*/ 0 << TheCall->getSourceRange());
5670
5671 // Determine which of the following types of shufflevector we're checking:
5672 // 1) unary, vector mask: (lhs, mask)
5673 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5674 QualType ResType = TheCall->getArg(0)->getType();
5675 unsigned NumElements = 0;
5676
5677 if (!TheCall->getArg(0)->isTypeDependent() &&
5678 !TheCall->getArg(1)->isTypeDependent()) {
5679 QualType LHSType = TheCall->getArg(0)->getType();
5680 QualType RHSType = TheCall->getArg(1)->getType();
5681
5682 if (!LHSType->isVectorType() || !RHSType->isVectorType())
5683 return ExprError(
5684 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5685 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
5686 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5687 TheCall->getArg(1)->getEndLoc()));
5688
5689 NumElements = LHSType->castAs<VectorType>()->getNumElements();
5690 unsigned NumResElements = NumArgs - 2;
5691
5692 // Check to see if we have a call with 2 vector arguments, the unary shuffle
5693 // with mask. If so, verify that RHS is an integer vector type with the
5694 // same number of elts as lhs.
5695 if (NumArgs == 2) {
5696 if (!RHSType->hasIntegerRepresentation() ||
5697 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
5698 return ExprError(Diag(TheCall->getBeginLoc(),
5699 diag::err_vec_builtin_incompatible_vector)
5700 << TheCall->getDirectCallee()
5701 << /*isMoreThanTwoArgs*/ false
5702 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5703 TheCall->getArg(1)->getEndLoc()));
5704 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5705 return ExprError(Diag(TheCall->getBeginLoc(),
5706 diag::err_vec_builtin_incompatible_vector)
5707 << TheCall->getDirectCallee()
5708 << /*isMoreThanTwoArgs*/ false
5709 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5710 TheCall->getArg(1)->getEndLoc()));
5711 } else if (NumElements != NumResElements) {
5712 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
5713 ResType = ResType->isExtVectorType()
5714 ? Context.getExtVectorType(EltType, NumResElements)
5715 : Context.getVectorType(EltType, NumResElements,
5717 }
5718 }
5719
5720 for (unsigned I = 2; I != NumArgs; ++I) {
5721 Expr *Arg = TheCall->getArg(I);
5722 if (Arg->isTypeDependent() || Arg->isValueDependent())
5723 continue;
5724
5725 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
5726 if (!Result)
5727 return ExprError(Diag(TheCall->getBeginLoc(),
5728 diag::err_shufflevector_nonconstant_argument)
5729 << Arg->getSourceRange());
5730
5731 // Allow -1 which will be translated to undef in the IR.
5732 if (Result->isSigned() && Result->isAllOnes())
5733 ;
5734 else if (Result->getActiveBits() > 64 ||
5735 Result->getZExtValue() >= NumElements * 2)
5736 return ExprError(Diag(TheCall->getBeginLoc(),
5737 diag::err_shufflevector_argument_too_large)
5738 << Arg->getSourceRange());
5739
5740 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
5741 }
5742
5743 auto *Result = new (Context) ShuffleVectorExpr(
5744 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
5745 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
5746
5747 // All moved to Result.
5748 TheCall->shrinkNumArgs(0);
5749 return Result;
5750}
5751
5753 SourceLocation BuiltinLoc,
5754 SourceLocation RParenLoc) {
5757 QualType DstTy = TInfo->getType();
5758 QualType SrcTy = E->getType();
5759
5760 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5761 return ExprError(Diag(BuiltinLoc,
5762 diag::err_convertvector_non_vector)
5763 << E->getSourceRange());
5764 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5765 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
5766 << "second"
5767 << "__builtin_convertvector");
5768
5769 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5770 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5771 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5772 if (SrcElts != DstElts)
5773 return ExprError(Diag(BuiltinLoc,
5774 diag::err_convertvector_incompatible_vector)
5775 << E->getSourceRange());
5776 }
5777
5778 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
5779 RParenLoc, CurFPFeatureOverrides());
5780}
5781
5782bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
5783 unsigned NumArgs = TheCall->getNumArgs();
5784
5785 if (NumArgs > 3)
5786 return Diag(TheCall->getEndLoc(),
5787 diag::err_typecheck_call_too_many_args_at_most)
5788 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
5789 << TheCall->getSourceRange();
5790
5791 // Argument 0 is checked for us and the remaining arguments must be
5792 // constant integers.
5793 for (unsigned i = 1; i != NumArgs; ++i)
5794 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5795 return true;
5796
5797 return false;
5798}
5799
5800bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
5801 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
5802 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
5803 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5804 if (checkArgCount(TheCall, 1))
5805 return true;
5806 Expr *Arg = TheCall->getArg(0);
5807 if (Arg->isInstantiationDependent())
5808 return false;
5809
5810 QualType ArgTy = Arg->getType();
5811 if (!ArgTy->hasFloatingRepresentation())
5812 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
5813 << ArgTy;
5814 if (Arg->isLValue()) {
5815 ExprResult FirstArg = DefaultLvalueConversion(Arg);
5816 TheCall->setArg(0, FirstArg.get());
5817 }
5818 TheCall->setType(TheCall->getArg(0)->getType());
5819 return false;
5820}
5821
5822bool Sema::BuiltinAssume(CallExpr *TheCall) {
5823 Expr *Arg = TheCall->getArg(0);
5824 if (Arg->isInstantiationDependent()) return false;
5825
5826 if (Arg->HasSideEffects(Context))
5827 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5828 << Arg->getSourceRange()
5829 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5830
5831 return false;
5832}
5833
5834bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
5835 // The alignment must be a constant integer.
5836 Expr *Arg = TheCall->getArg(1);
5837
5838 // We can't check the value of a dependent argument.
5839 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5840 if (const auto *UE =
5841 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5842 if (UE->getKind() == UETT_AlignOf ||
5843 UE->getKind() == UETT_PreferredAlignOf)
5844 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5845 << Arg->getSourceRange();
5846
5847 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5848
5849 if (!Result.isPowerOf2())
5850 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5851 << Arg->getSourceRange();
5852
5853 if (Result < Context.getCharWidth())
5854 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5855 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5856
5857 if (Result > std::numeric_limits<int32_t>::max())
5858 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5859 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5860 }
5861
5862 return false;
5863}
5864
5865bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
5866 if (checkArgCountRange(TheCall, 2, 3))
5867 return true;
5868
5869 unsigned NumArgs = TheCall->getNumArgs();
5870 Expr *FirstArg = TheCall->getArg(0);
5871
5872 {
5873 ExprResult FirstArgResult =
5875 if (!FirstArgResult.get()->getType()->isPointerType()) {
5876 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
5877 << TheCall->getSourceRange();
5878 return true;
5879 }
5880 TheCall->setArg(0, FirstArgResult.get());
5881 }
5882
5883 // The alignment must be a constant integer.
5884 Expr *SecondArg = TheCall->getArg(1);
5885
5886 // We can't check the value of a dependent argument.
5887 if (!SecondArg->isValueDependent()) {
5888 llvm::APSInt Result;
5889 if (BuiltinConstantArg(TheCall, 1, Result))
5890 return true;
5891
5892 if (!Result.isPowerOf2())
5893 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5894 << SecondArg->getSourceRange();
5895
5897 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5898 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
5899 }
5900
5901 if (NumArgs > 2) {
5902 Expr *ThirdArg = TheCall->getArg(2);
5903 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
5904 return true;
5905 TheCall->setArg(2, ThirdArg);
5906 }
5907
5908 return false;
5909}
5910
5911bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
5912 unsigned BuiltinID =
5913 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5914 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5915
5916 unsigned NumArgs = TheCall->getNumArgs();
5917 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5918 if (NumArgs < NumRequiredArgs) {
5919 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5920 << 0 /* function call */ << NumRequiredArgs << NumArgs
5921 << /*is non object*/ 0 << TheCall->getSourceRange();
5922 }
5923 if (NumArgs >= NumRequiredArgs + 0x100) {
5924 return Diag(TheCall->getEndLoc(),
5925 diag::err_typecheck_call_too_many_args_at_most)
5926 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5927 << /*is non object*/ 0 << TheCall->getSourceRange();
5928 }
5929 unsigned i = 0;
5930
5931 // For formatting call, check buffer arg.
5932 if (!IsSizeCall) {
5933 ExprResult Arg(TheCall->getArg(i));
5934 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5935 Context, Context.VoidPtrTy, false);
5936 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5937 if (Arg.isInvalid())
5938 return true;
5939 TheCall->setArg(i, Arg.get());
5940 i++;
5941 }
5942
5943 // Check string literal arg.
5944 unsigned FormatIdx = i;
5945 {
5946 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5947 if (Arg.isInvalid())
5948 return true;
5949 TheCall->setArg(i, Arg.get());
5950 i++;
5951 }
5952
5953 // Make sure variadic args are scalar.
5954 unsigned FirstDataArg = i;
5955 while (i < NumArgs) {
5957 TheCall->getArg(i), VariadicCallType::Function, nullptr);
5958 if (Arg.isInvalid())
5959 return true;
5960 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5961 if (ArgSize.getQuantity() >= 0x100) {
5962 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5963 << i << (int)ArgSize.getQuantity() << 0xff
5964 << TheCall->getSourceRange();
5965 }
5966 TheCall->setArg(i, Arg.get());
5967 i++;
5968 }
5969
5970 // Check formatting specifiers. NOTE: We're only doing this for the non-size
5971 // call to avoid duplicate diagnostics.
5972 if (!IsSizeCall) {
5973 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5974 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5975 bool Success = CheckFormatArguments(
5976 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
5978 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
5979 if (!Success)
5980 return true;
5981 }
5982
5983 if (IsSizeCall) {
5984 TheCall->setType(Context.getSizeType());
5985 } else {
5986 TheCall->setType(Context.VoidPtrTy);
5987 }
5988 return false;
5989}
5990
5991bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
5992 llvm::APSInt &Result) {
5993 Expr *Arg = TheCall->getArg(ArgNum);
5994
5995 if (Arg->isTypeDependent() || Arg->isValueDependent())
5996 return false;
5997
5998 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
5999 if (!R) {
6000 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6001 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6002 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6003 << FDecl->getDeclName() << Arg->getSourceRange();
6004 }
6005 Result = *R;
6006
6007 return false;
6008}
6009
6010bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6011 int High, bool RangeIsError) {
6013 return false;
6014 llvm::APSInt Result;
6015
6016 // We can't check the value of a dependent argument.
6017 Expr *Arg = TheCall->getArg(ArgNum);
6018 if (Arg->isTypeDependent() || Arg->isValueDependent())
6019 return false;
6020
6021 // Check constant-ness first.
6022 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6023 return true;
6024
6025 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6026 if (RangeIsError)
6027 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6028 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6029 else
6030 // Defer the warning until we know if the code will be emitted so that
6031 // dead code can ignore this.
6032 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6033 PDiag(diag::warn_argument_invalid_range)
6034 << toString(Result, 10) << Low << High
6035 << Arg->getSourceRange());
6036 }
6037
6038 return false;
6039}
6040
6041bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6042 unsigned Num) {
6043 llvm::APSInt Result;
6044
6045 // We can't check the value of a dependent argument.
6046 Expr *Arg = TheCall->getArg(ArgNum);
6047 if (Arg->isTypeDependent() || Arg->isValueDependent())
6048 return false;
6049
6050 // Check constant-ness first.
6051 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6052 return true;
6053
6054 if (Result.getSExtValue() % Num != 0)
6055 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6056 << Num << Arg->getSourceRange();
6057
6058 return false;
6059}
6060
6061bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6062 llvm::APSInt Result;
6063
6064 // We can't check the value of a dependent argument.
6065 Expr *Arg = TheCall->getArg(ArgNum);
6066 if (Arg->isTypeDependent() || Arg->isValueDependent())
6067 return false;
6068
6069 // Check constant-ness first.
6070 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6071 return true;
6072
6073 if (Result.isPowerOf2())
6074 return false;
6075
6076 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6077 << Arg->getSourceRange();
6078}
6079
6080static bool IsShiftedByte(llvm::APSInt Value) {
6081 if (Value.isNegative())
6082 return false;
6083
6084 // Check if it's a shifted byte, by shifting it down
6085 while (true) {
6086 // If the value fits in the bottom byte, the check passes.
6087 if (Value < 0x100)
6088 return true;
6089
6090 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6091 // fails.
6092 if ((Value & 0xFF) != 0)
6093 return false;
6094
6095 // If the bottom 8 bits are all 0, but something above that is nonzero,
6096 // then shifting the value right by 8 bits won't affect whether it's a
6097 // shifted byte or not. So do that, and go round again.
6098 Value >>= 8;
6099 }
6100}
6101
6102bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6103 unsigned ArgBits) {
6104 llvm::APSInt Result;
6105
6106 // We can't check the value of a dependent argument.
6107 Expr *Arg = TheCall->getArg(ArgNum);
6108 if (Arg->isTypeDependent() || Arg->isValueDependent())
6109 return false;
6110
6111 // Check constant-ness first.
6112 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6113 return true;
6114
6115 // Truncate to the given size.
6116 Result = Result.getLoBits(ArgBits);
6117 Result.setIsUnsigned(true);
6118
6119 if (IsShiftedByte(Result))
6120 return false;
6121
6122 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6123 << Arg->getSourceRange();
6124}
6125
6127 unsigned ArgNum,
6128 unsigned ArgBits) {
6129 llvm::APSInt Result;
6130
6131 // We can't check the value of a dependent argument.
6132 Expr *Arg = TheCall->getArg(ArgNum);
6133 if (Arg->isTypeDependent() || Arg->isValueDependent())
6134 return false;
6135
6136 // Check constant-ness first.
6137 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6138 return true;
6139
6140 // Truncate to the given size.
6141 Result = Result.getLoBits(ArgBits);
6142 Result.setIsUnsigned(true);
6143
6144 // Check to see if it's in either of the required forms.
6145 if (IsShiftedByte(Result) ||
6146 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6147 return false;
6148
6149 return Diag(TheCall->getBeginLoc(),
6150 diag::err_argument_not_shifted_byte_or_xxff)
6151 << Arg->getSourceRange();
6152}
6153
6154bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6155 if (!Context.getTargetInfo().hasSjLjLowering())
6156 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6157 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6158
6159 Expr *Arg = TheCall->getArg(1);
6160 llvm::APSInt Result;
6161
6162 // TODO: This is less than ideal. Overload this to take a value.
6163 if (BuiltinConstantArg(TheCall, 1, Result))
6164 return true;
6165
6166 if (Result != 1)
6167 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6168 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6169
6170 return false;
6171}
6172
6173bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6174 if (!Context.getTargetInfo().hasSjLjLowering())
6175 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6176 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6177 return false;
6178}
6179
6180bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6181 if (checkArgCount(TheCall, 1))
6182 return true;
6183
6184 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
6185 if (ArgRes.isInvalid())
6186 return true;
6187
6188 // For simplicity, we support only limited expressions for the argument.
6189 // Specifically a pointer to a flexible array member:'ptr->array'. This
6190 // allows us to reject arguments with complex casting, which really shouldn't
6191 // be a huge problem.
6192 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6193 if (!isa<PointerType>(Arg->getType()) && !Arg->getType()->isArrayType())
6194 return Diag(Arg->getBeginLoc(),
6195 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6196 << Arg->getSourceRange();
6197
6198 if (Arg->HasSideEffects(Context))
6199 return Diag(Arg->getBeginLoc(),
6200 diag::err_builtin_counted_by_ref_has_side_effects)
6201 << Arg->getSourceRange();
6202
6203 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
6204 if (!ME->isFlexibleArrayMemberLike(
6205 Context, getLangOpts().getStrictFlexArraysLevel()))
6206 return Diag(Arg->getBeginLoc(),
6207 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6208 << Arg->getSourceRange();
6209
6210 if (auto *CATy =
6211 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6212 CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6213 const auto *FAMDecl = cast<FieldDecl>(ME->getMemberDecl());
6214 if (const FieldDecl *CountFD = FAMDecl->findCountedByField()) {
6215 TheCall->setType(Context.getPointerType(CountFD->getType()));
6216 return false;
6217 }
6218 }
6219 } else {
6220 return Diag(Arg->getBeginLoc(),
6221 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6222 << Arg->getSourceRange();
6223 }
6224
6225 TheCall->setType(Context.getPointerType(Context.VoidTy));
6226 return false;
6227}
6228
6229/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6230/// It allows leaking and modification of bounds safety information.
6231bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6233 const CallExpr *CE =
6234 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
6235 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6236 return false;
6237
6238 switch (K) {
6241 Diag(E->getExprLoc(),
6242 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6243 << 0 << E->getSourceRange();
6244 break;
6246 Diag(E->getExprLoc(),
6247 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6248 << 1 << E->getSourceRange();
6249 break;
6251 Diag(E->getExprLoc(),
6252 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6253 << 2 << E->getSourceRange();
6254 break;
6256 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6257 << 0 << E->getSourceRange();
6258 break;
6260 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6261 << 1 << E->getSourceRange();
6262 break;
6263 }
6264
6265 return true;
6266}
6267
6268namespace {
6269
6270class UncoveredArgHandler {
6271 enum { Unknown = -1, AllCovered = -2 };
6272
6273 signed FirstUncoveredArg = Unknown;
6274 SmallVector<const Expr *, 4> DiagnosticExprs;
6275
6276public:
6277 UncoveredArgHandler() = default;
6278
6279 bool hasUncoveredArg() const {
6280 return (FirstUncoveredArg >= 0);
6281 }
6282
6283 unsigned getUncoveredArg() const {
6284 assert(hasUncoveredArg() && "no uncovered argument");
6285 return FirstUncoveredArg;
6286 }
6287
6288 void setAllCovered() {
6289 // A string has been found with all arguments covered, so clear out
6290 // the diagnostics.
6291 DiagnosticExprs.clear();
6292 FirstUncoveredArg = AllCovered;
6293 }
6294
6295 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6296 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6297
6298 // Don't update if a previous string covers all arguments.
6299 if (FirstUncoveredArg == AllCovered)
6300 return;
6301
6302 // UncoveredArgHandler tracks the highest uncovered argument index
6303 // and with it all the strings that match this index.
6304 if (NewFirstUncoveredArg == FirstUncoveredArg)
6305 DiagnosticExprs.push_back(StrExpr);
6306 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6307 DiagnosticExprs.clear();
6308 DiagnosticExprs.push_back(StrExpr);
6309 FirstUncoveredArg = NewFirstUncoveredArg;
6310 }
6311 }
6312
6313 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6314};
6315
6316enum StringLiteralCheckType {
6317 SLCT_NotALiteral,
6318 SLCT_UncheckedLiteral,
6319 SLCT_CheckedLiteral
6320};
6321
6322} // namespace
6323
6324static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6325 BinaryOperatorKind BinOpKind,
6326 bool AddendIsRight) {
6327 unsigned BitWidth = Offset.getBitWidth();
6328 unsigned AddendBitWidth = Addend.getBitWidth();
6329 // There might be negative interim results.
6330 if (Addend.isUnsigned()) {
6331 Addend = Addend.zext(++AddendBitWidth);
6332 Addend.setIsSigned(true);
6333 }
6334 // Adjust the bit width of the APSInts.
6335 if (AddendBitWidth > BitWidth) {
6336 Offset = Offset.sext(AddendBitWidth);
6337 BitWidth = AddendBitWidth;
6338 } else if (BitWidth > AddendBitWidth) {
6339 Addend = Addend.sext(BitWidth);
6340 }
6341
6342 bool Ov = false;
6343 llvm::APSInt ResOffset = Offset;
6344 if (BinOpKind == BO_Add)
6345 ResOffset = Offset.sadd_ov(Addend, Ov);
6346 else {
6347 assert(AddendIsRight && BinOpKind == BO_Sub &&
6348 "operator must be add or sub with addend on the right");
6349 ResOffset = Offset.ssub_ov(Addend, Ov);
6350 }
6351
6352 // We add an offset to a pointer here so we should support an offset as big as
6353 // possible.
6354 if (Ov) {
6355 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6356 "index (intermediate) result too big");
6357 Offset = Offset.sext(2 * BitWidth);
6358 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6359 return;
6360 }
6361
6362 Offset = ResOffset;
6363}
6364
6365namespace {
6366
6367// This is a wrapper class around StringLiteral to support offsetted string
6368// literals as format strings. It takes the offset into account when returning
6369// the string and its length or the source locations to display notes correctly.
6370class FormatStringLiteral {
6371 const StringLiteral *FExpr;
6372 int64_t Offset;
6373
6374public:
6375 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6376 : FExpr(fexpr), Offset(Offset) {}
6377
6378 const StringLiteral *getFormatString() const { return FExpr; }
6379
6380 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
6381
6382 unsigned getByteLength() const {
6383 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6384 }
6385
6386 unsigned getLength() const { return FExpr->getLength() - Offset; }
6387 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6388
6389 StringLiteralKind getKind() const { return FExpr->getKind(); }
6390
6391 QualType getType() const { return FExpr->getType(); }
6392
6393 bool isAscii() const { return FExpr->isOrdinary(); }
6394 bool isWide() const { return FExpr->isWide(); }
6395 bool isUTF8() const { return FExpr->isUTF8(); }
6396 bool isUTF16() const { return FExpr->isUTF16(); }
6397 bool isUTF32() const { return FExpr->isUTF32(); }
6398 bool isPascal() const { return FExpr->isPascal(); }
6399
6400 SourceLocation getLocationOfByte(
6401 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6402 const TargetInfo &Target, unsigned *StartToken = nullptr,
6403 unsigned *StartTokenByteOffset = nullptr) const {
6404 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6405 StartToken, StartTokenByteOffset);
6406 }
6407
6408 SourceLocation getBeginLoc() const LLVM_READONLY {
6409 return FExpr->getBeginLoc().getLocWithOffset(Offset);
6410 }
6411
6412 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6413};
6414
6415} // namespace
6416
6417static void CheckFormatString(
6418 Sema &S, const FormatStringLiteral *FExpr,
6419 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
6421 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6422 bool inFunctionCall, VariadicCallType CallType,
6423 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6424 bool IgnoreStringsWithoutSpecifiers);
6425
6426static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
6427 const Expr *E);
6428
6429// Determine if an expression is a string literal or constant string.
6430// If this function returns false on the arguments to a function expecting a
6431// format string, we will usually need to emit a warning.
6432// True string literals are then checked by CheckFormatString.
6433static StringLiteralCheckType checkFormatStringExpr(
6434 Sema &S, const StringLiteral *ReferenceFormatString, const Expr *E,
6436 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6437 VariadicCallType CallType, bool InFunctionCall,
6438 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6439 llvm::APSInt Offset, bool IgnoreStringsWithoutSpecifiers = false) {
6441 return SLCT_NotALiteral;
6442tryAgain:
6443 assert(Offset.isSigned() && "invalid offset");
6444
6445 if (E->isTypeDependent() || E->isValueDependent())
6446 return SLCT_NotALiteral;
6447
6448 E = E->IgnoreParenCasts();
6449
6451 // Technically -Wformat-nonliteral does not warn about this case.
6452 // The behavior of printf and friends in this case is implementation
6453 // dependent. Ideally if the format string cannot be null then
6454 // it should have a 'nonnull' attribute in the function prototype.
6455 return SLCT_UncheckedLiteral;
6456
6457 switch (E->getStmtClass()) {
6458 case Stmt::InitListExprClass:
6459 // Handle expressions like {"foobar"}.
6460 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
6461 return checkFormatStringExpr(
6462 S, ReferenceFormatString, SLE, Args, APK, format_idx, firstDataArg,
6463 Type, CallType, /*InFunctionCall*/ false, CheckedVarArgs,
6464 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6465 }
6466 return SLCT_NotALiteral;
6467 case Stmt::BinaryConditionalOperatorClass:
6468 case Stmt::ConditionalOperatorClass: {
6469 // The expression is a literal if both sub-expressions were, and it was
6470 // completely checked only if both sub-expressions were checked.
6473
6474 // Determine whether it is necessary to check both sub-expressions, for
6475 // example, because the condition expression is a constant that can be
6476 // evaluated at compile time.
6477 bool CheckLeft = true, CheckRight = true;
6478
6479 bool Cond;
6480 if (C->getCond()->EvaluateAsBooleanCondition(
6482 if (Cond)
6483 CheckRight = false;
6484 else
6485 CheckLeft = false;
6486 }
6487
6488 // We need to maintain the offsets for the right and the left hand side
6489 // separately to check if every possible indexed expression is a valid
6490 // string literal. They might have different offsets for different string
6491 // literals in the end.
6492 StringLiteralCheckType Left;
6493 if (!CheckLeft)
6494 Left = SLCT_UncheckedLiteral;
6495 else {
6496 Left = checkFormatStringExpr(
6497 S, ReferenceFormatString, C->getTrueExpr(), Args, APK, format_idx,
6498 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6499 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6500 if (Left == SLCT_NotALiteral || !CheckRight) {
6501 return Left;
6502 }
6503 }
6504
6505 StringLiteralCheckType Right = checkFormatStringExpr(
6506 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
6507 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6508 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6509
6510 return (CheckLeft && Left < Right) ? Left : Right;
6511 }
6512
6513 case Stmt::ImplicitCastExprClass:
6514 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6515 goto tryAgain;
6516
6517 case Stmt::OpaqueValueExprClass:
6518 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6519 E = src;
6520 goto tryAgain;
6521 }
6522 return SLCT_NotALiteral;
6523
6524 case Stmt::PredefinedExprClass:
6525 // While __func__, etc., are technically not string literals, they
6526 // cannot contain format specifiers and thus are not a security
6527 // liability.
6528 return SLCT_UncheckedLiteral;
6529
6530 case Stmt::DeclRefExprClass: {
6531 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6532
6533 // As an exception, do not flag errors for variables binding to
6534 // const string literals.
6535 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6536 bool isConstant = false;
6537 QualType T = DR->getType();
6538
6539 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6540 isConstant = AT->getElementType().isConstant(S.Context);
6541 } else if (const PointerType *PT = T->getAs<PointerType>()) {
6542 isConstant = T.isConstant(S.Context) &&
6543 PT->getPointeeType().isConstant(S.Context);
6544 } else if (T->isObjCObjectPointerType()) {
6545 // In ObjC, there is usually no "const ObjectPointer" type,
6546 // so don't check if the pointee type is constant.
6547 isConstant = T.isConstant(S.Context);
6548 }
6549
6550 if (isConstant) {
6551 if (const Expr *Init = VD->getAnyInitializer()) {
6552 // Look through initializers like const char c[] = { "foo" }
6553 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6554 if (InitList->isStringLiteralInit())
6555 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6556 }
6557 return checkFormatStringExpr(
6558 S, ReferenceFormatString, Init, Args, APK, format_idx,
6559 firstDataArg, Type, CallType,
6560 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg, Offset);
6561 }
6562 }
6563
6564 // When the format argument is an argument of this function, and this
6565 // function also has the format attribute, there are several interactions
6566 // for which there shouldn't be a warning. For instance, when calling
6567 // v*printf from a function that has the printf format attribute, we
6568 // should not emit a warning about using `fmt`, even though it's not
6569 // constant, because the arguments have already been checked for the
6570 // caller of `logmessage`:
6571 //
6572 // __attribute__((format(printf, 1, 2)))
6573 // void logmessage(char const *fmt, ...) {
6574 // va_list ap;
6575 // va_start(ap, fmt);
6576 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
6577 // ...
6578 // }
6579 //
6580 // Another interaction that we need to support is using a format string
6581 // specified by the format_matches attribute:
6582 //
6583 // __attribute__((format_matches(printf, 1, "%s %d")))
6584 // void logmessage(char const *fmt, const char *a, int b) {
6585 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
6586 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
6587 // ...
6588 // }
6589 //
6590 // Yet another interaction that we need to support is calling a variadic
6591 // format function from a format function that has fixed arguments. For
6592 // instance:
6593 //
6594 // __attribute__((format(printf, 1, 2)))
6595 // void logstring(char const *fmt, char const *str) {
6596 // printf(fmt, str); /* do not emit a warning about "fmt" */
6597 // }
6598 //
6599 // Same (and perhaps more relatably) for the variadic template case:
6600 //
6601 // template<typename... Args>
6602 // __attribute__((format(printf, 1, 2)))
6603 // void log(const char *fmt, Args&&... args) {
6604 // printf(fmt, forward<Args>(args)...);
6605 // /* do not emit a warning about "fmt" */
6606 // }
6607 //
6608 // Due to implementation difficulty, we only check the format, not the
6609 // format arguments, in all cases.
6610 //
6611 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
6612 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
6613 for (const auto *PVFormatMatches :
6614 D->specific_attrs<FormatMatchesAttr>()) {
6615 Sema::FormatStringInfo CalleeFSI;
6616 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
6617 0, &CalleeFSI))
6618 continue;
6619 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
6620 // If using the wrong type of format string, emit a diagnostic
6621 // here and stop checking to avoid irrelevant diagnostics.
6622 if (Type != S.GetFormatStringType(PVFormatMatches)) {
6623 S.Diag(Args[format_idx]->getBeginLoc(),
6624 diag::warn_format_string_type_incompatible)
6625 << PVFormatMatches->getType()->getName()
6627 if (!InFunctionCall) {
6628 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
6629 diag::note_format_string_defined);
6630 }
6631 return SLCT_UncheckedLiteral;
6632 }
6633 return checkFormatStringExpr(
6634 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
6635 Args, APK, format_idx, firstDataArg, Type, CallType,
6636 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
6637 Offset, IgnoreStringsWithoutSpecifiers);
6638 }
6639 }
6640
6641 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
6642 Sema::FormatStringInfo CallerFSI;
6643 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
6644 PVFormat->getFirstArg(), &CallerFSI))
6645 continue;
6646 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
6647 // We also check if the formats are compatible.
6648 // We can't pass a 'scanf' string to a 'printf' function.
6649 if (Type != S.GetFormatStringType(PVFormat)) {
6650 S.Diag(Args[format_idx]->getBeginLoc(),
6651 diag::warn_format_string_type_incompatible)
6652 << PVFormat->getType()->getName()
6654 if (!InFunctionCall) {
6655 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
6656 }
6657 return SLCT_UncheckedLiteral;
6658 }
6659 // Lastly, check that argument passing kinds transition in a
6660 // way that makes sense:
6661 // from a caller with FAPK_VAList, allow FAPK_VAList
6662 // from a caller with FAPK_Fixed, allow FAPK_Fixed
6663 // from a caller with FAPK_Fixed, allow FAPK_Variadic
6664 // from a caller with FAPK_Variadic, allow FAPK_VAList
6665 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
6670 return SLCT_UncheckedLiteral;
6671 }
6672 }
6673 }
6674 }
6675 }
6676 }
6677
6678 return SLCT_NotALiteral;
6679 }
6680
6681 case Stmt::CallExprClass:
6682 case Stmt::CXXMemberCallExprClass: {
6683 const CallExpr *CE = cast<CallExpr>(E);
6684 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6685 bool IsFirst = true;
6686 StringLiteralCheckType CommonResult;
6687 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6688 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6689 StringLiteralCheckType Result = checkFormatStringExpr(
6690 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6691 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6692 Offset, IgnoreStringsWithoutSpecifiers);
6693 if (IsFirst) {
6694 CommonResult = Result;
6695 IsFirst = false;
6696 }
6697 }
6698 if (!IsFirst)
6699 return CommonResult;
6700
6701 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6702 unsigned BuiltinID = FD->getBuiltinID();
6703 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6704 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6705 const Expr *Arg = CE->getArg(0);
6706 return checkFormatStringExpr(
6707 S, ReferenceFormatString, Arg, Args, APK, format_idx,
6708 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6709 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6710 }
6711 }
6712 }
6713 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
6714 return checkFormatStringExpr(
6715 S, ReferenceFormatString, SLE, Args, APK, format_idx, firstDataArg,
6716 Type, CallType, /*InFunctionCall*/ false, CheckedVarArgs,
6717 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6718 return SLCT_NotALiteral;
6719 }
6720 case Stmt::ObjCMessageExprClass: {
6721 const auto *ME = cast<ObjCMessageExpr>(E);
6722 if (const auto *MD = ME->getMethodDecl()) {
6723 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6724 // As a special case heuristic, if we're using the method -[NSBundle
6725 // localizedStringForKey:value:table:], ignore any key strings that lack
6726 // format specifiers. The idea is that if the key doesn't have any
6727 // format specifiers then its probably just a key to map to the
6728 // localized strings. If it does have format specifiers though, then its
6729 // likely that the text of the key is the format string in the
6730 // programmer's language, and should be checked.
6731 const ObjCInterfaceDecl *IFace;
6732 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6733 IFace->getIdentifier()->isStr("NSBundle") &&
6734 MD->getSelector().isKeywordSelector(
6735 {"localizedStringForKey", "value", "table"})) {
6736 IgnoreStringsWithoutSpecifiers = true;
6737 }
6738
6739 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6740 return checkFormatStringExpr(
6741 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6742 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6743 Offset, IgnoreStringsWithoutSpecifiers);
6744 }
6745 }
6746
6747 return SLCT_NotALiteral;
6748 }
6749 case Stmt::ObjCStringLiteralClass:
6750 case Stmt::StringLiteralClass: {
6751 const StringLiteral *StrE = nullptr;
6752
6753 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6754 StrE = ObjCFExpr->getString();
6755 else
6756 StrE = cast<StringLiteral>(E);
6757
6758 if (StrE) {
6759 if (Offset.isNegative() || Offset > StrE->getLength()) {
6760 // TODO: It would be better to have an explicit warning for out of
6761 // bounds literals.
6762 return SLCT_NotALiteral;
6763 }
6764 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6765 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
6766 format_idx, firstDataArg, Type, InFunctionCall,
6767 CallType, CheckedVarArgs, UncoveredArg,
6768 IgnoreStringsWithoutSpecifiers);
6769 return SLCT_CheckedLiteral;
6770 }
6771
6772 return SLCT_NotALiteral;
6773 }
6774 case Stmt::BinaryOperatorClass: {
6775 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6776
6777 // A string literal + an int offset is still a string literal.
6778 if (BinOp->isAdditiveOp()) {
6779 Expr::EvalResult LResult, RResult;
6780
6781 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6782 LResult, S.Context, Expr::SE_NoSideEffects,
6784 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6785 RResult, S.Context, Expr::SE_NoSideEffects,
6787
6788 if (LIsInt != RIsInt) {
6789 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6790
6791 if (LIsInt) {
6792 if (BinOpKind == BO_Add) {
6793 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6794 E = BinOp->getRHS();
6795 goto tryAgain;
6796 }
6797 } else {
6798 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6799 E = BinOp->getLHS();
6800 goto tryAgain;
6801 }
6802 }
6803 }
6804
6805 return SLCT_NotALiteral;
6806 }
6807 case Stmt::UnaryOperatorClass: {
6808 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6809 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6810 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6811 Expr::EvalResult IndexResult;
6812 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6815 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6816 /*RHS is int*/ true);
6817 E = ASE->getBase();
6818 goto tryAgain;
6819 }
6820 }
6821
6822 return SLCT_NotALiteral;
6823 }
6824
6825 default:
6826 return SLCT_NotALiteral;
6827 }
6828}
6829
6830// If this expression can be evaluated at compile-time,
6831// check if the result is a StringLiteral and return it
6832// otherwise return nullptr
6834 const Expr *E) {
6835 Expr::EvalResult Result;
6836 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
6837 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
6838 if (isa_and_nonnull<StringLiteral>(LVE))
6839 return LVE;
6840 }
6841 return nullptr;
6842}
6843
6845 switch (FST) {
6847 return "scanf";
6849 return "printf";
6851 return "NSString";
6853 return "strftime";
6855 return "strfmon";
6857 return "kprintf";
6859 return "freebsd_kprintf";
6861 return "os_log";
6862 default:
6863 return "<unknown>";
6864 }
6865}
6866
6868 return llvm::StringSwitch<FormatStringType>(Flavor)
6869 .Cases("gnu_scanf", "scanf", FormatStringType::Scanf)
6870 .Cases("gnu_printf", "printf", "printf0", "syslog",
6872 .Cases("NSString", "CFString", FormatStringType::NSString)
6873 .Cases("gnu_strftime", "strftime", FormatStringType::Strftime)
6874 .Cases("gnu_strfmon", "strfmon", FormatStringType::Strfmon)
6875 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err",
6877 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
6878 .Case("os_trace", FormatStringType::OSLog)
6879 .Case("os_log", FormatStringType::OSLog)
6880 .Default(FormatStringType::Unknown);
6881}
6882
6884 return GetFormatStringType(Format->getType()->getName());
6885}
6886
6887FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
6888 return GetFormatStringType(Format->getType()->getName());
6889}
6890
6891bool Sema::CheckFormatArguments(const FormatAttr *Format,
6892 ArrayRef<const Expr *> Args, bool IsCXXMember,
6893 VariadicCallType CallType, SourceLocation Loc,
6894 SourceRange Range,
6895 llvm::SmallBitVector &CheckedVarArgs) {
6896 FormatStringInfo FSI;
6897 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
6898 IsCXXMember,
6899 CallType != VariadicCallType::DoesNotApply, &FSI))
6900 return CheckFormatArguments(
6901 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
6902 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
6903 return false;
6904}
6905
6906bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
6907 ArrayRef<const Expr *> Args, bool IsCXXMember,
6908 VariadicCallType CallType, SourceLocation Loc,
6909 SourceRange Range,
6910 llvm::SmallBitVector &CheckedVarArgs) {
6911 FormatStringInfo FSI;
6912 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
6913 &FSI)) {
6914 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
6915 return CheckFormatArguments(Args, FSI.ArgPassingKind,
6916 Format->getFormatString(), FSI.FormatIdx,
6917 FSI.FirstDataArg, GetFormatStringType(Format),
6918 CallType, Loc, Range, CheckedVarArgs);
6919 }
6920 return false;
6921}
6922
6923bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6925 const StringLiteral *ReferenceFormatString,
6926 unsigned format_idx, unsigned firstDataArg,
6928 VariadicCallType CallType, SourceLocation Loc,
6929 SourceRange Range,
6930 llvm::SmallBitVector &CheckedVarArgs) {
6931 // CHECK: printf/scanf-like function is called with no format string.
6932 if (format_idx >= Args.size()) {
6933 Diag(Loc, diag::warn_missing_format_string) << Range;
6934 return false;
6935 }
6936
6937 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6938
6939 // CHECK: format string is not a string literal.
6940 //
6941 // Dynamically generated format strings are difficult to
6942 // automatically vet at compile time. Requiring that format strings
6943 // are string literals: (1) permits the checking of format strings by
6944 // the compiler and thereby (2) can practically remove the source of
6945 // many format string exploits.
6946
6947 // Format string can be either ObjC string (e.g. @"%d") or
6948 // C string (e.g. "%d")
6949 // ObjC string uses the same format specifiers as C string, so we can use
6950 // the same format string checking logic for both ObjC and C strings.
6951 UncoveredArgHandler UncoveredArg;
6952 StringLiteralCheckType CT = checkFormatStringExpr(
6953 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
6954 firstDataArg, Type, CallType,
6955 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
6956 /*no string offset*/ llvm::APSInt(64, false) = 0);
6957
6958 // Generate a diagnostic where an uncovered argument is detected.
6959 if (UncoveredArg.hasUncoveredArg()) {
6960 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6961 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6962 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6963 }
6964
6965 if (CT != SLCT_NotALiteral)
6966 // Literal format string found, check done!
6967 return CT == SLCT_CheckedLiteral;
6968
6969 // Strftime is particular as it always uses a single 'time' argument,
6970 // so it is safe to pass a non-literal string.
6972 return false;
6973
6974 // Do not emit diag when the string param is a macro expansion and the
6975 // format is either NSString or CFString. This is a hack to prevent
6976 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6977 // which are usually used in place of NS and CF string literals.
6978 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6980 SourceMgr.isInSystemMacro(FormatLoc))
6981 return false;
6982
6983 // If there are no arguments specified, warn with -Wformat-security, otherwise
6984 // warn only with -Wformat-nonliteral.
6985 if (Args.size() == firstDataArg) {
6986 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6987 << OrigFormatExpr->getSourceRange();
6988 switch (Type) {
6989 default:
6990 break;
6994 Diag(FormatLoc, diag::note_format_security_fixit)
6995 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6996 break;
6998 Diag(FormatLoc, diag::note_format_security_fixit)
6999 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7000 break;
7001 }
7002 } else {
7003 Diag(FormatLoc, diag::warn_format_nonliteral)
7004 << OrigFormatExpr->getSourceRange();
7005 }
7006 return false;
7007}
7008
7009namespace {
7010
7011class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7012protected:
7013 Sema &S;
7014 const FormatStringLiteral *FExpr;
7015 const Expr *OrigFormatExpr;
7016 const FormatStringType FSType;
7017 const unsigned FirstDataArg;
7018 const unsigned NumDataArgs;
7019 const char *Beg; // Start of format string.
7020 const Sema::FormatArgumentPassingKind ArgPassingKind;
7021 ArrayRef<const Expr *> Args;
7022 unsigned FormatIdx;
7023 llvm::SmallBitVector CoveredArgs;
7024 bool usesPositionalArgs = false;
7025 bool atFirstArg = true;
7026 bool inFunctionCall;
7027 VariadicCallType CallType;
7028 llvm::SmallBitVector &CheckedVarArgs;
7029 UncoveredArgHandler &UncoveredArg;
7030
7031public:
7032 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7033 const Expr *origFormatExpr, const FormatStringType type,
7034 unsigned firstDataArg, unsigned numDataArgs,
7035 const char *beg, Sema::FormatArgumentPassingKind APK,
7036 ArrayRef<const Expr *> Args, unsigned formatIdx,
7037 bool inFunctionCall, VariadicCallType callType,
7038 llvm::SmallBitVector &CheckedVarArgs,
7039 UncoveredArgHandler &UncoveredArg)
7040 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7041 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7042 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7043 inFunctionCall(inFunctionCall), CallType(callType),
7044 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7045 CoveredArgs.resize(numDataArgs);
7046 CoveredArgs.reset();
7047 }
7048
7049 bool HasFormatArguments() const {
7050 return ArgPassingKind == Sema::FAPK_Fixed ||
7051 ArgPassingKind == Sema::FAPK_Variadic;
7052 }
7053
7054 void DoneProcessing();
7055
7056 void HandleIncompleteSpecifier(const char *startSpecifier,
7057 unsigned specifierLen) override;
7058
7059 void HandleInvalidLengthModifier(
7060 const analyze_format_string::FormatSpecifier &FS,
7061 const analyze_format_string::ConversionSpecifier &CS,
7062 const char *startSpecifier, unsigned specifierLen,
7063 unsigned DiagID);
7064
7065 void HandleNonStandardLengthModifier(
7066 const analyze_format_string::FormatSpecifier &FS,
7067 const char *startSpecifier, unsigned specifierLen);
7068
7069 void HandleNonStandardConversionSpecifier(
7070 const analyze_format_string::ConversionSpecifier &CS,
7071 const char *startSpecifier, unsigned specifierLen);
7072
7073 void HandlePosition(const char *startPos, unsigned posLen) override;
7074
7075 void HandleInvalidPosition(const char *startSpecifier,
7076 unsigned specifierLen,
7078
7079 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7080
7081 void HandleNullChar(const char *nullCharacter) override;
7082
7083 template <typename Range>
7084 static void
7085 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7086 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7087 bool IsStringLocation, Range StringRange,
7088 ArrayRef<FixItHint> Fixit = {});
7089
7090protected:
7091 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7092 const char *startSpec,
7093 unsigned specifierLen,
7094 const char *csStart, unsigned csLen);
7095
7096 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7097 const char *startSpec,
7098 unsigned specifierLen);
7099
7100 SourceRange getFormatStringRange();
7101 CharSourceRange getSpecifierRange(const char *startSpecifier,
7102 unsigned specifierLen);
7103 SourceLocation getLocationOfByte(const char *x);
7104
7105 const Expr *getDataArg(unsigned i) const;
7106
7107 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7108 const analyze_format_string::ConversionSpecifier &CS,
7109 const char *startSpecifier, unsigned specifierLen,
7110 unsigned argIndex);
7111
7112 template <typename Range>
7113 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7114 bool IsStringLocation, Range StringRange,
7115 ArrayRef<FixItHint> Fixit = {});
7116};
7117
7118} // namespace
7119
7120SourceRange CheckFormatHandler::getFormatStringRange() {
7121 return OrigFormatExpr->getSourceRange();
7122}
7123
7124CharSourceRange CheckFormatHandler::
7125getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7126 SourceLocation Start = getLocationOfByte(startSpecifier);
7127 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7128
7129 // Advance the end SourceLocation by one due to half-open ranges.
7130 End = End.getLocWithOffset(1);
7131
7132 return CharSourceRange::getCharRange(Start, End);
7133}
7134
7135SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7136 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7138}
7139
7140void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7141 unsigned specifierLen){
7142 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7143 getLocationOfByte(startSpecifier),
7144 /*IsStringLocation*/true,
7145 getSpecifierRange(startSpecifier, specifierLen));
7146}
7147
7148void CheckFormatHandler::HandleInvalidLengthModifier(
7151 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7152 using namespace analyze_format_string;
7153
7154 const LengthModifier &LM = FS.getLengthModifier();
7155 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7156
7157 // See if we know how to fix this length modifier.
7158 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7159 if (FixedLM) {
7160 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7161 getLocationOfByte(LM.getStart()),
7162 /*IsStringLocation*/true,
7163 getSpecifierRange(startSpecifier, specifierLen));
7164
7165 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7166 << FixedLM->toString()
7167 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7168
7169 } else {
7170 FixItHint Hint;
7171 if (DiagID == diag::warn_format_nonsensical_length)
7172 Hint = FixItHint::CreateRemoval(LMRange);
7173
7174 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7175 getLocationOfByte(LM.getStart()),
7176 /*IsStringLocation*/true,
7177 getSpecifierRange(startSpecifier, specifierLen),
7178 Hint);
7179 }
7180}
7181
7182void CheckFormatHandler::HandleNonStandardLengthModifier(
7184 const char *startSpecifier, unsigned specifierLen) {
7185 using namespace analyze_format_string;
7186
7187 const LengthModifier &LM = FS.getLengthModifier();
7188 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7189
7190 // See if we know how to fix this length modifier.
7191 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7192 if (FixedLM) {
7193 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7194 << LM.toString() << 0,
7195 getLocationOfByte(LM.getStart()),
7196 /*IsStringLocation*/true,
7197 getSpecifierRange(startSpecifier, specifierLen));
7198
7199 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7200 << FixedLM->toString()
7201 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7202
7203 } else {
7204 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7205 << LM.toString() << 0,
7206 getLocationOfByte(LM.getStart()),
7207 /*IsStringLocation*/true,
7208 getSpecifierRange(startSpecifier, specifierLen));
7209 }
7210}
7211
7212void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7214 const char *startSpecifier, unsigned specifierLen) {
7215 using namespace analyze_format_string;
7216
7217 // See if we know how to fix this conversion specifier.
7218 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7219 if (FixedCS) {
7220 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7221 << CS.toString() << /*conversion specifier*/1,
7222 getLocationOfByte(CS.getStart()),
7223 /*IsStringLocation*/true,
7224 getSpecifierRange(startSpecifier, specifierLen));
7225
7226 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7227 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7228 << FixedCS->toString()
7229 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7230 } else {
7231 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7232 << CS.toString() << /*conversion specifier*/1,
7233 getLocationOfByte(CS.getStart()),
7234 /*IsStringLocation*/true,
7235 getSpecifierRange(startSpecifier, specifierLen));
7236 }
7237}
7238
7239void CheckFormatHandler::HandlePosition(const char *startPos,
7240 unsigned posLen) {
7241 if (!S.getDiagnostics().isIgnored(
7242 diag::warn_format_non_standard_positional_arg, SourceLocation()))
7243 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7244 getLocationOfByte(startPos),
7245 /*IsStringLocation*/ true,
7246 getSpecifierRange(startPos, posLen));
7247}
7248
7249void CheckFormatHandler::HandleInvalidPosition(
7250 const char *startSpecifier, unsigned specifierLen,
7252 if (!S.getDiagnostics().isIgnored(
7253 diag::warn_format_invalid_positional_specifier, SourceLocation()))
7254 EmitFormatDiagnostic(
7255 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
7256 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
7257 getSpecifierRange(startSpecifier, specifierLen));
7258}
7259
7260void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7261 unsigned posLen) {
7262 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
7263 SourceLocation()))
7264 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7265 getLocationOfByte(startPos),
7266 /*IsStringLocation*/ true,
7267 getSpecifierRange(startPos, posLen));
7268}
7269
7270void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7271 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7272 // The presence of a null character is likely an error.
7273 EmitFormatDiagnostic(
7274 S.PDiag(diag::warn_printf_format_string_contains_null_char),
7275 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7276 getFormatStringRange());
7277 }
7278}
7279
7280// Note that this may return NULL if there was an error parsing or building
7281// one of the argument expressions.
7282const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7283 return Args[FirstDataArg + i];
7284}
7285
7286void CheckFormatHandler::DoneProcessing() {
7287 // Does the number of data arguments exceed the number of
7288 // format conversions in the format string?
7289 if (HasFormatArguments()) {
7290 // Find any arguments that weren't covered.
7291 CoveredArgs.flip();
7292 signed notCoveredArg = CoveredArgs.find_first();
7293 if (notCoveredArg >= 0) {
7294 assert((unsigned)notCoveredArg < NumDataArgs);
7295 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7296 } else {
7297 UncoveredArg.setAllCovered();
7298 }
7299 }
7300}
7301
7302void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7303 const Expr *ArgExpr) {
7304 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
7305 "Invalid state");
7306
7307 if (!ArgExpr)
7308 return;
7309
7310 SourceLocation Loc = ArgExpr->getBeginLoc();
7311
7312 if (S.getSourceManager().isInSystemMacro(Loc))
7313 return;
7314
7315 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7316 for (auto E : DiagnosticExprs)
7317 PDiag << E->getSourceRange();
7318
7319 CheckFormatHandler::EmitFormatDiagnostic(
7320 S, IsFunctionCall, DiagnosticExprs[0],
7321 PDiag, Loc, /*IsStringLocation*/false,
7322 DiagnosticExprs[0]->getSourceRange());
7323}
7324
7325bool
7326CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7327 SourceLocation Loc,
7328 const char *startSpec,
7329 unsigned specifierLen,
7330 const char *csStart,
7331 unsigned csLen) {
7332 bool keepGoing = true;
7333 if (argIndex < NumDataArgs) {
7334 // Consider the argument coverered, even though the specifier doesn't
7335 // make sense.
7336 CoveredArgs.set(argIndex);
7337 }
7338 else {
7339 // If argIndex exceeds the number of data arguments we
7340 // don't issue a warning because that is just a cascade of warnings (and
7341 // they may have intended '%%' anyway). We don't want to continue processing
7342 // the format string after this point, however, as we will like just get
7343 // gibberish when trying to match arguments.
7344 keepGoing = false;
7345 }
7346
7347 StringRef Specifier(csStart, csLen);
7348
7349 // If the specifier in non-printable, it could be the first byte of a UTF-8
7350 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7351 // hex value.
7352 std::string CodePointStr;
7353 if (!llvm::sys::locale::isPrint(*csStart)) {
7354 llvm::UTF32 CodePoint;
7355 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7356 const llvm::UTF8 *E =
7357 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7358 llvm::ConversionResult Result =
7359 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7360
7361 if (Result != llvm::conversionOK) {
7362 unsigned char FirstChar = *csStart;
7363 CodePoint = (llvm::UTF32)FirstChar;
7364 }
7365
7366 llvm::raw_string_ostream OS(CodePointStr);
7367 if (CodePoint < 256)
7368 OS << "\\x" << llvm::format("%02x", CodePoint);
7369 else if (CodePoint <= 0xFFFF)
7370 OS << "\\u" << llvm::format("%04x", CodePoint);
7371 else
7372 OS << "\\U" << llvm::format("%08x", CodePoint);
7373 Specifier = CodePointStr;
7374 }
7375
7376 EmitFormatDiagnostic(
7377 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7378 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7379
7380 return keepGoing;
7381}
7382
7383void
7384CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7385 const char *startSpec,
7386 unsigned specifierLen) {
7387 EmitFormatDiagnostic(
7388 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7389 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7390}
7391
7392bool
7393CheckFormatHandler::CheckNumArgs(
7396 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7397
7398 if (HasFormatArguments() && argIndex >= NumDataArgs) {
7400 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7401 << (argIndex+1) << NumDataArgs)
7402 : S.PDiag(diag::warn_printf_insufficient_data_args);
7403 EmitFormatDiagnostic(
7404 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7405 getSpecifierRange(startSpecifier, specifierLen));
7406
7407 // Since more arguments than conversion tokens are given, by extension
7408 // all arguments are covered, so mark this as so.
7409 UncoveredArg.setAllCovered();
7410 return false;
7411 }
7412 return true;
7413}
7414
7415template<typename Range>
7416void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7417 SourceLocation Loc,
7418 bool IsStringLocation,
7419 Range StringRange,
7420 ArrayRef<FixItHint> FixIt) {
7421 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7422 Loc, IsStringLocation, StringRange, FixIt);
7423}
7424
7425/// If the format string is not within the function call, emit a note
7426/// so that the function call and string are in diagnostic messages.
7427///
7428/// \param InFunctionCall if true, the format string is within the function
7429/// call and only one diagnostic message will be produced. Otherwise, an
7430/// extra note will be emitted pointing to location of the format string.
7431///
7432/// \param ArgumentExpr the expression that is passed as the format string
7433/// argument in the function call. Used for getting locations when two
7434/// diagnostics are emitted.
7435///
7436/// \param PDiag the callee should already have provided any strings for the
7437/// diagnostic message. This function only adds locations and fixits
7438/// to diagnostics.
7439///
7440/// \param Loc primary location for diagnostic. If two diagnostics are
7441/// required, one will be at Loc and a new SourceLocation will be created for
7442/// the other one.
7443///
7444/// \param IsStringLocation if true, Loc points to the format string should be
7445/// used for the note. Otherwise, Loc points to the argument list and will
7446/// be used with PDiag.
7447///
7448/// \param StringRange some or all of the string to highlight. This is
7449/// templated so it can accept either a CharSourceRange or a SourceRange.
7450///
7451/// \param FixIt optional fix it hint for the format string.
7452template <typename Range>
7453void CheckFormatHandler::EmitFormatDiagnostic(
7454 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7455 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7456 Range StringRange, ArrayRef<FixItHint> FixIt) {
7457 if (InFunctionCall) {
7458 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7459 D << StringRange;
7460 D << FixIt;
7461 } else {
7462 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7463 << ArgumentExpr->getSourceRange();
7464
7466 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7467 diag::note_format_string_defined);
7468
7469 Note << StringRange;
7470 Note << FixIt;
7471 }
7472}
7473
7474//===--- CHECK: Printf format string checking -----------------------------===//
7475
7476namespace {
7477
7478class CheckPrintfHandler : public CheckFormatHandler {
7479public:
7480 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7481 const Expr *origFormatExpr, const FormatStringType type,
7482 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
7483 const char *beg, Sema::FormatArgumentPassingKind APK,
7484 ArrayRef<const Expr *> Args, unsigned formatIdx,
7485 bool inFunctionCall, VariadicCallType CallType,
7486 llvm::SmallBitVector &CheckedVarArgs,
7487 UncoveredArgHandler &UncoveredArg)
7488 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7489 numDataArgs, beg, APK, Args, formatIdx,
7490 inFunctionCall, CallType, CheckedVarArgs,
7491 UncoveredArg) {}
7492
7493 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
7494
7495 /// Returns true if '%@' specifiers are allowed in the format string.
7496 bool allowsObjCArg() const {
7497 return FSType == FormatStringType::NSString ||
7498 FSType == FormatStringType::OSLog ||
7499 FSType == FormatStringType::OSTrace;
7500 }
7501
7502 bool HandleInvalidPrintfConversionSpecifier(
7503 const analyze_printf::PrintfSpecifier &FS,
7504 const char *startSpecifier,
7505 unsigned specifierLen) override;
7506
7507 void handleInvalidMaskType(StringRef MaskType) override;
7508
7509 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7510 const char *startSpecifier, unsigned specifierLen,
7511 const TargetInfo &Target) override;
7512 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7513 const char *StartSpecifier,
7514 unsigned SpecifierLen,
7515 const Expr *E);
7516
7517 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7518 const char *startSpecifier, unsigned specifierLen);
7519 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7520 const analyze_printf::OptionalAmount &Amt,
7521 unsigned type,
7522 const char *startSpecifier, unsigned specifierLen);
7523 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7524 const analyze_printf::OptionalFlag &flag,
7525 const char *startSpecifier, unsigned specifierLen);
7526 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7527 const analyze_printf::OptionalFlag &ignoredFlag,
7528 const analyze_printf::OptionalFlag &flag,
7529 const char *startSpecifier, unsigned specifierLen);
7530 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7531 const Expr *E);
7532
7533 void HandleEmptyObjCModifierFlag(const char *startFlag,
7534 unsigned flagLen) override;
7535
7536 void HandleInvalidObjCModifierFlag(const char *startFlag,
7537 unsigned flagLen) override;
7538
7539 void
7540 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7541 const char *flagsEnd,
7542 const char *conversionPosition) override;
7543};
7544
7545/// Keeps around the information needed to verify that two specifiers are
7546/// compatible.
7547class EquatableFormatArgument {
7548public:
7549 enum SpecifierSensitivity : unsigned {
7550 SS_None,
7551 SS_Private,
7552 SS_Public,
7553 SS_Sensitive
7554 };
7555
7556 enum FormatArgumentRole : unsigned {
7557 FAR_Data,
7558 FAR_FieldWidth,
7559 FAR_Precision,
7560 FAR_Auxiliary, // FreeBSD kernel %b and %D
7561 };
7562
7563private:
7564 analyze_format_string::ArgType ArgType;
7566 StringRef SpecifierLetter;
7567 CharSourceRange Range;
7568 SourceLocation ElementLoc;
7569 FormatArgumentRole Role : 2;
7570 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
7571 unsigned Position : 14;
7572 unsigned ModifierFor : 14; // not set for FAR_Data
7573
7574 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
7575 bool InFunctionCall) const;
7576
7577public:
7578 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
7580 StringRef SpecifierLetter,
7581 analyze_format_string::ArgType ArgType,
7582 FormatArgumentRole Role,
7583 SpecifierSensitivity Sensitivity, unsigned Position,
7584 unsigned ModifierFor)
7585 : ArgType(ArgType), LengthMod(LengthMod),
7586 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
7587 Role(Role), Sensitivity(Sensitivity), Position(Position),
7588 ModifierFor(ModifierFor) {}
7589
7590 unsigned getPosition() const { return Position; }
7591 SourceLocation getSourceLocation() const { return ElementLoc; }
7592 CharSourceRange getSourceRange() const { return Range; }
7593 analyze_format_string::LengthModifier getLengthModifier() const {
7594 return analyze_format_string::LengthModifier(nullptr, LengthMod);
7595 }
7596 void setModifierFor(unsigned V) { ModifierFor = V; }
7597
7598 std::string buildFormatSpecifier() const {
7599 std::string result;
7600 llvm::raw_string_ostream(result)
7601 << getLengthModifier().toString() << SpecifierLetter;
7602 return result;
7603 }
7604
7605 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
7606 const Expr *FmtExpr, bool InFunctionCall) const;
7607};
7608
7609/// Turns format strings into lists of EquatableSpecifier objects.
7610class DecomposePrintfHandler : public CheckPrintfHandler {
7611 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
7612 bool HadError;
7613
7614 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7615 const Expr *origFormatExpr,
7616 const FormatStringType type, unsigned firstDataArg,
7617 unsigned numDataArgs, bool isObjC, const char *beg,
7619 ArrayRef<const Expr *> Args, unsigned formatIdx,
7620 bool inFunctionCall, VariadicCallType CallType,
7621 llvm::SmallBitVector &CheckedVarArgs,
7622 UncoveredArgHandler &UncoveredArg,
7623 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
7624 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7625 numDataArgs, isObjC, beg, APK, Args, formatIdx,
7626 inFunctionCall, CallType, CheckedVarArgs,
7627 UncoveredArg),
7628 Specs(Specs), HadError(false) {}
7629
7630public:
7631 static bool
7632 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
7633 FormatStringType type, bool IsObjC, bool InFunctionCall,
7634 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
7635
7636 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7637 const char *startSpecifier,
7638 unsigned specifierLen,
7639 const TargetInfo &Target) override;
7640};
7641
7642} // namespace
7643
7644bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7645 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
7646 unsigned specifierLen) {
7649
7650 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7651 getLocationOfByte(CS.getStart()),
7652 startSpecifier, specifierLen,
7653 CS.getStart(), CS.getLength());
7654}
7655
7656void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7657 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7658}
7659
7660// Error out if struct or complex type argments are passed to os_log.
7662 QualType T) {
7663 if (FSType != FormatStringType::OSLog)
7664 return false;
7665 return T->isRecordType() || T->isComplexType();
7666}
7667
7668bool CheckPrintfHandler::HandleAmount(
7669 const analyze_format_string::OptionalAmount &Amt, unsigned k,
7670 const char *startSpecifier, unsigned specifierLen) {
7671 if (Amt.hasDataArgument()) {
7672 if (HasFormatArguments()) {
7673 unsigned argIndex = Amt.getArgIndex();
7674 if (argIndex >= NumDataArgs) {
7675 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7676 << k,
7677 getLocationOfByte(Amt.getStart()),
7678 /*IsStringLocation*/ true,
7679 getSpecifierRange(startSpecifier, specifierLen));
7680 // Don't do any more checking. We will just emit
7681 // spurious errors.
7682 return false;
7683 }
7684
7685 // Type check the data argument. It should be an 'int'.
7686 // Although not in conformance with C99, we also allow the argument to be
7687 // an 'unsigned int' as that is a reasonably safe case. GCC also
7688 // doesn't emit a warning for that case.
7689 CoveredArgs.set(argIndex);
7690 const Expr *Arg = getDataArg(argIndex);
7691 if (!Arg)
7692 return false;
7693
7694 QualType T = Arg->getType();
7695
7696 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7697 assert(AT.isValid());
7698
7699 if (!AT.matchesType(S.Context, T)) {
7700 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
7701 ? diag::err_printf_asterisk_wrong_type
7702 : diag::warn_printf_asterisk_wrong_type;
7703 EmitFormatDiagnostic(S.PDiag(DiagID)
7705 << T << Arg->getSourceRange(),
7706 getLocationOfByte(Amt.getStart()),
7707 /*IsStringLocation*/ true,
7708 getSpecifierRange(startSpecifier, specifierLen));
7709 // Don't do any more checking. We will just emit
7710 // spurious errors.
7711 return false;
7712 }
7713 }
7714 }
7715 return true;
7716}
7717
7718void CheckPrintfHandler::HandleInvalidAmount(
7721 unsigned type,
7722 const char *startSpecifier,
7723 unsigned specifierLen) {
7726
7727 FixItHint fixit =
7729 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7730 Amt.getConstantLength()))
7731 : FixItHint();
7732
7733 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7734 << type << CS.toString(),
7735 getLocationOfByte(Amt.getStart()),
7736 /*IsStringLocation*/true,
7737 getSpecifierRange(startSpecifier, specifierLen),
7738 fixit);
7739}
7740
7741void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7742 const analyze_printf::OptionalFlag &flag,
7743 const char *startSpecifier,
7744 unsigned specifierLen) {
7745 // Warn about pointless flag with a fixit removal.
7748 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7749 << flag.toString() << CS.toString(),
7750 getLocationOfByte(flag.getPosition()),
7751 /*IsStringLocation*/true,
7752 getSpecifierRange(startSpecifier, specifierLen),
7754 getSpecifierRange(flag.getPosition(), 1)));
7755}
7756
7757void CheckPrintfHandler::HandleIgnoredFlag(
7759 const analyze_printf::OptionalFlag &ignoredFlag,
7760 const analyze_printf::OptionalFlag &flag,
7761 const char *startSpecifier,
7762 unsigned specifierLen) {
7763 // Warn about ignored flag with a fixit removal.
7764 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7765 << ignoredFlag.toString() << flag.toString(),
7766 getLocationOfByte(ignoredFlag.getPosition()),
7767 /*IsStringLocation*/true,
7768 getSpecifierRange(startSpecifier, specifierLen),
7770 getSpecifierRange(ignoredFlag.getPosition(), 1)));
7771}
7772
7773void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7774 unsigned flagLen) {
7775 // Warn about an empty flag.
7776 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7777 getLocationOfByte(startFlag),
7778 /*IsStringLocation*/true,
7779 getSpecifierRange(startFlag, flagLen));
7780}
7781
7782void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7783 unsigned flagLen) {
7784 // Warn about an invalid flag.
7785 auto Range = getSpecifierRange(startFlag, flagLen);
7786 StringRef flag(startFlag, flagLen);
7787 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7788 getLocationOfByte(startFlag),
7789 /*IsStringLocation*/true,
7790 Range, FixItHint::CreateRemoval(Range));
7791}
7792
7793void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7794 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7795 // Warn about using '[...]' without a '@' conversion.
7796 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7797 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7798 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7799 getLocationOfByte(conversionPosition),
7800 /*IsStringLocation*/ true, Range,
7802}
7803
7804void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
7805 const Expr *FmtExpr,
7806 bool InFunctionCall) const {
7807 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
7808 ElementLoc, true, Range);
7809}
7810
7811bool EquatableFormatArgument::VerifyCompatible(
7812 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
7813 bool InFunctionCall) const {
7815 if (Role != Other.Role) {
7816 // diagnose and stop
7817 EmitDiagnostic(
7818 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
7819 FmtExpr, InFunctionCall);
7820 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
7821 return false;
7822 }
7823
7824 if (Role != FAR_Data) {
7825 if (ModifierFor != Other.ModifierFor) {
7826 // diagnose and stop
7827 EmitDiagnostic(S,
7828 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
7829 << (ModifierFor + 1) << (Other.ModifierFor + 1),
7830 FmtExpr, InFunctionCall);
7831 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
7832 return false;
7833 }
7834 return true;
7835 }
7836
7837 bool HadError = false;
7838 if (Sensitivity != Other.Sensitivity) {
7839 // diagnose and continue
7840 EmitDiagnostic(S,
7841 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
7842 << Sensitivity << Other.Sensitivity,
7843 FmtExpr, InFunctionCall);
7844 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7845 << 0 << Other.Range;
7846 }
7847
7848 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
7849 case MK::Match:
7850 break;
7851
7852 case MK::MatchPromotion:
7853 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
7854 // MatchPromotion is treated as a failure by format_matches.
7855 case MK::NoMatch:
7856 case MK::NoMatchTypeConfusion:
7857 case MK::NoMatchPromotionTypeConfusion:
7858 EmitDiagnostic(S,
7859 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
7860 << buildFormatSpecifier()
7861 << Other.buildFormatSpecifier(),
7862 FmtExpr, InFunctionCall);
7863 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7864 << 0 << Other.Range;
7865 break;
7866
7867 case MK::NoMatchPedantic:
7868 EmitDiagnostic(S,
7869 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
7870 << buildFormatSpecifier()
7871 << Other.buildFormatSpecifier(),
7872 FmtExpr, InFunctionCall);
7873 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7874 << 0 << Other.Range;
7875 break;
7876
7877 case MK::NoMatchSignedness:
7878 EmitDiagnostic(S,
7879 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
7880 << buildFormatSpecifier()
7881 << Other.buildFormatSpecifier(),
7882 FmtExpr, InFunctionCall);
7883 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7884 << 0 << Other.Range;
7885 break;
7886 }
7887 return !HadError;
7888}
7889
7890bool DecomposePrintfHandler::GetSpecifiers(
7891 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
7892 FormatStringType Type, bool IsObjC, bool InFunctionCall,
7894 StringRef Data = FSL->getString();
7895 const char *Str = Data.data();
7896 llvm::SmallBitVector BV;
7897 UncoveredArgHandler UA;
7898 const Expr *PrintfArgs[] = {FSL->getFormatString()};
7899 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
7900 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
7901 InFunctionCall, VariadicCallType::DoesNotApply, BV,
7902 UA, Args);
7903
7905 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
7907 H.DoneProcessing();
7908 if (H.HadError)
7909 return false;
7910
7911 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
7912 const EquatableFormatArgument &B) {
7913 return A.getPosition() < B.getPosition();
7914 });
7915 return true;
7916}
7917
7918bool DecomposePrintfHandler::HandlePrintfSpecifier(
7919 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
7920 unsigned specifierLen, const TargetInfo &Target) {
7921 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
7922 specifierLen, Target)) {
7923 HadError = true;
7924 return false;
7925 }
7926
7927 // Do not add any specifiers to the list for %%. This is possibly incorrect
7928 // if using a precision/width with a data argument, but that combination is
7929 // meaningless and we wouldn't know which format to attach the
7930 // precision/width to.
7931 const auto &CS = FS.getConversionSpecifier();
7933 return true;
7934
7935 // have to patch these to have the right ModifierFor if they are used
7936 const unsigned Unset = ~0;
7937 unsigned FieldWidthIndex = Unset;
7938 unsigned PrecisionIndex = Unset;
7939
7940 // field width?
7941 const auto &FieldWidth = FS.getFieldWidth();
7942 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
7943 FieldWidthIndex = Specs.size();
7944 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
7945 getLocationOfByte(FieldWidth.getStart()),
7947 FieldWidth.getArgType(S.Context),
7948 EquatableFormatArgument::FAR_FieldWidth,
7949 EquatableFormatArgument::SS_None,
7950 FieldWidth.usesPositionalArg()
7951 ? FieldWidth.getPositionalArgIndex() - 1
7952 : FieldWidthIndex,
7953 0);
7954 }
7955 // precision?
7956 const auto &Precision = FS.getPrecision();
7957 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
7958 PrecisionIndex = Specs.size();
7959 Specs.emplace_back(
7960 getSpecifierRange(startSpecifier, specifierLen),
7961 getLocationOfByte(Precision.getStart()),
7963 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
7964 EquatableFormatArgument::SS_None,
7965 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
7966 : PrecisionIndex,
7967 0);
7968 }
7969
7970 // this specifier
7971 unsigned SpecIndex =
7972 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
7973 if (FieldWidthIndex != Unset)
7974 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
7975 if (PrecisionIndex != Unset)
7976 Specs[PrecisionIndex].setModifierFor(SpecIndex);
7977
7978 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
7979 if (FS.isPrivate())
7980 Sensitivity = EquatableFormatArgument::SS_Private;
7981 else if (FS.isPublic())
7982 Sensitivity = EquatableFormatArgument::SS_Public;
7983 else if (FS.isSensitive())
7984 Sensitivity = EquatableFormatArgument::SS_Sensitive;
7985 else
7986 Sensitivity = EquatableFormatArgument::SS_None;
7987
7988 Specs.emplace_back(
7989 getSpecifierRange(startSpecifier, specifierLen),
7990 getLocationOfByte(CS.getStart()), FS.getLengthModifier().getKind(),
7991 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
7992 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
7993
7994 // auxiliary argument?
7997 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
7998 getLocationOfByte(CS.getStart()),
8000 CS.getCharacters(),
8002 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
8003 SpecIndex + 1, SpecIndex);
8004 }
8005 return true;
8006}
8007
8008// Determines if the specified is a C++ class or struct containing
8009// a member with the specified name and kind (e.g. a CXXMethodDecl named
8010// "c_str()").
8011template<typename MemberKind>
8013CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8014 auto *RD = Ty->getAsCXXRecordDecl();
8016
8017 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8018 return Results;
8019
8020 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8023
8024 // We just need to include all members of the right kind turned up by the
8025 // filter, at this point.
8026 if (S.LookupQualifiedName(R, RD))
8027 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8028 NamedDecl *decl = (*I)->getUnderlyingDecl();
8029 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8030 Results.insert(FK);
8031 }
8032 return Results;
8033}
8034
8035/// Check if we could call '.c_str()' on an object.
8036///
8037/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8038/// allow the call, or if it would be ambiguous).
8040 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8041
8042 MethodSet Results =
8043 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8044 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8045 MI != ME; ++MI)
8046 if ((*MI)->getMinRequiredArguments() == 0)
8047 return true;
8048 return false;
8049}
8050
8051// Check if a (w)string was passed when a (w)char* was needed, and offer a
8052// better diagnostic if so. AT is assumed to be valid.
8053// Returns true when a c_str() conversion method is found.
8054bool CheckPrintfHandler::checkForCStrMembers(
8055 const analyze_printf::ArgType &AT, const Expr *E) {
8056 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8057
8058 MethodSet Results =
8060
8061 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8062 MI != ME; ++MI) {
8063 const CXXMethodDecl *Method = *MI;
8064 if (Method->getMinRequiredArguments() == 0 &&
8065 AT.matchesType(S.Context, Method->getReturnType())) {
8066 // FIXME: Suggest parens if the expression needs them.
8068 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8069 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8070 return true;
8071 }
8072 }
8073
8074 return false;
8075}
8076
8077bool CheckPrintfHandler::HandlePrintfSpecifier(
8078 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8079 unsigned specifierLen, const TargetInfo &Target) {
8080 using namespace analyze_format_string;
8081 using namespace analyze_printf;
8082
8083 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8084
8085 if (FS.consumesDataArgument()) {
8086 if (atFirstArg) {
8087 atFirstArg = false;
8088 usesPositionalArgs = FS.usesPositionalArg();
8089 }
8090 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8091 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8092 startSpecifier, specifierLen);
8093 return false;
8094 }
8095 }
8096
8097 // First check if the field width, precision, and conversion specifier
8098 // have matching data arguments.
8099 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8100 startSpecifier, specifierLen)) {
8101 return false;
8102 }
8103
8104 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8105 startSpecifier, specifierLen)) {
8106 return false;
8107 }
8108
8109 if (!CS.consumesDataArgument()) {
8110 // FIXME: Technically specifying a precision or field width here
8111 // makes no sense. Worth issuing a warning at some point.
8112 return true;
8113 }
8114
8115 // Consume the argument.
8116 unsigned argIndex = FS.getArgIndex();
8117 if (argIndex < NumDataArgs) {
8118 // The check to see if the argIndex is valid will come later.
8119 // We set the bit here because we may exit early from this
8120 // function if we encounter some other error.
8121 CoveredArgs.set(argIndex);
8122 }
8123
8124 // FreeBSD kernel extensions.
8125 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8126 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8127 // We need at least two arguments.
8128 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8129 return false;
8130
8131 if (HasFormatArguments()) {
8132 // Claim the second argument.
8133 CoveredArgs.set(argIndex + 1);
8134
8135 // Type check the first argument (int for %b, pointer for %D)
8136 const Expr *Ex = getDataArg(argIndex);
8137 const analyze_printf::ArgType &AT =
8138 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8139 ? ArgType(S.Context.IntTy)
8140 : ArgType::CPointerTy;
8141 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8142 EmitFormatDiagnostic(
8143 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8144 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8145 << false << Ex->getSourceRange(),
8146 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8147 getSpecifierRange(startSpecifier, specifierLen));
8148
8149 // Type check the second argument (char * for both %b and %D)
8150 Ex = getDataArg(argIndex + 1);
8152 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8153 EmitFormatDiagnostic(
8154 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8155 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8156 << false << Ex->getSourceRange(),
8157 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8158 getSpecifierRange(startSpecifier, specifierLen));
8159 }
8160 return true;
8161 }
8162
8163 // Check for using an Objective-C specific conversion specifier
8164 // in a non-ObjC literal.
8165 if (!allowsObjCArg() && CS.isObjCArg()) {
8166 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8167 specifierLen);
8168 }
8169
8170 // %P can only be used with os_log.
8171 if (FSType != FormatStringType::OSLog &&
8172 CS.getKind() == ConversionSpecifier::PArg) {
8173 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8174 specifierLen);
8175 }
8176
8177 // %n is not allowed with os_log.
8178 if (FSType == FormatStringType::OSLog &&
8179 CS.getKind() == ConversionSpecifier::nArg) {
8180 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8181 getLocationOfByte(CS.getStart()),
8182 /*IsStringLocation*/ false,
8183 getSpecifierRange(startSpecifier, specifierLen));
8184
8185 return true;
8186 }
8187
8188 // Only scalars are allowed for os_trace.
8189 if (FSType == FormatStringType::OSTrace &&
8190 (CS.getKind() == ConversionSpecifier::PArg ||
8191 CS.getKind() == ConversionSpecifier::sArg ||
8192 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8193 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8194 specifierLen);
8195 }
8196
8197 // Check for use of public/private annotation outside of os_log().
8198 if (FSType != FormatStringType::OSLog) {
8199 if (FS.isPublic().isSet()) {
8200 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8201 << "public",
8202 getLocationOfByte(FS.isPublic().getPosition()),
8203 /*IsStringLocation*/ false,
8204 getSpecifierRange(startSpecifier, specifierLen));
8205 }
8206 if (FS.isPrivate().isSet()) {
8207 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8208 << "private",
8209 getLocationOfByte(FS.isPrivate().getPosition()),
8210 /*IsStringLocation*/ false,
8211 getSpecifierRange(startSpecifier, specifierLen));
8212 }
8213 }
8214
8215 const llvm::Triple &Triple = Target.getTriple();
8216 if (CS.getKind() == ConversionSpecifier::nArg &&
8217 (Triple.isAndroid() || Triple.isOSFuchsia())) {
8218 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
8219 getLocationOfByte(CS.getStart()),
8220 /*IsStringLocation*/ false,
8221 getSpecifierRange(startSpecifier, specifierLen));
8222 }
8223
8224 // Check for invalid use of field width
8225 if (!FS.hasValidFieldWidth()) {
8226 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8227 startSpecifier, specifierLen);
8228 }
8229
8230 // Check for invalid use of precision
8231 if (!FS.hasValidPrecision()) {
8232 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8233 startSpecifier, specifierLen);
8234 }
8235
8236 // Precision is mandatory for %P specifier.
8237 if (CS.getKind() == ConversionSpecifier::PArg &&
8239 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8240 getLocationOfByte(startSpecifier),
8241 /*IsStringLocation*/ false,
8242 getSpecifierRange(startSpecifier, specifierLen));
8243 }
8244
8245 // Check each flag does not conflict with any other component.
8247 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8248 if (!FS.hasValidLeadingZeros())
8249 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8250 if (!FS.hasValidPlusPrefix())
8251 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8252 if (!FS.hasValidSpacePrefix())
8253 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8254 if (!FS.hasValidAlternativeForm())
8255 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8256 if (!FS.hasValidLeftJustified())
8257 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8258
8259 // Check that flags are not ignored by another flag
8260 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8261 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8262 startSpecifier, specifierLen);
8263 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8264 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8265 startSpecifier, specifierLen);
8266
8267 // Check the length modifier is valid with the given conversion specifier.
8269 S.getLangOpts()))
8270 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8271 diag::warn_format_nonsensical_length);
8272 else if (!FS.hasStandardLengthModifier())
8273 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8275 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8276 diag::warn_format_non_standard_conversion_spec);
8277
8279 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8280
8281 // The remaining checks depend on the data arguments.
8282 if (!HasFormatArguments())
8283 return true;
8284
8285 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8286 return false;
8287
8288 const Expr *Arg = getDataArg(argIndex);
8289 if (!Arg)
8290 return true;
8291
8292 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8293}
8294
8295static bool requiresParensToAddCast(const Expr *E) {
8296 // FIXME: We should have a general way to reason about operator
8297 // precedence and whether parens are actually needed here.
8298 // Take care of a few common cases where they aren't.
8299 const Expr *Inside = E->IgnoreImpCasts();
8300 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8301 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8302
8303 switch (Inside->getStmtClass()) {
8304 case Stmt::ArraySubscriptExprClass:
8305 case Stmt::CallExprClass:
8306 case Stmt::CharacterLiteralClass:
8307 case Stmt::CXXBoolLiteralExprClass:
8308 case Stmt::DeclRefExprClass:
8309 case Stmt::FloatingLiteralClass:
8310 case Stmt::IntegerLiteralClass:
8311 case Stmt::MemberExprClass:
8312 case Stmt::ObjCArrayLiteralClass:
8313 case Stmt::ObjCBoolLiteralExprClass:
8314 case Stmt::ObjCBoxedExprClass:
8315 case Stmt::ObjCDictionaryLiteralClass:
8316 case Stmt::ObjCEncodeExprClass:
8317 case Stmt::ObjCIvarRefExprClass:
8318 case Stmt::ObjCMessageExprClass:
8319 case Stmt::ObjCPropertyRefExprClass:
8320 case Stmt::ObjCStringLiteralClass:
8321 case Stmt::ObjCSubscriptRefExprClass:
8322 case Stmt::ParenExprClass:
8323 case Stmt::StringLiteralClass:
8324 case Stmt::UnaryOperatorClass:
8325 return false;
8326 default:
8327 return true;
8328 }
8329}
8330
8331static std::pair<QualType, StringRef>
8333 QualType IntendedTy,
8334 const Expr *E) {
8335 // Use a 'while' to peel off layers of typedefs.
8336 QualType TyTy = IntendedTy;
8337 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8338 StringRef Name = UserTy->getDecl()->getName();
8339 QualType CastTy = llvm::StringSwitch<QualType>(Name)
8340 .Case("CFIndex", Context.getNSIntegerType())
8341 .Case("NSInteger", Context.getNSIntegerType())
8342 .Case("NSUInteger", Context.getNSUIntegerType())
8343 .Case("SInt32", Context.IntTy)
8344 .Case("UInt32", Context.UnsignedIntTy)
8345 .Default(QualType());
8346
8347 if (!CastTy.isNull())
8348 return std::make_pair(CastTy, Name);
8349
8350 TyTy = UserTy->desugar();
8351 }
8352
8353 // Strip parens if necessary.
8354 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8355 return shouldNotPrintDirectly(Context,
8356 PE->getSubExpr()->getType(),
8357 PE->getSubExpr());
8358
8359 // If this is a conditional expression, then its result type is constructed
8360 // via usual arithmetic conversions and thus there might be no necessary
8361 // typedef sugar there. Recurse to operands to check for NSInteger &
8362 // Co. usage condition.
8363 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8364 QualType TrueTy, FalseTy;
8365 StringRef TrueName, FalseName;
8366
8367 std::tie(TrueTy, TrueName) =
8368 shouldNotPrintDirectly(Context,
8369 CO->getTrueExpr()->getType(),
8370 CO->getTrueExpr());
8371 std::tie(FalseTy, FalseName) =
8372 shouldNotPrintDirectly(Context,
8373 CO->getFalseExpr()->getType(),
8374 CO->getFalseExpr());
8375
8376 if (TrueTy == FalseTy)
8377 return std::make_pair(TrueTy, TrueName);
8378 else if (TrueTy.isNull())
8379 return std::make_pair(FalseTy, FalseName);
8380 else if (FalseTy.isNull())
8381 return std::make_pair(TrueTy, TrueName);
8382 }
8383
8384 return std::make_pair(QualType(), StringRef());
8385}
8386
8387/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8388/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8389/// type do not count.
8390static bool
8392 QualType From = ICE->getSubExpr()->getType();
8393 QualType To = ICE->getType();
8394 // It's an integer promotion if the destination type is the promoted
8395 // source type.
8396 if (ICE->getCastKind() == CK_IntegralCast &&
8398 S.Context.getPromotedIntegerType(From) == To)
8399 return true;
8400 // Look through vector types, since we do default argument promotion for
8401 // those in OpenCL.
8402 if (const auto *VecTy = From->getAs<ExtVectorType>())
8403 From = VecTy->getElementType();
8404 if (const auto *VecTy = To->getAs<ExtVectorType>())
8405 To = VecTy->getElementType();
8406 // It's a floating promotion if the source type is a lower rank.
8407 return ICE->getCastKind() == CK_FloatingCast &&
8408 S.Context.getFloatingTypeOrder(From, To) < 0;
8409}
8410
8413 DiagnosticsEngine &Diags, SourceLocation Loc) {
8415 if (Diags.isIgnored(
8416 diag::warn_format_conversion_argument_type_mismatch_signedness,
8417 Loc) ||
8418 Diags.isIgnored(
8419 // Arbitrary -Wformat diagnostic to detect -Wno-format:
8420 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
8422 }
8423 }
8424 return Match;
8425}
8426
8427bool
8428CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8429 const char *StartSpecifier,
8430 unsigned SpecifierLen,
8431 const Expr *E) {
8432 using namespace analyze_format_string;
8433 using namespace analyze_printf;
8434
8435 // Now type check the data expression that matches the
8436 // format specifier.
8437 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8438 if (!AT.isValid())
8439 return true;
8440
8441 QualType ExprTy = E->getType();
8442 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8443 ExprTy = TET->getUnderlyingExpr()->getType();
8444 }
8445
8446 // When using the format attribute in C++, you can receive a function or an
8447 // array that will necessarily decay to a pointer when passed to the final
8448 // format consumer. Apply decay before type comparison.
8449 if (ExprTy->canDecayToPointerType())
8450 ExprTy = S.Context.getDecayedType(ExprTy);
8451
8452 // Diagnose attempts to print a boolean value as a character. Unlike other
8453 // -Wformat diagnostics, this is fine from a type perspective, but it still
8454 // doesn't make sense.
8457 const CharSourceRange &CSR =
8458 getSpecifierRange(StartSpecifier, SpecifierLen);
8459 SmallString<4> FSString;
8460 llvm::raw_svector_ostream os(FSString);
8461 FS.toString(os);
8462 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8463 << FSString,
8464 E->getExprLoc(), false, CSR);
8465 return true;
8466 }
8467
8468 // Diagnose attempts to use '%P' with ObjC object types, which will result in
8469 // dumping raw class data (like is-a pointer), not actual data.
8471 ExprTy->isObjCObjectPointerType()) {
8472 const CharSourceRange &CSR =
8473 getSpecifierRange(StartSpecifier, SpecifierLen);
8474 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
8475 E->getExprLoc(), false, CSR);
8476 return true;
8477 }
8478
8479 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
8481 ArgType::MatchKind OrigMatch = Match;
8482
8484 if (Match == ArgType::Match)
8485 return true;
8486
8487 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
8488 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
8489
8490 // Look through argument promotions for our error message's reported type.
8491 // This includes the integral and floating promotions, but excludes array
8492 // and function pointer decay (seeing that an argument intended to be a
8493 // string has type 'char [6]' is probably more confusing than 'char *') and
8494 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8495 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8496 if (isArithmeticArgumentPromotion(S, ICE)) {
8497 E = ICE->getSubExpr();
8498 ExprTy = E->getType();
8499
8500 // Check if we didn't match because of an implicit cast from a 'char'
8501 // or 'short' to an 'int'. This is done because printf is a varargs
8502 // function.
8503 if (ICE->getType() == S.Context.IntTy ||
8504 ICE->getType() == S.Context.UnsignedIntTy) {
8505 // All further checking is done on the subexpression
8506 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
8507 if (OrigMatch == ArgType::NoMatchSignedness &&
8508 ImplicitMatch != ArgType::NoMatchSignedness)
8509 // If the original match was a signedness match this match on the
8510 // implicit cast type also need to be signedness match otherwise we
8511 // might introduce new unexpected warnings from -Wformat-signedness.
8512 return true;
8513 ImplicitMatch = handleFormatSignedness(
8514 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
8515 if (ImplicitMatch == ArgType::Match)
8516 return true;
8517 }
8518 }
8519 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8520 // Special case for 'a', which has type 'int' in C.
8521 // Note, however, that we do /not/ want to treat multibyte constants like
8522 // 'MooV' as characters! This form is deprecated but still exists. In
8523 // addition, don't treat expressions as of type 'char' if one byte length
8524 // modifier is provided.
8525 if (ExprTy == S.Context.IntTy &&
8527 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
8528 ExprTy = S.Context.CharTy;
8529 // To improve check results, we consider a character literal in C
8530 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
8531 // more likely a type confusion situation, so we will suggest to
8532 // use '%hhd' instead by discarding the MatchPromotion.
8533 if (Match == ArgType::MatchPromotion)
8535 }
8536 }
8537 if (Match == ArgType::MatchPromotion) {
8538 // WG14 N2562 only clarified promotions in *printf
8539 // For NSLog in ObjC, just preserve -Wformat behavior
8540 if (!S.getLangOpts().ObjC &&
8541 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
8542 ImplicitMatch != ArgType::NoMatchTypeConfusion)
8543 return true;
8545 }
8546 if (ImplicitMatch == ArgType::NoMatchPedantic ||
8547 ImplicitMatch == ArgType::NoMatchTypeConfusion)
8548 Match = ImplicitMatch;
8549 assert(Match != ArgType::MatchPromotion);
8550
8551 // Look through unscoped enums to their underlying type.
8552 bool IsEnum = false;
8553 bool IsScopedEnum = false;
8554 QualType IntendedTy = ExprTy;
8555 if (const auto *ED = ExprTy->getAsEnumDecl()) {
8556 IntendedTy = ED->getIntegerType();
8557 if (!ED->isScoped()) {
8558 ExprTy = IntendedTy;
8559 // This controls whether we're talking about the underlying type or not,
8560 // which we only want to do when it's an unscoped enum.
8561 IsEnum = true;
8562 } else {
8563 IsScopedEnum = true;
8564 }
8565 }
8566
8567 // %C in an Objective-C context prints a unichar, not a wchar_t.
8568 // If the argument is an integer of some kind, believe the %C and suggest
8569 // a cast instead of changing the conversion specifier.
8570 if (isObjCContext() &&
8573 !ExprTy->isCharType()) {
8574 // 'unichar' is defined as a typedef of unsigned short, but we should
8575 // prefer using the typedef if it is visible.
8576 IntendedTy = S.Context.UnsignedShortTy;
8577
8578 // While we are here, check if the value is an IntegerLiteral that happens
8579 // to be within the valid range.
8580 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8581 const llvm::APInt &V = IL->getValue();
8582 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8583 return true;
8584 }
8585
8586 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8588 if (S.LookupName(Result, S.getCurScope())) {
8589 NamedDecl *ND = Result.getFoundDecl();
8590 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8591 if (TD->getUnderlyingType() == IntendedTy)
8592 IntendedTy =
8594 /*Qualifier=*/std::nullopt, TD);
8595 }
8596 }
8597 }
8598
8599 // Special-case some of Darwin's platform-independence types by suggesting
8600 // casts to primitive types that are known to be large enough.
8601 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8602 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8603 QualType CastTy;
8604 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8605 if (!CastTy.isNull()) {
8606 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8607 // (long in ASTContext). Only complain to pedants or when they're the
8608 // underlying type of a scoped enum (which always needs a cast).
8609 if (!IsScopedEnum &&
8610 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8611 (AT.isSizeT() || AT.isPtrdiffT()) &&
8612 AT.matchesType(S.Context, CastTy))
8614 IntendedTy = CastTy;
8615 ShouldNotPrintDirectly = true;
8616 }
8617 }
8618
8619 // We may be able to offer a FixItHint if it is a supported type.
8620 PrintfSpecifier fixedFS = FS;
8621 bool Success =
8622 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8623
8624 if (Success) {
8625 // Get the fix string from the fixed format specifier
8626 SmallString<16> buf;
8627 llvm::raw_svector_ostream os(buf);
8628 fixedFS.toString(os);
8629
8630 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8631
8632 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
8633 unsigned Diag;
8634 switch (Match) {
8635 case ArgType::Match:
8638 llvm_unreachable("expected non-matching");
8640 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
8641 break;
8643 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8644 break;
8646 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8647 break;
8648 case ArgType::NoMatch:
8649 Diag = diag::warn_format_conversion_argument_type_mismatch;
8650 break;
8651 }
8652
8653 // In this case, the specifier is wrong and should be changed to match
8654 // the argument.
8655 EmitFormatDiagnostic(S.PDiag(Diag)
8657 << IntendedTy << IsEnum << E->getSourceRange(),
8658 E->getBeginLoc(),
8659 /*IsStringLocation*/ false, SpecRange,
8660 FixItHint::CreateReplacement(SpecRange, os.str()));
8661 } else {
8662 // The canonical type for formatting this value is different from the
8663 // actual type of the expression. (This occurs, for example, with Darwin's
8664 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8665 // should be printed as 'long' for 64-bit compatibility.)
8666 // Rather than emitting a normal format/argument mismatch, we want to
8667 // add a cast to the recommended type (and correct the format string
8668 // if necessary). We should also do so for scoped enumerations.
8669 SmallString<16> CastBuf;
8670 llvm::raw_svector_ostream CastFix(CastBuf);
8671 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
8672 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8673 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
8674
8676 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
8677 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
8678 E->getExprLoc());
8679 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
8680 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8681
8682 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8683 // If there's already a cast present, just replace it.
8684 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8685 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8686
8687 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
8688 // If the expression has high enough precedence,
8689 // just write the C-style cast.
8690 Hints.push_back(
8691 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8692 } else {
8693 // Otherwise, add parens around the expression as well as the cast.
8694 CastFix << "(";
8695 Hints.push_back(
8696 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8697
8698 // We don't use getLocForEndOfToken because it returns invalid source
8699 // locations for macro expansions (by design).
8703 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8704 }
8705
8706 if (ShouldNotPrintDirectly && !IsScopedEnum) {
8707 // The expression has a type that should not be printed directly.
8708 // We extract the name from the typedef because we don't want to show
8709 // the underlying type in the diagnostic.
8710 StringRef Name;
8711 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
8712 Name = TypedefTy->getDecl()->getName();
8713 else
8714 Name = CastTyName;
8715 unsigned Diag = Match == ArgType::NoMatchPedantic
8716 ? diag::warn_format_argument_needs_cast_pedantic
8717 : diag::warn_format_argument_needs_cast;
8718 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8719 << E->getSourceRange(),
8720 E->getBeginLoc(), /*IsStringLocation=*/false,
8721 SpecRange, Hints);
8722 } else {
8723 // In this case, the expression could be printed using a different
8724 // specifier, but we've decided that the specifier is probably correct
8725 // and we should cast instead. Just use the normal warning message.
8726
8727 unsigned Diag =
8728 IsScopedEnum
8729 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8730 : diag::warn_format_conversion_argument_type_mismatch;
8731
8732 EmitFormatDiagnostic(
8733 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8734 << IsEnum << E->getSourceRange(),
8735 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8736 }
8737 }
8738 } else {
8739 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8740 SpecifierLen);
8741 // Since the warning for passing non-POD types to variadic functions
8742 // was deferred until now, we emit a warning for non-POD
8743 // arguments here.
8744 bool EmitTypeMismatch = false;
8745 switch (S.isValidVarArgType(ExprTy)) {
8746 case VarArgKind::Valid:
8748 unsigned Diag;
8749 switch (Match) {
8750 case ArgType::Match:
8754 llvm_unreachable("expected non-matching");
8756 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8757 break;
8759 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8760 break;
8761 case ArgType::NoMatch:
8762 Diag = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)
8763 ? diag::err_format_conversion_argument_type_mismatch
8764 : diag::warn_format_conversion_argument_type_mismatch;
8765 break;
8766 }
8767
8768 EmitFormatDiagnostic(
8769 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8770 << IsEnum << CSR << E->getSourceRange(),
8771 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8772 break;
8773 }
8776 if (CallType == VariadicCallType::DoesNotApply) {
8777 EmitTypeMismatch = true;
8778 } else {
8779 EmitFormatDiagnostic(
8780 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8781 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8782 << AT.getRepresentativeTypeName(S.Context) << CSR
8783 << E->getSourceRange(),
8784 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8785 checkForCStrMembers(AT, E);
8786 }
8787 break;
8788
8790 if (CallType == VariadicCallType::DoesNotApply)
8791 EmitTypeMismatch = true;
8792 else if (ExprTy->isObjCObjectType())
8793 EmitFormatDiagnostic(
8794 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8795 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8796 << AT.getRepresentativeTypeName(S.Context) << CSR
8797 << E->getSourceRange(),
8798 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8799 else
8800 // FIXME: If this is an initializer list, suggest removing the braces
8801 // or inserting a cast to the target type.
8802 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8803 << isa<InitListExpr>(E) << ExprTy << CallType
8805 break;
8806 }
8807
8808 if (EmitTypeMismatch) {
8809 // The function is not variadic, so we do not generate warnings about
8810 // being allowed to pass that object as a variadic argument. Instead,
8811 // since there are inherently no printf specifiers for types which cannot
8812 // be passed as variadic arguments, emit a plain old specifier mismatch
8813 // argument.
8814 EmitFormatDiagnostic(
8815 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8816 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
8817 << E->getSourceRange(),
8818 E->getBeginLoc(), false, CSR);
8819 }
8820
8821 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8822 "format string specifier index out of range");
8823 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8824 }
8825
8826 return true;
8827}
8828
8829//===--- CHECK: Scanf format string checking ------------------------------===//
8830
8831namespace {
8832
8833class CheckScanfHandler : public CheckFormatHandler {
8834public:
8835 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8836 const Expr *origFormatExpr, FormatStringType type,
8837 unsigned firstDataArg, unsigned numDataArgs,
8838 const char *beg, Sema::FormatArgumentPassingKind APK,
8839 ArrayRef<const Expr *> Args, unsigned formatIdx,
8840 bool inFunctionCall, VariadicCallType CallType,
8841 llvm::SmallBitVector &CheckedVarArgs,
8842 UncoveredArgHandler &UncoveredArg)
8843 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8844 numDataArgs, beg, APK, Args, formatIdx,
8845 inFunctionCall, CallType, CheckedVarArgs,
8846 UncoveredArg) {}
8847
8848 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8849 const char *startSpecifier,
8850 unsigned specifierLen) override;
8851
8852 bool HandleInvalidScanfConversionSpecifier(
8853 const analyze_scanf::ScanfSpecifier &FS,
8854 const char *startSpecifier,
8855 unsigned specifierLen) override;
8856
8857 void HandleIncompleteScanList(const char *start, const char *end) override;
8858};
8859
8860} // namespace
8861
8862void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8863 const char *end) {
8864 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8865 getLocationOfByte(end), /*IsStringLocation*/true,
8866 getSpecifierRange(start, end - start));
8867}
8868
8869bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8871 const char *startSpecifier,
8872 unsigned specifierLen) {
8875
8876 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8877 getLocationOfByte(CS.getStart()),
8878 startSpecifier, specifierLen,
8879 CS.getStart(), CS.getLength());
8880}
8881
8882bool CheckScanfHandler::HandleScanfSpecifier(
8884 const char *startSpecifier,
8885 unsigned specifierLen) {
8886 using namespace analyze_scanf;
8887 using namespace analyze_format_string;
8888
8889 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8890
8891 // Handle case where '%' and '*' don't consume an argument. These shouldn't
8892 // be used to decide if we are using positional arguments consistently.
8893 if (FS.consumesDataArgument()) {
8894 if (atFirstArg) {
8895 atFirstArg = false;
8896 usesPositionalArgs = FS.usesPositionalArg();
8897 }
8898 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8899 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8900 startSpecifier, specifierLen);
8901 return false;
8902 }
8903 }
8904
8905 // Check if the field with is non-zero.
8906 const OptionalAmount &Amt = FS.getFieldWidth();
8908 if (Amt.getConstantAmount() == 0) {
8909 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8910 Amt.getConstantLength());
8911 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8912 getLocationOfByte(Amt.getStart()),
8913 /*IsStringLocation*/true, R,
8915 }
8916 }
8917
8918 if (!FS.consumesDataArgument()) {
8919 // FIXME: Technically specifying a precision or field width here
8920 // makes no sense. Worth issuing a warning at some point.
8921 return true;
8922 }
8923
8924 // Consume the argument.
8925 unsigned argIndex = FS.getArgIndex();
8926 if (argIndex < NumDataArgs) {
8927 // The check to see if the argIndex is valid will come later.
8928 // We set the bit here because we may exit early from this
8929 // function if we encounter some other error.
8930 CoveredArgs.set(argIndex);
8931 }
8932
8933 // Check the length modifier is valid with the given conversion specifier.
8935 S.getLangOpts()))
8936 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8937 diag::warn_format_nonsensical_length);
8938 else if (!FS.hasStandardLengthModifier())
8939 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8941 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8942 diag::warn_format_non_standard_conversion_spec);
8943
8945 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8946
8947 // The remaining checks depend on the data arguments.
8948 if (!HasFormatArguments())
8949 return true;
8950
8951 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8952 return false;
8953
8954 // Check that the argument type matches the format specifier.
8955 const Expr *Ex = getDataArg(argIndex);
8956 if (!Ex)
8957 return true;
8958
8960
8961 if (!AT.isValid()) {
8962 return true;
8963 }
8964
8966 AT.matchesType(S.Context, Ex->getType());
8969 return true;
8972
8973 ScanfSpecifier fixedFS = FS;
8974 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8975 S.getLangOpts(), S.Context);
8976
8977 unsigned Diag =
8978 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8979 : Signedness
8980 ? diag::warn_format_conversion_argument_type_mismatch_signedness
8981 : diag::warn_format_conversion_argument_type_mismatch;
8982
8983 if (Success) {
8984 // Get the fix string from the fixed format specifier.
8985 SmallString<128> buf;
8986 llvm::raw_svector_ostream os(buf);
8987 fixedFS.toString(os);
8988
8989 EmitFormatDiagnostic(
8991 << Ex->getType() << false << Ex->getSourceRange(),
8992 Ex->getBeginLoc(),
8993 /*IsStringLocation*/ false,
8994 getSpecifierRange(startSpecifier, specifierLen),
8996 getSpecifierRange(startSpecifier, specifierLen), os.str()));
8997 } else {
8998 EmitFormatDiagnostic(S.PDiag(Diag)
9000 << Ex->getType() << false << Ex->getSourceRange(),
9001 Ex->getBeginLoc(),
9002 /*IsStringLocation*/ false,
9003 getSpecifierRange(startSpecifier, specifierLen));
9004 }
9005
9006 return true;
9007}
9008
9009static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9011 const StringLiteral *Fmt,
9013 const Expr *FmtExpr, bool InFunctionCall) {
9014 bool HadError = false;
9015 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9016 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9017 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9018 // In positional-style format strings, the same specifier can appear
9019 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9020 // are sorted by getPosition(), and we process each range of equal
9021 // getPosition() values as one group.
9022 // RefArgs are taken from a string literal that was given to
9023 // attribute(format_matches), and if we got this far, we have already
9024 // verified that if it has positional specifiers that appear in multiple
9025 // locations, then they are all mutually compatible. What's left for us to
9026 // do is verify that all specifiers with the same position in FmtArgs are
9027 // compatible with the RefArgs specifiers. We check each specifier from
9028 // FmtArgs against the first member of the RefArgs group.
9029 for (; FmtIter < FmtEnd; ++FmtIter) {
9030 // Clang does not diagnose missing format specifiers in positional-style
9031 // strings (TODO: which it probably should do, as it is UB to skip over a
9032 // format argument). Skip specifiers if needed.
9033 if (FmtIter->getPosition() < RefIter->getPosition())
9034 continue;
9035
9036 // Delimits a new getPosition() value.
9037 if (FmtIter->getPosition() > RefIter->getPosition())
9038 break;
9039
9040 HadError |=
9041 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
9042 }
9043
9044 // Jump RefIter to the start of the next group.
9045 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
9046 return Arg.getPosition() != RefIter->getPosition();
9047 });
9048 }
9049
9050 if (FmtIter < FmtEnd) {
9051 CheckFormatHandler::EmitFormatDiagnostic(
9052 S, InFunctionCall, FmtExpr,
9053 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
9054 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
9055 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
9056 } else if (RefIter < RefEnd) {
9057 CheckFormatHandler::EmitFormatDiagnostic(
9058 S, InFunctionCall, FmtExpr,
9059 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
9060 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
9061 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
9062 << 1 << RefIter->getSourceRange();
9063 }
9064 return !HadError;
9065}
9066
9068 Sema &S, const FormatStringLiteral *FExpr,
9069 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
9071 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
9072 bool inFunctionCall, VariadicCallType CallType,
9073 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
9074 bool IgnoreStringsWithoutSpecifiers) {
9075 // CHECK: is the format string a wide literal?
9076 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9077 CheckFormatHandler::EmitFormatDiagnostic(
9078 S, inFunctionCall, Args[format_idx],
9079 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9080 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9081 return;
9082 }
9083
9084 // Str - The format string. NOTE: this is NOT null-terminated!
9085 StringRef StrRef = FExpr->getString();
9086 const char *Str = StrRef.data();
9087 // Account for cases where the string literal is truncated in a declaration.
9088 const ConstantArrayType *T =
9089 S.Context.getAsConstantArrayType(FExpr->getType());
9090 assert(T && "String literal not of constant array type!");
9091 size_t TypeSize = T->getZExtSize();
9092 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9093 const unsigned numDataArgs = Args.size() - firstDataArg;
9094
9095 if (IgnoreStringsWithoutSpecifiers &&
9097 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9098 return;
9099
9100 // Emit a warning if the string literal is truncated and does not contain an
9101 // embedded null character.
9102 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9103 CheckFormatHandler::EmitFormatDiagnostic(
9104 S, inFunctionCall, Args[format_idx],
9105 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9106 FExpr->getBeginLoc(),
9107 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9108 return;
9109 }
9110
9111 // CHECK: empty format string?
9112 if (StrLen == 0 && numDataArgs > 0) {
9113 CheckFormatHandler::EmitFormatDiagnostic(
9114 S, inFunctionCall, Args[format_idx],
9115 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9116 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9117 return;
9118 }
9119
9124 bool IsObjC =
9126 if (ReferenceFormatString == nullptr) {
9127 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9128 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9129 inFunctionCall, CallType, CheckedVarArgs,
9130 UncoveredArg);
9131
9133 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
9136 H.DoneProcessing();
9137 } else {
9139 Type, ReferenceFormatString, FExpr->getFormatString(),
9140 inFunctionCall ? nullptr : Args[format_idx]);
9141 }
9142 } else if (Type == FormatStringType::Scanf) {
9143 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9144 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9145 CallType, CheckedVarArgs, UncoveredArg);
9146
9148 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9149 H.DoneProcessing();
9150 } // TODO: handle other formats
9151}
9152
9154 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9155 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9160 return true;
9161
9162 bool IsObjC =
9165 FormatStringLiteral RefLit = AuthoritativeFormatString;
9166 FormatStringLiteral TestLit = TestedFormatString;
9167 const Expr *Arg;
9168 bool DiagAtStringLiteral;
9169 if (FunctionCallArg) {
9170 Arg = FunctionCallArg;
9171 DiagAtStringLiteral = false;
9172 } else {
9173 Arg = TestedFormatString;
9174 DiagAtStringLiteral = true;
9175 }
9176 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
9177 AuthoritativeFormatString, Type,
9178 IsObjC, true, RefArgs) &&
9179 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
9180 DiagAtStringLiteral, FmtArgs)) {
9181 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
9182 TestedFormatString, FmtArgs, Arg,
9183 DiagAtStringLiteral);
9184 }
9185 return false;
9186}
9187
9189 const StringLiteral *Str) {
9194 return true;
9195
9196 FormatStringLiteral RefLit = Str;
9198 bool IsObjC =
9200 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
9201 true, Args))
9202 return false;
9203
9204 // Group arguments by getPosition() value, and check that each member of the
9205 // group is compatible with the first member. This verifies that when
9206 // positional arguments are used multiple times (such as %2$i %2$d), all uses
9207 // are mutually compatible. As an optimization, don't test the first member
9208 // against itself.
9209 bool HadError = false;
9210 auto Iter = Args.begin();
9211 auto End = Args.end();
9212 while (Iter != End) {
9213 const auto &FirstInGroup = *Iter;
9214 for (++Iter;
9215 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
9216 ++Iter) {
9217 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
9218 }
9219 }
9220 return !HadError;
9221}
9222
9224 // Str - The format string. NOTE: this is NOT null-terminated!
9225 StringRef StrRef = FExpr->getString();
9226 const char *Str = StrRef.data();
9227 // Account for cases where the string literal is truncated in a declaration.
9228 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9229 assert(T && "String literal not of constant array type!");
9230 size_t TypeSize = T->getZExtSize();
9231 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9232 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9233 getLangOpts(),
9234 Context.getTargetInfo());
9235}
9236
9237//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9238
9239// Returns the related absolute value function that is larger, of 0 if one
9240// does not exist.
9241static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9242 switch (AbsFunction) {
9243 default:
9244 return 0;
9245
9246 case Builtin::BI__builtin_abs:
9247 return Builtin::BI__builtin_labs;
9248 case Builtin::BI__builtin_labs:
9249 return Builtin::BI__builtin_llabs;
9250 case Builtin::BI__builtin_llabs:
9251 return 0;
9252
9253 case Builtin::BI__builtin_fabsf:
9254 return Builtin::BI__builtin_fabs;
9255 case Builtin::BI__builtin_fabs:
9256 return Builtin::BI__builtin_fabsl;
9257 case Builtin::BI__builtin_fabsl:
9258 return 0;
9259
9260 case Builtin::BI__builtin_cabsf:
9261 return Builtin::BI__builtin_cabs;
9262 case Builtin::BI__builtin_cabs:
9263 return Builtin::BI__builtin_cabsl;
9264 case Builtin::BI__builtin_cabsl:
9265 return 0;
9266
9267 case Builtin::BIabs:
9268 return Builtin::BIlabs;
9269 case Builtin::BIlabs:
9270 return Builtin::BIllabs;
9271 case Builtin::BIllabs:
9272 return 0;
9273
9274 case Builtin::BIfabsf:
9275 return Builtin::BIfabs;
9276 case Builtin::BIfabs:
9277 return Builtin::BIfabsl;
9278 case Builtin::BIfabsl:
9279 return 0;
9280
9281 case Builtin::BIcabsf:
9282 return Builtin::BIcabs;
9283 case Builtin::BIcabs:
9284 return Builtin::BIcabsl;
9285 case Builtin::BIcabsl:
9286 return 0;
9287 }
9288}
9289
9290// Returns the argument type of the absolute value function.
9292 unsigned AbsType) {
9293 if (AbsType == 0)
9294 return QualType();
9295
9297 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9299 return QualType();
9300
9302 if (!FT)
9303 return QualType();
9304
9305 if (FT->getNumParams() != 1)
9306 return QualType();
9307
9308 return FT->getParamType(0);
9309}
9310
9311// Returns the best absolute value function, or zero, based on type and
9312// current absolute value function.
9313static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9314 unsigned AbsFunctionKind) {
9315 unsigned BestKind = 0;
9316 uint64_t ArgSize = Context.getTypeSize(ArgType);
9317 for (unsigned Kind = AbsFunctionKind; Kind != 0;
9318 Kind = getLargerAbsoluteValueFunction(Kind)) {
9319 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9320 if (Context.getTypeSize(ParamType) >= ArgSize) {
9321 if (BestKind == 0)
9322 BestKind = Kind;
9323 else if (Context.hasSameType(ParamType, ArgType)) {
9324 BestKind = Kind;
9325 break;
9326 }
9327 }
9328 }
9329 return BestKind;
9330}
9331
9337
9339 if (T->isIntegralOrEnumerationType())
9340 return AVK_Integer;
9341 if (T->isRealFloatingType())
9342 return AVK_Floating;
9343 if (T->isAnyComplexType())
9344 return AVK_Complex;
9345
9346 llvm_unreachable("Type not integer, floating, or complex");
9347}
9348
9349// Changes the absolute value function to a different type. Preserves whether
9350// the function is a builtin.
9351static unsigned changeAbsFunction(unsigned AbsKind,
9352 AbsoluteValueKind ValueKind) {
9353 switch (ValueKind) {
9354 case AVK_Integer:
9355 switch (AbsKind) {
9356 default:
9357 return 0;
9358 case Builtin::BI__builtin_fabsf:
9359 case Builtin::BI__builtin_fabs:
9360 case Builtin::BI__builtin_fabsl:
9361 case Builtin::BI__builtin_cabsf:
9362 case Builtin::BI__builtin_cabs:
9363 case Builtin::BI__builtin_cabsl:
9364 return Builtin::BI__builtin_abs;
9365 case Builtin::BIfabsf:
9366 case Builtin::BIfabs:
9367 case Builtin::BIfabsl:
9368 case Builtin::BIcabsf:
9369 case Builtin::BIcabs:
9370 case Builtin::BIcabsl:
9371 return Builtin::BIabs;
9372 }
9373 case AVK_Floating:
9374 switch (AbsKind) {
9375 default:
9376 return 0;
9377 case Builtin::BI__builtin_abs:
9378 case Builtin::BI__builtin_labs:
9379 case Builtin::BI__builtin_llabs:
9380 case Builtin::BI__builtin_cabsf:
9381 case Builtin::BI__builtin_cabs:
9382 case Builtin::BI__builtin_cabsl:
9383 return Builtin::BI__builtin_fabsf;
9384 case Builtin::BIabs:
9385 case Builtin::BIlabs:
9386 case Builtin::BIllabs:
9387 case Builtin::BIcabsf:
9388 case Builtin::BIcabs:
9389 case Builtin::BIcabsl:
9390 return Builtin::BIfabsf;
9391 }
9392 case AVK_Complex:
9393 switch (AbsKind) {
9394 default:
9395 return 0;
9396 case Builtin::BI__builtin_abs:
9397 case Builtin::BI__builtin_labs:
9398 case Builtin::BI__builtin_llabs:
9399 case Builtin::BI__builtin_fabsf:
9400 case Builtin::BI__builtin_fabs:
9401 case Builtin::BI__builtin_fabsl:
9402 return Builtin::BI__builtin_cabsf;
9403 case Builtin::BIabs:
9404 case Builtin::BIlabs:
9405 case Builtin::BIllabs:
9406 case Builtin::BIfabsf:
9407 case Builtin::BIfabs:
9408 case Builtin::BIfabsl:
9409 return Builtin::BIcabsf;
9410 }
9411 }
9412 llvm_unreachable("Unable to convert function");
9413}
9414
9415static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9416 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9417 if (!FnInfo)
9418 return 0;
9419
9420 switch (FDecl->getBuiltinID()) {
9421 default:
9422 return 0;
9423 case Builtin::BI__builtin_abs:
9424 case Builtin::BI__builtin_fabs:
9425 case Builtin::BI__builtin_fabsf:
9426 case Builtin::BI__builtin_fabsl:
9427 case Builtin::BI__builtin_labs:
9428 case Builtin::BI__builtin_llabs:
9429 case Builtin::BI__builtin_cabs:
9430 case Builtin::BI__builtin_cabsf:
9431 case Builtin::BI__builtin_cabsl:
9432 case Builtin::BIabs:
9433 case Builtin::BIlabs:
9434 case Builtin::BIllabs:
9435 case Builtin::BIfabs:
9436 case Builtin::BIfabsf:
9437 case Builtin::BIfabsl:
9438 case Builtin::BIcabs:
9439 case Builtin::BIcabsf:
9440 case Builtin::BIcabsl:
9441 return FDecl->getBuiltinID();
9442 }
9443 llvm_unreachable("Unknown Builtin type");
9444}
9445
9446// If the replacement is valid, emit a note with replacement function.
9447// Additionally, suggest including the proper header if not already included.
9449 unsigned AbsKind, QualType ArgType) {
9450 bool EmitHeaderHint = true;
9451 const char *HeaderName = nullptr;
9452 std::string FunctionName;
9453 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9454 FunctionName = "std::abs";
9455 if (ArgType->isIntegralOrEnumerationType()) {
9456 HeaderName = "cstdlib";
9457 } else if (ArgType->isRealFloatingType()) {
9458 HeaderName = "cmath";
9459 } else {
9460 llvm_unreachable("Invalid Type");
9461 }
9462
9463 // Lookup all std::abs
9464 if (NamespaceDecl *Std = S.getStdNamespace()) {
9465 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9467 S.LookupQualifiedName(R, Std);
9468
9469 for (const auto *I : R) {
9470 const FunctionDecl *FDecl = nullptr;
9471 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9472 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9473 } else {
9474 FDecl = dyn_cast<FunctionDecl>(I);
9475 }
9476 if (!FDecl)
9477 continue;
9478
9479 // Found std::abs(), check that they are the right ones.
9480 if (FDecl->getNumParams() != 1)
9481 continue;
9482
9483 // Check that the parameter type can handle the argument.
9484 QualType ParamType = FDecl->getParamDecl(0)->getType();
9485 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9486 S.Context.getTypeSize(ArgType) <=
9487 S.Context.getTypeSize(ParamType)) {
9488 // Found a function, don't need the header hint.
9489 EmitHeaderHint = false;
9490 break;
9491 }
9492 }
9493 }
9494 } else {
9495 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9496 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9497
9498 if (HeaderName) {
9499 DeclarationName DN(&S.Context.Idents.get(FunctionName));
9500 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9502 S.LookupName(R, S.getCurScope());
9503
9504 if (R.isSingleResult()) {
9505 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9506 if (FD && FD->getBuiltinID() == AbsKind) {
9507 EmitHeaderHint = false;
9508 } else {
9509 return;
9510 }
9511 } else if (!R.empty()) {
9512 return;
9513 }
9514 }
9515 }
9516
9517 S.Diag(Loc, diag::note_replace_abs_function)
9518 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9519
9520 if (!HeaderName)
9521 return;
9522
9523 if (!EmitHeaderHint)
9524 return;
9525
9526 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9527 << FunctionName;
9528}
9529
9530template <std::size_t StrLen>
9531static bool IsStdFunction(const FunctionDecl *FDecl,
9532 const char (&Str)[StrLen]) {
9533 if (!FDecl)
9534 return false;
9535 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9536 return false;
9537 if (!FDecl->isInStdNamespace())
9538 return false;
9539
9540 return true;
9541}
9542
9543enum class MathCheck { NaN, Inf };
9544static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
9545 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
9546 return llvm::is_contained(names, calleeName);
9547 };
9548
9549 switch (Check) {
9550 case MathCheck::NaN:
9551 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
9552 "__builtin_nanf16", "__builtin_nanf128"});
9553 case MathCheck::Inf:
9554 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
9555 "__builtin_inff16", "__builtin_inff128"});
9556 }
9557 llvm_unreachable("unknown MathCheck");
9558}
9559
9560static bool IsInfinityFunction(const FunctionDecl *FDecl) {
9561 if (FDecl->getName() != "infinity")
9562 return false;
9563
9564 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
9565 const CXXRecordDecl *RDecl = MDecl->getParent();
9566 if (RDecl->getName() != "numeric_limits")
9567 return false;
9568
9569 if (const NamespaceDecl *NSDecl =
9570 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
9571 return NSDecl->isStdNamespace();
9572 }
9573
9574 return false;
9575}
9576
9577void Sema::CheckInfNaNFunction(const CallExpr *Call,
9578 const FunctionDecl *FDecl) {
9579 if (!FDecl->getIdentifier())
9580 return;
9581
9582 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
9583 if (FPO.getNoHonorNaNs() &&
9584 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
9586 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9587 << 1 << 0 << Call->getSourceRange();
9588 return;
9589 }
9590
9591 if (FPO.getNoHonorInfs() &&
9592 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
9593 IsInfinityFunction(FDecl) ||
9595 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9596 << 0 << 0 << Call->getSourceRange();
9597 }
9598}
9599
9600void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9601 const FunctionDecl *FDecl) {
9602 if (Call->getNumArgs() != 1)
9603 return;
9604
9605 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9606 bool IsStdAbs = IsStdFunction(FDecl, "abs");
9607 if (AbsKind == 0 && !IsStdAbs)
9608 return;
9609
9610 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9611 QualType ParamType = Call->getArg(0)->getType();
9612
9613 // Unsigned types cannot be negative. Suggest removing the absolute value
9614 // function call.
9615 if (ArgType->isUnsignedIntegerType()) {
9616 std::string FunctionName =
9617 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9618 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9619 Diag(Call->getExprLoc(), diag::note_remove_abs)
9620 << FunctionName
9621 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9622 return;
9623 }
9624
9625 // Taking the absolute value of a pointer is very suspicious, they probably
9626 // wanted to index into an array, dereference a pointer, call a function, etc.
9627 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9628 unsigned DiagType = 0;
9629 if (ArgType->isFunctionType())
9630 DiagType = 1;
9631 else if (ArgType->isArrayType())
9632 DiagType = 2;
9633
9634 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9635 return;
9636 }
9637
9638 // std::abs has overloads which prevent most of the absolute value problems
9639 // from occurring.
9640 if (IsStdAbs)
9641 return;
9642
9643 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9644 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9645
9646 // The argument and parameter are the same kind. Check if they are the right
9647 // size.
9648 if (ArgValueKind == ParamValueKind) {
9649 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9650 return;
9651
9652 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9653 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9654 << FDecl << ArgType << ParamType;
9655
9656 if (NewAbsKind == 0)
9657 return;
9658
9659 emitReplacement(*this, Call->getExprLoc(),
9660 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9661 return;
9662 }
9663
9664 // ArgValueKind != ParamValueKind
9665 // The wrong type of absolute value function was used. Attempt to find the
9666 // proper one.
9667 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9668 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9669 if (NewAbsKind == 0)
9670 return;
9671
9672 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9673 << FDecl << ParamValueKind << ArgValueKind;
9674
9675 emitReplacement(*this, Call->getExprLoc(),
9676 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9677}
9678
9679//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9680void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9681 const FunctionDecl *FDecl) {
9682 if (!Call || !FDecl) return;
9683
9684 // Ignore template specializations and macros.
9685 if (inTemplateInstantiation()) return;
9686 if (Call->getExprLoc().isMacroID()) return;
9687
9688 // Only care about the one template argument, two function parameter std::max
9689 if (Call->getNumArgs() != 2) return;
9690 if (!IsStdFunction(FDecl, "max")) return;
9691 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9692 if (!ArgList) return;
9693 if (ArgList->size() != 1) return;
9694
9695 // Check that template type argument is unsigned integer.
9696 const auto& TA = ArgList->get(0);
9697 if (TA.getKind() != TemplateArgument::Type) return;
9698 QualType ArgType = TA.getAsType();
9699 if (!ArgType->isUnsignedIntegerType()) return;
9700
9701 // See if either argument is a literal zero.
9702 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9703 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9704 if (!MTE) return false;
9705 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9706 if (!Num) return false;
9707 if (Num->getValue() != 0) return false;
9708 return true;
9709 };
9710
9711 const Expr *FirstArg = Call->getArg(0);
9712 const Expr *SecondArg = Call->getArg(1);
9713 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9714 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9715
9716 // Only warn when exactly one argument is zero.
9717 if (IsFirstArgZero == IsSecondArgZero) return;
9718
9719 SourceRange FirstRange = FirstArg->getSourceRange();
9720 SourceRange SecondRange = SecondArg->getSourceRange();
9721
9722 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9723
9724 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9725 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9726
9727 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9728 SourceRange RemovalRange;
9729 if (IsFirstArgZero) {
9730 RemovalRange = SourceRange(FirstRange.getBegin(),
9731 SecondRange.getBegin().getLocWithOffset(-1));
9732 } else {
9733 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9734 SecondRange.getEnd());
9735 }
9736
9737 Diag(Call->getExprLoc(), diag::note_remove_max_call)
9738 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9739 << FixItHint::CreateRemoval(RemovalRange);
9740}
9741
9742//===--- CHECK: Standard memory functions ---------------------------------===//
9743
9744/// Takes the expression passed to the size_t parameter of functions
9745/// such as memcmp, strncat, etc and warns if it's a comparison.
9746///
9747/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9749 const IdentifierInfo *FnName,
9750 SourceLocation FnLoc,
9751 SourceLocation RParenLoc) {
9752 const auto *Size = dyn_cast<BinaryOperator>(E);
9753 if (!Size)
9754 return false;
9755
9756 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9757 if (!Size->isComparisonOp() && !Size->isLogicalOp())
9758 return false;
9759
9760 SourceRange SizeRange = Size->getSourceRange();
9761 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9762 << SizeRange << FnName;
9763 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9764 << FnName
9766 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9767 << FixItHint::CreateRemoval(RParenLoc);
9768 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9769 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9771 ")");
9772
9773 return true;
9774}
9775
9776/// Determine whether the given type is or contains a dynamic class type
9777/// (e.g., whether it has a vtable).
9779 bool &IsContained) {
9780 // Look through array types while ignoring qualifiers.
9781 const Type *Ty = T->getBaseElementTypeUnsafe();
9782 IsContained = false;
9783
9784 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9785 RD = RD ? RD->getDefinition() : nullptr;
9786 if (!RD || RD->isInvalidDecl())
9787 return nullptr;
9788
9789 if (RD->isDynamicClass())
9790 return RD;
9791
9792 // Check all the fields. If any bases were dynamic, the class is dynamic.
9793 // It's impossible for a class to transitively contain itself by value, so
9794 // infinite recursion is impossible.
9795 for (auto *FD : RD->fields()) {
9796 bool SubContained;
9797 if (const CXXRecordDecl *ContainedRD =
9798 getContainedDynamicClass(FD->getType(), SubContained)) {
9799 IsContained = true;
9800 return ContainedRD;
9801 }
9802 }
9803
9804 return nullptr;
9805}
9806
9808 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9809 if (Unary->getKind() == UETT_SizeOf)
9810 return Unary;
9811 return nullptr;
9812}
9813
9814/// If E is a sizeof expression, returns its argument expression,
9815/// otherwise returns NULL.
9816static const Expr *getSizeOfExprArg(const Expr *E) {
9818 if (!SizeOf->isArgumentType())
9819 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9820 return nullptr;
9821}
9822
9823/// If E is a sizeof expression, returns its argument type.
9826 return SizeOf->getTypeOfArgument();
9827 return QualType();
9828}
9829
9830namespace {
9831
9832struct SearchNonTrivialToInitializeField
9833 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9834 using Super =
9835 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9836
9837 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9838
9839 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9840 SourceLocation SL) {
9841 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9842 asDerived().visitArray(PDIK, AT, SL);
9843 return;
9844 }
9845
9846 Super::visitWithKind(PDIK, FT, SL);
9847 }
9848
9849 void visitARCStrong(QualType FT, SourceLocation SL) {
9850 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9851 }
9852 void visitARCWeak(QualType FT, SourceLocation SL) {
9853 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9854 }
9855 void visitStruct(QualType FT, SourceLocation SL) {
9856 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
9857 visit(FD->getType(), FD->getLocation());
9858 }
9859 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9860 const ArrayType *AT, SourceLocation SL) {
9861 visit(getContext().getBaseElementType(AT), SL);
9862 }
9863 void visitTrivial(QualType FT, SourceLocation SL) {}
9864
9865 static void diag(QualType RT, const Expr *E, Sema &S) {
9866 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9867 }
9868
9869 ASTContext &getContext() { return S.getASTContext(); }
9870
9871 const Expr *E;
9872 Sema &S;
9873};
9874
9875struct SearchNonTrivialToCopyField
9876 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9877 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9878
9879 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9880
9881 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9882 SourceLocation SL) {
9883 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9884 asDerived().visitArray(PCK, AT, SL);
9885 return;
9886 }
9887
9888 Super::visitWithKind(PCK, FT, SL);
9889 }
9890
9891 void visitARCStrong(QualType FT, SourceLocation SL) {
9892 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9893 }
9894 void visitARCWeak(QualType FT, SourceLocation SL) {
9895 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9896 }
9897 void visitPtrAuth(QualType FT, SourceLocation SL) {
9898 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9899 }
9900 void visitStruct(QualType FT, SourceLocation SL) {
9901 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
9902 visit(FD->getType(), FD->getLocation());
9903 }
9904 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9905 SourceLocation SL) {
9906 visit(getContext().getBaseElementType(AT), SL);
9907 }
9908 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9909 SourceLocation SL) {}
9910 void visitTrivial(QualType FT, SourceLocation SL) {}
9911 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9912
9913 static void diag(QualType RT, const Expr *E, Sema &S) {
9914 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9915 }
9916
9917 ASTContext &getContext() { return S.getASTContext(); }
9918
9919 const Expr *E;
9920 Sema &S;
9921};
9922
9923}
9924
9925/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9926static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9927 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9928
9929 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9930 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9931 return false;
9932
9933 return doesExprLikelyComputeSize(BO->getLHS()) ||
9934 doesExprLikelyComputeSize(BO->getRHS());
9935 }
9936
9937 return getAsSizeOfExpr(SizeofExpr) != nullptr;
9938}
9939
9940/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9941///
9942/// \code
9943/// #define MACRO 0
9944/// foo(MACRO);
9945/// foo(0);
9946/// \endcode
9947///
9948/// This should return true for the first call to foo, but not for the second
9949/// (regardless of whether foo is a macro or function).
9951 SourceLocation CallLoc,
9952 SourceLocation ArgLoc) {
9953 if (!CallLoc.isMacroID())
9954 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9955
9956 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9957 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9958}
9959
9960/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9961/// last two arguments transposed.
9962static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9963 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9964 return;
9965
9966 const Expr *SizeArg =
9967 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9968
9969 auto isLiteralZero = [](const Expr *E) {
9970 return (isa<IntegerLiteral>(E) &&
9971 cast<IntegerLiteral>(E)->getValue() == 0) ||
9973 cast<CharacterLiteral>(E)->getValue() == 0);
9974 };
9975
9976 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9977 SourceLocation CallLoc = Call->getRParenLoc();
9979 if (isLiteralZero(SizeArg) &&
9980 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9981
9982 SourceLocation DiagLoc = SizeArg->getExprLoc();
9983
9984 // Some platforms #define bzero to __builtin_memset. See if this is the
9985 // case, and if so, emit a better diagnostic.
9986 if (BId == Builtin::BIbzero ||
9988 CallLoc, SM, S.getLangOpts()) == "bzero")) {
9989 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9990 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9991 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9992 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9993 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9994 }
9995 return;
9996 }
9997
9998 // If the second argument to a memset is a sizeof expression and the third
9999 // isn't, this is also likely an error. This should catch
10000 // 'memset(buf, sizeof(buf), 0xff)'.
10001 if (BId == Builtin::BImemset &&
10002 doesExprLikelyComputeSize(Call->getArg(1)) &&
10003 !doesExprLikelyComputeSize(Call->getArg(2))) {
10004 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10005 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10006 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10007 return;
10008 }
10009}
10010
10011void Sema::CheckMemaccessArguments(const CallExpr *Call,
10012 unsigned BId,
10013 IdentifierInfo *FnName) {
10014 assert(BId != 0);
10015
10016 // It is possible to have a non-standard definition of memset. Validate
10017 // we have enough arguments, and if not, abort further checking.
10018 unsigned ExpectedNumArgs =
10019 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10020 if (Call->getNumArgs() < ExpectedNumArgs)
10021 return;
10022
10023 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10024 BId == Builtin::BIstrndup ? 1 : 2);
10025 unsigned LenArg =
10026 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10027 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10028
10029 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10030 Call->getBeginLoc(), Call->getRParenLoc()))
10031 return;
10032
10033 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10034 CheckMemaccessSize(*this, BId, Call);
10035
10036 // We have special checking when the length is a sizeof expression.
10037 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10038 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10039 llvm::FoldingSetNodeID SizeOfArgID;
10040
10041 // Although widely used, 'bzero' is not a standard function. Be more strict
10042 // with the argument types before allowing diagnostics and only allow the
10043 // form bzero(ptr, sizeof(...)).
10044 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10045 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10046 return;
10047
10048 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10049 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10050 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10051
10052 QualType DestTy = Dest->getType();
10053 QualType PointeeTy;
10054 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10055 PointeeTy = DestPtrTy->getPointeeType();
10056
10057 // Never warn about void type pointers. This can be used to suppress
10058 // false positives.
10059 if (PointeeTy->isVoidType())
10060 continue;
10061
10062 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10063 // actually comparing the expressions for equality. Because computing the
10064 // expression IDs can be expensive, we only do this if the diagnostic is
10065 // enabled.
10066 if (SizeOfArg &&
10067 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10068 SizeOfArg->getExprLoc())) {
10069 // We only compute IDs for expressions if the warning is enabled, and
10070 // cache the sizeof arg's ID.
10071 if (SizeOfArgID == llvm::FoldingSetNodeID())
10072 SizeOfArg->Profile(SizeOfArgID, Context, true);
10073 llvm::FoldingSetNodeID DestID;
10074 Dest->Profile(DestID, Context, true);
10075 if (DestID == SizeOfArgID) {
10076 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10077 // over sizeof(src) as well.
10078 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10079 StringRef ReadableName = FnName->getName();
10080
10081 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10082 if (UnaryOp->getOpcode() == UO_AddrOf)
10083 ActionIdx = 1; // If its an address-of operator, just remove it.
10084 if (!PointeeTy->isIncompleteType() &&
10085 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10086 ActionIdx = 2; // If the pointee's size is sizeof(char),
10087 // suggest an explicit length.
10088
10089 // If the function is defined as a builtin macro, do not show macro
10090 // expansion.
10091 SourceLocation SL = SizeOfArg->getExprLoc();
10092 SourceRange DSR = Dest->getSourceRange();
10093 SourceRange SSR = SizeOfArg->getSourceRange();
10094 SourceManager &SM = getSourceManager();
10095
10096 if (SM.isMacroArgExpansion(SL)) {
10097 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10098 SL = SM.getSpellingLoc(SL);
10099 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10100 SM.getSpellingLoc(DSR.getEnd()));
10101 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10102 SM.getSpellingLoc(SSR.getEnd()));
10103 }
10104
10105 DiagRuntimeBehavior(SL, SizeOfArg,
10106 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10107 << ReadableName
10108 << PointeeTy
10109 << DestTy
10110 << DSR
10111 << SSR);
10112 DiagRuntimeBehavior(SL, SizeOfArg,
10113 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10114 << ActionIdx
10115 << SSR);
10116
10117 break;
10118 }
10119 }
10120
10121 // Also check for cases where the sizeof argument is the exact same
10122 // type as the memory argument, and where it points to a user-defined
10123 // record type.
10124 if (SizeOfArgTy != QualType()) {
10125 if (PointeeTy->isRecordType() &&
10126 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10127 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10128 PDiag(diag::warn_sizeof_pointer_type_memaccess)
10129 << FnName << SizeOfArgTy << ArgIdx
10130 << PointeeTy << Dest->getSourceRange()
10131 << LenExpr->getSourceRange());
10132 break;
10133 }
10134 }
10135 } else if (DestTy->isArrayType()) {
10136 PointeeTy = DestTy;
10137 }
10138
10139 if (PointeeTy == QualType())
10140 continue;
10141
10142 // Always complain about dynamic classes.
10143 bool IsContained;
10144 if (const CXXRecordDecl *ContainedRD =
10145 getContainedDynamicClass(PointeeTy, IsContained)) {
10146
10147 unsigned OperationType = 0;
10148 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10149 // "overwritten" if we're warning about the destination for any call
10150 // but memcmp; otherwise a verb appropriate to the call.
10151 if (ArgIdx != 0 || IsCmp) {
10152 if (BId == Builtin::BImemcpy)
10153 OperationType = 1;
10154 else if(BId == Builtin::BImemmove)
10155 OperationType = 2;
10156 else if (IsCmp)
10157 OperationType = 3;
10158 }
10159
10160 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10161 PDiag(diag::warn_dyn_class_memaccess)
10162 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10163 << IsContained << ContainedRD << OperationType
10164 << Call->getCallee()->getSourceRange());
10165 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10166 BId != Builtin::BImemset)
10168 Dest->getExprLoc(), Dest,
10169 PDiag(diag::warn_arc_object_memaccess)
10170 << ArgIdx << FnName << PointeeTy
10171 << Call->getCallee()->getSourceRange());
10172 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10173
10174 // FIXME: Do not consider incomplete types even though they may be
10175 // completed later. GCC does not diagnose such code, but we may want to
10176 // consider diagnosing it in the future, perhaps under a different, but
10177 // related, diagnostic group.
10178 bool NonTriviallyCopyableCXXRecord =
10179 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10180 !PointeeTy.isTriviallyCopyableType(Context);
10181
10182 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10184 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10185 PDiag(diag::warn_cstruct_memaccess)
10186 << ArgIdx << FnName << PointeeTy << 0);
10187 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10188 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10189 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10190 // FIXME: Limiting this warning to dest argument until we decide
10191 // whether it's valid for source argument too.
10192 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10193 PDiag(diag::warn_cxxstruct_memaccess)
10194 << FnName << PointeeTy);
10195 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10197 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10198 PDiag(diag::warn_cstruct_memaccess)
10199 << ArgIdx << FnName << PointeeTy << 1);
10200 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10201 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10202 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10203 // FIXME: Limiting this warning to dest argument until we decide
10204 // whether it's valid for source argument too.
10205 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10206 PDiag(diag::warn_cxxstruct_memaccess)
10207 << FnName << PointeeTy);
10208 } else {
10209 continue;
10210 }
10211 } else
10212 continue;
10213
10215 Dest->getExprLoc(), Dest,
10216 PDiag(diag::note_bad_memaccess_silence)
10217 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10218 break;
10219 }
10220}
10221
10222// A little helper routine: ignore addition and subtraction of integer literals.
10223// This intentionally does not ignore all integer constant expressions because
10224// we don't want to remove sizeof().
10225static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10226 Ex = Ex->IgnoreParenCasts();
10227
10228 while (true) {
10229 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10230 if (!BO || !BO->isAdditiveOp())
10231 break;
10232
10233 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10234 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10235
10236 if (isa<IntegerLiteral>(RHS))
10237 Ex = LHS;
10238 else if (isa<IntegerLiteral>(LHS))
10239 Ex = RHS;
10240 else
10241 break;
10242 }
10243
10244 return Ex;
10245}
10246
10248 ASTContext &Context) {
10249 // Only handle constant-sized or VLAs, but not flexible members.
10250 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10251 // Only issue the FIXIT for arrays of size > 1.
10252 if (CAT->getZExtSize() <= 1)
10253 return false;
10254 } else if (!Ty->isVariableArrayType()) {
10255 return false;
10256 }
10257 return true;
10258}
10259
10260void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10261 IdentifierInfo *FnName) {
10262
10263 // Don't crash if the user has the wrong number of arguments
10264 unsigned NumArgs = Call->getNumArgs();
10265 if ((NumArgs != 3) && (NumArgs != 4))
10266 return;
10267
10268 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10269 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10270 const Expr *CompareWithSrc = nullptr;
10271
10272 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10273 Call->getBeginLoc(), Call->getRParenLoc()))
10274 return;
10275
10276 // Look for 'strlcpy(dst, x, sizeof(x))'
10277 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10278 CompareWithSrc = Ex;
10279 else {
10280 // Look for 'strlcpy(dst, x, strlen(x))'
10281 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10282 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10283 SizeCall->getNumArgs() == 1)
10284 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10285 }
10286 }
10287
10288 if (!CompareWithSrc)
10289 return;
10290
10291 // Determine if the argument to sizeof/strlen is equal to the source
10292 // argument. In principle there's all kinds of things you could do
10293 // here, for instance creating an == expression and evaluating it with
10294 // EvaluateAsBooleanCondition, but this uses a more direct technique:
10295 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10296 if (!SrcArgDRE)
10297 return;
10298
10299 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10300 if (!CompareWithSrcDRE ||
10301 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10302 return;
10303
10304 const Expr *OriginalSizeArg = Call->getArg(2);
10305 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10306 << OriginalSizeArg->getSourceRange() << FnName;
10307
10308 // Output a FIXIT hint if the destination is an array (rather than a
10309 // pointer to an array). This could be enhanced to handle some
10310 // pointers if we know the actual size, like if DstArg is 'array+2'
10311 // we could say 'sizeof(array)-2'.
10312 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10314 return;
10315
10316 SmallString<128> sizeString;
10317 llvm::raw_svector_ostream OS(sizeString);
10318 OS << "sizeof(";
10319 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10320 OS << ")";
10321
10322 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10323 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10324 OS.str());
10325}
10326
10327/// Check if two expressions refer to the same declaration.
10328static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10329 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10330 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10331 return D1->getDecl() == D2->getDecl();
10332 return false;
10333}
10334
10335static const Expr *getStrlenExprArg(const Expr *E) {
10336 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10337 const FunctionDecl *FD = CE->getDirectCallee();
10338 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10339 return nullptr;
10340 return CE->getArg(0)->IgnoreParenCasts();
10341 }
10342 return nullptr;
10343}
10344
10345void Sema::CheckStrncatArguments(const CallExpr *CE,
10346 const IdentifierInfo *FnName) {
10347 // Don't crash if the user has the wrong number of arguments.
10348 if (CE->getNumArgs() < 3)
10349 return;
10350 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10351 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10352 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10353
10354 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10355 CE->getRParenLoc()))
10356 return;
10357
10358 // Identify common expressions, which are wrongly used as the size argument
10359 // to strncat and may lead to buffer overflows.
10360 unsigned PatternType = 0;
10361 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10362 // - sizeof(dst)
10363 if (referToTheSameDecl(SizeOfArg, DstArg))
10364 PatternType = 1;
10365 // - sizeof(src)
10366 else if (referToTheSameDecl(SizeOfArg, SrcArg))
10367 PatternType = 2;
10368 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10369 if (BE->getOpcode() == BO_Sub) {
10370 const Expr *L = BE->getLHS()->IgnoreParenCasts();
10371 const Expr *R = BE->getRHS()->IgnoreParenCasts();
10372 // - sizeof(dst) - strlen(dst)
10373 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10375 PatternType = 1;
10376 // - sizeof(src) - (anything)
10377 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10378 PatternType = 2;
10379 }
10380 }
10381
10382 if (PatternType == 0)
10383 return;
10384
10385 // Generate the diagnostic.
10386 SourceLocation SL = LenArg->getBeginLoc();
10387 SourceRange SR = LenArg->getSourceRange();
10388 SourceManager &SM = getSourceManager();
10389
10390 // If the function is defined as a builtin macro, do not show macro expansion.
10391 if (SM.isMacroArgExpansion(SL)) {
10392 SL = SM.getSpellingLoc(SL);
10393 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10394 SM.getSpellingLoc(SR.getEnd()));
10395 }
10396
10397 // Check if the destination is an array (rather than a pointer to an array).
10398 QualType DstTy = DstArg->getType();
10399 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10400 Context);
10401 if (!isKnownSizeArray) {
10402 if (PatternType == 1)
10403 Diag(SL, diag::warn_strncat_wrong_size) << SR;
10404 else
10405 Diag(SL, diag::warn_strncat_src_size) << SR;
10406 return;
10407 }
10408
10409 if (PatternType == 1)
10410 Diag(SL, diag::warn_strncat_large_size) << SR;
10411 else
10412 Diag(SL, diag::warn_strncat_src_size) << SR;
10413
10414 SmallString<128> sizeString;
10415 llvm::raw_svector_ostream OS(sizeString);
10416 OS << "sizeof(";
10417 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10418 OS << ") - ";
10419 OS << "strlen(";
10420 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10421 OS << ") - 1";
10422
10423 Diag(SL, diag::note_strncat_wrong_size)
10424 << FixItHint::CreateReplacement(SR, OS.str());
10425}
10426
10427namespace {
10428void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10429 const UnaryOperator *UnaryExpr, const Decl *D) {
10431 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10432 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10433 return;
10434 }
10435}
10436
10437void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10438 const UnaryOperator *UnaryExpr) {
10439 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10440 const Decl *D = Lvalue->getDecl();
10441 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
10442 if (!DD->getType()->isReferenceType())
10443 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10444 }
10445 }
10446
10447 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10448 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10449 Lvalue->getMemberDecl());
10450}
10451
10452void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10453 const UnaryOperator *UnaryExpr) {
10454 const auto *Lambda = dyn_cast<LambdaExpr>(
10456 if (!Lambda)
10457 return;
10458
10459 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10460 << CalleeName << 2 /*object: lambda expression*/;
10461}
10462
10463void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10464 const DeclRefExpr *Lvalue) {
10465 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10466 if (Var == nullptr)
10467 return;
10468
10469 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10470 << CalleeName << 0 /*object: */ << Var;
10471}
10472
10473void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10474 const CastExpr *Cast) {
10475 SmallString<128> SizeString;
10476 llvm::raw_svector_ostream OS(SizeString);
10477
10478 clang::CastKind Kind = Cast->getCastKind();
10479 if (Kind == clang::CK_BitCast &&
10480 !Cast->getSubExpr()->getType()->isFunctionPointerType())
10481 return;
10482 if (Kind == clang::CK_IntegralToPointer &&
10484 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10485 return;
10486
10487 switch (Cast->getCastKind()) {
10488 case clang::CK_BitCast:
10489 case clang::CK_IntegralToPointer:
10490 case clang::CK_FunctionToPointerDecay:
10491 OS << '\'';
10492 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10493 OS << '\'';
10494 break;
10495 default:
10496 return;
10497 }
10498
10499 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10500 << CalleeName << 0 /*object: */ << OS.str();
10501}
10502} // namespace
10503
10504void Sema::CheckFreeArguments(const CallExpr *E) {
10505 const std::string CalleeName =
10506 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10507
10508 { // Prefer something that doesn't involve a cast to make things simpler.
10509 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10510 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10511 switch (UnaryExpr->getOpcode()) {
10512 case UnaryOperator::Opcode::UO_AddrOf:
10513 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10514 case UnaryOperator::Opcode::UO_Plus:
10515 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10516 default:
10517 break;
10518 }
10519
10520 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10521 if (Lvalue->getType()->isArrayType())
10522 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10523
10524 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10525 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10526 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10527 return;
10528 }
10529
10530 if (isa<BlockExpr>(Arg)) {
10531 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10532 << CalleeName << 1 /*object: block*/;
10533 return;
10534 }
10535 }
10536 // Maybe the cast was important, check after the other cases.
10537 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10538 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10539}
10540
10541void
10542Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10543 SourceLocation ReturnLoc,
10544 bool isObjCMethod,
10545 const AttrVec *Attrs,
10546 const FunctionDecl *FD) {
10547 // Check if the return value is null but should not be.
10548 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10549 (!isObjCMethod && isNonNullType(lhsType))) &&
10550 CheckNonNullExpr(*this, RetValExp))
10551 Diag(ReturnLoc, diag::warn_null_ret)
10552 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10553
10554 // C++11 [basic.stc.dynamic.allocation]p4:
10555 // If an allocation function declared with a non-throwing
10556 // exception-specification fails to allocate storage, it shall return
10557 // a null pointer. Any other allocation function that fails to allocate
10558 // storage shall indicate failure only by throwing an exception [...]
10559 if (FD) {
10561 if (Op == OO_New || Op == OO_Array_New) {
10562 const FunctionProtoType *Proto
10563 = FD->getType()->castAs<FunctionProtoType>();
10564 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10565 CheckNonNullExpr(*this, RetValExp))
10566 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10567 << FD << getLangOpts().CPlusPlus11;
10568 }
10569 }
10570
10571 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
10572 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
10573 }
10574
10575 // PPC MMA non-pointer types are not allowed as return type. Checking the type
10576 // here prevent the user from using a PPC MMA type as trailing return type.
10577 if (Context.getTargetInfo().getTriple().isPPC64())
10578 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10579}
10580
10582 const Expr *RHS, BinaryOperatorKind Opcode) {
10583 if (!BinaryOperator::isEqualityOp(Opcode))
10584 return;
10585
10586 // Match and capture subexpressions such as "(float) X == 0.1".
10587 const FloatingLiteral *FPLiteral;
10588 const CastExpr *FPCast;
10589 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
10590 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
10591 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
10592 return FPLiteral && FPCast;
10593 };
10594
10595 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
10596 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
10597 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
10598 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
10599 TargetTy->isFloatingPoint()) {
10600 bool Lossy;
10601 llvm::APFloat TargetC = FPLiteral->getValue();
10602 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
10603 llvm::APFloat::rmNearestTiesToEven, &Lossy);
10604 if (Lossy) {
10605 // If the literal cannot be represented in the source type, then a
10606 // check for == is always false and check for != is always true.
10607 Diag(Loc, diag::warn_float_compare_literal)
10608 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
10609 << LHS->getSourceRange() << RHS->getSourceRange();
10610 return;
10611 }
10612 }
10613 }
10614
10615 // Match a more general floating-point equality comparison (-Wfloat-equal).
10616 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
10617 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
10618
10619 // Special case: check for x == x (which is OK).
10620 // Do not emit warnings for such cases.
10621 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10622 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10623 if (DRL->getDecl() == DRR->getDecl())
10624 return;
10625
10626 // Special case: check for comparisons against literals that can be exactly
10627 // represented by APFloat. In such cases, do not emit a warning. This
10628 // is a heuristic: often comparison against such literals are used to
10629 // detect if a value in a variable has not changed. This clearly can
10630 // lead to false negatives.
10631 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10632 if (FLL->isExact())
10633 return;
10634 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10635 if (FLR->isExact())
10636 return;
10637
10638 // Check for comparisons with builtin types.
10639 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
10640 CL && CL->getBuiltinCallee())
10641 return;
10642
10643 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
10644 CR && CR->getBuiltinCallee())
10645 return;
10646
10647 // Emit the diagnostic.
10648 Diag(Loc, diag::warn_floatingpoint_eq)
10649 << LHS->getSourceRange() << RHS->getSourceRange();
10650}
10651
10652//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10653//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10654
10655namespace {
10656
10657/// Structure recording the 'active' range of an integer-valued
10658/// expression.
10659struct IntRange {
10660 /// The number of bits active in the int. Note that this includes exactly one
10661 /// sign bit if !NonNegative.
10662 unsigned Width;
10663
10664 /// True if the int is known not to have negative values. If so, all leading
10665 /// bits before Width are known zero, otherwise they are known to be the
10666 /// same as the MSB within Width.
10667 bool NonNegative;
10668
10669 IntRange(unsigned Width, bool NonNegative)
10670 : Width(Width), NonNegative(NonNegative) {}
10671
10672 /// Number of bits excluding the sign bit.
10673 unsigned valueBits() const {
10674 return NonNegative ? Width : Width - 1;
10675 }
10676
10677 /// Returns the range of the bool type.
10678 static IntRange forBoolType() {
10679 return IntRange(1, true);
10680 }
10681
10682 /// Returns the range of an opaque value of the given integral type.
10683 static IntRange forValueOfType(ASTContext &C, QualType T) {
10684 return forValueOfCanonicalType(C,
10686 }
10687
10688 /// Returns the range of an opaque value of a canonical integral type.
10689 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10690 assert(T->isCanonicalUnqualified());
10691
10692 if (const auto *VT = dyn_cast<VectorType>(T))
10693 T = VT->getElementType().getTypePtr();
10694 if (const auto *CT = dyn_cast<ComplexType>(T))
10695 T = CT->getElementType().getTypePtr();
10696 if (const auto *AT = dyn_cast<AtomicType>(T))
10697 T = AT->getValueType().getTypePtr();
10698
10699 if (!C.getLangOpts().CPlusPlus) {
10700 // For enum types in C code, use the underlying datatype.
10701 if (const auto *ED = T->getAsEnumDecl())
10702 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
10703 } else if (auto *Enum = T->getAsEnumDecl()) {
10704 // For enum types in C++, use the known bit width of the enumerators.
10705 // In C++11, enums can have a fixed underlying type. Use this type to
10706 // compute the range.
10707 if (Enum->isFixed()) {
10708 return IntRange(C.getIntWidth(QualType(T, 0)),
10709 !Enum->getIntegerType()->isSignedIntegerType());
10710 }
10711
10712 unsigned NumPositive = Enum->getNumPositiveBits();
10713 unsigned NumNegative = Enum->getNumNegativeBits();
10714
10715 if (NumNegative == 0)
10716 return IntRange(NumPositive, true/*NonNegative*/);
10717 else
10718 return IntRange(std::max(NumPositive + 1, NumNegative),
10719 false/*NonNegative*/);
10720 }
10721
10722 if (const auto *EIT = dyn_cast<BitIntType>(T))
10723 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10724
10725 const BuiltinType *BT = cast<BuiltinType>(T);
10726 assert(BT->isInteger());
10727
10728 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10729 }
10730
10731 /// Returns the "target" range of a canonical integral type, i.e.
10732 /// the range of values expressible in the type.
10733 ///
10734 /// This matches forValueOfCanonicalType except that enums have the
10735 /// full range of their type, not the range of their enumerators.
10736 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10737 assert(T->isCanonicalUnqualified());
10738
10739 if (const VectorType *VT = dyn_cast<VectorType>(T))
10740 T = VT->getElementType().getTypePtr();
10741 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10742 T = CT->getElementType().getTypePtr();
10743 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10744 T = AT->getValueType().getTypePtr();
10745 if (const auto *ED = T->getAsEnumDecl())
10746 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
10747
10748 if (const auto *EIT = dyn_cast<BitIntType>(T))
10749 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10750
10751 const BuiltinType *BT = cast<BuiltinType>(T);
10752 assert(BT->isInteger());
10753
10754 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10755 }
10756
10757 /// Returns the supremum of two ranges: i.e. their conservative merge.
10758 static IntRange join(IntRange L, IntRange R) {
10759 bool Unsigned = L.NonNegative && R.NonNegative;
10760 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10761 L.NonNegative && R.NonNegative);
10762 }
10763
10764 /// Return the range of a bitwise-AND of the two ranges.
10765 static IntRange bit_and(IntRange L, IntRange R) {
10766 unsigned Bits = std::max(L.Width, R.Width);
10767 bool NonNegative = false;
10768 if (L.NonNegative) {
10769 Bits = std::min(Bits, L.Width);
10770 NonNegative = true;
10771 }
10772 if (R.NonNegative) {
10773 Bits = std::min(Bits, R.Width);
10774 NonNegative = true;
10775 }
10776 return IntRange(Bits, NonNegative);
10777 }
10778
10779 /// Return the range of a sum of the two ranges.
10780 static IntRange sum(IntRange L, IntRange R) {
10781 bool Unsigned = L.NonNegative && R.NonNegative;
10782 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10783 Unsigned);
10784 }
10785
10786 /// Return the range of a difference of the two ranges.
10787 static IntRange difference(IntRange L, IntRange R) {
10788 // We need a 1-bit-wider range if:
10789 // 1) LHS can be negative: least value can be reduced.
10790 // 2) RHS can be negative: greatest value can be increased.
10791 bool CanWiden = !L.NonNegative || !R.NonNegative;
10792 bool Unsigned = L.NonNegative && R.Width == 0;
10793 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10794 !Unsigned,
10795 Unsigned);
10796 }
10797
10798 /// Return the range of a product of the two ranges.
10799 static IntRange product(IntRange L, IntRange R) {
10800 // If both LHS and RHS can be negative, we can form
10801 // -2^L * -2^R = 2^(L + R)
10802 // which requires L + R + 1 value bits to represent.
10803 bool CanWiden = !L.NonNegative && !R.NonNegative;
10804 bool Unsigned = L.NonNegative && R.NonNegative;
10805 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10806 Unsigned);
10807 }
10808
10809 /// Return the range of a remainder operation between the two ranges.
10810 static IntRange rem(IntRange L, IntRange R) {
10811 // The result of a remainder can't be larger than the result of
10812 // either side. The sign of the result is the sign of the LHS.
10813 bool Unsigned = L.NonNegative;
10814 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10815 Unsigned);
10816 }
10817};
10818
10819} // namespace
10820
10821static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
10822 if (value.isSigned() && value.isNegative())
10823 return IntRange(value.getSignificantBits(), false);
10824
10825 if (value.getBitWidth() > MaxWidth)
10826 value = value.trunc(MaxWidth);
10827
10828 // isNonNegative() just checks the sign bit without considering
10829 // signedness.
10830 return IntRange(value.getActiveBits(), true);
10831}
10832
10833static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
10834 if (result.isInt())
10835 return GetValueRange(result.getInt(), MaxWidth);
10836
10837 if (result.isVector()) {
10838 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
10839 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10840 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
10841 R = IntRange::join(R, El);
10842 }
10843 return R;
10844 }
10845
10846 if (result.isComplexInt()) {
10847 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
10848 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
10849 return IntRange::join(R, I);
10850 }
10851
10852 // This can happen with lossless casts to intptr_t of "based" lvalues.
10853 // Assume it might use arbitrary bits.
10854 // FIXME: The only reason we need to pass the type in here is to get
10855 // the sign right on this one case. It would be nice if APValue
10856 // preserved this.
10857 assert(result.isLValue() || result.isAddrLabelDiff());
10858 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10859}
10860
10861static QualType GetExprType(const Expr *E) {
10862 QualType Ty = E->getType();
10863 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
10864 Ty = AtomicRHS->getValueType();
10865 return Ty;
10866}
10867
10868/// Attempts to estimate an approximate range for the given integer expression.
10869/// Returns a range if successful, otherwise it returns \c std::nullopt if a
10870/// reliable estimation cannot be determined.
10871///
10872/// \param MaxWidth The width to which the value will be truncated.
10873/// \param InConstantContext If \c true, interpret the expression within a
10874/// constant context.
10875/// \param Approximate If \c true, provide a likely range of values by assuming
10876/// that arithmetic on narrower types remains within those types.
10877/// If \c false, return a range that includes all possible values
10878/// resulting from the expression.
10879/// \returns A range of values that the expression might take, or
10880/// std::nullopt if a reliable estimation cannot be determined.
10881static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
10882 unsigned MaxWidth,
10883 bool InConstantContext,
10884 bool Approximate) {
10885 E = E->IgnoreParens();
10886
10887 // Try a full evaluation first.
10888 Expr::EvalResult result;
10889 if (E->EvaluateAsRValue(result, C, InConstantContext))
10890 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
10891
10892 // I think we only want to look through implicit casts here; if the
10893 // user has an explicit widening cast, we should treat the value as
10894 // being of the new, wider type.
10895 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10896 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10897 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10898 Approximate);
10899
10900 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10901
10902 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10903 CE->getCastKind() == CK_BooleanToSignedIntegral;
10904
10905 // Assume that non-integer casts can span the full range of the type.
10906 if (!isIntegerCast)
10907 return OutputTypeRange;
10908
10909 std::optional<IntRange> SubRange = TryGetExprRange(
10910 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
10911 InConstantContext, Approximate);
10912 if (!SubRange)
10913 return std::nullopt;
10914
10915 // Bail out if the subexpr's range is as wide as the cast type.
10916 if (SubRange->Width >= OutputTypeRange.Width)
10917 return OutputTypeRange;
10918
10919 // Otherwise, we take the smaller width, and we're non-negative if
10920 // either the output type or the subexpr is.
10921 return IntRange(SubRange->Width,
10922 SubRange->NonNegative || OutputTypeRange.NonNegative);
10923 }
10924
10925 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10926 // If we can fold the condition, just take that operand.
10927 bool CondResult;
10928 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10929 return TryGetExprRange(
10930 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
10931 InConstantContext, Approximate);
10932
10933 // Otherwise, conservatively merge.
10934 // TryGetExprRange requires an integer expression, but a throw expression
10935 // results in a void type.
10936 Expr *TrueExpr = CO->getTrueExpr();
10937 if (TrueExpr->getType()->isVoidType())
10938 return std::nullopt;
10939
10940 std::optional<IntRange> L =
10941 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
10942 if (!L)
10943 return std::nullopt;
10944
10945 Expr *FalseExpr = CO->getFalseExpr();
10946 if (FalseExpr->getType()->isVoidType())
10947 return std::nullopt;
10948
10949 std::optional<IntRange> R =
10950 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
10951 if (!R)
10952 return std::nullopt;
10953
10954 return IntRange::join(*L, *R);
10955 }
10956
10957 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10958 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
10959
10960 switch (BO->getOpcode()) {
10961 case BO_Cmp:
10962 llvm_unreachable("builtin <=> should have class type");
10963
10964 // Boolean-valued operations are single-bit and positive.
10965 case BO_LAnd:
10966 case BO_LOr:
10967 case BO_LT:
10968 case BO_GT:
10969 case BO_LE:
10970 case BO_GE:
10971 case BO_EQ:
10972 case BO_NE:
10973 return IntRange::forBoolType();
10974
10975 // The type of the assignments is the type of the LHS, so the RHS
10976 // is not necessarily the same type.
10977 case BO_MulAssign:
10978 case BO_DivAssign:
10979 case BO_RemAssign:
10980 case BO_AddAssign:
10981 case BO_SubAssign:
10982 case BO_XorAssign:
10983 case BO_OrAssign:
10984 // TODO: bitfields?
10985 return IntRange::forValueOfType(C, GetExprType(E));
10986
10987 // Simple assignments just pass through the RHS, which will have
10988 // been coerced to the LHS type.
10989 case BO_Assign:
10990 // TODO: bitfields?
10991 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10992 Approximate);
10993
10994 // Operations with opaque sources are black-listed.
10995 case BO_PtrMemD:
10996 case BO_PtrMemI:
10997 return IntRange::forValueOfType(C, GetExprType(E));
10998
10999 // Bitwise-and uses the *infinum* of the two source ranges.
11000 case BO_And:
11001 case BO_AndAssign:
11002 Combine = IntRange::bit_and;
11003 break;
11004
11005 // Left shift gets black-listed based on a judgement call.
11006 case BO_Shl:
11007 // ...except that we want to treat '1 << (blah)' as logically
11008 // positive. It's an important idiom.
11009 if (IntegerLiteral *I
11010 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11011 if (I->getValue() == 1) {
11012 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11013 return IntRange(R.Width, /*NonNegative*/ true);
11014 }
11015 }
11016 [[fallthrough]];
11017
11018 case BO_ShlAssign:
11019 return IntRange::forValueOfType(C, GetExprType(E));
11020
11021 // Right shift by a constant can narrow its left argument.
11022 case BO_Shr:
11023 case BO_ShrAssign: {
11024 std::optional<IntRange> L = TryGetExprRange(
11025 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11026 if (!L)
11027 return std::nullopt;
11028
11029 // If the shift amount is a positive constant, drop the width by
11030 // that much.
11031 if (std::optional<llvm::APSInt> shift =
11032 BO->getRHS()->getIntegerConstantExpr(C)) {
11033 if (shift->isNonNegative()) {
11034 if (shift->uge(L->Width))
11035 L->Width = (L->NonNegative ? 0 : 1);
11036 else
11037 L->Width -= shift->getZExtValue();
11038 }
11039 }
11040
11041 return L;
11042 }
11043
11044 // Comma acts as its right operand.
11045 case BO_Comma:
11046 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11047 Approximate);
11048
11049 case BO_Add:
11050 if (!Approximate)
11051 Combine = IntRange::sum;
11052 break;
11053
11054 case BO_Sub:
11055 if (BO->getLHS()->getType()->isPointerType())
11056 return IntRange::forValueOfType(C, GetExprType(E));
11057 if (!Approximate)
11058 Combine = IntRange::difference;
11059 break;
11060
11061 case BO_Mul:
11062 if (!Approximate)
11063 Combine = IntRange::product;
11064 break;
11065
11066 // The width of a division result is mostly determined by the size
11067 // of the LHS.
11068 case BO_Div: {
11069 // Don't 'pre-truncate' the operands.
11070 unsigned opWidth = C.getIntWidth(GetExprType(E));
11071 std::optional<IntRange> L = TryGetExprRange(
11072 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11073 if (!L)
11074 return std::nullopt;
11075
11076 // If the divisor is constant, use that.
11077 if (std::optional<llvm::APSInt> divisor =
11078 BO->getRHS()->getIntegerConstantExpr(C)) {
11079 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11080 if (log2 >= L->Width)
11081 L->Width = (L->NonNegative ? 0 : 1);
11082 else
11083 L->Width = std::min(L->Width - log2, MaxWidth);
11084 return L;
11085 }
11086
11087 // Otherwise, just use the LHS's width.
11088 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11089 // could be -1.
11090 std::optional<IntRange> R = TryGetExprRange(
11091 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11092 if (!R)
11093 return std::nullopt;
11094
11095 return IntRange(L->Width, L->NonNegative && R->NonNegative);
11096 }
11097
11098 case BO_Rem:
11099 Combine = IntRange::rem;
11100 break;
11101
11102 // The default behavior is okay for these.
11103 case BO_Xor:
11104 case BO_Or:
11105 break;
11106 }
11107
11108 // Combine the two ranges, but limit the result to the type in which we
11109 // performed the computation.
11110 QualType T = GetExprType(E);
11111 unsigned opWidth = C.getIntWidth(T);
11112 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
11113 InConstantContext, Approximate);
11114 if (!L)
11115 return std::nullopt;
11116
11117 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
11118 InConstantContext, Approximate);
11119 if (!R)
11120 return std::nullopt;
11121
11122 IntRange C = Combine(*L, *R);
11123 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11124 C.Width = std::min(C.Width, MaxWidth);
11125 return C;
11126 }
11127
11128 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11129 switch (UO->getOpcode()) {
11130 // Boolean-valued operations are white-listed.
11131 case UO_LNot:
11132 return IntRange::forBoolType();
11133
11134 // Operations with opaque sources are black-listed.
11135 case UO_Deref:
11136 case UO_AddrOf: // should be impossible
11137 return IntRange::forValueOfType(C, GetExprType(E));
11138
11139 case UO_Minus: {
11140 if (E->getType()->isUnsignedIntegerType()) {
11141 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11142 Approximate);
11143 }
11144
11145 std::optional<IntRange> SubRange = TryGetExprRange(
11146 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11147
11148 if (!SubRange)
11149 return std::nullopt;
11150
11151 // If the range was previously non-negative, we need an extra bit for the
11152 // sign bit. Otherwise, we need an extra bit because the negation of the
11153 // most-negative value is one bit wider than that value.
11154 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
11155 }
11156
11157 case UO_Not: {
11158 if (E->getType()->isUnsignedIntegerType()) {
11159 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11160 Approximate);
11161 }
11162
11163 std::optional<IntRange> SubRange = TryGetExprRange(
11164 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11165
11166 if (!SubRange)
11167 return std::nullopt;
11168
11169 // The width increments by 1 if the sub-expression cannot be negative
11170 // since it now can be.
11171 return IntRange(
11172 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
11173 false);
11174 }
11175
11176 default:
11177 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11178 Approximate);
11179 }
11180 }
11181
11182 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11183 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11184 Approximate);
11185
11186 if (const auto *BitField = E->getSourceBitField())
11187 return IntRange(BitField->getBitWidthValue(),
11188 BitField->getType()->isUnsignedIntegerOrEnumerationType());
11189
11190 if (GetExprType(E)->isVoidType())
11191 return std::nullopt;
11192
11193 return IntRange::forValueOfType(C, GetExprType(E));
11194}
11195
11196static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11197 bool InConstantContext,
11198 bool Approximate) {
11199 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11200 Approximate);
11201}
11202
11203/// Checks whether the given value, which currently has the given
11204/// source semantics, has the same value when coerced through the
11205/// target semantics.
11206static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11207 const llvm::fltSemantics &Src,
11208 const llvm::fltSemantics &Tgt) {
11209 llvm::APFloat truncated = value;
11210
11211 bool ignored;
11212 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11213 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11214
11215 return truncated.bitwiseIsEqual(value);
11216}
11217
11218/// Checks whether the given value, which currently has the given
11219/// source semantics, has the same value when coerced through the
11220/// target semantics.
11221///
11222/// The value might be a vector of floats (or a complex number).
11223static bool IsSameFloatAfterCast(const APValue &value,
11224 const llvm::fltSemantics &Src,
11225 const llvm::fltSemantics &Tgt) {
11226 if (value.isFloat())
11227 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11228
11229 if (value.isVector()) {
11230 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11231 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11232 return false;
11233 return true;
11234 }
11235
11236 assert(value.isComplexFloat());
11237 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11238 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11239}
11240
11241static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11242 bool IsListInit = false);
11243
11244static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
11245 // Suppress cases where we are comparing against an enum constant.
11246 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11247 if (isa<EnumConstantDecl>(DR->getDecl()))
11248 return true;
11249
11250 // Suppress cases where the value is expanded from a macro, unless that macro
11251 // is how a language represents a boolean literal. This is the case in both C
11252 // and Objective-C.
11253 SourceLocation BeginLoc = E->getBeginLoc();
11254 if (BeginLoc.isMacroID()) {
11255 StringRef MacroName = Lexer::getImmediateMacroName(
11256 BeginLoc, S.getSourceManager(), S.getLangOpts());
11257 return MacroName != "YES" && MacroName != "NO" &&
11258 MacroName != "true" && MacroName != "false";
11259 }
11260
11261 return false;
11262}
11263
11264static bool isKnownToHaveUnsignedValue(const Expr *E) {
11265 return E->getType()->isIntegerType() &&
11266 (!E->getType()->isSignedIntegerType() ||
11268}
11269
11270namespace {
11271/// The promoted range of values of a type. In general this has the
11272/// following structure:
11273///
11274/// |-----------| . . . |-----------|
11275/// ^ ^ ^ ^
11276/// Min HoleMin HoleMax Max
11277///
11278/// ... where there is only a hole if a signed type is promoted to unsigned
11279/// (in which case Min and Max are the smallest and largest representable
11280/// values).
11281struct PromotedRange {
11282 // Min, or HoleMax if there is a hole.
11283 llvm::APSInt PromotedMin;
11284 // Max, or HoleMin if there is a hole.
11285 llvm::APSInt PromotedMax;
11286
11287 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11288 if (R.Width == 0)
11289 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11290 else if (R.Width >= BitWidth && !Unsigned) {
11291 // Promotion made the type *narrower*. This happens when promoting
11292 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11293 // Treat all values of 'signed int' as being in range for now.
11294 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11295 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11296 } else {
11297 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11298 .extOrTrunc(BitWidth);
11299 PromotedMin.setIsUnsigned(Unsigned);
11300
11301 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11302 .extOrTrunc(BitWidth);
11303 PromotedMax.setIsUnsigned(Unsigned);
11304 }
11305 }
11306
11307 // Determine whether this range is contiguous (has no hole).
11308 bool isContiguous() const { return PromotedMin <= PromotedMax; }
11309
11310 // Where a constant value is within the range.
11311 enum ComparisonResult {
11312 LT = 0x1,
11313 LE = 0x2,
11314 GT = 0x4,
11315 GE = 0x8,
11316 EQ = 0x10,
11317 NE = 0x20,
11318 InRangeFlag = 0x40,
11319
11320 Less = LE | LT | NE,
11321 Min = LE | InRangeFlag,
11322 InRange = InRangeFlag,
11323 Max = GE | InRangeFlag,
11324 Greater = GE | GT | NE,
11325
11326 OnlyValue = LE | GE | EQ | InRangeFlag,
11327 InHole = NE
11328 };
11329
11330 ComparisonResult compare(const llvm::APSInt &Value) const {
11331 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11332 Value.isUnsigned() == PromotedMin.isUnsigned());
11333 if (!isContiguous()) {
11334 assert(Value.isUnsigned() && "discontiguous range for signed compare");
11335 if (Value.isMinValue()) return Min;
11336 if (Value.isMaxValue()) return Max;
11337 if (Value >= PromotedMin) return InRange;
11338 if (Value <= PromotedMax) return InRange;
11339 return InHole;
11340 }
11341
11342 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11343 case -1: return Less;
11344 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11345 case 1:
11346 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11347 case -1: return InRange;
11348 case 0: return Max;
11349 case 1: return Greater;
11350 }
11351 }
11352
11353 llvm_unreachable("impossible compare result");
11354 }
11355
11356 static std::optional<StringRef>
11357 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11358 if (Op == BO_Cmp) {
11359 ComparisonResult LTFlag = LT, GTFlag = GT;
11360 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11361
11362 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11363 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11364 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11365 return std::nullopt;
11366 }
11367
11368 ComparisonResult TrueFlag, FalseFlag;
11369 if (Op == BO_EQ) {
11370 TrueFlag = EQ;
11371 FalseFlag = NE;
11372 } else if (Op == BO_NE) {
11373 TrueFlag = NE;
11374 FalseFlag = EQ;
11375 } else {
11376 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11377 TrueFlag = LT;
11378 FalseFlag = GE;
11379 } else {
11380 TrueFlag = GT;
11381 FalseFlag = LE;
11382 }
11383 if (Op == BO_GE || Op == BO_LE)
11384 std::swap(TrueFlag, FalseFlag);
11385 }
11386 if (R & TrueFlag)
11387 return StringRef("true");
11388 if (R & FalseFlag)
11389 return StringRef("false");
11390 return std::nullopt;
11391 }
11392};
11393}
11394
11395static bool HasEnumType(const Expr *E) {
11396 // Strip off implicit integral promotions.
11397 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11398 if (ICE->getCastKind() != CK_IntegralCast &&
11399 ICE->getCastKind() != CK_NoOp)
11400 break;
11401 E = ICE->getSubExpr();
11402 }
11403
11404 return E->getType()->isEnumeralType();
11405}
11406
11407static int classifyConstantValue(Expr *Constant) {
11408 // The values of this enumeration are used in the diagnostics
11409 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11410 enum ConstantValueKind {
11411 Miscellaneous = 0,
11412 LiteralTrue,
11413 LiteralFalse
11414 };
11415 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11416 return BL->getValue() ? ConstantValueKind::LiteralTrue
11417 : ConstantValueKind::LiteralFalse;
11418 return ConstantValueKind::Miscellaneous;
11419}
11420
11422 Expr *Constant, Expr *Other,
11423 const llvm::APSInt &Value,
11424 bool RhsConstant) {
11426 return false;
11427
11428 Expr *OriginalOther = Other;
11429
11430 Constant = Constant->IgnoreParenImpCasts();
11431 Other = Other->IgnoreParenImpCasts();
11432
11433 // Suppress warnings on tautological comparisons between values of the same
11434 // enumeration type. There are only two ways we could warn on this:
11435 // - If the constant is outside the range of representable values of
11436 // the enumeration. In such a case, we should warn about the cast
11437 // to enumeration type, not about the comparison.
11438 // - If the constant is the maximum / minimum in-range value. For an
11439 // enumeratin type, such comparisons can be meaningful and useful.
11440 if (Constant->getType()->isEnumeralType() &&
11441 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11442 return false;
11443
11444 std::optional<IntRange> OtherValueRange = TryGetExprRange(
11445 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
11446 if (!OtherValueRange)
11447 return false;
11448
11449 QualType OtherT = Other->getType();
11450 if (const auto *AT = OtherT->getAs<AtomicType>())
11451 OtherT = AT->getValueType();
11452 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11453
11454 // Special case for ObjC BOOL on targets where its a typedef for a signed char
11455 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11456 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11457 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
11458 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11459
11460 // Whether we're treating Other as being a bool because of the form of
11461 // expression despite it having another type (typically 'int' in C).
11462 bool OtherIsBooleanDespiteType =
11463 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11464 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11465 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
11466
11467 // Check if all values in the range of possible values of this expression
11468 // lead to the same comparison outcome.
11469 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
11470 Value.isUnsigned());
11471 auto Cmp = OtherPromotedValueRange.compare(Value);
11472 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11473 if (!Result)
11474 return false;
11475
11476 // Also consider the range determined by the type alone. This allows us to
11477 // classify the warning under the proper diagnostic group.
11478 bool TautologicalTypeCompare = false;
11479 {
11480 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11481 Value.isUnsigned());
11482 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11483 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11484 RhsConstant)) {
11485 TautologicalTypeCompare = true;
11486 Cmp = TypeCmp;
11487 Result = TypeResult;
11488 }
11489 }
11490
11491 // Don't warn if the non-constant operand actually always evaluates to the
11492 // same value.
11493 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
11494 return false;
11495
11496 // Suppress the diagnostic for an in-range comparison if the constant comes
11497 // from a macro or enumerator. We don't want to diagnose
11498 //
11499 // some_long_value <= INT_MAX
11500 //
11501 // when sizeof(int) == sizeof(long).
11502 bool InRange = Cmp & PromotedRange::InRangeFlag;
11503 if (InRange && IsEnumConstOrFromMacro(S, Constant))
11504 return false;
11505
11506 // A comparison of an unsigned bit-field against 0 is really a type problem,
11507 // even though at the type level the bit-field might promote to 'signed int'.
11508 if (Other->refersToBitField() && InRange && Value == 0 &&
11509 Other->getType()->isUnsignedIntegerOrEnumerationType())
11510 TautologicalTypeCompare = true;
11511
11512 // If this is a comparison to an enum constant, include that
11513 // constant in the diagnostic.
11514 const EnumConstantDecl *ED = nullptr;
11515 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
11516 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11517
11518 // Should be enough for uint128 (39 decimal digits)
11519 SmallString<64> PrettySourceValue;
11520 llvm::raw_svector_ostream OS(PrettySourceValue);
11521 if (ED) {
11522 OS << '\'' << *ED << "' (" << Value << ")";
11523 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11524 Constant->IgnoreParenImpCasts())) {
11525 OS << (BL->getValue() ? "YES" : "NO");
11526 } else {
11527 OS << Value;
11528 }
11529
11530 if (!TautologicalTypeCompare) {
11531 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11532 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
11533 << E->getOpcodeStr() << OS.str() << *Result
11534 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11535 return true;
11536 }
11537
11538 if (IsObjCSignedCharBool) {
11540 S.PDiag(diag::warn_tautological_compare_objc_bool)
11541 << OS.str() << *Result);
11542 return true;
11543 }
11544
11545 // FIXME: We use a somewhat different formatting for the in-range cases and
11546 // cases involving boolean values for historical reasons. We should pick a
11547 // consistent way of presenting these diagnostics.
11548 if (!InRange || Other->isKnownToHaveBooleanValue()) {
11549
11551 E->getOperatorLoc(), E,
11552 S.PDiag(!InRange ? diag::warn_out_of_range_compare
11553 : diag::warn_tautological_bool_compare)
11554 << OS.str() << classifyConstantValue(Constant) << OtherT
11555 << OtherIsBooleanDespiteType << *Result
11556 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11557 } else {
11558 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11559 unsigned Diag =
11560 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11561 ? (HasEnumType(OriginalOther)
11562 ? diag::warn_unsigned_enum_always_true_comparison
11563 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11564 : diag::warn_unsigned_always_true_comparison)
11565 : diag::warn_tautological_constant_compare;
11566
11567 S.Diag(E->getOperatorLoc(), Diag)
11568 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11569 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11570 }
11571
11572 return true;
11573}
11574
11575/// Analyze the operands of the given comparison. Implements the
11576/// fallback case from AnalyzeComparison.
11581
11582/// Implements -Wsign-compare.
11583///
11584/// \param E the binary operator to check for warnings
11586 // The type the comparison is being performed in.
11587 QualType T = E->getLHS()->getType();
11588
11589 // Only analyze comparison operators where both sides have been converted to
11590 // the same type.
11592 return AnalyzeImpConvsInComparison(S, E);
11593
11594 // Don't analyze value-dependent comparisons directly.
11595 if (E->isValueDependent())
11596 return AnalyzeImpConvsInComparison(S, E);
11597
11598 Expr *LHS = E->getLHS();
11599 Expr *RHS = E->getRHS();
11600
11601 if (T->isIntegralType(S.Context)) {
11602 std::optional<llvm::APSInt> RHSValue =
11604 std::optional<llvm::APSInt> LHSValue =
11606
11607 // We don't care about expressions whose result is a constant.
11608 if (RHSValue && LHSValue)
11609 return AnalyzeImpConvsInComparison(S, E);
11610
11611 // We only care about expressions where just one side is literal
11612 if ((bool)RHSValue ^ (bool)LHSValue) {
11613 // Is the constant on the RHS or LHS?
11614 const bool RhsConstant = (bool)RHSValue;
11615 Expr *Const = RhsConstant ? RHS : LHS;
11616 Expr *Other = RhsConstant ? LHS : RHS;
11617 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11618
11619 // Check whether an integer constant comparison results in a value
11620 // of 'true' or 'false'.
11621 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11622 return AnalyzeImpConvsInComparison(S, E);
11623 }
11624 }
11625
11626 if (!T->hasUnsignedIntegerRepresentation()) {
11627 // We don't do anything special if this isn't an unsigned integral
11628 // comparison: we're only interested in integral comparisons, and
11629 // signed comparisons only happen in cases we don't care to warn about.
11630 return AnalyzeImpConvsInComparison(S, E);
11631 }
11632
11633 LHS = LHS->IgnoreParenImpCasts();
11634 RHS = RHS->IgnoreParenImpCasts();
11635
11636 if (!S.getLangOpts().CPlusPlus) {
11637 // Avoid warning about comparison of integers with different signs when
11638 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11639 // the type of `E`.
11640 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11641 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11642 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11643 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11644 }
11645
11646 // Check to see if one of the (unmodified) operands is of different
11647 // signedness.
11648 Expr *signedOperand, *unsignedOperand;
11650 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11651 "unsigned comparison between two signed integer expressions?");
11652 signedOperand = LHS;
11653 unsignedOperand = RHS;
11654 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11655 signedOperand = RHS;
11656 unsignedOperand = LHS;
11657 } else {
11658 return AnalyzeImpConvsInComparison(S, E);
11659 }
11660
11661 // Otherwise, calculate the effective range of the signed operand.
11662 std::optional<IntRange> signedRange =
11664 /*Approximate=*/true);
11665 if (!signedRange)
11666 return;
11667
11668 // Go ahead and analyze implicit conversions in the operands. Note
11669 // that we skip the implicit conversions on both sides.
11672
11673 // If the signed range is non-negative, -Wsign-compare won't fire.
11674 if (signedRange->NonNegative)
11675 return;
11676
11677 // For (in)equality comparisons, if the unsigned operand is a
11678 // constant which cannot collide with a overflowed signed operand,
11679 // then reinterpreting the signed operand as unsigned will not
11680 // change the result of the comparison.
11681 if (E->isEqualityOp()) {
11682 unsigned comparisonWidth = S.Context.getIntWidth(T);
11683 std::optional<IntRange> unsignedRange = TryGetExprRange(
11684 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
11685 /*Approximate=*/true);
11686 if (!unsignedRange)
11687 return;
11688
11689 // We should never be unable to prove that the unsigned operand is
11690 // non-negative.
11691 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
11692
11693 if (unsignedRange->Width < comparisonWidth)
11694 return;
11695 }
11696
11698 S.PDiag(diag::warn_mixed_sign_comparison)
11699 << LHS->getType() << RHS->getType()
11700 << LHS->getSourceRange() << RHS->getSourceRange());
11701}
11702
11703/// Analyzes an attempt to assign the given value to a bitfield.
11704///
11705/// Returns true if there was something fishy about the attempt.
11707 SourceLocation InitLoc) {
11708 assert(Bitfield->isBitField());
11709 if (Bitfield->isInvalidDecl())
11710 return false;
11711
11712 // White-list bool bitfields.
11713 QualType BitfieldType = Bitfield->getType();
11714 if (BitfieldType->isBooleanType())
11715 return false;
11716
11717 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
11718 // If the underlying enum type was not explicitly specified as an unsigned
11719 // type and the enum contain only positive values, MSVC++ will cause an
11720 // inconsistency by storing this as a signed type.
11721 if (S.getLangOpts().CPlusPlus11 &&
11722 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11723 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11724 BitfieldEnumDecl->getNumNegativeBits() == 0) {
11725 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11726 << BitfieldEnumDecl;
11727 }
11728 }
11729
11730 // Ignore value- or type-dependent expressions.
11731 if (Bitfield->getBitWidth()->isValueDependent() ||
11732 Bitfield->getBitWidth()->isTypeDependent() ||
11733 Init->isValueDependent() ||
11734 Init->isTypeDependent())
11735 return false;
11736
11737 Expr *OriginalInit = Init->IgnoreParenImpCasts();
11738 unsigned FieldWidth = Bitfield->getBitWidthValue();
11739
11740 Expr::EvalResult Result;
11741 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11743 // The RHS is not constant. If the RHS has an enum type, make sure the
11744 // bitfield is wide enough to hold all the values of the enum without
11745 // truncation.
11746 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
11747 const PreferredTypeAttr *PTAttr = nullptr;
11748 if (!ED) {
11749 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
11750 if (PTAttr)
11751 ED = PTAttr->getType()->getAsEnumDecl();
11752 }
11753 if (ED) {
11754 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
11755
11756 // Enum types are implicitly signed on Windows, so check if there are any
11757 // negative enumerators to see if the enum was intended to be signed or
11758 // not.
11759 bool SignedEnum = ED->getNumNegativeBits() > 0;
11760
11761 // Check for surprising sign changes when assigning enum values to a
11762 // bitfield of different signedness. If the bitfield is signed and we
11763 // have exactly the right number of bits to store this unsigned enum,
11764 // suggest changing the enum to an unsigned type. This typically happens
11765 // on Windows where unfixed enums always use an underlying type of 'int'.
11766 unsigned DiagID = 0;
11767 if (SignedEnum && !SignedBitfield) {
11768 DiagID =
11769 PTAttr == nullptr
11770 ? diag::warn_unsigned_bitfield_assigned_signed_enum
11771 : diag::
11772 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
11773 } else if (SignedBitfield && !SignedEnum &&
11774 ED->getNumPositiveBits() == FieldWidth) {
11775 DiagID =
11776 PTAttr == nullptr
11777 ? diag::warn_signed_bitfield_enum_conversion
11778 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
11779 }
11780 if (DiagID) {
11781 S.Diag(InitLoc, DiagID) << Bitfield << ED;
11782 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11783 SourceRange TypeRange =
11784 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11785 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11786 << SignedEnum << TypeRange;
11787 if (PTAttr)
11788 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
11789 << ED;
11790 }
11791
11792 // Compute the required bitwidth. If the enum has negative values, we need
11793 // one more bit than the normal number of positive bits to represent the
11794 // sign bit.
11795 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11796 ED->getNumNegativeBits())
11797 : ED->getNumPositiveBits();
11798
11799 // Check the bitwidth.
11800 if (BitsNeeded > FieldWidth) {
11801 Expr *WidthExpr = Bitfield->getBitWidth();
11802 auto DiagID =
11803 PTAttr == nullptr
11804 ? diag::warn_bitfield_too_small_for_enum
11805 : diag::warn_preferred_type_bitfield_too_small_for_enum;
11806 S.Diag(InitLoc, DiagID) << Bitfield << ED;
11807 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11808 << BitsNeeded << ED << WidthExpr->getSourceRange();
11809 if (PTAttr)
11810 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
11811 << ED;
11812 }
11813 }
11814
11815 return false;
11816 }
11817
11818 llvm::APSInt Value = Result.Val.getInt();
11819
11820 unsigned OriginalWidth = Value.getBitWidth();
11821
11822 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
11823 // false positives where the user is demonstrating they intend to use the
11824 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
11825 // to a one-bit bit-field to see if the value came from a macro named 'true'.
11826 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
11827 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
11828 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
11829 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
11830 S.findMacroSpelling(MaybeMacroLoc, "true"))
11831 return false;
11832 }
11833
11834 if (!Value.isSigned() || Value.isNegative())
11835 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11836 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11837 OriginalWidth = Value.getSignificantBits();
11838
11839 if (OriginalWidth <= FieldWidth)
11840 return false;
11841
11842 // Compute the value which the bitfield will contain.
11843 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11844 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11845
11846 // Check whether the stored value is equal to the original value.
11847 TruncatedValue = TruncatedValue.extend(OriginalWidth);
11848 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11849 return false;
11850
11851 std::string PrettyValue = toString(Value, 10);
11852 std::string PrettyTrunc = toString(TruncatedValue, 10);
11853
11854 S.Diag(InitLoc, OneAssignedToOneBitBitfield
11855 ? diag::warn_impcast_single_bit_bitield_precision_constant
11856 : diag::warn_impcast_bitfield_precision_constant)
11857 << PrettyValue << PrettyTrunc << OriginalInit->getType()
11858 << Init->getSourceRange();
11859
11860 return true;
11861}
11862
11863/// Analyze the given simple or compound assignment for warning-worthy
11864/// operations.
11866 // Just recurse on the LHS.
11868
11869 // We want to recurse on the RHS as normal unless we're assigning to
11870 // a bitfield.
11871 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11872 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11873 E->getOperatorLoc())) {
11874 // Recurse, ignoring any implicit conversions on the RHS.
11876 E->getOperatorLoc());
11877 }
11878 }
11879
11881
11882 // Diagnose implicitly sequentially-consistent atomic assignment.
11883 if (E->getLHS()->getType()->isAtomicType())
11884 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11885}
11886
11887/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
11888static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
11889 QualType T, SourceLocation CContext, unsigned diag,
11890 bool PruneControlFlow = false) {
11891 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
11892 // address space annotations isn't really useful. The warnings aren't because
11893 // you're converting a `private int` to `unsigned int`, it is because you're
11894 // conerting `int` to `unsigned int`.
11895 if (SourceType.hasAddressSpace())
11896 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
11897 if (T.hasAddressSpace())
11899 if (PruneControlFlow) {
11901 S.PDiag(diag)
11902 << SourceType << T << E->getSourceRange()
11903 << SourceRange(CContext));
11904 return;
11905 }
11906 S.Diag(E->getExprLoc(), diag)
11907 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11908}
11909
11910/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
11911static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
11912 SourceLocation CContext, unsigned diag,
11913 bool PruneControlFlow = false) {
11914 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
11915}
11916
11917/// Diagnose an implicit cast from a floating point value to an integer value.
11918static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
11919 SourceLocation CContext) {
11920 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11921 bool PruneWarnings = S.inTemplateInstantiation();
11922
11923 const Expr *InnerE = E->IgnoreParenImpCasts();
11924 // We also want to warn on, e.g., "int i = -1.234"
11925 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
11926 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11927 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11928
11929 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11930
11931 llvm::APFloat Value(0.0);
11932 bool IsConstant =
11934 if (!IsConstant) {
11935 if (S.ObjC().isSignedCharBool(T)) {
11937 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11938 << E->getType());
11939 }
11940
11941 return DiagnoseImpCast(S, E, T, CContext,
11942 diag::warn_impcast_float_integer, PruneWarnings);
11943 }
11944
11945 bool isExact = false;
11946
11947 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11948 T->hasUnsignedIntegerRepresentation());
11949 llvm::APFloat::opStatus Result = Value.convertToInteger(
11950 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11951
11952 // FIXME: Force the precision of the source value down so we don't print
11953 // digits which are usually useless (we don't really care here if we
11954 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
11955 // would automatically print the shortest representation, but it's a bit
11956 // tricky to implement.
11957 SmallString<16> PrettySourceValue;
11958 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11959 precision = (precision * 59 + 195) / 196;
11960 Value.toString(PrettySourceValue, precision);
11961
11962 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
11964 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11965 << PrettySourceValue);
11966 }
11967
11968 if (Result == llvm::APFloat::opOK && isExact) {
11969 if (IsLiteral) return;
11970 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11971 PruneWarnings);
11972 }
11973
11974 // Conversion of a floating-point value to a non-bool integer where the
11975 // integral part cannot be represented by the integer type is undefined.
11976 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11977 return DiagnoseImpCast(
11978 S, E, T, CContext,
11979 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11980 : diag::warn_impcast_float_to_integer_out_of_range,
11981 PruneWarnings);
11982
11983 unsigned DiagID = 0;
11984 if (IsLiteral) {
11985 // Warn on floating point literal to integer.
11986 DiagID = diag::warn_impcast_literal_float_to_integer;
11987 } else if (IntegerValue == 0) {
11988 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
11989 return DiagnoseImpCast(S, E, T, CContext,
11990 diag::warn_impcast_float_integer, PruneWarnings);
11991 }
11992 // Warn on non-zero to zero conversion.
11993 DiagID = diag::warn_impcast_float_to_integer_zero;
11994 } else {
11995 if (IntegerValue.isUnsigned()) {
11996 if (!IntegerValue.isMaxValue()) {
11997 return DiagnoseImpCast(S, E, T, CContext,
11998 diag::warn_impcast_float_integer, PruneWarnings);
11999 }
12000 } else { // IntegerValue.isSigned()
12001 if (!IntegerValue.isMaxSignedValue() &&
12002 !IntegerValue.isMinSignedValue()) {
12003 return DiagnoseImpCast(S, E, T, CContext,
12004 diag::warn_impcast_float_integer, PruneWarnings);
12005 }
12006 }
12007 // Warn on evaluatable floating point expression to integer conversion.
12008 DiagID = diag::warn_impcast_float_to_integer;
12009 }
12010
12011 SmallString<16> PrettyTargetValue;
12012 if (IsBool)
12013 PrettyTargetValue = Value.isZero() ? "false" : "true";
12014 else
12015 IntegerValue.toString(PrettyTargetValue);
12016
12017 if (PruneWarnings) {
12019 S.PDiag(DiagID)
12020 << E->getType() << T.getUnqualifiedType()
12021 << PrettySourceValue << PrettyTargetValue
12022 << E->getSourceRange() << SourceRange(CContext));
12023 } else {
12024 S.Diag(E->getExprLoc(), DiagID)
12025 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12026 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12027 }
12028}
12029
12030/// Analyze the given compound assignment for the possible losing of
12031/// floating-point precision.
12033 assert(isa<CompoundAssignOperator>(E) &&
12034 "Must be compound assignment operation");
12035 // Recurse on the LHS and RHS in here
12038
12039 if (E->getLHS()->getType()->isAtomicType())
12040 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12041
12042 // Now check the outermost expression
12043 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12044 const auto *RBT = cast<CompoundAssignOperator>(E)
12045 ->getComputationResultType()
12046 ->getAs<BuiltinType>();
12047
12048 // The below checks assume source is floating point.
12049 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12050
12051 // If source is floating point but target is an integer.
12052 if (ResultBT->isInteger())
12053 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12054 E->getExprLoc(), diag::warn_impcast_float_integer);
12055
12056 if (!ResultBT->isFloatingPoint())
12057 return;
12058
12059 // If both source and target are floating points, warn about losing precision.
12061 QualType(ResultBT, 0), QualType(RBT, 0));
12062 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12063 // warn about dropping FP rank.
12064 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12065 diag::warn_impcast_float_result_precision);
12066}
12067
12068static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12069 IntRange Range) {
12070 if (!Range.Width) return "0";
12071
12072 llvm::APSInt ValueInRange = Value;
12073 ValueInRange.setIsSigned(!Range.NonNegative);
12074 ValueInRange = ValueInRange.trunc(Range.Width);
12075 return toString(ValueInRange, 10);
12076}
12077
12078static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
12079 bool ToBool) {
12080 if (!isa<ImplicitCastExpr>(Ex))
12081 return false;
12082
12083 const Expr *InnerE = Ex->IgnoreParenImpCasts();
12085 const Type *Source =
12087 if (Target->isDependentType())
12088 return false;
12089
12090 const auto *FloatCandidateBT =
12091 dyn_cast<BuiltinType>(ToBool ? Source : Target);
12092 const Type *BoolCandidateType = ToBool ? Target : Source;
12093
12094 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12095 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12096}
12097
12098static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
12099 SourceLocation CC) {
12100 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
12101 const Expr *CurrA = TheCall->getArg(I);
12102 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12103 continue;
12104
12105 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
12106 S, TheCall->getArg(I - 1), false));
12107 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
12108 S, TheCall->getArg(I + 1), false));
12109 if (IsSwapped) {
12110 // Warn on this floating-point to bool conversion.
12112 CurrA->getType(), CC,
12113 diag::warn_impcast_floating_point_to_bool);
12114 }
12115 }
12116}
12117
12119 SourceLocation CC) {
12120 // Don't warn on functions which have return type nullptr_t.
12121 if (isa<CallExpr>(E))
12122 return;
12123
12124 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12125 const Expr *NewE = E->IgnoreParenImpCasts();
12126 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
12127 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12128 if (!IsGNUNullExpr && !HasNullPtrType)
12129 return;
12130
12131 // Return if target type is a safe conversion.
12132 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12133 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12134 return;
12135
12136 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12137 E->getExprLoc()))
12138 return;
12139
12141
12142 // Venture through the macro stacks to get to the source of macro arguments.
12143 // The new location is a better location than the complete location that was
12144 // passed in.
12145 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12147
12148 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12149 if (IsGNUNullExpr && Loc.isMacroID()) {
12150 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12151 Loc, S.SourceMgr, S.getLangOpts());
12152 if (MacroName == "NULL")
12154 }
12155
12156 // Only warn if the null and context location are in the same macro expansion.
12157 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12158 return;
12159
12160 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12161 << HasNullPtrType << T << SourceRange(CC)
12164}
12165
12166// Helper function to filter out cases for constant width constant conversion.
12167// Don't warn on char array initialization or for non-decimal values.
12169 SourceLocation CC) {
12170 // If initializing from a constant, and the constant starts with '0',
12171 // then it is a binary, octal, or hexadecimal. Allow these constants
12172 // to fill all the bits, even if there is a sign change.
12173 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12174 const char FirstLiteralCharacter =
12175 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12176 if (FirstLiteralCharacter == '0')
12177 return false;
12178 }
12179
12180 // If the CC location points to a '{', and the type is char, then assume
12181 // assume it is an array initialization.
12182 if (CC.isValid() && T->isCharType()) {
12183 const char FirstContextCharacter =
12185 if (FirstContextCharacter == '{')
12186 return false;
12187 }
12188
12189 return true;
12190}
12191
12193 const auto *IL = dyn_cast<IntegerLiteral>(E);
12194 if (!IL) {
12195 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12196 if (UO->getOpcode() == UO_Minus)
12197 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12198 }
12199 }
12200
12201 return IL;
12202}
12203
12205 E = E->IgnoreParenImpCasts();
12206 SourceLocation ExprLoc = E->getExprLoc();
12207
12208 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12209 BinaryOperator::Opcode Opc = BO->getOpcode();
12210 Expr::EvalResult Result;
12211 // Do not diagnose unsigned shifts.
12212 if (Opc == BO_Shl) {
12213 const auto *LHS = getIntegerLiteral(BO->getLHS());
12214 const auto *RHS = getIntegerLiteral(BO->getRHS());
12215 if (LHS && LHS->getValue() == 0)
12216 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12217 else if (!E->isValueDependent() && LHS && RHS &&
12218 RHS->getValue().isNonNegative() &&
12220 S.Diag(ExprLoc, diag::warn_left_shift_always)
12221 << (Result.Val.getInt() != 0);
12222 else if (E->getType()->isSignedIntegerType())
12223 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
12226 ") != 0");
12227 }
12228 }
12229
12230 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12231 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12232 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12233 if (!LHS || !RHS)
12234 return;
12235 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12236 (RHS->getValue() == 0 || RHS->getValue() == 1))
12237 // Do not diagnose common idioms.
12238 return;
12239 if (LHS->getValue() != 0 && RHS->getValue() != 0)
12240 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12241 }
12242}
12243
12245 const Type *Target, Expr *E,
12246 QualType T,
12247 SourceLocation CC) {
12248 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
12249 Source != Target);
12250 Expr::EvalResult Result;
12253 llvm::APSInt Value(32);
12254 Value = Result.Val.getInt();
12255 bool IsASCII = Value <= 0x7F;
12256 bool IsBMP = Value <= 0xD7FF || (Value >= 0xE000 && Value <= 0xFFFF);
12257 bool ConversionPreservesSemantics =
12258 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
12259
12260 if (!ConversionPreservesSemantics) {
12261 auto IsSingleCodeUnitCP = [](const QualType &T,
12262 const llvm::APSInt &Value) {
12263 if (T->isChar8Type())
12264 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
12265 if (T->isChar16Type())
12266 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
12267 assert(T->isChar32Type());
12268 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
12269 };
12270
12271 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
12272 << E->getType() << T
12273 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
12274 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
12275 }
12276 } else {
12277 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
12279 DiagnoseImpCast(S, E, T, CC,
12280 LosesPrecision ? diag::warn_impcast_unicode_precision
12281 : diag::warn_impcast_unicode_char_type);
12282 }
12283}
12284
12290
12292 QualType To) {
12293 QualType MaybePointee = From->getPointeeType();
12294 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12295 From = MaybePointee;
12296 MaybePointee = To->getPointeeType();
12297 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12298 To = MaybePointee;
12299
12300 if (const auto *FromFn = From->getAs<FunctionType>()) {
12301 if (const auto *ToFn = To->getAs<FunctionType>()) {
12302 if (FromFn->getCFIUncheckedCalleeAttr() &&
12303 !ToFn->getCFIUncheckedCalleeAttr())
12304 return Discarding;
12305 if (!FromFn->getCFIUncheckedCalleeAttr() &&
12306 ToFn->getCFIUncheckedCalleeAttr())
12307 return Adding;
12308 }
12309 }
12310 return None;
12311}
12312
12314 From = Context.getCanonicalType(From);
12315 To = Context.getCanonicalType(To);
12316 return ::AdjustingCFIUncheckedCallee(From, To) == Discarding;
12317}
12318
12320 From = Context.getCanonicalType(From);
12321 To = Context.getCanonicalType(To);
12322 return ::AdjustingCFIUncheckedCallee(From, To) == Adding;
12323}
12324
12326 bool *ICContext, bool IsListInit) {
12327 if (E->isTypeDependent() || E->isValueDependent()) return;
12328
12329 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
12330 const Type *Target = Context.getCanonicalType(T).getTypePtr();
12331 if (Source == Target) return;
12332 if (Target->isDependentType()) return;
12333
12334 // If the conversion context location is invalid don't complain. We also
12335 // don't want to emit a warning if the issue occurs from the expansion of
12336 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12337 // delay this check as long as possible. Once we detect we are in that
12338 // scenario, we just return.
12339 if (CC.isInvalid())
12340 return;
12341
12342 if (Source->isAtomicType())
12343 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12344
12345 // Diagnose implicit casts to bool.
12346 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12347 if (isa<StringLiteral>(E))
12348 // Warn on string literal to bool. Checks for string literals in logical
12349 // and expressions, for instance, assert(0 && "error here"), are
12350 // prevented by a check in AnalyzeImplicitConversions().
12351 return DiagnoseImpCast(*this, E, T, CC,
12352 diag::warn_impcast_string_literal_to_bool);
12355 // This covers the literal expressions that evaluate to Objective-C
12356 // objects.
12357 return DiagnoseImpCast(*this, E, T, CC,
12358 diag::warn_impcast_objective_c_literal_to_bool);
12359 }
12360 if (Source->isPointerType() || Source->canDecayToPointerType()) {
12361 // Warn on pointer to bool conversion that is always true.
12363 SourceRange(CC));
12364 }
12365 }
12366
12367 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12368 // is a typedef for signed char (macOS), then that constant value has to be 1
12369 // or 0.
12370 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
12373 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12375 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12376 << toString(Result.Val.getInt(), 10));
12377 }
12378 return;
12379 }
12380 }
12381
12382 // Check implicit casts from Objective-C collection literals to specialized
12383 // collection types, e.g., NSArray<NSString *> *.
12384 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12385 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
12386 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12387 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
12388
12389 // Strip vector types.
12390 if (isa<VectorType>(Source)) {
12391 if (Target->isSveVLSBuiltinType() &&
12392 (ARM().areCompatibleSveTypes(QualType(Target, 0),
12393 QualType(Source, 0)) ||
12394 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
12395 QualType(Source, 0))))
12396 return;
12397
12398 if (Target->isRVVVLSBuiltinType() &&
12399 (Context.areCompatibleRVVTypes(QualType(Target, 0),
12400 QualType(Source, 0)) ||
12401 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
12402 QualType(Source, 0))))
12403 return;
12404
12405 if (!isa<VectorType>(Target)) {
12406 if (SourceMgr.isInSystemMacro(CC))
12407 return;
12408 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
12409 } else if (getLangOpts().HLSL &&
12410 Target->castAs<VectorType>()->getNumElements() <
12411 Source->castAs<VectorType>()->getNumElements()) {
12412 // Diagnose vector truncation but don't return. We may also want to
12413 // diagnose an element conversion.
12414 DiagnoseImpCast(*this, E, T, CC,
12415 diag::warn_hlsl_impcast_vector_truncation);
12416 }
12417
12418 // If the vector cast is cast between two vectors of the same size, it is
12419 // a bitcast, not a conversion, except under HLSL where it is a conversion.
12420 if (!getLangOpts().HLSL &&
12421 Context.getTypeSize(Source) == Context.getTypeSize(Target))
12422 return;
12423
12424 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12425 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12426 }
12427 if (auto VecTy = dyn_cast<VectorType>(Target))
12428 Target = VecTy->getElementType().getTypePtr();
12429
12430 // Strip complex types.
12431 if (isa<ComplexType>(Source)) {
12432 if (!isa<ComplexType>(Target)) {
12433 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12434 return;
12435
12436 return DiagnoseImpCast(*this, E, T, CC,
12438 ? diag::err_impcast_complex_scalar
12439 : diag::warn_impcast_complex_scalar);
12440 }
12441
12442 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12443 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12444 }
12445
12446 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12447 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12448
12449 // Strip SVE vector types
12450 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
12451 // Need the original target type for vector type checks
12452 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
12453 // Handle conversion from scalable to fixed when msve-vector-bits is
12454 // specified
12455 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
12456 QualType(Source, 0)) ||
12457 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
12458 QualType(Source, 0)))
12459 return;
12460
12461 // If the vector cast is cast between two vectors of the same size, it is
12462 // a bitcast, not a conversion.
12463 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
12464 return;
12465
12466 Source = SourceBT->getSveEltType(Context).getTypePtr();
12467 }
12468
12469 if (TargetBT && TargetBT->isSveVLSBuiltinType())
12470 Target = TargetBT->getSveEltType(Context).getTypePtr();
12471
12472 // If the source is floating point...
12473 if (SourceBT && SourceBT->isFloatingPoint()) {
12474 // ...and the target is floating point...
12475 if (TargetBT && TargetBT->isFloatingPoint()) {
12476 // ...then warn if we're dropping FP rank.
12477
12479 QualType(SourceBT, 0), QualType(TargetBT, 0));
12480 if (Order > 0) {
12481 // Don't warn about float constants that are precisely
12482 // representable in the target type.
12483 Expr::EvalResult result;
12484 if (E->EvaluateAsRValue(result, Context)) {
12485 // Value might be a float, a float vector, or a float complex.
12487 result.Val,
12488 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12489 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12490 return;
12491 }
12492
12493 if (SourceMgr.isInSystemMacro(CC))
12494 return;
12495
12496 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
12497 }
12498 // ... or possibly if we're increasing rank, too
12499 else if (Order < 0) {
12500 if (SourceMgr.isInSystemMacro(CC))
12501 return;
12502
12503 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
12504 }
12505 return;
12506 }
12507
12508 // If the target is integral, always warn.
12509 if (TargetBT && TargetBT->isInteger()) {
12510 if (SourceMgr.isInSystemMacro(CC))
12511 return;
12512
12513 DiagnoseFloatingImpCast(*this, E, T, CC);
12514 }
12515
12516 // Detect the case where a call result is converted from floating-point to
12517 // to bool, and the final argument to the call is converted from bool, to
12518 // discover this typo:
12519 //
12520 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
12521 //
12522 // FIXME: This is an incredibly special case; is there some more general
12523 // way to detect this class of misplaced-parentheses bug?
12524 if (Target->isBooleanType() && isa<CallExpr>(E)) {
12525 // Check last argument of function call to see if it is an
12526 // implicit cast from a type matching the type the result
12527 // is being cast to.
12528 CallExpr *CEx = cast<CallExpr>(E);
12529 if (unsigned NumArgs = CEx->getNumArgs()) {
12530 Expr *LastA = CEx->getArg(NumArgs - 1);
12531 Expr *InnerE = LastA->IgnoreParenImpCasts();
12532 if (isa<ImplicitCastExpr>(LastA) &&
12533 InnerE->getType()->isBooleanType()) {
12534 // Warn on this floating-point to bool conversion
12535 DiagnoseImpCast(*this, E, T, CC,
12536 diag::warn_impcast_floating_point_to_bool);
12537 }
12538 }
12539 }
12540 return;
12541 }
12542
12543 // Valid casts involving fixed point types should be accounted for here.
12544 if (Source->isFixedPointType()) {
12545 if (Target->isUnsaturatedFixedPointType()) {
12549 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12550 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
12551 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
12552 if (Value > MaxVal || Value < MinVal) {
12554 PDiag(diag::warn_impcast_fixed_point_range)
12555 << Value.toString() << T
12556 << E->getSourceRange()
12557 << clang::SourceRange(CC));
12558 return;
12559 }
12560 }
12561 } else if (Target->isIntegerType()) {
12565 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12566
12567 bool Overflowed;
12568 llvm::APSInt IntResult = FXResult.convertToInt(
12569 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
12570 &Overflowed);
12571
12572 if (Overflowed) {
12574 PDiag(diag::warn_impcast_fixed_point_range)
12575 << FXResult.toString() << T
12576 << E->getSourceRange()
12577 << clang::SourceRange(CC));
12578 return;
12579 }
12580 }
12581 }
12582 } else if (Target->isUnsaturatedFixedPointType()) {
12583 if (Source->isIntegerType()) {
12587 llvm::APSInt Value = Result.Val.getInt();
12588
12589 bool Overflowed;
12590 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12591 Value, Context.getFixedPointSemantics(T), &Overflowed);
12592
12593 if (Overflowed) {
12595 PDiag(diag::warn_impcast_fixed_point_range)
12596 << toString(Value, /*Radix=*/10) << T
12597 << E->getSourceRange()
12598 << clang::SourceRange(CC));
12599 return;
12600 }
12601 }
12602 }
12603 }
12604
12605 // If we are casting an integer type to a floating point type without
12606 // initialization-list syntax, we might lose accuracy if the floating
12607 // point type has a narrower significand than the integer type.
12608 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12609 TargetBT->isFloatingType() && !IsListInit) {
12610 // Determine the number of precision bits in the source integer type.
12611 std::optional<IntRange> SourceRange =
12613 /*Approximate=*/true);
12614 if (!SourceRange)
12615 return;
12616 unsigned int SourcePrecision = SourceRange->Width;
12617
12618 // Determine the number of precision bits in the
12619 // target floating point type.
12620 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12621 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12622
12623 if (SourcePrecision > 0 && TargetPrecision > 0 &&
12624 SourcePrecision > TargetPrecision) {
12625
12626 if (std::optional<llvm::APSInt> SourceInt =
12628 // If the source integer is a constant, convert it to the target
12629 // floating point type. Issue a warning if the value changes
12630 // during the whole conversion.
12631 llvm::APFloat TargetFloatValue(
12632 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12633 llvm::APFloat::opStatus ConversionStatus =
12634 TargetFloatValue.convertFromAPInt(
12635 *SourceInt, SourceBT->isSignedInteger(),
12636 llvm::APFloat::rmNearestTiesToEven);
12637
12638 if (ConversionStatus != llvm::APFloat::opOK) {
12639 SmallString<32> PrettySourceValue;
12640 SourceInt->toString(PrettySourceValue, 10);
12641 SmallString<32> PrettyTargetValue;
12642 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12643
12645 E->getExprLoc(), E,
12646 PDiag(diag::warn_impcast_integer_float_precision_constant)
12647 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12648 << E->getSourceRange() << clang::SourceRange(CC));
12649 }
12650 } else {
12651 // Otherwise, the implicit conversion may lose precision.
12652 DiagnoseImpCast(*this, E, T, CC,
12653 diag::warn_impcast_integer_float_precision);
12654 }
12655 }
12656 }
12657
12658 DiagnoseNullConversion(*this, E, T, CC);
12659
12661
12662 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
12663 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
12664 return;
12665 }
12666
12667 if (Target->isBooleanType())
12668 DiagnoseIntInBoolContext(*this, E);
12669
12671 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
12672 << QualType(Source, 0) << QualType(Target, 0);
12673 }
12674
12675 if (!Source->isIntegerType() || !Target->isIntegerType())
12676 return;
12677
12678 // TODO: remove this early return once the false positives for constant->bool
12679 // in templates, macros, etc, are reduced or removed.
12680 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12681 return;
12682
12683 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
12684 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12686 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12687 << E->getType());
12688 }
12689 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
12690 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
12691 if (!LikelySourceRange)
12692 return;
12693
12694 IntRange SourceTypeRange =
12695 IntRange::forTargetOfCanonicalType(Context, Source);
12696 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
12697
12698 if (LikelySourceRange->Width > TargetRange.Width) {
12699 // If the source is a constant, use a default-on diagnostic.
12700 // TODO: this should happen for bitfield stores, too.
12704 llvm::APSInt Value(32);
12705 Value = Result.Val.getInt();
12706
12707 if (SourceMgr.isInSystemMacro(CC))
12708 return;
12709
12710 std::string PrettySourceValue = toString(Value, 10);
12711 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12712
12714 PDiag(diag::warn_impcast_integer_precision_constant)
12715 << PrettySourceValue << PrettyTargetValue
12716 << E->getType() << T << E->getSourceRange()
12717 << SourceRange(CC));
12718 return;
12719 }
12720
12721 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12722 if (SourceMgr.isInSystemMacro(CC))
12723 return;
12724
12725 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12726 if (UO->getOpcode() == UO_Minus)
12727 return DiagnoseImpCast(
12728 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
12729 }
12730
12731 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
12732 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
12733 /* pruneControlFlow */ true);
12734 return DiagnoseImpCast(*this, E, T, CC,
12735 diag::warn_impcast_integer_precision);
12736 }
12737
12738 if (TargetRange.Width > SourceTypeRange.Width) {
12739 if (auto *UO = dyn_cast<UnaryOperator>(E))
12740 if (UO->getOpcode() == UO_Minus)
12741 if (Source->isUnsignedIntegerType()) {
12742 if (Target->isUnsignedIntegerType())
12743 return DiagnoseImpCast(*this, E, T, CC,
12744 diag::warn_impcast_high_order_zero_bits);
12745 if (Target->isSignedIntegerType())
12746 return DiagnoseImpCast(*this, E, T, CC,
12747 diag::warn_impcast_nonnegative_result);
12748 }
12749 }
12750
12751 if (TargetRange.Width == LikelySourceRange->Width &&
12752 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
12753 Source->isSignedIntegerType()) {
12754 // Warn when doing a signed to signed conversion, warn if the positive
12755 // source value is exactly the width of the target type, which will
12756 // cause a negative value to be stored.
12757
12760 !SourceMgr.isInSystemMacro(CC)) {
12761 llvm::APSInt Value = Result.Val.getInt();
12762 if (isSameWidthConstantConversion(*this, E, T, CC)) {
12763 std::string PrettySourceValue = toString(Value, 10);
12764 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12765
12766 Diag(E->getExprLoc(),
12767 PDiag(diag::warn_impcast_integer_precision_constant)
12768 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12769 << E->getSourceRange() << SourceRange(CC));
12770 return;
12771 }
12772 }
12773
12774 // Fall through for non-constants to give a sign conversion warning.
12775 }
12776
12777 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
12778 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
12779 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
12780 LikelySourceRange->Width == TargetRange.Width))) {
12781 if (SourceMgr.isInSystemMacro(CC))
12782 return;
12783
12784 if (SourceBT && SourceBT->isInteger() && TargetBT &&
12785 TargetBT->isInteger() &&
12786 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
12787 return;
12788 }
12789
12790 unsigned DiagID = diag::warn_impcast_integer_sign;
12791
12792 // Traditionally, gcc has warned about this under -Wsign-compare.
12793 // We also want to warn about it in -Wconversion.
12794 // So if -Wconversion is off, use a completely identical diagnostic
12795 // in the sign-compare group.
12796 // The conditional-checking code will
12797 if (ICContext) {
12798 DiagID = diag::warn_impcast_integer_sign_conditional;
12799 *ICContext = true;
12800 }
12801
12802 DiagnoseImpCast(*this, E, T, CC, DiagID);
12803 }
12804
12805 // If we're implicitly converting from an integer into an enumeration, that
12806 // is valid in C but invalid in C++.
12807 QualType SourceType = E->getEnumCoercedType(Context);
12808 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
12809 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
12810 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
12811
12812 // Diagnose conversions between different enumeration types.
12813 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12814 // type, to give us better diagnostics.
12815 Source = Context.getCanonicalType(SourceType).getTypePtr();
12816
12817 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
12818 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
12819 if (SourceEnum->getOriginalDecl()->hasNameForLinkage() &&
12820 TargetEnum->getOriginalDecl()->hasNameForLinkage() &&
12821 SourceEnum != TargetEnum) {
12822 if (SourceMgr.isInSystemMacro(CC))
12823 return;
12824
12825 return DiagnoseImpCast(*this, E, SourceType, T, CC,
12826 diag::warn_impcast_different_enum_types);
12827 }
12828}
12829
12832
12834 SourceLocation CC, bool &ICContext) {
12835 E = E->IgnoreParenImpCasts();
12836 // Diagnose incomplete type for second or third operand in C.
12837 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
12838 S.RequireCompleteExprType(E, diag::err_incomplete_type);
12839
12840 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12841 return CheckConditionalOperator(S, CO, CC, T);
12842
12844 if (E->getType() != T)
12845 return S.CheckImplicitConversion(E, T, CC, &ICContext);
12846}
12847
12851
12852 Expr *TrueExpr = E->getTrueExpr();
12853 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12854 TrueExpr = BCO->getCommon();
12855
12856 bool Suspicious = false;
12857 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12858 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12859
12860 if (T->isBooleanType())
12862
12863 // If -Wconversion would have warned about either of the candidates
12864 // for a signedness conversion to the context type...
12865 if (!Suspicious) return;
12866
12867 // ...but it's currently ignored...
12868 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12869 return;
12870
12871 // ...then check whether it would have warned about either of the
12872 // candidates for a signedness conversion to the condition type.
12873 if (E->getType() == T) return;
12874
12875 Suspicious = false;
12876 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
12877 &Suspicious);
12878 if (!Suspicious)
12880 E->getType(), CC, &Suspicious);
12881}
12882
12883/// Check conversion of given expression to boolean.
12884/// Input argument E is a logical expression.
12886 // Run the bool-like conversion checks only for C since there bools are
12887 // still not used as the return type from "boolean" operators or as the input
12888 // type for conditional operators.
12889 if (S.getLangOpts().CPlusPlus)
12890 return;
12892 return;
12894}
12895
12896namespace {
12897struct AnalyzeImplicitConversionsWorkItem {
12898 Expr *E;
12899 SourceLocation CC;
12900 bool IsListInit;
12901};
12902}
12903
12905 Sema &S, Expr *E, QualType T, SourceLocation CC,
12906 bool ExtraCheckForImplicitConversion,
12908 E = E->IgnoreParenImpCasts();
12909 WorkList.push_back({E, CC, false});
12910
12911 if (ExtraCheckForImplicitConversion && E->getType() != T)
12912 S.CheckImplicitConversion(E, T, CC);
12913}
12914
12915/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12916/// that should be visited are added to WorkList.
12918 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12920 Expr *OrigE = Item.E;
12921 SourceLocation CC = Item.CC;
12922
12923 QualType T = OrigE->getType();
12924 Expr *E = OrigE->IgnoreParenImpCasts();
12925
12926 // Propagate whether we are in a C++ list initialization expression.
12927 // If so, we do not issue warnings for implicit int-float conversion
12928 // precision loss, because C++11 narrowing already handles it.
12929 //
12930 // HLSL's initialization lists are special, so they shouldn't observe the C++
12931 // behavior here.
12932 bool IsListInit =
12933 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
12934 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
12935
12936 if (E->isTypeDependent() || E->isValueDependent())
12937 return;
12938
12939 Expr *SourceExpr = E;
12940 // Examine, but don't traverse into the source expression of an
12941 // OpaqueValueExpr, since it may have multiple parents and we don't want to
12942 // emit duplicate diagnostics. Its fine to examine the form or attempt to
12943 // evaluate it in the context of checking the specific conversion to T though.
12944 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12945 if (auto *Src = OVE->getSourceExpr())
12946 SourceExpr = Src;
12947
12948 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12949 if (UO->getOpcode() == UO_Not &&
12950 UO->getSubExpr()->isKnownToHaveBooleanValue())
12951 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12952 << OrigE->getSourceRange() << T->isBooleanType()
12953 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12954
12955 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
12956 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
12957 BO->getLHS()->isKnownToHaveBooleanValue() &&
12958 BO->getRHS()->isKnownToHaveBooleanValue() &&
12959 BO->getLHS()->HasSideEffects(S.Context) &&
12960 BO->getRHS()->HasSideEffects(S.Context)) {
12962 const LangOptions &LO = S.getLangOpts();
12963 SourceLocation BLoc = BO->getOperatorLoc();
12964 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
12965 StringRef SR = clang::Lexer::getSourceText(
12966 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
12967 // To reduce false positives, only issue the diagnostic if the operator
12968 // is explicitly spelled as a punctuator. This suppresses the diagnostic
12969 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
12970 // in C, along with other macro spellings the user might invent.
12971 if (SR.str() == "&" || SR.str() == "|") {
12972
12973 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
12974 << (BO->getOpcode() == BO_And ? "&" : "|")
12975 << OrigE->getSourceRange()
12977 BO->getOperatorLoc(),
12978 (BO->getOpcode() == BO_And ? "&&" : "||"));
12979 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
12980 }
12981 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
12982 /// Analyze the given comma operator. The basic idea behind the analysis
12983 /// is to analyze the left and right operands slightly differently. The
12984 /// left operand needs to check whether the operand itself has an implicit
12985 /// conversion, but not whether the left operand induces an implicit
12986 /// conversion for the entire comma expression itself. This is similar to
12987 /// how CheckConditionalOperand behaves; it's as-if the correct operand
12988 /// were directly used for the implicit conversion check.
12989 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
12990 /*ExtraCheckForImplicitConversion=*/false, WorkList);
12991 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
12992 /*ExtraCheckForImplicitConversion=*/true, WorkList);
12993 return;
12994 }
12995 }
12996
12997 // For conditional operators, we analyze the arguments as if they
12998 // were being fed directly into the output.
12999 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13000 CheckConditionalOperator(S, CO, CC, T);
13001 return;
13002 }
13003
13004 // Check implicit argument conversions for function calls.
13005 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
13007
13008 // Go ahead and check any implicit conversions we might have skipped.
13009 // The non-canonical typecheck is just an optimization;
13010 // CheckImplicitConversion will filter out dead implicit conversions.
13011 if (SourceExpr->getType() != T)
13012 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
13013
13014 // Now continue drilling into this expression.
13015
13016 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13017 // The bound subexpressions in a PseudoObjectExpr are not reachable
13018 // as transitive children.
13019 // FIXME: Use a more uniform representation for this.
13020 for (auto *SE : POE->semantics())
13021 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13022 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13023 }
13024
13025 // Skip past explicit casts.
13026 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13027 E = CE->getSubExpr();
13028 // In the special case of a C++ function-style cast with braces,
13029 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
13030 // initializer. This InitListExpr basically belongs to the cast itself, so
13031 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
13033 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
13034 if (InitListE->getNumInits() == 1) {
13035 E = InitListE->getInit(0);
13036 }
13037 }
13038 }
13039 E = E->IgnoreParenImpCasts();
13040 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13041 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13042 WorkList.push_back({E, CC, IsListInit});
13043 return;
13044 }
13045
13046 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
13047 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
13048 // The base expression is only used to initialize the parameter for
13049 // arguments to `inout` parameters, so we only traverse down the base
13050 // expression for `inout` cases.
13051 if (OutArgE->isInOut())
13052 WorkList.push_back(
13053 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
13054 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
13055 return;
13056 }
13057
13058 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13059 // Do a somewhat different check with comparison operators.
13060 if (BO->isComparisonOp())
13061 return AnalyzeComparison(S, BO);
13062
13063 // And with simple assignments.
13064 if (BO->getOpcode() == BO_Assign)
13065 return AnalyzeAssignment(S, BO);
13066 // And with compound assignments.
13067 if (BO->isAssignmentOp())
13068 return AnalyzeCompoundAssignment(S, BO);
13069 }
13070
13071 // These break the otherwise-useful invariant below. Fortunately,
13072 // we don't really need to recurse into them, because any internal
13073 // expressions should have been analyzed already when they were
13074 // built into statements.
13075 if (isa<StmtExpr>(E)) return;
13076
13077 // Don't descend into unevaluated contexts.
13078 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13079
13080 // Now just recurse over the expression's children.
13081 CC = E->getExprLoc();
13082 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13083 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13084 for (Stmt *SubStmt : E->children()) {
13085 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13086 if (!ChildExpr)
13087 continue;
13088
13089 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
13090 if (ChildExpr == CSE->getOperand())
13091 // Do not recurse over a CoroutineSuspendExpr's operand.
13092 // The operand is also a subexpression of getCommonExpr(), and
13093 // recursing into it directly would produce duplicate diagnostics.
13094 continue;
13095
13096 if (IsLogicalAndOperator &&
13098 // Ignore checking string literals that are in logical and operators.
13099 // This is a common pattern for asserts.
13100 continue;
13101 WorkList.push_back({ChildExpr, CC, IsListInit});
13102 }
13103
13104 if (BO && BO->isLogicalOp()) {
13105 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13106 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13107 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13108
13109 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13110 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13111 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13112 }
13113
13114 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13115 if (U->getOpcode() == UO_LNot) {
13116 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13117 } else if (U->getOpcode() != UO_AddrOf) {
13118 if (U->getSubExpr()->getType()->isAtomicType())
13119 S.Diag(U->getSubExpr()->getBeginLoc(),
13120 diag::warn_atomic_implicit_seq_cst);
13121 }
13122 }
13123}
13124
13125/// AnalyzeImplicitConversions - Find and report any interesting
13126/// implicit conversions in the given expression. There are a couple
13127/// of competing diagnostics here, -Wconversion and -Wsign-compare.
13129 bool IsListInit/*= false*/) {
13131 WorkList.push_back({OrigE, CC, IsListInit});
13132 while (!WorkList.empty())
13133 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13134}
13135
13136// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13137// Returns true when emitting a warning about taking the address of a reference.
13138static bool CheckForReference(Sema &SemaRef, const Expr *E,
13139 const PartialDiagnostic &PD) {
13140 E = E->IgnoreParenImpCasts();
13141
13142 const FunctionDecl *FD = nullptr;
13143
13144 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13145 if (!DRE->getDecl()->getType()->isReferenceType())
13146 return false;
13147 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13148 if (!M->getMemberDecl()->getType()->isReferenceType())
13149 return false;
13150 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13151 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13152 return false;
13153 FD = Call->getDirectCallee();
13154 } else {
13155 return false;
13156 }
13157
13158 SemaRef.Diag(E->getExprLoc(), PD);
13159
13160 // If possible, point to location of function.
13161 if (FD) {
13162 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13163 }
13164
13165 return true;
13166}
13167
13168// Returns true if the SourceLocation is expanded from any macro body.
13169// Returns false if the SourceLocation is invalid, is from not in a macro
13170// expansion, or is from expanded from a top-level macro argument.
13172 if (Loc.isInvalid())
13173 return false;
13174
13175 while (Loc.isMacroID()) {
13176 if (SM.isMacroBodyExpansion(Loc))
13177 return true;
13178 Loc = SM.getImmediateMacroCallerLoc(Loc);
13179 }
13180
13181 return false;
13182}
13183
13186 bool IsEqual, SourceRange Range) {
13187 if (!E)
13188 return;
13189
13190 // Don't warn inside macros.
13191 if (E->getExprLoc().isMacroID()) {
13193 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13194 IsInAnyMacroBody(SM, Range.getBegin()))
13195 return;
13196 }
13197 E = E->IgnoreImpCasts();
13198
13199 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13200
13201 if (isa<CXXThisExpr>(E)) {
13202 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13203 : diag::warn_this_bool_conversion;
13204 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13205 return;
13206 }
13207
13208 bool IsAddressOf = false;
13209
13210 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
13211 if (UO->getOpcode() != UO_AddrOf)
13212 return;
13213 IsAddressOf = true;
13214 E = UO->getSubExpr();
13215 }
13216
13217 if (IsAddressOf) {
13218 unsigned DiagID = IsCompare
13219 ? diag::warn_address_of_reference_null_compare
13220 : diag::warn_address_of_reference_bool_conversion;
13221 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13222 << IsEqual;
13223 if (CheckForReference(*this, E, PD)) {
13224 return;
13225 }
13226 }
13227
13228 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13229 bool IsParam = isa<NonNullAttr>(NonnullAttr);
13230 std::string Str;
13231 llvm::raw_string_ostream S(Str);
13232 E->printPretty(S, nullptr, getPrintingPolicy());
13233 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13234 : diag::warn_cast_nonnull_to_bool;
13235 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13236 << E->getSourceRange() << Range << IsEqual;
13237 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13238 };
13239
13240 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13241 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13242 if (auto *Callee = Call->getDirectCallee()) {
13243 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13244 ComplainAboutNonnullParamOrCall(A);
13245 return;
13246 }
13247 }
13248 }
13249
13250 // Complain if we are converting a lambda expression to a boolean value
13251 // outside of instantiation.
13252 if (!inTemplateInstantiation()) {
13253 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
13254 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
13255 MRecordDecl && MRecordDecl->isLambda()) {
13256 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
13257 << /*LambdaPointerConversionOperatorType=*/3
13258 << MRecordDecl->getSourceRange() << Range << IsEqual;
13259 return;
13260 }
13261 }
13262 }
13263
13264 // Expect to find a single Decl. Skip anything more complicated.
13265 ValueDecl *D = nullptr;
13266 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13267 D = R->getDecl();
13268 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13269 D = M->getMemberDecl();
13270 }
13271
13272 // Weak Decls can be null.
13273 if (!D || D->isWeak())
13274 return;
13275
13276 // Check for parameter decl with nonnull attribute
13277 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13278 if (getCurFunction() &&
13279 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13280 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13281 ComplainAboutNonnullParamOrCall(A);
13282 return;
13283 }
13284
13285 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13286 // Skip function template not specialized yet.
13288 return;
13289 auto ParamIter = llvm::find(FD->parameters(), PV);
13290 assert(ParamIter != FD->param_end());
13291 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13292
13293 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13294 if (!NonNull->args_size()) {
13295 ComplainAboutNonnullParamOrCall(NonNull);
13296 return;
13297 }
13298
13299 for (const ParamIdx &ArgNo : NonNull->args()) {
13300 if (ArgNo.getASTIndex() == ParamNo) {
13301 ComplainAboutNonnullParamOrCall(NonNull);
13302 return;
13303 }
13304 }
13305 }
13306 }
13307 }
13308 }
13309
13310 QualType T = D->getType();
13311 const bool IsArray = T->isArrayType();
13312 const bool IsFunction = T->isFunctionType();
13313
13314 // Address of function is used to silence the function warning.
13315 if (IsAddressOf && IsFunction) {
13316 return;
13317 }
13318
13319 // Found nothing.
13320 if (!IsAddressOf && !IsFunction && !IsArray)
13321 return;
13322
13323 // Pretty print the expression for the diagnostic.
13324 std::string Str;
13325 llvm::raw_string_ostream S(Str);
13326 E->printPretty(S, nullptr, getPrintingPolicy());
13327
13328 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13329 : diag::warn_impcast_pointer_to_bool;
13330 enum {
13331 AddressOf,
13332 FunctionPointer,
13333 ArrayPointer
13334 } DiagType;
13335 if (IsAddressOf)
13336 DiagType = AddressOf;
13337 else if (IsFunction)
13338 DiagType = FunctionPointer;
13339 else if (IsArray)
13340 DiagType = ArrayPointer;
13341 else
13342 llvm_unreachable("Could not determine diagnostic.");
13343 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13344 << Range << IsEqual;
13345
13346 if (!IsFunction)
13347 return;
13348
13349 // Suggest '&' to silence the function warning.
13350 Diag(E->getExprLoc(), diag::note_function_warning_silence)
13352
13353 // Check to see if '()' fixit should be emitted.
13354 QualType ReturnType;
13355 UnresolvedSet<4> NonTemplateOverloads;
13356 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13357 if (ReturnType.isNull())
13358 return;
13359
13360 if (IsCompare) {
13361 // There are two cases here. If there is null constant, the only suggest
13362 // for a pointer return type. If the null is 0, then suggest if the return
13363 // type is a pointer or an integer type.
13364 if (!ReturnType->isPointerType()) {
13365 if (NullKind == Expr::NPCK_ZeroExpression ||
13366 NullKind == Expr::NPCK_ZeroLiteral) {
13367 if (!ReturnType->isIntegerType())
13368 return;
13369 } else {
13370 return;
13371 }
13372 }
13373 } else { // !IsCompare
13374 // For function to bool, only suggest if the function pointer has bool
13375 // return type.
13376 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13377 return;
13378 }
13379 Diag(E->getExprLoc(), diag::note_function_to_function_call)
13381}
13382
13383void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13384 // Don't diagnose in unevaluated contexts.
13386 return;
13387
13388 // Don't diagnose for value- or type-dependent expressions.
13389 if (E->isTypeDependent() || E->isValueDependent())
13390 return;
13391
13392 // Check for array bounds violations in cases where the check isn't triggered
13393 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13394 // ArraySubscriptExpr is on the RHS of a variable initialization.
13395 CheckArrayAccess(E);
13396
13397 // This is not the right CC for (e.g.) a variable initialization.
13398 AnalyzeImplicitConversions(*this, E, CC);
13399}
13400
13401void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13402 ::CheckBoolLikeConversion(*this, E, CC);
13403}
13404
13405void Sema::CheckForIntOverflow (const Expr *E) {
13406 // Use a work list to deal with nested struct initializers.
13407 SmallVector<const Expr *, 2> Exprs(1, E);
13408
13409 do {
13410 const Expr *OriginalE = Exprs.pop_back_val();
13411 const Expr *E = OriginalE->IgnoreParenCasts();
13412
13415 continue;
13416 }
13417
13418 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
13419 Exprs.append(InitList->inits().begin(), InitList->inits().end());
13420 else if (isa<ObjCBoxedExpr>(OriginalE))
13422 else if (const auto *Call = dyn_cast<CallExpr>(E))
13423 Exprs.append(Call->arg_begin(), Call->arg_end());
13424 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
13425 Exprs.append(Message->arg_begin(), Message->arg_end());
13426 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
13427 Exprs.append(Construct->arg_begin(), Construct->arg_end());
13428 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
13429 Exprs.push_back(Temporary->getSubExpr());
13430 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
13431 Exprs.push_back(Array->getIdx());
13432 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
13433 Exprs.push_back(Compound->getInitializer());
13434 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
13435 New && New->isArray()) {
13436 if (auto ArraySize = New->getArraySize())
13437 Exprs.push_back(*ArraySize);
13438 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
13439 Exprs.push_back(MTE->getSubExpr());
13440 } while (!Exprs.empty());
13441}
13442
13443namespace {
13444
13445/// Visitor for expressions which looks for unsequenced operations on the
13446/// same object.
13447class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13448 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13449
13450 /// A tree of sequenced regions within an expression. Two regions are
13451 /// unsequenced if one is an ancestor or a descendent of the other. When we
13452 /// finish processing an expression with sequencing, such as a comma
13453 /// expression, we fold its tree nodes into its parent, since they are
13454 /// unsequenced with respect to nodes we will visit later.
13455 class SequenceTree {
13456 struct Value {
13457 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13458 unsigned Parent : 31;
13459 LLVM_PREFERRED_TYPE(bool)
13460 unsigned Merged : 1;
13461 };
13462 SmallVector<Value, 8> Values;
13463
13464 public:
13465 /// A region within an expression which may be sequenced with respect
13466 /// to some other region.
13467 class Seq {
13468 friend class SequenceTree;
13469
13470 unsigned Index;
13471
13472 explicit Seq(unsigned N) : Index(N) {}
13473
13474 public:
13475 Seq() : Index(0) {}
13476 };
13477
13478 SequenceTree() { Values.push_back(Value(0)); }
13479 Seq root() const { return Seq(0); }
13480
13481 /// Create a new sequence of operations, which is an unsequenced
13482 /// subset of \p Parent. This sequence of operations is sequenced with
13483 /// respect to other children of \p Parent.
13484 Seq allocate(Seq Parent) {
13485 Values.push_back(Value(Parent.Index));
13486 return Seq(Values.size() - 1);
13487 }
13488
13489 /// Merge a sequence of operations into its parent.
13490 void merge(Seq S) {
13491 Values[S.Index].Merged = true;
13492 }
13493
13494 /// Determine whether two operations are unsequenced. This operation
13495 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13496 /// should have been merged into its parent as appropriate.
13497 bool isUnsequenced(Seq Cur, Seq Old) {
13498 unsigned C = representative(Cur.Index);
13499 unsigned Target = representative(Old.Index);
13500 while (C >= Target) {
13501 if (C == Target)
13502 return true;
13503 C = Values[C].Parent;
13504 }
13505 return false;
13506 }
13507
13508 private:
13509 /// Pick a representative for a sequence.
13510 unsigned representative(unsigned K) {
13511 if (Values[K].Merged)
13512 // Perform path compression as we go.
13513 return Values[K].Parent = representative(Values[K].Parent);
13514 return K;
13515 }
13516 };
13517
13518 /// An object for which we can track unsequenced uses.
13519 using Object = const NamedDecl *;
13520
13521 /// Different flavors of object usage which we track. We only track the
13522 /// least-sequenced usage of each kind.
13523 enum UsageKind {
13524 /// A read of an object. Multiple unsequenced reads are OK.
13525 UK_Use,
13526
13527 /// A modification of an object which is sequenced before the value
13528 /// computation of the expression, such as ++n in C++.
13529 UK_ModAsValue,
13530
13531 /// A modification of an object which is not sequenced before the value
13532 /// computation of the expression, such as n++.
13533 UK_ModAsSideEffect,
13534
13535 UK_Count = UK_ModAsSideEffect + 1
13536 };
13537
13538 /// Bundle together a sequencing region and the expression corresponding
13539 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13540 struct Usage {
13541 const Expr *UsageExpr = nullptr;
13542 SequenceTree::Seq Seq;
13543
13544 Usage() = default;
13545 };
13546
13547 struct UsageInfo {
13548 Usage Uses[UK_Count];
13549
13550 /// Have we issued a diagnostic for this object already?
13551 bool Diagnosed = false;
13552
13553 UsageInfo();
13554 };
13555 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13556
13557 Sema &SemaRef;
13558
13559 /// Sequenced regions within the expression.
13560 SequenceTree Tree;
13561
13562 /// Declaration modifications and references which we have seen.
13563 UsageInfoMap UsageMap;
13564
13565 /// The region we are currently within.
13566 SequenceTree::Seq Region;
13567
13568 /// Filled in with declarations which were modified as a side-effect
13569 /// (that is, post-increment operations).
13570 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13571
13572 /// Expressions to check later. We defer checking these to reduce
13573 /// stack usage.
13574 SmallVectorImpl<const Expr *> &WorkList;
13575
13576 /// RAII object wrapping the visitation of a sequenced subexpression of an
13577 /// expression. At the end of this process, the side-effects of the evaluation
13578 /// become sequenced with respect to the value computation of the result, so
13579 /// we downgrade any UK_ModAsSideEffect within the evaluation to
13580 /// UK_ModAsValue.
13581 struct SequencedSubexpression {
13582 SequencedSubexpression(SequenceChecker &Self)
13583 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13584 Self.ModAsSideEffect = &ModAsSideEffect;
13585 }
13586
13587 ~SequencedSubexpression() {
13588 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13589 // Add a new usage with usage kind UK_ModAsValue, and then restore
13590 // the previous usage with UK_ModAsSideEffect (thus clearing it if
13591 // the previous one was empty).
13592 UsageInfo &UI = Self.UsageMap[M.first];
13593 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13594 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13595 SideEffectUsage = M.second;
13596 }
13597 Self.ModAsSideEffect = OldModAsSideEffect;
13598 }
13599
13600 SequenceChecker &Self;
13601 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13602 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13603 };
13604
13605 /// RAII object wrapping the visitation of a subexpression which we might
13606 /// choose to evaluate as a constant. If any subexpression is evaluated and
13607 /// found to be non-constant, this allows us to suppress the evaluation of
13608 /// the outer expression.
13609 class EvaluationTracker {
13610 public:
13611 EvaluationTracker(SequenceChecker &Self)
13612 : Self(Self), Prev(Self.EvalTracker) {
13613 Self.EvalTracker = this;
13614 }
13615
13616 ~EvaluationTracker() {
13617 Self.EvalTracker = Prev;
13618 if (Prev)
13619 Prev->EvalOK &= EvalOK;
13620 }
13621
13622 bool evaluate(const Expr *E, bool &Result) {
13623 if (!EvalOK || E->isValueDependent())
13624 return false;
13625 EvalOK = E->EvaluateAsBooleanCondition(
13626 Result, Self.SemaRef.Context,
13627 Self.SemaRef.isConstantEvaluatedContext());
13628 return EvalOK;
13629 }
13630
13631 private:
13632 SequenceChecker &Self;
13633 EvaluationTracker *Prev;
13634 bool EvalOK = true;
13635 } *EvalTracker = nullptr;
13636
13637 /// Find the object which is produced by the specified expression,
13638 /// if any.
13639 Object getObject(const Expr *E, bool Mod) const {
13640 E = E->IgnoreParenCasts();
13641 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13642 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13643 return getObject(UO->getSubExpr(), Mod);
13644 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13645 if (BO->getOpcode() == BO_Comma)
13646 return getObject(BO->getRHS(), Mod);
13647 if (Mod && BO->isAssignmentOp())
13648 return getObject(BO->getLHS(), Mod);
13649 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13650 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13651 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13652 return ME->getMemberDecl();
13653 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13654 // FIXME: If this is a reference, map through to its value.
13655 return DRE->getDecl();
13656 return nullptr;
13657 }
13658
13659 /// Note that an object \p O was modified or used by an expression
13660 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13661 /// the object \p O as obtained via the \p UsageMap.
13662 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13663 // Get the old usage for the given object and usage kind.
13664 Usage &U = UI.Uses[UK];
13665 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13666 // If we have a modification as side effect and are in a sequenced
13667 // subexpression, save the old Usage so that we can restore it later
13668 // in SequencedSubexpression::~SequencedSubexpression.
13669 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13670 ModAsSideEffect->push_back(std::make_pair(O, U));
13671 // Then record the new usage with the current sequencing region.
13672 U.UsageExpr = UsageExpr;
13673 U.Seq = Region;
13674 }
13675 }
13676
13677 /// Check whether a modification or use of an object \p O in an expression
13678 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13679 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13680 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13681 /// usage and false we are checking for a mod-use unsequenced usage.
13682 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13683 UsageKind OtherKind, bool IsModMod) {
13684 if (UI.Diagnosed)
13685 return;
13686
13687 const Usage &U = UI.Uses[OtherKind];
13688 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13689 return;
13690
13691 const Expr *Mod = U.UsageExpr;
13692 const Expr *ModOrUse = UsageExpr;
13693 if (OtherKind == UK_Use)
13694 std::swap(Mod, ModOrUse);
13695
13696 SemaRef.DiagRuntimeBehavior(
13697 Mod->getExprLoc(), {Mod, ModOrUse},
13698 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13699 : diag::warn_unsequenced_mod_use)
13700 << O << SourceRange(ModOrUse->getExprLoc()));
13701 UI.Diagnosed = true;
13702 }
13703
13704 // A note on note{Pre, Post}{Use, Mod}:
13705 //
13706 // (It helps to follow the algorithm with an expression such as
13707 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13708 // operations before C++17 and both are well-defined in C++17).
13709 //
13710 // When visiting a node which uses/modify an object we first call notePreUse
13711 // or notePreMod before visiting its sub-expression(s). At this point the
13712 // children of the current node have not yet been visited and so the eventual
13713 // uses/modifications resulting from the children of the current node have not
13714 // been recorded yet.
13715 //
13716 // We then visit the children of the current node. After that notePostUse or
13717 // notePostMod is called. These will 1) detect an unsequenced modification
13718 // as side effect (as in "k++ + k") and 2) add a new usage with the
13719 // appropriate usage kind.
13720 //
13721 // We also have to be careful that some operation sequences modification as
13722 // side effect as well (for example: || or ,). To account for this we wrap
13723 // the visitation of such a sub-expression (for example: the LHS of || or ,)
13724 // with SequencedSubexpression. SequencedSubexpression is an RAII object
13725 // which record usages which are modifications as side effect, and then
13726 // downgrade them (or more accurately restore the previous usage which was a
13727 // modification as side effect) when exiting the scope of the sequenced
13728 // subexpression.
13729
13730 void notePreUse(Object O, const Expr *UseExpr) {
13731 UsageInfo &UI = UsageMap[O];
13732 // Uses conflict with other modifications.
13733 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13734 }
13735
13736 void notePostUse(Object O, const Expr *UseExpr) {
13737 UsageInfo &UI = UsageMap[O];
13738 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13739 /*IsModMod=*/false);
13740 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13741 }
13742
13743 void notePreMod(Object O, const Expr *ModExpr) {
13744 UsageInfo &UI = UsageMap[O];
13745 // Modifications conflict with other modifications and with uses.
13746 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13747 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13748 }
13749
13750 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13751 UsageInfo &UI = UsageMap[O];
13752 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13753 /*IsModMod=*/true);
13754 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13755 }
13756
13757public:
13758 SequenceChecker(Sema &S, const Expr *E,
13759 SmallVectorImpl<const Expr *> &WorkList)
13760 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13761 Visit(E);
13762 // Silence a -Wunused-private-field since WorkList is now unused.
13763 // TODO: Evaluate if it can be used, and if not remove it.
13764 (void)this->WorkList;
13765 }
13766
13767 void VisitStmt(const Stmt *S) {
13768 // Skip all statements which aren't expressions for now.
13769 }
13770
13771 void VisitExpr(const Expr *E) {
13772 // By default, just recurse to evaluated subexpressions.
13773 Base::VisitStmt(E);
13774 }
13775
13776 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
13777 for (auto *Sub : CSE->children()) {
13778 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
13779 if (!ChildExpr)
13780 continue;
13781
13782 if (ChildExpr == CSE->getOperand())
13783 // Do not recurse over a CoroutineSuspendExpr's operand.
13784 // The operand is also a subexpression of getCommonExpr(), and
13785 // recursing into it directly could confuse object management
13786 // for the sake of sequence tracking.
13787 continue;
13788
13789 Visit(Sub);
13790 }
13791 }
13792
13793 void VisitCastExpr(const CastExpr *E) {
13794 Object O = Object();
13795 if (E->getCastKind() == CK_LValueToRValue)
13796 O = getObject(E->getSubExpr(), false);
13797
13798 if (O)
13799 notePreUse(O, E);
13800 VisitExpr(E);
13801 if (O)
13802 notePostUse(O, E);
13803 }
13804
13805 void VisitSequencedExpressions(const Expr *SequencedBefore,
13806 const Expr *SequencedAfter) {
13807 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13808 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13809 SequenceTree::Seq OldRegion = Region;
13810
13811 {
13812 SequencedSubexpression SeqBefore(*this);
13813 Region = BeforeRegion;
13814 Visit(SequencedBefore);
13815 }
13816
13817 Region = AfterRegion;
13818 Visit(SequencedAfter);
13819
13820 Region = OldRegion;
13821
13822 Tree.merge(BeforeRegion);
13823 Tree.merge(AfterRegion);
13824 }
13825
13826 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13827 // C++17 [expr.sub]p1:
13828 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13829 // expression E1 is sequenced before the expression E2.
13830 if (SemaRef.getLangOpts().CPlusPlus17)
13831 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13832 else {
13833 Visit(ASE->getLHS());
13834 Visit(ASE->getRHS());
13835 }
13836 }
13837
13838 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13839 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13840 void VisitBinPtrMem(const BinaryOperator *BO) {
13841 // C++17 [expr.mptr.oper]p4:
13842 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13843 // the expression E1 is sequenced before the expression E2.
13844 if (SemaRef.getLangOpts().CPlusPlus17)
13845 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13846 else {
13847 Visit(BO->getLHS());
13848 Visit(BO->getRHS());
13849 }
13850 }
13851
13852 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13853 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13854 void VisitBinShlShr(const BinaryOperator *BO) {
13855 // C++17 [expr.shift]p4:
13856 // The expression E1 is sequenced before the expression E2.
13857 if (SemaRef.getLangOpts().CPlusPlus17)
13858 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13859 else {
13860 Visit(BO->getLHS());
13861 Visit(BO->getRHS());
13862 }
13863 }
13864
13865 void VisitBinComma(const BinaryOperator *BO) {
13866 // C++11 [expr.comma]p1:
13867 // Every value computation and side effect associated with the left
13868 // expression is sequenced before every value computation and side
13869 // effect associated with the right expression.
13870 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13871 }
13872
13873 void VisitBinAssign(const BinaryOperator *BO) {
13874 SequenceTree::Seq RHSRegion;
13875 SequenceTree::Seq LHSRegion;
13876 if (SemaRef.getLangOpts().CPlusPlus17) {
13877 RHSRegion = Tree.allocate(Region);
13878 LHSRegion = Tree.allocate(Region);
13879 } else {
13880 RHSRegion = Region;
13881 LHSRegion = Region;
13882 }
13883 SequenceTree::Seq OldRegion = Region;
13884
13885 // C++11 [expr.ass]p1:
13886 // [...] the assignment is sequenced after the value computation
13887 // of the right and left operands, [...]
13888 //
13889 // so check it before inspecting the operands and update the
13890 // map afterwards.
13891 Object O = getObject(BO->getLHS(), /*Mod=*/true);
13892 if (O)
13893 notePreMod(O, BO);
13894
13895 if (SemaRef.getLangOpts().CPlusPlus17) {
13896 // C++17 [expr.ass]p1:
13897 // [...] The right operand is sequenced before the left operand. [...]
13898 {
13899 SequencedSubexpression SeqBefore(*this);
13900 Region = RHSRegion;
13901 Visit(BO->getRHS());
13902 }
13903
13904 Region = LHSRegion;
13905 Visit(BO->getLHS());
13906
13907 if (O && isa<CompoundAssignOperator>(BO))
13908 notePostUse(O, BO);
13909
13910 } else {
13911 // C++11 does not specify any sequencing between the LHS and RHS.
13912 Region = LHSRegion;
13913 Visit(BO->getLHS());
13914
13915 if (O && isa<CompoundAssignOperator>(BO))
13916 notePostUse(O, BO);
13917
13918 Region = RHSRegion;
13919 Visit(BO->getRHS());
13920 }
13921
13922 // C++11 [expr.ass]p1:
13923 // the assignment is sequenced [...] before the value computation of the
13924 // assignment expression.
13925 // C11 6.5.16/3 has no such rule.
13926 Region = OldRegion;
13927 if (O)
13928 notePostMod(O, BO,
13929 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13930 : UK_ModAsSideEffect);
13931 if (SemaRef.getLangOpts().CPlusPlus17) {
13932 Tree.merge(RHSRegion);
13933 Tree.merge(LHSRegion);
13934 }
13935 }
13936
13937 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13938 VisitBinAssign(CAO);
13939 }
13940
13941 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13942 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13943 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13944 Object O = getObject(UO->getSubExpr(), true);
13945 if (!O)
13946 return VisitExpr(UO);
13947
13948 notePreMod(O, UO);
13949 Visit(UO->getSubExpr());
13950 // C++11 [expr.pre.incr]p1:
13951 // the expression ++x is equivalent to x+=1
13952 notePostMod(O, UO,
13953 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13954 : UK_ModAsSideEffect);
13955 }
13956
13957 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13958 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13959 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13960 Object O = getObject(UO->getSubExpr(), true);
13961 if (!O)
13962 return VisitExpr(UO);
13963
13964 notePreMod(O, UO);
13965 Visit(UO->getSubExpr());
13966 notePostMod(O, UO, UK_ModAsSideEffect);
13967 }
13968
13969 void VisitBinLOr(const BinaryOperator *BO) {
13970 // C++11 [expr.log.or]p2:
13971 // If the second expression is evaluated, every value computation and
13972 // side effect associated with the first expression is sequenced before
13973 // every value computation and side effect associated with the
13974 // second expression.
13975 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13976 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13977 SequenceTree::Seq OldRegion = Region;
13978
13979 EvaluationTracker Eval(*this);
13980 {
13981 SequencedSubexpression Sequenced(*this);
13982 Region = LHSRegion;
13983 Visit(BO->getLHS());
13984 }
13985
13986 // C++11 [expr.log.or]p1:
13987 // [...] the second operand is not evaluated if the first operand
13988 // evaluates to true.
13989 bool EvalResult = false;
13990 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13991 bool ShouldVisitRHS = !EvalOK || !EvalResult;
13992 if (ShouldVisitRHS) {
13993 Region = RHSRegion;
13994 Visit(BO->getRHS());
13995 }
13996
13997 Region = OldRegion;
13998 Tree.merge(LHSRegion);
13999 Tree.merge(RHSRegion);
14000 }
14001
14002 void VisitBinLAnd(const BinaryOperator *BO) {
14003 // C++11 [expr.log.and]p2:
14004 // If the second expression is evaluated, every value computation and
14005 // side effect associated with the first expression is sequenced before
14006 // every value computation and side effect associated with the
14007 // second expression.
14008 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14009 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14010 SequenceTree::Seq OldRegion = Region;
14011
14012 EvaluationTracker Eval(*this);
14013 {
14014 SequencedSubexpression Sequenced(*this);
14015 Region = LHSRegion;
14016 Visit(BO->getLHS());
14017 }
14018
14019 // C++11 [expr.log.and]p1:
14020 // [...] the second operand is not evaluated if the first operand is false.
14021 bool EvalResult = false;
14022 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14023 bool ShouldVisitRHS = !EvalOK || EvalResult;
14024 if (ShouldVisitRHS) {
14025 Region = RHSRegion;
14026 Visit(BO->getRHS());
14027 }
14028
14029 Region = OldRegion;
14030 Tree.merge(LHSRegion);
14031 Tree.merge(RHSRegion);
14032 }
14033
14034 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14035 // C++11 [expr.cond]p1:
14036 // [...] Every value computation and side effect associated with the first
14037 // expression is sequenced before every value computation and side effect
14038 // associated with the second or third expression.
14039 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14040
14041 // No sequencing is specified between the true and false expression.
14042 // However since exactly one of both is going to be evaluated we can
14043 // consider them to be sequenced. This is needed to avoid warning on
14044 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14045 // both the true and false expressions because we can't evaluate x.
14046 // This will still allow us to detect an expression like (pre C++17)
14047 // "(x ? y += 1 : y += 2) = y".
14048 //
14049 // We don't wrap the visitation of the true and false expression with
14050 // SequencedSubexpression because we don't want to downgrade modifications
14051 // as side effect in the true and false expressions after the visition
14052 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14053 // not warn between the two "y++", but we should warn between the "y++"
14054 // and the "y".
14055 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14056 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14057 SequenceTree::Seq OldRegion = Region;
14058
14059 EvaluationTracker Eval(*this);
14060 {
14061 SequencedSubexpression Sequenced(*this);
14062 Region = ConditionRegion;
14063 Visit(CO->getCond());
14064 }
14065
14066 // C++11 [expr.cond]p1:
14067 // [...] The first expression is contextually converted to bool (Clause 4).
14068 // It is evaluated and if it is true, the result of the conditional
14069 // expression is the value of the second expression, otherwise that of the
14070 // third expression. Only one of the second and third expressions is
14071 // evaluated. [...]
14072 bool EvalResult = false;
14073 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14074 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
14075 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
14076 if (ShouldVisitTrueExpr) {
14077 Region = TrueRegion;
14078 Visit(CO->getTrueExpr());
14079 }
14080 if (ShouldVisitFalseExpr) {
14081 Region = FalseRegion;
14082 Visit(CO->getFalseExpr());
14083 }
14084
14085 Region = OldRegion;
14086 Tree.merge(ConditionRegion);
14087 Tree.merge(TrueRegion);
14088 Tree.merge(FalseRegion);
14089 }
14090
14091 void VisitCallExpr(const CallExpr *CE) {
14092 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14093
14094 if (CE->isUnevaluatedBuiltinCall(Context))
14095 return;
14096
14097 // C++11 [intro.execution]p15:
14098 // When calling a function [...], every value computation and side effect
14099 // associated with any argument expression, or with the postfix expression
14100 // designating the called function, is sequenced before execution of every
14101 // expression or statement in the body of the function [and thus before
14102 // the value computation of its result].
14103 SequencedSubexpression Sequenced(*this);
14104 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14105 // C++17 [expr.call]p5
14106 // The postfix-expression is sequenced before each expression in the
14107 // expression-list and any default argument. [...]
14108 SequenceTree::Seq CalleeRegion;
14109 SequenceTree::Seq OtherRegion;
14110 if (SemaRef.getLangOpts().CPlusPlus17) {
14111 CalleeRegion = Tree.allocate(Region);
14112 OtherRegion = Tree.allocate(Region);
14113 } else {
14114 CalleeRegion = Region;
14115 OtherRegion = Region;
14116 }
14117 SequenceTree::Seq OldRegion = Region;
14118
14119 // Visit the callee expression first.
14120 Region = CalleeRegion;
14121 if (SemaRef.getLangOpts().CPlusPlus17) {
14122 SequencedSubexpression Sequenced(*this);
14123 Visit(CE->getCallee());
14124 } else {
14125 Visit(CE->getCallee());
14126 }
14127
14128 // Then visit the argument expressions.
14129 Region = OtherRegion;
14130 for (const Expr *Argument : CE->arguments())
14131 Visit(Argument);
14132
14133 Region = OldRegion;
14134 if (SemaRef.getLangOpts().CPlusPlus17) {
14135 Tree.merge(CalleeRegion);
14136 Tree.merge(OtherRegion);
14137 }
14138 });
14139 }
14140
14141 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14142 // C++17 [over.match.oper]p2:
14143 // [...] the operator notation is first transformed to the equivalent
14144 // function-call notation as summarized in Table 12 (where @ denotes one
14145 // of the operators covered in the specified subclause). However, the
14146 // operands are sequenced in the order prescribed for the built-in
14147 // operator (Clause 8).
14148 //
14149 // From the above only overloaded binary operators and overloaded call
14150 // operators have sequencing rules in C++17 that we need to handle
14151 // separately.
14152 if (!SemaRef.getLangOpts().CPlusPlus17 ||
14153 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14154 return VisitCallExpr(CXXOCE);
14155
14156 enum {
14157 NoSequencing,
14158 LHSBeforeRHS,
14159 RHSBeforeLHS,
14160 LHSBeforeRest
14161 } SequencingKind;
14162 switch (CXXOCE->getOperator()) {
14163 case OO_Equal:
14164 case OO_PlusEqual:
14165 case OO_MinusEqual:
14166 case OO_StarEqual:
14167 case OO_SlashEqual:
14168 case OO_PercentEqual:
14169 case OO_CaretEqual:
14170 case OO_AmpEqual:
14171 case OO_PipeEqual:
14172 case OO_LessLessEqual:
14173 case OO_GreaterGreaterEqual:
14174 SequencingKind = RHSBeforeLHS;
14175 break;
14176
14177 case OO_LessLess:
14178 case OO_GreaterGreater:
14179 case OO_AmpAmp:
14180 case OO_PipePipe:
14181 case OO_Comma:
14182 case OO_ArrowStar:
14183 case OO_Subscript:
14184 SequencingKind = LHSBeforeRHS;
14185 break;
14186
14187 case OO_Call:
14188 SequencingKind = LHSBeforeRest;
14189 break;
14190
14191 default:
14192 SequencingKind = NoSequencing;
14193 break;
14194 }
14195
14196 if (SequencingKind == NoSequencing)
14197 return VisitCallExpr(CXXOCE);
14198
14199 // This is a call, so all subexpressions are sequenced before the result.
14200 SequencedSubexpression Sequenced(*this);
14201
14202 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14203 assert(SemaRef.getLangOpts().CPlusPlus17 &&
14204 "Should only get there with C++17 and above!");
14205 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14206 "Should only get there with an overloaded binary operator"
14207 " or an overloaded call operator!");
14208
14209 if (SequencingKind == LHSBeforeRest) {
14210 assert(CXXOCE->getOperator() == OO_Call &&
14211 "We should only have an overloaded call operator here!");
14212
14213 // This is very similar to VisitCallExpr, except that we only have the
14214 // C++17 case. The postfix-expression is the first argument of the
14215 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14216 // are in the following arguments.
14217 //
14218 // Note that we intentionally do not visit the callee expression since
14219 // it is just a decayed reference to a function.
14220 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14221 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14222 SequenceTree::Seq OldRegion = Region;
14223
14224 assert(CXXOCE->getNumArgs() >= 1 &&
14225 "An overloaded call operator must have at least one argument"
14226 " for the postfix-expression!");
14227 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14228 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14229 CXXOCE->getNumArgs() - 1);
14230
14231 // Visit the postfix-expression first.
14232 {
14233 Region = PostfixExprRegion;
14234 SequencedSubexpression Sequenced(*this);
14235 Visit(PostfixExpr);
14236 }
14237
14238 // Then visit the argument expressions.
14239 Region = ArgsRegion;
14240 for (const Expr *Arg : Args)
14241 Visit(Arg);
14242
14243 Region = OldRegion;
14244 Tree.merge(PostfixExprRegion);
14245 Tree.merge(ArgsRegion);
14246 } else {
14247 assert(CXXOCE->getNumArgs() == 2 &&
14248 "Should only have two arguments here!");
14249 assert((SequencingKind == LHSBeforeRHS ||
14250 SequencingKind == RHSBeforeLHS) &&
14251 "Unexpected sequencing kind!");
14252
14253 // We do not visit the callee expression since it is just a decayed
14254 // reference to a function.
14255 const Expr *E1 = CXXOCE->getArg(0);
14256 const Expr *E2 = CXXOCE->getArg(1);
14257 if (SequencingKind == RHSBeforeLHS)
14258 std::swap(E1, E2);
14259
14260 return VisitSequencedExpressions(E1, E2);
14261 }
14262 });
14263 }
14264
14265 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14266 // This is a call, so all subexpressions are sequenced before the result.
14267 SequencedSubexpression Sequenced(*this);
14268
14269 if (!CCE->isListInitialization())
14270 return VisitExpr(CCE);
14271
14272 // In C++11, list initializations are sequenced.
14273 SequenceExpressionsInOrder(
14274 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
14275 }
14276
14277 void VisitInitListExpr(const InitListExpr *ILE) {
14278 if (!SemaRef.getLangOpts().CPlusPlus11)
14279 return VisitExpr(ILE);
14280
14281 // In C++11, list initializations are sequenced.
14282 SequenceExpressionsInOrder(ILE->inits());
14283 }
14284
14285 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
14286 // C++20 parenthesized list initializations are sequenced. See C++20
14287 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
14288 SequenceExpressionsInOrder(PLIE->getInitExprs());
14289 }
14290
14291private:
14292 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
14294 SequenceTree::Seq Parent = Region;
14295 for (const Expr *E : ExpressionList) {
14296 if (!E)
14297 continue;
14298 Region = Tree.allocate(Parent);
14299 Elts.push_back(Region);
14300 Visit(E);
14301 }
14302
14303 // Forget that the initializers are sequenced.
14304 Region = Parent;
14305 for (unsigned I = 0; I < Elts.size(); ++I)
14306 Tree.merge(Elts[I]);
14307 }
14308};
14309
14310SequenceChecker::UsageInfo::UsageInfo() = default;
14311
14312} // namespace
14313
14314void Sema::CheckUnsequencedOperations(const Expr *E) {
14315 SmallVector<const Expr *, 8> WorkList;
14316 WorkList.push_back(E);
14317 while (!WorkList.empty()) {
14318 const Expr *Item = WorkList.pop_back_val();
14319 SequenceChecker(*this, Item, WorkList);
14320 }
14321}
14322
14323void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14324 bool IsConstexpr) {
14325 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
14326 IsConstexpr || isa<ConstantExpr>(E));
14327 CheckImplicitConversions(E, CheckLoc);
14328 if (!E->isInstantiationDependent())
14329 CheckUnsequencedOperations(E);
14330 if (!IsConstexpr && !E->isValueDependent())
14331 CheckForIntOverflow(E);
14332}
14333
14334void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14335 FieldDecl *BitField,
14336 Expr *Init) {
14337 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14338}
14339
14341 SourceLocation Loc) {
14342 if (!PType->isVariablyModifiedType())
14343 return;
14344 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14345 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14346 return;
14347 }
14348 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14349 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14350 return;
14351 }
14352 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14353 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14354 return;
14355 }
14356
14357 const ArrayType *AT = S.Context.getAsArrayType(PType);
14358 if (!AT)
14359 return;
14360
14363 return;
14364 }
14365
14366 S.Diag(Loc, diag::err_array_star_in_function_definition);
14367}
14368
14370 bool CheckParameterNames) {
14371 bool HasInvalidParm = false;
14372 for (ParmVarDecl *Param : Parameters) {
14373 assert(Param && "null in a parameter list");
14374 // C99 6.7.5.3p4: the parameters in a parameter type list in a
14375 // function declarator that is part of a function definition of
14376 // that function shall not have incomplete type.
14377 //
14378 // C++23 [dcl.fct.def.general]/p2
14379 // The type of a parameter [...] for a function definition
14380 // shall not be a (possibly cv-qualified) class type that is incomplete
14381 // or abstract within the function body unless the function is deleted.
14382 if (!Param->isInvalidDecl() &&
14383 (RequireCompleteType(Param->getLocation(), Param->getType(),
14384 diag::err_typecheck_decl_incomplete_type) ||
14385 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
14386 diag::err_abstract_type_in_decl,
14388 Param->setInvalidDecl();
14389 HasInvalidParm = true;
14390 }
14391
14392 // C99 6.9.1p5: If the declarator includes a parameter type list, the
14393 // declaration of each parameter shall include an identifier.
14394 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14395 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14396 // Diagnose this as an extension in C17 and earlier.
14397 if (!getLangOpts().C23)
14398 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
14399 }
14400
14401 // C99 6.7.5.3p12:
14402 // If the function declarator is not part of a definition of that
14403 // function, parameters may have incomplete type and may use the [*]
14404 // notation in their sequences of declarator specifiers to specify
14405 // variable length array types.
14406 QualType PType = Param->getOriginalType();
14407 // FIXME: This diagnostic should point the '[*]' if source-location
14408 // information is added for it.
14409 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14410
14411 // If the parameter is a c++ class type and it has to be destructed in the
14412 // callee function, declare the destructor so that it can be called by the
14413 // callee function. Do not perform any direct access check on the dtor here.
14414 if (!Param->isInvalidDecl()) {
14415 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14416 if (!ClassDecl->isInvalidDecl() &&
14417 !ClassDecl->hasIrrelevantDestructor() &&
14418 !ClassDecl->isDependentContext() &&
14419 ClassDecl->isParamDestroyedInCallee()) {
14421 MarkFunctionReferenced(Param->getLocation(), Destructor);
14422 DiagnoseUseOfDecl(Destructor, Param->getLocation());
14423 }
14424 }
14425 }
14426
14427 // Parameters with the pass_object_size attribute only need to be marked
14428 // constant at function definitions. Because we lack information about
14429 // whether we're on a declaration or definition when we're instantiating the
14430 // attribute, we need to check for constness here.
14431 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14432 if (!Param->getType().isConstQualified())
14433 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14434 << Attr->getSpelling() << 1;
14435
14436 // Check for parameter names shadowing fields from the class.
14437 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14438 // The owning context for the parameter should be the function, but we
14439 // want to see if this function's declaration context is a record.
14440 DeclContext *DC = Param->getDeclContext();
14441 if (DC && DC->isFunctionOrMethod()) {
14442 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14443 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14444 RD, /*DeclIsField*/ false);
14445 }
14446 }
14447
14448 if (!Param->isInvalidDecl() &&
14449 Param->getOriginalType()->isWebAssemblyTableType()) {
14450 Param->setInvalidDecl();
14451 HasInvalidParm = true;
14452 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
14453 }
14454 }
14455
14456 return HasInvalidParm;
14457}
14458
14459std::optional<std::pair<
14461 *E,
14463 &Ctx);
14464
14465/// Compute the alignment and offset of the base class object given the
14466/// derived-to-base cast expression and the alignment and offset of the derived
14467/// class object.
14468static std::pair<CharUnits, CharUnits>
14470 CharUnits BaseAlignment, CharUnits Offset,
14471 ASTContext &Ctx) {
14472 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14473 ++PathI) {
14474 const CXXBaseSpecifier *Base = *PathI;
14475 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14476 if (Base->isVirtual()) {
14477 // The complete object may have a lower alignment than the non-virtual
14478 // alignment of the base, in which case the base may be misaligned. Choose
14479 // the smaller of the non-virtual alignment and BaseAlignment, which is a
14480 // conservative lower bound of the complete object alignment.
14481 CharUnits NonVirtualAlignment =
14483 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14484 Offset = CharUnits::Zero();
14485 } else {
14486 const ASTRecordLayout &RL =
14487 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14488 Offset += RL.getBaseClassOffset(BaseDecl);
14489 }
14490 DerivedType = Base->getType();
14491 }
14492
14493 return std::make_pair(BaseAlignment, Offset);
14494}
14495
14496/// Compute the alignment and offset of a binary additive operator.
14497static std::optional<std::pair<CharUnits, CharUnits>>
14499 bool IsSub, ASTContext &Ctx) {
14500 QualType PointeeType = PtrE->getType()->getPointeeType();
14501
14502 if (!PointeeType->isConstantSizeType())
14503 return std::nullopt;
14504
14505 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14506
14507 if (!P)
14508 return std::nullopt;
14509
14510 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14511 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14512 CharUnits Offset = EltSize * IdxRes->getExtValue();
14513 if (IsSub)
14514 Offset = -Offset;
14515 return std::make_pair(P->first, P->second + Offset);
14516 }
14517
14518 // If the integer expression isn't a constant expression, compute the lower
14519 // bound of the alignment using the alignment and offset of the pointer
14520 // expression and the element size.
14521 return std::make_pair(
14522 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14523 CharUnits::Zero());
14524}
14525
14526/// This helper function takes an lvalue expression and returns the alignment of
14527/// a VarDecl and a constant offset from the VarDecl.
14528std::optional<std::pair<
14529 CharUnits,
14531 ASTContext &Ctx) {
14532 E = E->IgnoreParens();
14533 switch (E->getStmtClass()) {
14534 default:
14535 break;
14536 case Stmt::CStyleCastExprClass:
14537 case Stmt::CXXStaticCastExprClass:
14538 case Stmt::ImplicitCastExprClass: {
14539 auto *CE = cast<CastExpr>(E);
14540 const Expr *From = CE->getSubExpr();
14541 switch (CE->getCastKind()) {
14542 default:
14543 break;
14544 case CK_NoOp:
14545 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14546 case CK_UncheckedDerivedToBase:
14547 case CK_DerivedToBase: {
14548 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14549 if (!P)
14550 break;
14551 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14552 P->second, Ctx);
14553 }
14554 }
14555 break;
14556 }
14557 case Stmt::ArraySubscriptExprClass: {
14558 auto *ASE = cast<ArraySubscriptExpr>(E);
14560 false, Ctx);
14561 }
14562 case Stmt::DeclRefExprClass: {
14563 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14564 // FIXME: If VD is captured by copy or is an escaping __block variable,
14565 // use the alignment of VD's type.
14566 if (!VD->getType()->isReferenceType()) {
14567 // Dependent alignment cannot be resolved -> bail out.
14568 if (VD->hasDependentAlignment())
14569 break;
14570 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14571 }
14572 if (VD->hasInit())
14573 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14574 }
14575 break;
14576 }
14577 case Stmt::MemberExprClass: {
14578 auto *ME = cast<MemberExpr>(E);
14579 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14580 if (!FD || FD->getType()->isReferenceType() ||
14581 FD->getParent()->isInvalidDecl())
14582 break;
14583 std::optional<std::pair<CharUnits, CharUnits>> P;
14584 if (ME->isArrow())
14585 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14586 else
14587 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14588 if (!P)
14589 break;
14590 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14591 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14592 return std::make_pair(P->first,
14593 P->second + CharUnits::fromQuantity(Offset));
14594 }
14595 case Stmt::UnaryOperatorClass: {
14596 auto *UO = cast<UnaryOperator>(E);
14597 switch (UO->getOpcode()) {
14598 default:
14599 break;
14600 case UO_Deref:
14602 }
14603 break;
14604 }
14605 case Stmt::BinaryOperatorClass: {
14606 auto *BO = cast<BinaryOperator>(E);
14607 auto Opcode = BO->getOpcode();
14608 switch (Opcode) {
14609 default:
14610 break;
14611 case BO_Comma:
14613 }
14614 break;
14615 }
14616 }
14617 return std::nullopt;
14618}
14619
14620/// This helper function takes a pointer expression and returns the alignment of
14621/// a VarDecl and a constant offset from the VarDecl.
14622std::optional<std::pair<
14624 *E,
14626 &Ctx) {
14627 E = E->IgnoreParens();
14628 switch (E->getStmtClass()) {
14629 default:
14630 break;
14631 case Stmt::CStyleCastExprClass:
14632 case Stmt::CXXStaticCastExprClass:
14633 case Stmt::ImplicitCastExprClass: {
14634 auto *CE = cast<CastExpr>(E);
14635 const Expr *From = CE->getSubExpr();
14636 switch (CE->getCastKind()) {
14637 default:
14638 break;
14639 case CK_NoOp:
14640 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14641 case CK_ArrayToPointerDecay:
14642 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14643 case CK_UncheckedDerivedToBase:
14644 case CK_DerivedToBase: {
14645 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14646 if (!P)
14647 break;
14649 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14650 }
14651 }
14652 break;
14653 }
14654 case Stmt::CXXThisExprClass: {
14655 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14657 return std::make_pair(Alignment, CharUnits::Zero());
14658 }
14659 case Stmt::UnaryOperatorClass: {
14660 auto *UO = cast<UnaryOperator>(E);
14661 if (UO->getOpcode() == UO_AddrOf)
14663 break;
14664 }
14665 case Stmt::BinaryOperatorClass: {
14666 auto *BO = cast<BinaryOperator>(E);
14667 auto Opcode = BO->getOpcode();
14668 switch (Opcode) {
14669 default:
14670 break;
14671 case BO_Add:
14672 case BO_Sub: {
14673 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14674 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14675 std::swap(LHS, RHS);
14676 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14677 Ctx);
14678 }
14679 case BO_Comma:
14680 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14681 }
14682 break;
14683 }
14684 }
14685 return std::nullopt;
14686}
14687
14689 // See if we can compute the alignment of a VarDecl and an offset from it.
14690 std::optional<std::pair<CharUnits, CharUnits>> P =
14692
14693 if (P)
14694 return P->first.alignmentAtOffset(P->second);
14695
14696 // If that failed, return the type's alignment.
14698}
14699
14701 // This is actually a lot of work to potentially be doing on every
14702 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14703 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14704 return;
14705
14706 // Ignore dependent types.
14707 if (T->isDependentType() || Op->getType()->isDependentType())
14708 return;
14709
14710 // Require that the destination be a pointer type.
14711 const PointerType *DestPtr = T->getAs<PointerType>();
14712 if (!DestPtr) return;
14713
14714 // If the destination has alignment 1, we're done.
14715 QualType DestPointee = DestPtr->getPointeeType();
14716 if (DestPointee->isIncompleteType()) return;
14717 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14718 if (DestAlign.isOne()) return;
14719
14720 // Require that the source be a pointer type.
14721 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14722 if (!SrcPtr) return;
14723 QualType SrcPointee = SrcPtr->getPointeeType();
14724
14725 // Explicitly allow casts from cv void*. We already implicitly
14726 // allowed casts to cv void*, since they have alignment 1.
14727 // Also allow casts involving incomplete types, which implicitly
14728 // includes 'void'.
14729 if (SrcPointee->isIncompleteType()) return;
14730
14731 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14732
14733 if (SrcAlign >= DestAlign) return;
14734
14735 Diag(TRange.getBegin(), diag::warn_cast_align)
14736 << Op->getType() << T
14737 << static_cast<unsigned>(SrcAlign.getQuantity())
14738 << static_cast<unsigned>(DestAlign.getQuantity())
14739 << TRange << Op->getSourceRange();
14740}
14741
14742void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14743 const ArraySubscriptExpr *ASE,
14744 bool AllowOnePastEnd, bool IndexNegated) {
14745 // Already diagnosed by the constant evaluator.
14747 return;
14748
14749 IndexExpr = IndexExpr->IgnoreParenImpCasts();
14750 if (IndexExpr->isValueDependent())
14751 return;
14752
14753 const Type *EffectiveType =
14755 BaseExpr = BaseExpr->IgnoreParenCasts();
14756 const ConstantArrayType *ArrayTy =
14757 Context.getAsConstantArrayType(BaseExpr->getType());
14758
14760 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
14761
14762 const Type *BaseType =
14763 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14764 bool IsUnboundedArray =
14765 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
14766 Context, StrictFlexArraysLevel,
14767 /*IgnoreTemplateOrMacroSubstitution=*/true);
14768 if (EffectiveType->isDependentType() ||
14769 (!IsUnboundedArray && BaseType->isDependentType()))
14770 return;
14771
14773 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14774 return;
14775
14776 llvm::APSInt index = Result.Val.getInt();
14777 if (IndexNegated) {
14778 index.setIsUnsigned(false);
14779 index = -index;
14780 }
14781
14782 if (IsUnboundedArray) {
14783 if (EffectiveType->isFunctionType())
14784 return;
14785 if (index.isUnsigned() || !index.isNegative()) {
14786 const auto &ASTC = getASTContext();
14787 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
14788 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
14789 if (index.getBitWidth() < AddrBits)
14790 index = index.zext(AddrBits);
14791 std::optional<CharUnits> ElemCharUnits =
14792 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14793 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14794 // pointer) bounds-checking isn't meaningful.
14795 if (!ElemCharUnits || ElemCharUnits->isZero())
14796 return;
14797 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14798 // If index has more active bits than address space, we already know
14799 // we have a bounds violation to warn about. Otherwise, compute
14800 // address of (index + 1)th element, and warn about bounds violation
14801 // only if that address exceeds address space.
14802 if (index.getActiveBits() <= AddrBits) {
14803 bool Overflow;
14804 llvm::APInt Product(index);
14805 Product += 1;
14806 Product = Product.umul_ov(ElemBytes, Overflow);
14807 if (!Overflow && Product.getActiveBits() <= AddrBits)
14808 return;
14809 }
14810
14811 // Need to compute max possible elements in address space, since that
14812 // is included in diag message.
14813 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14814 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14815 MaxElems += 1;
14816 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14817 MaxElems = MaxElems.udiv(ElemBytes);
14818
14819 unsigned DiagID =
14820 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14821 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14822
14823 // Diag message shows element size in bits and in "bytes" (platform-
14824 // dependent CharUnits)
14825 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14826 PDiag(DiagID)
14827 << toString(index, 10, true) << AddrBits
14828 << (unsigned)ASTC.toBits(*ElemCharUnits)
14829 << toString(ElemBytes, 10, false)
14830 << toString(MaxElems, 10, false)
14831 << (unsigned)MaxElems.getLimitedValue(~0U)
14832 << IndexExpr->getSourceRange());
14833
14834 const NamedDecl *ND = nullptr;
14835 // Try harder to find a NamedDecl to point at in the note.
14836 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14837 BaseExpr = ASE->getBase()->IgnoreParenCasts();
14838 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14839 ND = DRE->getDecl();
14840 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14841 ND = ME->getMemberDecl();
14842
14843 if (ND)
14844 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14845 PDiag(diag::note_array_declared_here) << ND);
14846 }
14847 return;
14848 }
14849
14850 if (index.isUnsigned() || !index.isNegative()) {
14851 // It is possible that the type of the base expression after
14852 // IgnoreParenCasts is incomplete, even though the type of the base
14853 // expression before IgnoreParenCasts is complete (see PR39746 for an
14854 // example). In this case we have no information about whether the array
14855 // access exceeds the array bounds. However we can still diagnose an array
14856 // access which precedes the array bounds.
14857 if (BaseType->isIncompleteType())
14858 return;
14859
14860 llvm::APInt size = ArrayTy->getSize();
14861
14862 if (BaseType != EffectiveType) {
14863 // Make sure we're comparing apples to apples when comparing index to
14864 // size.
14865 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14866 uint64_t array_typesize = Context.getTypeSize(BaseType);
14867
14868 // Handle ptrarith_typesize being zero, such as when casting to void*.
14869 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
14870 if (!ptrarith_typesize)
14871 ptrarith_typesize = Context.getCharWidth();
14872
14873 if (ptrarith_typesize != array_typesize) {
14874 // There's a cast to a different size type involved.
14875 uint64_t ratio = array_typesize / ptrarith_typesize;
14876
14877 // TODO: Be smarter about handling cases where array_typesize is not a
14878 // multiple of ptrarith_typesize.
14879 if (ptrarith_typesize * ratio == array_typesize)
14880 size *= llvm::APInt(size.getBitWidth(), ratio);
14881 }
14882 }
14883
14884 if (size.getBitWidth() > index.getBitWidth())
14885 index = index.zext(size.getBitWidth());
14886 else if (size.getBitWidth() < index.getBitWidth())
14887 size = size.zext(index.getBitWidth());
14888
14889 // For array subscripting the index must be less than size, but for pointer
14890 // arithmetic also allow the index (offset) to be equal to size since
14891 // computing the next address after the end of the array is legal and
14892 // commonly done e.g. in C++ iterators and range-based for loops.
14893 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14894 return;
14895
14896 // Suppress the warning if the subscript expression (as identified by the
14897 // ']' location) and the index expression are both from macro expansions
14898 // within a system header.
14899 if (ASE) {
14900 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14901 ASE->getRBracketLoc());
14902 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14903 SourceLocation IndexLoc =
14904 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14905 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14906 return;
14907 }
14908 }
14909
14910 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
14911 : diag::warn_ptr_arith_exceeds_bounds;
14912 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
14913 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
14914
14916 BaseExpr->getBeginLoc(), BaseExpr,
14917 PDiag(DiagID) << toString(index, 10, true) << ArrayTy->desugar()
14918 << CastMsg << CastMsgTy << IndexExpr->getSourceRange());
14919 } else {
14920 unsigned DiagID = diag::warn_array_index_precedes_bounds;
14921 if (!ASE) {
14922 DiagID = diag::warn_ptr_arith_precedes_bounds;
14923 if (index.isNegative()) index = -index;
14924 }
14925
14926 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14927 PDiag(DiagID) << toString(index, 10, true)
14928 << IndexExpr->getSourceRange());
14929 }
14930
14931 const NamedDecl *ND = nullptr;
14932 // Try harder to find a NamedDecl to point at in the note.
14933 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14934 BaseExpr = ASE->getBase()->IgnoreParenCasts();
14935 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14936 ND = DRE->getDecl();
14937 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14938 ND = ME->getMemberDecl();
14939
14940 if (ND)
14941 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14942 PDiag(diag::note_array_declared_here) << ND);
14943}
14944
14945void Sema::CheckArrayAccess(const Expr *expr) {
14946 int AllowOnePastEnd = 0;
14947 while (expr) {
14948 expr = expr->IgnoreParenImpCasts();
14949 switch (expr->getStmtClass()) {
14950 case Stmt::ArraySubscriptExprClass: {
14951 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14952 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14953 AllowOnePastEnd > 0);
14954 expr = ASE->getBase();
14955 break;
14956 }
14957 case Stmt::MemberExprClass: {
14958 expr = cast<MemberExpr>(expr)->getBase();
14959 break;
14960 }
14961 case Stmt::ArraySectionExprClass: {
14962 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
14963 // FIXME: We should probably be checking all of the elements to the
14964 // 'length' here as well.
14965 if (ASE->getLowerBound())
14966 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14967 /*ASE=*/nullptr, AllowOnePastEnd > 0);
14968 return;
14969 }
14970 case Stmt::UnaryOperatorClass: {
14971 // Only unwrap the * and & unary operators
14972 const UnaryOperator *UO = cast<UnaryOperator>(expr);
14973 expr = UO->getSubExpr();
14974 switch (UO->getOpcode()) {
14975 case UO_AddrOf:
14976 AllowOnePastEnd++;
14977 break;
14978 case UO_Deref:
14979 AllowOnePastEnd--;
14980 break;
14981 default:
14982 return;
14983 }
14984 break;
14985 }
14986 case Stmt::ConditionalOperatorClass: {
14987 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14988 if (const Expr *lhs = cond->getLHS())
14989 CheckArrayAccess(lhs);
14990 if (const Expr *rhs = cond->getRHS())
14991 CheckArrayAccess(rhs);
14992 return;
14993 }
14994 case Stmt::CXXOperatorCallExprClass: {
14995 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14996 for (const auto *Arg : OCE->arguments())
14997 CheckArrayAccess(Arg);
14998 return;
14999 }
15000 default:
15001 return;
15002 }
15003 }
15004}
15005
15007 Expr *RHS, bool isProperty) {
15008 // Check if RHS is an Objective-C object literal, which also can get
15009 // immediately zapped in a weak reference. Note that we explicitly
15010 // allow ObjCStringLiterals, since those are designed to never really die.
15011 RHS = RHS->IgnoreParenImpCasts();
15012
15013 // This enum needs to match with the 'select' in
15014 // warn_objc_arc_literal_assign (off-by-1).
15016 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
15017 return false;
15018
15019 S.Diag(Loc, diag::warn_arc_literal_assign)
15020 << (unsigned) Kind
15021 << (isProperty ? 0 : 1)
15022 << RHS->getSourceRange();
15023
15024 return true;
15025}
15026
15029 Expr *RHS, bool isProperty) {
15030 // Strip off any implicit cast added to get to the one ARC-specific.
15031 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15032 if (cast->getCastKind() == CK_ARCConsumeObject) {
15033 S.Diag(Loc, diag::warn_arc_retained_assign)
15035 << (isProperty ? 0 : 1)
15036 << RHS->getSourceRange();
15037 return true;
15038 }
15039 RHS = cast->getSubExpr();
15040 }
15041
15042 if (LT == Qualifiers::OCL_Weak &&
15043 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15044 return true;
15045
15046 return false;
15047}
15048
15050 QualType LHS, Expr *RHS) {
15052
15054 return false;
15055
15056 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15057 return true;
15058
15059 return false;
15060}
15061
15063 Expr *LHS, Expr *RHS) {
15064 QualType LHSType;
15065 // PropertyRef on LHS type need be directly obtained from
15066 // its declaration as it has a PseudoType.
15068 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15069 if (PRE && !PRE->isImplicitProperty()) {
15070 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15071 if (PD)
15072 LHSType = PD->getType();
15073 }
15074
15075 if (LHSType.isNull())
15076 LHSType = LHS->getType();
15077
15079
15080 if (LT == Qualifiers::OCL_Weak) {
15081 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15083 }
15084
15085 if (checkUnsafeAssigns(Loc, LHSType, RHS))
15086 return;
15087
15088 // FIXME. Check for other life times.
15089 if (LT != Qualifiers::OCL_None)
15090 return;
15091
15092 if (PRE) {
15093 if (PRE->isImplicitProperty())
15094 return;
15095 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15096 if (!PD)
15097 return;
15098
15099 unsigned Attributes = PD->getPropertyAttributes();
15100 if (Attributes & ObjCPropertyAttribute::kind_assign) {
15101 // when 'assign' attribute was not explicitly specified
15102 // by user, ignore it and rely on property type itself
15103 // for lifetime info.
15104 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15105 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15106 LHSType->isObjCRetainableType())
15107 return;
15108
15109 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15110 if (cast->getCastKind() == CK_ARCConsumeObject) {
15111 Diag(Loc, diag::warn_arc_retained_property_assign)
15112 << RHS->getSourceRange();
15113 return;
15114 }
15115 RHS = cast->getSubExpr();
15116 }
15117 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15118 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15119 return;
15120 }
15121 }
15122}
15123
15124//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15125
15126static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15127 SourceLocation StmtLoc,
15128 const NullStmt *Body) {
15129 // Do not warn if the body is a macro that expands to nothing, e.g:
15130 //
15131 // #define CALL(x)
15132 // if (condition)
15133 // CALL(0);
15134 if (Body->hasLeadingEmptyMacro())
15135 return false;
15136
15137 // Get line numbers of statement and body.
15138 bool StmtLineInvalid;
15139 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15140 &StmtLineInvalid);
15141 if (StmtLineInvalid)
15142 return false;
15143
15144 bool BodyLineInvalid;
15145 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15146 &BodyLineInvalid);
15147 if (BodyLineInvalid)
15148 return false;
15149
15150 // Warn if null statement and body are on the same line.
15151 if (StmtLine != BodyLine)
15152 return false;
15153
15154 return true;
15155}
15156
15158 const Stmt *Body,
15159 unsigned DiagID) {
15160 // Since this is a syntactic check, don't emit diagnostic for template
15161 // instantiations, this just adds noise.
15163 return;
15164
15165 // The body should be a null statement.
15166 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15167 if (!NBody)
15168 return;
15169
15170 // Do the usual checks.
15171 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15172 return;
15173
15174 Diag(NBody->getSemiLoc(), DiagID);
15175 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15176}
15177
15179 const Stmt *PossibleBody) {
15180 assert(!CurrentInstantiationScope); // Ensured by caller
15181
15182 SourceLocation StmtLoc;
15183 const Stmt *Body;
15184 unsigned DiagID;
15185 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15186 StmtLoc = FS->getRParenLoc();
15187 Body = FS->getBody();
15188 DiagID = diag::warn_empty_for_body;
15189 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15190 StmtLoc = WS->getRParenLoc();
15191 Body = WS->getBody();
15192 DiagID = diag::warn_empty_while_body;
15193 } else
15194 return; // Neither `for' nor `while'.
15195
15196 // The body should be a null statement.
15197 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15198 if (!NBody)
15199 return;
15200
15201 // Skip expensive checks if diagnostic is disabled.
15202 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15203 return;
15204
15205 // Do the usual checks.
15206 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15207 return;
15208
15209 // `for(...);' and `while(...);' are popular idioms, so in order to keep
15210 // noise level low, emit diagnostics only if for/while is followed by a
15211 // CompoundStmt, e.g.:
15212 // for (int i = 0; i < n; i++);
15213 // {
15214 // a(i);
15215 // }
15216 // or if for/while is followed by a statement with more indentation
15217 // than for/while itself:
15218 // for (int i = 0; i < n; i++);
15219 // a(i);
15220 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15221 if (!ProbableTypo) {
15222 bool BodyColInvalid;
15223 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15224 PossibleBody->getBeginLoc(), &BodyColInvalid);
15225 if (BodyColInvalid)
15226 return;
15227
15228 bool StmtColInvalid;
15229 unsigned StmtCol =
15230 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15231 if (StmtColInvalid)
15232 return;
15233
15234 if (BodyCol > StmtCol)
15235 ProbableTypo = true;
15236 }
15237
15238 if (ProbableTypo) {
15239 Diag(NBody->getSemiLoc(), DiagID);
15240 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15241 }
15242}
15243
15244//===--- CHECK: Warn on self move with std::move. -------------------------===//
15245
15246void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15247 SourceLocation OpLoc) {
15248 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15249 return;
15250
15252 return;
15253
15254 // Strip parens and casts away.
15255 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15256 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15257
15258 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
15259 // which we can treat as an inlined std::move
15260 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
15261 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
15262 RHSExpr = CE->getArg(0);
15263 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
15264 CXXSCE && CXXSCE->isXValue())
15265 RHSExpr = CXXSCE->getSubExpr();
15266 else
15267 return;
15268
15269 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15270 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15271
15272 // Two DeclRefExpr's, check that the decls are the same.
15273 if (LHSDeclRef && RHSDeclRef) {
15274 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15275 return;
15276 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15277 RHSDeclRef->getDecl()->getCanonicalDecl())
15278 return;
15279
15280 auto D = Diag(OpLoc, diag::warn_self_move)
15281 << LHSExpr->getType() << LHSExpr->getSourceRange()
15282 << RHSExpr->getSourceRange();
15283 if (const FieldDecl *F =
15285 D << 1 << F
15286 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15287 else
15288 D << 0;
15289 return;
15290 }
15291
15292 // Member variables require a different approach to check for self moves.
15293 // MemberExpr's are the same if every nested MemberExpr refers to the same
15294 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15295 // the base Expr's are CXXThisExpr's.
15296 const Expr *LHSBase = LHSExpr;
15297 const Expr *RHSBase = RHSExpr;
15298 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15299 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15300 if (!LHSME || !RHSME)
15301 return;
15302
15303 while (LHSME && RHSME) {
15304 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15305 RHSME->getMemberDecl()->getCanonicalDecl())
15306 return;
15307
15308 LHSBase = LHSME->getBase();
15309 RHSBase = RHSME->getBase();
15310 LHSME = dyn_cast<MemberExpr>(LHSBase);
15311 RHSME = dyn_cast<MemberExpr>(RHSBase);
15312 }
15313
15314 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15315 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15316 if (LHSDeclRef && RHSDeclRef) {
15317 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15318 return;
15319 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15320 RHSDeclRef->getDecl()->getCanonicalDecl())
15321 return;
15322
15323 Diag(OpLoc, diag::warn_self_move)
15324 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15325 << RHSExpr->getSourceRange();
15326 return;
15327 }
15328
15329 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15330 Diag(OpLoc, diag::warn_self_move)
15331 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15332 << RHSExpr->getSourceRange();
15333}
15334
15335//===--- Layout compatibility ----------------------------------------------//
15336
15337static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
15338
15339/// Check if two enumeration types are layout-compatible.
15340static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
15341 const EnumDecl *ED2) {
15342 // C++11 [dcl.enum] p8:
15343 // Two enumeration types are layout-compatible if they have the same
15344 // underlying type.
15345 return ED1->isComplete() && ED2->isComplete() &&
15346 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15347}
15348
15349/// Check if two fields are layout-compatible.
15350/// Can be used on union members, which are exempt from alignment requirement
15351/// of common initial sequence.
15352static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
15353 const FieldDecl *Field2,
15354 bool AreUnionMembers = false) {
15355#ifndef NDEBUG
15356 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
15357 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
15358 assert(((Field1Parent->isStructureOrClassType() &&
15359 Field2Parent->isStructureOrClassType()) ||
15360 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
15361 "Can't evaluate layout compatibility between a struct field and a "
15362 "union field.");
15363 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
15364 (AreUnionMembers && Field1Parent->isUnionType())) &&
15365 "AreUnionMembers should be 'true' for union fields (only).");
15366#endif
15367
15368 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15369 return false;
15370
15371 if (Field1->isBitField() != Field2->isBitField())
15372 return false;
15373
15374 if (Field1->isBitField()) {
15375 // Make sure that the bit-fields are the same length.
15376 unsigned Bits1 = Field1->getBitWidthValue();
15377 unsigned Bits2 = Field2->getBitWidthValue();
15378
15379 if (Bits1 != Bits2)
15380 return false;
15381 }
15382
15383 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
15384 Field2->hasAttr<clang::NoUniqueAddressAttr>())
15385 return false;
15386
15387 if (!AreUnionMembers &&
15388 Field1->getMaxAlignment() != Field2->getMaxAlignment())
15389 return false;
15390
15391 return true;
15392}
15393
15394/// Check if two standard-layout structs are layout-compatible.
15395/// (C++11 [class.mem] p17)
15396static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
15397 const RecordDecl *RD2) {
15398 // Get to the class where the fields are declared
15399 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
15400 RD1 = D1CXX->getStandardLayoutBaseWithFields();
15401
15402 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
15403 RD2 = D2CXX->getStandardLayoutBaseWithFields();
15404
15405 // Check the fields.
15406 return llvm::equal(RD1->fields(), RD2->fields(),
15407 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
15408 return isLayoutCompatible(C, F1, F2);
15409 });
15410}
15411
15412/// Check if two standard-layout unions are layout-compatible.
15413/// (C++11 [class.mem] p18)
15414static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
15415 const RecordDecl *RD2) {
15416 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
15417 RD2->fields());
15418
15419 for (auto *Field1 : RD1->fields()) {
15420 auto I = UnmatchedFields.begin();
15421 auto E = UnmatchedFields.end();
15422
15423 for ( ; I != E; ++I) {
15424 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
15425 bool Result = UnmatchedFields.erase(*I);
15426 (void) Result;
15427 assert(Result);
15428 break;
15429 }
15430 }
15431 if (I == E)
15432 return false;
15433 }
15434
15435 return UnmatchedFields.empty();
15436}
15437
15438static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
15439 const RecordDecl *RD2) {
15440 if (RD1->isUnion() != RD2->isUnion())
15441 return false;
15442
15443 if (RD1->isUnion())
15444 return isLayoutCompatibleUnion(C, RD1, RD2);
15445 else
15446 return isLayoutCompatibleStruct(C, RD1, RD2);
15447}
15448
15449/// Check if two types are layout-compatible in C++11 sense.
15450static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
15451 if (T1.isNull() || T2.isNull())
15452 return false;
15453
15454 // C++20 [basic.types] p11:
15455 // Two types cv1 T1 and cv2 T2 are layout-compatible types
15456 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
15457 // or layout-compatible standard-layout class types (11.4).
15460
15461 if (C.hasSameType(T1, T2))
15462 return true;
15463
15464 const Type::TypeClass TC1 = T1->getTypeClass();
15465 const Type::TypeClass TC2 = T2->getTypeClass();
15466
15467 if (TC1 != TC2)
15468 return false;
15469
15470 if (TC1 == Type::Enum)
15471 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
15472 if (TC1 == Type::Record) {
15473 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15474 return false;
15475
15477 T2->castAsRecordDecl());
15478 }
15479
15480 return false;
15481}
15482
15484 return isLayoutCompatible(getASTContext(), T1, T2);
15485}
15486
15487//===-------------- Pointer interconvertibility ----------------------------//
15488
15490 const TypeSourceInfo *Derived) {
15491 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
15492 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
15493
15494 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
15495 getASTContext().hasSameType(BaseT, DerivedT))
15496 return true;
15497
15498 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
15499 return false;
15500
15501 // Per [basic.compound]/4.3, containing object has to be standard-layout.
15502 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
15503 return true;
15504
15505 return false;
15506}
15507
15508//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15509
15510/// Given a type tag expression find the type tag itself.
15511///
15512/// \param TypeExpr Type tag expression, as it appears in user's code.
15513///
15514/// \param VD Declaration of an identifier that appears in a type tag.
15515///
15516/// \param MagicValue Type tag magic value.
15517///
15518/// \param isConstantEvaluated whether the evalaution should be performed in
15519
15520/// constant context.
15521static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15522 const ValueDecl **VD, uint64_t *MagicValue,
15523 bool isConstantEvaluated) {
15524 while(true) {
15525 if (!TypeExpr)
15526 return false;
15527
15528 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15529
15530 switch (TypeExpr->getStmtClass()) {
15531 case Stmt::UnaryOperatorClass: {
15532 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15533 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15534 TypeExpr = UO->getSubExpr();
15535 continue;
15536 }
15537 return false;
15538 }
15539
15540 case Stmt::DeclRefExprClass: {
15541 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15542 *VD = DRE->getDecl();
15543 return true;
15544 }
15545
15546 case Stmt::IntegerLiteralClass: {
15547 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15548 llvm::APInt MagicValueAPInt = IL->getValue();
15549 if (MagicValueAPInt.getActiveBits() <= 64) {
15550 *MagicValue = MagicValueAPInt.getZExtValue();
15551 return true;
15552 } else
15553 return false;
15554 }
15555
15556 case Stmt::BinaryConditionalOperatorClass:
15557 case Stmt::ConditionalOperatorClass: {
15558 const AbstractConditionalOperator *ACO =
15560 bool Result;
15561 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15562 isConstantEvaluated)) {
15563 if (Result)
15564 TypeExpr = ACO->getTrueExpr();
15565 else
15566 TypeExpr = ACO->getFalseExpr();
15567 continue;
15568 }
15569 return false;
15570 }
15571
15572 case Stmt::BinaryOperatorClass: {
15573 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15574 if (BO->getOpcode() == BO_Comma) {
15575 TypeExpr = BO->getRHS();
15576 continue;
15577 }
15578 return false;
15579 }
15580
15581 default:
15582 return false;
15583 }
15584 }
15585}
15586
15587/// Retrieve the C type corresponding to type tag TypeExpr.
15588///
15589/// \param TypeExpr Expression that specifies a type tag.
15590///
15591/// \param MagicValues Registered magic values.
15592///
15593/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15594/// kind.
15595///
15596/// \param TypeInfo Information about the corresponding C type.
15597///
15598/// \param isConstantEvaluated whether the evalaution should be performed in
15599/// constant context.
15600///
15601/// \returns true if the corresponding C type was found.
15603 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15604 const ASTContext &Ctx,
15605 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15606 *MagicValues,
15607 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15608 bool isConstantEvaluated) {
15609 FoundWrongKind = false;
15610
15611 // Variable declaration that has type_tag_for_datatype attribute.
15612 const ValueDecl *VD = nullptr;
15613
15614 uint64_t MagicValue;
15615
15616 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15617 return false;
15618
15619 if (VD) {
15620 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15621 if (I->getArgumentKind() != ArgumentKind) {
15622 FoundWrongKind = true;
15623 return false;
15624 }
15625 TypeInfo.Type = I->getMatchingCType();
15626 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15627 TypeInfo.MustBeNull = I->getMustBeNull();
15628 return true;
15629 }
15630 return false;
15631 }
15632
15633 if (!MagicValues)
15634 return false;
15635
15636 llvm::DenseMap<Sema::TypeTagMagicValue,
15638 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15639 if (I == MagicValues->end())
15640 return false;
15641
15642 TypeInfo = I->second;
15643 return true;
15644}
15645
15647 uint64_t MagicValue, QualType Type,
15648 bool LayoutCompatible,
15649 bool MustBeNull) {
15650 if (!TypeTagForDatatypeMagicValues)
15651 TypeTagForDatatypeMagicValues.reset(
15652 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15653
15654 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15655 (*TypeTagForDatatypeMagicValues)[Magic] =
15656 TypeTagData(Type, LayoutCompatible, MustBeNull);
15657}
15658
15659static bool IsSameCharType(QualType T1, QualType T2) {
15660 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15661 if (!BT1)
15662 return false;
15663
15664 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15665 if (!BT2)
15666 return false;
15667
15668 BuiltinType::Kind T1Kind = BT1->getKind();
15669 BuiltinType::Kind T2Kind = BT2->getKind();
15670
15671 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
15672 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
15673 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15674 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15675}
15676
15677void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15678 const ArrayRef<const Expr *> ExprArgs,
15679 SourceLocation CallSiteLoc) {
15680 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15681 bool IsPointerAttr = Attr->getIsPointer();
15682
15683 // Retrieve the argument representing the 'type_tag'.
15684 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15685 if (TypeTagIdxAST >= ExprArgs.size()) {
15686 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15687 << 0 << Attr->getTypeTagIdx().getSourceIndex();
15688 return;
15689 }
15690 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15691 bool FoundWrongKind;
15692 TypeTagData TypeInfo;
15693 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15694 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15695 TypeInfo, isConstantEvaluatedContext())) {
15696 if (FoundWrongKind)
15697 Diag(TypeTagExpr->getExprLoc(),
15698 diag::warn_type_tag_for_datatype_wrong_kind)
15699 << TypeTagExpr->getSourceRange();
15700 return;
15701 }
15702
15703 // Retrieve the argument representing the 'arg_idx'.
15704 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15705 if (ArgumentIdxAST >= ExprArgs.size()) {
15706 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15707 << 1 << Attr->getArgumentIdx().getSourceIndex();
15708 return;
15709 }
15710 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15711 if (IsPointerAttr) {
15712 // Skip implicit cast of pointer to `void *' (as a function argument).
15713 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15714 if (ICE->getType()->isVoidPointerType() &&
15715 ICE->getCastKind() == CK_BitCast)
15716 ArgumentExpr = ICE->getSubExpr();
15717 }
15718 QualType ArgumentType = ArgumentExpr->getType();
15719
15720 // Passing a `void*' pointer shouldn't trigger a warning.
15721 if (IsPointerAttr && ArgumentType->isVoidPointerType())
15722 return;
15723
15724 if (TypeInfo.MustBeNull) {
15725 // Type tag with matching void type requires a null pointer.
15726 if (!ArgumentExpr->isNullPointerConstant(Context,
15728 Diag(ArgumentExpr->getExprLoc(),
15729 diag::warn_type_safety_null_pointer_required)
15730 << ArgumentKind->getName()
15731 << ArgumentExpr->getSourceRange()
15732 << TypeTagExpr->getSourceRange();
15733 }
15734 return;
15735 }
15736
15737 QualType RequiredType = TypeInfo.Type;
15738 if (IsPointerAttr)
15739 RequiredType = Context.getPointerType(RequiredType);
15740
15741 bool mismatch = false;
15742 if (!TypeInfo.LayoutCompatible) {
15743 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15744
15745 // C++11 [basic.fundamental] p1:
15746 // Plain char, signed char, and unsigned char are three distinct types.
15747 //
15748 // But we treat plain `char' as equivalent to `signed char' or `unsigned
15749 // char' depending on the current char signedness mode.
15750 if (mismatch)
15751 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15752 RequiredType->getPointeeType())) ||
15753 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15754 mismatch = false;
15755 } else
15756 if (IsPointerAttr)
15757 mismatch = !isLayoutCompatible(Context,
15758 ArgumentType->getPointeeType(),
15759 RequiredType->getPointeeType());
15760 else
15761 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15762
15763 if (mismatch)
15764 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15765 << ArgumentType << ArgumentKind
15766 << TypeInfo.LayoutCompatible << RequiredType
15767 << ArgumentExpr->getSourceRange()
15768 << TypeTagExpr->getSourceRange();
15769}
15770
15771void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15772 CharUnits Alignment) {
15773 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
15774 Alignment);
15775}
15776
15778 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
15779 const NamedDecl *ND = m.RD;
15780 if (ND->getName().empty()) {
15781 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15782 ND = TD;
15783 }
15784 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15785 << m.MD << ND << m.E->getSourceRange();
15786 }
15788}
15789
15791 E = E->IgnoreParens();
15792 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
15793 return;
15794 if (isa<UnaryOperator>(E) &&
15795 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15796 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15797 if (isa<MemberExpr>(Op)) {
15798 auto &MisalignedMembersForExpr =
15800 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
15801 if (MA != MisalignedMembersForExpr.end() &&
15802 (T->isDependentType() || T->isIntegerType() ||
15803 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15804 Context.getTypeAlignInChars(
15805 T->getPointeeType()) <= MA->Alignment))))
15806 MisalignedMembersForExpr.erase(MA);
15807 }
15808 }
15809}
15810
15812 Expr *E,
15813 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15814 Action) {
15815 const auto *ME = dyn_cast<MemberExpr>(E);
15816 if (!ME)
15817 return;
15818
15819 // No need to check expressions with an __unaligned-qualified type.
15820 if (E->getType().getQualifiers().hasUnaligned())
15821 return;
15822
15823 // For a chain of MemberExpr like "a.b.c.d" this list
15824 // will keep FieldDecl's like [d, c, b].
15825 SmallVector<FieldDecl *, 4> ReverseMemberChain;
15826 const MemberExpr *TopME = nullptr;
15827 bool AnyIsPacked = false;
15828 do {
15829 QualType BaseType = ME->getBase()->getType();
15830 if (BaseType->isDependentType())
15831 return;
15832 if (ME->isArrow())
15833 BaseType = BaseType->getPointeeType();
15834 auto *RD = BaseType->castAsRecordDecl();
15835 if (RD->isInvalidDecl())
15836 return;
15837
15838 ValueDecl *MD = ME->getMemberDecl();
15839 auto *FD = dyn_cast<FieldDecl>(MD);
15840 // We do not care about non-data members.
15841 if (!FD || FD->isInvalidDecl())
15842 return;
15843
15844 AnyIsPacked =
15845 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15846 ReverseMemberChain.push_back(FD);
15847
15848 TopME = ME;
15849 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15850 } while (ME);
15851 assert(TopME && "We did not compute a topmost MemberExpr!");
15852
15853 // Not the scope of this diagnostic.
15854 if (!AnyIsPacked)
15855 return;
15856
15857 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15858 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15859 // TODO: The innermost base of the member expression may be too complicated.
15860 // For now, just disregard these cases. This is left for future
15861 // improvement.
15862 if (!DRE && !isa<CXXThisExpr>(TopBase))
15863 return;
15864
15865 // Alignment expected by the whole expression.
15866 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15867
15868 // No need to do anything else with this case.
15869 if (ExpectedAlignment.isOne())
15870 return;
15871
15872 // Synthesize offset of the whole access.
15873 CharUnits Offset;
15874 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
15875 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
15876
15877 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15878 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15879 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
15880
15881 // The base expression of the innermost MemberExpr may give
15882 // stronger guarantees than the class containing the member.
15883 if (DRE && !TopME->isArrow()) {
15884 const ValueDecl *VD = DRE->getDecl();
15885 if (!VD->getType()->isReferenceType())
15886 CompleteObjectAlignment =
15887 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15888 }
15889
15890 // Check if the synthesized offset fulfills the alignment.
15891 if (Offset % ExpectedAlignment != 0 ||
15892 // It may fulfill the offset it but the effective alignment may still be
15893 // lower than the expected expression alignment.
15894 CompleteObjectAlignment < ExpectedAlignment) {
15895 // If this happens, we want to determine a sensible culprit of this.
15896 // Intuitively, watching the chain of member expressions from right to
15897 // left, we start with the required alignment (as required by the field
15898 // type) but some packed attribute in that chain has reduced the alignment.
15899 // It may happen that another packed structure increases it again. But if
15900 // we are here such increase has not been enough. So pointing the first
15901 // FieldDecl that either is packed or else its RecordDecl is,
15902 // seems reasonable.
15903 FieldDecl *FD = nullptr;
15904 CharUnits Alignment;
15905 for (FieldDecl *FDI : ReverseMemberChain) {
15906 if (FDI->hasAttr<PackedAttr>() ||
15907 FDI->getParent()->hasAttr<PackedAttr>()) {
15908 FD = FDI;
15909 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
15910 Context.getTypeAlignInChars(
15911 Context.getCanonicalTagType(FD->getParent())));
15912 break;
15913 }
15914 }
15915 assert(FD && "We did not find a packed FieldDecl!");
15916 Action(E, FD->getParent(), FD, Alignment);
15917 }
15918}
15919
15920void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15921 using namespace std::placeholders;
15922
15924 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15925 _2, _3, _4));
15926}
15927
15928// Performs a similar job to Sema::UsualUnaryConversions, but without any
15929// implicit promotion of integral/enumeration types.
15931 // First, convert to an r-value.
15933 if (Res.isInvalid())
15934 return ExprError();
15935
15936 // Promote floating-point types.
15937 return S.UsualUnaryFPConversions(Res.get());
15938}
15939
15941 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
15942 if (checkArgCount(TheCall, 1))
15943 return true;
15944
15945 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
15946 if (A.isInvalid())
15947 return true;
15948
15949 TheCall->setArg(0, A.get());
15950 QualType TyA = A.get()->getType();
15951
15952 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
15953 ArgTyRestr, 1))
15954 return true;
15955
15956 TheCall->setType(TyA);
15957 return false;
15958}
15959
15960bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
15961 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
15962 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
15963 TheCall->setType(*Res);
15964 return false;
15965 }
15966 return true;
15967}
15968
15970 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
15971 if (!Res)
15972 return true;
15973
15974 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
15975 TheCall->setType(VecTy0->getElementType());
15976 else
15977 TheCall->setType(*Res);
15978
15979 return false;
15980}
15981
15983 SourceLocation Loc) {
15985 R = RHS->getEnumCoercedType(S.Context);
15986 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
15988 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
15989 << LHS->getSourceRange() << RHS->getSourceRange()
15990 << /*Arithmetic Between*/ 0 << L << R;
15991 }
15992 return false;
15993}
15994
15995/// Check if all arguments have the same type. If the types don't match, emit an
15996/// error message and return true. Otherwise return false.
15997///
15998/// For scalars we directly compare their unqualified types. But even if we
15999/// compare unqualified vector types, a difference in qualifiers in the element
16000/// types can make the vector types be considered not equal. For example,
16001/// vector of 4 'const float' values vs vector of 4 'float' values.
16002/// So we compare unqualified types of their elements and number of elements.
16004 ArrayRef<Expr *> Args) {
16005 assert(!Args.empty() && "Should have at least one argument.");
16006
16007 Expr *Arg0 = Args.front();
16008 QualType Ty0 = Arg0->getType();
16009
16010 auto EmitError = [&](Expr *ArgI) {
16011 SemaRef.Diag(Arg0->getBeginLoc(),
16012 diag::err_typecheck_call_different_arg_types)
16013 << Arg0->getType() << ArgI->getType();
16014 };
16015
16016 // Compare scalar types.
16017 if (!Ty0->isVectorType()) {
16018 for (Expr *ArgI : Args.drop_front())
16019 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
16020 EmitError(ArgI);
16021 return true;
16022 }
16023
16024 return false;
16025 }
16026
16027 // Compare vector types.
16028 const auto *Vec0 = Ty0->castAs<VectorType>();
16029 for (Expr *ArgI : Args.drop_front()) {
16030 const auto *VecI = ArgI->getType()->getAs<VectorType>();
16031 if (!VecI ||
16032 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
16033 VecI->getElementType()) ||
16034 Vec0->getNumElements() != VecI->getNumElements()) {
16035 EmitError(ArgI);
16036 return true;
16037 }
16038 }
16039
16040 return false;
16041}
16042
16043std::optional<QualType>
16045 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16046 if (checkArgCount(TheCall, 2))
16047 return std::nullopt;
16048
16050 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
16051 return std::nullopt;
16052
16053 Expr *Args[2];
16054 for (int I = 0; I < 2; ++I) {
16055 ExprResult Converted =
16056 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16057 if (Converted.isInvalid())
16058 return std::nullopt;
16059 Args[I] = Converted.get();
16060 }
16061
16062 SourceLocation LocA = Args[0]->getBeginLoc();
16063 QualType TyA = Args[0]->getType();
16064
16065 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
16066 return std::nullopt;
16067
16068 if (checkBuiltinVectorMathArgTypes(*this, Args))
16069 return std::nullopt;
16070
16071 TheCall->setArg(0, Args[0]);
16072 TheCall->setArg(1, Args[1]);
16073 return TyA;
16074}
16075
16077 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16078 if (checkArgCount(TheCall, 3))
16079 return true;
16080
16081 SourceLocation Loc = TheCall->getExprLoc();
16082 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
16083 TheCall->getArg(1), Loc) ||
16084 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
16085 TheCall->getArg(2), Loc))
16086 return true;
16087
16088 Expr *Args[3];
16089 for (int I = 0; I < 3; ++I) {
16090 ExprResult Converted =
16091 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16092 if (Converted.isInvalid())
16093 return true;
16094 Args[I] = Converted.get();
16095 }
16096
16097 int ArgOrdinal = 1;
16098 for (Expr *Arg : Args) {
16099 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
16100 ArgTyRestr, ArgOrdinal++))
16101 return true;
16102 }
16103
16104 if (checkBuiltinVectorMathArgTypes(*this, Args))
16105 return true;
16106
16107 for (int I = 0; I < 3; ++I)
16108 TheCall->setArg(I, Args[I]);
16109
16110 TheCall->setType(Args[0]->getType());
16111 return false;
16112}
16113
16114bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16115 if (checkArgCount(TheCall, 1))
16116 return true;
16117
16118 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16119 if (A.isInvalid())
16120 return true;
16121
16122 TheCall->setArg(0, A.get());
16123 return false;
16124}
16125
16126bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
16127 if (checkArgCount(TheCall, 1))
16128 return true;
16129
16130 ExprResult Arg = TheCall->getArg(0);
16131 QualType TyArg = Arg.get()->getType();
16132
16133 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
16134 return Diag(TheCall->getArg(0)->getBeginLoc(),
16135 diag::err_builtin_invalid_arg_type)
16136 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
16137
16138 TheCall->setType(TyArg);
16139 return false;
16140}
16141
16142ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
16143 ExprResult CallResult) {
16144 if (checkArgCount(TheCall, 1))
16145 return ExprError();
16146
16147 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16148 if (MatrixArg.isInvalid())
16149 return MatrixArg;
16150 Expr *Matrix = MatrixArg.get();
16151
16152 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16153 if (!MType) {
16154 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16155 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
16156 << Matrix->getType();
16157 return ExprError();
16158 }
16159
16160 // Create returned matrix type by swapping rows and columns of the argument
16161 // matrix type.
16162 QualType ResultType = Context.getConstantMatrixType(
16163 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16164
16165 // Change the return type to the type of the returned matrix.
16166 TheCall->setType(ResultType);
16167
16168 // Update call argument to use the possibly converted matrix argument.
16169 TheCall->setArg(0, Matrix);
16170 return CallResult;
16171}
16172
16173// Get and verify the matrix dimensions.
16174static std::optional<unsigned>
16176 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
16177 if (!Value) {
16178 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16179 << Name;
16180 return {};
16181 }
16182 uint64_t Dim = Value->getZExtValue();
16184 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16186 return {};
16187 }
16188 return Dim;
16189}
16190
16191ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16192 ExprResult CallResult) {
16193 if (!getLangOpts().MatrixTypes) {
16194 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16195 return ExprError();
16196 }
16197
16198 if (checkArgCount(TheCall, 4))
16199 return ExprError();
16200
16201 unsigned PtrArgIdx = 0;
16202 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16203 Expr *RowsExpr = TheCall->getArg(1);
16204 Expr *ColumnsExpr = TheCall->getArg(2);
16205 Expr *StrideExpr = TheCall->getArg(3);
16206
16207 bool ArgError = false;
16208
16209 // Check pointer argument.
16210 {
16212 if (PtrConv.isInvalid())
16213 return PtrConv;
16214 PtrExpr = PtrConv.get();
16215 TheCall->setArg(0, PtrExpr);
16216 if (PtrExpr->isTypeDependent()) {
16217 TheCall->setType(Context.DependentTy);
16218 return TheCall;
16219 }
16220 }
16221
16222 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16223 QualType ElementTy;
16224 if (!PtrTy) {
16225 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16226 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
16227 << PtrExpr->getType();
16228 ArgError = true;
16229 } else {
16230 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16231
16233 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16234 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
16235 << /* no fp */ 0 << PtrExpr->getType();
16236 ArgError = true;
16237 }
16238 }
16239
16240 // Apply default Lvalue conversions and convert the expression to size_t.
16241 auto ApplyArgumentConversions = [this](Expr *E) {
16243 if (Conv.isInvalid())
16244 return Conv;
16245
16246 return tryConvertExprToType(Conv.get(), Context.getSizeType());
16247 };
16248
16249 // Apply conversion to row and column expressions.
16250 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16251 if (!RowsConv.isInvalid()) {
16252 RowsExpr = RowsConv.get();
16253 TheCall->setArg(1, RowsExpr);
16254 } else
16255 RowsExpr = nullptr;
16256
16257 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16258 if (!ColumnsConv.isInvalid()) {
16259 ColumnsExpr = ColumnsConv.get();
16260 TheCall->setArg(2, ColumnsExpr);
16261 } else
16262 ColumnsExpr = nullptr;
16263
16264 // If any part of the result matrix type is still pending, just use
16265 // Context.DependentTy, until all parts are resolved.
16266 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16267 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16268 TheCall->setType(Context.DependentTy);
16269 return CallResult;
16270 }
16271
16272 // Check row and column dimensions.
16273 std::optional<unsigned> MaybeRows;
16274 if (RowsExpr)
16275 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16276
16277 std::optional<unsigned> MaybeColumns;
16278 if (ColumnsExpr)
16279 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16280
16281 // Check stride argument.
16282 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16283 if (StrideConv.isInvalid())
16284 return ExprError();
16285 StrideExpr = StrideConv.get();
16286 TheCall->setArg(3, StrideExpr);
16287
16288 if (MaybeRows) {
16289 if (std::optional<llvm::APSInt> Value =
16290 StrideExpr->getIntegerConstantExpr(Context)) {
16291 uint64_t Stride = Value->getZExtValue();
16292 if (Stride < *MaybeRows) {
16293 Diag(StrideExpr->getBeginLoc(),
16294 diag::err_builtin_matrix_stride_too_small);
16295 ArgError = true;
16296 }
16297 }
16298 }
16299
16300 if (ArgError || !MaybeRows || !MaybeColumns)
16301 return ExprError();
16302
16303 TheCall->setType(
16304 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16305 return CallResult;
16306}
16307
16308ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16309 ExprResult CallResult) {
16310 if (checkArgCount(TheCall, 3))
16311 return ExprError();
16312
16313 unsigned PtrArgIdx = 1;
16314 Expr *MatrixExpr = TheCall->getArg(0);
16315 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16316 Expr *StrideExpr = TheCall->getArg(2);
16317
16318 bool ArgError = false;
16319
16320 {
16321 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16322 if (MatrixConv.isInvalid())
16323 return MatrixConv;
16324 MatrixExpr = MatrixConv.get();
16325 TheCall->setArg(0, MatrixExpr);
16326 }
16327 if (MatrixExpr->isTypeDependent()) {
16328 TheCall->setType(Context.DependentTy);
16329 return TheCall;
16330 }
16331
16332 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16333 if (!MatrixTy) {
16334 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16335 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
16336 ArgError = true;
16337 }
16338
16339 {
16341 if (PtrConv.isInvalid())
16342 return PtrConv;
16343 PtrExpr = PtrConv.get();
16344 TheCall->setArg(1, PtrExpr);
16345 if (PtrExpr->isTypeDependent()) {
16346 TheCall->setType(Context.DependentTy);
16347 return TheCall;
16348 }
16349 }
16350
16351 // Check pointer argument.
16352 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16353 if (!PtrTy) {
16354 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16355 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
16356 << PtrExpr->getType();
16357 ArgError = true;
16358 } else {
16359 QualType ElementTy = PtrTy->getPointeeType();
16360 if (ElementTy.isConstQualified()) {
16361 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16362 ArgError = true;
16363 }
16364 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16365 if (MatrixTy &&
16366 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16367 Diag(PtrExpr->getBeginLoc(),
16368 diag::err_builtin_matrix_pointer_arg_mismatch)
16369 << ElementTy << MatrixTy->getElementType();
16370 ArgError = true;
16371 }
16372 }
16373
16374 // Apply default Lvalue conversions and convert the stride expression to
16375 // size_t.
16376 {
16377 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16378 if (StrideConv.isInvalid())
16379 return StrideConv;
16380
16381 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16382 if (StrideConv.isInvalid())
16383 return StrideConv;
16384 StrideExpr = StrideConv.get();
16385 TheCall->setArg(2, StrideExpr);
16386 }
16387
16388 // Check stride argument.
16389 if (MatrixTy) {
16390 if (std::optional<llvm::APSInt> Value =
16391 StrideExpr->getIntegerConstantExpr(Context)) {
16392 uint64_t Stride = Value->getZExtValue();
16393 if (Stride < MatrixTy->getNumRows()) {
16394 Diag(StrideExpr->getBeginLoc(),
16395 diag::err_builtin_matrix_stride_too_small);
16396 ArgError = true;
16397 }
16398 }
16399 }
16400
16401 if (ArgError)
16402 return ExprError();
16403
16404 return CallResult;
16405}
16406
16408 const NamedDecl *Callee) {
16409 // This warning does not make sense in code that has no runtime behavior.
16411 return;
16412
16413 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
16414
16415 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
16416 return;
16417
16418 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16419 // all TCBs the callee is a part of.
16420 llvm::StringSet<> CalleeTCBs;
16421 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
16422 CalleeTCBs.insert(A->getTCBName());
16423 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
16424 CalleeTCBs.insert(A->getTCBName());
16425
16426 // Go through the TCBs the caller is a part of and emit warnings if Caller
16427 // is in a TCB that the Callee is not.
16428 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
16429 StringRef CallerTCB = A->getTCBName();
16430 if (CalleeTCBs.count(CallerTCB) == 0) {
16431 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
16432 << Callee << CallerTCB;
16433 }
16434 }
16435}
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.
TokenType getType() const
Returns the token's type, e.g.
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.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
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
#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)
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 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 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, bool IgnoreStringsWithoutSpecifiers=false)
static bool IsSameFloatAfterCast(const llvm::APFloat &value, const llvm::fltSemantics &Src, const llvm::fltSemantics &Tgt)
Checks whether the given value, which currently has the given source semantics, has the same value wh...
static 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)
CFIUncheckedCalleeChange
@ Discarding
@ Adding
static QualType GetExprType(const Expr *E)
static CFIUncheckedCalleeChange AdjustingCFIUncheckedCallee(QualType From, QualType To)
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 CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref, ArrayRef< EquatableFormatArgument > RefArgs, const StringLiteral *Fmt, ArrayRef< EquatableFormatArgument > FmtArgs, const Expr *FmtExpr, bool InFunctionCall)
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 CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg, unsigned Pos)
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 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)
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 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 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 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 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 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)
MathCheck
static bool isNonNullType(QualType type)
Determine whether the given type has a non-null nullability annotation.
static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A, Sema::FormatArgumentPassingKind B)
static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall)
Check that the first argument to __builtin_annotation is an integer and the second argument is a non-...
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx)
This helper function takes a pointer expression and returns the alignment of a VarDecl and a constant...
static bool IsShiftedByte(llvm::APSInt Value)
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, unsigned AbsFunctionKind)
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
checkBuiltinArgument - Given a call to a builtin function, perform normal type-checking on the given ...
static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E)
Analyze the operands of the given comparison.
static bool 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 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.
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)
__device__ __2f16 float __ockl_bool s
@ 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 * toString() const
const char * getStart() 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
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
const LValueBase getLValueBase() const
Definition APValue.cpp:983
APSInt & getInt()
Definition APValue.h:489
bool isVector() const
Definition APValue.h:473
APSInt & getComplexIntImag()
Definition APValue.h:527
bool isComplexInt() const
Definition APValue.h:470
bool isFloat() const
Definition APValue.h:468
bool isComplexFloat() const
Definition APValue.h:471
APValue & getVectorElt(unsigned I)
Definition APValue.h:563
unsigned getVectorLength() const
Definition APValue.h:571
bool isLValue() const
Definition APValue.h:472
bool isInt() const
Definition APValue.h:467
APSInt & getComplexIntReal()
Definition APValue.h:519
APFloat & getComplexFloatImag()
Definition APValue.h:543
APFloat & getComplexFloatReal()
Definition APValue.h:535
APFloat & getFloat()
Definition APValue.h:503
bool isAddrLabelDiff() const
Definition APValue.h:478
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:188
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
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
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.
IdentifierTable & Idents
Definition ASTContext.h:737
Builtin::Context & BuiltinInfo
Definition ASTContext.h:739
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:790
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
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.
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:856
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.
@ 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:4287
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4465
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4471
SourceLocation getQuestionLoc() const
Definition Expr.h:4314
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4477
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:7171
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7175
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2721
SourceLocation getRBracketLoc() const
Definition Expr.h:2769
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2750
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3720
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3734
QualType getElementType() const
Definition TypeBase.h:3732
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6814
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:6963
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:6945
Attr - This represents one attribute.
Definition Attr.h:44
const char * getSpelling() const
Type source information for an attributed type.
Definition TypeLoc.h:1017
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1031
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3972
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4105
Expr * getLHS() const
Definition Expr.h:4022
SourceLocation getOperatorLoc() const
Definition Expr.h:4014
SourceLocation getExprLoc() const
Definition Expr.h:4013
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2128
Expr * getRHS() const
Definition Expr.h:4024
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4058
Opcode getOpcode() const
Definition Expr.h:4017
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4069
BinaryOperatorKind Opcode
Definition Expr.h:3977
Pointer to a block type.
Definition TypeBase.h:3540
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
bool isInteger() const
Definition TypeBase.h:3225
bool isFloatingPoint() const
Definition TypeBase.h:3237
bool isSignedInteger() const
Definition TypeBase.h:3229
bool isUnsignedInteger() const
Definition TypeBase.h:3233
Kind getKind() const
Definition TypeBase.h:3212
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:375
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:3903
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a call to a C++ constructor.
Definition ExprCXX.h:1549
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition ExprCXX.h:1631
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1689
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:84
SourceLocation getExprLoc() const LLVM_READONLY
Definition ExprCXX.h:154
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:114
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5135
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5175
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:1225
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:1214
bool isDynamicClass() const
Definition DeclCXX.h:574
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2877
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3081
SourceLocation getBeginLoc() const
Definition Expr.h:3211
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3094
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1588
arg_iterator arg_begin()
Definition Expr.h:3134
arg_iterator arg_end()
Definition Expr.h:3137
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3060
bool isCallToStdMove() const
Definition Expr.cpp:3619
Expr * getCallee()
Definition Expr.h:3024
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3068
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3170
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3071
arg_range arguments()
Definition Expr.h:3129
SourceLocation getEndLoc() const
Definition Expr.h:3230
SourceLocation getRParenLoc() const
Definition Expr.h:3208
Decl * getCalleeDecl()
Definition Expr.h:3054
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:1593
void setCallee(Expr *F)
Definition Expr.h:3026
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition Expr.h:3113
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:3610
path_iterator path_begin()
Definition Expr.h:3680
CastKind getCastKind() const
Definition Expr.h:3654
path_iterator path_end()
Definition Expr.h:3681
Expr * getSubExpr()
Definition Expr.h:3660
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
bool isOne() const
isOne - Test whether the quantity equals one.
Definition CharUnits.h:125
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
ConditionalOperator - The ?
Definition Expr.h:4325
Expr * getLHS() const
Definition Expr.h:4359
Expr * getRHS() const
Definition Expr.h:4360
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3758
QualType desugar() const
Definition TypeBase.h:3859
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3814
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:346
static constexpr unsigned getMaxElementsPerDimension()
Returns the maximum number of elements per dimension.
Definition TypeBase.h:4405
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition TypeBase.h:4400
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:5527
Expr * getOperand() const
Definition ExprCXX.h:5318
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:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool isStdNamespace() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
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:484
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1363
ValueDecl * getDecl()
Definition Expr.h:1338
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1468
SourceLocation getBeginLoc() const
Definition Expr.h:1349
SourceLocation getLocation() const
Definition Expr.h:1346
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:427
T * getAttr() const
Definition DeclBase.h:573
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:538
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:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:427
The name of a declaration.
std::string getAsString() const
Retrieve the human-readable string for this name.
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:1988
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:808
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:231
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:950
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3420
Represents an enum.
Definition Decl.h:4004
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4227
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4168
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,...
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:674
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition Expr.h:671
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3090
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:444
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.
bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3085
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3073
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:3081
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:202
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:4205
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:831
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:835
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:451
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3077
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:3665
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:3065
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:802
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:811
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:814
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:804
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:4042
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:262
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:461
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:464
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:523
bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
const ValueDecl * getAsBuiltinConstantDeclRef(const ASTContext &Context) const
If this expression is an unambiguous reference to a single declaration, in the style of __builtin_fun...
Definition Expr.cpp:222
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:133
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition TypeBase.h:4265
Represents a member of a struct/union/class.
Definition Decl.h:3157
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3260
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4693
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3393
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3273
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:78
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:139
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:128
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:102
llvm::APFloat getValue() const
Definition Expr.h:1666
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2888
Represents a function declaration or definition.
Definition Decl.h:1999
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4494
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2794
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3703
param_iterator param_end()
Definition Decl.h:2784
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3806
QualType getReturnType() const
Definition Decl.h:2842
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2771
param_iterator param_begin()
Definition Decl.h:2783
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3125
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4270
bool isStatic() const
Definition Decl.h:2926
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4085
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4071
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3767
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5264
unsigned getNumParams() const
Definition TypeBase.h:5542
QualType getParamType(unsigned i) const
Definition TypeBase.h:5544
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5668
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5553
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5663
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5549
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4460
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4769
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4765
QualType getReturnType() const
Definition TypeBase.h:4800
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:3787
Describes an C or C++ initializer list.
Definition Expr.h:5233
ArrayRef< Expr * > inits()
Definition Expr.h:5283
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:971
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:1020
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1056
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:498
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1103
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:848
Represents the results of name lookup.
Definition Lookup.h:147
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition TypeBase.h:4356
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3298
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3381
Expr * getBase() const
Definition Expr.h:3375
bool isArrow() const
Definition Expr.h:3482
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3651
This represents a decl that may have a name.
Definition Decl.h:273
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:294
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:300
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1930
Represent a C++ namespace.
Definition Decl.h:591
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition Stmt.h:1683
bool hasLeadingEmptyMacro() const
Definition Stmt.h:1697
SourceLocation getSemiLoc() const
Definition Stmt.h:1694
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:616
ObjCPropertyDecl * getExplicitProperty() const
Definition ExprObjC.h:705
bool isImplicitProperty() const
Definition ExprObjC.h:702
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:52
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:290
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
Represents a parameter to a function.
Definition Decl.h:1789
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:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6690
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5073
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2867
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1453
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1214
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:8285
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8411
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8325
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition TypeBase.h:8337
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8379
void removeLocalVolatile()
Definition TypeBase.h:8401
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1179
void removeLocalConst()
Definition TypeBase.h:8393
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8358
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8406
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8331
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1442
@ 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:4309
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4395
field_range fields() const
Definition Decl.h:4512
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4387
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:616
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
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:1012
@ 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:1093
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
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
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:95
void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg)
Definition SemaPPC.cpp:30
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition SemaPPC.cpp:262
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSPIRVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaWasm.cpp:283
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaX86.cpp:543
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:853
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:1419
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:12943
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1119
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:2639
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9290
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9298
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9335
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:6889
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.
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2048
SemaHexagon & Hexagon()
Definition Sema.h:1459
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:1647
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition SemaExpr.cpp:827
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition Sema.h:1549
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:1282
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:921
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:1489
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:748
ASTContext & getASTContext() const
Definition Sema.h:924
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:756
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2588
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:1190
bool AddingCFIUncheckedCallee(QualType From, QualType To) const
Returns true if From is a function or pointer to a function without the cfi_unchecked_callee attribut...
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:2700
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
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:917
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:1434
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:1449
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:1280
static const uint64_t MaximumAlignment
Definition Sema.h:1213
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:946
SemaHLSL & HLSL()
Definition Sema.h:1454
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1474
SemaRISCV & RISCV()
Definition Sema.h:1519
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:2766
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:6922
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1659
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:1313
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition Sema.h:2668
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15245
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:2294
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:633
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:1417
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:1499
FormatArgumentPassingKind
Definition Sema.h:2598
@ FAPK_Elsewhere
Definition Sema.h:2602
@ FAPK_Fixed
Definition Sema.h:2599
@ FAPK_Variadic
Definition Sema.h:2600
@ FAPK_VAList
Definition Sema.h:2601
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:8129
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:13798
SourceManager & getSourceManager() const
Definition Sema.h:922
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 DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:218
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:2590
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:1509
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:1245
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 FomatStringIn...
SemaSystemZ & SystemZ()
Definition Sema.h:1539
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:1285
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:777
DiagnosticsEngine & Diags
Definition Sema.h:1284
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:1484
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:627
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:6194
SemaSPIRV & SPIRV()
Definition Sema.h:1524
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:1464
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6382
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:1544
SemaARM & ARM()
Definition Sema.h:1424
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:4577
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:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:358
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:295
StmtClass getStmtClass() const
Definition Stmt.h:1472
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:334
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:346
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1973
bool isUTF8() const
Definition Expr.h:1918
bool isWide() const
Definition Expr.h:1917
bool isPascal() const
Definition Expr.h:1922
unsigned getLength() const
Definition Expr.h:1909
StringLiteralKind getKind() const
Definition Expr.h:1912
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:1322
bool isUTF32() const
Definition Expr.h:1920
unsigned getByteLength() const
Definition Expr.h:1908
StringRef getString() const
Definition Expr.h:1867
bool isUTF16() const
Definition Expr.h:1919
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.h:1974
bool isOrdinary() const
Definition Expr.h:1916
unsigned getCharByteWidth() const
Definition Expr.h:1910
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3829
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3809
bool isUnion() const
Definition Decl.h:3919
Exposes information about the current target.
Definition TargetInfo.h:226
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:385
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:2715
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:6175
A container of type source information.
Definition TypeBase.h:8256
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:272
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8267
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isBlockPointerType() const
Definition TypeBase.h:8542
bool isVoidType() const
Definition TypeBase.h:8878
bool isBooleanType() const
Definition TypeBase.h:9008
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9058
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:787
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2273
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2115
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:9038
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:2066
bool isVoidPointerType() const
Definition Type.cpp:712
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2426
bool isArrayType() const
Definition TypeBase.h:8621
bool isCharType() const
Definition Type.cpp:2132
bool isFunctionPointerType() const
Definition TypeBase.h:8589
bool isPointerType() const
Definition TypeBase.h:8522
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8922
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9165
bool isReferenceType() const
Definition TypeBase.h:8546
bool isEnumeralType() const
Definition TypeBase.h:8653
bool isScalarType() const
Definition TypeBase.h:8980
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:1909
bool isVariableArrayType() const
Definition TypeBase.h:8633
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2608
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isExtVectorType() const
Definition TypeBase.h:8665
bool isExtVectorBoolType() const
Definition TypeBase.h:8669
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2647
bool isBitIntType() const
Definition TypeBase.h:8787
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8847
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8645
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
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:2243
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3119
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2558
bool isAtomicType() const
Definition TypeBase.h:8704
bool isFunctionProtoType() const
Definition TypeBase.h:2601
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3075
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:2800
bool isUnscopedEnumerationType() const
Definition Type.cpp:2125
bool isObjCObjectType() const
Definition TypeBase.h:8695
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9151
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9014
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2510
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:2436
bool isFunctionType() const
Definition TypeBase.h:8518
bool isObjCObjectPointerType() const
Definition TypeBase.h:8691
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2312
bool isStructureOrClassType() const
Definition Type.cpp:706
bool isVectorType() const
Definition TypeBase.h:8661
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2320
bool isFloatingType() const
Definition Type.cpp:2304
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:2253
bool isAnyPointerType() const
Definition TypeBase.h:8530
TypeClass getTypeClass() const
Definition TypeBase.h:2385
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2411
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9098
bool isNullPtrType() const
Definition TypeBase.h:8915
bool isRecordType() const
Definition TypeBase.h:8649
bool isObjCRetainableType() const
Definition Type.cpp:5291
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5022
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2570
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2635
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3559
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2625
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
Expr * getSubExpr() const
Definition Expr.h:2285
Opcode getOpcode() const
Definition Expr.h:2280
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2362
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:998
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1086
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3399
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:711
QualType getType() const
Definition Decl.h:722
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5453
Represents a variable declaration or definition.
Definition Decl.h:925
Represents a GCC generic vector type.
Definition TypeBase.h:4173
unsigned getNumElements() const
Definition TypeBase.h:4188
QualType getElementType() const
Definition TypeBase.h:4187
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2697
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
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.
#define bool
Definition gpuintrin.h:32
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:216
@ 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:1282
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1267
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1260
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1274
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2502
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1228
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1289
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
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:815
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
Expr * IgnoreElidableImplicitConstructorSingleStep(Expr *E)
Definition IgnoreExpr.h:125
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
VariadicCallType
Definition Sema.h:510
bool hasSpecificAttr(const Container &container)
@ Arithmetic
An arithmetic operation.
Definition Sema.h:660
@ Comparison
A comparison.
Definition Sema.h:664
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
Expr * IgnoreExprNodes(Expr *E, FnTys &&... Fns)
Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *, Recursively apply each of the f...
Definition IgnoreExpr.h:34
@ 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:149
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
PointerAuthDiscArgKind
Definition Sema.h:591
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:124
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:257
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:545
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
const FunctionProtoType * T
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:561
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:496
CastKind
CastKind - The kind of operation required for a conversion.
BuiltinCountedByRefKind
Definition Sema.h:518
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
for(const auto &A :T->param_types())
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition IgnoreExpr.h:137
StringLiteralKind
Definition Expr.h:1763
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_Win64
Definition Specifiers.h:285
@ CC_X86_64SysV
Definition Specifiers.h:286
@ Generic
not a target-specific vector type
Definition TypeBase.h:4134
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5884
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5877
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1745
unsigned long uint64_t
long int64_t
#define false
Definition stdbool.h:26
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
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:633
Extra information about a function prototype.
Definition TypeBase.h:5349
unsigned AnonymousTagLocations
When printing an anonymous tag name, also print the location of that entity (e.g.,...
unsigned Indentation
The number of spaces to use to indent each line.
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13083
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13109
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13099
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13058
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6783
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2610
#define log2(__x)
Definition tgmath.h:970