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, bool AllowConst,
2272 bool AllowAS) {
2273 QualType MaskTy = MaskArg->getType();
2274 if (!MaskTy->isExtVectorBoolType())
2275 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2276 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2277 << MaskTy;
2278
2279 QualType PtrTy = PtrArg->getType();
2280 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2281 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2282 << Pos << "scalar pointer";
2283
2284 QualType PointeeTy = PtrTy->getPointeeType();
2285 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2286 (!AllowConst && PointeeTy.isConstQualified()) ||
2287 (!AllowAS && PointeeTy.hasAddressSpace())) {
2290 return S.Diag(PtrArg->getExprLoc(),
2291 diag::err_typecheck_convert_incompatible)
2292 << PtrTy << Target << /*different qualifiers=*/5
2293 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2294 << PtrTy << Target;
2295 }
2296 return false;
2297}
2298
2299static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2300 bool TypeDependent = false;
2301 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2302 ExprResult Converted =
2304 if (Converted.isInvalid())
2305 return true;
2306 TheCall->setArg(Arg, Converted.get());
2307 TypeDependent |= Converted.get()->isTypeDependent();
2308 }
2309
2310 if (TypeDependent)
2311 TheCall->setType(S.Context.DependentTy);
2312 return false;
2313}
2314
2316 if (S.checkArgCountRange(TheCall, 2, 3))
2317 return ExprError();
2318
2319 if (ConvertMaskedBuiltinArgs(S, TheCall))
2320 return ExprError();
2321
2322 Expr *MaskArg = TheCall->getArg(0);
2323 Expr *PtrArg = TheCall->getArg(1);
2324 if (TheCall->isTypeDependent())
2325 return TheCall;
2326
2327 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2328 TheCall->getBuiltinCallee() ==
2329 Builtin::BI__builtin_masked_load))
2330 return ExprError();
2331
2332 QualType MaskTy = MaskArg->getType();
2333 QualType PtrTy = PtrArg->getType();
2334 QualType PointeeTy = PtrTy->getPointeeType();
2335 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2336
2338 MaskVecTy->getNumElements());
2339 if (TheCall->getNumArgs() == 3) {
2340 Expr *PassThruArg = TheCall->getArg(2);
2341 QualType PassThruTy = PassThruArg->getType();
2342 if (!S.Context.hasSameType(PassThruTy, RetTy))
2343 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2344 << /* third argument */ 3 << RetTy;
2345 }
2346
2347 TheCall->setType(RetTy);
2348 return TheCall;
2349}
2350
2352 if (S.checkArgCount(TheCall, 3))
2353 return ExprError();
2354
2355 if (ConvertMaskedBuiltinArgs(S, TheCall))
2356 return ExprError();
2357
2358 Expr *MaskArg = TheCall->getArg(0);
2359 Expr *ValArg = TheCall->getArg(1);
2360 Expr *PtrArg = TheCall->getArg(2);
2361 if (TheCall->isTypeDependent())
2362 return TheCall;
2363
2364 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2365 TheCall->getBuiltinCallee() ==
2366 Builtin::BI__builtin_masked_store))
2367 return ExprError();
2368
2369 QualType MaskTy = MaskArg->getType();
2370 QualType PtrTy = PtrArg->getType();
2371 QualType ValTy = ValArg->getType();
2372 if (!ValTy->isVectorType())
2373 return ExprError(
2374 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2375 << 2 << "vector");
2376
2377 QualType PointeeTy = PtrTy->getPointeeType();
2378 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2379 QualType MemoryTy = S.Context.getExtVectorType(PointeeTy.getUnqualifiedType(),
2380 MaskVecTy->getNumElements());
2381 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(),
2382 MemoryTy.getUnqualifiedType()))
2383 return ExprError(S.Diag(TheCall->getBeginLoc(),
2384 diag::err_vec_builtin_incompatible_vector)
2385 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2386 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2387 TheCall->getArg(1)->getEndLoc()));
2388
2389 TheCall->setType(S.Context.VoidTy);
2390 return TheCall;
2391}
2392
2394 if (S.checkArgCountRange(TheCall, 3, 4))
2395 return ExprError();
2396
2397 if (ConvertMaskedBuiltinArgs(S, TheCall))
2398 return ExprError();
2399
2400 Expr *MaskArg = TheCall->getArg(0);
2401 Expr *IdxArg = TheCall->getArg(1);
2402 Expr *PtrArg = TheCall->getArg(2);
2403 if (TheCall->isTypeDependent())
2404 return TheCall;
2405
2406 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
2407 /*AllowAS=*/true))
2408 return ExprError();
2409
2410 QualType IdxTy = IdxArg->getType();
2411 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2412 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2413 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2414 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2415 << IdxTy;
2416
2417 QualType MaskTy = MaskArg->getType();
2418 QualType PtrTy = PtrArg->getType();
2419 QualType PointeeTy = PtrTy->getPointeeType();
2420 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2421 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2422 return ExprError(
2423 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2425 TheCall->getBuiltinCallee())
2426 << MaskTy << IdxTy);
2427
2429 MaskVecTy->getNumElements());
2430 if (TheCall->getNumArgs() == 4) {
2431 Expr *PassThruArg = TheCall->getArg(3);
2432 QualType PassThruTy = PassThruArg->getType();
2433 if (!S.Context.hasSameType(PassThruTy, RetTy))
2434 return S.Diag(PassThruArg->getExprLoc(),
2435 diag::err_vec_masked_load_store_ptr)
2436 << /* fourth argument */ 4 << RetTy;
2437 }
2438
2439 TheCall->setType(RetTy);
2440 return TheCall;
2441}
2442
2444 if (S.checkArgCount(TheCall, 4))
2445 return ExprError();
2446
2447 if (ConvertMaskedBuiltinArgs(S, TheCall))
2448 return ExprError();
2449
2450 Expr *MaskArg = TheCall->getArg(0);
2451 Expr *IdxArg = TheCall->getArg(1);
2452 Expr *ValArg = TheCall->getArg(2);
2453 Expr *PtrArg = TheCall->getArg(3);
2454 if (TheCall->isTypeDependent())
2455 return TheCall;
2456
2457 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
2458 /*AllowAS=*/true))
2459 return ExprError();
2460
2461 QualType IdxTy = IdxArg->getType();
2462 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2463 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2464 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2465 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2466 << IdxTy;
2467
2468 QualType ValTy = ValArg->getType();
2469 QualType MaskTy = MaskArg->getType();
2470 QualType PtrTy = PtrArg->getType();
2471 QualType PointeeTy = PtrTy->getPointeeType();
2472
2473 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2474 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2475 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2476 return ExprError(
2477 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2479 TheCall->getBuiltinCallee())
2480 << MaskTy << IdxTy);
2481 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2482 return ExprError(
2483 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2485 TheCall->getBuiltinCallee())
2486 << MaskTy << ValTy);
2487
2489 MaskVecTy->getNumElements());
2490 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(), ArgTy))
2491 return ExprError(S.Diag(TheCall->getBeginLoc(),
2492 diag::err_vec_builtin_incompatible_vector)
2493 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2494 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2495 TheCall->getArg(1)->getEndLoc()));
2496
2497 TheCall->setType(S.Context.VoidTy);
2498 return TheCall;
2499}
2500
2502 SourceLocation Loc = TheCall->getBeginLoc();
2503 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2504 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2505
2506 if (Args.size() == 0) {
2507 S.Diag(TheCall->getBeginLoc(),
2508 diag::err_typecheck_call_too_few_args_at_least)
2509 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2510 << /*is_non_object=*/0 << TheCall->getSourceRange();
2511 return ExprError();
2512 }
2513
2514 QualType FuncT = Args[0]->getType();
2515
2516 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2517 if (Args.size() < 2) {
2518 S.Diag(TheCall->getBeginLoc(),
2519 diag::err_typecheck_call_too_few_args_at_least)
2520 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2521 << /*is_non_object=*/0 << TheCall->getSourceRange();
2522 return ExprError();
2523 }
2524
2525 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2526 QualType ObjectT = Args[1]->getType();
2527
2528 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
2529 return ExprError();
2530
2531 ExprResult ObjectArg = [&]() -> ExprResult {
2532 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2533 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2534 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2535 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2536 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2537 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2538 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
2539 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
2540 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
2541 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
2542 return Args[1];
2543 }
2544
2545 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2546 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2547 // reference_wrapper;
2548 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2549 if (RD->isInStdNamespace() &&
2550 RD->getDeclName().getAsString() == "reference_wrapper") {
2551 CXXScopeSpec SS;
2552 IdentifierInfo *GetName = &S.Context.Idents.get("get");
2553 UnqualifiedId GetID;
2554 GetID.setIdentifier(GetName, Loc);
2555
2557 S.getCurScope(), Args[1], Loc, tok::period, SS,
2558 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
2559
2560 if (MemExpr.isInvalid())
2561 return ExprError();
2562
2563 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
2564 }
2565 }
2566
2567 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
2568 // class T and t1 does not satisfy the previous two items;
2569
2570 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
2571 }();
2572
2573 if (ObjectArg.isInvalid())
2574 return ExprError();
2575
2576 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
2577 tok::periodstar, ObjectArg.get(), Args[0]);
2578 if (BinOp.isInvalid())
2579 return ExprError();
2580
2581 if (MPT->isMemberDataPointer())
2582 return BinOp;
2583
2584 auto *MemCall = new (S.Context)
2586
2587 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
2588 Args.drop_front(2), TheCall->getRParenLoc());
2589 }
2590 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
2591 Args.drop_front(), TheCall->getRParenLoc());
2592}
2593
2595Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2596 CallExpr *TheCall) {
2597 ExprResult TheCallResult(TheCall);
2598
2599 // Find out if any arguments are required to be integer constant expressions.
2600 unsigned ICEArguments = 0;
2602 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2604 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2605
2606 // If any arguments are required to be ICE's, check and diagnose.
2607 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2608 // Skip arguments not required to be ICE's.
2609 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2610
2611 llvm::APSInt Result;
2612 // If we don't have enough arguments, continue so we can issue better
2613 // diagnostic in checkArgCount(...)
2614 if (ArgNo < TheCall->getNumArgs() &&
2615 BuiltinConstantArg(TheCall, ArgNo, Result))
2616 return true;
2617 ICEArguments &= ~(1 << ArgNo);
2618 }
2619
2620 FPOptions FPO;
2621 switch (BuiltinID) {
2622 case Builtin::BI__builtin_cpu_supports:
2623 case Builtin::BI__builtin_cpu_is:
2624 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2625 Context.getAuxTargetInfo(), BuiltinID))
2626 return ExprError();
2627 break;
2628 case Builtin::BI__builtin_cpu_init:
2629 if (!Context.getTargetInfo().supportsCpuInit()) {
2630 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2631 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2632 return ExprError();
2633 }
2634 break;
2635 case Builtin::BI__builtin___CFStringMakeConstantString:
2636 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2637 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2639 *this, BuiltinID, TheCall,
2640 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2641 return ExprError();
2642 assert(TheCall->getNumArgs() == 1 &&
2643 "Wrong # arguments to builtin CFStringMakeConstantString");
2644 if (ObjC().CheckObjCString(TheCall->getArg(0)))
2645 return ExprError();
2646 break;
2647 case Builtin::BI__builtin_ms_va_start:
2648 case Builtin::BI__builtin_stdarg_start:
2649 case Builtin::BI__builtin_va_start:
2650 case Builtin::BI__builtin_c23_va_start:
2651 if (BuiltinVAStart(BuiltinID, TheCall))
2652 return ExprError();
2653 break;
2654 case Builtin::BI__va_start: {
2655 switch (Context.getTargetInfo().getTriple().getArch()) {
2656 case llvm::Triple::aarch64:
2657 case llvm::Triple::arm:
2658 case llvm::Triple::thumb:
2659 if (BuiltinVAStartARMMicrosoft(TheCall))
2660 return ExprError();
2661 break;
2662 default:
2663 if (BuiltinVAStart(BuiltinID, TheCall))
2664 return ExprError();
2665 break;
2666 }
2667 break;
2668 }
2669
2670 // The acquire, release, and no fence variants are ARM and AArch64 only.
2671 case Builtin::BI_interlockedbittestandset_acq:
2672 case Builtin::BI_interlockedbittestandset_rel:
2673 case Builtin::BI_interlockedbittestandset_nf:
2674 case Builtin::BI_interlockedbittestandreset_acq:
2675 case Builtin::BI_interlockedbittestandreset_rel:
2676 case Builtin::BI_interlockedbittestandreset_nf:
2678 *this, TheCall,
2679 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2680 return ExprError();
2681 break;
2682
2683 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2684 case Builtin::BI_bittest64:
2685 case Builtin::BI_bittestandcomplement64:
2686 case Builtin::BI_bittestandreset64:
2687 case Builtin::BI_bittestandset64:
2688 case Builtin::BI_interlockedbittestandreset64:
2689 case Builtin::BI_interlockedbittestandset64:
2691 *this, TheCall,
2692 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2693 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2694 return ExprError();
2695 break;
2696
2697 // The 64-bit acquire, release, and no fence variants are AArch64 only.
2698 case Builtin::BI_interlockedbittestandreset64_acq:
2699 case Builtin::BI_interlockedbittestandreset64_rel:
2700 case Builtin::BI_interlockedbittestandreset64_nf:
2701 case Builtin::BI_interlockedbittestandset64_acq:
2702 case Builtin::BI_interlockedbittestandset64_rel:
2703 case Builtin::BI_interlockedbittestandset64_nf:
2704 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
2705 return ExprError();
2706 break;
2707
2708 case Builtin::BI__builtin_set_flt_rounds:
2710 *this, TheCall,
2711 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
2712 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
2713 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
2714 llvm::Triple::ppc64le}))
2715 return ExprError();
2716 break;
2717
2718 case Builtin::BI__builtin_isgreater:
2719 case Builtin::BI__builtin_isgreaterequal:
2720 case Builtin::BI__builtin_isless:
2721 case Builtin::BI__builtin_islessequal:
2722 case Builtin::BI__builtin_islessgreater:
2723 case Builtin::BI__builtin_isunordered:
2724 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2725 return ExprError();
2726 break;
2727 case Builtin::BI__builtin_fpclassify:
2728 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
2729 return ExprError();
2730 break;
2731 case Builtin::BI__builtin_isfpclass:
2732 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
2733 return ExprError();
2734 break;
2735 case Builtin::BI__builtin_isfinite:
2736 case Builtin::BI__builtin_isinf:
2737 case Builtin::BI__builtin_isinf_sign:
2738 case Builtin::BI__builtin_isnan:
2739 case Builtin::BI__builtin_issignaling:
2740 case Builtin::BI__builtin_isnormal:
2741 case Builtin::BI__builtin_issubnormal:
2742 case Builtin::BI__builtin_iszero:
2743 case Builtin::BI__builtin_signbit:
2744 case Builtin::BI__builtin_signbitf:
2745 case Builtin::BI__builtin_signbitl:
2746 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
2747 return ExprError();
2748 break;
2749 case Builtin::BI__builtin_shufflevector:
2750 return BuiltinShuffleVector(TheCall);
2751 // TheCall will be freed by the smart pointer here, but that's fine, since
2752 // BuiltinShuffleVector guts it, but then doesn't release it.
2753 case Builtin::BI__builtin_masked_load:
2754 case Builtin::BI__builtin_masked_expand_load:
2755 return BuiltinMaskedLoad(*this, TheCall);
2756 case Builtin::BI__builtin_masked_store:
2757 case Builtin::BI__builtin_masked_compress_store:
2758 return BuiltinMaskedStore(*this, TheCall);
2759 case Builtin::BI__builtin_masked_gather:
2760 return BuiltinMaskedGather(*this, TheCall);
2761 case Builtin::BI__builtin_masked_scatter:
2762 return BuiltinMaskedScatter(*this, TheCall);
2763 case Builtin::BI__builtin_invoke:
2764 return BuiltinInvoke(*this, TheCall);
2765 case Builtin::BI__builtin_prefetch:
2766 if (BuiltinPrefetch(TheCall))
2767 return ExprError();
2768 break;
2769 case Builtin::BI__builtin_alloca_with_align:
2770 case Builtin::BI__builtin_alloca_with_align_uninitialized:
2771 if (BuiltinAllocaWithAlign(TheCall))
2772 return ExprError();
2773 [[fallthrough]];
2774 case Builtin::BI__builtin_alloca:
2775 case Builtin::BI__builtin_alloca_uninitialized:
2776 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
2777 << TheCall->getDirectCallee();
2778 if (getLangOpts().OpenCL) {
2779 builtinAllocaAddrSpace(*this, TheCall);
2780 }
2781 break;
2782 case Builtin::BI__arithmetic_fence:
2783 if (BuiltinArithmeticFence(TheCall))
2784 return ExprError();
2785 break;
2786 case Builtin::BI__assume:
2787 case Builtin::BI__builtin_assume:
2788 if (BuiltinAssume(TheCall))
2789 return ExprError();
2790 break;
2791 case Builtin::BI__builtin_assume_aligned:
2792 if (BuiltinAssumeAligned(TheCall))
2793 return ExprError();
2794 break;
2795 case Builtin::BI__builtin_dynamic_object_size:
2796 case Builtin::BI__builtin_object_size:
2797 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
2798 return ExprError();
2799 break;
2800 case Builtin::BI__builtin_longjmp:
2801 if (BuiltinLongjmp(TheCall))
2802 return ExprError();
2803 break;
2804 case Builtin::BI__builtin_setjmp:
2805 if (BuiltinSetjmp(TheCall))
2806 return ExprError();
2807 break;
2808 case Builtin::BI__builtin_classify_type:
2809 if (checkArgCount(TheCall, 1))
2810 return true;
2811 TheCall->setType(Context.IntTy);
2812 break;
2813 case Builtin::BI__builtin_complex:
2814 if (BuiltinComplex(TheCall))
2815 return ExprError();
2816 break;
2817 case Builtin::BI__builtin_constant_p: {
2818 if (checkArgCount(TheCall, 1))
2819 return true;
2821 if (Arg.isInvalid()) return true;
2822 TheCall->setArg(0, Arg.get());
2823 TheCall->setType(Context.IntTy);
2824 break;
2825 }
2826 case Builtin::BI__builtin_launder:
2827 return BuiltinLaunder(*this, TheCall);
2828 case Builtin::BI__builtin_is_within_lifetime:
2829 return BuiltinIsWithinLifetime(*this, TheCall);
2830 case Builtin::BI__builtin_trivially_relocate:
2831 return BuiltinTriviallyRelocate(*this, TheCall);
2832
2833 case Builtin::BI__sync_fetch_and_add:
2834 case Builtin::BI__sync_fetch_and_add_1:
2835 case Builtin::BI__sync_fetch_and_add_2:
2836 case Builtin::BI__sync_fetch_and_add_4:
2837 case Builtin::BI__sync_fetch_and_add_8:
2838 case Builtin::BI__sync_fetch_and_add_16:
2839 case Builtin::BI__sync_fetch_and_sub:
2840 case Builtin::BI__sync_fetch_and_sub_1:
2841 case Builtin::BI__sync_fetch_and_sub_2:
2842 case Builtin::BI__sync_fetch_and_sub_4:
2843 case Builtin::BI__sync_fetch_and_sub_8:
2844 case Builtin::BI__sync_fetch_and_sub_16:
2845 case Builtin::BI__sync_fetch_and_or:
2846 case Builtin::BI__sync_fetch_and_or_1:
2847 case Builtin::BI__sync_fetch_and_or_2:
2848 case Builtin::BI__sync_fetch_and_or_4:
2849 case Builtin::BI__sync_fetch_and_or_8:
2850 case Builtin::BI__sync_fetch_and_or_16:
2851 case Builtin::BI__sync_fetch_and_and:
2852 case Builtin::BI__sync_fetch_and_and_1:
2853 case Builtin::BI__sync_fetch_and_and_2:
2854 case Builtin::BI__sync_fetch_and_and_4:
2855 case Builtin::BI__sync_fetch_and_and_8:
2856 case Builtin::BI__sync_fetch_and_and_16:
2857 case Builtin::BI__sync_fetch_and_xor:
2858 case Builtin::BI__sync_fetch_and_xor_1:
2859 case Builtin::BI__sync_fetch_and_xor_2:
2860 case Builtin::BI__sync_fetch_and_xor_4:
2861 case Builtin::BI__sync_fetch_and_xor_8:
2862 case Builtin::BI__sync_fetch_and_xor_16:
2863 case Builtin::BI__sync_fetch_and_nand:
2864 case Builtin::BI__sync_fetch_and_nand_1:
2865 case Builtin::BI__sync_fetch_and_nand_2:
2866 case Builtin::BI__sync_fetch_and_nand_4:
2867 case Builtin::BI__sync_fetch_and_nand_8:
2868 case Builtin::BI__sync_fetch_and_nand_16:
2869 case Builtin::BI__sync_add_and_fetch:
2870 case Builtin::BI__sync_add_and_fetch_1:
2871 case Builtin::BI__sync_add_and_fetch_2:
2872 case Builtin::BI__sync_add_and_fetch_4:
2873 case Builtin::BI__sync_add_and_fetch_8:
2874 case Builtin::BI__sync_add_and_fetch_16:
2875 case Builtin::BI__sync_sub_and_fetch:
2876 case Builtin::BI__sync_sub_and_fetch_1:
2877 case Builtin::BI__sync_sub_and_fetch_2:
2878 case Builtin::BI__sync_sub_and_fetch_4:
2879 case Builtin::BI__sync_sub_and_fetch_8:
2880 case Builtin::BI__sync_sub_and_fetch_16:
2881 case Builtin::BI__sync_and_and_fetch:
2882 case Builtin::BI__sync_and_and_fetch_1:
2883 case Builtin::BI__sync_and_and_fetch_2:
2884 case Builtin::BI__sync_and_and_fetch_4:
2885 case Builtin::BI__sync_and_and_fetch_8:
2886 case Builtin::BI__sync_and_and_fetch_16:
2887 case Builtin::BI__sync_or_and_fetch:
2888 case Builtin::BI__sync_or_and_fetch_1:
2889 case Builtin::BI__sync_or_and_fetch_2:
2890 case Builtin::BI__sync_or_and_fetch_4:
2891 case Builtin::BI__sync_or_and_fetch_8:
2892 case Builtin::BI__sync_or_and_fetch_16:
2893 case Builtin::BI__sync_xor_and_fetch:
2894 case Builtin::BI__sync_xor_and_fetch_1:
2895 case Builtin::BI__sync_xor_and_fetch_2:
2896 case Builtin::BI__sync_xor_and_fetch_4:
2897 case Builtin::BI__sync_xor_and_fetch_8:
2898 case Builtin::BI__sync_xor_and_fetch_16:
2899 case Builtin::BI__sync_nand_and_fetch:
2900 case Builtin::BI__sync_nand_and_fetch_1:
2901 case Builtin::BI__sync_nand_and_fetch_2:
2902 case Builtin::BI__sync_nand_and_fetch_4:
2903 case Builtin::BI__sync_nand_and_fetch_8:
2904 case Builtin::BI__sync_nand_and_fetch_16:
2905 case Builtin::BI__sync_val_compare_and_swap:
2906 case Builtin::BI__sync_val_compare_and_swap_1:
2907 case Builtin::BI__sync_val_compare_and_swap_2:
2908 case Builtin::BI__sync_val_compare_and_swap_4:
2909 case Builtin::BI__sync_val_compare_and_swap_8:
2910 case Builtin::BI__sync_val_compare_and_swap_16:
2911 case Builtin::BI__sync_bool_compare_and_swap:
2912 case Builtin::BI__sync_bool_compare_and_swap_1:
2913 case Builtin::BI__sync_bool_compare_and_swap_2:
2914 case Builtin::BI__sync_bool_compare_and_swap_4:
2915 case Builtin::BI__sync_bool_compare_and_swap_8:
2916 case Builtin::BI__sync_bool_compare_and_swap_16:
2917 case Builtin::BI__sync_lock_test_and_set:
2918 case Builtin::BI__sync_lock_test_and_set_1:
2919 case Builtin::BI__sync_lock_test_and_set_2:
2920 case Builtin::BI__sync_lock_test_and_set_4:
2921 case Builtin::BI__sync_lock_test_and_set_8:
2922 case Builtin::BI__sync_lock_test_and_set_16:
2923 case Builtin::BI__sync_lock_release:
2924 case Builtin::BI__sync_lock_release_1:
2925 case Builtin::BI__sync_lock_release_2:
2926 case Builtin::BI__sync_lock_release_4:
2927 case Builtin::BI__sync_lock_release_8:
2928 case Builtin::BI__sync_lock_release_16:
2929 case Builtin::BI__sync_swap:
2930 case Builtin::BI__sync_swap_1:
2931 case Builtin::BI__sync_swap_2:
2932 case Builtin::BI__sync_swap_4:
2933 case Builtin::BI__sync_swap_8:
2934 case Builtin::BI__sync_swap_16:
2935 return BuiltinAtomicOverloaded(TheCallResult);
2936 case Builtin::BI__sync_synchronize:
2937 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
2938 << TheCall->getCallee()->getSourceRange();
2939 break;
2940 case Builtin::BI__builtin_nontemporal_load:
2941 case Builtin::BI__builtin_nontemporal_store:
2942 return BuiltinNontemporalOverloaded(TheCallResult);
2943 case Builtin::BI__builtin_memcpy_inline: {
2944 clang::Expr *SizeOp = TheCall->getArg(2);
2945 // We warn about copying to or from `nullptr` pointers when `size` is
2946 // greater than 0. When `size` is value dependent we cannot evaluate its
2947 // value so we bail out.
2948 if (SizeOp->isValueDependent())
2949 break;
2950 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
2951 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2952 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
2953 }
2954 break;
2955 }
2956 case Builtin::BI__builtin_memset_inline: {
2957 clang::Expr *SizeOp = TheCall->getArg(2);
2958 // We warn about filling to `nullptr` pointers when `size` is greater than
2959 // 0. When `size` is value dependent we cannot evaluate its value so we bail
2960 // out.
2961 if (SizeOp->isValueDependent())
2962 break;
2963 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
2964 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2965 break;
2966 }
2967#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
2968 case Builtin::BI##ID: \
2969 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
2970#include "clang/Basic/Builtins.inc"
2971 case Builtin::BI__annotation:
2972 if (BuiltinMSVCAnnotation(*this, TheCall))
2973 return ExprError();
2974 break;
2975 case Builtin::BI__builtin_annotation:
2976 if (BuiltinAnnotation(*this, TheCall))
2977 return ExprError();
2978 break;
2979 case Builtin::BI__builtin_addressof:
2980 if (BuiltinAddressof(*this, TheCall))
2981 return ExprError();
2982 break;
2983 case Builtin::BI__builtin_function_start:
2984 if (BuiltinFunctionStart(*this, TheCall))
2985 return ExprError();
2986 break;
2987 case Builtin::BI__builtin_is_aligned:
2988 case Builtin::BI__builtin_align_up:
2989 case Builtin::BI__builtin_align_down:
2990 if (BuiltinAlignment(*this, TheCall, BuiltinID))
2991 return ExprError();
2992 break;
2993 case Builtin::BI__builtin_add_overflow:
2994 case Builtin::BI__builtin_sub_overflow:
2995 case Builtin::BI__builtin_mul_overflow:
2996 if (BuiltinOverflow(*this, TheCall, BuiltinID))
2997 return ExprError();
2998 break;
2999 case Builtin::BI__builtin_operator_new:
3000 case Builtin::BI__builtin_operator_delete: {
3001 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3002 ExprResult Res =
3003 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3004 return Res;
3005 }
3006 case Builtin::BI__builtin_dump_struct:
3007 return BuiltinDumpStruct(*this, TheCall);
3008 case Builtin::BI__builtin_expect_with_probability: {
3009 // We first want to ensure we are called with 3 arguments
3010 if (checkArgCount(TheCall, 3))
3011 return ExprError();
3012 // then check probability is constant float in range [0.0, 1.0]
3013 const Expr *ProbArg = TheCall->getArg(2);
3014 SmallVector<PartialDiagnosticAt, 8> Notes;
3015 Expr::EvalResult Eval;
3016 Eval.Diag = &Notes;
3017 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3018 !Eval.Val.isFloat()) {
3019 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3020 << ProbArg->getSourceRange();
3021 for (const PartialDiagnosticAt &PDiag : Notes)
3022 Diag(PDiag.first, PDiag.second);
3023 return ExprError();
3024 }
3025 llvm::APFloat Probability = Eval.Val.getFloat();
3026 bool LoseInfo = false;
3027 Probability.convert(llvm::APFloat::IEEEdouble(),
3028 llvm::RoundingMode::Dynamic, &LoseInfo);
3029 if (!(Probability >= llvm::APFloat(0.0) &&
3030 Probability <= llvm::APFloat(1.0))) {
3031 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3032 << ProbArg->getSourceRange();
3033 return ExprError();
3034 }
3035 break;
3036 }
3037 case Builtin::BI__builtin_preserve_access_index:
3038 if (BuiltinPreserveAI(*this, TheCall))
3039 return ExprError();
3040 break;
3041 case Builtin::BI__builtin_call_with_static_chain:
3042 if (BuiltinCallWithStaticChain(*this, TheCall))
3043 return ExprError();
3044 break;
3045 case Builtin::BI__exception_code:
3046 case Builtin::BI_exception_code:
3047 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3048 diag::err_seh___except_block))
3049 return ExprError();
3050 break;
3051 case Builtin::BI__exception_info:
3052 case Builtin::BI_exception_info:
3053 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3054 diag::err_seh___except_filter))
3055 return ExprError();
3056 break;
3057 case Builtin::BI__GetExceptionInfo:
3058 if (checkArgCount(TheCall, 1))
3059 return ExprError();
3060
3062 TheCall->getBeginLoc(),
3063 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3064 TheCall))
3065 return ExprError();
3066
3067 TheCall->setType(Context.VoidPtrTy);
3068 break;
3069 case Builtin::BIaddressof:
3070 case Builtin::BI__addressof:
3071 case Builtin::BIforward:
3072 case Builtin::BIforward_like:
3073 case Builtin::BImove:
3074 case Builtin::BImove_if_noexcept:
3075 case Builtin::BIas_const: {
3076 // These are all expected to be of the form
3077 // T &/&&/* f(U &/&&)
3078 // where T and U only differ in qualification.
3079 if (checkArgCount(TheCall, 1))
3080 return ExprError();
3081 QualType Param = FDecl->getParamDecl(0)->getType();
3082 QualType Result = FDecl->getReturnType();
3083 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3084 BuiltinID == Builtin::BI__addressof;
3085 if (!(Param->isReferenceType() &&
3086 (ReturnsPointer ? Result->isAnyPointerType()
3087 : Result->isReferenceType()) &&
3088 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3089 Result->getPointeeType()))) {
3090 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3091 << FDecl;
3092 return ExprError();
3093 }
3094 break;
3095 }
3096 case Builtin::BI__builtin_ptrauth_strip:
3097 return PointerAuthStrip(*this, TheCall);
3098 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3099 return PointerAuthBlendDiscriminator(*this, TheCall);
3100 case Builtin::BI__builtin_ptrauth_sign_constant:
3101 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3102 /*RequireConstant=*/true);
3103 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3104 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3105 /*RequireConstant=*/false);
3106 case Builtin::BI__builtin_ptrauth_auth:
3107 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3108 /*RequireConstant=*/false);
3109 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3110 return PointerAuthSignGenericData(*this, TheCall);
3111 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3112 return PointerAuthAuthAndResign(*this, TheCall);
3113 case Builtin::BI__builtin_ptrauth_string_discriminator:
3114 return PointerAuthStringDiscriminator(*this, TheCall);
3115
3116 case Builtin::BI__builtin_get_vtable_pointer:
3117 return GetVTablePointer(*this, TheCall);
3118
3119 // OpenCL v2.0, s6.13.16 - Pipe functions
3120 case Builtin::BIread_pipe:
3121 case Builtin::BIwrite_pipe:
3122 // Since those two functions are declared with var args, we need a semantic
3123 // check for the argument.
3124 if (OpenCL().checkBuiltinRWPipe(TheCall))
3125 return ExprError();
3126 break;
3127 case Builtin::BIreserve_read_pipe:
3128 case Builtin::BIreserve_write_pipe:
3129 case Builtin::BIwork_group_reserve_read_pipe:
3130 case Builtin::BIwork_group_reserve_write_pipe:
3131 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3132 return ExprError();
3133 break;
3134 case Builtin::BIsub_group_reserve_read_pipe:
3135 case Builtin::BIsub_group_reserve_write_pipe:
3136 if (OpenCL().checkSubgroupExt(TheCall) ||
3137 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3138 return ExprError();
3139 break;
3140 case Builtin::BIcommit_read_pipe:
3141 case Builtin::BIcommit_write_pipe:
3142 case Builtin::BIwork_group_commit_read_pipe:
3143 case Builtin::BIwork_group_commit_write_pipe:
3144 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3145 return ExprError();
3146 break;
3147 case Builtin::BIsub_group_commit_read_pipe:
3148 case Builtin::BIsub_group_commit_write_pipe:
3149 if (OpenCL().checkSubgroupExt(TheCall) ||
3150 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3151 return ExprError();
3152 break;
3153 case Builtin::BIget_pipe_num_packets:
3154 case Builtin::BIget_pipe_max_packets:
3155 if (OpenCL().checkBuiltinPipePackets(TheCall))
3156 return ExprError();
3157 break;
3158 case Builtin::BIto_global:
3159 case Builtin::BIto_local:
3160 case Builtin::BIto_private:
3161 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3162 return ExprError();
3163 break;
3164 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3165 case Builtin::BIenqueue_kernel:
3166 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3167 return ExprError();
3168 break;
3169 case Builtin::BIget_kernel_work_group_size:
3170 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3171 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3172 return ExprError();
3173 break;
3174 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3175 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3176 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3177 return ExprError();
3178 break;
3179 case Builtin::BI__builtin_os_log_format:
3180 Cleanup.setExprNeedsCleanups(true);
3181 [[fallthrough]];
3182 case Builtin::BI__builtin_os_log_format_buffer_size:
3183 if (BuiltinOSLogFormat(TheCall))
3184 return ExprError();
3185 break;
3186 case Builtin::BI__builtin_frame_address:
3187 case Builtin::BI__builtin_return_address: {
3188 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3189 return ExprError();
3190
3191 // -Wframe-address warning if non-zero passed to builtin
3192 // return/frame address.
3193 Expr::EvalResult Result;
3194 if (!TheCall->getArg(0)->isValueDependent() &&
3195 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3196 Result.Val.getInt() != 0)
3197 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3198 << ((BuiltinID == Builtin::BI__builtin_return_address)
3199 ? "__builtin_return_address"
3200 : "__builtin_frame_address")
3201 << TheCall->getSourceRange();
3202 break;
3203 }
3204
3205 case Builtin::BI__builtin_nondeterministic_value: {
3206 if (BuiltinNonDeterministicValue(TheCall))
3207 return ExprError();
3208 break;
3209 }
3210
3211 // __builtin_elementwise_abs restricts the element type to signed integers or
3212 // floating point types only.
3213 case Builtin::BI__builtin_elementwise_abs:
3216 return ExprError();
3217 break;
3218
3219 // These builtins restrict the element type to floating point
3220 // types only.
3221 case Builtin::BI__builtin_elementwise_acos:
3222 case Builtin::BI__builtin_elementwise_asin:
3223 case Builtin::BI__builtin_elementwise_atan:
3224 case Builtin::BI__builtin_elementwise_ceil:
3225 case Builtin::BI__builtin_elementwise_cos:
3226 case Builtin::BI__builtin_elementwise_cosh:
3227 case Builtin::BI__builtin_elementwise_exp:
3228 case Builtin::BI__builtin_elementwise_exp2:
3229 case Builtin::BI__builtin_elementwise_exp10:
3230 case Builtin::BI__builtin_elementwise_floor:
3231 case Builtin::BI__builtin_elementwise_log:
3232 case Builtin::BI__builtin_elementwise_log2:
3233 case Builtin::BI__builtin_elementwise_log10:
3234 case Builtin::BI__builtin_elementwise_roundeven:
3235 case Builtin::BI__builtin_elementwise_round:
3236 case Builtin::BI__builtin_elementwise_rint:
3237 case Builtin::BI__builtin_elementwise_nearbyint:
3238 case Builtin::BI__builtin_elementwise_sin:
3239 case Builtin::BI__builtin_elementwise_sinh:
3240 case Builtin::BI__builtin_elementwise_sqrt:
3241 case Builtin::BI__builtin_elementwise_tan:
3242 case Builtin::BI__builtin_elementwise_tanh:
3243 case Builtin::BI__builtin_elementwise_trunc:
3244 case Builtin::BI__builtin_elementwise_canonicalize:
3247 return ExprError();
3248 break;
3249 case Builtin::BI__builtin_elementwise_fma:
3250 if (BuiltinElementwiseTernaryMath(TheCall))
3251 return ExprError();
3252 break;
3253
3254 // These builtins restrict the element type to floating point
3255 // types only, and take in two arguments.
3256 case Builtin::BI__builtin_elementwise_minnum:
3257 case Builtin::BI__builtin_elementwise_maxnum:
3258 case Builtin::BI__builtin_elementwise_minimum:
3259 case Builtin::BI__builtin_elementwise_maximum:
3260 case Builtin::BI__builtin_elementwise_minimumnum:
3261 case Builtin::BI__builtin_elementwise_maximumnum:
3262 case Builtin::BI__builtin_elementwise_atan2:
3263 case Builtin::BI__builtin_elementwise_fmod:
3264 case Builtin::BI__builtin_elementwise_pow:
3265 if (BuiltinElementwiseMath(TheCall,
3267 return ExprError();
3268 break;
3269 // These builtins restrict the element type to integer
3270 // types only.
3271 case Builtin::BI__builtin_elementwise_add_sat:
3272 case Builtin::BI__builtin_elementwise_sub_sat:
3273 if (BuiltinElementwiseMath(TheCall,
3275 return ExprError();
3276 break;
3277 case Builtin::BI__builtin_elementwise_fshl:
3278 case Builtin::BI__builtin_elementwise_fshr:
3281 return ExprError();
3282 break;
3283 case Builtin::BI__builtin_elementwise_min:
3284 case Builtin::BI__builtin_elementwise_max:
3285 if (BuiltinElementwiseMath(TheCall))
3286 return ExprError();
3287 break;
3288 case Builtin::BI__builtin_elementwise_popcount:
3289 case Builtin::BI__builtin_elementwise_bitreverse:
3292 return ExprError();
3293 break;
3294 case Builtin::BI__builtin_elementwise_copysign: {
3295 if (checkArgCount(TheCall, 2))
3296 return ExprError();
3297
3298 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3299 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3300 if (Magnitude.isInvalid() || Sign.isInvalid())
3301 return ExprError();
3302
3303 QualType MagnitudeTy = Magnitude.get()->getType();
3304 QualType SignTy = Sign.get()->getType();
3306 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
3309 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
3311 return ExprError();
3312 }
3313
3314 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3315 return Diag(Sign.get()->getBeginLoc(),
3316 diag::err_typecheck_call_different_arg_types)
3317 << MagnitudeTy << SignTy;
3318 }
3319
3320 TheCall->setArg(0, Magnitude.get());
3321 TheCall->setArg(1, Sign.get());
3322 TheCall->setType(Magnitude.get()->getType());
3323 break;
3324 }
3325 case Builtin::BI__builtin_elementwise_clzg:
3326 case Builtin::BI__builtin_elementwise_ctzg:
3327 // These builtins can be unary or binary. Note for empty calls we call the
3328 // unary checker in order to not emit an error that says the function
3329 // expects 2 arguments, which would be misleading.
3330 if (TheCall->getNumArgs() <= 1) {
3333 return ExprError();
3334 } else if (BuiltinElementwiseMath(
3336 return ExprError();
3337 break;
3338 case Builtin::BI__builtin_reduce_max:
3339 case Builtin::BI__builtin_reduce_min: {
3340 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3341 return ExprError();
3342
3343 const Expr *Arg = TheCall->getArg(0);
3344 const auto *TyA = Arg->getType()->getAs<VectorType>();
3345
3346 QualType ElTy;
3347 if (TyA)
3348 ElTy = TyA->getElementType();
3349 else if (Arg->getType()->isSizelessVectorType())
3351
3352 if (ElTy.isNull()) {
3353 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3354 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3355 << Arg->getType();
3356 return ExprError();
3357 }
3358
3359 TheCall->setType(ElTy);
3360 break;
3361 }
3362 case Builtin::BI__builtin_reduce_maximum:
3363 case Builtin::BI__builtin_reduce_minimum: {
3364 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3365 return ExprError();
3366
3367 const Expr *Arg = TheCall->getArg(0);
3368 const auto *TyA = Arg->getType()->getAs<VectorType>();
3369
3370 QualType ElTy;
3371 if (TyA)
3372 ElTy = TyA->getElementType();
3373 else if (Arg->getType()->isSizelessVectorType())
3375
3376 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3377 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3378 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3379 << Arg->getType();
3380 return ExprError();
3381 }
3382
3383 TheCall->setType(ElTy);
3384 break;
3385 }
3386
3387 // These builtins support vectors of integers only.
3388 // TODO: ADD/MUL should support floating-point types.
3389 case Builtin::BI__builtin_reduce_add:
3390 case Builtin::BI__builtin_reduce_mul:
3391 case Builtin::BI__builtin_reduce_xor:
3392 case Builtin::BI__builtin_reduce_or:
3393 case Builtin::BI__builtin_reduce_and: {
3394 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3395 return ExprError();
3396
3397 const Expr *Arg = TheCall->getArg(0);
3398 const auto *TyA = Arg->getType()->getAs<VectorType>();
3399
3400 QualType ElTy;
3401 if (TyA)
3402 ElTy = TyA->getElementType();
3403 else if (Arg->getType()->isSizelessVectorType())
3405
3406 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3407 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3408 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3409 << Arg->getType();
3410 return ExprError();
3411 }
3412
3413 TheCall->setType(ElTy);
3414 break;
3415 }
3416
3417 case Builtin::BI__builtin_matrix_transpose:
3418 return BuiltinMatrixTranspose(TheCall, TheCallResult);
3419
3420 case Builtin::BI__builtin_matrix_column_major_load:
3421 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
3422
3423 case Builtin::BI__builtin_matrix_column_major_store:
3424 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
3425
3426 case Builtin::BI__builtin_verbose_trap:
3427 if (!checkBuiltinVerboseTrap(TheCall, *this))
3428 return ExprError();
3429 break;
3430
3431 case Builtin::BI__builtin_get_device_side_mangled_name: {
3432 auto Check = [](CallExpr *TheCall) {
3433 if (TheCall->getNumArgs() != 1)
3434 return false;
3435 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
3436 if (!DRE)
3437 return false;
3438 auto *D = DRE->getDecl();
3439 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
3440 return false;
3441 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3442 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3443 };
3444 if (!Check(TheCall)) {
3445 Diag(TheCall->getBeginLoc(),
3446 diag::err_hip_invalid_args_builtin_mangled_name);
3447 return ExprError();
3448 }
3449 break;
3450 }
3451 case Builtin::BI__builtin_popcountg:
3452 if (BuiltinPopcountg(*this, TheCall))
3453 return ExprError();
3454 break;
3455 case Builtin::BI__builtin_clzg:
3456 case Builtin::BI__builtin_ctzg:
3457 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
3458 return ExprError();
3459 break;
3460
3461 case Builtin::BI__builtin_allow_runtime_check: {
3462 Expr *Arg = TheCall->getArg(0);
3463 // Check if the argument is a string literal.
3465 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3466 << Arg->getSourceRange();
3467 return ExprError();
3468 }
3469 break;
3470 }
3471 case Builtin::BI__builtin_counted_by_ref:
3472 if (BuiltinCountedByRef(TheCall))
3473 return ExprError();
3474 break;
3475 }
3476
3477 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
3478 return ExprError();
3479
3480 // Since the target specific builtins for each arch overlap, only check those
3481 // of the arch we are compiling for.
3482 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
3483 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
3484 assert(Context.getAuxTargetInfo() &&
3485 "Aux Target Builtin, but not an aux target?");
3486
3487 if (CheckTSBuiltinFunctionCall(
3488 *Context.getAuxTargetInfo(),
3489 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
3490 return ExprError();
3491 } else {
3492 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
3493 TheCall))
3494 return ExprError();
3495 }
3496 }
3497
3498 return TheCallResult;
3499}
3500
3501bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3502 llvm::APSInt Result;
3503 // We can't check the value of a dependent argument.
3504 Expr *Arg = TheCall->getArg(ArgNum);
3505 if (Arg->isTypeDependent() || Arg->isValueDependent())
3506 return false;
3507
3508 // Check constant-ness first.
3509 if (BuiltinConstantArg(TheCall, ArgNum, Result))
3510 return true;
3511
3512 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3513 if (Result.isShiftedMask() || (~Result).isShiftedMask())
3514 return false;
3515
3516 return Diag(TheCall->getBeginLoc(),
3517 diag::err_argument_not_contiguous_bit_field)
3518 << ArgNum << Arg->getSourceRange();
3519}
3520
3521bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
3522 unsigned FirstArg, FormatStringInfo *FSI) {
3523 bool IsCXXMember = false;
3524 if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
3525 IsCXXMember = MD->isInstance();
3526 bool IsVariadic = false;
3527 if (const FunctionType *FnTy = D->getFunctionType())
3528 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
3529 else if (const auto *BD = dyn_cast<BlockDecl>(D))
3530 IsVariadic = BD->isVariadic();
3531 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
3532 IsVariadic = OMD->isVariadic();
3533
3534 return getFormatStringInfo(FormatIdx, FirstArg, IsCXXMember, IsVariadic, FSI);
3535}
3536
3537bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
3538 bool IsCXXMember, bool IsVariadic,
3539 FormatStringInfo *FSI) {
3540 if (FirstArg == 0)
3542 else if (IsVariadic)
3544 else
3546 FSI->FormatIdx = FormatIdx - 1;
3547 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
3548
3549 // The way the format attribute works in GCC, the implicit this argument
3550 // of member functions is counted. However, it doesn't appear in our own
3551 // lists, so decrement format_idx in that case.
3552 if (IsCXXMember) {
3553 if(FSI->FormatIdx == 0)
3554 return false;
3555 --FSI->FormatIdx;
3556 if (FSI->FirstDataArg != 0)
3557 --FSI->FirstDataArg;
3558 }
3559 return true;
3560}
3561
3562/// Checks if a the given expression evaluates to null.
3563///
3564/// Returns true if the value evaluates to null.
3565static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3566 // Treat (smart) pointers constructed from nullptr as null, whether we can
3567 // const-evaluate them or not.
3568 // This must happen first: the smart pointer expr might have _Nonnull type!
3572 return true;
3573
3574 // If the expression has non-null type, it doesn't evaluate to null.
3575 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
3576 if (*nullability == NullabilityKind::NonNull)
3577 return false;
3578 }
3579
3580 // As a special case, transparent unions initialized with zero are
3581 // considered null for the purposes of the nonnull attribute.
3582 if (const RecordType *UT = Expr->getType()->getAsUnionType();
3583 UT && UT->getOriginalDecl()
3584 ->getMostRecentDecl()
3585 ->hasAttr<TransparentUnionAttr>()) {
3586 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
3587 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
3588 Expr = ILE->getInit(0);
3589 }
3590
3591 bool Result;
3592 return (!Expr->isValueDependent() &&
3594 !Result);
3595}
3596
3598 const Expr *ArgExpr,
3599 SourceLocation CallSiteLoc) {
3600 if (CheckNonNullExpr(S, ArgExpr))
3601 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3602 S.PDiag(diag::warn_null_arg)
3603 << ArgExpr->getSourceRange());
3604}
3605
3606/// Determine whether the given type has a non-null nullability annotation.
3608 if (auto nullability = type->getNullability())
3609 return *nullability == NullabilityKind::NonNull;
3610
3611 return false;
3612}
3613
3615 const NamedDecl *FDecl,
3616 const FunctionProtoType *Proto,
3618 SourceLocation CallSiteLoc) {
3619 assert((FDecl || Proto) && "Need a function declaration or prototype");
3620
3621 // Already checked by constant evaluator.
3623 return;
3624 // Check the attributes attached to the method/function itself.
3625 llvm::SmallBitVector NonNullArgs;
3626 if (FDecl) {
3627 // Handle the nonnull attribute on the function/method declaration itself.
3628 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3629 if (!NonNull->args_size()) {
3630 // Easy case: all pointer arguments are nonnull.
3631 for (const auto *Arg : Args)
3632 if (S.isValidPointerAttrType(Arg->getType()))
3633 CheckNonNullArgument(S, Arg, CallSiteLoc);
3634 return;
3635 }
3636
3637 for (const ParamIdx &Idx : NonNull->args()) {
3638 unsigned IdxAST = Idx.getASTIndex();
3639 if (IdxAST >= Args.size())
3640 continue;
3641 if (NonNullArgs.empty())
3642 NonNullArgs.resize(Args.size());
3643 NonNullArgs.set(IdxAST);
3644 }
3645 }
3646 }
3647
3648 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3649 // Handle the nonnull attribute on the parameters of the
3650 // function/method.
3652 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3653 parms = FD->parameters();
3654 else
3655 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3656
3657 unsigned ParamIndex = 0;
3658 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3659 I != E; ++I, ++ParamIndex) {
3660 const ParmVarDecl *PVD = *I;
3661 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
3662 if (NonNullArgs.empty())
3663 NonNullArgs.resize(Args.size());
3664
3665 NonNullArgs.set(ParamIndex);
3666 }
3667 }
3668 } else {
3669 // If we have a non-function, non-method declaration but no
3670 // function prototype, try to dig out the function prototype.
3671 if (!Proto) {
3672 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3673 QualType type = VD->getType().getNonReferenceType();
3674 if (auto pointerType = type->getAs<PointerType>())
3675 type = pointerType->getPointeeType();
3676 else if (auto blockType = type->getAs<BlockPointerType>())
3677 type = blockType->getPointeeType();
3678 // FIXME: data member pointers?
3679
3680 // Dig out the function prototype, if there is one.
3681 Proto = type->getAs<FunctionProtoType>();
3682 }
3683 }
3684
3685 // Fill in non-null argument information from the nullability
3686 // information on the parameter types (if we have them).
3687 if (Proto) {
3688 unsigned Index = 0;
3689 for (auto paramType : Proto->getParamTypes()) {
3690 if (isNonNullType(paramType)) {
3691 if (NonNullArgs.empty())
3692 NonNullArgs.resize(Args.size());
3693
3694 NonNullArgs.set(Index);
3695 }
3696
3697 ++Index;
3698 }
3699 }
3700 }
3701
3702 // Check for non-null arguments.
3703 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3704 ArgIndex != ArgIndexEnd; ++ArgIndex) {
3705 if (NonNullArgs[ArgIndex])
3706 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
3707 }
3708}
3709
3710void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
3711 StringRef ParamName, QualType ArgTy,
3712 QualType ParamTy) {
3713
3714 // If a function accepts a pointer or reference type
3715 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
3716 return;
3717
3718 // If the parameter is a pointer type, get the pointee type for the
3719 // argument too. If the parameter is a reference type, don't try to get
3720 // the pointee type for the argument.
3721 if (ParamTy->isPointerType())
3722 ArgTy = ArgTy->getPointeeType();
3723
3724 // Remove reference or pointer
3725 ParamTy = ParamTy->getPointeeType();
3726
3727 // Find expected alignment, and the actual alignment of the passed object.
3728 // getTypeAlignInChars requires complete types
3729 if (ArgTy.isNull() || ParamTy->isDependentType() ||
3730 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
3731 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
3732 return;
3733
3734 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
3735 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
3736
3737 // If the argument is less aligned than the parameter, there is a
3738 // potential alignment issue.
3739 if (ArgAlign < ParamAlign)
3740 Diag(Loc, diag::warn_param_mismatched_alignment)
3741 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
3742 << ParamName << (FDecl != nullptr) << FDecl;
3743}
3744
3745void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
3746 const Expr *ThisArg,
3748 if (!FD || Args.empty())
3749 return;
3750 auto GetArgAt = [&](int Idx) -> const Expr * {
3751 if (Idx == LifetimeCaptureByAttr::Global ||
3752 Idx == LifetimeCaptureByAttr::Unknown)
3753 return nullptr;
3754 if (IsMemberFunction && Idx == 0)
3755 return ThisArg;
3756 return Args[Idx - IsMemberFunction];
3757 };
3758 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
3759 unsigned ArgIdx) {
3760 if (!Attr)
3761 return;
3762
3763 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
3764 for (int CapturingParamIdx : Attr->params()) {
3765 // lifetime_capture_by(this) case is handled in the lifetimebound expr
3766 // initialization codepath.
3767 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
3769 continue;
3770 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
3771 CapturingEntity CE{Capturing};
3772 // Ensure that 'Captured' outlives the 'Capturing' entity.
3773 checkCaptureByLifetime(*this, CE, Captured);
3774 }
3775 };
3776 for (unsigned I = 0; I < FD->getNumParams(); ++I)
3777 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(),
3778 I + IsMemberFunction);
3779 // Check when the implicit object param is captured.
3780 if (IsMemberFunction) {
3781 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
3782 if (!TSI)
3783 return;
3785 for (TypeLoc TL = TSI->getTypeLoc();
3786 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
3787 TL = ATL.getModifiedLoc())
3788 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
3789 }
3790}
3791
3793 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3794 bool IsMemberFunction, SourceLocation Loc,
3795 SourceRange Range, VariadicCallType CallType) {
3796 // FIXME: We should check as much as we can in the template definition.
3797 if (CurContext->isDependentContext())
3798 return;
3799
3800 // Printf and scanf checking.
3801 llvm::SmallBitVector CheckedVarArgs;
3802 if (FDecl) {
3803 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
3804 // Only create vector if there are format attributes.
3805 CheckedVarArgs.resize(Args.size());
3806 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
3807 CheckedVarArgs);
3808 }
3809
3810 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3811 CheckedVarArgs.resize(Args.size());
3812 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3813 CheckedVarArgs);
3814 }
3815 }
3816
3817 // Refuse POD arguments that weren't caught by the format string
3818 // checks above.
3819 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3820 if (CallType != VariadicCallType::DoesNotApply &&
3821 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3822 unsigned NumParams = Proto ? Proto->getNumParams()
3823 : isa_and_nonnull<FunctionDecl>(FDecl)
3824 ? cast<FunctionDecl>(FDecl)->getNumParams()
3825 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
3826 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3827 : 0;
3828
3829 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3830 // Args[ArgIdx] can be null in malformed code.
3831 if (const Expr *Arg = Args[ArgIdx]) {
3832 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3833 checkVariadicArgument(Arg, CallType);
3834 }
3835 }
3836 }
3837 if (FD)
3838 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
3839 if (FDecl || Proto) {
3840 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
3841
3842 // Type safety checking.
3843 if (FDecl) {
3844 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
3845 CheckArgumentWithTypeTag(I, Args, Loc);
3846 }
3847 }
3848
3849 // Check that passed arguments match the alignment of original arguments.
3850 // Try to get the missing prototype from the declaration.
3851 if (!Proto && FDecl) {
3852 const auto *FT = FDecl->getFunctionType();
3853 if (isa_and_nonnull<FunctionProtoType>(FT))
3854 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
3855 }
3856 if (Proto) {
3857 // For variadic functions, we may have more args than parameters.
3858 // For some K&R functions, we may have less args than parameters.
3859 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
3860 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
3861 bool IsScalableArg = false;
3862 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
3863 // Args[ArgIdx] can be null in malformed code.
3864 if (const Expr *Arg = Args[ArgIdx]) {
3865 if (Arg->containsErrors())
3866 continue;
3867
3868 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
3869 FDecl->hasLinkage() &&
3870 FDecl->getFormalLinkage() != Linkage::Internal &&
3872 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
3873
3874 QualType ParamTy = Proto->getParamType(ArgIdx);
3875 if (ParamTy->isSizelessVectorType())
3876 IsScalableArg = true;
3877 QualType ArgTy = Arg->getType();
3878 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
3879 ArgTy, ParamTy);
3880 }
3881 }
3882
3883 // If the callee has an AArch64 SME attribute to indicate that it is an
3884 // __arm_streaming function, then the caller requires SME to be available.
3887 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
3888 llvm::StringMap<bool> CallerFeatureMap;
3889 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
3890 if (!CallerFeatureMap.contains("sme"))
3891 Diag(Loc, diag::err_sme_call_in_non_sme_target);
3892 } else if (!Context.getTargetInfo().hasFeature("sme")) {
3893 Diag(Loc, diag::err_sme_call_in_non_sme_target);
3894 }
3895 }
3896
3897 // If the call requires a streaming-mode change and has scalable vector
3898 // arguments or return values, then warn the user that the streaming and
3899 // non-streaming vector lengths may be different.
3900 // When both streaming and non-streaming vector lengths are defined and
3901 // mismatched, produce an error.
3902 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
3903 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
3904 (IsScalableArg || IsScalableRet)) {
3905 bool IsCalleeStreaming =
3907 bool IsCalleeStreamingCompatible =
3908 ExtInfo.AArch64SMEAttributes &
3910 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
3911 if (!IsCalleeStreamingCompatible &&
3912 (CallerFnType == SemaARM::ArmStreamingCompatible ||
3913 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
3914 const LangOptions &LO = getLangOpts();
3915 unsigned VL = LO.VScaleMin * 128;
3916 unsigned SVL = LO.VScaleStreamingMin * 128;
3917 bool IsVLMismatch = VL && SVL && VL != SVL;
3918
3919 auto EmitDiag = [&](bool IsArg) {
3920 if (IsVLMismatch) {
3921 if (CallerFnType == SemaARM::ArmStreamingCompatible)
3922 // Emit warning for streaming-compatible callers
3923 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
3924 << IsArg << IsCalleeStreaming << SVL << VL;
3925 else
3926 // Emit error otherwise
3927 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
3928 << IsArg << SVL << VL;
3929 } else
3930 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
3931 << IsArg;
3932 };
3933
3934 if (IsScalableArg)
3935 EmitDiag(true);
3936 if (IsScalableRet)
3937 EmitDiag(false);
3938 }
3939 }
3940
3941 FunctionType::ArmStateValue CalleeArmZAState =
3943 FunctionType::ArmStateValue CalleeArmZT0State =
3945 if (CalleeArmZAState != FunctionType::ARM_None ||
3946 CalleeArmZT0State != FunctionType::ARM_None) {
3947 bool CallerHasZAState = false;
3948 bool CallerHasZT0State = false;
3949 if (CallerFD) {
3950 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
3951 if (Attr && Attr->isNewZA())
3952 CallerHasZAState = true;
3953 if (Attr && Attr->isNewZT0())
3954 CallerHasZT0State = true;
3955 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
3956 CallerHasZAState |=
3958 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
3960 CallerHasZT0State |=
3962 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
3964 }
3965 }
3966
3967 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
3968 Diag(Loc, diag::err_sme_za_call_no_za_state);
3969
3970 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
3971 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
3972
3973 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
3974 CalleeArmZT0State != FunctionType::ARM_None) {
3975 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
3976 Diag(Loc, diag::note_sme_use_preserves_za);
3977 }
3978 }
3979 }
3980
3981 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
3982 auto *AA = FDecl->getAttr<AllocAlignAttr>();
3983 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
3984 if (!Arg->isValueDependent()) {
3985 Expr::EvalResult Align;
3986 if (Arg->EvaluateAsInt(Align, Context)) {
3987 const llvm::APSInt &I = Align.Val.getInt();
3988 if (!I.isPowerOf2())
3989 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
3990 << Arg->getSourceRange();
3991
3992 if (I > Sema::MaximumAlignment)
3993 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
3994 << Arg->getSourceRange() << Sema::MaximumAlignment;
3995 }
3996 }
3997 }
3998
3999 if (FD)
4000 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4001}
4002
4003void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4004 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4005 DiagnoseUseOfDecl(Decl, Loc);
4006 }
4007}
4008
4009void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4011 const FunctionProtoType *Proto,
4012 SourceLocation Loc) {
4013 VariadicCallType CallType = Proto->isVariadic()
4016
4017 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4018 CheckArgAlignment(
4019 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4020 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4021
4022 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4023 Loc, SourceRange(), CallType);
4024}
4025
4027 const FunctionProtoType *Proto) {
4028 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4029 isa<CXXMethodDecl>(FDecl);
4030 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4031 IsMemberOperatorCall;
4032 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4033 TheCall->getCallee());
4034 Expr** Args = TheCall->getArgs();
4035 unsigned NumArgs = TheCall->getNumArgs();
4036
4037 Expr *ImplicitThis = nullptr;
4038 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4039 // If this is a call to a member operator, hide the first
4040 // argument from checkCall.
4041 // FIXME: Our choice of AST representation here is less than ideal.
4042 ImplicitThis = Args[0];
4043 ++Args;
4044 --NumArgs;
4045 } else if (IsMemberFunction && !FDecl->isStatic() &&
4047 ImplicitThis =
4048 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4049
4050 if (ImplicitThis) {
4051 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4052 // used.
4053 QualType ThisType = ImplicitThis->getType();
4054 if (!ThisType->isPointerType()) {
4055 assert(!ThisType->isReferenceType());
4056 ThisType = Context.getPointerType(ThisType);
4057 }
4058
4059 QualType ThisTypeFromDecl = Context.getPointerType(
4060 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4061
4062 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4063 ThisTypeFromDecl);
4064 }
4065
4066 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4067 IsMemberFunction, TheCall->getRParenLoc(),
4068 TheCall->getCallee()->getSourceRange(), CallType);
4069
4070 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4071 // None of the checks below are needed for functions that don't have
4072 // simple names (e.g., C++ conversion functions).
4073 if (!FnInfo)
4074 return false;
4075
4076 // Enforce TCB except for builtin calls, which are always allowed.
4077 if (FDecl->getBuiltinID() == 0)
4078 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4079
4080 CheckAbsoluteValueFunction(TheCall, FDecl);
4081 CheckMaxUnsignedZero(TheCall, FDecl);
4082 CheckInfNaNFunction(TheCall, FDecl);
4083
4084 if (getLangOpts().ObjC)
4085 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4086
4087 unsigned CMId = FDecl->getMemoryFunctionKind();
4088
4089 // Handle memory setting and copying functions.
4090 switch (CMId) {
4091 case 0:
4092 return false;
4093 case Builtin::BIstrlcpy: // fallthrough
4094 case Builtin::BIstrlcat:
4095 CheckStrlcpycatArguments(TheCall, FnInfo);
4096 break;
4097 case Builtin::BIstrncat:
4098 CheckStrncatArguments(TheCall, FnInfo);
4099 break;
4100 case Builtin::BIfree:
4101 CheckFreeArguments(TheCall);
4102 break;
4103 default:
4104 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4105 }
4106
4107 return false;
4108}
4109
4110bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4111 const FunctionProtoType *Proto) {
4112 QualType Ty;
4113 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4114 Ty = V->getType().getNonReferenceType();
4115 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4116 Ty = F->getType().getNonReferenceType();
4117 else
4118 return false;
4119
4120 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4121 !Ty->isFunctionProtoType())
4122 return false;
4123
4124 VariadicCallType CallType;
4125 if (!Proto || !Proto->isVariadic()) {
4127 } else if (Ty->isBlockPointerType()) {
4128 CallType = VariadicCallType::Block;
4129 } else { // Ty->isFunctionPointerType()
4130 CallType = VariadicCallType::Function;
4131 }
4132
4133 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4134 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4135 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4136 TheCall->getCallee()->getSourceRange(), CallType);
4137
4138 return false;
4139}
4140
4141bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4142 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4143 TheCall->getCallee());
4144 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4145 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4146 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4147 TheCall->getCallee()->getSourceRange(), CallType);
4148
4149 return false;
4150}
4151
4152static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4153 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4154 return false;
4155
4156 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4157 switch (Op) {
4158 case AtomicExpr::AO__c11_atomic_init:
4159 case AtomicExpr::AO__opencl_atomic_init:
4160 llvm_unreachable("There is no ordering argument for an init");
4161
4162 case AtomicExpr::AO__c11_atomic_load:
4163 case AtomicExpr::AO__opencl_atomic_load:
4164 case AtomicExpr::AO__hip_atomic_load:
4165 case AtomicExpr::AO__atomic_load_n:
4166 case AtomicExpr::AO__atomic_load:
4167 case AtomicExpr::AO__scoped_atomic_load_n:
4168 case AtomicExpr::AO__scoped_atomic_load:
4169 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4170 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4171
4172 case AtomicExpr::AO__c11_atomic_store:
4173 case AtomicExpr::AO__opencl_atomic_store:
4174 case AtomicExpr::AO__hip_atomic_store:
4175 case AtomicExpr::AO__atomic_store:
4176 case AtomicExpr::AO__atomic_store_n:
4177 case AtomicExpr::AO__scoped_atomic_store:
4178 case AtomicExpr::AO__scoped_atomic_store_n:
4179 case AtomicExpr::AO__atomic_clear:
4180 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4181 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4182 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4183
4184 default:
4185 return true;
4186 }
4187}
4188
4189ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4191 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4192 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4193 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4194 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4195 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4196 Op);
4197}
4198
4200 SourceLocation RParenLoc, MultiExprArg Args,
4202 AtomicArgumentOrder ArgOrder) {
4203 // All the non-OpenCL operations take one of the following forms.
4204 // The OpenCL operations take the __c11 forms with one extra argument for
4205 // synchronization scope.
4206 enum {
4207 // C __c11_atomic_init(A *, C)
4208 Init,
4209
4210 // C __c11_atomic_load(A *, int)
4211 Load,
4212
4213 // void __atomic_load(A *, CP, int)
4214 LoadCopy,
4215
4216 // void __atomic_store(A *, CP, int)
4217 Copy,
4218
4219 // C __c11_atomic_add(A *, M, int)
4220 Arithmetic,
4221
4222 // C __atomic_exchange_n(A *, CP, int)
4223 Xchg,
4224
4225 // void __atomic_exchange(A *, C *, CP, int)
4226 GNUXchg,
4227
4228 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4229 C11CmpXchg,
4230
4231 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4232 GNUCmpXchg,
4233
4234 // bool __atomic_test_and_set(A *, int)
4235 TestAndSetByte,
4236
4237 // void __atomic_clear(A *, int)
4238 ClearByte,
4239 } Form = Init;
4240
4241 const unsigned NumForm = ClearByte + 1;
4242 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4243 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4244 // where:
4245 // C is an appropriate type,
4246 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4247 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4248 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4249 // the int parameters are for orderings.
4250
4251 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4252 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4253 "need to update code for modified forms");
4254 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4255 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4256 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4257 "need to update code for modified C11 atomics");
4258 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4259 Op <= AtomicExpr::AO__opencl_atomic_store;
4260 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4261 Op <= AtomicExpr::AO__hip_atomic_store;
4262 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4263 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4264 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4265 Op <= AtomicExpr::AO__c11_atomic_store) ||
4266 IsOpenCL;
4267 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4268 Op == AtomicExpr::AO__atomic_store_n ||
4269 Op == AtomicExpr::AO__atomic_exchange_n ||
4270 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4271 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4272 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4273 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4274 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4275 // Bit mask for extra allowed value types other than integers for atomic
4276 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4277 // allow floating point.
4278 enum ArithOpExtraValueType {
4279 AOEVT_None = 0,
4280 AOEVT_Pointer = 1,
4281 AOEVT_FP = 2,
4282 };
4283 unsigned ArithAllows = AOEVT_None;
4284
4285 switch (Op) {
4286 case AtomicExpr::AO__c11_atomic_init:
4287 case AtomicExpr::AO__opencl_atomic_init:
4288 Form = Init;
4289 break;
4290
4291 case AtomicExpr::AO__c11_atomic_load:
4292 case AtomicExpr::AO__opencl_atomic_load:
4293 case AtomicExpr::AO__hip_atomic_load:
4294 case AtomicExpr::AO__atomic_load_n:
4295 case AtomicExpr::AO__scoped_atomic_load_n:
4296 Form = Load;
4297 break;
4298
4299 case AtomicExpr::AO__atomic_load:
4300 case AtomicExpr::AO__scoped_atomic_load:
4301 Form = LoadCopy;
4302 break;
4303
4304 case AtomicExpr::AO__c11_atomic_store:
4305 case AtomicExpr::AO__opencl_atomic_store:
4306 case AtomicExpr::AO__hip_atomic_store:
4307 case AtomicExpr::AO__atomic_store:
4308 case AtomicExpr::AO__atomic_store_n:
4309 case AtomicExpr::AO__scoped_atomic_store:
4310 case AtomicExpr::AO__scoped_atomic_store_n:
4311 Form = Copy;
4312 break;
4313 case AtomicExpr::AO__atomic_fetch_add:
4314 case AtomicExpr::AO__atomic_fetch_sub:
4315 case AtomicExpr::AO__atomic_add_fetch:
4316 case AtomicExpr::AO__atomic_sub_fetch:
4317 case AtomicExpr::AO__scoped_atomic_fetch_add:
4318 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4319 case AtomicExpr::AO__scoped_atomic_add_fetch:
4320 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4321 case AtomicExpr::AO__c11_atomic_fetch_add:
4322 case AtomicExpr::AO__c11_atomic_fetch_sub:
4323 case AtomicExpr::AO__opencl_atomic_fetch_add:
4324 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4325 case AtomicExpr::AO__hip_atomic_fetch_add:
4326 case AtomicExpr::AO__hip_atomic_fetch_sub:
4327 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4328 Form = Arithmetic;
4329 break;
4330 case AtomicExpr::AO__atomic_fetch_max:
4331 case AtomicExpr::AO__atomic_fetch_min:
4332 case AtomicExpr::AO__atomic_max_fetch:
4333 case AtomicExpr::AO__atomic_min_fetch:
4334 case AtomicExpr::AO__scoped_atomic_fetch_max:
4335 case AtomicExpr::AO__scoped_atomic_fetch_min:
4336 case AtomicExpr::AO__scoped_atomic_max_fetch:
4337 case AtomicExpr::AO__scoped_atomic_min_fetch:
4338 case AtomicExpr::AO__c11_atomic_fetch_max:
4339 case AtomicExpr::AO__c11_atomic_fetch_min:
4340 case AtomicExpr::AO__opencl_atomic_fetch_max:
4341 case AtomicExpr::AO__opencl_atomic_fetch_min:
4342 case AtomicExpr::AO__hip_atomic_fetch_max:
4343 case AtomicExpr::AO__hip_atomic_fetch_min:
4344 ArithAllows = AOEVT_FP;
4345 Form = Arithmetic;
4346 break;
4347 case AtomicExpr::AO__c11_atomic_fetch_and:
4348 case AtomicExpr::AO__c11_atomic_fetch_or:
4349 case AtomicExpr::AO__c11_atomic_fetch_xor:
4350 case AtomicExpr::AO__hip_atomic_fetch_and:
4351 case AtomicExpr::AO__hip_atomic_fetch_or:
4352 case AtomicExpr::AO__hip_atomic_fetch_xor:
4353 case AtomicExpr::AO__c11_atomic_fetch_nand:
4354 case AtomicExpr::AO__opencl_atomic_fetch_and:
4355 case AtomicExpr::AO__opencl_atomic_fetch_or:
4356 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4357 case AtomicExpr::AO__atomic_fetch_and:
4358 case AtomicExpr::AO__atomic_fetch_or:
4359 case AtomicExpr::AO__atomic_fetch_xor:
4360 case AtomicExpr::AO__atomic_fetch_nand:
4361 case AtomicExpr::AO__atomic_and_fetch:
4362 case AtomicExpr::AO__atomic_or_fetch:
4363 case AtomicExpr::AO__atomic_xor_fetch:
4364 case AtomicExpr::AO__atomic_nand_fetch:
4365 case AtomicExpr::AO__scoped_atomic_fetch_and:
4366 case AtomicExpr::AO__scoped_atomic_fetch_or:
4367 case AtomicExpr::AO__scoped_atomic_fetch_xor:
4368 case AtomicExpr::AO__scoped_atomic_fetch_nand:
4369 case AtomicExpr::AO__scoped_atomic_and_fetch:
4370 case AtomicExpr::AO__scoped_atomic_or_fetch:
4371 case AtomicExpr::AO__scoped_atomic_xor_fetch:
4372 case AtomicExpr::AO__scoped_atomic_nand_fetch:
4373 Form = Arithmetic;
4374 break;
4375
4376 case AtomicExpr::AO__c11_atomic_exchange:
4377 case AtomicExpr::AO__hip_atomic_exchange:
4378 case AtomicExpr::AO__opencl_atomic_exchange:
4379 case AtomicExpr::AO__atomic_exchange_n:
4380 case AtomicExpr::AO__scoped_atomic_exchange_n:
4381 Form = Xchg;
4382 break;
4383
4384 case AtomicExpr::AO__atomic_exchange:
4385 case AtomicExpr::AO__scoped_atomic_exchange:
4386 Form = GNUXchg;
4387 break;
4388
4389 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4390 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4391 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4392 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4393 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4394 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4395 Form = C11CmpXchg;
4396 break;
4397
4398 case AtomicExpr::AO__atomic_compare_exchange:
4399 case AtomicExpr::AO__atomic_compare_exchange_n:
4400 case AtomicExpr::AO__scoped_atomic_compare_exchange:
4401 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
4402 Form = GNUCmpXchg;
4403 break;
4404
4405 case AtomicExpr::AO__atomic_test_and_set:
4406 Form = TestAndSetByte;
4407 break;
4408
4409 case AtomicExpr::AO__atomic_clear:
4410 Form = ClearByte;
4411 break;
4412 }
4413
4414 unsigned AdjustedNumArgs = NumArgs[Form];
4415 if ((IsOpenCL || IsHIP || IsScoped) &&
4416 Op != AtomicExpr::AO__opencl_atomic_init)
4417 ++AdjustedNumArgs;
4418 // Check we have the right number of arguments.
4419 if (Args.size() < AdjustedNumArgs) {
4420 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4421 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4422 << /*is non object*/ 0 << ExprRange;
4423 return ExprError();
4424 } else if (Args.size() > AdjustedNumArgs) {
4425 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4426 diag::err_typecheck_call_too_many_args)
4427 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4428 << /*is non object*/ 0 << ExprRange;
4429 return ExprError();
4430 }
4431
4432 // Inspect the first argument of the atomic operation.
4433 Expr *Ptr = Args[0];
4435 if (ConvertedPtr.isInvalid())
4436 return ExprError();
4437
4438 Ptr = ConvertedPtr.get();
4439 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4440 if (!pointerType) {
4441 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4442 << Ptr->getType() << 0 << Ptr->getSourceRange();
4443 return ExprError();
4444 }
4445
4446 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4447 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4448 QualType ValType = AtomTy; // 'C'
4449 if (IsC11) {
4450 if (!AtomTy->isAtomicType()) {
4451 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4452 << Ptr->getType() << Ptr->getSourceRange();
4453 return ExprError();
4454 }
4455 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4457 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4458 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4459 << Ptr->getSourceRange();
4460 return ExprError();
4461 }
4462 ValType = AtomTy->castAs<AtomicType>()->getValueType();
4463 } else if (Form != Load && Form != LoadCopy) {
4464 if (ValType.isConstQualified()) {
4465 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4466 << Ptr->getType() << Ptr->getSourceRange();
4467 return ExprError();
4468 }
4469 }
4470
4471 if (Form != TestAndSetByte && Form != ClearByte) {
4472 // Pointer to object of size zero is not allowed.
4473 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
4474 diag::err_incomplete_type))
4475 return ExprError();
4476
4477 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
4478 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4479 << Ptr->getType() << 1 << Ptr->getSourceRange();
4480 return ExprError();
4481 }
4482 } else {
4483 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
4484 // non-const pointer type, including void* and pointers to incomplete
4485 // structs, but only access the first byte.
4486 AtomTy = Context.CharTy;
4487 AtomTy = AtomTy.withCVRQualifiers(
4488 pointerType->getPointeeType().getCVRQualifiers());
4489 QualType PointerQT = Context.getPointerType(AtomTy);
4490 pointerType = PointerQT->getAs<PointerType>();
4491 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
4492 ValType = AtomTy;
4493 }
4494
4495 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
4496 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4497 Diag(ExprRange.getBegin(),
4498 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4499 << 0 << Ptr->getType() << Ptr->getSourceRange();
4500 return ExprError();
4501 }
4502
4503 // For an arithmetic operation, the implied arithmetic must be well-formed.
4504 if (Form == Arithmetic) {
4505 // GCC does not enforce these rules for GNU atomics, but we do to help catch
4506 // trivial type errors.
4507 auto IsAllowedValueType = [&](QualType ValType,
4508 unsigned AllowedType) -> bool {
4509 if (ValType->isIntegerType())
4510 return true;
4511 if (ValType->isPointerType())
4512 return AllowedType & AOEVT_Pointer;
4513 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
4514 return false;
4515 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
4516 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
4517 &Context.getTargetInfo().getLongDoubleFormat() ==
4518 &llvm::APFloat::x87DoubleExtended())
4519 return false;
4520 return true;
4521 };
4522 if (!IsAllowedValueType(ValType, ArithAllows)) {
4523 auto DID = ArithAllows & AOEVT_FP
4524 ? (ArithAllows & AOEVT_Pointer
4525 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
4526 : diag::err_atomic_op_needs_atomic_int_or_fp)
4527 : diag::err_atomic_op_needs_atomic_int;
4528 Diag(ExprRange.getBegin(), DID)
4529 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4530 return ExprError();
4531 }
4532 if (IsC11 && ValType->isPointerType() &&
4534 diag::err_incomplete_type)) {
4535 return ExprError();
4536 }
4537 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4538 // For __atomic_*_n operations, the value type must be a scalar integral or
4539 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4540 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4541 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4542 return ExprError();
4543 }
4544
4545 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4546 !AtomTy->isScalarType()) {
4547 // For GNU atomics, require a trivially-copyable type. This is not part of
4548 // the GNU atomics specification but we enforce it for consistency with
4549 // other atomics which generally all require a trivially-copyable type. This
4550 // is because atomics just copy bits.
4551 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4552 << Ptr->getType() << Ptr->getSourceRange();
4553 return ExprError();
4554 }
4555
4556 switch (ValType.getObjCLifetime()) {
4559 // okay
4560 break;
4561
4565 // FIXME: Can this happen? By this point, ValType should be known
4566 // to be trivially copyable.
4567 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4568 << ValType << Ptr->getSourceRange();
4569 return ExprError();
4570 }
4571
4572 // All atomic operations have an overload which takes a pointer to a volatile
4573 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4574 // into the result or the other operands. Similarly atomic_load takes a
4575 // pointer to a const 'A'.
4576 ValType.removeLocalVolatile();
4577 ValType.removeLocalConst();
4578 QualType ResultType = ValType;
4579 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
4580 Form == ClearByte)
4581 ResultType = Context.VoidTy;
4582 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
4583 ResultType = Context.BoolTy;
4584
4585 // The type of a parameter passed 'by value'. In the GNU atomics, such
4586 // arguments are actually passed as pointers.
4587 QualType ByValType = ValType; // 'CP'
4588 bool IsPassedByAddress = false;
4589 if (!IsC11 && !IsHIP && !IsN) {
4590 ByValType = Ptr->getType();
4591 IsPassedByAddress = true;
4592 }
4593
4594 SmallVector<Expr *, 5> APIOrderedArgs;
4595 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4596 APIOrderedArgs.push_back(Args[0]);
4597 switch (Form) {
4598 case Init:
4599 case Load:
4600 APIOrderedArgs.push_back(Args[1]); // Val1/Order
4601 break;
4602 case LoadCopy:
4603 case Copy:
4604 case Arithmetic:
4605 case Xchg:
4606 APIOrderedArgs.push_back(Args[2]); // Val1
4607 APIOrderedArgs.push_back(Args[1]); // Order
4608 break;
4609 case GNUXchg:
4610 APIOrderedArgs.push_back(Args[2]); // Val1
4611 APIOrderedArgs.push_back(Args[3]); // Val2
4612 APIOrderedArgs.push_back(Args[1]); // Order
4613 break;
4614 case C11CmpXchg:
4615 APIOrderedArgs.push_back(Args[2]); // Val1
4616 APIOrderedArgs.push_back(Args[4]); // Val2
4617 APIOrderedArgs.push_back(Args[1]); // Order
4618 APIOrderedArgs.push_back(Args[3]); // OrderFail
4619 break;
4620 case GNUCmpXchg:
4621 APIOrderedArgs.push_back(Args[2]); // Val1
4622 APIOrderedArgs.push_back(Args[4]); // Val2
4623 APIOrderedArgs.push_back(Args[5]); // Weak
4624 APIOrderedArgs.push_back(Args[1]); // Order
4625 APIOrderedArgs.push_back(Args[3]); // OrderFail
4626 break;
4627 case TestAndSetByte:
4628 case ClearByte:
4629 APIOrderedArgs.push_back(Args[1]); // Order
4630 break;
4631 }
4632 } else
4633 APIOrderedArgs.append(Args.begin(), Args.end());
4634
4635 // The first argument's non-CV pointer type is used to deduce the type of
4636 // subsequent arguments, except for:
4637 // - weak flag (always converted to bool)
4638 // - memory order (always converted to int)
4639 // - scope (always converted to int)
4640 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4641 QualType Ty;
4642 if (i < NumVals[Form] + 1) {
4643 switch (i) {
4644 case 0:
4645 // The first argument is always a pointer. It has a fixed type.
4646 // It is always dereferenced, a nullptr is undefined.
4647 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4648 // Nothing else to do: we already know all we want about this pointer.
4649 continue;
4650 case 1:
4651 // The second argument is the non-atomic operand. For arithmetic, this
4652 // is always passed by value, and for a compare_exchange it is always
4653 // passed by address. For the rest, GNU uses by-address and C11 uses
4654 // by-value.
4655 assert(Form != Load);
4656 if (Form == Arithmetic && ValType->isPointerType())
4657 Ty = Context.getPointerDiffType();
4658 else if (Form == Init || Form == Arithmetic)
4659 Ty = ValType;
4660 else if (Form == Copy || Form == Xchg) {
4661 if (IsPassedByAddress) {
4662 // The value pointer is always dereferenced, a nullptr is undefined.
4663 CheckNonNullArgument(*this, APIOrderedArgs[i],
4664 ExprRange.getBegin());
4665 }
4666 Ty = ByValType;
4667 } else {
4668 Expr *ValArg = APIOrderedArgs[i];
4669 // The value pointer is always dereferenced, a nullptr is undefined.
4670 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4672 // Keep address space of non-atomic pointer type.
4673 if (const PointerType *PtrTy =
4674 ValArg->getType()->getAs<PointerType>()) {
4675 AS = PtrTy->getPointeeType().getAddressSpace();
4676 }
4677 Ty = Context.getPointerType(
4678 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4679 }
4680 break;
4681 case 2:
4682 // The third argument to compare_exchange / GNU exchange is the desired
4683 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4684 if (IsPassedByAddress)
4685 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4686 Ty = ByValType;
4687 break;
4688 case 3:
4689 // The fourth argument to GNU compare_exchange is a 'weak' flag.
4690 Ty = Context.BoolTy;
4691 break;
4692 }
4693 } else {
4694 // The order(s) and scope are always converted to int.
4695 Ty = Context.IntTy;
4696 }
4697
4698 InitializedEntity Entity =
4700 ExprResult Arg = APIOrderedArgs[i];
4701 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4702 if (Arg.isInvalid())
4703 return true;
4704 APIOrderedArgs[i] = Arg.get();
4705 }
4706
4707 // Permute the arguments into a 'consistent' order.
4708 SmallVector<Expr*, 5> SubExprs;
4709 SubExprs.push_back(Ptr);
4710 switch (Form) {
4711 case Init:
4712 // Note, AtomicExpr::getVal1() has a special case for this atomic.
4713 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4714 break;
4715 case Load:
4716 case TestAndSetByte:
4717 case ClearByte:
4718 SubExprs.push_back(APIOrderedArgs[1]); // Order
4719 break;
4720 case LoadCopy:
4721 case Copy:
4722 case Arithmetic:
4723 case Xchg:
4724 SubExprs.push_back(APIOrderedArgs[2]); // Order
4725 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4726 break;
4727 case GNUXchg:
4728 // Note, AtomicExpr::getVal2() has a special case for this atomic.
4729 SubExprs.push_back(APIOrderedArgs[3]); // Order
4730 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4731 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4732 break;
4733 case C11CmpXchg:
4734 SubExprs.push_back(APIOrderedArgs[3]); // Order
4735 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4736 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4737 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4738 break;
4739 case GNUCmpXchg:
4740 SubExprs.push_back(APIOrderedArgs[4]); // Order
4741 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4742 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4743 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4744 SubExprs.push_back(APIOrderedArgs[3]); // Weak
4745 break;
4746 }
4747
4748 // If the memory orders are constants, check they are valid.
4749 if (SubExprs.size() >= 2 && Form != Init) {
4750 std::optional<llvm::APSInt> Success =
4751 SubExprs[1]->getIntegerConstantExpr(Context);
4752 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
4753 Diag(SubExprs[1]->getBeginLoc(),
4754 diag::warn_atomic_op_has_invalid_memory_order)
4755 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
4756 << SubExprs[1]->getSourceRange();
4757 }
4758 if (SubExprs.size() >= 5) {
4759 if (std::optional<llvm::APSInt> Failure =
4760 SubExprs[3]->getIntegerConstantExpr(Context)) {
4761 if (!llvm::is_contained(
4762 {llvm::AtomicOrderingCABI::relaxed,
4763 llvm::AtomicOrderingCABI::consume,
4764 llvm::AtomicOrderingCABI::acquire,
4765 llvm::AtomicOrderingCABI::seq_cst},
4766 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
4767 Diag(SubExprs[3]->getBeginLoc(),
4768 diag::warn_atomic_op_has_invalid_memory_order)
4769 << /*failure=*/2 << SubExprs[3]->getSourceRange();
4770 }
4771 }
4772 }
4773 }
4774
4775 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4776 auto *Scope = Args[Args.size() - 1];
4777 if (std::optional<llvm::APSInt> Result =
4778 Scope->getIntegerConstantExpr(Context)) {
4779 if (!ScopeModel->isValid(Result->getZExtValue()))
4780 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
4781 << Scope->getSourceRange();
4782 }
4783 SubExprs.push_back(Scope);
4784 }
4785
4786 AtomicExpr *AE = new (Context)
4787 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4788
4789 if ((Op == AtomicExpr::AO__c11_atomic_load ||
4790 Op == AtomicExpr::AO__c11_atomic_store ||
4791 Op == AtomicExpr::AO__opencl_atomic_load ||
4792 Op == AtomicExpr::AO__hip_atomic_load ||
4793 Op == AtomicExpr::AO__opencl_atomic_store ||
4794 Op == AtomicExpr::AO__hip_atomic_store) &&
4795 Context.AtomicUsesUnsupportedLibcall(AE))
4796 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4797 << ((Op == AtomicExpr::AO__c11_atomic_load ||
4798 Op == AtomicExpr::AO__opencl_atomic_load ||
4799 Op == AtomicExpr::AO__hip_atomic_load)
4800 ? 0
4801 : 1);
4802
4803 if (ValType->isBitIntType()) {
4804 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
4805 return ExprError();
4806 }
4807
4808 return AE;
4809}
4810
4811/// checkBuiltinArgument - Given a call to a builtin function, perform
4812/// normal type-checking on the given argument, updating the call in
4813/// place. This is useful when a builtin function requires custom
4814/// type-checking for some of its arguments but not necessarily all of
4815/// them.
4816///
4817/// Returns true on error.
4818static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4819 FunctionDecl *Fn = E->getDirectCallee();
4820 assert(Fn && "builtin call without direct callee!");
4821
4822 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4823 InitializedEntity Entity =
4825
4826 ExprResult Arg = E->getArg(ArgIndex);
4827 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4828 if (Arg.isInvalid())
4829 return true;
4830
4831 E->setArg(ArgIndex, Arg.get());
4832 return false;
4833}
4834
4835ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
4836 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4837 Expr *Callee = TheCall->getCallee();
4838 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4839 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4840
4841 // Ensure that we have at least one argument to do type inference from.
4842 if (TheCall->getNumArgs() < 1) {
4843 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4844 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
4845 << Callee->getSourceRange();
4846 return ExprError();
4847 }
4848
4849 // Inspect the first argument of the atomic builtin. This should always be
4850 // a pointer type, whose element is an integral scalar or pointer type.
4851 // Because it is a pointer type, we don't have to worry about any implicit
4852 // casts here.
4853 // FIXME: We don't allow floating point scalars as input.
4854 Expr *FirstArg = TheCall->getArg(0);
4855 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4856 if (FirstArgResult.isInvalid())
4857 return ExprError();
4858 FirstArg = FirstArgResult.get();
4859 TheCall->setArg(0, FirstArg);
4860
4861 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4862 if (!pointerType) {
4863 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4864 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4865 return ExprError();
4866 }
4867
4868 QualType ValType = pointerType->getPointeeType();
4869 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4870 !ValType->isBlockPointerType()) {
4871 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4872 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4873 return ExprError();
4874 }
4875 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
4876 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4877 Diag(FirstArg->getBeginLoc(),
4878 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4879 << 1 << ValType << FirstArg->getSourceRange();
4880 return ExprError();
4881 }
4882
4883 if (ValType.isConstQualified()) {
4884 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4885 << FirstArg->getType() << FirstArg->getSourceRange();
4886 return ExprError();
4887 }
4888
4889 switch (ValType.getObjCLifetime()) {
4892 // okay
4893 break;
4894
4898 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4899 << ValType << FirstArg->getSourceRange();
4900 return ExprError();
4901 }
4902
4903 // Strip any qualifiers off ValType.
4904 ValType = ValType.getUnqualifiedType();
4905
4906 // The majority of builtins return a value, but a few have special return
4907 // types, so allow them to override appropriately below.
4908 QualType ResultType = ValType;
4909
4910 // We need to figure out which concrete builtin this maps onto. For example,
4911 // __sync_fetch_and_add with a 2 byte object turns into
4912 // __sync_fetch_and_add_2.
4913#define BUILTIN_ROW(x) \
4914 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4915 Builtin::BI##x##_8, Builtin::BI##x##_16 }
4916
4917 static const unsigned BuiltinIndices[][5] = {
4918 BUILTIN_ROW(__sync_fetch_and_add),
4919 BUILTIN_ROW(__sync_fetch_and_sub),
4920 BUILTIN_ROW(__sync_fetch_and_or),
4921 BUILTIN_ROW(__sync_fetch_and_and),
4922 BUILTIN_ROW(__sync_fetch_and_xor),
4923 BUILTIN_ROW(__sync_fetch_and_nand),
4924
4925 BUILTIN_ROW(__sync_add_and_fetch),
4926 BUILTIN_ROW(__sync_sub_and_fetch),
4927 BUILTIN_ROW(__sync_and_and_fetch),
4928 BUILTIN_ROW(__sync_or_and_fetch),
4929 BUILTIN_ROW(__sync_xor_and_fetch),
4930 BUILTIN_ROW(__sync_nand_and_fetch),
4931
4932 BUILTIN_ROW(__sync_val_compare_and_swap),
4933 BUILTIN_ROW(__sync_bool_compare_and_swap),
4934 BUILTIN_ROW(__sync_lock_test_and_set),
4935 BUILTIN_ROW(__sync_lock_release),
4936 BUILTIN_ROW(__sync_swap)
4937 };
4938#undef BUILTIN_ROW
4939
4940 // Determine the index of the size.
4941 unsigned SizeIndex;
4942 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4943 case 1: SizeIndex = 0; break;
4944 case 2: SizeIndex = 1; break;
4945 case 4: SizeIndex = 2; break;
4946 case 8: SizeIndex = 3; break;
4947 case 16: SizeIndex = 4; break;
4948 default:
4949 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4950 << FirstArg->getType() << FirstArg->getSourceRange();
4951 return ExprError();
4952 }
4953
4954 // Each of these builtins has one pointer argument, followed by some number of
4955 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4956 // that we ignore. Find out which row of BuiltinIndices to read from as well
4957 // as the number of fixed args.
4958 unsigned BuiltinID = FDecl->getBuiltinID();
4959 unsigned BuiltinIndex, NumFixed = 1;
4960 bool WarnAboutSemanticsChange = false;
4961 switch (BuiltinID) {
4962 default: llvm_unreachable("Unknown overloaded atomic builtin!");
4963 case Builtin::BI__sync_fetch_and_add:
4964 case Builtin::BI__sync_fetch_and_add_1:
4965 case Builtin::BI__sync_fetch_and_add_2:
4966 case Builtin::BI__sync_fetch_and_add_4:
4967 case Builtin::BI__sync_fetch_and_add_8:
4968 case Builtin::BI__sync_fetch_and_add_16:
4969 BuiltinIndex = 0;
4970 break;
4971
4972 case Builtin::BI__sync_fetch_and_sub:
4973 case Builtin::BI__sync_fetch_and_sub_1:
4974 case Builtin::BI__sync_fetch_and_sub_2:
4975 case Builtin::BI__sync_fetch_and_sub_4:
4976 case Builtin::BI__sync_fetch_and_sub_8:
4977 case Builtin::BI__sync_fetch_and_sub_16:
4978 BuiltinIndex = 1;
4979 break;
4980
4981 case Builtin::BI__sync_fetch_and_or:
4982 case Builtin::BI__sync_fetch_and_or_1:
4983 case Builtin::BI__sync_fetch_and_or_2:
4984 case Builtin::BI__sync_fetch_and_or_4:
4985 case Builtin::BI__sync_fetch_and_or_8:
4986 case Builtin::BI__sync_fetch_and_or_16:
4987 BuiltinIndex = 2;
4988 break;
4989
4990 case Builtin::BI__sync_fetch_and_and:
4991 case Builtin::BI__sync_fetch_and_and_1:
4992 case Builtin::BI__sync_fetch_and_and_2:
4993 case Builtin::BI__sync_fetch_and_and_4:
4994 case Builtin::BI__sync_fetch_and_and_8:
4995 case Builtin::BI__sync_fetch_and_and_16:
4996 BuiltinIndex = 3;
4997 break;
4998
4999 case Builtin::BI__sync_fetch_and_xor:
5000 case Builtin::BI__sync_fetch_and_xor_1:
5001 case Builtin::BI__sync_fetch_and_xor_2:
5002 case Builtin::BI__sync_fetch_and_xor_4:
5003 case Builtin::BI__sync_fetch_and_xor_8:
5004 case Builtin::BI__sync_fetch_and_xor_16:
5005 BuiltinIndex = 4;
5006 break;
5007
5008 case Builtin::BI__sync_fetch_and_nand:
5009 case Builtin::BI__sync_fetch_and_nand_1:
5010 case Builtin::BI__sync_fetch_and_nand_2:
5011 case Builtin::BI__sync_fetch_and_nand_4:
5012 case Builtin::BI__sync_fetch_and_nand_8:
5013 case Builtin::BI__sync_fetch_and_nand_16:
5014 BuiltinIndex = 5;
5015 WarnAboutSemanticsChange = true;
5016 break;
5017
5018 case Builtin::BI__sync_add_and_fetch:
5019 case Builtin::BI__sync_add_and_fetch_1:
5020 case Builtin::BI__sync_add_and_fetch_2:
5021 case Builtin::BI__sync_add_and_fetch_4:
5022 case Builtin::BI__sync_add_and_fetch_8:
5023 case Builtin::BI__sync_add_and_fetch_16:
5024 BuiltinIndex = 6;
5025 break;
5026
5027 case Builtin::BI__sync_sub_and_fetch:
5028 case Builtin::BI__sync_sub_and_fetch_1:
5029 case Builtin::BI__sync_sub_and_fetch_2:
5030 case Builtin::BI__sync_sub_and_fetch_4:
5031 case Builtin::BI__sync_sub_and_fetch_8:
5032 case Builtin::BI__sync_sub_and_fetch_16:
5033 BuiltinIndex = 7;
5034 break;
5035
5036 case Builtin::BI__sync_and_and_fetch:
5037 case Builtin::BI__sync_and_and_fetch_1:
5038 case Builtin::BI__sync_and_and_fetch_2:
5039 case Builtin::BI__sync_and_and_fetch_4:
5040 case Builtin::BI__sync_and_and_fetch_8:
5041 case Builtin::BI__sync_and_and_fetch_16:
5042 BuiltinIndex = 8;
5043 break;
5044
5045 case Builtin::BI__sync_or_and_fetch:
5046 case Builtin::BI__sync_or_and_fetch_1:
5047 case Builtin::BI__sync_or_and_fetch_2:
5048 case Builtin::BI__sync_or_and_fetch_4:
5049 case Builtin::BI__sync_or_and_fetch_8:
5050 case Builtin::BI__sync_or_and_fetch_16:
5051 BuiltinIndex = 9;
5052 break;
5053
5054 case Builtin::BI__sync_xor_and_fetch:
5055 case Builtin::BI__sync_xor_and_fetch_1:
5056 case Builtin::BI__sync_xor_and_fetch_2:
5057 case Builtin::BI__sync_xor_and_fetch_4:
5058 case Builtin::BI__sync_xor_and_fetch_8:
5059 case Builtin::BI__sync_xor_and_fetch_16:
5060 BuiltinIndex = 10;
5061 break;
5062
5063 case Builtin::BI__sync_nand_and_fetch:
5064 case Builtin::BI__sync_nand_and_fetch_1:
5065 case Builtin::BI__sync_nand_and_fetch_2:
5066 case Builtin::BI__sync_nand_and_fetch_4:
5067 case Builtin::BI__sync_nand_and_fetch_8:
5068 case Builtin::BI__sync_nand_and_fetch_16:
5069 BuiltinIndex = 11;
5070 WarnAboutSemanticsChange = true;
5071 break;
5072
5073 case Builtin::BI__sync_val_compare_and_swap:
5074 case Builtin::BI__sync_val_compare_and_swap_1:
5075 case Builtin::BI__sync_val_compare_and_swap_2:
5076 case Builtin::BI__sync_val_compare_and_swap_4:
5077 case Builtin::BI__sync_val_compare_and_swap_8:
5078 case Builtin::BI__sync_val_compare_and_swap_16:
5079 BuiltinIndex = 12;
5080 NumFixed = 2;
5081 break;
5082
5083 case Builtin::BI__sync_bool_compare_and_swap:
5084 case Builtin::BI__sync_bool_compare_and_swap_1:
5085 case Builtin::BI__sync_bool_compare_and_swap_2:
5086 case Builtin::BI__sync_bool_compare_and_swap_4:
5087 case Builtin::BI__sync_bool_compare_and_swap_8:
5088 case Builtin::BI__sync_bool_compare_and_swap_16:
5089 BuiltinIndex = 13;
5090 NumFixed = 2;
5091 ResultType = Context.BoolTy;
5092 break;
5093
5094 case Builtin::BI__sync_lock_test_and_set:
5095 case Builtin::BI__sync_lock_test_and_set_1:
5096 case Builtin::BI__sync_lock_test_and_set_2:
5097 case Builtin::BI__sync_lock_test_and_set_4:
5098 case Builtin::BI__sync_lock_test_and_set_8:
5099 case Builtin::BI__sync_lock_test_and_set_16:
5100 BuiltinIndex = 14;
5101 break;
5102
5103 case Builtin::BI__sync_lock_release:
5104 case Builtin::BI__sync_lock_release_1:
5105 case Builtin::BI__sync_lock_release_2:
5106 case Builtin::BI__sync_lock_release_4:
5107 case Builtin::BI__sync_lock_release_8:
5108 case Builtin::BI__sync_lock_release_16:
5109 BuiltinIndex = 15;
5110 NumFixed = 0;
5111 ResultType = Context.VoidTy;
5112 break;
5113
5114 case Builtin::BI__sync_swap:
5115 case Builtin::BI__sync_swap_1:
5116 case Builtin::BI__sync_swap_2:
5117 case Builtin::BI__sync_swap_4:
5118 case Builtin::BI__sync_swap_8:
5119 case Builtin::BI__sync_swap_16:
5120 BuiltinIndex = 16;
5121 break;
5122 }
5123
5124 // Now that we know how many fixed arguments we expect, first check that we
5125 // have at least that many.
5126 if (TheCall->getNumArgs() < 1+NumFixed) {
5127 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5128 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5129 << Callee->getSourceRange();
5130 return ExprError();
5131 }
5132
5133 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5134 << Callee->getSourceRange();
5135
5136 if (WarnAboutSemanticsChange) {
5137 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5138 << Callee->getSourceRange();
5139 }
5140
5141 // Get the decl for the concrete builtin from this, we can tell what the
5142 // concrete integer type we should convert to is.
5143 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5144 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5145 FunctionDecl *NewBuiltinDecl;
5146 if (NewBuiltinID == BuiltinID)
5147 NewBuiltinDecl = FDecl;
5148 else {
5149 // Perform builtin lookup to avoid redeclaring it.
5150 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5151 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5152 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5153 assert(Res.getFoundDecl());
5154 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5155 if (!NewBuiltinDecl)
5156 return ExprError();
5157 }
5158
5159 // The first argument --- the pointer --- has a fixed type; we
5160 // deduce the types of the rest of the arguments accordingly. Walk
5161 // the remaining arguments, converting them to the deduced value type.
5162 for (unsigned i = 0; i != NumFixed; ++i) {
5163 ExprResult Arg = TheCall->getArg(i+1);
5164
5165 // GCC does an implicit conversion to the pointer or integer ValType. This
5166 // can fail in some cases (1i -> int**), check for this error case now.
5167 // Initialize the argument.
5168 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5169 ValType, /*consume*/ false);
5170 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5171 if (Arg.isInvalid())
5172 return ExprError();
5173
5174 // Okay, we have something that *can* be converted to the right type. Check
5175 // to see if there is a potentially weird extension going on here. This can
5176 // happen when you do an atomic operation on something like an char* and
5177 // pass in 42. The 42 gets converted to char. This is even more strange
5178 // for things like 45.123 -> char, etc.
5179 // FIXME: Do this check.
5180 TheCall->setArg(i+1, Arg.get());
5181 }
5182
5183 // Create a new DeclRefExpr to refer to the new decl.
5184 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5185 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5186 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5187 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5188
5189 // Set the callee in the CallExpr.
5190 // FIXME: This loses syntactic information.
5191 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5192 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5193 CK_BuiltinFnToFnPtr);
5194 TheCall->setCallee(PromotedCall.get());
5195
5196 // Change the result type of the call to match the original value type. This
5197 // is arbitrary, but the codegen for these builtins ins design to handle it
5198 // gracefully.
5199 TheCall->setType(ResultType);
5200
5201 // Prohibit problematic uses of bit-precise integer types with atomic
5202 // builtins. The arguments would have already been converted to the first
5203 // argument's type, so only need to check the first argument.
5204 const auto *BitIntValType = ValType->getAs<BitIntType>();
5205 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
5206 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5207 return ExprError();
5208 }
5209
5210 return TheCallResult;
5211}
5212
5213ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5214 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5215 DeclRefExpr *DRE =
5217 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5218 unsigned BuiltinID = FDecl->getBuiltinID();
5219 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5220 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5221 "Unexpected nontemporal load/store builtin!");
5222 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5223 unsigned numArgs = isStore ? 2 : 1;
5224
5225 // Ensure that we have the proper number of arguments.
5226 if (checkArgCount(TheCall, numArgs))
5227 return ExprError();
5228
5229 // Inspect the last argument of the nontemporal builtin. This should always
5230 // be a pointer type, from which we imply the type of the memory access.
5231 // Because it is a pointer type, we don't have to worry about any implicit
5232 // casts here.
5233 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5234 ExprResult PointerArgResult =
5236
5237 if (PointerArgResult.isInvalid())
5238 return ExprError();
5239 PointerArg = PointerArgResult.get();
5240 TheCall->setArg(numArgs - 1, PointerArg);
5241
5242 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5243 if (!pointerType) {
5244 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5245 << PointerArg->getType() << PointerArg->getSourceRange();
5246 return ExprError();
5247 }
5248
5249 QualType ValType = pointerType->getPointeeType();
5250
5251 // Strip any qualifiers off ValType.
5252 ValType = ValType.getUnqualifiedType();
5253 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5254 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5255 !ValType->isVectorType()) {
5256 Diag(DRE->getBeginLoc(),
5257 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5258 << PointerArg->getType() << PointerArg->getSourceRange();
5259 return ExprError();
5260 }
5261
5262 if (!isStore) {
5263 TheCall->setType(ValType);
5264 return TheCallResult;
5265 }
5266
5267 ExprResult ValArg = TheCall->getArg(0);
5268 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5269 Context, ValType, /*consume*/ false);
5270 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5271 if (ValArg.isInvalid())
5272 return ExprError();
5273
5274 TheCall->setArg(0, ValArg.get());
5275 TheCall->setType(Context.VoidTy);
5276 return TheCallResult;
5277}
5278
5279/// CheckObjCString - Checks that the format string argument to the os_log()
5280/// and os_trace() functions is correct, and converts it to const char *.
5281ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5282 Arg = Arg->IgnoreParenCasts();
5283 auto *Literal = dyn_cast<StringLiteral>(Arg);
5284 if (!Literal) {
5285 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5286 Literal = ObjcLiteral->getString();
5287 }
5288 }
5289
5290 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5291 return ExprError(
5292 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5293 << Arg->getSourceRange());
5294 }
5295
5296 ExprResult Result(Literal);
5297 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5298 InitializedEntity Entity =
5300 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5301 return Result;
5302}
5303
5304/// Check that the user is calling the appropriate va_start builtin for the
5305/// target and calling convention.
5306static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5307 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5308 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5309 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5310 TT.getArch() == llvm::Triple::aarch64_32);
5311 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5312 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5313 if (IsX64 || IsAArch64) {
5314 CallingConv CC = CC_C;
5315 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5316 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5317 if (IsMSVAStart) {
5318 // Don't allow this in System V ABI functions.
5319 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5320 return S.Diag(Fn->getBeginLoc(),
5321 diag::err_ms_va_start_used_in_sysv_function);
5322 } else {
5323 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5324 // On x64 Windows, don't allow this in System V ABI functions.
5325 // (Yes, that means there's no corresponding way to support variadic
5326 // System V ABI functions on Windows.)
5327 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5328 (!IsWindowsOrUEFI && CC == CC_Win64))
5329 return S.Diag(Fn->getBeginLoc(),
5330 diag::err_va_start_used_in_wrong_abi_function)
5331 << !IsWindowsOrUEFI;
5332 }
5333 return false;
5334 }
5335
5336 if (IsMSVAStart)
5337 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5338 return false;
5339}
5340
5342 ParmVarDecl **LastParam = nullptr) {
5343 // Determine whether the current function, block, or obj-c method is variadic
5344 // and get its parameter list.
5345 bool IsVariadic = false;
5347 DeclContext *Caller = S.CurContext;
5348 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5349 IsVariadic = Block->isVariadic();
5350 Params = Block->parameters();
5351 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5352 IsVariadic = FD->isVariadic();
5353 Params = FD->parameters();
5354 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5355 IsVariadic = MD->isVariadic();
5356 // FIXME: This isn't correct for methods (results in bogus warning).
5357 Params = MD->parameters();
5358 } else if (isa<CapturedDecl>(Caller)) {
5359 // We don't support va_start in a CapturedDecl.
5360 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5361 return true;
5362 } else {
5363 // This must be some other declcontext that parses exprs.
5364 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5365 return true;
5366 }
5367
5368 if (!IsVariadic) {
5369 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5370 return true;
5371 }
5372
5373 if (LastParam)
5374 *LastParam = Params.empty() ? nullptr : Params.back();
5375
5376 return false;
5377}
5378
5379bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5380 Expr *Fn = TheCall->getCallee();
5381 if (checkVAStartABI(*this, BuiltinID, Fn))
5382 return true;
5383
5384 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
5385 // This builtin requires one argument (the va_list), allows two arguments,
5386 // but diagnoses more than two arguments. e.g.,
5387 // __builtin_c23_va_start(); // error
5388 // __builtin_c23_va_start(list); // ok
5389 // __builtin_c23_va_start(list, param); // ok
5390 // __builtin_c23_va_start(list, anything, anything); // error
5391 // This differs from the GCC behavior in that they accept the last case
5392 // with a warning, but it doesn't seem like a useful behavior to allow.
5393 if (checkArgCountRange(TheCall, 1, 2))
5394 return true;
5395 } else {
5396 // In C23 mode, va_start only needs one argument. However, the builtin still
5397 // requires two arguments (which matches the behavior of the GCC builtin),
5398 // <stdarg.h> passes `0` as the second argument in C23 mode.
5399 if (checkArgCount(TheCall, 2))
5400 return true;
5401 }
5402
5403 // Type-check the first argument normally.
5404 if (checkBuiltinArgument(*this, TheCall, 0))
5405 return true;
5406
5407 // Check that the current function is variadic, and get its last parameter.
5408 ParmVarDecl *LastParam;
5409 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5410 return true;
5411
5412 // Verify that the second argument to the builtin is the last non-variadic
5413 // argument of the current function or method. In C23 mode, if the call is
5414 // not to __builtin_c23_va_start, and the second argument is an integer
5415 // constant expression with value 0, then we don't bother with this check.
5416 // For __builtin_c23_va_start, we only perform the check for the second
5417 // argument being the last argument to the current function if there is a
5418 // second argument present.
5419 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
5420 TheCall->getNumArgs() < 2) {
5421 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5422 return false;
5423 }
5424
5425 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5426 if (std::optional<llvm::APSInt> Val =
5428 Val && LangOpts.C23 && *Val == 0 &&
5429 BuiltinID != Builtin::BI__builtin_c23_va_start) {
5430 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5431 return false;
5432 }
5433
5434 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
5435 // next block.
5436 QualType Type;
5437 SourceLocation ParamLoc;
5438 bool IsCRegister = false;
5439 bool SecondArgIsLastNonVariadicArgument = false;
5440 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5441 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5442 SecondArgIsLastNonVariadicArgument = PV == LastParam;
5443
5444 Type = PV->getType();
5445 ParamLoc = PV->getLocation();
5446 IsCRegister =
5447 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5448 }
5449 }
5450
5451 if (!SecondArgIsLastNonVariadicArgument)
5452 Diag(TheCall->getArg(1)->getBeginLoc(),
5453 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
5454 else if (IsCRegister || Type->isReferenceType() ||
5455 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5456 // Promotable integers are UB, but enumerations need a bit of
5457 // extra checking to see what their promotable type actually is.
5458 if (!Context.isPromotableIntegerType(Type))
5459 return false;
5460 const auto *ED = Type->getAsEnumDecl();
5461 if (!ED)
5462 return true;
5463 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
5464 }()) {
5465 unsigned Reason = 0;
5466 if (Type->isReferenceType()) Reason = 1;
5467 else if (IsCRegister) Reason = 2;
5468 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5469 Diag(ParamLoc, diag::note_parameter_type) << Type;
5470 }
5471
5472 return false;
5473}
5474
5475bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
5476 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
5477 const LangOptions &LO = getLangOpts();
5478
5479 if (LO.CPlusPlus)
5480 return Arg->getType()
5482 .getTypePtr()
5483 ->getPointeeType()
5485
5486 // In C, allow aliasing through `char *`, this is required for AArch64 at
5487 // least.
5488 return true;
5489 };
5490
5491 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5492 // const char *named_addr);
5493
5494 Expr *Func = Call->getCallee();
5495
5496 if (Call->getNumArgs() < 3)
5497 return Diag(Call->getEndLoc(),
5498 diag::err_typecheck_call_too_few_args_at_least)
5499 << 0 /*function call*/ << 3 << Call->getNumArgs()
5500 << /*is non object*/ 0;
5501
5502 // Type-check the first argument normally.
5503 if (checkBuiltinArgument(*this, Call, 0))
5504 return true;
5505
5506 // Check that the current function is variadic.
5508 return true;
5509
5510 // __va_start on Windows does not validate the parameter qualifiers
5511
5512 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5513 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5514
5515 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5516 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5517
5518 const QualType &ConstCharPtrTy =
5519 Context.getPointerType(Context.CharTy.withConst());
5520 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
5521 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5522 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5523 << 0 /* qualifier difference */
5524 << 3 /* parameter mismatch */
5525 << 2 << Arg1->getType() << ConstCharPtrTy;
5526
5527 const QualType SizeTy = Context.getSizeType();
5528 if (!Context.hasSameType(
5530 SizeTy))
5531 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5532 << Arg2->getType() << SizeTy << 1 /* different class */
5533 << 0 /* qualifier difference */
5534 << 3 /* parameter mismatch */
5535 << 3 << Arg2->getType() << SizeTy;
5536
5537 return false;
5538}
5539
5540bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
5541 if (checkArgCount(TheCall, 2))
5542 return true;
5543
5544 if (BuiltinID == Builtin::BI__builtin_isunordered &&
5545 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
5546 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5547 << 1 << 0 << TheCall->getSourceRange();
5548
5549 ExprResult OrigArg0 = TheCall->getArg(0);
5550 ExprResult OrigArg1 = TheCall->getArg(1);
5551
5552 // Do standard promotions between the two arguments, returning their common
5553 // type.
5554 QualType Res = UsualArithmeticConversions(
5555 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
5556 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5557 return true;
5558
5559 // Make sure any conversions are pushed back into the call; this is
5560 // type safe since unordered compare builtins are declared as "_Bool
5561 // foo(...)".
5562 TheCall->setArg(0, OrigArg0.get());
5563 TheCall->setArg(1, OrigArg1.get());
5564
5565 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5566 return false;
5567
5568 // If the common type isn't a real floating type, then the arguments were
5569 // invalid for this operation.
5570 if (Res.isNull() || !Res->isRealFloatingType())
5571 return Diag(OrigArg0.get()->getBeginLoc(),
5572 diag::err_typecheck_call_invalid_ordered_compare)
5573 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5574 << SourceRange(OrigArg0.get()->getBeginLoc(),
5575 OrigArg1.get()->getEndLoc());
5576
5577 return false;
5578}
5579
5580bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
5581 unsigned BuiltinID) {
5582 if (checkArgCount(TheCall, NumArgs))
5583 return true;
5584
5585 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
5586 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
5587 BuiltinID == Builtin::BI__builtin_isinf ||
5588 BuiltinID == Builtin::BI__builtin_isinf_sign))
5589 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5590 << 0 << 0 << TheCall->getSourceRange();
5591
5592 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
5593 BuiltinID == Builtin::BI__builtin_isunordered))
5594 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5595 << 1 << 0 << TheCall->getSourceRange();
5596
5597 bool IsFPClass = NumArgs == 2;
5598
5599 // Find out position of floating-point argument.
5600 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
5601
5602 // We can count on all parameters preceding the floating-point just being int.
5603 // Try all of those.
5604 for (unsigned i = 0; i < FPArgNo; ++i) {
5605 Expr *Arg = TheCall->getArg(i);
5606
5607 if (Arg->isTypeDependent())
5608 return false;
5609
5612
5613 if (Res.isInvalid())
5614 return true;
5615 TheCall->setArg(i, Res.get());
5616 }
5617
5618 Expr *OrigArg = TheCall->getArg(FPArgNo);
5619
5620 if (OrigArg->isTypeDependent())
5621 return false;
5622
5623 // Usual Unary Conversions will convert half to float, which we want for
5624 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5625 // type how it is, but do normal L->Rvalue conversions.
5626 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
5627 ExprResult Res = UsualUnaryConversions(OrigArg);
5628
5629 if (!Res.isUsable())
5630 return true;
5631 OrigArg = Res.get();
5632 } else {
5634
5635 if (!Res.isUsable())
5636 return true;
5637 OrigArg = Res.get();
5638 }
5639 TheCall->setArg(FPArgNo, OrigArg);
5640
5641 QualType VectorResultTy;
5642 QualType ElementTy = OrigArg->getType();
5643 // TODO: When all classification function are implemented with is_fpclass,
5644 // vector argument can be supported in all of them.
5645 if (ElementTy->isVectorType() && IsFPClass) {
5646 VectorResultTy = GetSignedVectorType(ElementTy);
5647 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
5648 }
5649
5650 // This operation requires a non-_Complex floating-point number.
5651 if (!ElementTy->isRealFloatingType())
5652 return Diag(OrigArg->getBeginLoc(),
5653 diag::err_typecheck_call_invalid_unary_fp)
5654 << OrigArg->getType() << OrigArg->getSourceRange();
5655
5656 // __builtin_isfpclass has integer parameter that specify test mask. It is
5657 // passed in (...), so it should be analyzed completely here.
5658 if (IsFPClass)
5659 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
5660 return true;
5661
5662 // TODO: enable this code to all classification functions.
5663 if (IsFPClass) {
5664 QualType ResultTy;
5665 if (!VectorResultTy.isNull())
5666 ResultTy = VectorResultTy;
5667 else
5668 ResultTy = Context.IntTy;
5669 TheCall->setType(ResultTy);
5670 }
5671
5672 return false;
5673}
5674
5675bool Sema::BuiltinComplex(CallExpr *TheCall) {
5676 if (checkArgCount(TheCall, 2))
5677 return true;
5678
5679 bool Dependent = false;
5680 for (unsigned I = 0; I != 2; ++I) {
5681 Expr *Arg = TheCall->getArg(I);
5682 QualType T = Arg->getType();
5683 if (T->isDependentType()) {
5684 Dependent = true;
5685 continue;
5686 }
5687
5688 // Despite supporting _Complex int, GCC requires a real floating point type
5689 // for the operands of __builtin_complex.
5690 if (!T->isRealFloatingType()) {
5691 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
5692 << Arg->getType() << Arg->getSourceRange();
5693 }
5694
5695 ExprResult Converted = DefaultLvalueConversion(Arg);
5696 if (Converted.isInvalid())
5697 return true;
5698 TheCall->setArg(I, Converted.get());
5699 }
5700
5701 if (Dependent) {
5702 TheCall->setType(Context.DependentTy);
5703 return false;
5704 }
5705
5706 Expr *Real = TheCall->getArg(0);
5707 Expr *Imag = TheCall->getArg(1);
5708 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
5709 return Diag(Real->getBeginLoc(),
5710 diag::err_typecheck_call_different_arg_types)
5711 << Real->getType() << Imag->getType()
5712 << Real->getSourceRange() << Imag->getSourceRange();
5713 }
5714
5715 TheCall->setType(Context.getComplexType(Real->getType()));
5716 return false;
5717}
5718
5719/// BuiltinShuffleVector - Handle __builtin_shufflevector.
5720// This is declared to take (...), so we have to check everything.
5722 unsigned NumArgs = TheCall->getNumArgs();
5723 if (NumArgs < 2)
5724 return ExprError(Diag(TheCall->getEndLoc(),
5725 diag::err_typecheck_call_too_few_args_at_least)
5726 << 0 /*function call*/ << 2 << NumArgs
5727 << /*is non object*/ 0 << TheCall->getSourceRange());
5728
5729 // Determine which of the following types of shufflevector we're checking:
5730 // 1) unary, vector mask: (lhs, mask)
5731 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5732 QualType ResType = TheCall->getArg(0)->getType();
5733 unsigned NumElements = 0;
5734
5735 if (!TheCall->getArg(0)->isTypeDependent() &&
5736 !TheCall->getArg(1)->isTypeDependent()) {
5737 QualType LHSType = TheCall->getArg(0)->getType();
5738 QualType RHSType = TheCall->getArg(1)->getType();
5739
5740 if (!LHSType->isVectorType() || !RHSType->isVectorType())
5741 return ExprError(
5742 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5743 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
5744 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5745 TheCall->getArg(1)->getEndLoc()));
5746
5747 NumElements = LHSType->castAs<VectorType>()->getNumElements();
5748 unsigned NumResElements = NumArgs - 2;
5749
5750 // Check to see if we have a call with 2 vector arguments, the unary shuffle
5751 // with mask. If so, verify that RHS is an integer vector type with the
5752 // same number of elts as lhs.
5753 if (NumArgs == 2) {
5754 if (!RHSType->hasIntegerRepresentation() ||
5755 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
5756 return ExprError(Diag(TheCall->getBeginLoc(),
5757 diag::err_vec_builtin_incompatible_vector)
5758 << TheCall->getDirectCallee()
5759 << /*isMoreThanTwoArgs*/ false
5760 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5761 TheCall->getArg(1)->getEndLoc()));
5762 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5763 return ExprError(Diag(TheCall->getBeginLoc(),
5764 diag::err_vec_builtin_incompatible_vector)
5765 << TheCall->getDirectCallee()
5766 << /*isMoreThanTwoArgs*/ false
5767 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5768 TheCall->getArg(1)->getEndLoc()));
5769 } else if (NumElements != NumResElements) {
5770 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
5771 ResType = ResType->isExtVectorType()
5772 ? Context.getExtVectorType(EltType, NumResElements)
5773 : Context.getVectorType(EltType, NumResElements,
5775 }
5776 }
5777
5778 for (unsigned I = 2; I != NumArgs; ++I) {
5779 Expr *Arg = TheCall->getArg(I);
5780 if (Arg->isTypeDependent() || Arg->isValueDependent())
5781 continue;
5782
5783 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
5784 if (!Result)
5785 return ExprError(Diag(TheCall->getBeginLoc(),
5786 diag::err_shufflevector_nonconstant_argument)
5787 << Arg->getSourceRange());
5788
5789 // Allow -1 which will be translated to undef in the IR.
5790 if (Result->isSigned() && Result->isAllOnes())
5791 ;
5792 else if (Result->getActiveBits() > 64 ||
5793 Result->getZExtValue() >= NumElements * 2)
5794 return ExprError(Diag(TheCall->getBeginLoc(),
5795 diag::err_shufflevector_argument_too_large)
5796 << Arg->getSourceRange());
5797
5798 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
5799 }
5800
5801 auto *Result = new (Context) ShuffleVectorExpr(
5802 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
5803 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
5804
5805 // All moved to Result.
5806 TheCall->shrinkNumArgs(0);
5807 return Result;
5808}
5809
5811 SourceLocation BuiltinLoc,
5812 SourceLocation RParenLoc) {
5815 QualType DstTy = TInfo->getType();
5816 QualType SrcTy = E->getType();
5817
5818 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5819 return ExprError(Diag(BuiltinLoc,
5820 diag::err_convertvector_non_vector)
5821 << E->getSourceRange());
5822 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5823 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
5824 << "second"
5825 << "__builtin_convertvector");
5826
5827 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5828 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5829 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5830 if (SrcElts != DstElts)
5831 return ExprError(Diag(BuiltinLoc,
5832 diag::err_convertvector_incompatible_vector)
5833 << E->getSourceRange());
5834 }
5835
5836 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
5837 RParenLoc, CurFPFeatureOverrides());
5838}
5839
5840bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
5841 unsigned NumArgs = TheCall->getNumArgs();
5842
5843 if (NumArgs > 3)
5844 return Diag(TheCall->getEndLoc(),
5845 diag::err_typecheck_call_too_many_args_at_most)
5846 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
5847 << TheCall->getSourceRange();
5848
5849 // Argument 0 is checked for us and the remaining arguments must be
5850 // constant integers.
5851 for (unsigned i = 1; i != NumArgs; ++i)
5852 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5853 return true;
5854
5855 return false;
5856}
5857
5858bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
5859 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
5860 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
5861 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5862 if (checkArgCount(TheCall, 1))
5863 return true;
5864 Expr *Arg = TheCall->getArg(0);
5865 if (Arg->isInstantiationDependent())
5866 return false;
5867
5868 QualType ArgTy = Arg->getType();
5869 if (!ArgTy->hasFloatingRepresentation())
5870 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
5871 << ArgTy;
5872 if (Arg->isLValue()) {
5873 ExprResult FirstArg = DefaultLvalueConversion(Arg);
5874 TheCall->setArg(0, FirstArg.get());
5875 }
5876 TheCall->setType(TheCall->getArg(0)->getType());
5877 return false;
5878}
5879
5880bool Sema::BuiltinAssume(CallExpr *TheCall) {
5881 Expr *Arg = TheCall->getArg(0);
5882 if (Arg->isInstantiationDependent()) return false;
5883
5884 if (Arg->HasSideEffects(Context))
5885 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5886 << Arg->getSourceRange()
5887 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5888
5889 return false;
5890}
5891
5892bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
5893 // The alignment must be a constant integer.
5894 Expr *Arg = TheCall->getArg(1);
5895
5896 // We can't check the value of a dependent argument.
5897 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5898 if (const auto *UE =
5899 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5900 if (UE->getKind() == UETT_AlignOf ||
5901 UE->getKind() == UETT_PreferredAlignOf)
5902 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5903 << Arg->getSourceRange();
5904
5905 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5906
5907 if (!Result.isPowerOf2())
5908 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5909 << Arg->getSourceRange();
5910
5911 if (Result < Context.getCharWidth())
5912 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5913 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5914
5915 if (Result > std::numeric_limits<int32_t>::max())
5916 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5917 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5918 }
5919
5920 return false;
5921}
5922
5923bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
5924 if (checkArgCountRange(TheCall, 2, 3))
5925 return true;
5926
5927 unsigned NumArgs = TheCall->getNumArgs();
5928 Expr *FirstArg = TheCall->getArg(0);
5929
5930 {
5931 ExprResult FirstArgResult =
5933 if (!FirstArgResult.get()->getType()->isPointerType()) {
5934 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
5935 << TheCall->getSourceRange();
5936 return true;
5937 }
5938 TheCall->setArg(0, FirstArgResult.get());
5939 }
5940
5941 // The alignment must be a constant integer.
5942 Expr *SecondArg = TheCall->getArg(1);
5943
5944 // We can't check the value of a dependent argument.
5945 if (!SecondArg->isValueDependent()) {
5946 llvm::APSInt Result;
5947 if (BuiltinConstantArg(TheCall, 1, Result))
5948 return true;
5949
5950 if (!Result.isPowerOf2())
5951 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5952 << SecondArg->getSourceRange();
5953
5955 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5956 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
5957
5958 TheCall->setArg(1,
5960 }
5961
5962 if (NumArgs > 2) {
5963 Expr *ThirdArg = TheCall->getArg(2);
5964 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
5965 return true;
5966 TheCall->setArg(2, ThirdArg);
5967 }
5968
5969 return false;
5970}
5971
5972bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
5973 unsigned BuiltinID =
5974 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5975 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5976
5977 unsigned NumArgs = TheCall->getNumArgs();
5978 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5979 if (NumArgs < NumRequiredArgs) {
5980 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5981 << 0 /* function call */ << NumRequiredArgs << NumArgs
5982 << /*is non object*/ 0 << TheCall->getSourceRange();
5983 }
5984 if (NumArgs >= NumRequiredArgs + 0x100) {
5985 return Diag(TheCall->getEndLoc(),
5986 diag::err_typecheck_call_too_many_args_at_most)
5987 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5988 << /*is non object*/ 0 << TheCall->getSourceRange();
5989 }
5990 unsigned i = 0;
5991
5992 // For formatting call, check buffer arg.
5993 if (!IsSizeCall) {
5994 ExprResult Arg(TheCall->getArg(i));
5995 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5996 Context, Context.VoidPtrTy, false);
5997 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5998 if (Arg.isInvalid())
5999 return true;
6000 TheCall->setArg(i, Arg.get());
6001 i++;
6002 }
6003
6004 // Check string literal arg.
6005 unsigned FormatIdx = i;
6006 {
6007 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6008 if (Arg.isInvalid())
6009 return true;
6010 TheCall->setArg(i, Arg.get());
6011 i++;
6012 }
6013
6014 // Make sure variadic args are scalar.
6015 unsigned FirstDataArg = i;
6016 while (i < NumArgs) {
6018 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6019 if (Arg.isInvalid())
6020 return true;
6021 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6022 if (ArgSize.getQuantity() >= 0x100) {
6023 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6024 << i << (int)ArgSize.getQuantity() << 0xff
6025 << TheCall->getSourceRange();
6026 }
6027 TheCall->setArg(i, Arg.get());
6028 i++;
6029 }
6030
6031 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6032 // call to avoid duplicate diagnostics.
6033 if (!IsSizeCall) {
6034 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6035 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6036 bool Success = CheckFormatArguments(
6037 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
6039 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
6040 if (!Success)
6041 return true;
6042 }
6043
6044 if (IsSizeCall) {
6045 TheCall->setType(Context.getSizeType());
6046 } else {
6047 TheCall->setType(Context.VoidPtrTy);
6048 }
6049 return false;
6050}
6051
6052bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6053 llvm::APSInt &Result) {
6054 Expr *Arg = TheCall->getArg(ArgNum);
6055
6056 if (Arg->isTypeDependent() || Arg->isValueDependent())
6057 return false;
6058
6059 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
6060 if (!R) {
6061 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6062 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6063 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6064 << FDecl->getDeclName() << Arg->getSourceRange();
6065 }
6066 Result = *R;
6067
6068 return false;
6069}
6070
6071bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6072 int High, bool RangeIsError) {
6074 return false;
6075 llvm::APSInt Result;
6076
6077 // We can't check the value of a dependent argument.
6078 Expr *Arg = TheCall->getArg(ArgNum);
6079 if (Arg->isTypeDependent() || Arg->isValueDependent())
6080 return false;
6081
6082 // Check constant-ness first.
6083 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6084 return true;
6085
6086 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6087 if (RangeIsError)
6088 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6089 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6090 else
6091 // Defer the warning until we know if the code will be emitted so that
6092 // dead code can ignore this.
6093 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6094 PDiag(diag::warn_argument_invalid_range)
6095 << toString(Result, 10) << Low << High
6096 << Arg->getSourceRange());
6097 }
6098
6099 return false;
6100}
6101
6102bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6103 unsigned Num) {
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 if (Result.getSExtValue() % Num != 0)
6116 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6117 << Num << Arg->getSourceRange();
6118
6119 return false;
6120}
6121
6122bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6123 llvm::APSInt Result;
6124
6125 // We can't check the value of a dependent argument.
6126 Expr *Arg = TheCall->getArg(ArgNum);
6127 if (Arg->isTypeDependent() || Arg->isValueDependent())
6128 return false;
6129
6130 // Check constant-ness first.
6131 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6132 return true;
6133
6134 if (Result.isPowerOf2())
6135 return false;
6136
6137 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6138 << Arg->getSourceRange();
6139}
6140
6141static bool IsShiftedByte(llvm::APSInt Value) {
6142 if (Value.isNegative())
6143 return false;
6144
6145 // Check if it's a shifted byte, by shifting it down
6146 while (true) {
6147 // If the value fits in the bottom byte, the check passes.
6148 if (Value < 0x100)
6149 return true;
6150
6151 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6152 // fails.
6153 if ((Value & 0xFF) != 0)
6154 return false;
6155
6156 // If the bottom 8 bits are all 0, but something above that is nonzero,
6157 // then shifting the value right by 8 bits won't affect whether it's a
6158 // shifted byte or not. So do that, and go round again.
6159 Value >>= 8;
6160 }
6161}
6162
6163bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6164 unsigned ArgBits) {
6165 llvm::APSInt Result;
6166
6167 // We can't check the value of a dependent argument.
6168 Expr *Arg = TheCall->getArg(ArgNum);
6169 if (Arg->isTypeDependent() || Arg->isValueDependent())
6170 return false;
6171
6172 // Check constant-ness first.
6173 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6174 return true;
6175
6176 // Truncate to the given size.
6177 Result = Result.getLoBits(ArgBits);
6178 Result.setIsUnsigned(true);
6179
6180 if (IsShiftedByte(Result))
6181 return false;
6182
6183 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6184 << Arg->getSourceRange();
6185}
6186
6188 unsigned ArgNum,
6189 unsigned ArgBits) {
6190 llvm::APSInt Result;
6191
6192 // We can't check the value of a dependent argument.
6193 Expr *Arg = TheCall->getArg(ArgNum);
6194 if (Arg->isTypeDependent() || Arg->isValueDependent())
6195 return false;
6196
6197 // Check constant-ness first.
6198 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6199 return true;
6200
6201 // Truncate to the given size.
6202 Result = Result.getLoBits(ArgBits);
6203 Result.setIsUnsigned(true);
6204
6205 // Check to see if it's in either of the required forms.
6206 if (IsShiftedByte(Result) ||
6207 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6208 return false;
6209
6210 return Diag(TheCall->getBeginLoc(),
6211 diag::err_argument_not_shifted_byte_or_xxff)
6212 << Arg->getSourceRange();
6213}
6214
6215bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6216 if (!Context.getTargetInfo().hasSjLjLowering())
6217 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6218 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6219
6220 Expr *Arg = TheCall->getArg(1);
6221 llvm::APSInt Result;
6222
6223 // TODO: This is less than ideal. Overload this to take a value.
6224 if (BuiltinConstantArg(TheCall, 1, Result))
6225 return true;
6226
6227 if (Result != 1)
6228 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6229 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6230
6231 return false;
6232}
6233
6234bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6235 if (!Context.getTargetInfo().hasSjLjLowering())
6236 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6237 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6238 return false;
6239}
6240
6241bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6242 if (checkArgCount(TheCall, 1))
6243 return true;
6244
6245 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
6246 if (ArgRes.isInvalid())
6247 return true;
6248
6249 // For simplicity, we support only limited expressions for the argument.
6250 // Specifically a pointer to a flexible array member:'ptr->array'. This
6251 // allows us to reject arguments with complex casting, which really shouldn't
6252 // be a huge problem.
6253 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6254 if (!isa<PointerType>(Arg->getType()) && !Arg->getType()->isArrayType())
6255 return Diag(Arg->getBeginLoc(),
6256 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6257 << Arg->getSourceRange();
6258
6259 if (Arg->HasSideEffects(Context))
6260 return Diag(Arg->getBeginLoc(),
6261 diag::err_builtin_counted_by_ref_has_side_effects)
6262 << Arg->getSourceRange();
6263
6264 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
6265 if (!ME->isFlexibleArrayMemberLike(
6266 Context, getLangOpts().getStrictFlexArraysLevel()))
6267 return Diag(Arg->getBeginLoc(),
6268 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6269 << Arg->getSourceRange();
6270
6271 if (auto *CATy =
6272 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6273 CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6274 const auto *FAMDecl = cast<FieldDecl>(ME->getMemberDecl());
6275 if (const FieldDecl *CountFD = FAMDecl->findCountedByField()) {
6276 TheCall->setType(Context.getPointerType(CountFD->getType()));
6277 return false;
6278 }
6279 }
6280 } else {
6281 return Diag(Arg->getBeginLoc(),
6282 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6283 << Arg->getSourceRange();
6284 }
6285
6286 TheCall->setType(Context.getPointerType(Context.VoidTy));
6287 return false;
6288}
6289
6290/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6291/// It allows leaking and modification of bounds safety information.
6292bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6294 const CallExpr *CE =
6295 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
6296 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6297 return false;
6298
6299 switch (K) {
6302 Diag(E->getExprLoc(),
6303 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6304 << 0 << E->getSourceRange();
6305 break;
6307 Diag(E->getExprLoc(),
6308 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6309 << 1 << E->getSourceRange();
6310 break;
6312 Diag(E->getExprLoc(),
6313 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6314 << 2 << E->getSourceRange();
6315 break;
6317 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6318 << 0 << E->getSourceRange();
6319 break;
6321 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6322 << 1 << E->getSourceRange();
6323 break;
6324 }
6325
6326 return true;
6327}
6328
6329namespace {
6330
6331class UncoveredArgHandler {
6332 enum { Unknown = -1, AllCovered = -2 };
6333
6334 signed FirstUncoveredArg = Unknown;
6335 SmallVector<const Expr *, 4> DiagnosticExprs;
6336
6337public:
6338 UncoveredArgHandler() = default;
6339
6340 bool hasUncoveredArg() const {
6341 return (FirstUncoveredArg >= 0);
6342 }
6343
6344 unsigned getUncoveredArg() const {
6345 assert(hasUncoveredArg() && "no uncovered argument");
6346 return FirstUncoveredArg;
6347 }
6348
6349 void setAllCovered() {
6350 // A string has been found with all arguments covered, so clear out
6351 // the diagnostics.
6352 DiagnosticExprs.clear();
6353 FirstUncoveredArg = AllCovered;
6354 }
6355
6356 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6357 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6358
6359 // Don't update if a previous string covers all arguments.
6360 if (FirstUncoveredArg == AllCovered)
6361 return;
6362
6363 // UncoveredArgHandler tracks the highest uncovered argument index
6364 // and with it all the strings that match this index.
6365 if (NewFirstUncoveredArg == FirstUncoveredArg)
6366 DiagnosticExprs.push_back(StrExpr);
6367 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6368 DiagnosticExprs.clear();
6369 DiagnosticExprs.push_back(StrExpr);
6370 FirstUncoveredArg = NewFirstUncoveredArg;
6371 }
6372 }
6373
6374 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6375};
6376
6377enum StringLiteralCheckType {
6378 SLCT_NotALiteral,
6379 SLCT_UncheckedLiteral,
6380 SLCT_CheckedLiteral
6381};
6382
6383} // namespace
6384
6385static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6386 BinaryOperatorKind BinOpKind,
6387 bool AddendIsRight) {
6388 unsigned BitWidth = Offset.getBitWidth();
6389 unsigned AddendBitWidth = Addend.getBitWidth();
6390 // There might be negative interim results.
6391 if (Addend.isUnsigned()) {
6392 Addend = Addend.zext(++AddendBitWidth);
6393 Addend.setIsSigned(true);
6394 }
6395 // Adjust the bit width of the APSInts.
6396 if (AddendBitWidth > BitWidth) {
6397 Offset = Offset.sext(AddendBitWidth);
6398 BitWidth = AddendBitWidth;
6399 } else if (BitWidth > AddendBitWidth) {
6400 Addend = Addend.sext(BitWidth);
6401 }
6402
6403 bool Ov = false;
6404 llvm::APSInt ResOffset = Offset;
6405 if (BinOpKind == BO_Add)
6406 ResOffset = Offset.sadd_ov(Addend, Ov);
6407 else {
6408 assert(AddendIsRight && BinOpKind == BO_Sub &&
6409 "operator must be add or sub with addend on the right");
6410 ResOffset = Offset.ssub_ov(Addend, Ov);
6411 }
6412
6413 // We add an offset to a pointer here so we should support an offset as big as
6414 // possible.
6415 if (Ov) {
6416 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6417 "index (intermediate) result too big");
6418 Offset = Offset.sext(2 * BitWidth);
6419 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6420 return;
6421 }
6422
6423 Offset = ResOffset;
6424}
6425
6426namespace {
6427
6428// This is a wrapper class around StringLiteral to support offsetted string
6429// literals as format strings. It takes the offset into account when returning
6430// the string and its length or the source locations to display notes correctly.
6431class FormatStringLiteral {
6432 const StringLiteral *FExpr;
6433 int64_t Offset;
6434
6435public:
6436 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6437 : FExpr(fexpr), Offset(Offset) {}
6438
6439 const StringLiteral *getFormatString() const { return FExpr; }
6440
6441 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
6442
6443 unsigned getByteLength() const {
6444 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6445 }
6446
6447 unsigned getLength() const { return FExpr->getLength() - Offset; }
6448 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6449
6450 StringLiteralKind getKind() const { return FExpr->getKind(); }
6451
6452 QualType getType() const { return FExpr->getType(); }
6453
6454 bool isAscii() const { return FExpr->isOrdinary(); }
6455 bool isWide() const { return FExpr->isWide(); }
6456 bool isUTF8() const { return FExpr->isUTF8(); }
6457 bool isUTF16() const { return FExpr->isUTF16(); }
6458 bool isUTF32() const { return FExpr->isUTF32(); }
6459 bool isPascal() const { return FExpr->isPascal(); }
6460
6461 SourceLocation getLocationOfByte(
6462 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6463 const TargetInfo &Target, unsigned *StartToken = nullptr,
6464 unsigned *StartTokenByteOffset = nullptr) const {
6465 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6466 StartToken, StartTokenByteOffset);
6467 }
6468
6469 SourceLocation getBeginLoc() const LLVM_READONLY {
6470 return FExpr->getBeginLoc().getLocWithOffset(Offset);
6471 }
6472
6473 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6474};
6475
6476} // namespace
6477
6478static void CheckFormatString(
6479 Sema &S, const FormatStringLiteral *FExpr,
6480 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
6482 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6483 bool inFunctionCall, VariadicCallType CallType,
6484 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6485 bool IgnoreStringsWithoutSpecifiers);
6486
6487static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
6488 const Expr *E);
6489
6490// Determine if an expression is a string literal or constant string.
6491// If this function returns false on the arguments to a function expecting a
6492// format string, we will usually need to emit a warning.
6493// True string literals are then checked by CheckFormatString.
6494static StringLiteralCheckType checkFormatStringExpr(
6495 Sema &S, const StringLiteral *ReferenceFormatString, const Expr *E,
6497 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6498 VariadicCallType CallType, bool InFunctionCall,
6499 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6500 llvm::APSInt Offset, bool IgnoreStringsWithoutSpecifiers = false) {
6502 return SLCT_NotALiteral;
6503tryAgain:
6504 assert(Offset.isSigned() && "invalid offset");
6505
6506 if (E->isTypeDependent() || E->isValueDependent())
6507 return SLCT_NotALiteral;
6508
6509 E = E->IgnoreParenCasts();
6510
6512 // Technically -Wformat-nonliteral does not warn about this case.
6513 // The behavior of printf and friends in this case is implementation
6514 // dependent. Ideally if the format string cannot be null then
6515 // it should have a 'nonnull' attribute in the function prototype.
6516 return SLCT_UncheckedLiteral;
6517
6518 switch (E->getStmtClass()) {
6519 case Stmt::InitListExprClass:
6520 // Handle expressions like {"foobar"}.
6521 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
6522 return checkFormatStringExpr(
6523 S, ReferenceFormatString, SLE, Args, APK, format_idx, firstDataArg,
6524 Type, CallType, /*InFunctionCall*/ false, CheckedVarArgs,
6525 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6526 }
6527 return SLCT_NotALiteral;
6528 case Stmt::BinaryConditionalOperatorClass:
6529 case Stmt::ConditionalOperatorClass: {
6530 // The expression is a literal if both sub-expressions were, and it was
6531 // completely checked only if both sub-expressions were checked.
6534
6535 // Determine whether it is necessary to check both sub-expressions, for
6536 // example, because the condition expression is a constant that can be
6537 // evaluated at compile time.
6538 bool CheckLeft = true, CheckRight = true;
6539
6540 bool Cond;
6541 if (C->getCond()->EvaluateAsBooleanCondition(
6543 if (Cond)
6544 CheckRight = false;
6545 else
6546 CheckLeft = false;
6547 }
6548
6549 // We need to maintain the offsets for the right and the left hand side
6550 // separately to check if every possible indexed expression is a valid
6551 // string literal. They might have different offsets for different string
6552 // literals in the end.
6553 StringLiteralCheckType Left;
6554 if (!CheckLeft)
6555 Left = SLCT_UncheckedLiteral;
6556 else {
6557 Left = checkFormatStringExpr(
6558 S, ReferenceFormatString, C->getTrueExpr(), Args, APK, format_idx,
6559 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6560 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6561 if (Left == SLCT_NotALiteral || !CheckRight) {
6562 return Left;
6563 }
6564 }
6565
6566 StringLiteralCheckType Right = checkFormatStringExpr(
6567 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
6568 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6569 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6570
6571 return (CheckLeft && Left < Right) ? Left : Right;
6572 }
6573
6574 case Stmt::ImplicitCastExprClass:
6575 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6576 goto tryAgain;
6577
6578 case Stmt::OpaqueValueExprClass:
6579 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6580 E = src;
6581 goto tryAgain;
6582 }
6583 return SLCT_NotALiteral;
6584
6585 case Stmt::PredefinedExprClass:
6586 // While __func__, etc., are technically not string literals, they
6587 // cannot contain format specifiers and thus are not a security
6588 // liability.
6589 return SLCT_UncheckedLiteral;
6590
6591 case Stmt::DeclRefExprClass: {
6592 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6593
6594 // As an exception, do not flag errors for variables binding to
6595 // const string literals.
6596 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6597 bool isConstant = false;
6598 QualType T = DR->getType();
6599
6600 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6601 isConstant = AT->getElementType().isConstant(S.Context);
6602 } else if (const PointerType *PT = T->getAs<PointerType>()) {
6603 isConstant = T.isConstant(S.Context) &&
6604 PT->getPointeeType().isConstant(S.Context);
6605 } else if (T->isObjCObjectPointerType()) {
6606 // In ObjC, there is usually no "const ObjectPointer" type,
6607 // so don't check if the pointee type is constant.
6608 isConstant = T.isConstant(S.Context);
6609 }
6610
6611 if (isConstant) {
6612 if (const Expr *Init = VD->getAnyInitializer()) {
6613 // Look through initializers like const char c[] = { "foo" }
6614 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6615 if (InitList->isStringLiteralInit())
6616 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6617 }
6618 return checkFormatStringExpr(
6619 S, ReferenceFormatString, Init, Args, APK, format_idx,
6620 firstDataArg, Type, CallType,
6621 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg, Offset);
6622 }
6623 }
6624
6625 // When the format argument is an argument of this function, and this
6626 // function also has the format attribute, there are several interactions
6627 // for which there shouldn't be a warning. For instance, when calling
6628 // v*printf from a function that has the printf format attribute, we
6629 // should not emit a warning about using `fmt`, even though it's not
6630 // constant, because the arguments have already been checked for the
6631 // caller of `logmessage`:
6632 //
6633 // __attribute__((format(printf, 1, 2)))
6634 // void logmessage(char const *fmt, ...) {
6635 // va_list ap;
6636 // va_start(ap, fmt);
6637 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
6638 // ...
6639 // }
6640 //
6641 // Another interaction that we need to support is using a format string
6642 // specified by the format_matches attribute:
6643 //
6644 // __attribute__((format_matches(printf, 1, "%s %d")))
6645 // void logmessage(char const *fmt, const char *a, int b) {
6646 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
6647 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
6648 // ...
6649 // }
6650 //
6651 // Yet another interaction that we need to support is calling a variadic
6652 // format function from a format function that has fixed arguments. For
6653 // instance:
6654 //
6655 // __attribute__((format(printf, 1, 2)))
6656 // void logstring(char const *fmt, char const *str) {
6657 // printf(fmt, str); /* do not emit a warning about "fmt" */
6658 // }
6659 //
6660 // Same (and perhaps more relatably) for the variadic template case:
6661 //
6662 // template<typename... Args>
6663 // __attribute__((format(printf, 1, 2)))
6664 // void log(const char *fmt, Args&&... args) {
6665 // printf(fmt, forward<Args>(args)...);
6666 // /* do not emit a warning about "fmt" */
6667 // }
6668 //
6669 // Due to implementation difficulty, we only check the format, not the
6670 // format arguments, in all cases.
6671 //
6672 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
6673 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
6674 for (const auto *PVFormatMatches :
6675 D->specific_attrs<FormatMatchesAttr>()) {
6676 Sema::FormatStringInfo CalleeFSI;
6677 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
6678 0, &CalleeFSI))
6679 continue;
6680 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
6681 // If using the wrong type of format string, emit a diagnostic
6682 // here and stop checking to avoid irrelevant diagnostics.
6683 if (Type != S.GetFormatStringType(PVFormatMatches)) {
6684 S.Diag(Args[format_idx]->getBeginLoc(),
6685 diag::warn_format_string_type_incompatible)
6686 << PVFormatMatches->getType()->getName()
6688 if (!InFunctionCall) {
6689 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
6690 diag::note_format_string_defined);
6691 }
6692 return SLCT_UncheckedLiteral;
6693 }
6694 return checkFormatStringExpr(
6695 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
6696 Args, APK, format_idx, firstDataArg, Type, CallType,
6697 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
6698 Offset, IgnoreStringsWithoutSpecifiers);
6699 }
6700 }
6701
6702 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
6703 Sema::FormatStringInfo CallerFSI;
6704 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
6705 PVFormat->getFirstArg(), &CallerFSI))
6706 continue;
6707 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
6708 // We also check if the formats are compatible.
6709 // We can't pass a 'scanf' string to a 'printf' function.
6710 if (Type != S.GetFormatStringType(PVFormat)) {
6711 S.Diag(Args[format_idx]->getBeginLoc(),
6712 diag::warn_format_string_type_incompatible)
6713 << PVFormat->getType()->getName()
6715 if (!InFunctionCall) {
6716 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
6717 }
6718 return SLCT_UncheckedLiteral;
6719 }
6720 // Lastly, check that argument passing kinds transition in a
6721 // way that makes sense:
6722 // from a caller with FAPK_VAList, allow FAPK_VAList
6723 // from a caller with FAPK_Fixed, allow FAPK_Fixed
6724 // from a caller with FAPK_Fixed, allow FAPK_Variadic
6725 // from a caller with FAPK_Variadic, allow FAPK_VAList
6726 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
6731 return SLCT_UncheckedLiteral;
6732 }
6733 }
6734 }
6735 }
6736 }
6737 }
6738
6739 return SLCT_NotALiteral;
6740 }
6741
6742 case Stmt::CallExprClass:
6743 case Stmt::CXXMemberCallExprClass: {
6744 const CallExpr *CE = cast<CallExpr>(E);
6745 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6746 bool IsFirst = true;
6747 StringLiteralCheckType CommonResult;
6748 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6749 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6750 StringLiteralCheckType Result = checkFormatStringExpr(
6751 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6752 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6753 Offset, IgnoreStringsWithoutSpecifiers);
6754 if (IsFirst) {
6755 CommonResult = Result;
6756 IsFirst = false;
6757 }
6758 }
6759 if (!IsFirst)
6760 return CommonResult;
6761
6762 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6763 unsigned BuiltinID = FD->getBuiltinID();
6764 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6765 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6766 const Expr *Arg = CE->getArg(0);
6767 return checkFormatStringExpr(
6768 S, ReferenceFormatString, Arg, Args, APK, format_idx,
6769 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6770 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6771 }
6772 }
6773 }
6774 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
6775 return checkFormatStringExpr(
6776 S, ReferenceFormatString, SLE, Args, APK, format_idx, firstDataArg,
6777 Type, CallType, /*InFunctionCall*/ false, CheckedVarArgs,
6778 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6779 return SLCT_NotALiteral;
6780 }
6781 case Stmt::ObjCMessageExprClass: {
6782 const auto *ME = cast<ObjCMessageExpr>(E);
6783 if (const auto *MD = ME->getMethodDecl()) {
6784 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6785 // As a special case heuristic, if we're using the method -[NSBundle
6786 // localizedStringForKey:value:table:], ignore any key strings that lack
6787 // format specifiers. The idea is that if the key doesn't have any
6788 // format specifiers then its probably just a key to map to the
6789 // localized strings. If it does have format specifiers though, then its
6790 // likely that the text of the key is the format string in the
6791 // programmer's language, and should be checked.
6792 const ObjCInterfaceDecl *IFace;
6793 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6794 IFace->getIdentifier()->isStr("NSBundle") &&
6795 MD->getSelector().isKeywordSelector(
6796 {"localizedStringForKey", "value", "table"})) {
6797 IgnoreStringsWithoutSpecifiers = true;
6798 }
6799
6800 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6801 return checkFormatStringExpr(
6802 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6803 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6804 Offset, IgnoreStringsWithoutSpecifiers);
6805 }
6806 }
6807
6808 return SLCT_NotALiteral;
6809 }
6810 case Stmt::ObjCStringLiteralClass:
6811 case Stmt::StringLiteralClass: {
6812 const StringLiteral *StrE = nullptr;
6813
6814 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6815 StrE = ObjCFExpr->getString();
6816 else
6817 StrE = cast<StringLiteral>(E);
6818
6819 if (StrE) {
6820 if (Offset.isNegative() || Offset > StrE->getLength()) {
6821 // TODO: It would be better to have an explicit warning for out of
6822 // bounds literals.
6823 return SLCT_NotALiteral;
6824 }
6825 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6826 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
6827 format_idx, firstDataArg, Type, InFunctionCall,
6828 CallType, CheckedVarArgs, UncoveredArg,
6829 IgnoreStringsWithoutSpecifiers);
6830 return SLCT_CheckedLiteral;
6831 }
6832
6833 return SLCT_NotALiteral;
6834 }
6835 case Stmt::BinaryOperatorClass: {
6836 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6837
6838 // A string literal + an int offset is still a string literal.
6839 if (BinOp->isAdditiveOp()) {
6840 Expr::EvalResult LResult, RResult;
6841
6842 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6843 LResult, S.Context, Expr::SE_NoSideEffects,
6845 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6846 RResult, S.Context, Expr::SE_NoSideEffects,
6848
6849 if (LIsInt != RIsInt) {
6850 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6851
6852 if (LIsInt) {
6853 if (BinOpKind == BO_Add) {
6854 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6855 E = BinOp->getRHS();
6856 goto tryAgain;
6857 }
6858 } else {
6859 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6860 E = BinOp->getLHS();
6861 goto tryAgain;
6862 }
6863 }
6864 }
6865
6866 return SLCT_NotALiteral;
6867 }
6868 case Stmt::UnaryOperatorClass: {
6869 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6870 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6871 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6872 Expr::EvalResult IndexResult;
6873 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6876 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6877 /*RHS is int*/ true);
6878 E = ASE->getBase();
6879 goto tryAgain;
6880 }
6881 }
6882
6883 return SLCT_NotALiteral;
6884 }
6885
6886 default:
6887 return SLCT_NotALiteral;
6888 }
6889}
6890
6891// If this expression can be evaluated at compile-time,
6892// check if the result is a StringLiteral and return it
6893// otherwise return nullptr
6895 const Expr *E) {
6896 Expr::EvalResult Result;
6897 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
6898 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
6899 if (isa_and_nonnull<StringLiteral>(LVE))
6900 return LVE;
6901 }
6902 return nullptr;
6903}
6904
6906 switch (FST) {
6908 return "scanf";
6910 return "printf";
6912 return "NSString";
6914 return "strftime";
6916 return "strfmon";
6918 return "kprintf";
6920 return "freebsd_kprintf";
6922 return "os_log";
6923 default:
6924 return "<unknown>";
6925 }
6926}
6927
6929 return llvm::StringSwitch<FormatStringType>(Flavor)
6930 .Cases("gnu_scanf", "scanf", FormatStringType::Scanf)
6931 .Cases("gnu_printf", "printf", "printf0", "syslog",
6933 .Cases("NSString", "CFString", FormatStringType::NSString)
6934 .Cases("gnu_strftime", "strftime", FormatStringType::Strftime)
6935 .Cases("gnu_strfmon", "strfmon", FormatStringType::Strfmon)
6936 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err",
6938 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
6939 .Case("os_trace", FormatStringType::OSLog)
6940 .Case("os_log", FormatStringType::OSLog)
6941 .Default(FormatStringType::Unknown);
6942}
6943
6945 return GetFormatStringType(Format->getType()->getName());
6946}
6947
6948FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
6949 return GetFormatStringType(Format->getType()->getName());
6950}
6951
6952bool Sema::CheckFormatArguments(const FormatAttr *Format,
6953 ArrayRef<const Expr *> Args, bool IsCXXMember,
6954 VariadicCallType CallType, SourceLocation Loc,
6955 SourceRange Range,
6956 llvm::SmallBitVector &CheckedVarArgs) {
6957 FormatStringInfo FSI;
6958 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
6959 IsCXXMember,
6960 CallType != VariadicCallType::DoesNotApply, &FSI))
6961 return CheckFormatArguments(
6962 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
6963 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
6964 return false;
6965}
6966
6967bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
6968 ArrayRef<const Expr *> Args, bool IsCXXMember,
6969 VariadicCallType CallType, SourceLocation Loc,
6970 SourceRange Range,
6971 llvm::SmallBitVector &CheckedVarArgs) {
6972 FormatStringInfo FSI;
6973 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
6974 &FSI)) {
6975 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
6976 return CheckFormatArguments(Args, FSI.ArgPassingKind,
6977 Format->getFormatString(), FSI.FormatIdx,
6978 FSI.FirstDataArg, GetFormatStringType(Format),
6979 CallType, Loc, Range, CheckedVarArgs);
6980 }
6981 return false;
6982}
6983
6984bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6986 const StringLiteral *ReferenceFormatString,
6987 unsigned format_idx, unsigned firstDataArg,
6989 VariadicCallType CallType, SourceLocation Loc,
6990 SourceRange Range,
6991 llvm::SmallBitVector &CheckedVarArgs) {
6992 // CHECK: printf/scanf-like function is called with no format string.
6993 if (format_idx >= Args.size()) {
6994 Diag(Loc, diag::warn_missing_format_string) << Range;
6995 return false;
6996 }
6997
6998 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6999
7000 // CHECK: format string is not a string literal.
7001 //
7002 // Dynamically generated format strings are difficult to
7003 // automatically vet at compile time. Requiring that format strings
7004 // are string literals: (1) permits the checking of format strings by
7005 // the compiler and thereby (2) can practically remove the source of
7006 // many format string exploits.
7007
7008 // Format string can be either ObjC string (e.g. @"%d") or
7009 // C string (e.g. "%d")
7010 // ObjC string uses the same format specifiers as C string, so we can use
7011 // the same format string checking logic for both ObjC and C strings.
7012 UncoveredArgHandler UncoveredArg;
7013 StringLiteralCheckType CT = checkFormatStringExpr(
7014 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
7015 firstDataArg, Type, CallType,
7016 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
7017 /*no string offset*/ llvm::APSInt(64, false) = 0);
7018
7019 // Generate a diagnostic where an uncovered argument is detected.
7020 if (UncoveredArg.hasUncoveredArg()) {
7021 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7022 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7023 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7024 }
7025
7026 if (CT != SLCT_NotALiteral)
7027 // Literal format string found, check done!
7028 return CT == SLCT_CheckedLiteral;
7029
7030 // Strftime is particular as it always uses a single 'time' argument,
7031 // so it is safe to pass a non-literal string.
7033 return false;
7034
7035 // Do not emit diag when the string param is a macro expansion and the
7036 // format is either NSString or CFString. This is a hack to prevent
7037 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7038 // which are usually used in place of NS and CF string literals.
7039 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7041 SourceMgr.isInSystemMacro(FormatLoc))
7042 return false;
7043
7044 // If there are no arguments specified, warn with -Wformat-security, otherwise
7045 // warn only with -Wformat-nonliteral.
7046 if (Args.size() == firstDataArg) {
7047 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7048 << OrigFormatExpr->getSourceRange();
7049 switch (Type) {
7050 default:
7051 break;
7055 Diag(FormatLoc, diag::note_format_security_fixit)
7056 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7057 break;
7059 Diag(FormatLoc, diag::note_format_security_fixit)
7060 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7061 break;
7062 }
7063 } else {
7064 Diag(FormatLoc, diag::warn_format_nonliteral)
7065 << OrigFormatExpr->getSourceRange();
7066 }
7067 return false;
7068}
7069
7070namespace {
7071
7072class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7073protected:
7074 Sema &S;
7075 const FormatStringLiteral *FExpr;
7076 const Expr *OrigFormatExpr;
7077 const FormatStringType FSType;
7078 const unsigned FirstDataArg;
7079 const unsigned NumDataArgs;
7080 const char *Beg; // Start of format string.
7081 const Sema::FormatArgumentPassingKind ArgPassingKind;
7082 ArrayRef<const Expr *> Args;
7083 unsigned FormatIdx;
7084 llvm::SmallBitVector CoveredArgs;
7085 bool usesPositionalArgs = false;
7086 bool atFirstArg = true;
7087 bool inFunctionCall;
7088 VariadicCallType CallType;
7089 llvm::SmallBitVector &CheckedVarArgs;
7090 UncoveredArgHandler &UncoveredArg;
7091
7092public:
7093 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7094 const Expr *origFormatExpr, const FormatStringType type,
7095 unsigned firstDataArg, unsigned numDataArgs,
7096 const char *beg, Sema::FormatArgumentPassingKind APK,
7097 ArrayRef<const Expr *> Args, unsigned formatIdx,
7098 bool inFunctionCall, VariadicCallType callType,
7099 llvm::SmallBitVector &CheckedVarArgs,
7100 UncoveredArgHandler &UncoveredArg)
7101 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7102 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7103 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7104 inFunctionCall(inFunctionCall), CallType(callType),
7105 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7106 CoveredArgs.resize(numDataArgs);
7107 CoveredArgs.reset();
7108 }
7109
7110 bool HasFormatArguments() const {
7111 return ArgPassingKind == Sema::FAPK_Fixed ||
7112 ArgPassingKind == Sema::FAPK_Variadic;
7113 }
7114
7115 void DoneProcessing();
7116
7117 void HandleIncompleteSpecifier(const char *startSpecifier,
7118 unsigned specifierLen) override;
7119
7120 void HandleInvalidLengthModifier(
7121 const analyze_format_string::FormatSpecifier &FS,
7122 const analyze_format_string::ConversionSpecifier &CS,
7123 const char *startSpecifier, unsigned specifierLen,
7124 unsigned DiagID);
7125
7126 void HandleNonStandardLengthModifier(
7127 const analyze_format_string::FormatSpecifier &FS,
7128 const char *startSpecifier, unsigned specifierLen);
7129
7130 void HandleNonStandardConversionSpecifier(
7131 const analyze_format_string::ConversionSpecifier &CS,
7132 const char *startSpecifier, unsigned specifierLen);
7133
7134 void HandlePosition(const char *startPos, unsigned posLen) override;
7135
7136 void HandleInvalidPosition(const char *startSpecifier,
7137 unsigned specifierLen,
7139
7140 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7141
7142 void HandleNullChar(const char *nullCharacter) override;
7143
7144 template <typename Range>
7145 static void
7146 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7147 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7148 bool IsStringLocation, Range StringRange,
7149 ArrayRef<FixItHint> Fixit = {});
7150
7151protected:
7152 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7153 const char *startSpec,
7154 unsigned specifierLen,
7155 const char *csStart, unsigned csLen);
7156
7157 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7158 const char *startSpec,
7159 unsigned specifierLen);
7160
7161 SourceRange getFormatStringRange();
7162 CharSourceRange getSpecifierRange(const char *startSpecifier,
7163 unsigned specifierLen);
7164 SourceLocation getLocationOfByte(const char *x);
7165
7166 const Expr *getDataArg(unsigned i) const;
7167
7168 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7169 const analyze_format_string::ConversionSpecifier &CS,
7170 const char *startSpecifier, unsigned specifierLen,
7171 unsigned argIndex);
7172
7173 template <typename Range>
7174 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7175 bool IsStringLocation, Range StringRange,
7176 ArrayRef<FixItHint> Fixit = {});
7177};
7178
7179} // namespace
7180
7181SourceRange CheckFormatHandler::getFormatStringRange() {
7182 return OrigFormatExpr->getSourceRange();
7183}
7184
7185CharSourceRange CheckFormatHandler::
7186getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7187 SourceLocation Start = getLocationOfByte(startSpecifier);
7188 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7189
7190 // Advance the end SourceLocation by one due to half-open ranges.
7191 End = End.getLocWithOffset(1);
7192
7193 return CharSourceRange::getCharRange(Start, End);
7194}
7195
7196SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7197 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7199}
7200
7201void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7202 unsigned specifierLen){
7203 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7204 getLocationOfByte(startSpecifier),
7205 /*IsStringLocation*/true,
7206 getSpecifierRange(startSpecifier, specifierLen));
7207}
7208
7209void CheckFormatHandler::HandleInvalidLengthModifier(
7212 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7213 using namespace analyze_format_string;
7214
7215 const LengthModifier &LM = FS.getLengthModifier();
7216 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7217
7218 // See if we know how to fix this length modifier.
7219 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7220 if (FixedLM) {
7221 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7222 getLocationOfByte(LM.getStart()),
7223 /*IsStringLocation*/true,
7224 getSpecifierRange(startSpecifier, specifierLen));
7225
7226 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7227 << FixedLM->toString()
7228 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7229
7230 } else {
7231 FixItHint Hint;
7232 if (DiagID == diag::warn_format_nonsensical_length)
7233 Hint = FixItHint::CreateRemoval(LMRange);
7234
7235 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7236 getLocationOfByte(LM.getStart()),
7237 /*IsStringLocation*/true,
7238 getSpecifierRange(startSpecifier, specifierLen),
7239 Hint);
7240 }
7241}
7242
7243void CheckFormatHandler::HandleNonStandardLengthModifier(
7245 const char *startSpecifier, unsigned specifierLen) {
7246 using namespace analyze_format_string;
7247
7248 const LengthModifier &LM = FS.getLengthModifier();
7249 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7250
7251 // See if we know how to fix this length modifier.
7252 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7253 if (FixedLM) {
7254 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7255 << LM.toString() << 0,
7256 getLocationOfByte(LM.getStart()),
7257 /*IsStringLocation*/true,
7258 getSpecifierRange(startSpecifier, specifierLen));
7259
7260 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7261 << FixedLM->toString()
7262 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7263
7264 } else {
7265 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7266 << LM.toString() << 0,
7267 getLocationOfByte(LM.getStart()),
7268 /*IsStringLocation*/true,
7269 getSpecifierRange(startSpecifier, specifierLen));
7270 }
7271}
7272
7273void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7275 const char *startSpecifier, unsigned specifierLen) {
7276 using namespace analyze_format_string;
7277
7278 // See if we know how to fix this conversion specifier.
7279 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7280 if (FixedCS) {
7281 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7282 << CS.toString() << /*conversion specifier*/1,
7283 getLocationOfByte(CS.getStart()),
7284 /*IsStringLocation*/true,
7285 getSpecifierRange(startSpecifier, specifierLen));
7286
7287 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7288 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7289 << FixedCS->toString()
7290 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7291 } else {
7292 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7293 << CS.toString() << /*conversion specifier*/1,
7294 getLocationOfByte(CS.getStart()),
7295 /*IsStringLocation*/true,
7296 getSpecifierRange(startSpecifier, specifierLen));
7297 }
7298}
7299
7300void CheckFormatHandler::HandlePosition(const char *startPos,
7301 unsigned posLen) {
7302 if (!S.getDiagnostics().isIgnored(
7303 diag::warn_format_non_standard_positional_arg, SourceLocation()))
7304 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7305 getLocationOfByte(startPos),
7306 /*IsStringLocation*/ true,
7307 getSpecifierRange(startPos, posLen));
7308}
7309
7310void CheckFormatHandler::HandleInvalidPosition(
7311 const char *startSpecifier, unsigned specifierLen,
7313 if (!S.getDiagnostics().isIgnored(
7314 diag::warn_format_invalid_positional_specifier, SourceLocation()))
7315 EmitFormatDiagnostic(
7316 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
7317 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
7318 getSpecifierRange(startSpecifier, specifierLen));
7319}
7320
7321void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7322 unsigned posLen) {
7323 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
7324 SourceLocation()))
7325 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7326 getLocationOfByte(startPos),
7327 /*IsStringLocation*/ true,
7328 getSpecifierRange(startPos, posLen));
7329}
7330
7331void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7332 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7333 // The presence of a null character is likely an error.
7334 EmitFormatDiagnostic(
7335 S.PDiag(diag::warn_printf_format_string_contains_null_char),
7336 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7337 getFormatStringRange());
7338 }
7339}
7340
7341// Note that this may return NULL if there was an error parsing or building
7342// one of the argument expressions.
7343const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7344 return Args[FirstDataArg + i];
7345}
7346
7347void CheckFormatHandler::DoneProcessing() {
7348 // Does the number of data arguments exceed the number of
7349 // format conversions in the format string?
7350 if (HasFormatArguments()) {
7351 // Find any arguments that weren't covered.
7352 CoveredArgs.flip();
7353 signed notCoveredArg = CoveredArgs.find_first();
7354 if (notCoveredArg >= 0) {
7355 assert((unsigned)notCoveredArg < NumDataArgs);
7356 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7357 } else {
7358 UncoveredArg.setAllCovered();
7359 }
7360 }
7361}
7362
7363void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7364 const Expr *ArgExpr) {
7365 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
7366 "Invalid state");
7367
7368 if (!ArgExpr)
7369 return;
7370
7371 SourceLocation Loc = ArgExpr->getBeginLoc();
7372
7373 if (S.getSourceManager().isInSystemMacro(Loc))
7374 return;
7375
7376 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7377 for (auto E : DiagnosticExprs)
7378 PDiag << E->getSourceRange();
7379
7380 CheckFormatHandler::EmitFormatDiagnostic(
7381 S, IsFunctionCall, DiagnosticExprs[0],
7382 PDiag, Loc, /*IsStringLocation*/false,
7383 DiagnosticExprs[0]->getSourceRange());
7384}
7385
7386bool
7387CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7388 SourceLocation Loc,
7389 const char *startSpec,
7390 unsigned specifierLen,
7391 const char *csStart,
7392 unsigned csLen) {
7393 bool keepGoing = true;
7394 if (argIndex < NumDataArgs) {
7395 // Consider the argument coverered, even though the specifier doesn't
7396 // make sense.
7397 CoveredArgs.set(argIndex);
7398 }
7399 else {
7400 // If argIndex exceeds the number of data arguments we
7401 // don't issue a warning because that is just a cascade of warnings (and
7402 // they may have intended '%%' anyway). We don't want to continue processing
7403 // the format string after this point, however, as we will like just get
7404 // gibberish when trying to match arguments.
7405 keepGoing = false;
7406 }
7407
7408 StringRef Specifier(csStart, csLen);
7409
7410 // If the specifier in non-printable, it could be the first byte of a UTF-8
7411 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7412 // hex value.
7413 std::string CodePointStr;
7414 if (!llvm::sys::locale::isPrint(*csStart)) {
7415 llvm::UTF32 CodePoint;
7416 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7417 const llvm::UTF8 *E =
7418 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7419 llvm::ConversionResult Result =
7420 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7421
7422 if (Result != llvm::conversionOK) {
7423 unsigned char FirstChar = *csStart;
7424 CodePoint = (llvm::UTF32)FirstChar;
7425 }
7426
7427 llvm::raw_string_ostream OS(CodePointStr);
7428 if (CodePoint < 256)
7429 OS << "\\x" << llvm::format("%02x", CodePoint);
7430 else if (CodePoint <= 0xFFFF)
7431 OS << "\\u" << llvm::format("%04x", CodePoint);
7432 else
7433 OS << "\\U" << llvm::format("%08x", CodePoint);
7434 Specifier = CodePointStr;
7435 }
7436
7437 EmitFormatDiagnostic(
7438 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7439 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7440
7441 return keepGoing;
7442}
7443
7444void
7445CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7446 const char *startSpec,
7447 unsigned specifierLen) {
7448 EmitFormatDiagnostic(
7449 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7450 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7451}
7452
7453bool
7454CheckFormatHandler::CheckNumArgs(
7457 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7458
7459 if (HasFormatArguments() && argIndex >= NumDataArgs) {
7461 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7462 << (argIndex+1) << NumDataArgs)
7463 : S.PDiag(diag::warn_printf_insufficient_data_args);
7464 EmitFormatDiagnostic(
7465 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7466 getSpecifierRange(startSpecifier, specifierLen));
7467
7468 // Since more arguments than conversion tokens are given, by extension
7469 // all arguments are covered, so mark this as so.
7470 UncoveredArg.setAllCovered();
7471 return false;
7472 }
7473 return true;
7474}
7475
7476template<typename Range>
7477void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7478 SourceLocation Loc,
7479 bool IsStringLocation,
7480 Range StringRange,
7481 ArrayRef<FixItHint> FixIt) {
7482 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7483 Loc, IsStringLocation, StringRange, FixIt);
7484}
7485
7486/// If the format string is not within the function call, emit a note
7487/// so that the function call and string are in diagnostic messages.
7488///
7489/// \param InFunctionCall if true, the format string is within the function
7490/// call and only one diagnostic message will be produced. Otherwise, an
7491/// extra note will be emitted pointing to location of the format string.
7492///
7493/// \param ArgumentExpr the expression that is passed as the format string
7494/// argument in the function call. Used for getting locations when two
7495/// diagnostics are emitted.
7496///
7497/// \param PDiag the callee should already have provided any strings for the
7498/// diagnostic message. This function only adds locations and fixits
7499/// to diagnostics.
7500///
7501/// \param Loc primary location for diagnostic. If two diagnostics are
7502/// required, one will be at Loc and a new SourceLocation will be created for
7503/// the other one.
7504///
7505/// \param IsStringLocation if true, Loc points to the format string should be
7506/// used for the note. Otherwise, Loc points to the argument list and will
7507/// be used with PDiag.
7508///
7509/// \param StringRange some or all of the string to highlight. This is
7510/// templated so it can accept either a CharSourceRange or a SourceRange.
7511///
7512/// \param FixIt optional fix it hint for the format string.
7513template <typename Range>
7514void CheckFormatHandler::EmitFormatDiagnostic(
7515 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7516 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7517 Range StringRange, ArrayRef<FixItHint> FixIt) {
7518 if (InFunctionCall) {
7519 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7520 D << StringRange;
7521 D << FixIt;
7522 } else {
7523 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7524 << ArgumentExpr->getSourceRange();
7525
7527 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7528 diag::note_format_string_defined);
7529
7530 Note << StringRange;
7531 Note << FixIt;
7532 }
7533}
7534
7535//===--- CHECK: Printf format string checking -----------------------------===//
7536
7537namespace {
7538
7539class CheckPrintfHandler : public CheckFormatHandler {
7540public:
7541 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7542 const Expr *origFormatExpr, const FormatStringType type,
7543 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
7544 const char *beg, Sema::FormatArgumentPassingKind APK,
7545 ArrayRef<const Expr *> Args, unsigned formatIdx,
7546 bool inFunctionCall, VariadicCallType CallType,
7547 llvm::SmallBitVector &CheckedVarArgs,
7548 UncoveredArgHandler &UncoveredArg)
7549 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7550 numDataArgs, beg, APK, Args, formatIdx,
7551 inFunctionCall, CallType, CheckedVarArgs,
7552 UncoveredArg) {}
7553
7554 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
7555
7556 /// Returns true if '%@' specifiers are allowed in the format string.
7557 bool allowsObjCArg() const {
7558 return FSType == FormatStringType::NSString ||
7559 FSType == FormatStringType::OSLog ||
7560 FSType == FormatStringType::OSTrace;
7561 }
7562
7563 bool HandleInvalidPrintfConversionSpecifier(
7564 const analyze_printf::PrintfSpecifier &FS,
7565 const char *startSpecifier,
7566 unsigned specifierLen) override;
7567
7568 void handleInvalidMaskType(StringRef MaskType) override;
7569
7570 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7571 const char *startSpecifier, unsigned specifierLen,
7572 const TargetInfo &Target) override;
7573 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7574 const char *StartSpecifier,
7575 unsigned SpecifierLen,
7576 const Expr *E);
7577
7578 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7579 const char *startSpecifier, unsigned specifierLen);
7580 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7581 const analyze_printf::OptionalAmount &Amt,
7582 unsigned type,
7583 const char *startSpecifier, unsigned specifierLen);
7584 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7585 const analyze_printf::OptionalFlag &flag,
7586 const char *startSpecifier, unsigned specifierLen);
7587 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7588 const analyze_printf::OptionalFlag &ignoredFlag,
7589 const analyze_printf::OptionalFlag &flag,
7590 const char *startSpecifier, unsigned specifierLen);
7591 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7592 const Expr *E);
7593
7594 void HandleEmptyObjCModifierFlag(const char *startFlag,
7595 unsigned flagLen) override;
7596
7597 void HandleInvalidObjCModifierFlag(const char *startFlag,
7598 unsigned flagLen) override;
7599
7600 void
7601 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7602 const char *flagsEnd,
7603 const char *conversionPosition) override;
7604};
7605
7606/// Keeps around the information needed to verify that two specifiers are
7607/// compatible.
7608class EquatableFormatArgument {
7609public:
7610 enum SpecifierSensitivity : unsigned {
7611 SS_None,
7612 SS_Private,
7613 SS_Public,
7614 SS_Sensitive
7615 };
7616
7617 enum FormatArgumentRole : unsigned {
7618 FAR_Data,
7619 FAR_FieldWidth,
7620 FAR_Precision,
7621 FAR_Auxiliary, // FreeBSD kernel %b and %D
7622 };
7623
7624private:
7625 analyze_format_string::ArgType ArgType;
7627 StringRef SpecifierLetter;
7628 CharSourceRange Range;
7629 SourceLocation ElementLoc;
7630 FormatArgumentRole Role : 2;
7631 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
7632 unsigned Position : 14;
7633 unsigned ModifierFor : 14; // not set for FAR_Data
7634
7635 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
7636 bool InFunctionCall) const;
7637
7638public:
7639 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
7641 StringRef SpecifierLetter,
7642 analyze_format_string::ArgType ArgType,
7643 FormatArgumentRole Role,
7644 SpecifierSensitivity Sensitivity, unsigned Position,
7645 unsigned ModifierFor)
7646 : ArgType(ArgType), LengthMod(LengthMod),
7647 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
7648 Role(Role), Sensitivity(Sensitivity), Position(Position),
7649 ModifierFor(ModifierFor) {}
7650
7651 unsigned getPosition() const { return Position; }
7652 SourceLocation getSourceLocation() const { return ElementLoc; }
7653 CharSourceRange getSourceRange() const { return Range; }
7654 analyze_format_string::LengthModifier getLengthModifier() const {
7655 return analyze_format_string::LengthModifier(nullptr, LengthMod);
7656 }
7657 void setModifierFor(unsigned V) { ModifierFor = V; }
7658
7659 std::string buildFormatSpecifier() const {
7660 std::string result;
7661 llvm::raw_string_ostream(result)
7662 << getLengthModifier().toString() << SpecifierLetter;
7663 return result;
7664 }
7665
7666 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
7667 const Expr *FmtExpr, bool InFunctionCall) const;
7668};
7669
7670/// Turns format strings into lists of EquatableSpecifier objects.
7671class DecomposePrintfHandler : public CheckPrintfHandler {
7672 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
7673 bool HadError;
7674
7675 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7676 const Expr *origFormatExpr,
7677 const FormatStringType type, unsigned firstDataArg,
7678 unsigned numDataArgs, bool isObjC, const char *beg,
7680 ArrayRef<const Expr *> Args, unsigned formatIdx,
7681 bool inFunctionCall, VariadicCallType CallType,
7682 llvm::SmallBitVector &CheckedVarArgs,
7683 UncoveredArgHandler &UncoveredArg,
7684 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
7685 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7686 numDataArgs, isObjC, beg, APK, Args, formatIdx,
7687 inFunctionCall, CallType, CheckedVarArgs,
7688 UncoveredArg),
7689 Specs(Specs), HadError(false) {}
7690
7691public:
7692 static bool
7693 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
7694 FormatStringType type, bool IsObjC, bool InFunctionCall,
7695 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
7696
7697 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7698 const char *startSpecifier,
7699 unsigned specifierLen,
7700 const TargetInfo &Target) override;
7701};
7702
7703} // namespace
7704
7705bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7706 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
7707 unsigned specifierLen) {
7710
7711 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7712 getLocationOfByte(CS.getStart()),
7713 startSpecifier, specifierLen,
7714 CS.getStart(), CS.getLength());
7715}
7716
7717void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7718 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7719}
7720
7721// Error out if struct or complex type argments are passed to os_log.
7723 QualType T) {
7724 if (FSType != FormatStringType::OSLog)
7725 return false;
7726 return T->isRecordType() || T->isComplexType();
7727}
7728
7729bool CheckPrintfHandler::HandleAmount(
7730 const analyze_format_string::OptionalAmount &Amt, unsigned k,
7731 const char *startSpecifier, unsigned specifierLen) {
7732 if (Amt.hasDataArgument()) {
7733 if (HasFormatArguments()) {
7734 unsigned argIndex = Amt.getArgIndex();
7735 if (argIndex >= NumDataArgs) {
7736 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7737 << k,
7738 getLocationOfByte(Amt.getStart()),
7739 /*IsStringLocation*/ true,
7740 getSpecifierRange(startSpecifier, specifierLen));
7741 // Don't do any more checking. We will just emit
7742 // spurious errors.
7743 return false;
7744 }
7745
7746 // Type check the data argument. It should be an 'int'.
7747 // Although not in conformance with C99, we also allow the argument to be
7748 // an 'unsigned int' as that is a reasonably safe case. GCC also
7749 // doesn't emit a warning for that case.
7750 CoveredArgs.set(argIndex);
7751 const Expr *Arg = getDataArg(argIndex);
7752 if (!Arg)
7753 return false;
7754
7755 QualType T = Arg->getType();
7756
7757 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7758 assert(AT.isValid());
7759
7760 if (!AT.matchesType(S.Context, T)) {
7761 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
7762 ? diag::err_printf_asterisk_wrong_type
7763 : diag::warn_printf_asterisk_wrong_type;
7764 EmitFormatDiagnostic(S.PDiag(DiagID)
7766 << T << Arg->getSourceRange(),
7767 getLocationOfByte(Amt.getStart()),
7768 /*IsStringLocation*/ true,
7769 getSpecifierRange(startSpecifier, specifierLen));
7770 // Don't do any more checking. We will just emit
7771 // spurious errors.
7772 return false;
7773 }
7774 }
7775 }
7776 return true;
7777}
7778
7779void CheckPrintfHandler::HandleInvalidAmount(
7782 unsigned type,
7783 const char *startSpecifier,
7784 unsigned specifierLen) {
7787
7788 FixItHint fixit =
7790 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7791 Amt.getConstantLength()))
7792 : FixItHint();
7793
7794 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7795 << type << CS.toString(),
7796 getLocationOfByte(Amt.getStart()),
7797 /*IsStringLocation*/true,
7798 getSpecifierRange(startSpecifier, specifierLen),
7799 fixit);
7800}
7801
7802void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7803 const analyze_printf::OptionalFlag &flag,
7804 const char *startSpecifier,
7805 unsigned specifierLen) {
7806 // Warn about pointless flag with a fixit removal.
7809 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7810 << flag.toString() << CS.toString(),
7811 getLocationOfByte(flag.getPosition()),
7812 /*IsStringLocation*/true,
7813 getSpecifierRange(startSpecifier, specifierLen),
7815 getSpecifierRange(flag.getPosition(), 1)));
7816}
7817
7818void CheckPrintfHandler::HandleIgnoredFlag(
7820 const analyze_printf::OptionalFlag &ignoredFlag,
7821 const analyze_printf::OptionalFlag &flag,
7822 const char *startSpecifier,
7823 unsigned specifierLen) {
7824 // Warn about ignored flag with a fixit removal.
7825 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7826 << ignoredFlag.toString() << flag.toString(),
7827 getLocationOfByte(ignoredFlag.getPosition()),
7828 /*IsStringLocation*/true,
7829 getSpecifierRange(startSpecifier, specifierLen),
7831 getSpecifierRange(ignoredFlag.getPosition(), 1)));
7832}
7833
7834void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7835 unsigned flagLen) {
7836 // Warn about an empty flag.
7837 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7838 getLocationOfByte(startFlag),
7839 /*IsStringLocation*/true,
7840 getSpecifierRange(startFlag, flagLen));
7841}
7842
7843void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7844 unsigned flagLen) {
7845 // Warn about an invalid flag.
7846 auto Range = getSpecifierRange(startFlag, flagLen);
7847 StringRef flag(startFlag, flagLen);
7848 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7849 getLocationOfByte(startFlag),
7850 /*IsStringLocation*/true,
7851 Range, FixItHint::CreateRemoval(Range));
7852}
7853
7854void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7855 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7856 // Warn about using '[...]' without a '@' conversion.
7857 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7858 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7859 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7860 getLocationOfByte(conversionPosition),
7861 /*IsStringLocation*/ true, Range,
7863}
7864
7865void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
7866 const Expr *FmtExpr,
7867 bool InFunctionCall) const {
7868 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
7869 ElementLoc, true, Range);
7870}
7871
7872bool EquatableFormatArgument::VerifyCompatible(
7873 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
7874 bool InFunctionCall) const {
7876 if (Role != Other.Role) {
7877 // diagnose and stop
7878 EmitDiagnostic(
7879 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
7880 FmtExpr, InFunctionCall);
7881 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
7882 return false;
7883 }
7884
7885 if (Role != FAR_Data) {
7886 if (ModifierFor != Other.ModifierFor) {
7887 // diagnose and stop
7888 EmitDiagnostic(S,
7889 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
7890 << (ModifierFor + 1) << (Other.ModifierFor + 1),
7891 FmtExpr, InFunctionCall);
7892 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
7893 return false;
7894 }
7895 return true;
7896 }
7897
7898 bool HadError = false;
7899 if (Sensitivity != Other.Sensitivity) {
7900 // diagnose and continue
7901 EmitDiagnostic(S,
7902 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
7903 << Sensitivity << Other.Sensitivity,
7904 FmtExpr, InFunctionCall);
7905 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7906 << 0 << Other.Range;
7907 }
7908
7909 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
7910 case MK::Match:
7911 break;
7912
7913 case MK::MatchPromotion:
7914 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
7915 // MatchPromotion is treated as a failure by format_matches.
7916 case MK::NoMatch:
7917 case MK::NoMatchTypeConfusion:
7918 case MK::NoMatchPromotionTypeConfusion:
7919 EmitDiagnostic(S,
7920 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
7921 << buildFormatSpecifier()
7922 << Other.buildFormatSpecifier(),
7923 FmtExpr, InFunctionCall);
7924 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7925 << 0 << Other.Range;
7926 break;
7927
7928 case MK::NoMatchPedantic:
7929 EmitDiagnostic(S,
7930 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
7931 << buildFormatSpecifier()
7932 << Other.buildFormatSpecifier(),
7933 FmtExpr, InFunctionCall);
7934 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7935 << 0 << Other.Range;
7936 break;
7937
7938 case MK::NoMatchSignedness:
7939 EmitDiagnostic(S,
7940 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
7941 << buildFormatSpecifier()
7942 << Other.buildFormatSpecifier(),
7943 FmtExpr, InFunctionCall);
7944 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7945 << 0 << Other.Range;
7946 break;
7947 }
7948 return !HadError;
7949}
7950
7951bool DecomposePrintfHandler::GetSpecifiers(
7952 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
7953 FormatStringType Type, bool IsObjC, bool InFunctionCall,
7955 StringRef Data = FSL->getString();
7956 const char *Str = Data.data();
7957 llvm::SmallBitVector BV;
7958 UncoveredArgHandler UA;
7959 const Expr *PrintfArgs[] = {FSL->getFormatString()};
7960 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
7961 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
7962 InFunctionCall, VariadicCallType::DoesNotApply, BV,
7963 UA, Args);
7964
7966 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
7968 H.DoneProcessing();
7969 if (H.HadError)
7970 return false;
7971
7972 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
7973 const EquatableFormatArgument &B) {
7974 return A.getPosition() < B.getPosition();
7975 });
7976 return true;
7977}
7978
7979bool DecomposePrintfHandler::HandlePrintfSpecifier(
7980 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
7981 unsigned specifierLen, const TargetInfo &Target) {
7982 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
7983 specifierLen, Target)) {
7984 HadError = true;
7985 return false;
7986 }
7987
7988 // Do not add any specifiers to the list for %%. This is possibly incorrect
7989 // if using a precision/width with a data argument, but that combination is
7990 // meaningless and we wouldn't know which format to attach the
7991 // precision/width to.
7992 const auto &CS = FS.getConversionSpecifier();
7994 return true;
7995
7996 // have to patch these to have the right ModifierFor if they are used
7997 const unsigned Unset = ~0;
7998 unsigned FieldWidthIndex = Unset;
7999 unsigned PrecisionIndex = Unset;
8000
8001 // field width?
8002 const auto &FieldWidth = FS.getFieldWidth();
8003 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8004 FieldWidthIndex = Specs.size();
8005 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8006 getLocationOfByte(FieldWidth.getStart()),
8008 FieldWidth.getArgType(S.Context),
8009 EquatableFormatArgument::FAR_FieldWidth,
8010 EquatableFormatArgument::SS_None,
8011 FieldWidth.usesPositionalArg()
8012 ? FieldWidth.getPositionalArgIndex() - 1
8013 : FieldWidthIndex,
8014 0);
8015 }
8016 // precision?
8017 const auto &Precision = FS.getPrecision();
8018 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8019 PrecisionIndex = Specs.size();
8020 Specs.emplace_back(
8021 getSpecifierRange(startSpecifier, specifierLen),
8022 getLocationOfByte(Precision.getStart()),
8024 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
8025 EquatableFormatArgument::SS_None,
8026 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8027 : PrecisionIndex,
8028 0);
8029 }
8030
8031 // this specifier
8032 unsigned SpecIndex =
8033 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8034 if (FieldWidthIndex != Unset)
8035 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8036 if (PrecisionIndex != Unset)
8037 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8038
8039 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8040 if (FS.isPrivate())
8041 Sensitivity = EquatableFormatArgument::SS_Private;
8042 else if (FS.isPublic())
8043 Sensitivity = EquatableFormatArgument::SS_Public;
8044 else if (FS.isSensitive())
8045 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8046 else
8047 Sensitivity = EquatableFormatArgument::SS_None;
8048
8049 Specs.emplace_back(
8050 getSpecifierRange(startSpecifier, specifierLen),
8051 getLocationOfByte(CS.getStart()), FS.getLengthModifier().getKind(),
8052 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
8053 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
8054
8055 // auxiliary argument?
8058 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8059 getLocationOfByte(CS.getStart()),
8061 CS.getCharacters(),
8063 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
8064 SpecIndex + 1, SpecIndex);
8065 }
8066 return true;
8067}
8068
8069// Determines if the specified is a C++ class or struct containing
8070// a member with the specified name and kind (e.g. a CXXMethodDecl named
8071// "c_str()").
8072template<typename MemberKind>
8074CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8075 auto *RD = Ty->getAsCXXRecordDecl();
8077
8078 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8079 return Results;
8080
8081 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8084
8085 // We just need to include all members of the right kind turned up by the
8086 // filter, at this point.
8087 if (S.LookupQualifiedName(R, RD))
8088 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8089 NamedDecl *decl = (*I)->getUnderlyingDecl();
8090 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8091 Results.insert(FK);
8092 }
8093 return Results;
8094}
8095
8096/// Check if we could call '.c_str()' on an object.
8097///
8098/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8099/// allow the call, or if it would be ambiguous).
8101 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8102
8103 MethodSet Results =
8104 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8105 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8106 MI != ME; ++MI)
8107 if ((*MI)->getMinRequiredArguments() == 0)
8108 return true;
8109 return false;
8110}
8111
8112// Check if a (w)string was passed when a (w)char* was needed, and offer a
8113// better diagnostic if so. AT is assumed to be valid.
8114// Returns true when a c_str() conversion method is found.
8115bool CheckPrintfHandler::checkForCStrMembers(
8116 const analyze_printf::ArgType &AT, const Expr *E) {
8117 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8118
8119 MethodSet Results =
8121
8122 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8123 MI != ME; ++MI) {
8124 const CXXMethodDecl *Method = *MI;
8125 if (Method->getMinRequiredArguments() == 0 &&
8126 AT.matchesType(S.Context, Method->getReturnType())) {
8127 // FIXME: Suggest parens if the expression needs them.
8129 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8130 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8131 return true;
8132 }
8133 }
8134
8135 return false;
8136}
8137
8138bool CheckPrintfHandler::HandlePrintfSpecifier(
8139 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8140 unsigned specifierLen, const TargetInfo &Target) {
8141 using namespace analyze_format_string;
8142 using namespace analyze_printf;
8143
8144 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8145
8146 if (FS.consumesDataArgument()) {
8147 if (atFirstArg) {
8148 atFirstArg = false;
8149 usesPositionalArgs = FS.usesPositionalArg();
8150 }
8151 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8152 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8153 startSpecifier, specifierLen);
8154 return false;
8155 }
8156 }
8157
8158 // First check if the field width, precision, and conversion specifier
8159 // have matching data arguments.
8160 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8161 startSpecifier, specifierLen)) {
8162 return false;
8163 }
8164
8165 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8166 startSpecifier, specifierLen)) {
8167 return false;
8168 }
8169
8170 if (!CS.consumesDataArgument()) {
8171 // FIXME: Technically specifying a precision or field width here
8172 // makes no sense. Worth issuing a warning at some point.
8173 return true;
8174 }
8175
8176 // Consume the argument.
8177 unsigned argIndex = FS.getArgIndex();
8178 if (argIndex < NumDataArgs) {
8179 // The check to see if the argIndex is valid will come later.
8180 // We set the bit here because we may exit early from this
8181 // function if we encounter some other error.
8182 CoveredArgs.set(argIndex);
8183 }
8184
8185 // FreeBSD kernel extensions.
8186 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8187 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8188 // We need at least two arguments.
8189 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8190 return false;
8191
8192 if (HasFormatArguments()) {
8193 // Claim the second argument.
8194 CoveredArgs.set(argIndex + 1);
8195
8196 // Type check the first argument (int for %b, pointer for %D)
8197 const Expr *Ex = getDataArg(argIndex);
8198 const analyze_printf::ArgType &AT =
8199 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8200 ? ArgType(S.Context.IntTy)
8201 : ArgType::CPointerTy;
8202 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8203 EmitFormatDiagnostic(
8204 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8205 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8206 << false << Ex->getSourceRange(),
8207 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8208 getSpecifierRange(startSpecifier, specifierLen));
8209
8210 // Type check the second argument (char * for both %b and %D)
8211 Ex = getDataArg(argIndex + 1);
8213 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8214 EmitFormatDiagnostic(
8215 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8216 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8217 << false << Ex->getSourceRange(),
8218 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8219 getSpecifierRange(startSpecifier, specifierLen));
8220 }
8221 return true;
8222 }
8223
8224 // Check for using an Objective-C specific conversion specifier
8225 // in a non-ObjC literal.
8226 if (!allowsObjCArg() && CS.isObjCArg()) {
8227 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8228 specifierLen);
8229 }
8230
8231 // %P can only be used with os_log.
8232 if (FSType != FormatStringType::OSLog &&
8233 CS.getKind() == ConversionSpecifier::PArg) {
8234 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8235 specifierLen);
8236 }
8237
8238 // %n is not allowed with os_log.
8239 if (FSType == FormatStringType::OSLog &&
8240 CS.getKind() == ConversionSpecifier::nArg) {
8241 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8242 getLocationOfByte(CS.getStart()),
8243 /*IsStringLocation*/ false,
8244 getSpecifierRange(startSpecifier, specifierLen));
8245
8246 return true;
8247 }
8248
8249 // Only scalars are allowed for os_trace.
8250 if (FSType == FormatStringType::OSTrace &&
8251 (CS.getKind() == ConversionSpecifier::PArg ||
8252 CS.getKind() == ConversionSpecifier::sArg ||
8253 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8254 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8255 specifierLen);
8256 }
8257
8258 // Check for use of public/private annotation outside of os_log().
8259 if (FSType != FormatStringType::OSLog) {
8260 if (FS.isPublic().isSet()) {
8261 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8262 << "public",
8263 getLocationOfByte(FS.isPublic().getPosition()),
8264 /*IsStringLocation*/ false,
8265 getSpecifierRange(startSpecifier, specifierLen));
8266 }
8267 if (FS.isPrivate().isSet()) {
8268 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8269 << "private",
8270 getLocationOfByte(FS.isPrivate().getPosition()),
8271 /*IsStringLocation*/ false,
8272 getSpecifierRange(startSpecifier, specifierLen));
8273 }
8274 }
8275
8276 const llvm::Triple &Triple = Target.getTriple();
8277 if (CS.getKind() == ConversionSpecifier::nArg &&
8278 (Triple.isAndroid() || Triple.isOSFuchsia())) {
8279 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
8280 getLocationOfByte(CS.getStart()),
8281 /*IsStringLocation*/ false,
8282 getSpecifierRange(startSpecifier, specifierLen));
8283 }
8284
8285 // Check for invalid use of field width
8286 if (!FS.hasValidFieldWidth()) {
8287 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8288 startSpecifier, specifierLen);
8289 }
8290
8291 // Check for invalid use of precision
8292 if (!FS.hasValidPrecision()) {
8293 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8294 startSpecifier, specifierLen);
8295 }
8296
8297 // Precision is mandatory for %P specifier.
8298 if (CS.getKind() == ConversionSpecifier::PArg &&
8300 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8301 getLocationOfByte(startSpecifier),
8302 /*IsStringLocation*/ false,
8303 getSpecifierRange(startSpecifier, specifierLen));
8304 }
8305
8306 // Check each flag does not conflict with any other component.
8308 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8309 if (!FS.hasValidLeadingZeros())
8310 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8311 if (!FS.hasValidPlusPrefix())
8312 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8313 if (!FS.hasValidSpacePrefix())
8314 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8315 if (!FS.hasValidAlternativeForm())
8316 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8317 if (!FS.hasValidLeftJustified())
8318 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8319
8320 // Check that flags are not ignored by another flag
8321 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8322 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8323 startSpecifier, specifierLen);
8324 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8325 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8326 startSpecifier, specifierLen);
8327
8328 // Check the length modifier is valid with the given conversion specifier.
8330 S.getLangOpts()))
8331 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8332 diag::warn_format_nonsensical_length);
8333 else if (!FS.hasStandardLengthModifier())
8334 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8336 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8337 diag::warn_format_non_standard_conversion_spec);
8338
8340 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8341
8342 // The remaining checks depend on the data arguments.
8343 if (!HasFormatArguments())
8344 return true;
8345
8346 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8347 return false;
8348
8349 const Expr *Arg = getDataArg(argIndex);
8350 if (!Arg)
8351 return true;
8352
8353 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8354}
8355
8356static bool requiresParensToAddCast(const Expr *E) {
8357 // FIXME: We should have a general way to reason about operator
8358 // precedence and whether parens are actually needed here.
8359 // Take care of a few common cases where they aren't.
8360 const Expr *Inside = E->IgnoreImpCasts();
8361 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8362 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8363
8364 switch (Inside->getStmtClass()) {
8365 case Stmt::ArraySubscriptExprClass:
8366 case Stmt::CallExprClass:
8367 case Stmt::CharacterLiteralClass:
8368 case Stmt::CXXBoolLiteralExprClass:
8369 case Stmt::DeclRefExprClass:
8370 case Stmt::FloatingLiteralClass:
8371 case Stmt::IntegerLiteralClass:
8372 case Stmt::MemberExprClass:
8373 case Stmt::ObjCArrayLiteralClass:
8374 case Stmt::ObjCBoolLiteralExprClass:
8375 case Stmt::ObjCBoxedExprClass:
8376 case Stmt::ObjCDictionaryLiteralClass:
8377 case Stmt::ObjCEncodeExprClass:
8378 case Stmt::ObjCIvarRefExprClass:
8379 case Stmt::ObjCMessageExprClass:
8380 case Stmt::ObjCPropertyRefExprClass:
8381 case Stmt::ObjCStringLiteralClass:
8382 case Stmt::ObjCSubscriptRefExprClass:
8383 case Stmt::ParenExprClass:
8384 case Stmt::StringLiteralClass:
8385 case Stmt::UnaryOperatorClass:
8386 return false;
8387 default:
8388 return true;
8389 }
8390}
8391
8392static std::pair<QualType, StringRef>
8394 QualType IntendedTy,
8395 const Expr *E) {
8396 // Use a 'while' to peel off layers of typedefs.
8397 QualType TyTy = IntendedTy;
8398 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8399 StringRef Name = UserTy->getDecl()->getName();
8400 QualType CastTy = llvm::StringSwitch<QualType>(Name)
8401 .Case("CFIndex", Context.getNSIntegerType())
8402 .Case("NSInteger", Context.getNSIntegerType())
8403 .Case("NSUInteger", Context.getNSUIntegerType())
8404 .Case("SInt32", Context.IntTy)
8405 .Case("UInt32", Context.UnsignedIntTy)
8406 .Default(QualType());
8407
8408 if (!CastTy.isNull())
8409 return std::make_pair(CastTy, Name);
8410
8411 TyTy = UserTy->desugar();
8412 }
8413
8414 // Strip parens if necessary.
8415 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8416 return shouldNotPrintDirectly(Context,
8417 PE->getSubExpr()->getType(),
8418 PE->getSubExpr());
8419
8420 // If this is a conditional expression, then its result type is constructed
8421 // via usual arithmetic conversions and thus there might be no necessary
8422 // typedef sugar there. Recurse to operands to check for NSInteger &
8423 // Co. usage condition.
8424 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8425 QualType TrueTy, FalseTy;
8426 StringRef TrueName, FalseName;
8427
8428 std::tie(TrueTy, TrueName) =
8429 shouldNotPrintDirectly(Context,
8430 CO->getTrueExpr()->getType(),
8431 CO->getTrueExpr());
8432 std::tie(FalseTy, FalseName) =
8433 shouldNotPrintDirectly(Context,
8434 CO->getFalseExpr()->getType(),
8435 CO->getFalseExpr());
8436
8437 if (TrueTy == FalseTy)
8438 return std::make_pair(TrueTy, TrueName);
8439 else if (TrueTy.isNull())
8440 return std::make_pair(FalseTy, FalseName);
8441 else if (FalseTy.isNull())
8442 return std::make_pair(TrueTy, TrueName);
8443 }
8444
8445 return std::make_pair(QualType(), StringRef());
8446}
8447
8448/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8449/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8450/// type do not count.
8451static bool
8453 QualType From = ICE->getSubExpr()->getType();
8454 QualType To = ICE->getType();
8455 // It's an integer promotion if the destination type is the promoted
8456 // source type.
8457 if (ICE->getCastKind() == CK_IntegralCast &&
8459 S.Context.getPromotedIntegerType(From) == To)
8460 return true;
8461 // Look through vector types, since we do default argument promotion for
8462 // those in OpenCL.
8463 if (const auto *VecTy = From->getAs<ExtVectorType>())
8464 From = VecTy->getElementType();
8465 if (const auto *VecTy = To->getAs<ExtVectorType>())
8466 To = VecTy->getElementType();
8467 // It's a floating promotion if the source type is a lower rank.
8468 return ICE->getCastKind() == CK_FloatingCast &&
8469 S.Context.getFloatingTypeOrder(From, To) < 0;
8470}
8471
8474 DiagnosticsEngine &Diags, SourceLocation Loc) {
8476 if (Diags.isIgnored(
8477 diag::warn_format_conversion_argument_type_mismatch_signedness,
8478 Loc) ||
8479 Diags.isIgnored(
8480 // Arbitrary -Wformat diagnostic to detect -Wno-format:
8481 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
8483 }
8484 }
8485 return Match;
8486}
8487
8488bool
8489CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8490 const char *StartSpecifier,
8491 unsigned SpecifierLen,
8492 const Expr *E) {
8493 using namespace analyze_format_string;
8494 using namespace analyze_printf;
8495
8496 // Now type check the data expression that matches the
8497 // format specifier.
8498 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8499 if (!AT.isValid())
8500 return true;
8501
8502 QualType ExprTy = E->getType();
8503 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8504 ExprTy = TET->getUnderlyingExpr()->getType();
8505 }
8506
8507 // When using the format attribute in C++, you can receive a function or an
8508 // array that will necessarily decay to a pointer when passed to the final
8509 // format consumer. Apply decay before type comparison.
8510 if (ExprTy->canDecayToPointerType())
8511 ExprTy = S.Context.getDecayedType(ExprTy);
8512
8513 // Diagnose attempts to print a boolean value as a character. Unlike other
8514 // -Wformat diagnostics, this is fine from a type perspective, but it still
8515 // doesn't make sense.
8518 const CharSourceRange &CSR =
8519 getSpecifierRange(StartSpecifier, SpecifierLen);
8520 SmallString<4> FSString;
8521 llvm::raw_svector_ostream os(FSString);
8522 FS.toString(os);
8523 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8524 << FSString,
8525 E->getExprLoc(), false, CSR);
8526 return true;
8527 }
8528
8529 // Diagnose attempts to use '%P' with ObjC object types, which will result in
8530 // dumping raw class data (like is-a pointer), not actual data.
8532 ExprTy->isObjCObjectPointerType()) {
8533 const CharSourceRange &CSR =
8534 getSpecifierRange(StartSpecifier, SpecifierLen);
8535 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
8536 E->getExprLoc(), false, CSR);
8537 return true;
8538 }
8539
8540 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
8542 ArgType::MatchKind OrigMatch = Match;
8543
8545 if (Match == ArgType::Match)
8546 return true;
8547
8548 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
8549 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
8550
8551 // Look through argument promotions for our error message's reported type.
8552 // This includes the integral and floating promotions, but excludes array
8553 // and function pointer decay (seeing that an argument intended to be a
8554 // string has type 'char [6]' is probably more confusing than 'char *') and
8555 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8556 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8557 if (isArithmeticArgumentPromotion(S, ICE)) {
8558 E = ICE->getSubExpr();
8559 ExprTy = E->getType();
8560
8561 // Check if we didn't match because of an implicit cast from a 'char'
8562 // or 'short' to an 'int'. This is done because printf is a varargs
8563 // function.
8564 if (ICE->getType() == S.Context.IntTy ||
8565 ICE->getType() == S.Context.UnsignedIntTy) {
8566 // All further checking is done on the subexpression
8567 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
8568 if (OrigMatch == ArgType::NoMatchSignedness &&
8569 ImplicitMatch != ArgType::NoMatchSignedness)
8570 // If the original match was a signedness match this match on the
8571 // implicit cast type also need to be signedness match otherwise we
8572 // might introduce new unexpected warnings from -Wformat-signedness.
8573 return true;
8574 ImplicitMatch = handleFormatSignedness(
8575 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
8576 if (ImplicitMatch == ArgType::Match)
8577 return true;
8578 }
8579 }
8580 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8581 // Special case for 'a', which has type 'int' in C.
8582 // Note, however, that we do /not/ want to treat multibyte constants like
8583 // 'MooV' as characters! This form is deprecated but still exists. In
8584 // addition, don't treat expressions as of type 'char' if one byte length
8585 // modifier is provided.
8586 if (ExprTy == S.Context.IntTy &&
8588 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
8589 ExprTy = S.Context.CharTy;
8590 // To improve check results, we consider a character literal in C
8591 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
8592 // more likely a type confusion situation, so we will suggest to
8593 // use '%hhd' instead by discarding the MatchPromotion.
8594 if (Match == ArgType::MatchPromotion)
8596 }
8597 }
8598 if (Match == ArgType::MatchPromotion) {
8599 // WG14 N2562 only clarified promotions in *printf
8600 // For NSLog in ObjC, just preserve -Wformat behavior
8601 if (!S.getLangOpts().ObjC &&
8602 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
8603 ImplicitMatch != ArgType::NoMatchTypeConfusion)
8604 return true;
8606 }
8607 if (ImplicitMatch == ArgType::NoMatchPedantic ||
8608 ImplicitMatch == ArgType::NoMatchTypeConfusion)
8609 Match = ImplicitMatch;
8610 assert(Match != ArgType::MatchPromotion);
8611
8612 // Look through unscoped enums to their underlying type.
8613 bool IsEnum = false;
8614 bool IsScopedEnum = false;
8615 QualType IntendedTy = ExprTy;
8616 if (const auto *ED = ExprTy->getAsEnumDecl()) {
8617 IntendedTy = ED->getIntegerType();
8618 if (!ED->isScoped()) {
8619 ExprTy = IntendedTy;
8620 // This controls whether we're talking about the underlying type or not,
8621 // which we only want to do when it's an unscoped enum.
8622 IsEnum = true;
8623 } else {
8624 IsScopedEnum = true;
8625 }
8626 }
8627
8628 // %C in an Objective-C context prints a unichar, not a wchar_t.
8629 // If the argument is an integer of some kind, believe the %C and suggest
8630 // a cast instead of changing the conversion specifier.
8631 if (isObjCContext() &&
8634 !ExprTy->isCharType()) {
8635 // 'unichar' is defined as a typedef of unsigned short, but we should
8636 // prefer using the typedef if it is visible.
8637 IntendedTy = S.Context.UnsignedShortTy;
8638
8639 // While we are here, check if the value is an IntegerLiteral that happens
8640 // to be within the valid range.
8641 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8642 const llvm::APInt &V = IL->getValue();
8643 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8644 return true;
8645 }
8646
8647 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8649 if (S.LookupName(Result, S.getCurScope())) {
8650 NamedDecl *ND = Result.getFoundDecl();
8651 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8652 if (TD->getUnderlyingType() == IntendedTy)
8653 IntendedTy =
8655 /*Qualifier=*/std::nullopt, TD);
8656 }
8657 }
8658 }
8659
8660 // Special-case some of Darwin's platform-independence types by suggesting
8661 // casts to primitive types that are known to be large enough.
8662 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8663 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8664 QualType CastTy;
8665 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8666 if (!CastTy.isNull()) {
8667 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8668 // (long in ASTContext). Only complain to pedants or when they're the
8669 // underlying type of a scoped enum (which always needs a cast).
8670 if (!IsScopedEnum &&
8671 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8672 (AT.isSizeT() || AT.isPtrdiffT()) &&
8673 AT.matchesType(S.Context, CastTy))
8675 IntendedTy = CastTy;
8676 ShouldNotPrintDirectly = true;
8677 }
8678 }
8679
8680 // We may be able to offer a FixItHint if it is a supported type.
8681 PrintfSpecifier fixedFS = FS;
8682 bool Success =
8683 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8684
8685 if (Success) {
8686 // Get the fix string from the fixed format specifier
8687 SmallString<16> buf;
8688 llvm::raw_svector_ostream os(buf);
8689 fixedFS.toString(os);
8690
8691 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8692
8693 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
8694 unsigned Diag;
8695 switch (Match) {
8696 case ArgType::Match:
8699 llvm_unreachable("expected non-matching");
8701 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
8702 break;
8704 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8705 break;
8707 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8708 break;
8709 case ArgType::NoMatch:
8710 Diag = diag::warn_format_conversion_argument_type_mismatch;
8711 break;
8712 }
8713
8714 // In this case, the specifier is wrong and should be changed to match
8715 // the argument.
8716 EmitFormatDiagnostic(S.PDiag(Diag)
8718 << IntendedTy << IsEnum << E->getSourceRange(),
8719 E->getBeginLoc(),
8720 /*IsStringLocation*/ false, SpecRange,
8721 FixItHint::CreateReplacement(SpecRange, os.str()));
8722 } else {
8723 // The canonical type for formatting this value is different from the
8724 // actual type of the expression. (This occurs, for example, with Darwin's
8725 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8726 // should be printed as 'long' for 64-bit compatibility.)
8727 // Rather than emitting a normal format/argument mismatch, we want to
8728 // add a cast to the recommended type (and correct the format string
8729 // if necessary). We should also do so for scoped enumerations.
8730 SmallString<16> CastBuf;
8731 llvm::raw_svector_ostream CastFix(CastBuf);
8732 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
8733 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8734 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
8735
8737 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
8738 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
8739 E->getExprLoc());
8740 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
8741 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8742
8743 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8744 // If there's already a cast present, just replace it.
8745 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8746 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8747
8748 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
8749 // If the expression has high enough precedence,
8750 // just write the C-style cast.
8751 Hints.push_back(
8752 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8753 } else {
8754 // Otherwise, add parens around the expression as well as the cast.
8755 CastFix << "(";
8756 Hints.push_back(
8757 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8758
8759 // We don't use getLocForEndOfToken because it returns invalid source
8760 // locations for macro expansions (by design).
8764 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8765 }
8766
8767 if (ShouldNotPrintDirectly && !IsScopedEnum) {
8768 // The expression has a type that should not be printed directly.
8769 // We extract the name from the typedef because we don't want to show
8770 // the underlying type in the diagnostic.
8771 StringRef Name;
8772 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
8773 Name = TypedefTy->getDecl()->getName();
8774 else
8775 Name = CastTyName;
8776 unsigned Diag = Match == ArgType::NoMatchPedantic
8777 ? diag::warn_format_argument_needs_cast_pedantic
8778 : diag::warn_format_argument_needs_cast;
8779 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8780 << E->getSourceRange(),
8781 E->getBeginLoc(), /*IsStringLocation=*/false,
8782 SpecRange, Hints);
8783 } else {
8784 // In this case, the expression could be printed using a different
8785 // specifier, but we've decided that the specifier is probably correct
8786 // and we should cast instead. Just use the normal warning message.
8787
8788 unsigned Diag =
8789 IsScopedEnum
8790 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8791 : diag::warn_format_conversion_argument_type_mismatch;
8792
8793 EmitFormatDiagnostic(
8794 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8795 << IsEnum << E->getSourceRange(),
8796 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8797 }
8798 }
8799 } else {
8800 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8801 SpecifierLen);
8802 // Since the warning for passing non-POD types to variadic functions
8803 // was deferred until now, we emit a warning for non-POD
8804 // arguments here.
8805 bool EmitTypeMismatch = false;
8806 switch (S.isValidVarArgType(ExprTy)) {
8807 case VarArgKind::Valid:
8809 unsigned Diag;
8810 switch (Match) {
8811 case ArgType::Match:
8815 llvm_unreachable("expected non-matching");
8817 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8818 break;
8820 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8821 break;
8822 case ArgType::NoMatch:
8823 Diag = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)
8824 ? diag::err_format_conversion_argument_type_mismatch
8825 : diag::warn_format_conversion_argument_type_mismatch;
8826 break;
8827 }
8828
8829 EmitFormatDiagnostic(
8830 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8831 << IsEnum << CSR << E->getSourceRange(),
8832 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8833 break;
8834 }
8837 if (CallType == VariadicCallType::DoesNotApply) {
8838 EmitTypeMismatch = true;
8839 } else {
8840 EmitFormatDiagnostic(
8841 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8842 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8843 << AT.getRepresentativeTypeName(S.Context) << CSR
8844 << E->getSourceRange(),
8845 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8846 checkForCStrMembers(AT, E);
8847 }
8848 break;
8849
8851 if (CallType == VariadicCallType::DoesNotApply)
8852 EmitTypeMismatch = true;
8853 else if (ExprTy->isObjCObjectType())
8854 EmitFormatDiagnostic(
8855 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8856 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8857 << AT.getRepresentativeTypeName(S.Context) << CSR
8858 << E->getSourceRange(),
8859 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8860 else
8861 // FIXME: If this is an initializer list, suggest removing the braces
8862 // or inserting a cast to the target type.
8863 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8864 << isa<InitListExpr>(E) << ExprTy << CallType
8866 break;
8867 }
8868
8869 if (EmitTypeMismatch) {
8870 // The function is not variadic, so we do not generate warnings about
8871 // being allowed to pass that object as a variadic argument. Instead,
8872 // since there are inherently no printf specifiers for types which cannot
8873 // be passed as variadic arguments, emit a plain old specifier mismatch
8874 // argument.
8875 EmitFormatDiagnostic(
8876 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8877 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
8878 << E->getSourceRange(),
8879 E->getBeginLoc(), false, CSR);
8880 }
8881
8882 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8883 "format string specifier index out of range");
8884 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8885 }
8886
8887 return true;
8888}
8889
8890//===--- CHECK: Scanf format string checking ------------------------------===//
8891
8892namespace {
8893
8894class CheckScanfHandler : public CheckFormatHandler {
8895public:
8896 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8897 const Expr *origFormatExpr, FormatStringType type,
8898 unsigned firstDataArg, unsigned numDataArgs,
8899 const char *beg, Sema::FormatArgumentPassingKind APK,
8900 ArrayRef<const Expr *> Args, unsigned formatIdx,
8901 bool inFunctionCall, VariadicCallType CallType,
8902 llvm::SmallBitVector &CheckedVarArgs,
8903 UncoveredArgHandler &UncoveredArg)
8904 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8905 numDataArgs, beg, APK, Args, formatIdx,
8906 inFunctionCall, CallType, CheckedVarArgs,
8907 UncoveredArg) {}
8908
8909 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8910 const char *startSpecifier,
8911 unsigned specifierLen) override;
8912
8913 bool HandleInvalidScanfConversionSpecifier(
8914 const analyze_scanf::ScanfSpecifier &FS,
8915 const char *startSpecifier,
8916 unsigned specifierLen) override;
8917
8918 void HandleIncompleteScanList(const char *start, const char *end) override;
8919};
8920
8921} // namespace
8922
8923void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8924 const char *end) {
8925 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8926 getLocationOfByte(end), /*IsStringLocation*/true,
8927 getSpecifierRange(start, end - start));
8928}
8929
8930bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8932 const char *startSpecifier,
8933 unsigned specifierLen) {
8936
8937 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8938 getLocationOfByte(CS.getStart()),
8939 startSpecifier, specifierLen,
8940 CS.getStart(), CS.getLength());
8941}
8942
8943bool CheckScanfHandler::HandleScanfSpecifier(
8945 const char *startSpecifier,
8946 unsigned specifierLen) {
8947 using namespace analyze_scanf;
8948 using namespace analyze_format_string;
8949
8950 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8951
8952 // Handle case where '%' and '*' don't consume an argument. These shouldn't
8953 // be used to decide if we are using positional arguments consistently.
8954 if (FS.consumesDataArgument()) {
8955 if (atFirstArg) {
8956 atFirstArg = false;
8957 usesPositionalArgs = FS.usesPositionalArg();
8958 }
8959 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8960 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8961 startSpecifier, specifierLen);
8962 return false;
8963 }
8964 }
8965
8966 // Check if the field with is non-zero.
8967 const OptionalAmount &Amt = FS.getFieldWidth();
8969 if (Amt.getConstantAmount() == 0) {
8970 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8971 Amt.getConstantLength());
8972 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8973 getLocationOfByte(Amt.getStart()),
8974 /*IsStringLocation*/true, R,
8976 }
8977 }
8978
8979 if (!FS.consumesDataArgument()) {
8980 // FIXME: Technically specifying a precision or field width here
8981 // makes no sense. Worth issuing a warning at some point.
8982 return true;
8983 }
8984
8985 // Consume the argument.
8986 unsigned argIndex = FS.getArgIndex();
8987 if (argIndex < NumDataArgs) {
8988 // The check to see if the argIndex is valid will come later.
8989 // We set the bit here because we may exit early from this
8990 // function if we encounter some other error.
8991 CoveredArgs.set(argIndex);
8992 }
8993
8994 // Check the length modifier is valid with the given conversion specifier.
8996 S.getLangOpts()))
8997 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8998 diag::warn_format_nonsensical_length);
8999 else if (!FS.hasStandardLengthModifier())
9000 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9002 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9003 diag::warn_format_non_standard_conversion_spec);
9004
9006 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9007
9008 // The remaining checks depend on the data arguments.
9009 if (!HasFormatArguments())
9010 return true;
9011
9012 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9013 return false;
9014
9015 // Check that the argument type matches the format specifier.
9016 const Expr *Ex = getDataArg(argIndex);
9017 if (!Ex)
9018 return true;
9019
9021
9022 if (!AT.isValid()) {
9023 return true;
9024 }
9025
9027 AT.matchesType(S.Context, Ex->getType());
9030 return true;
9033
9034 ScanfSpecifier fixedFS = FS;
9035 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9036 S.getLangOpts(), S.Context);
9037
9038 unsigned Diag =
9039 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9040 : Signedness
9041 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9042 : diag::warn_format_conversion_argument_type_mismatch;
9043
9044 if (Success) {
9045 // Get the fix string from the fixed format specifier.
9046 SmallString<128> buf;
9047 llvm::raw_svector_ostream os(buf);
9048 fixedFS.toString(os);
9049
9050 EmitFormatDiagnostic(
9052 << Ex->getType() << false << Ex->getSourceRange(),
9053 Ex->getBeginLoc(),
9054 /*IsStringLocation*/ false,
9055 getSpecifierRange(startSpecifier, specifierLen),
9057 getSpecifierRange(startSpecifier, specifierLen), os.str()));
9058 } else {
9059 EmitFormatDiagnostic(S.PDiag(Diag)
9061 << Ex->getType() << false << Ex->getSourceRange(),
9062 Ex->getBeginLoc(),
9063 /*IsStringLocation*/ false,
9064 getSpecifierRange(startSpecifier, specifierLen));
9065 }
9066
9067 return true;
9068}
9069
9070static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9072 const StringLiteral *Fmt,
9074 const Expr *FmtExpr, bool InFunctionCall) {
9075 bool HadError = false;
9076 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9077 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9078 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9079 // In positional-style format strings, the same specifier can appear
9080 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9081 // are sorted by getPosition(), and we process each range of equal
9082 // getPosition() values as one group.
9083 // RefArgs are taken from a string literal that was given to
9084 // attribute(format_matches), and if we got this far, we have already
9085 // verified that if it has positional specifiers that appear in multiple
9086 // locations, then they are all mutually compatible. What's left for us to
9087 // do is verify that all specifiers with the same position in FmtArgs are
9088 // compatible with the RefArgs specifiers. We check each specifier from
9089 // FmtArgs against the first member of the RefArgs group.
9090 for (; FmtIter < FmtEnd; ++FmtIter) {
9091 // Clang does not diagnose missing format specifiers in positional-style
9092 // strings (TODO: which it probably should do, as it is UB to skip over a
9093 // format argument). Skip specifiers if needed.
9094 if (FmtIter->getPosition() < RefIter->getPosition())
9095 continue;
9096
9097 // Delimits a new getPosition() value.
9098 if (FmtIter->getPosition() > RefIter->getPosition())
9099 break;
9100
9101 HadError |=
9102 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
9103 }
9104
9105 // Jump RefIter to the start of the next group.
9106 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
9107 return Arg.getPosition() != RefIter->getPosition();
9108 });
9109 }
9110
9111 if (FmtIter < FmtEnd) {
9112 CheckFormatHandler::EmitFormatDiagnostic(
9113 S, InFunctionCall, FmtExpr,
9114 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
9115 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
9116 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
9117 } else if (RefIter < RefEnd) {
9118 CheckFormatHandler::EmitFormatDiagnostic(
9119 S, InFunctionCall, FmtExpr,
9120 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
9121 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
9122 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
9123 << 1 << RefIter->getSourceRange();
9124 }
9125 return !HadError;
9126}
9127
9129 Sema &S, const FormatStringLiteral *FExpr,
9130 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
9132 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
9133 bool inFunctionCall, VariadicCallType CallType,
9134 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
9135 bool IgnoreStringsWithoutSpecifiers) {
9136 // CHECK: is the format string a wide literal?
9137 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9138 CheckFormatHandler::EmitFormatDiagnostic(
9139 S, inFunctionCall, Args[format_idx],
9140 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9141 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9142 return;
9143 }
9144
9145 // Str - The format string. NOTE: this is NOT null-terminated!
9146 StringRef StrRef = FExpr->getString();
9147 const char *Str = StrRef.data();
9148 // Account for cases where the string literal is truncated in a declaration.
9149 const ConstantArrayType *T =
9150 S.Context.getAsConstantArrayType(FExpr->getType());
9151 assert(T && "String literal not of constant array type!");
9152 size_t TypeSize = T->getZExtSize();
9153 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9154 const unsigned numDataArgs = Args.size() - firstDataArg;
9155
9156 if (IgnoreStringsWithoutSpecifiers &&
9158 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9159 return;
9160
9161 // Emit a warning if the string literal is truncated and does not contain an
9162 // embedded null character.
9163 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9164 CheckFormatHandler::EmitFormatDiagnostic(
9165 S, inFunctionCall, Args[format_idx],
9166 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9167 FExpr->getBeginLoc(),
9168 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9169 return;
9170 }
9171
9172 // CHECK: empty format string?
9173 if (StrLen == 0 && numDataArgs > 0) {
9174 CheckFormatHandler::EmitFormatDiagnostic(
9175 S, inFunctionCall, Args[format_idx],
9176 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9177 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9178 return;
9179 }
9180
9185 bool IsObjC =
9187 if (ReferenceFormatString == nullptr) {
9188 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9189 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9190 inFunctionCall, CallType, CheckedVarArgs,
9191 UncoveredArg);
9192
9194 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
9197 H.DoneProcessing();
9198 } else {
9200 Type, ReferenceFormatString, FExpr->getFormatString(),
9201 inFunctionCall ? nullptr : Args[format_idx]);
9202 }
9203 } else if (Type == FormatStringType::Scanf) {
9204 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9205 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9206 CallType, CheckedVarArgs, UncoveredArg);
9207
9209 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9210 H.DoneProcessing();
9211 } // TODO: handle other formats
9212}
9213
9215 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9216 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9221 return true;
9222
9223 bool IsObjC =
9226 FormatStringLiteral RefLit = AuthoritativeFormatString;
9227 FormatStringLiteral TestLit = TestedFormatString;
9228 const Expr *Arg;
9229 bool DiagAtStringLiteral;
9230 if (FunctionCallArg) {
9231 Arg = FunctionCallArg;
9232 DiagAtStringLiteral = false;
9233 } else {
9234 Arg = TestedFormatString;
9235 DiagAtStringLiteral = true;
9236 }
9237 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
9238 AuthoritativeFormatString, Type,
9239 IsObjC, true, RefArgs) &&
9240 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
9241 DiagAtStringLiteral, FmtArgs)) {
9242 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
9243 TestedFormatString, FmtArgs, Arg,
9244 DiagAtStringLiteral);
9245 }
9246 return false;
9247}
9248
9250 const StringLiteral *Str) {
9255 return true;
9256
9257 FormatStringLiteral RefLit = Str;
9259 bool IsObjC =
9261 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
9262 true, Args))
9263 return false;
9264
9265 // Group arguments by getPosition() value, and check that each member of the
9266 // group is compatible with the first member. This verifies that when
9267 // positional arguments are used multiple times (such as %2$i %2$d), all uses
9268 // are mutually compatible. As an optimization, don't test the first member
9269 // against itself.
9270 bool HadError = false;
9271 auto Iter = Args.begin();
9272 auto End = Args.end();
9273 while (Iter != End) {
9274 const auto &FirstInGroup = *Iter;
9275 for (++Iter;
9276 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
9277 ++Iter) {
9278 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
9279 }
9280 }
9281 return !HadError;
9282}
9283
9285 // Str - The format string. NOTE: this is NOT null-terminated!
9286 StringRef StrRef = FExpr->getString();
9287 const char *Str = StrRef.data();
9288 // Account for cases where the string literal is truncated in a declaration.
9289 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9290 assert(T && "String literal not of constant array type!");
9291 size_t TypeSize = T->getZExtSize();
9292 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9293 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9294 getLangOpts(),
9295 Context.getTargetInfo());
9296}
9297
9298//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9299
9300// Returns the related absolute value function that is larger, of 0 if one
9301// does not exist.
9302static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9303 switch (AbsFunction) {
9304 default:
9305 return 0;
9306
9307 case Builtin::BI__builtin_abs:
9308 return Builtin::BI__builtin_labs;
9309 case Builtin::BI__builtin_labs:
9310 return Builtin::BI__builtin_llabs;
9311 case Builtin::BI__builtin_llabs:
9312 return 0;
9313
9314 case Builtin::BI__builtin_fabsf:
9315 return Builtin::BI__builtin_fabs;
9316 case Builtin::BI__builtin_fabs:
9317 return Builtin::BI__builtin_fabsl;
9318 case Builtin::BI__builtin_fabsl:
9319 return 0;
9320
9321 case Builtin::BI__builtin_cabsf:
9322 return Builtin::BI__builtin_cabs;
9323 case Builtin::BI__builtin_cabs:
9324 return Builtin::BI__builtin_cabsl;
9325 case Builtin::BI__builtin_cabsl:
9326 return 0;
9327
9328 case Builtin::BIabs:
9329 return Builtin::BIlabs;
9330 case Builtin::BIlabs:
9331 return Builtin::BIllabs;
9332 case Builtin::BIllabs:
9333 return 0;
9334
9335 case Builtin::BIfabsf:
9336 return Builtin::BIfabs;
9337 case Builtin::BIfabs:
9338 return Builtin::BIfabsl;
9339 case Builtin::BIfabsl:
9340 return 0;
9341
9342 case Builtin::BIcabsf:
9343 return Builtin::BIcabs;
9344 case Builtin::BIcabs:
9345 return Builtin::BIcabsl;
9346 case Builtin::BIcabsl:
9347 return 0;
9348 }
9349}
9350
9351// Returns the argument type of the absolute value function.
9353 unsigned AbsType) {
9354 if (AbsType == 0)
9355 return QualType();
9356
9358 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9360 return QualType();
9361
9363 if (!FT)
9364 return QualType();
9365
9366 if (FT->getNumParams() != 1)
9367 return QualType();
9368
9369 return FT->getParamType(0);
9370}
9371
9372// Returns the best absolute value function, or zero, based on type and
9373// current absolute value function.
9374static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9375 unsigned AbsFunctionKind) {
9376 unsigned BestKind = 0;
9377 uint64_t ArgSize = Context.getTypeSize(ArgType);
9378 for (unsigned Kind = AbsFunctionKind; Kind != 0;
9379 Kind = getLargerAbsoluteValueFunction(Kind)) {
9380 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9381 if (Context.getTypeSize(ParamType) >= ArgSize) {
9382 if (BestKind == 0)
9383 BestKind = Kind;
9384 else if (Context.hasSameType(ParamType, ArgType)) {
9385 BestKind = Kind;
9386 break;
9387 }
9388 }
9389 }
9390 return BestKind;
9391}
9392
9398
9400 if (T->isIntegralOrEnumerationType())
9401 return AVK_Integer;
9402 if (T->isRealFloatingType())
9403 return AVK_Floating;
9404 if (T->isAnyComplexType())
9405 return AVK_Complex;
9406
9407 llvm_unreachable("Type not integer, floating, or complex");
9408}
9409
9410// Changes the absolute value function to a different type. Preserves whether
9411// the function is a builtin.
9412static unsigned changeAbsFunction(unsigned AbsKind,
9413 AbsoluteValueKind ValueKind) {
9414 switch (ValueKind) {
9415 case AVK_Integer:
9416 switch (AbsKind) {
9417 default:
9418 return 0;
9419 case Builtin::BI__builtin_fabsf:
9420 case Builtin::BI__builtin_fabs:
9421 case Builtin::BI__builtin_fabsl:
9422 case Builtin::BI__builtin_cabsf:
9423 case Builtin::BI__builtin_cabs:
9424 case Builtin::BI__builtin_cabsl:
9425 return Builtin::BI__builtin_abs;
9426 case Builtin::BIfabsf:
9427 case Builtin::BIfabs:
9428 case Builtin::BIfabsl:
9429 case Builtin::BIcabsf:
9430 case Builtin::BIcabs:
9431 case Builtin::BIcabsl:
9432 return Builtin::BIabs;
9433 }
9434 case AVK_Floating:
9435 switch (AbsKind) {
9436 default:
9437 return 0;
9438 case Builtin::BI__builtin_abs:
9439 case Builtin::BI__builtin_labs:
9440 case Builtin::BI__builtin_llabs:
9441 case Builtin::BI__builtin_cabsf:
9442 case Builtin::BI__builtin_cabs:
9443 case Builtin::BI__builtin_cabsl:
9444 return Builtin::BI__builtin_fabsf;
9445 case Builtin::BIabs:
9446 case Builtin::BIlabs:
9447 case Builtin::BIllabs:
9448 case Builtin::BIcabsf:
9449 case Builtin::BIcabs:
9450 case Builtin::BIcabsl:
9451 return Builtin::BIfabsf;
9452 }
9453 case AVK_Complex:
9454 switch (AbsKind) {
9455 default:
9456 return 0;
9457 case Builtin::BI__builtin_abs:
9458 case Builtin::BI__builtin_labs:
9459 case Builtin::BI__builtin_llabs:
9460 case Builtin::BI__builtin_fabsf:
9461 case Builtin::BI__builtin_fabs:
9462 case Builtin::BI__builtin_fabsl:
9463 return Builtin::BI__builtin_cabsf;
9464 case Builtin::BIabs:
9465 case Builtin::BIlabs:
9466 case Builtin::BIllabs:
9467 case Builtin::BIfabsf:
9468 case Builtin::BIfabs:
9469 case Builtin::BIfabsl:
9470 return Builtin::BIcabsf;
9471 }
9472 }
9473 llvm_unreachable("Unable to convert function");
9474}
9475
9476static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9477 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9478 if (!FnInfo)
9479 return 0;
9480
9481 switch (FDecl->getBuiltinID()) {
9482 default:
9483 return 0;
9484 case Builtin::BI__builtin_abs:
9485 case Builtin::BI__builtin_fabs:
9486 case Builtin::BI__builtin_fabsf:
9487 case Builtin::BI__builtin_fabsl:
9488 case Builtin::BI__builtin_labs:
9489 case Builtin::BI__builtin_llabs:
9490 case Builtin::BI__builtin_cabs:
9491 case Builtin::BI__builtin_cabsf:
9492 case Builtin::BI__builtin_cabsl:
9493 case Builtin::BIabs:
9494 case Builtin::BIlabs:
9495 case Builtin::BIllabs:
9496 case Builtin::BIfabs:
9497 case Builtin::BIfabsf:
9498 case Builtin::BIfabsl:
9499 case Builtin::BIcabs:
9500 case Builtin::BIcabsf:
9501 case Builtin::BIcabsl:
9502 return FDecl->getBuiltinID();
9503 }
9504 llvm_unreachable("Unknown Builtin type");
9505}
9506
9507// If the replacement is valid, emit a note with replacement function.
9508// Additionally, suggest including the proper header if not already included.
9510 unsigned AbsKind, QualType ArgType) {
9511 bool EmitHeaderHint = true;
9512 const char *HeaderName = nullptr;
9513 std::string FunctionName;
9514 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9515 FunctionName = "std::abs";
9516 if (ArgType->isIntegralOrEnumerationType()) {
9517 HeaderName = "cstdlib";
9518 } else if (ArgType->isRealFloatingType()) {
9519 HeaderName = "cmath";
9520 } else {
9521 llvm_unreachable("Invalid Type");
9522 }
9523
9524 // Lookup all std::abs
9525 if (NamespaceDecl *Std = S.getStdNamespace()) {
9526 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9528 S.LookupQualifiedName(R, Std);
9529
9530 for (const auto *I : R) {
9531 const FunctionDecl *FDecl = nullptr;
9532 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9533 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9534 } else {
9535 FDecl = dyn_cast<FunctionDecl>(I);
9536 }
9537 if (!FDecl)
9538 continue;
9539
9540 // Found std::abs(), check that they are the right ones.
9541 if (FDecl->getNumParams() != 1)
9542 continue;
9543
9544 // Check that the parameter type can handle the argument.
9545 QualType ParamType = FDecl->getParamDecl(0)->getType();
9546 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9547 S.Context.getTypeSize(ArgType) <=
9548 S.Context.getTypeSize(ParamType)) {
9549 // Found a function, don't need the header hint.
9550 EmitHeaderHint = false;
9551 break;
9552 }
9553 }
9554 }
9555 } else {
9556 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9557 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9558
9559 if (HeaderName) {
9560 DeclarationName DN(&S.Context.Idents.get(FunctionName));
9561 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9563 S.LookupName(R, S.getCurScope());
9564
9565 if (R.isSingleResult()) {
9566 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9567 if (FD && FD->getBuiltinID() == AbsKind) {
9568 EmitHeaderHint = false;
9569 } else {
9570 return;
9571 }
9572 } else if (!R.empty()) {
9573 return;
9574 }
9575 }
9576 }
9577
9578 S.Diag(Loc, diag::note_replace_abs_function)
9579 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9580
9581 if (!HeaderName)
9582 return;
9583
9584 if (!EmitHeaderHint)
9585 return;
9586
9587 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9588 << FunctionName;
9589}
9590
9591template <std::size_t StrLen>
9592static bool IsStdFunction(const FunctionDecl *FDecl,
9593 const char (&Str)[StrLen]) {
9594 if (!FDecl)
9595 return false;
9596 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9597 return false;
9598 if (!FDecl->isInStdNamespace())
9599 return false;
9600
9601 return true;
9602}
9603
9604enum class MathCheck { NaN, Inf };
9605static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
9606 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
9607 return llvm::is_contained(names, calleeName);
9608 };
9609
9610 switch (Check) {
9611 case MathCheck::NaN:
9612 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
9613 "__builtin_nanf16", "__builtin_nanf128"});
9614 case MathCheck::Inf:
9615 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
9616 "__builtin_inff16", "__builtin_inff128"});
9617 }
9618 llvm_unreachable("unknown MathCheck");
9619}
9620
9621static bool IsInfinityFunction(const FunctionDecl *FDecl) {
9622 if (FDecl->getName() != "infinity")
9623 return false;
9624
9625 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
9626 const CXXRecordDecl *RDecl = MDecl->getParent();
9627 if (RDecl->getName() != "numeric_limits")
9628 return false;
9629
9630 if (const NamespaceDecl *NSDecl =
9631 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
9632 return NSDecl->isStdNamespace();
9633 }
9634
9635 return false;
9636}
9637
9638void Sema::CheckInfNaNFunction(const CallExpr *Call,
9639 const FunctionDecl *FDecl) {
9640 if (!FDecl->getIdentifier())
9641 return;
9642
9643 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
9644 if (FPO.getNoHonorNaNs() &&
9645 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
9647 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9648 << 1 << 0 << Call->getSourceRange();
9649 return;
9650 }
9651
9652 if (FPO.getNoHonorInfs() &&
9653 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
9654 IsInfinityFunction(FDecl) ||
9656 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9657 << 0 << 0 << Call->getSourceRange();
9658 }
9659}
9660
9661void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9662 const FunctionDecl *FDecl) {
9663 if (Call->getNumArgs() != 1)
9664 return;
9665
9666 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9667 bool IsStdAbs = IsStdFunction(FDecl, "abs");
9668 if (AbsKind == 0 && !IsStdAbs)
9669 return;
9670
9671 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9672 QualType ParamType = Call->getArg(0)->getType();
9673
9674 // Unsigned types cannot be negative. Suggest removing the absolute value
9675 // function call.
9676 if (ArgType->isUnsignedIntegerType()) {
9677 std::string FunctionName =
9678 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9679 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9680 Diag(Call->getExprLoc(), diag::note_remove_abs)
9681 << FunctionName
9682 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9683 return;
9684 }
9685
9686 // Taking the absolute value of a pointer is very suspicious, they probably
9687 // wanted to index into an array, dereference a pointer, call a function, etc.
9688 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9689 unsigned DiagType = 0;
9690 if (ArgType->isFunctionType())
9691 DiagType = 1;
9692 else if (ArgType->isArrayType())
9693 DiagType = 2;
9694
9695 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9696 return;
9697 }
9698
9699 // std::abs has overloads which prevent most of the absolute value problems
9700 // from occurring.
9701 if (IsStdAbs)
9702 return;
9703
9704 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9705 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9706
9707 // The argument and parameter are the same kind. Check if they are the right
9708 // size.
9709 if (ArgValueKind == ParamValueKind) {
9710 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9711 return;
9712
9713 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9714 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9715 << FDecl << ArgType << ParamType;
9716
9717 if (NewAbsKind == 0)
9718 return;
9719
9720 emitReplacement(*this, Call->getExprLoc(),
9721 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9722 return;
9723 }
9724
9725 // ArgValueKind != ParamValueKind
9726 // The wrong type of absolute value function was used. Attempt to find the
9727 // proper one.
9728 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9729 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9730 if (NewAbsKind == 0)
9731 return;
9732
9733 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9734 << FDecl << ParamValueKind << ArgValueKind;
9735
9736 emitReplacement(*this, Call->getExprLoc(),
9737 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9738}
9739
9740//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9741void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9742 const FunctionDecl *FDecl) {
9743 if (!Call || !FDecl) return;
9744
9745 // Ignore template specializations and macros.
9746 if (inTemplateInstantiation()) return;
9747 if (Call->getExprLoc().isMacroID()) return;
9748
9749 // Only care about the one template argument, two function parameter std::max
9750 if (Call->getNumArgs() != 2) return;
9751 if (!IsStdFunction(FDecl, "max")) return;
9752 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9753 if (!ArgList) return;
9754 if (ArgList->size() != 1) return;
9755
9756 // Check that template type argument is unsigned integer.
9757 const auto& TA = ArgList->get(0);
9758 if (TA.getKind() != TemplateArgument::Type) return;
9759 QualType ArgType = TA.getAsType();
9760 if (!ArgType->isUnsignedIntegerType()) return;
9761
9762 // See if either argument is a literal zero.
9763 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9764 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9765 if (!MTE) return false;
9766 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9767 if (!Num) return false;
9768 if (Num->getValue() != 0) return false;
9769 return true;
9770 };
9771
9772 const Expr *FirstArg = Call->getArg(0);
9773 const Expr *SecondArg = Call->getArg(1);
9774 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9775 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9776
9777 // Only warn when exactly one argument is zero.
9778 if (IsFirstArgZero == IsSecondArgZero) return;
9779
9780 SourceRange FirstRange = FirstArg->getSourceRange();
9781 SourceRange SecondRange = SecondArg->getSourceRange();
9782
9783 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9784
9785 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9786 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9787
9788 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9789 SourceRange RemovalRange;
9790 if (IsFirstArgZero) {
9791 RemovalRange = SourceRange(FirstRange.getBegin(),
9792 SecondRange.getBegin().getLocWithOffset(-1));
9793 } else {
9794 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9795 SecondRange.getEnd());
9796 }
9797
9798 Diag(Call->getExprLoc(), diag::note_remove_max_call)
9799 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9800 << FixItHint::CreateRemoval(RemovalRange);
9801}
9802
9803//===--- CHECK: Standard memory functions ---------------------------------===//
9804
9805/// Takes the expression passed to the size_t parameter of functions
9806/// such as memcmp, strncat, etc and warns if it's a comparison.
9807///
9808/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9810 const IdentifierInfo *FnName,
9811 SourceLocation FnLoc,
9812 SourceLocation RParenLoc) {
9813 const auto *Size = dyn_cast<BinaryOperator>(E);
9814 if (!Size)
9815 return false;
9816
9817 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9818 if (!Size->isComparisonOp() && !Size->isLogicalOp())
9819 return false;
9820
9821 SourceRange SizeRange = Size->getSourceRange();
9822 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9823 << SizeRange << FnName;
9824 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9825 << FnName
9827 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9828 << FixItHint::CreateRemoval(RParenLoc);
9829 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9830 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9832 ")");
9833
9834 return true;
9835}
9836
9837/// Determine whether the given type is or contains a dynamic class type
9838/// (e.g., whether it has a vtable).
9840 bool &IsContained) {
9841 // Look through array types while ignoring qualifiers.
9842 const Type *Ty = T->getBaseElementTypeUnsafe();
9843 IsContained = false;
9844
9845 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9846 RD = RD ? RD->getDefinition() : nullptr;
9847 if (!RD || RD->isInvalidDecl())
9848 return nullptr;
9849
9850 if (RD->isDynamicClass())
9851 return RD;
9852
9853 // Check all the fields. If any bases were dynamic, the class is dynamic.
9854 // It's impossible for a class to transitively contain itself by value, so
9855 // infinite recursion is impossible.
9856 for (auto *FD : RD->fields()) {
9857 bool SubContained;
9858 if (const CXXRecordDecl *ContainedRD =
9859 getContainedDynamicClass(FD->getType(), SubContained)) {
9860 IsContained = true;
9861 return ContainedRD;
9862 }
9863 }
9864
9865 return nullptr;
9866}
9867
9869 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9870 if (Unary->getKind() == UETT_SizeOf)
9871 return Unary;
9872 return nullptr;
9873}
9874
9875/// If E is a sizeof expression, returns its argument expression,
9876/// otherwise returns NULL.
9877static const Expr *getSizeOfExprArg(const Expr *E) {
9879 if (!SizeOf->isArgumentType())
9880 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9881 return nullptr;
9882}
9883
9884/// If E is a sizeof expression, returns its argument type.
9887 return SizeOf->getTypeOfArgument();
9888 return QualType();
9889}
9890
9891namespace {
9892
9893struct SearchNonTrivialToInitializeField
9894 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9895 using Super =
9896 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9897
9898 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9899
9900 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9901 SourceLocation SL) {
9902 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9903 asDerived().visitArray(PDIK, AT, SL);
9904 return;
9905 }
9906
9907 Super::visitWithKind(PDIK, FT, SL);
9908 }
9909
9910 void visitARCStrong(QualType FT, SourceLocation SL) {
9911 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9912 }
9913 void visitARCWeak(QualType FT, SourceLocation SL) {
9914 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9915 }
9916 void visitStruct(QualType FT, SourceLocation SL) {
9917 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
9918 visit(FD->getType(), FD->getLocation());
9919 }
9920 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9921 const ArrayType *AT, SourceLocation SL) {
9922 visit(getContext().getBaseElementType(AT), SL);
9923 }
9924 void visitTrivial(QualType FT, SourceLocation SL) {}
9925
9926 static void diag(QualType RT, const Expr *E, Sema &S) {
9927 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9928 }
9929
9930 ASTContext &getContext() { return S.getASTContext(); }
9931
9932 const Expr *E;
9933 Sema &S;
9934};
9935
9936struct SearchNonTrivialToCopyField
9937 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9938 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9939
9940 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9941
9942 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9943 SourceLocation SL) {
9944 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9945 asDerived().visitArray(PCK, AT, SL);
9946 return;
9947 }
9948
9949 Super::visitWithKind(PCK, FT, SL);
9950 }
9951
9952 void visitARCStrong(QualType FT, SourceLocation SL) {
9953 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9954 }
9955 void visitARCWeak(QualType FT, SourceLocation SL) {
9956 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9957 }
9958 void visitPtrAuth(QualType FT, SourceLocation SL) {
9959 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9960 }
9961 void visitStruct(QualType FT, SourceLocation SL) {
9962 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
9963 visit(FD->getType(), FD->getLocation());
9964 }
9965 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9966 SourceLocation SL) {
9967 visit(getContext().getBaseElementType(AT), SL);
9968 }
9969 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9970 SourceLocation SL) {}
9971 void visitTrivial(QualType FT, SourceLocation SL) {}
9972 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9973
9974 static void diag(QualType RT, const Expr *E, Sema &S) {
9975 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9976 }
9977
9978 ASTContext &getContext() { return S.getASTContext(); }
9979
9980 const Expr *E;
9981 Sema &S;
9982};
9983
9984}
9985
9986/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9987static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9988 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9989
9990 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9991 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9992 return false;
9993
9994 return doesExprLikelyComputeSize(BO->getLHS()) ||
9995 doesExprLikelyComputeSize(BO->getRHS());
9996 }
9997
9998 return getAsSizeOfExpr(SizeofExpr) != nullptr;
9999}
10000
10001/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10002///
10003/// \code
10004/// #define MACRO 0
10005/// foo(MACRO);
10006/// foo(0);
10007/// \endcode
10008///
10009/// This should return true for the first call to foo, but not for the second
10010/// (regardless of whether foo is a macro or function).
10012 SourceLocation CallLoc,
10013 SourceLocation ArgLoc) {
10014 if (!CallLoc.isMacroID())
10015 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10016
10017 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10018 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10019}
10020
10021/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10022/// last two arguments transposed.
10023static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10024 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10025 return;
10026
10027 const Expr *SizeArg =
10028 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10029
10030 auto isLiteralZero = [](const Expr *E) {
10031 return (isa<IntegerLiteral>(E) &&
10032 cast<IntegerLiteral>(E)->getValue() == 0) ||
10034 cast<CharacterLiteral>(E)->getValue() == 0);
10035 };
10036
10037 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10038 SourceLocation CallLoc = Call->getRParenLoc();
10040 if (isLiteralZero(SizeArg) &&
10041 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10042
10043 SourceLocation DiagLoc = SizeArg->getExprLoc();
10044
10045 // Some platforms #define bzero to __builtin_memset. See if this is the
10046 // case, and if so, emit a better diagnostic.
10047 if (BId == Builtin::BIbzero ||
10049 CallLoc, SM, S.getLangOpts()) == "bzero")) {
10050 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10051 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10052 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10053 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10054 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10055 }
10056 return;
10057 }
10058
10059 // If the second argument to a memset is a sizeof expression and the third
10060 // isn't, this is also likely an error. This should catch
10061 // 'memset(buf, sizeof(buf), 0xff)'.
10062 if (BId == Builtin::BImemset &&
10063 doesExprLikelyComputeSize(Call->getArg(1)) &&
10064 !doesExprLikelyComputeSize(Call->getArg(2))) {
10065 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10066 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10067 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10068 return;
10069 }
10070}
10071
10072void Sema::CheckMemaccessArguments(const CallExpr *Call,
10073 unsigned BId,
10074 IdentifierInfo *FnName) {
10075 assert(BId != 0);
10076
10077 // It is possible to have a non-standard definition of memset. Validate
10078 // we have enough arguments, and if not, abort further checking.
10079 unsigned ExpectedNumArgs =
10080 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10081 if (Call->getNumArgs() < ExpectedNumArgs)
10082 return;
10083
10084 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10085 BId == Builtin::BIstrndup ? 1 : 2);
10086 unsigned LenArg =
10087 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10088 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10089
10090 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10091 Call->getBeginLoc(), Call->getRParenLoc()))
10092 return;
10093
10094 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10095 CheckMemaccessSize(*this, BId, Call);
10096
10097 // We have special checking when the length is a sizeof expression.
10098 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10099 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10100 llvm::FoldingSetNodeID SizeOfArgID;
10101
10102 // Although widely used, 'bzero' is not a standard function. Be more strict
10103 // with the argument types before allowing diagnostics and only allow the
10104 // form bzero(ptr, sizeof(...)).
10105 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10106 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10107 return;
10108
10109 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10110 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10111 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10112
10113 QualType DestTy = Dest->getType();
10114 QualType PointeeTy;
10115 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10116 PointeeTy = DestPtrTy->getPointeeType();
10117
10118 // Never warn about void type pointers. This can be used to suppress
10119 // false positives.
10120 if (PointeeTy->isVoidType())
10121 continue;
10122
10123 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10124 // actually comparing the expressions for equality. Because computing the
10125 // expression IDs can be expensive, we only do this if the diagnostic is
10126 // enabled.
10127 if (SizeOfArg &&
10128 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10129 SizeOfArg->getExprLoc())) {
10130 // We only compute IDs for expressions if the warning is enabled, and
10131 // cache the sizeof arg's ID.
10132 if (SizeOfArgID == llvm::FoldingSetNodeID())
10133 SizeOfArg->Profile(SizeOfArgID, Context, true);
10134 llvm::FoldingSetNodeID DestID;
10135 Dest->Profile(DestID, Context, true);
10136 if (DestID == SizeOfArgID) {
10137 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10138 // over sizeof(src) as well.
10139 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10140 StringRef ReadableName = FnName->getName();
10141
10142 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10143 if (UnaryOp->getOpcode() == UO_AddrOf)
10144 ActionIdx = 1; // If its an address-of operator, just remove it.
10145 if (!PointeeTy->isIncompleteType() &&
10146 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10147 ActionIdx = 2; // If the pointee's size is sizeof(char),
10148 // suggest an explicit length.
10149
10150 // If the function is defined as a builtin macro, do not show macro
10151 // expansion.
10152 SourceLocation SL = SizeOfArg->getExprLoc();
10153 SourceRange DSR = Dest->getSourceRange();
10154 SourceRange SSR = SizeOfArg->getSourceRange();
10155 SourceManager &SM = getSourceManager();
10156
10157 if (SM.isMacroArgExpansion(SL)) {
10158 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10159 SL = SM.getSpellingLoc(SL);
10160 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10161 SM.getSpellingLoc(DSR.getEnd()));
10162 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10163 SM.getSpellingLoc(SSR.getEnd()));
10164 }
10165
10166 DiagRuntimeBehavior(SL, SizeOfArg,
10167 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10168 << ReadableName
10169 << PointeeTy
10170 << DestTy
10171 << DSR
10172 << SSR);
10173 DiagRuntimeBehavior(SL, SizeOfArg,
10174 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10175 << ActionIdx
10176 << SSR);
10177
10178 break;
10179 }
10180 }
10181
10182 // Also check for cases where the sizeof argument is the exact same
10183 // type as the memory argument, and where it points to a user-defined
10184 // record type.
10185 if (SizeOfArgTy != QualType()) {
10186 if (PointeeTy->isRecordType() &&
10187 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10188 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10189 PDiag(diag::warn_sizeof_pointer_type_memaccess)
10190 << FnName << SizeOfArgTy << ArgIdx
10191 << PointeeTy << Dest->getSourceRange()
10192 << LenExpr->getSourceRange());
10193 break;
10194 }
10195 }
10196 } else if (DestTy->isArrayType()) {
10197 PointeeTy = DestTy;
10198 }
10199
10200 if (PointeeTy == QualType())
10201 continue;
10202
10203 // Always complain about dynamic classes.
10204 bool IsContained;
10205 if (const CXXRecordDecl *ContainedRD =
10206 getContainedDynamicClass(PointeeTy, IsContained)) {
10207
10208 unsigned OperationType = 0;
10209 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10210 // "overwritten" if we're warning about the destination for any call
10211 // but memcmp; otherwise a verb appropriate to the call.
10212 if (ArgIdx != 0 || IsCmp) {
10213 if (BId == Builtin::BImemcpy)
10214 OperationType = 1;
10215 else if(BId == Builtin::BImemmove)
10216 OperationType = 2;
10217 else if (IsCmp)
10218 OperationType = 3;
10219 }
10220
10221 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10222 PDiag(diag::warn_dyn_class_memaccess)
10223 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10224 << IsContained << ContainedRD << OperationType
10225 << Call->getCallee()->getSourceRange());
10226 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10227 BId != Builtin::BImemset)
10229 Dest->getExprLoc(), Dest,
10230 PDiag(diag::warn_arc_object_memaccess)
10231 << ArgIdx << FnName << PointeeTy
10232 << Call->getCallee()->getSourceRange());
10233 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10234
10235 // FIXME: Do not consider incomplete types even though they may be
10236 // completed later. GCC does not diagnose such code, but we may want to
10237 // consider diagnosing it in the future, perhaps under a different, but
10238 // related, diagnostic group.
10239 bool NonTriviallyCopyableCXXRecord =
10240 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10241 !PointeeTy.isTriviallyCopyableType(Context);
10242
10243 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10245 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10246 PDiag(diag::warn_cstruct_memaccess)
10247 << ArgIdx << FnName << PointeeTy << 0);
10248 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10249 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10250 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10251 // FIXME: Limiting this warning to dest argument until we decide
10252 // whether it's valid for source argument too.
10253 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10254 PDiag(diag::warn_cxxstruct_memaccess)
10255 << FnName << PointeeTy);
10256 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10258 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10259 PDiag(diag::warn_cstruct_memaccess)
10260 << ArgIdx << FnName << PointeeTy << 1);
10261 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10262 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10263 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10264 // FIXME: Limiting this warning to dest argument until we decide
10265 // whether it's valid for source argument too.
10266 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10267 PDiag(diag::warn_cxxstruct_memaccess)
10268 << FnName << PointeeTy);
10269 } else {
10270 continue;
10271 }
10272 } else
10273 continue;
10274
10276 Dest->getExprLoc(), Dest,
10277 PDiag(diag::note_bad_memaccess_silence)
10278 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10279 break;
10280 }
10281}
10282
10283// A little helper routine: ignore addition and subtraction of integer literals.
10284// This intentionally does not ignore all integer constant expressions because
10285// we don't want to remove sizeof().
10286static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10287 Ex = Ex->IgnoreParenCasts();
10288
10289 while (true) {
10290 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10291 if (!BO || !BO->isAdditiveOp())
10292 break;
10293
10294 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10295 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10296
10297 if (isa<IntegerLiteral>(RHS))
10298 Ex = LHS;
10299 else if (isa<IntegerLiteral>(LHS))
10300 Ex = RHS;
10301 else
10302 break;
10303 }
10304
10305 return Ex;
10306}
10307
10309 ASTContext &Context) {
10310 // Only handle constant-sized or VLAs, but not flexible members.
10311 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10312 // Only issue the FIXIT for arrays of size > 1.
10313 if (CAT->getZExtSize() <= 1)
10314 return false;
10315 } else if (!Ty->isVariableArrayType()) {
10316 return false;
10317 }
10318 return true;
10319}
10320
10321void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10322 IdentifierInfo *FnName) {
10323
10324 // Don't crash if the user has the wrong number of arguments
10325 unsigned NumArgs = Call->getNumArgs();
10326 if ((NumArgs != 3) && (NumArgs != 4))
10327 return;
10328
10329 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10330 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10331 const Expr *CompareWithSrc = nullptr;
10332
10333 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10334 Call->getBeginLoc(), Call->getRParenLoc()))
10335 return;
10336
10337 // Look for 'strlcpy(dst, x, sizeof(x))'
10338 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10339 CompareWithSrc = Ex;
10340 else {
10341 // Look for 'strlcpy(dst, x, strlen(x))'
10342 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10343 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10344 SizeCall->getNumArgs() == 1)
10345 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10346 }
10347 }
10348
10349 if (!CompareWithSrc)
10350 return;
10351
10352 // Determine if the argument to sizeof/strlen is equal to the source
10353 // argument. In principle there's all kinds of things you could do
10354 // here, for instance creating an == expression and evaluating it with
10355 // EvaluateAsBooleanCondition, but this uses a more direct technique:
10356 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10357 if (!SrcArgDRE)
10358 return;
10359
10360 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10361 if (!CompareWithSrcDRE ||
10362 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10363 return;
10364
10365 const Expr *OriginalSizeArg = Call->getArg(2);
10366 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10367 << OriginalSizeArg->getSourceRange() << FnName;
10368
10369 // Output a FIXIT hint if the destination is an array (rather than a
10370 // pointer to an array). This could be enhanced to handle some
10371 // pointers if we know the actual size, like if DstArg is 'array+2'
10372 // we could say 'sizeof(array)-2'.
10373 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10375 return;
10376
10377 SmallString<128> sizeString;
10378 llvm::raw_svector_ostream OS(sizeString);
10379 OS << "sizeof(";
10380 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10381 OS << ")";
10382
10383 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10384 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10385 OS.str());
10386}
10387
10388/// Check if two expressions refer to the same declaration.
10389static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10390 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10391 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10392 return D1->getDecl() == D2->getDecl();
10393 return false;
10394}
10395
10396static const Expr *getStrlenExprArg(const Expr *E) {
10397 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10398 const FunctionDecl *FD = CE->getDirectCallee();
10399 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10400 return nullptr;
10401 return CE->getArg(0)->IgnoreParenCasts();
10402 }
10403 return nullptr;
10404}
10405
10406void Sema::CheckStrncatArguments(const CallExpr *CE,
10407 const IdentifierInfo *FnName) {
10408 // Don't crash if the user has the wrong number of arguments.
10409 if (CE->getNumArgs() < 3)
10410 return;
10411 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10412 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10413 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10414
10415 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10416 CE->getRParenLoc()))
10417 return;
10418
10419 // Identify common expressions, which are wrongly used as the size argument
10420 // to strncat and may lead to buffer overflows.
10421 unsigned PatternType = 0;
10422 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10423 // - sizeof(dst)
10424 if (referToTheSameDecl(SizeOfArg, DstArg))
10425 PatternType = 1;
10426 // - sizeof(src)
10427 else if (referToTheSameDecl(SizeOfArg, SrcArg))
10428 PatternType = 2;
10429 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10430 if (BE->getOpcode() == BO_Sub) {
10431 const Expr *L = BE->getLHS()->IgnoreParenCasts();
10432 const Expr *R = BE->getRHS()->IgnoreParenCasts();
10433 // - sizeof(dst) - strlen(dst)
10434 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10436 PatternType = 1;
10437 // - sizeof(src) - (anything)
10438 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10439 PatternType = 2;
10440 }
10441 }
10442
10443 if (PatternType == 0)
10444 return;
10445
10446 // Generate the diagnostic.
10447 SourceLocation SL = LenArg->getBeginLoc();
10448 SourceRange SR = LenArg->getSourceRange();
10449 SourceManager &SM = getSourceManager();
10450
10451 // If the function is defined as a builtin macro, do not show macro expansion.
10452 if (SM.isMacroArgExpansion(SL)) {
10453 SL = SM.getSpellingLoc(SL);
10454 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10455 SM.getSpellingLoc(SR.getEnd()));
10456 }
10457
10458 // Check if the destination is an array (rather than a pointer to an array).
10459 QualType DstTy = DstArg->getType();
10460 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10461 Context);
10462 if (!isKnownSizeArray) {
10463 if (PatternType == 1)
10464 Diag(SL, diag::warn_strncat_wrong_size) << SR;
10465 else
10466 Diag(SL, diag::warn_strncat_src_size) << SR;
10467 return;
10468 }
10469
10470 if (PatternType == 1)
10471 Diag(SL, diag::warn_strncat_large_size) << SR;
10472 else
10473 Diag(SL, diag::warn_strncat_src_size) << SR;
10474
10475 SmallString<128> sizeString;
10476 llvm::raw_svector_ostream OS(sizeString);
10477 OS << "sizeof(";
10478 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10479 OS << ") - ";
10480 OS << "strlen(";
10481 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10482 OS << ") - 1";
10483
10484 Diag(SL, diag::note_strncat_wrong_size)
10485 << FixItHint::CreateReplacement(SR, OS.str());
10486}
10487
10488namespace {
10489void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10490 const UnaryOperator *UnaryExpr, const Decl *D) {
10492 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10493 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10494 return;
10495 }
10496}
10497
10498void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10499 const UnaryOperator *UnaryExpr) {
10500 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10501 const Decl *D = Lvalue->getDecl();
10502 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
10503 if (!DD->getType()->isReferenceType())
10504 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10505 }
10506 }
10507
10508 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10509 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10510 Lvalue->getMemberDecl());
10511}
10512
10513void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10514 const UnaryOperator *UnaryExpr) {
10515 const auto *Lambda = dyn_cast<LambdaExpr>(
10517 if (!Lambda)
10518 return;
10519
10520 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10521 << CalleeName << 2 /*object: lambda expression*/;
10522}
10523
10524void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10525 const DeclRefExpr *Lvalue) {
10526 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10527 if (Var == nullptr)
10528 return;
10529
10530 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10531 << CalleeName << 0 /*object: */ << Var;
10532}
10533
10534void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10535 const CastExpr *Cast) {
10536 SmallString<128> SizeString;
10537 llvm::raw_svector_ostream OS(SizeString);
10538
10539 clang::CastKind Kind = Cast->getCastKind();
10540 if (Kind == clang::CK_BitCast &&
10541 !Cast->getSubExpr()->getType()->isFunctionPointerType())
10542 return;
10543 if (Kind == clang::CK_IntegralToPointer &&
10545 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10546 return;
10547
10548 switch (Cast->getCastKind()) {
10549 case clang::CK_BitCast:
10550 case clang::CK_IntegralToPointer:
10551 case clang::CK_FunctionToPointerDecay:
10552 OS << '\'';
10553 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10554 OS << '\'';
10555 break;
10556 default:
10557 return;
10558 }
10559
10560 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10561 << CalleeName << 0 /*object: */ << OS.str();
10562}
10563} // namespace
10564
10565void Sema::CheckFreeArguments(const CallExpr *E) {
10566 const std::string CalleeName =
10567 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10568
10569 { // Prefer something that doesn't involve a cast to make things simpler.
10570 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10571 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10572 switch (UnaryExpr->getOpcode()) {
10573 case UnaryOperator::Opcode::UO_AddrOf:
10574 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10575 case UnaryOperator::Opcode::UO_Plus:
10576 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10577 default:
10578 break;
10579 }
10580
10581 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10582 if (Lvalue->getType()->isArrayType())
10583 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10584
10585 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10586 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10587 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10588 return;
10589 }
10590
10591 if (isa<BlockExpr>(Arg)) {
10592 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10593 << CalleeName << 1 /*object: block*/;
10594 return;
10595 }
10596 }
10597 // Maybe the cast was important, check after the other cases.
10598 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10599 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10600}
10601
10602void
10603Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10604 SourceLocation ReturnLoc,
10605 bool isObjCMethod,
10606 const AttrVec *Attrs,
10607 const FunctionDecl *FD) {
10608 // Check if the return value is null but should not be.
10609 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10610 (!isObjCMethod && isNonNullType(lhsType))) &&
10611 CheckNonNullExpr(*this, RetValExp))
10612 Diag(ReturnLoc, diag::warn_null_ret)
10613 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10614
10615 // C++11 [basic.stc.dynamic.allocation]p4:
10616 // If an allocation function declared with a non-throwing
10617 // exception-specification fails to allocate storage, it shall return
10618 // a null pointer. Any other allocation function that fails to allocate
10619 // storage shall indicate failure only by throwing an exception [...]
10620 if (FD) {
10622 if (Op == OO_New || Op == OO_Array_New) {
10623 const FunctionProtoType *Proto
10624 = FD->getType()->castAs<FunctionProtoType>();
10625 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10626 CheckNonNullExpr(*this, RetValExp))
10627 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10628 << FD << getLangOpts().CPlusPlus11;
10629 }
10630 }
10631
10632 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
10633 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
10634 }
10635
10636 // PPC MMA non-pointer types are not allowed as return type. Checking the type
10637 // here prevent the user from using a PPC MMA type as trailing return type.
10638 if (Context.getTargetInfo().getTriple().isPPC64())
10639 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10640}
10641
10643 const Expr *RHS, BinaryOperatorKind Opcode) {
10644 if (!BinaryOperator::isEqualityOp(Opcode))
10645 return;
10646
10647 // Match and capture subexpressions such as "(float) X == 0.1".
10648 const FloatingLiteral *FPLiteral;
10649 const CastExpr *FPCast;
10650 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
10651 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
10652 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
10653 return FPLiteral && FPCast;
10654 };
10655
10656 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
10657 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
10658 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
10659 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
10660 TargetTy->isFloatingPoint()) {
10661 bool Lossy;
10662 llvm::APFloat TargetC = FPLiteral->getValue();
10663 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
10664 llvm::APFloat::rmNearestTiesToEven, &Lossy);
10665 if (Lossy) {
10666 // If the literal cannot be represented in the source type, then a
10667 // check for == is always false and check for != is always true.
10668 Diag(Loc, diag::warn_float_compare_literal)
10669 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
10670 << LHS->getSourceRange() << RHS->getSourceRange();
10671 return;
10672 }
10673 }
10674 }
10675
10676 // Match a more general floating-point equality comparison (-Wfloat-equal).
10677 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
10678 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
10679
10680 // Special case: check for x == x (which is OK).
10681 // Do not emit warnings for such cases.
10682 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10683 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10684 if (DRL->getDecl() == DRR->getDecl())
10685 return;
10686
10687 // Special case: check for comparisons against literals that can be exactly
10688 // represented by APFloat. In such cases, do not emit a warning. This
10689 // is a heuristic: often comparison against such literals are used to
10690 // detect if a value in a variable has not changed. This clearly can
10691 // lead to false negatives.
10692 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10693 if (FLL->isExact())
10694 return;
10695 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10696 if (FLR->isExact())
10697 return;
10698
10699 // Check for comparisons with builtin types.
10700 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
10701 CL && CL->getBuiltinCallee())
10702 return;
10703
10704 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
10705 CR && CR->getBuiltinCallee())
10706 return;
10707
10708 // Emit the diagnostic.
10709 Diag(Loc, diag::warn_floatingpoint_eq)
10710 << LHS->getSourceRange() << RHS->getSourceRange();
10711}
10712
10713//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10714//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10715
10716namespace {
10717
10718/// Structure recording the 'active' range of an integer-valued
10719/// expression.
10720struct IntRange {
10721 /// The number of bits active in the int. Note that this includes exactly one
10722 /// sign bit if !NonNegative.
10723 unsigned Width;
10724
10725 /// True if the int is known not to have negative values. If so, all leading
10726 /// bits before Width are known zero, otherwise they are known to be the
10727 /// same as the MSB within Width.
10728 bool NonNegative;
10729
10730 IntRange(unsigned Width, bool NonNegative)
10731 : Width(Width), NonNegative(NonNegative) {}
10732
10733 /// Number of bits excluding the sign bit.
10734 unsigned valueBits() const {
10735 return NonNegative ? Width : Width - 1;
10736 }
10737
10738 /// Returns the range of the bool type.
10739 static IntRange forBoolType() {
10740 return IntRange(1, true);
10741 }
10742
10743 /// Returns the range of an opaque value of the given integral type.
10744 static IntRange forValueOfType(ASTContext &C, QualType T) {
10745 return forValueOfCanonicalType(C,
10747 }
10748
10749 /// Returns the range of an opaque value of a canonical integral type.
10750 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10751 assert(T->isCanonicalUnqualified());
10752
10753 if (const auto *VT = dyn_cast<VectorType>(T))
10754 T = VT->getElementType().getTypePtr();
10755 if (const auto *CT = dyn_cast<ComplexType>(T))
10756 T = CT->getElementType().getTypePtr();
10757 if (const auto *AT = dyn_cast<AtomicType>(T))
10758 T = AT->getValueType().getTypePtr();
10759
10760 if (!C.getLangOpts().CPlusPlus) {
10761 // For enum types in C code, use the underlying datatype.
10762 if (const auto *ED = T->getAsEnumDecl())
10763 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
10764 } else if (auto *Enum = T->getAsEnumDecl()) {
10765 // For enum types in C++, use the known bit width of the enumerators.
10766 // In C++11, enums can have a fixed underlying type. Use this type to
10767 // compute the range.
10768 if (Enum->isFixed()) {
10769 return IntRange(C.getIntWidth(QualType(T, 0)),
10770 !Enum->getIntegerType()->isSignedIntegerType());
10771 }
10772
10773 unsigned NumPositive = Enum->getNumPositiveBits();
10774 unsigned NumNegative = Enum->getNumNegativeBits();
10775
10776 if (NumNegative == 0)
10777 return IntRange(NumPositive, true/*NonNegative*/);
10778 else
10779 return IntRange(std::max(NumPositive + 1, NumNegative),
10780 false/*NonNegative*/);
10781 }
10782
10783 if (const auto *EIT = dyn_cast<BitIntType>(T))
10784 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10785
10786 const BuiltinType *BT = cast<BuiltinType>(T);
10787 assert(BT->isInteger());
10788
10789 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10790 }
10791
10792 /// Returns the "target" range of a canonical integral type, i.e.
10793 /// the range of values expressible in the type.
10794 ///
10795 /// This matches forValueOfCanonicalType except that enums have the
10796 /// full range of their type, not the range of their enumerators.
10797 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10798 assert(T->isCanonicalUnqualified());
10799
10800 if (const VectorType *VT = dyn_cast<VectorType>(T))
10801 T = VT->getElementType().getTypePtr();
10802 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10803 T = CT->getElementType().getTypePtr();
10804 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10805 T = AT->getValueType().getTypePtr();
10806 if (const auto *ED = T->getAsEnumDecl())
10807 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
10808
10809 if (const auto *EIT = dyn_cast<BitIntType>(T))
10810 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10811
10812 const BuiltinType *BT = cast<BuiltinType>(T);
10813 assert(BT->isInteger());
10814
10815 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10816 }
10817
10818 /// Returns the supremum of two ranges: i.e. their conservative merge.
10819 static IntRange join(IntRange L, IntRange R) {
10820 bool Unsigned = L.NonNegative && R.NonNegative;
10821 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10822 L.NonNegative && R.NonNegative);
10823 }
10824
10825 /// Return the range of a bitwise-AND of the two ranges.
10826 static IntRange bit_and(IntRange L, IntRange R) {
10827 unsigned Bits = std::max(L.Width, R.Width);
10828 bool NonNegative = false;
10829 if (L.NonNegative) {
10830 Bits = std::min(Bits, L.Width);
10831 NonNegative = true;
10832 }
10833 if (R.NonNegative) {
10834 Bits = std::min(Bits, R.Width);
10835 NonNegative = true;
10836 }
10837 return IntRange(Bits, NonNegative);
10838 }
10839
10840 /// Return the range of a sum of the two ranges.
10841 static IntRange sum(IntRange L, IntRange R) {
10842 bool Unsigned = L.NonNegative && R.NonNegative;
10843 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10844 Unsigned);
10845 }
10846
10847 /// Return the range of a difference of the two ranges.
10848 static IntRange difference(IntRange L, IntRange R) {
10849 // We need a 1-bit-wider range if:
10850 // 1) LHS can be negative: least value can be reduced.
10851 // 2) RHS can be negative: greatest value can be increased.
10852 bool CanWiden = !L.NonNegative || !R.NonNegative;
10853 bool Unsigned = L.NonNegative && R.Width == 0;
10854 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10855 !Unsigned,
10856 Unsigned);
10857 }
10858
10859 /// Return the range of a product of the two ranges.
10860 static IntRange product(IntRange L, IntRange R) {
10861 // If both LHS and RHS can be negative, we can form
10862 // -2^L * -2^R = 2^(L + R)
10863 // which requires L + R + 1 value bits to represent.
10864 bool CanWiden = !L.NonNegative && !R.NonNegative;
10865 bool Unsigned = L.NonNegative && R.NonNegative;
10866 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10867 Unsigned);
10868 }
10869
10870 /// Return the range of a remainder operation between the two ranges.
10871 static IntRange rem(IntRange L, IntRange R) {
10872 // The result of a remainder can't be larger than the result of
10873 // either side. The sign of the result is the sign of the LHS.
10874 bool Unsigned = L.NonNegative;
10875 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10876 Unsigned);
10877 }
10878};
10879
10880} // namespace
10881
10882static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
10883 if (value.isSigned() && value.isNegative())
10884 return IntRange(value.getSignificantBits(), false);
10885
10886 if (value.getBitWidth() > MaxWidth)
10887 value = value.trunc(MaxWidth);
10888
10889 // isNonNegative() just checks the sign bit without considering
10890 // signedness.
10891 return IntRange(value.getActiveBits(), true);
10892}
10893
10894static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
10895 if (result.isInt())
10896 return GetValueRange(result.getInt(), MaxWidth);
10897
10898 if (result.isVector()) {
10899 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
10900 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10901 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
10902 R = IntRange::join(R, El);
10903 }
10904 return R;
10905 }
10906
10907 if (result.isComplexInt()) {
10908 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
10909 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
10910 return IntRange::join(R, I);
10911 }
10912
10913 // This can happen with lossless casts to intptr_t of "based" lvalues.
10914 // Assume it might use arbitrary bits.
10915 // FIXME: The only reason we need to pass the type in here is to get
10916 // the sign right on this one case. It would be nice if APValue
10917 // preserved this.
10918 assert(result.isLValue() || result.isAddrLabelDiff());
10919 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10920}
10921
10922static QualType GetExprType(const Expr *E) {
10923 QualType Ty = E->getType();
10924 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
10925 Ty = AtomicRHS->getValueType();
10926 return Ty;
10927}
10928
10929/// Attempts to estimate an approximate range for the given integer expression.
10930/// Returns a range if successful, otherwise it returns \c std::nullopt if a
10931/// reliable estimation cannot be determined.
10932///
10933/// \param MaxWidth The width to which the value will be truncated.
10934/// \param InConstantContext If \c true, interpret the expression within a
10935/// constant context.
10936/// \param Approximate If \c true, provide a likely range of values by assuming
10937/// that arithmetic on narrower types remains within those types.
10938/// If \c false, return a range that includes all possible values
10939/// resulting from the expression.
10940/// \returns A range of values that the expression might take, or
10941/// std::nullopt if a reliable estimation cannot be determined.
10942static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
10943 unsigned MaxWidth,
10944 bool InConstantContext,
10945 bool Approximate) {
10946 E = E->IgnoreParens();
10947
10948 // Try a full evaluation first.
10949 Expr::EvalResult result;
10950 if (E->EvaluateAsRValue(result, C, InConstantContext))
10951 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
10952
10953 // I think we only want to look through implicit casts here; if the
10954 // user has an explicit widening cast, we should treat the value as
10955 // being of the new, wider type.
10956 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10957 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10958 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10959 Approximate);
10960
10961 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10962
10963 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10964 CE->getCastKind() == CK_BooleanToSignedIntegral;
10965
10966 // Assume that non-integer casts can span the full range of the type.
10967 if (!isIntegerCast)
10968 return OutputTypeRange;
10969
10970 std::optional<IntRange> SubRange = TryGetExprRange(
10971 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
10972 InConstantContext, Approximate);
10973 if (!SubRange)
10974 return std::nullopt;
10975
10976 // Bail out if the subexpr's range is as wide as the cast type.
10977 if (SubRange->Width >= OutputTypeRange.Width)
10978 return OutputTypeRange;
10979
10980 // Otherwise, we take the smaller width, and we're non-negative if
10981 // either the output type or the subexpr is.
10982 return IntRange(SubRange->Width,
10983 SubRange->NonNegative || OutputTypeRange.NonNegative);
10984 }
10985
10986 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10987 // If we can fold the condition, just take that operand.
10988 bool CondResult;
10989 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10990 return TryGetExprRange(
10991 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
10992 InConstantContext, Approximate);
10993
10994 // Otherwise, conservatively merge.
10995 // TryGetExprRange requires an integer expression, but a throw expression
10996 // results in a void type.
10997 Expr *TrueExpr = CO->getTrueExpr();
10998 if (TrueExpr->getType()->isVoidType())
10999 return std::nullopt;
11000
11001 std::optional<IntRange> L =
11002 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
11003 if (!L)
11004 return std::nullopt;
11005
11006 Expr *FalseExpr = CO->getFalseExpr();
11007 if (FalseExpr->getType()->isVoidType())
11008 return std::nullopt;
11009
11010 std::optional<IntRange> R =
11011 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
11012 if (!R)
11013 return std::nullopt;
11014
11015 return IntRange::join(*L, *R);
11016 }
11017
11018 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11019 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11020
11021 switch (BO->getOpcode()) {
11022 case BO_Cmp:
11023 llvm_unreachable("builtin <=> should have class type");
11024
11025 // Boolean-valued operations are single-bit and positive.
11026 case BO_LAnd:
11027 case BO_LOr:
11028 case BO_LT:
11029 case BO_GT:
11030 case BO_LE:
11031 case BO_GE:
11032 case BO_EQ:
11033 case BO_NE:
11034 return IntRange::forBoolType();
11035
11036 // The type of the assignments is the type of the LHS, so the RHS
11037 // is not necessarily the same type.
11038 case BO_MulAssign:
11039 case BO_DivAssign:
11040 case BO_RemAssign:
11041 case BO_AddAssign:
11042 case BO_SubAssign:
11043 case BO_XorAssign:
11044 case BO_OrAssign:
11045 // TODO: bitfields?
11046 return IntRange::forValueOfType(C, GetExprType(E));
11047
11048 // Simple assignments just pass through the RHS, which will have
11049 // been coerced to the LHS type.
11050 case BO_Assign:
11051 // TODO: bitfields?
11052 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11053 Approximate);
11054
11055 // Operations with opaque sources are black-listed.
11056 case BO_PtrMemD:
11057 case BO_PtrMemI:
11058 return IntRange::forValueOfType(C, GetExprType(E));
11059
11060 // Bitwise-and uses the *infinum* of the two source ranges.
11061 case BO_And:
11062 case BO_AndAssign:
11063 Combine = IntRange::bit_and;
11064 break;
11065
11066 // Left shift gets black-listed based on a judgement call.
11067 case BO_Shl:
11068 // ...except that we want to treat '1 << (blah)' as logically
11069 // positive. It's an important idiom.
11070 if (IntegerLiteral *I
11071 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11072 if (I->getValue() == 1) {
11073 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11074 return IntRange(R.Width, /*NonNegative*/ true);
11075 }
11076 }
11077 [[fallthrough]];
11078
11079 case BO_ShlAssign:
11080 return IntRange::forValueOfType(C, GetExprType(E));
11081
11082 // Right shift by a constant can narrow its left argument.
11083 case BO_Shr:
11084 case BO_ShrAssign: {
11085 std::optional<IntRange> L = TryGetExprRange(
11086 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11087 if (!L)
11088 return std::nullopt;
11089
11090 // If the shift amount is a positive constant, drop the width by
11091 // that much.
11092 if (std::optional<llvm::APSInt> shift =
11093 BO->getRHS()->getIntegerConstantExpr(C)) {
11094 if (shift->isNonNegative()) {
11095 if (shift->uge(L->Width))
11096 L->Width = (L->NonNegative ? 0 : 1);
11097 else
11098 L->Width -= shift->getZExtValue();
11099 }
11100 }
11101
11102 return L;
11103 }
11104
11105 // Comma acts as its right operand.
11106 case BO_Comma:
11107 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11108 Approximate);
11109
11110 case BO_Add:
11111 if (!Approximate)
11112 Combine = IntRange::sum;
11113 break;
11114
11115 case BO_Sub:
11116 if (BO->getLHS()->getType()->isPointerType())
11117 return IntRange::forValueOfType(C, GetExprType(E));
11118 if (!Approximate)
11119 Combine = IntRange::difference;
11120 break;
11121
11122 case BO_Mul:
11123 if (!Approximate)
11124 Combine = IntRange::product;
11125 break;
11126
11127 // The width of a division result is mostly determined by the size
11128 // of the LHS.
11129 case BO_Div: {
11130 // Don't 'pre-truncate' the operands.
11131 unsigned opWidth = C.getIntWidth(GetExprType(E));
11132 std::optional<IntRange> L = TryGetExprRange(
11133 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11134 if (!L)
11135 return std::nullopt;
11136
11137 // If the divisor is constant, use that.
11138 if (std::optional<llvm::APSInt> divisor =
11139 BO->getRHS()->getIntegerConstantExpr(C)) {
11140 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11141 if (log2 >= L->Width)
11142 L->Width = (L->NonNegative ? 0 : 1);
11143 else
11144 L->Width = std::min(L->Width - log2, MaxWidth);
11145 return L;
11146 }
11147
11148 // Otherwise, just use the LHS's width.
11149 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11150 // could be -1.
11151 std::optional<IntRange> R = TryGetExprRange(
11152 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11153 if (!R)
11154 return std::nullopt;
11155
11156 return IntRange(L->Width, L->NonNegative && R->NonNegative);
11157 }
11158
11159 case BO_Rem:
11160 Combine = IntRange::rem;
11161 break;
11162
11163 // The default behavior is okay for these.
11164 case BO_Xor:
11165 case BO_Or:
11166 break;
11167 }
11168
11169 // Combine the two ranges, but limit the result to the type in which we
11170 // performed the computation.
11171 QualType T = GetExprType(E);
11172 unsigned opWidth = C.getIntWidth(T);
11173 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
11174 InConstantContext, Approximate);
11175 if (!L)
11176 return std::nullopt;
11177
11178 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
11179 InConstantContext, Approximate);
11180 if (!R)
11181 return std::nullopt;
11182
11183 IntRange C = Combine(*L, *R);
11184 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11185 C.Width = std::min(C.Width, MaxWidth);
11186 return C;
11187 }
11188
11189 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11190 switch (UO->getOpcode()) {
11191 // Boolean-valued operations are white-listed.
11192 case UO_LNot:
11193 return IntRange::forBoolType();
11194
11195 // Operations with opaque sources are black-listed.
11196 case UO_Deref:
11197 case UO_AddrOf: // should be impossible
11198 return IntRange::forValueOfType(C, GetExprType(E));
11199
11200 case UO_Minus: {
11201 if (E->getType()->isUnsignedIntegerType()) {
11202 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11203 Approximate);
11204 }
11205
11206 std::optional<IntRange> SubRange = TryGetExprRange(
11207 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11208
11209 if (!SubRange)
11210 return std::nullopt;
11211
11212 // If the range was previously non-negative, we need an extra bit for the
11213 // sign bit. Otherwise, we need an extra bit because the negation of the
11214 // most-negative value is one bit wider than that value.
11215 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
11216 }
11217
11218 case UO_Not: {
11219 if (E->getType()->isUnsignedIntegerType()) {
11220 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11221 Approximate);
11222 }
11223
11224 std::optional<IntRange> SubRange = TryGetExprRange(
11225 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11226
11227 if (!SubRange)
11228 return std::nullopt;
11229
11230 // The width increments by 1 if the sub-expression cannot be negative
11231 // since it now can be.
11232 return IntRange(
11233 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
11234 false);
11235 }
11236
11237 default:
11238 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11239 Approximate);
11240 }
11241 }
11242
11243 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11244 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11245 Approximate);
11246
11247 if (const auto *BitField = E->getSourceBitField())
11248 return IntRange(BitField->getBitWidthValue(),
11249 BitField->getType()->isUnsignedIntegerOrEnumerationType());
11250
11251 if (GetExprType(E)->isVoidType())
11252 return std::nullopt;
11253
11254 return IntRange::forValueOfType(C, GetExprType(E));
11255}
11256
11257static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11258 bool InConstantContext,
11259 bool Approximate) {
11260 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11261 Approximate);
11262}
11263
11264/// Checks whether the given value, which currently has the given
11265/// source semantics, has the same value when coerced through the
11266/// target semantics.
11267static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11268 const llvm::fltSemantics &Src,
11269 const llvm::fltSemantics &Tgt) {
11270 llvm::APFloat truncated = value;
11271
11272 bool ignored;
11273 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11274 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11275
11276 return truncated.bitwiseIsEqual(value);
11277}
11278
11279/// Checks whether the given value, which currently has the given
11280/// source semantics, has the same value when coerced through the
11281/// target semantics.
11282///
11283/// The value might be a vector of floats (or a complex number).
11284static bool IsSameFloatAfterCast(const APValue &value,
11285 const llvm::fltSemantics &Src,
11286 const llvm::fltSemantics &Tgt) {
11287 if (value.isFloat())
11288 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11289
11290 if (value.isVector()) {
11291 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11292 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11293 return false;
11294 return true;
11295 }
11296
11297 assert(value.isComplexFloat());
11298 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11299 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11300}
11301
11302static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11303 bool IsListInit = false);
11304
11305static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
11306 // Suppress cases where we are comparing against an enum constant.
11307 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11308 if (isa<EnumConstantDecl>(DR->getDecl()))
11309 return true;
11310
11311 // Suppress cases where the value is expanded from a macro, unless that macro
11312 // is how a language represents a boolean literal. This is the case in both C
11313 // and Objective-C.
11314 SourceLocation BeginLoc = E->getBeginLoc();
11315 if (BeginLoc.isMacroID()) {
11316 StringRef MacroName = Lexer::getImmediateMacroName(
11317 BeginLoc, S.getSourceManager(), S.getLangOpts());
11318 return MacroName != "YES" && MacroName != "NO" &&
11319 MacroName != "true" && MacroName != "false";
11320 }
11321
11322 return false;
11323}
11324
11325static bool isKnownToHaveUnsignedValue(const Expr *E) {
11326 return E->getType()->isIntegerType() &&
11327 (!E->getType()->isSignedIntegerType() ||
11329}
11330
11331namespace {
11332/// The promoted range of values of a type. In general this has the
11333/// following structure:
11334///
11335/// |-----------| . . . |-----------|
11336/// ^ ^ ^ ^
11337/// Min HoleMin HoleMax Max
11338///
11339/// ... where there is only a hole if a signed type is promoted to unsigned
11340/// (in which case Min and Max are the smallest and largest representable
11341/// values).
11342struct PromotedRange {
11343 // Min, or HoleMax if there is a hole.
11344 llvm::APSInt PromotedMin;
11345 // Max, or HoleMin if there is a hole.
11346 llvm::APSInt PromotedMax;
11347
11348 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11349 if (R.Width == 0)
11350 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11351 else if (R.Width >= BitWidth && !Unsigned) {
11352 // Promotion made the type *narrower*. This happens when promoting
11353 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11354 // Treat all values of 'signed int' as being in range for now.
11355 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11356 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11357 } else {
11358 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11359 .extOrTrunc(BitWidth);
11360 PromotedMin.setIsUnsigned(Unsigned);
11361
11362 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11363 .extOrTrunc(BitWidth);
11364 PromotedMax.setIsUnsigned(Unsigned);
11365 }
11366 }
11367
11368 // Determine whether this range is contiguous (has no hole).
11369 bool isContiguous() const { return PromotedMin <= PromotedMax; }
11370
11371 // Where a constant value is within the range.
11372 enum ComparisonResult {
11373 LT = 0x1,
11374 LE = 0x2,
11375 GT = 0x4,
11376 GE = 0x8,
11377 EQ = 0x10,
11378 NE = 0x20,
11379 InRangeFlag = 0x40,
11380
11381 Less = LE | LT | NE,
11382 Min = LE | InRangeFlag,
11383 InRange = InRangeFlag,
11384 Max = GE | InRangeFlag,
11385 Greater = GE | GT | NE,
11386
11387 OnlyValue = LE | GE | EQ | InRangeFlag,
11388 InHole = NE
11389 };
11390
11391 ComparisonResult compare(const llvm::APSInt &Value) const {
11392 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11393 Value.isUnsigned() == PromotedMin.isUnsigned());
11394 if (!isContiguous()) {
11395 assert(Value.isUnsigned() && "discontiguous range for signed compare");
11396 if (Value.isMinValue()) return Min;
11397 if (Value.isMaxValue()) return Max;
11398 if (Value >= PromotedMin) return InRange;
11399 if (Value <= PromotedMax) return InRange;
11400 return InHole;
11401 }
11402
11403 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11404 case -1: return Less;
11405 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11406 case 1:
11407 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11408 case -1: return InRange;
11409 case 0: return Max;
11410 case 1: return Greater;
11411 }
11412 }
11413
11414 llvm_unreachable("impossible compare result");
11415 }
11416
11417 static std::optional<StringRef>
11418 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11419 if (Op == BO_Cmp) {
11420 ComparisonResult LTFlag = LT, GTFlag = GT;
11421 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11422
11423 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11424 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11425 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11426 return std::nullopt;
11427 }
11428
11429 ComparisonResult TrueFlag, FalseFlag;
11430 if (Op == BO_EQ) {
11431 TrueFlag = EQ;
11432 FalseFlag = NE;
11433 } else if (Op == BO_NE) {
11434 TrueFlag = NE;
11435 FalseFlag = EQ;
11436 } else {
11437 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11438 TrueFlag = LT;
11439 FalseFlag = GE;
11440 } else {
11441 TrueFlag = GT;
11442 FalseFlag = LE;
11443 }
11444 if (Op == BO_GE || Op == BO_LE)
11445 std::swap(TrueFlag, FalseFlag);
11446 }
11447 if (R & TrueFlag)
11448 return StringRef("true");
11449 if (R & FalseFlag)
11450 return StringRef("false");
11451 return std::nullopt;
11452 }
11453};
11454}
11455
11456static bool HasEnumType(const Expr *E) {
11457 // Strip off implicit integral promotions.
11458 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11459 if (ICE->getCastKind() != CK_IntegralCast &&
11460 ICE->getCastKind() != CK_NoOp)
11461 break;
11462 E = ICE->getSubExpr();
11463 }
11464
11465 return E->getType()->isEnumeralType();
11466}
11467
11468static int classifyConstantValue(Expr *Constant) {
11469 // The values of this enumeration are used in the diagnostics
11470 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11471 enum ConstantValueKind {
11472 Miscellaneous = 0,
11473 LiteralTrue,
11474 LiteralFalse
11475 };
11476 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11477 return BL->getValue() ? ConstantValueKind::LiteralTrue
11478 : ConstantValueKind::LiteralFalse;
11479 return ConstantValueKind::Miscellaneous;
11480}
11481
11483 Expr *Constant, Expr *Other,
11484 const llvm::APSInt &Value,
11485 bool RhsConstant) {
11487 return false;
11488
11489 Expr *OriginalOther = Other;
11490
11491 Constant = Constant->IgnoreParenImpCasts();
11492 Other = Other->IgnoreParenImpCasts();
11493
11494 // Suppress warnings on tautological comparisons between values of the same
11495 // enumeration type. There are only two ways we could warn on this:
11496 // - If the constant is outside the range of representable values of
11497 // the enumeration. In such a case, we should warn about the cast
11498 // to enumeration type, not about the comparison.
11499 // - If the constant is the maximum / minimum in-range value. For an
11500 // enumeratin type, such comparisons can be meaningful and useful.
11501 if (Constant->getType()->isEnumeralType() &&
11502 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11503 return false;
11504
11505 std::optional<IntRange> OtherValueRange = TryGetExprRange(
11506 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
11507 if (!OtherValueRange)
11508 return false;
11509
11510 QualType OtherT = Other->getType();
11511 if (const auto *AT = OtherT->getAs<AtomicType>())
11512 OtherT = AT->getValueType();
11513 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11514
11515 // Special case for ObjC BOOL on targets where its a typedef for a signed char
11516 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11517 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11518 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
11519 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11520
11521 // Whether we're treating Other as being a bool because of the form of
11522 // expression despite it having another type (typically 'int' in C).
11523 bool OtherIsBooleanDespiteType =
11524 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11525 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11526 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
11527
11528 // Check if all values in the range of possible values of this expression
11529 // lead to the same comparison outcome.
11530 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
11531 Value.isUnsigned());
11532 auto Cmp = OtherPromotedValueRange.compare(Value);
11533 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11534 if (!Result)
11535 return false;
11536
11537 // Also consider the range determined by the type alone. This allows us to
11538 // classify the warning under the proper diagnostic group.
11539 bool TautologicalTypeCompare = false;
11540 {
11541 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11542 Value.isUnsigned());
11543 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11544 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11545 RhsConstant)) {
11546 TautologicalTypeCompare = true;
11547 Cmp = TypeCmp;
11548 Result = TypeResult;
11549 }
11550 }
11551
11552 // Don't warn if the non-constant operand actually always evaluates to the
11553 // same value.
11554 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
11555 return false;
11556
11557 // Suppress the diagnostic for an in-range comparison if the constant comes
11558 // from a macro or enumerator. We don't want to diagnose
11559 //
11560 // some_long_value <= INT_MAX
11561 //
11562 // when sizeof(int) == sizeof(long).
11563 bool InRange = Cmp & PromotedRange::InRangeFlag;
11564 if (InRange && IsEnumConstOrFromMacro(S, Constant))
11565 return false;
11566
11567 // A comparison of an unsigned bit-field against 0 is really a type problem,
11568 // even though at the type level the bit-field might promote to 'signed int'.
11569 if (Other->refersToBitField() && InRange && Value == 0 &&
11570 Other->getType()->isUnsignedIntegerOrEnumerationType())
11571 TautologicalTypeCompare = true;
11572
11573 // If this is a comparison to an enum constant, include that
11574 // constant in the diagnostic.
11575 const EnumConstantDecl *ED = nullptr;
11576 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
11577 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11578
11579 // Should be enough for uint128 (39 decimal digits)
11580 SmallString<64> PrettySourceValue;
11581 llvm::raw_svector_ostream OS(PrettySourceValue);
11582 if (ED) {
11583 OS << '\'' << *ED << "' (" << Value << ")";
11584 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11585 Constant->IgnoreParenImpCasts())) {
11586 OS << (BL->getValue() ? "YES" : "NO");
11587 } else {
11588 OS << Value;
11589 }
11590
11591 if (!TautologicalTypeCompare) {
11592 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11593 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
11594 << E->getOpcodeStr() << OS.str() << *Result
11595 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11596 return true;
11597 }
11598
11599 if (IsObjCSignedCharBool) {
11601 S.PDiag(diag::warn_tautological_compare_objc_bool)
11602 << OS.str() << *Result);
11603 return true;
11604 }
11605
11606 // FIXME: We use a somewhat different formatting for the in-range cases and
11607 // cases involving boolean values for historical reasons. We should pick a
11608 // consistent way of presenting these diagnostics.
11609 if (!InRange || Other->isKnownToHaveBooleanValue()) {
11610
11612 E->getOperatorLoc(), E,
11613 S.PDiag(!InRange ? diag::warn_out_of_range_compare
11614 : diag::warn_tautological_bool_compare)
11615 << OS.str() << classifyConstantValue(Constant) << OtherT
11616 << OtherIsBooleanDespiteType << *Result
11617 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11618 } else {
11619 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11620 unsigned Diag =
11621 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11622 ? (HasEnumType(OriginalOther)
11623 ? diag::warn_unsigned_enum_always_true_comparison
11624 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11625 : diag::warn_unsigned_always_true_comparison)
11626 : diag::warn_tautological_constant_compare;
11627
11628 S.Diag(E->getOperatorLoc(), Diag)
11629 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11630 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11631 }
11632
11633 return true;
11634}
11635
11636/// Analyze the operands of the given comparison. Implements the
11637/// fallback case from AnalyzeComparison.
11642
11643/// Implements -Wsign-compare.
11644///
11645/// \param E the binary operator to check for warnings
11647 // The type the comparison is being performed in.
11648 QualType T = E->getLHS()->getType();
11649
11650 // Only analyze comparison operators where both sides have been converted to
11651 // the same type.
11653 return AnalyzeImpConvsInComparison(S, E);
11654
11655 // Don't analyze value-dependent comparisons directly.
11656 if (E->isValueDependent())
11657 return AnalyzeImpConvsInComparison(S, E);
11658
11659 Expr *LHS = E->getLHS();
11660 Expr *RHS = E->getRHS();
11661
11662 if (T->isIntegralType(S.Context)) {
11663 std::optional<llvm::APSInt> RHSValue =
11665 std::optional<llvm::APSInt> LHSValue =
11667
11668 // We don't care about expressions whose result is a constant.
11669 if (RHSValue && LHSValue)
11670 return AnalyzeImpConvsInComparison(S, E);
11671
11672 // We only care about expressions where just one side is literal
11673 if ((bool)RHSValue ^ (bool)LHSValue) {
11674 // Is the constant on the RHS or LHS?
11675 const bool RhsConstant = (bool)RHSValue;
11676 Expr *Const = RhsConstant ? RHS : LHS;
11677 Expr *Other = RhsConstant ? LHS : RHS;
11678 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11679
11680 // Check whether an integer constant comparison results in a value
11681 // of 'true' or 'false'.
11682 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11683 return AnalyzeImpConvsInComparison(S, E);
11684 }
11685 }
11686
11687 if (!T->hasUnsignedIntegerRepresentation()) {
11688 // We don't do anything special if this isn't an unsigned integral
11689 // comparison: we're only interested in integral comparisons, and
11690 // signed comparisons only happen in cases we don't care to warn about.
11691 return AnalyzeImpConvsInComparison(S, E);
11692 }
11693
11694 LHS = LHS->IgnoreParenImpCasts();
11695 RHS = RHS->IgnoreParenImpCasts();
11696
11697 if (!S.getLangOpts().CPlusPlus) {
11698 // Avoid warning about comparison of integers with different signs when
11699 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11700 // the type of `E`.
11701 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11702 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11703 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11704 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11705 }
11706
11707 // Check to see if one of the (unmodified) operands is of different
11708 // signedness.
11709 Expr *signedOperand, *unsignedOperand;
11711 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11712 "unsigned comparison between two signed integer expressions?");
11713 signedOperand = LHS;
11714 unsignedOperand = RHS;
11715 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11716 signedOperand = RHS;
11717 unsignedOperand = LHS;
11718 } else {
11719 return AnalyzeImpConvsInComparison(S, E);
11720 }
11721
11722 // Otherwise, calculate the effective range of the signed operand.
11723 std::optional<IntRange> signedRange =
11725 /*Approximate=*/true);
11726 if (!signedRange)
11727 return;
11728
11729 // Go ahead and analyze implicit conversions in the operands. Note
11730 // that we skip the implicit conversions on both sides.
11733
11734 // If the signed range is non-negative, -Wsign-compare won't fire.
11735 if (signedRange->NonNegative)
11736 return;
11737
11738 // For (in)equality comparisons, if the unsigned operand is a
11739 // constant which cannot collide with a overflowed signed operand,
11740 // then reinterpreting the signed operand as unsigned will not
11741 // change the result of the comparison.
11742 if (E->isEqualityOp()) {
11743 unsigned comparisonWidth = S.Context.getIntWidth(T);
11744 std::optional<IntRange> unsignedRange = TryGetExprRange(
11745 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
11746 /*Approximate=*/true);
11747 if (!unsignedRange)
11748 return;
11749
11750 // We should never be unable to prove that the unsigned operand is
11751 // non-negative.
11752 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
11753
11754 if (unsignedRange->Width < comparisonWidth)
11755 return;
11756 }
11757
11759 S.PDiag(diag::warn_mixed_sign_comparison)
11760 << LHS->getType() << RHS->getType()
11761 << LHS->getSourceRange() << RHS->getSourceRange());
11762}
11763
11764/// Analyzes an attempt to assign the given value to a bitfield.
11765///
11766/// Returns true if there was something fishy about the attempt.
11768 SourceLocation InitLoc) {
11769 assert(Bitfield->isBitField());
11770 if (Bitfield->isInvalidDecl())
11771 return false;
11772
11773 // White-list bool bitfields.
11774 QualType BitfieldType = Bitfield->getType();
11775 if (BitfieldType->isBooleanType())
11776 return false;
11777
11778 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
11779 // If the underlying enum type was not explicitly specified as an unsigned
11780 // type and the enum contain only positive values, MSVC++ will cause an
11781 // inconsistency by storing this as a signed type.
11782 if (S.getLangOpts().CPlusPlus11 &&
11783 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11784 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11785 BitfieldEnumDecl->getNumNegativeBits() == 0) {
11786 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11787 << BitfieldEnumDecl;
11788 }
11789 }
11790
11791 // Ignore value- or type-dependent expressions.
11792 if (Bitfield->getBitWidth()->isValueDependent() ||
11793 Bitfield->getBitWidth()->isTypeDependent() ||
11794 Init->isValueDependent() ||
11795 Init->isTypeDependent())
11796 return false;
11797
11798 Expr *OriginalInit = Init->IgnoreParenImpCasts();
11799 unsigned FieldWidth = Bitfield->getBitWidthValue();
11800
11801 Expr::EvalResult Result;
11802 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11804 // The RHS is not constant. If the RHS has an enum type, make sure the
11805 // bitfield is wide enough to hold all the values of the enum without
11806 // truncation.
11807 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
11808 const PreferredTypeAttr *PTAttr = nullptr;
11809 if (!ED) {
11810 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
11811 if (PTAttr)
11812 ED = PTAttr->getType()->getAsEnumDecl();
11813 }
11814 if (ED) {
11815 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
11816
11817 // Enum types are implicitly signed on Windows, so check if there are any
11818 // negative enumerators to see if the enum was intended to be signed or
11819 // not.
11820 bool SignedEnum = ED->getNumNegativeBits() > 0;
11821
11822 // Check for surprising sign changes when assigning enum values to a
11823 // bitfield of different signedness. If the bitfield is signed and we
11824 // have exactly the right number of bits to store this unsigned enum,
11825 // suggest changing the enum to an unsigned type. This typically happens
11826 // on Windows where unfixed enums always use an underlying type of 'int'.
11827 unsigned DiagID = 0;
11828 if (SignedEnum && !SignedBitfield) {
11829 DiagID =
11830 PTAttr == nullptr
11831 ? diag::warn_unsigned_bitfield_assigned_signed_enum
11832 : diag::
11833 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
11834 } else if (SignedBitfield && !SignedEnum &&
11835 ED->getNumPositiveBits() == FieldWidth) {
11836 DiagID =
11837 PTAttr == nullptr
11838 ? diag::warn_signed_bitfield_enum_conversion
11839 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
11840 }
11841 if (DiagID) {
11842 S.Diag(InitLoc, DiagID) << Bitfield << ED;
11843 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11844 SourceRange TypeRange =
11845 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11846 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11847 << SignedEnum << TypeRange;
11848 if (PTAttr)
11849 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
11850 << ED;
11851 }
11852
11853 // Compute the required bitwidth. If the enum has negative values, we need
11854 // one more bit than the normal number of positive bits to represent the
11855 // sign bit.
11856 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11857 ED->getNumNegativeBits())
11858 : ED->getNumPositiveBits();
11859
11860 // Check the bitwidth.
11861 if (BitsNeeded > FieldWidth) {
11862 Expr *WidthExpr = Bitfield->getBitWidth();
11863 auto DiagID =
11864 PTAttr == nullptr
11865 ? diag::warn_bitfield_too_small_for_enum
11866 : diag::warn_preferred_type_bitfield_too_small_for_enum;
11867 S.Diag(InitLoc, DiagID) << Bitfield << ED;
11868 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11869 << BitsNeeded << ED << WidthExpr->getSourceRange();
11870 if (PTAttr)
11871 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
11872 << ED;
11873 }
11874 }
11875
11876 return false;
11877 }
11878
11879 llvm::APSInt Value = Result.Val.getInt();
11880
11881 unsigned OriginalWidth = Value.getBitWidth();
11882
11883 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
11884 // false positives where the user is demonstrating they intend to use the
11885 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
11886 // to a one-bit bit-field to see if the value came from a macro named 'true'.
11887 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
11888 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
11889 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
11890 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
11891 S.findMacroSpelling(MaybeMacroLoc, "true"))
11892 return false;
11893 }
11894
11895 if (!Value.isSigned() || Value.isNegative())
11896 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11897 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11898 OriginalWidth = Value.getSignificantBits();
11899
11900 if (OriginalWidth <= FieldWidth)
11901 return false;
11902
11903 // Compute the value which the bitfield will contain.
11904 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11905 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11906
11907 // Check whether the stored value is equal to the original value.
11908 TruncatedValue = TruncatedValue.extend(OriginalWidth);
11909 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11910 return false;
11911
11912 std::string PrettyValue = toString(Value, 10);
11913 std::string PrettyTrunc = toString(TruncatedValue, 10);
11914
11915 S.Diag(InitLoc, OneAssignedToOneBitBitfield
11916 ? diag::warn_impcast_single_bit_bitield_precision_constant
11917 : diag::warn_impcast_bitfield_precision_constant)
11918 << PrettyValue << PrettyTrunc << OriginalInit->getType()
11919 << Init->getSourceRange();
11920
11921 return true;
11922}
11923
11924/// Analyze the given simple or compound assignment for warning-worthy
11925/// operations.
11927 // Just recurse on the LHS.
11929
11930 // We want to recurse on the RHS as normal unless we're assigning to
11931 // a bitfield.
11932 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11933 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11934 E->getOperatorLoc())) {
11935 // Recurse, ignoring any implicit conversions on the RHS.
11937 E->getOperatorLoc());
11938 }
11939 }
11940
11942
11943 // Diagnose implicitly sequentially-consistent atomic assignment.
11944 if (E->getLHS()->getType()->isAtomicType())
11945 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11946}
11947
11948/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
11949static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
11950 QualType T, SourceLocation CContext, unsigned diag,
11951 bool PruneControlFlow = false) {
11952 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
11953 // address space annotations isn't really useful. The warnings aren't because
11954 // you're converting a `private int` to `unsigned int`, it is because you're
11955 // conerting `int` to `unsigned int`.
11956 if (SourceType.hasAddressSpace())
11957 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
11958 if (T.hasAddressSpace())
11960 if (PruneControlFlow) {
11962 S.PDiag(diag)
11963 << SourceType << T << E->getSourceRange()
11964 << SourceRange(CContext));
11965 return;
11966 }
11967 S.Diag(E->getExprLoc(), diag)
11968 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11969}
11970
11971/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
11972static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
11973 SourceLocation CContext, unsigned diag,
11974 bool PruneControlFlow = false) {
11975 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
11976}
11977
11978/// Diagnose an implicit cast from a floating point value to an integer value.
11979static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
11980 SourceLocation CContext) {
11981 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11982 bool PruneWarnings = S.inTemplateInstantiation();
11983
11984 const Expr *InnerE = E->IgnoreParenImpCasts();
11985 // We also want to warn on, e.g., "int i = -1.234"
11986 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
11987 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11988 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11989
11990 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11991
11992 llvm::APFloat Value(0.0);
11993 bool IsConstant =
11995 if (!IsConstant) {
11996 if (S.ObjC().isSignedCharBool(T)) {
11998 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11999 << E->getType());
12000 }
12001
12002 return DiagnoseImpCast(S, E, T, CContext,
12003 diag::warn_impcast_float_integer, PruneWarnings);
12004 }
12005
12006 bool isExact = false;
12007
12008 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12009 T->hasUnsignedIntegerRepresentation());
12010 llvm::APFloat::opStatus Result = Value.convertToInteger(
12011 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12012
12013 // FIXME: Force the precision of the source value down so we don't print
12014 // digits which are usually useless (we don't really care here if we
12015 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12016 // would automatically print the shortest representation, but it's a bit
12017 // tricky to implement.
12018 SmallString<16> PrettySourceValue;
12019 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12020 precision = (precision * 59 + 195) / 196;
12021 Value.toString(PrettySourceValue, precision);
12022
12023 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
12025 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12026 << PrettySourceValue);
12027 }
12028
12029 if (Result == llvm::APFloat::opOK && isExact) {
12030 if (IsLiteral) return;
12031 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12032 PruneWarnings);
12033 }
12034
12035 // Conversion of a floating-point value to a non-bool integer where the
12036 // integral part cannot be represented by the integer type is undefined.
12037 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12038 return DiagnoseImpCast(
12039 S, E, T, CContext,
12040 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12041 : diag::warn_impcast_float_to_integer_out_of_range,
12042 PruneWarnings);
12043
12044 unsigned DiagID = 0;
12045 if (IsLiteral) {
12046 // Warn on floating point literal to integer.
12047 DiagID = diag::warn_impcast_literal_float_to_integer;
12048 } else if (IntegerValue == 0) {
12049 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
12050 return DiagnoseImpCast(S, E, T, CContext,
12051 diag::warn_impcast_float_integer, PruneWarnings);
12052 }
12053 // Warn on non-zero to zero conversion.
12054 DiagID = diag::warn_impcast_float_to_integer_zero;
12055 } else {
12056 if (IntegerValue.isUnsigned()) {
12057 if (!IntegerValue.isMaxValue()) {
12058 return DiagnoseImpCast(S, E, T, CContext,
12059 diag::warn_impcast_float_integer, PruneWarnings);
12060 }
12061 } else { // IntegerValue.isSigned()
12062 if (!IntegerValue.isMaxSignedValue() &&
12063 !IntegerValue.isMinSignedValue()) {
12064 return DiagnoseImpCast(S, E, T, CContext,
12065 diag::warn_impcast_float_integer, PruneWarnings);
12066 }
12067 }
12068 // Warn on evaluatable floating point expression to integer conversion.
12069 DiagID = diag::warn_impcast_float_to_integer;
12070 }
12071
12072 SmallString<16> PrettyTargetValue;
12073 if (IsBool)
12074 PrettyTargetValue = Value.isZero() ? "false" : "true";
12075 else
12076 IntegerValue.toString(PrettyTargetValue);
12077
12078 if (PruneWarnings) {
12080 S.PDiag(DiagID)
12081 << E->getType() << T.getUnqualifiedType()
12082 << PrettySourceValue << PrettyTargetValue
12083 << E->getSourceRange() << SourceRange(CContext));
12084 } else {
12085 S.Diag(E->getExprLoc(), DiagID)
12086 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12087 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12088 }
12089}
12090
12091/// Analyze the given compound assignment for the possible losing of
12092/// floating-point precision.
12094 assert(isa<CompoundAssignOperator>(E) &&
12095 "Must be compound assignment operation");
12096 // Recurse on the LHS and RHS in here
12099
12100 if (E->getLHS()->getType()->isAtomicType())
12101 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12102
12103 // Now check the outermost expression
12104 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12105 const auto *RBT = cast<CompoundAssignOperator>(E)
12106 ->getComputationResultType()
12107 ->getAs<BuiltinType>();
12108
12109 // The below checks assume source is floating point.
12110 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12111
12112 // If source is floating point but target is an integer.
12113 if (ResultBT->isInteger())
12114 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12115 E->getExprLoc(), diag::warn_impcast_float_integer);
12116
12117 if (!ResultBT->isFloatingPoint())
12118 return;
12119
12120 // If both source and target are floating points, warn about losing precision.
12122 QualType(ResultBT, 0), QualType(RBT, 0));
12123 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12124 // warn about dropping FP rank.
12125 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12126 diag::warn_impcast_float_result_precision);
12127}
12128
12129static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12130 IntRange Range) {
12131 if (!Range.Width) return "0";
12132
12133 llvm::APSInt ValueInRange = Value;
12134 ValueInRange.setIsSigned(!Range.NonNegative);
12135 ValueInRange = ValueInRange.trunc(Range.Width);
12136 return toString(ValueInRange, 10);
12137}
12138
12139static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
12140 bool ToBool) {
12141 if (!isa<ImplicitCastExpr>(Ex))
12142 return false;
12143
12144 const Expr *InnerE = Ex->IgnoreParenImpCasts();
12146 const Type *Source =
12148 if (Target->isDependentType())
12149 return false;
12150
12151 const auto *FloatCandidateBT =
12152 dyn_cast<BuiltinType>(ToBool ? Source : Target);
12153 const Type *BoolCandidateType = ToBool ? Target : Source;
12154
12155 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12156 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12157}
12158
12159static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
12160 SourceLocation CC) {
12161 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
12162 const Expr *CurrA = TheCall->getArg(I);
12163 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12164 continue;
12165
12166 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
12167 S, TheCall->getArg(I - 1), false));
12168 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
12169 S, TheCall->getArg(I + 1), false));
12170 if (IsSwapped) {
12171 // Warn on this floating-point to bool conversion.
12173 CurrA->getType(), CC,
12174 diag::warn_impcast_floating_point_to_bool);
12175 }
12176 }
12177}
12178
12180 SourceLocation CC) {
12181 // Don't warn on functions which have return type nullptr_t.
12182 if (isa<CallExpr>(E))
12183 return;
12184
12185 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12186 const Expr *NewE = E->IgnoreParenImpCasts();
12187 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
12188 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12189 if (!IsGNUNullExpr && !HasNullPtrType)
12190 return;
12191
12192 // Return if target type is a safe conversion.
12193 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12194 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12195 return;
12196
12197 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12198 E->getExprLoc()))
12199 return;
12200
12202
12203 // Venture through the macro stacks to get to the source of macro arguments.
12204 // The new location is a better location than the complete location that was
12205 // passed in.
12206 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12208
12209 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12210 if (IsGNUNullExpr && Loc.isMacroID()) {
12211 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12212 Loc, S.SourceMgr, S.getLangOpts());
12213 if (MacroName == "NULL")
12215 }
12216
12217 // Only warn if the null and context location are in the same macro expansion.
12218 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12219 return;
12220
12221 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12222 << HasNullPtrType << T << SourceRange(CC)
12225}
12226
12227// Helper function to filter out cases for constant width constant conversion.
12228// Don't warn on char array initialization or for non-decimal values.
12230 SourceLocation CC) {
12231 // If initializing from a constant, and the constant starts with '0',
12232 // then it is a binary, octal, or hexadecimal. Allow these constants
12233 // to fill all the bits, even if there is a sign change.
12234 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12235 const char FirstLiteralCharacter =
12236 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12237 if (FirstLiteralCharacter == '0')
12238 return false;
12239 }
12240
12241 // If the CC location points to a '{', and the type is char, then assume
12242 // assume it is an array initialization.
12243 if (CC.isValid() && T->isCharType()) {
12244 const char FirstContextCharacter =
12246 if (FirstContextCharacter == '{')
12247 return false;
12248 }
12249
12250 return true;
12251}
12252
12254 const auto *IL = dyn_cast<IntegerLiteral>(E);
12255 if (!IL) {
12256 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12257 if (UO->getOpcode() == UO_Minus)
12258 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12259 }
12260 }
12261
12262 return IL;
12263}
12264
12266 E = E->IgnoreParenImpCasts();
12267 SourceLocation ExprLoc = E->getExprLoc();
12268
12269 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12270 BinaryOperator::Opcode Opc = BO->getOpcode();
12271 Expr::EvalResult Result;
12272 // Do not diagnose unsigned shifts.
12273 if (Opc == BO_Shl) {
12274 const auto *LHS = getIntegerLiteral(BO->getLHS());
12275 const auto *RHS = getIntegerLiteral(BO->getRHS());
12276 if (LHS && LHS->getValue() == 0)
12277 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12278 else if (!E->isValueDependent() && LHS && RHS &&
12279 RHS->getValue().isNonNegative() &&
12281 S.Diag(ExprLoc, diag::warn_left_shift_always)
12282 << (Result.Val.getInt() != 0);
12283 else if (E->getType()->isSignedIntegerType())
12284 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
12287 ") != 0");
12288 }
12289 }
12290
12291 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12292 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12293 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12294 if (!LHS || !RHS)
12295 return;
12296 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12297 (RHS->getValue() == 0 || RHS->getValue() == 1))
12298 // Do not diagnose common idioms.
12299 return;
12300 if (LHS->getValue() != 0 && RHS->getValue() != 0)
12301 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12302 }
12303}
12304
12306 const Type *Target, Expr *E,
12307 QualType T,
12308 SourceLocation CC) {
12309 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
12310 Source != Target);
12311 Expr::EvalResult Result;
12314 llvm::APSInt Value(32);
12315 Value = Result.Val.getInt();
12316 bool IsASCII = Value <= 0x7F;
12317 bool IsBMP = Value <= 0xD7FF || (Value >= 0xE000 && Value <= 0xFFFF);
12318 bool ConversionPreservesSemantics =
12319 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
12320
12321 if (!ConversionPreservesSemantics) {
12322 auto IsSingleCodeUnitCP = [](const QualType &T,
12323 const llvm::APSInt &Value) {
12324 if (T->isChar8Type())
12325 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
12326 if (T->isChar16Type())
12327 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
12328 assert(T->isChar32Type());
12329 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
12330 };
12331
12332 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
12333 << E->getType() << T
12334 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
12335 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
12336 }
12337 } else {
12338 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
12340 DiagnoseImpCast(S, E, T, CC,
12341 LosesPrecision ? diag::warn_impcast_unicode_precision
12342 : diag::warn_impcast_unicode_char_type);
12343 }
12344}
12345
12351
12353 QualType To) {
12354 QualType MaybePointee = From->getPointeeType();
12355 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12356 From = MaybePointee;
12357 MaybePointee = To->getPointeeType();
12358 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12359 To = MaybePointee;
12360
12361 if (const auto *FromFn = From->getAs<FunctionType>()) {
12362 if (const auto *ToFn = To->getAs<FunctionType>()) {
12363 if (FromFn->getCFIUncheckedCalleeAttr() &&
12364 !ToFn->getCFIUncheckedCalleeAttr())
12365 return Discarding;
12366 if (!FromFn->getCFIUncheckedCalleeAttr() &&
12367 ToFn->getCFIUncheckedCalleeAttr())
12368 return Adding;
12369 }
12370 }
12371 return None;
12372}
12373
12375 From = Context.getCanonicalType(From);
12376 To = Context.getCanonicalType(To);
12377 return ::AdjustingCFIUncheckedCallee(From, To) == Discarding;
12378}
12379
12381 From = Context.getCanonicalType(From);
12382 To = Context.getCanonicalType(To);
12383 return ::AdjustingCFIUncheckedCallee(From, To) == Adding;
12384}
12385
12387 bool *ICContext, bool IsListInit) {
12388 if (E->isTypeDependent() || E->isValueDependent()) return;
12389
12390 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
12391 const Type *Target = Context.getCanonicalType(T).getTypePtr();
12392 if (Source == Target) return;
12393 if (Target->isDependentType()) return;
12394
12395 // If the conversion context location is invalid don't complain. We also
12396 // don't want to emit a warning if the issue occurs from the expansion of
12397 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12398 // delay this check as long as possible. Once we detect we are in that
12399 // scenario, we just return.
12400 if (CC.isInvalid())
12401 return;
12402
12403 if (Source->isAtomicType())
12404 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12405
12406 // Diagnose implicit casts to bool.
12407 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12408 if (isa<StringLiteral>(E))
12409 // Warn on string literal to bool. Checks for string literals in logical
12410 // and expressions, for instance, assert(0 && "error here"), are
12411 // prevented by a check in AnalyzeImplicitConversions().
12412 return DiagnoseImpCast(*this, E, T, CC,
12413 diag::warn_impcast_string_literal_to_bool);
12416 // This covers the literal expressions that evaluate to Objective-C
12417 // objects.
12418 return DiagnoseImpCast(*this, E, T, CC,
12419 diag::warn_impcast_objective_c_literal_to_bool);
12420 }
12421 if (Source->isPointerType() || Source->canDecayToPointerType()) {
12422 // Warn on pointer to bool conversion that is always true.
12424 SourceRange(CC));
12425 }
12426 }
12427
12428 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12429 // is a typedef for signed char (macOS), then that constant value has to be 1
12430 // or 0.
12431 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
12434 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12436 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12437 << toString(Result.Val.getInt(), 10));
12438 }
12439 return;
12440 }
12441 }
12442
12443 // Check implicit casts from Objective-C collection literals to specialized
12444 // collection types, e.g., NSArray<NSString *> *.
12445 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12446 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
12447 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12448 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
12449
12450 // Strip vector types.
12451 if (isa<VectorType>(Source)) {
12452 if (Target->isSveVLSBuiltinType() &&
12453 (ARM().areCompatibleSveTypes(QualType(Target, 0),
12454 QualType(Source, 0)) ||
12455 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
12456 QualType(Source, 0))))
12457 return;
12458
12459 if (Target->isRVVVLSBuiltinType() &&
12460 (Context.areCompatibleRVVTypes(QualType(Target, 0),
12461 QualType(Source, 0)) ||
12462 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
12463 QualType(Source, 0))))
12464 return;
12465
12466 if (!isa<VectorType>(Target)) {
12467 if (SourceMgr.isInSystemMacro(CC))
12468 return;
12469 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
12470 } else if (getLangOpts().HLSL &&
12471 Target->castAs<VectorType>()->getNumElements() <
12472 Source->castAs<VectorType>()->getNumElements()) {
12473 // Diagnose vector truncation but don't return. We may also want to
12474 // diagnose an element conversion.
12475 DiagnoseImpCast(*this, E, T, CC,
12476 diag::warn_hlsl_impcast_vector_truncation);
12477 }
12478
12479 // If the vector cast is cast between two vectors of the same size, it is
12480 // a bitcast, not a conversion, except under HLSL where it is a conversion.
12481 if (!getLangOpts().HLSL &&
12482 Context.getTypeSize(Source) == Context.getTypeSize(Target))
12483 return;
12484
12485 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12486 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12487 }
12488 if (auto VecTy = dyn_cast<VectorType>(Target))
12489 Target = VecTy->getElementType().getTypePtr();
12490
12491 // Strip complex types.
12492 if (isa<ComplexType>(Source)) {
12493 if (!isa<ComplexType>(Target)) {
12494 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12495 return;
12496
12497 return DiagnoseImpCast(*this, E, T, CC,
12499 ? diag::err_impcast_complex_scalar
12500 : diag::warn_impcast_complex_scalar);
12501 }
12502
12503 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12504 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12505 }
12506
12507 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12508 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12509
12510 // Strip SVE vector types
12511 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
12512 // Need the original target type for vector type checks
12513 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
12514 // Handle conversion from scalable to fixed when msve-vector-bits is
12515 // specified
12516 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
12517 QualType(Source, 0)) ||
12518 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
12519 QualType(Source, 0)))
12520 return;
12521
12522 // If the vector cast is cast between two vectors of the same size, it is
12523 // a bitcast, not a conversion.
12524 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
12525 return;
12526
12527 Source = SourceBT->getSveEltType(Context).getTypePtr();
12528 }
12529
12530 if (TargetBT && TargetBT->isSveVLSBuiltinType())
12531 Target = TargetBT->getSveEltType(Context).getTypePtr();
12532
12533 // If the source is floating point...
12534 if (SourceBT && SourceBT->isFloatingPoint()) {
12535 // ...and the target is floating point...
12536 if (TargetBT && TargetBT->isFloatingPoint()) {
12537 // ...then warn if we're dropping FP rank.
12538
12540 QualType(SourceBT, 0), QualType(TargetBT, 0));
12541 if (Order > 0) {
12542 // Don't warn about float constants that are precisely
12543 // representable in the target type.
12544 Expr::EvalResult result;
12545 if (E->EvaluateAsRValue(result, Context)) {
12546 // Value might be a float, a float vector, or a float complex.
12548 result.Val,
12549 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12550 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12551 return;
12552 }
12553
12554 if (SourceMgr.isInSystemMacro(CC))
12555 return;
12556
12557 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
12558 }
12559 // ... or possibly if we're increasing rank, too
12560 else if (Order < 0) {
12561 if (SourceMgr.isInSystemMacro(CC))
12562 return;
12563
12564 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
12565 }
12566 return;
12567 }
12568
12569 // If the target is integral, always warn.
12570 if (TargetBT && TargetBT->isInteger()) {
12571 if (SourceMgr.isInSystemMacro(CC))
12572 return;
12573
12574 DiagnoseFloatingImpCast(*this, E, T, CC);
12575 }
12576
12577 // Detect the case where a call result is converted from floating-point to
12578 // to bool, and the final argument to the call is converted from bool, to
12579 // discover this typo:
12580 //
12581 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
12582 //
12583 // FIXME: This is an incredibly special case; is there some more general
12584 // way to detect this class of misplaced-parentheses bug?
12585 if (Target->isBooleanType() && isa<CallExpr>(E)) {
12586 // Check last argument of function call to see if it is an
12587 // implicit cast from a type matching the type the result
12588 // is being cast to.
12589 CallExpr *CEx = cast<CallExpr>(E);
12590 if (unsigned NumArgs = CEx->getNumArgs()) {
12591 Expr *LastA = CEx->getArg(NumArgs - 1);
12592 Expr *InnerE = LastA->IgnoreParenImpCasts();
12593 if (isa<ImplicitCastExpr>(LastA) &&
12594 InnerE->getType()->isBooleanType()) {
12595 // Warn on this floating-point to bool conversion
12596 DiagnoseImpCast(*this, E, T, CC,
12597 diag::warn_impcast_floating_point_to_bool);
12598 }
12599 }
12600 }
12601 return;
12602 }
12603
12604 // Valid casts involving fixed point types should be accounted for here.
12605 if (Source->isFixedPointType()) {
12606 if (Target->isUnsaturatedFixedPointType()) {
12610 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12611 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
12612 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
12613 if (Value > MaxVal || Value < MinVal) {
12615 PDiag(diag::warn_impcast_fixed_point_range)
12616 << Value.toString() << T
12617 << E->getSourceRange()
12618 << clang::SourceRange(CC));
12619 return;
12620 }
12621 }
12622 } else if (Target->isIntegerType()) {
12626 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12627
12628 bool Overflowed;
12629 llvm::APSInt IntResult = FXResult.convertToInt(
12630 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
12631 &Overflowed);
12632
12633 if (Overflowed) {
12635 PDiag(diag::warn_impcast_fixed_point_range)
12636 << FXResult.toString() << T
12637 << E->getSourceRange()
12638 << clang::SourceRange(CC));
12639 return;
12640 }
12641 }
12642 }
12643 } else if (Target->isUnsaturatedFixedPointType()) {
12644 if (Source->isIntegerType()) {
12648 llvm::APSInt Value = Result.Val.getInt();
12649
12650 bool Overflowed;
12651 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12652 Value, Context.getFixedPointSemantics(T), &Overflowed);
12653
12654 if (Overflowed) {
12656 PDiag(diag::warn_impcast_fixed_point_range)
12657 << toString(Value, /*Radix=*/10) << T
12658 << E->getSourceRange()
12659 << clang::SourceRange(CC));
12660 return;
12661 }
12662 }
12663 }
12664 }
12665
12666 // If we are casting an integer type to a floating point type without
12667 // initialization-list syntax, we might lose accuracy if the floating
12668 // point type has a narrower significand than the integer type.
12669 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12670 TargetBT->isFloatingType() && !IsListInit) {
12671 // Determine the number of precision bits in the source integer type.
12672 std::optional<IntRange> SourceRange =
12674 /*Approximate=*/true);
12675 if (!SourceRange)
12676 return;
12677 unsigned int SourcePrecision = SourceRange->Width;
12678
12679 // Determine the number of precision bits in the
12680 // target floating point type.
12681 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12682 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12683
12684 if (SourcePrecision > 0 && TargetPrecision > 0 &&
12685 SourcePrecision > TargetPrecision) {
12686
12687 if (std::optional<llvm::APSInt> SourceInt =
12689 // If the source integer is a constant, convert it to the target
12690 // floating point type. Issue a warning if the value changes
12691 // during the whole conversion.
12692 llvm::APFloat TargetFloatValue(
12693 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12694 llvm::APFloat::opStatus ConversionStatus =
12695 TargetFloatValue.convertFromAPInt(
12696 *SourceInt, SourceBT->isSignedInteger(),
12697 llvm::APFloat::rmNearestTiesToEven);
12698
12699 if (ConversionStatus != llvm::APFloat::opOK) {
12700 SmallString<32> PrettySourceValue;
12701 SourceInt->toString(PrettySourceValue, 10);
12702 SmallString<32> PrettyTargetValue;
12703 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12704
12706 E->getExprLoc(), E,
12707 PDiag(diag::warn_impcast_integer_float_precision_constant)
12708 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12709 << E->getSourceRange() << clang::SourceRange(CC));
12710 }
12711 } else {
12712 // Otherwise, the implicit conversion may lose precision.
12713 DiagnoseImpCast(*this, E, T, CC,
12714 diag::warn_impcast_integer_float_precision);
12715 }
12716 }
12717 }
12718
12719 DiagnoseNullConversion(*this, E, T, CC);
12720
12722
12723 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
12724 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
12725 return;
12726 }
12727
12728 if (Target->isBooleanType())
12729 DiagnoseIntInBoolContext(*this, E);
12730
12732 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
12733 << QualType(Source, 0) << QualType(Target, 0);
12734 }
12735
12736 if (!Source->isIntegerType() || !Target->isIntegerType())
12737 return;
12738
12739 // TODO: remove this early return once the false positives for constant->bool
12740 // in templates, macros, etc, are reduced or removed.
12741 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12742 return;
12743
12744 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
12745 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12747 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12748 << E->getType());
12749 }
12750 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
12751 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
12752 if (!LikelySourceRange)
12753 return;
12754
12755 IntRange SourceTypeRange =
12756 IntRange::forTargetOfCanonicalType(Context, Source);
12757 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
12758
12759 if (LikelySourceRange->Width > TargetRange.Width) {
12760 // If the source is a constant, use a default-on diagnostic.
12761 // TODO: this should happen for bitfield stores, too.
12765 llvm::APSInt Value(32);
12766 Value = Result.Val.getInt();
12767
12768 if (SourceMgr.isInSystemMacro(CC))
12769 return;
12770
12771 std::string PrettySourceValue = toString(Value, 10);
12772 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12773
12775 PDiag(diag::warn_impcast_integer_precision_constant)
12776 << PrettySourceValue << PrettyTargetValue
12777 << E->getType() << T << E->getSourceRange()
12778 << SourceRange(CC));
12779 return;
12780 }
12781
12782 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12783 if (SourceMgr.isInSystemMacro(CC))
12784 return;
12785
12786 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12787 if (UO->getOpcode() == UO_Minus)
12788 return DiagnoseImpCast(
12789 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
12790 }
12791
12792 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
12793 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
12794 /* pruneControlFlow */ true);
12795 return DiagnoseImpCast(*this, E, T, CC,
12796 diag::warn_impcast_integer_precision);
12797 }
12798
12799 if (TargetRange.Width > SourceTypeRange.Width) {
12800 if (auto *UO = dyn_cast<UnaryOperator>(E))
12801 if (UO->getOpcode() == UO_Minus)
12802 if (Source->isUnsignedIntegerType()) {
12803 if (Target->isUnsignedIntegerType())
12804 return DiagnoseImpCast(*this, E, T, CC,
12805 diag::warn_impcast_high_order_zero_bits);
12806 if (Target->isSignedIntegerType())
12807 return DiagnoseImpCast(*this, E, T, CC,
12808 diag::warn_impcast_nonnegative_result);
12809 }
12810 }
12811
12812 if (TargetRange.Width == LikelySourceRange->Width &&
12813 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
12814 Source->isSignedIntegerType()) {
12815 // Warn when doing a signed to signed conversion, warn if the positive
12816 // source value is exactly the width of the target type, which will
12817 // cause a negative value to be stored.
12818
12821 !SourceMgr.isInSystemMacro(CC)) {
12822 llvm::APSInt Value = Result.Val.getInt();
12823 if (isSameWidthConstantConversion(*this, E, T, CC)) {
12824 std::string PrettySourceValue = toString(Value, 10);
12825 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12826
12827 Diag(E->getExprLoc(),
12828 PDiag(diag::warn_impcast_integer_precision_constant)
12829 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12830 << E->getSourceRange() << SourceRange(CC));
12831 return;
12832 }
12833 }
12834
12835 // Fall through for non-constants to give a sign conversion warning.
12836 }
12837
12838 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
12839 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
12840 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
12841 LikelySourceRange->Width == TargetRange.Width))) {
12842 if (SourceMgr.isInSystemMacro(CC))
12843 return;
12844
12845 if (SourceBT && SourceBT->isInteger() && TargetBT &&
12846 TargetBT->isInteger() &&
12847 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
12848 return;
12849 }
12850
12851 unsigned DiagID = diag::warn_impcast_integer_sign;
12852
12853 // Traditionally, gcc has warned about this under -Wsign-compare.
12854 // We also want to warn about it in -Wconversion.
12855 // So if -Wconversion is off, use a completely identical diagnostic
12856 // in the sign-compare group.
12857 // The conditional-checking code will
12858 if (ICContext) {
12859 DiagID = diag::warn_impcast_integer_sign_conditional;
12860 *ICContext = true;
12861 }
12862
12863 DiagnoseImpCast(*this, E, T, CC, DiagID);
12864 }
12865
12866 // If we're implicitly converting from an integer into an enumeration, that
12867 // is valid in C but invalid in C++.
12868 QualType SourceType = E->getEnumCoercedType(Context);
12869 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
12870 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
12871 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
12872
12873 // Diagnose conversions between different enumeration types.
12874 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12875 // type, to give us better diagnostics.
12876 Source = Context.getCanonicalType(SourceType).getTypePtr();
12877
12878 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
12879 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
12880 if (SourceEnum->getOriginalDecl()->hasNameForLinkage() &&
12881 TargetEnum->getOriginalDecl()->hasNameForLinkage() &&
12882 SourceEnum != TargetEnum) {
12883 if (SourceMgr.isInSystemMacro(CC))
12884 return;
12885
12886 return DiagnoseImpCast(*this, E, SourceType, T, CC,
12887 diag::warn_impcast_different_enum_types);
12888 }
12889}
12890
12893
12895 SourceLocation CC, bool &ICContext) {
12896 E = E->IgnoreParenImpCasts();
12897 // Diagnose incomplete type for second or third operand in C.
12898 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
12899 S.RequireCompleteExprType(E, diag::err_incomplete_type);
12900
12901 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12902 return CheckConditionalOperator(S, CO, CC, T);
12903
12905 if (E->getType() != T)
12906 return S.CheckImplicitConversion(E, T, CC, &ICContext);
12907}
12908
12912
12913 Expr *TrueExpr = E->getTrueExpr();
12914 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12915 TrueExpr = BCO->getCommon();
12916
12917 bool Suspicious = false;
12918 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12919 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12920
12921 if (T->isBooleanType())
12923
12924 // If -Wconversion would have warned about either of the candidates
12925 // for a signedness conversion to the context type...
12926 if (!Suspicious) return;
12927
12928 // ...but it's currently ignored...
12929 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12930 return;
12931
12932 // ...then check whether it would have warned about either of the
12933 // candidates for a signedness conversion to the condition type.
12934 if (E->getType() == T) return;
12935
12936 Suspicious = false;
12937 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
12938 &Suspicious);
12939 if (!Suspicious)
12941 E->getType(), CC, &Suspicious);
12942}
12943
12944/// Check conversion of given expression to boolean.
12945/// Input argument E is a logical expression.
12947 // Run the bool-like conversion checks only for C since there bools are
12948 // still not used as the return type from "boolean" operators or as the input
12949 // type for conditional operators.
12950 if (S.getLangOpts().CPlusPlus)
12951 return;
12953 return;
12955}
12956
12957namespace {
12958struct AnalyzeImplicitConversionsWorkItem {
12959 Expr *E;
12960 SourceLocation CC;
12961 bool IsListInit;
12962};
12963}
12964
12966 Sema &S, Expr *E, QualType T, SourceLocation CC,
12967 bool ExtraCheckForImplicitConversion,
12969 E = E->IgnoreParenImpCasts();
12970 WorkList.push_back({E, CC, false});
12971
12972 if (ExtraCheckForImplicitConversion && E->getType() != T)
12973 S.CheckImplicitConversion(E, T, CC);
12974}
12975
12976/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12977/// that should be visited are added to WorkList.
12979 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12981 Expr *OrigE = Item.E;
12982 SourceLocation CC = Item.CC;
12983
12984 QualType T = OrigE->getType();
12985 Expr *E = OrigE->IgnoreParenImpCasts();
12986
12987 // Propagate whether we are in a C++ list initialization expression.
12988 // If so, we do not issue warnings for implicit int-float conversion
12989 // precision loss, because C++11 narrowing already handles it.
12990 //
12991 // HLSL's initialization lists are special, so they shouldn't observe the C++
12992 // behavior here.
12993 bool IsListInit =
12994 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
12995 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
12996
12997 if (E->isTypeDependent() || E->isValueDependent())
12998 return;
12999
13000 Expr *SourceExpr = E;
13001 // Examine, but don't traverse into the source expression of an
13002 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13003 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13004 // evaluate it in the context of checking the specific conversion to T though.
13005 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13006 if (auto *Src = OVE->getSourceExpr())
13007 SourceExpr = Src;
13008
13009 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13010 if (UO->getOpcode() == UO_Not &&
13011 UO->getSubExpr()->isKnownToHaveBooleanValue())
13012 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13013 << OrigE->getSourceRange() << T->isBooleanType()
13014 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13015
13016 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
13017 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13018 BO->getLHS()->isKnownToHaveBooleanValue() &&
13019 BO->getRHS()->isKnownToHaveBooleanValue() &&
13020 BO->getLHS()->HasSideEffects(S.Context) &&
13021 BO->getRHS()->HasSideEffects(S.Context)) {
13023 const LangOptions &LO = S.getLangOpts();
13024 SourceLocation BLoc = BO->getOperatorLoc();
13025 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
13026 StringRef SR = clang::Lexer::getSourceText(
13027 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
13028 // To reduce false positives, only issue the diagnostic if the operator
13029 // is explicitly spelled as a punctuator. This suppresses the diagnostic
13030 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
13031 // in C, along with other macro spellings the user might invent.
13032 if (SR.str() == "&" || SR.str() == "|") {
13033
13034 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13035 << (BO->getOpcode() == BO_And ? "&" : "|")
13036 << OrigE->getSourceRange()
13038 BO->getOperatorLoc(),
13039 (BO->getOpcode() == BO_And ? "&&" : "||"));
13040 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13041 }
13042 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
13043 /// Analyze the given comma operator. The basic idea behind the analysis
13044 /// is to analyze the left and right operands slightly differently. The
13045 /// left operand needs to check whether the operand itself has an implicit
13046 /// conversion, but not whether the left operand induces an implicit
13047 /// conversion for the entire comma expression itself. This is similar to
13048 /// how CheckConditionalOperand behaves; it's as-if the correct operand
13049 /// were directly used for the implicit conversion check.
13050 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
13051 /*ExtraCheckForImplicitConversion=*/false, WorkList);
13052 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
13053 /*ExtraCheckForImplicitConversion=*/true, WorkList);
13054 return;
13055 }
13056 }
13057
13058 // For conditional operators, we analyze the arguments as if they
13059 // were being fed directly into the output.
13060 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13061 CheckConditionalOperator(S, CO, CC, T);
13062 return;
13063 }
13064
13065 // Check implicit argument conversions for function calls.
13066 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
13068
13069 // Go ahead and check any implicit conversions we might have skipped.
13070 // The non-canonical typecheck is just an optimization;
13071 // CheckImplicitConversion will filter out dead implicit conversions.
13072 if (SourceExpr->getType() != T)
13073 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
13074
13075 // Now continue drilling into this expression.
13076
13077 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13078 // The bound subexpressions in a PseudoObjectExpr are not reachable
13079 // as transitive children.
13080 // FIXME: Use a more uniform representation for this.
13081 for (auto *SE : POE->semantics())
13082 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13083 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13084 }
13085
13086 // Skip past explicit casts.
13087 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13088 E = CE->getSubExpr();
13089 // In the special case of a C++ function-style cast with braces,
13090 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
13091 // initializer. This InitListExpr basically belongs to the cast itself, so
13092 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
13094 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
13095 if (InitListE->getNumInits() == 1) {
13096 E = InitListE->getInit(0);
13097 }
13098 }
13099 }
13100 E = E->IgnoreParenImpCasts();
13101 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13102 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13103 WorkList.push_back({E, CC, IsListInit});
13104 return;
13105 }
13106
13107 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
13108 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
13109 // The base expression is only used to initialize the parameter for
13110 // arguments to `inout` parameters, so we only traverse down the base
13111 // expression for `inout` cases.
13112 if (OutArgE->isInOut())
13113 WorkList.push_back(
13114 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
13115 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
13116 return;
13117 }
13118
13119 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13120 // Do a somewhat different check with comparison operators.
13121 if (BO->isComparisonOp())
13122 return AnalyzeComparison(S, BO);
13123
13124 // And with simple assignments.
13125 if (BO->getOpcode() == BO_Assign)
13126 return AnalyzeAssignment(S, BO);
13127 // And with compound assignments.
13128 if (BO->isAssignmentOp())
13129 return AnalyzeCompoundAssignment(S, BO);
13130 }
13131
13132 // These break the otherwise-useful invariant below. Fortunately,
13133 // we don't really need to recurse into them, because any internal
13134 // expressions should have been analyzed already when they were
13135 // built into statements.
13136 if (isa<StmtExpr>(E)) return;
13137
13138 // Don't descend into unevaluated contexts.
13139 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13140
13141 // Now just recurse over the expression's children.
13142 CC = E->getExprLoc();
13143 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13144 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13145 for (Stmt *SubStmt : E->children()) {
13146 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13147 if (!ChildExpr)
13148 continue;
13149
13150 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
13151 if (ChildExpr == CSE->getOperand())
13152 // Do not recurse over a CoroutineSuspendExpr's operand.
13153 // The operand is also a subexpression of getCommonExpr(), and
13154 // recursing into it directly would produce duplicate diagnostics.
13155 continue;
13156
13157 if (IsLogicalAndOperator &&
13159 // Ignore checking string literals that are in logical and operators.
13160 // This is a common pattern for asserts.
13161 continue;
13162 WorkList.push_back({ChildExpr, CC, IsListInit});
13163 }
13164
13165 if (BO && BO->isLogicalOp()) {
13166 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13167 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13168 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13169
13170 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13171 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13172 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13173 }
13174
13175 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13176 if (U->getOpcode() == UO_LNot) {
13177 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13178 } else if (U->getOpcode() != UO_AddrOf) {
13179 if (U->getSubExpr()->getType()->isAtomicType())
13180 S.Diag(U->getSubExpr()->getBeginLoc(),
13181 diag::warn_atomic_implicit_seq_cst);
13182 }
13183 }
13184}
13185
13186/// AnalyzeImplicitConversions - Find and report any interesting
13187/// implicit conversions in the given expression. There are a couple
13188/// of competing diagnostics here, -Wconversion and -Wsign-compare.
13190 bool IsListInit/*= false*/) {
13192 WorkList.push_back({OrigE, CC, IsListInit});
13193 while (!WorkList.empty())
13194 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13195}
13196
13197// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13198// Returns true when emitting a warning about taking the address of a reference.
13199static bool CheckForReference(Sema &SemaRef, const Expr *E,
13200 const PartialDiagnostic &PD) {
13201 E = E->IgnoreParenImpCasts();
13202
13203 const FunctionDecl *FD = nullptr;
13204
13205 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13206 if (!DRE->getDecl()->getType()->isReferenceType())
13207 return false;
13208 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13209 if (!M->getMemberDecl()->getType()->isReferenceType())
13210 return false;
13211 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13212 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13213 return false;
13214 FD = Call->getDirectCallee();
13215 } else {
13216 return false;
13217 }
13218
13219 SemaRef.Diag(E->getExprLoc(), PD);
13220
13221 // If possible, point to location of function.
13222 if (FD) {
13223 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13224 }
13225
13226 return true;
13227}
13228
13229// Returns true if the SourceLocation is expanded from any macro body.
13230// Returns false if the SourceLocation is invalid, is from not in a macro
13231// expansion, or is from expanded from a top-level macro argument.
13233 if (Loc.isInvalid())
13234 return false;
13235
13236 while (Loc.isMacroID()) {
13237 if (SM.isMacroBodyExpansion(Loc))
13238 return true;
13239 Loc = SM.getImmediateMacroCallerLoc(Loc);
13240 }
13241
13242 return false;
13243}
13244
13247 bool IsEqual, SourceRange Range) {
13248 if (!E)
13249 return;
13250
13251 // Don't warn inside macros.
13252 if (E->getExprLoc().isMacroID()) {
13254 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13255 IsInAnyMacroBody(SM, Range.getBegin()))
13256 return;
13257 }
13258 E = E->IgnoreImpCasts();
13259
13260 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13261
13262 if (isa<CXXThisExpr>(E)) {
13263 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13264 : diag::warn_this_bool_conversion;
13265 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13266 return;
13267 }
13268
13269 bool IsAddressOf = false;
13270
13271 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
13272 if (UO->getOpcode() != UO_AddrOf)
13273 return;
13274 IsAddressOf = true;
13275 E = UO->getSubExpr();
13276 }
13277
13278 if (IsAddressOf) {
13279 unsigned DiagID = IsCompare
13280 ? diag::warn_address_of_reference_null_compare
13281 : diag::warn_address_of_reference_bool_conversion;
13282 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13283 << IsEqual;
13284 if (CheckForReference(*this, E, PD)) {
13285 return;
13286 }
13287 }
13288
13289 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13290 bool IsParam = isa<NonNullAttr>(NonnullAttr);
13291 std::string Str;
13292 llvm::raw_string_ostream S(Str);
13293 E->printPretty(S, nullptr, getPrintingPolicy());
13294 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13295 : diag::warn_cast_nonnull_to_bool;
13296 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13297 << E->getSourceRange() << Range << IsEqual;
13298 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13299 };
13300
13301 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13302 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13303 if (auto *Callee = Call->getDirectCallee()) {
13304 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13305 ComplainAboutNonnullParamOrCall(A);
13306 return;
13307 }
13308 }
13309 }
13310
13311 // Complain if we are converting a lambda expression to a boolean value
13312 // outside of instantiation.
13313 if (!inTemplateInstantiation()) {
13314 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
13315 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
13316 MRecordDecl && MRecordDecl->isLambda()) {
13317 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
13318 << /*LambdaPointerConversionOperatorType=*/3
13319 << MRecordDecl->getSourceRange() << Range << IsEqual;
13320 return;
13321 }
13322 }
13323 }
13324
13325 // Expect to find a single Decl. Skip anything more complicated.
13326 ValueDecl *D = nullptr;
13327 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13328 D = R->getDecl();
13329 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13330 D = M->getMemberDecl();
13331 }
13332
13333 // Weak Decls can be null.
13334 if (!D || D->isWeak())
13335 return;
13336
13337 // Check for parameter decl with nonnull attribute
13338 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13339 if (getCurFunction() &&
13340 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13341 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13342 ComplainAboutNonnullParamOrCall(A);
13343 return;
13344 }
13345
13346 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13347 // Skip function template not specialized yet.
13349 return;
13350 auto ParamIter = llvm::find(FD->parameters(), PV);
13351 assert(ParamIter != FD->param_end());
13352 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13353
13354 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13355 if (!NonNull->args_size()) {
13356 ComplainAboutNonnullParamOrCall(NonNull);
13357 return;
13358 }
13359
13360 for (const ParamIdx &ArgNo : NonNull->args()) {
13361 if (ArgNo.getASTIndex() == ParamNo) {
13362 ComplainAboutNonnullParamOrCall(NonNull);
13363 return;
13364 }
13365 }
13366 }
13367 }
13368 }
13369 }
13370
13371 QualType T = D->getType();
13372 const bool IsArray = T->isArrayType();
13373 const bool IsFunction = T->isFunctionType();
13374
13375 // Address of function is used to silence the function warning.
13376 if (IsAddressOf && IsFunction) {
13377 return;
13378 }
13379
13380 // Found nothing.
13381 if (!IsAddressOf && !IsFunction && !IsArray)
13382 return;
13383
13384 // Pretty print the expression for the diagnostic.
13385 std::string Str;
13386 llvm::raw_string_ostream S(Str);
13387 E->printPretty(S, nullptr, getPrintingPolicy());
13388
13389 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13390 : diag::warn_impcast_pointer_to_bool;
13391 enum {
13392 AddressOf,
13393 FunctionPointer,
13394 ArrayPointer
13395 } DiagType;
13396 if (IsAddressOf)
13397 DiagType = AddressOf;
13398 else if (IsFunction)
13399 DiagType = FunctionPointer;
13400 else if (IsArray)
13401 DiagType = ArrayPointer;
13402 else
13403 llvm_unreachable("Could not determine diagnostic.");
13404 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13405 << Range << IsEqual;
13406
13407 if (!IsFunction)
13408 return;
13409
13410 // Suggest '&' to silence the function warning.
13411 Diag(E->getExprLoc(), diag::note_function_warning_silence)
13413
13414 // Check to see if '()' fixit should be emitted.
13415 QualType ReturnType;
13416 UnresolvedSet<4> NonTemplateOverloads;
13417 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13418 if (ReturnType.isNull())
13419 return;
13420
13421 if (IsCompare) {
13422 // There are two cases here. If there is null constant, the only suggest
13423 // for a pointer return type. If the null is 0, then suggest if the return
13424 // type is a pointer or an integer type.
13425 if (!ReturnType->isPointerType()) {
13426 if (NullKind == Expr::NPCK_ZeroExpression ||
13427 NullKind == Expr::NPCK_ZeroLiteral) {
13428 if (!ReturnType->isIntegerType())
13429 return;
13430 } else {
13431 return;
13432 }
13433 }
13434 } else { // !IsCompare
13435 // For function to bool, only suggest if the function pointer has bool
13436 // return type.
13437 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13438 return;
13439 }
13440 Diag(E->getExprLoc(), diag::note_function_to_function_call)
13442}
13443
13444void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13445 // Don't diagnose in unevaluated contexts.
13447 return;
13448
13449 // Don't diagnose for value- or type-dependent expressions.
13450 if (E->isTypeDependent() || E->isValueDependent())
13451 return;
13452
13453 // Check for array bounds violations in cases where the check isn't triggered
13454 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13455 // ArraySubscriptExpr is on the RHS of a variable initialization.
13456 CheckArrayAccess(E);
13457
13458 // This is not the right CC for (e.g.) a variable initialization.
13459 AnalyzeImplicitConversions(*this, E, CC);
13460}
13461
13462void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13463 ::CheckBoolLikeConversion(*this, E, CC);
13464}
13465
13466void Sema::CheckForIntOverflow (const Expr *E) {
13467 // Use a work list to deal with nested struct initializers.
13468 SmallVector<const Expr *, 2> Exprs(1, E);
13469
13470 do {
13471 const Expr *OriginalE = Exprs.pop_back_val();
13472 const Expr *E = OriginalE->IgnoreParenCasts();
13473
13476 continue;
13477 }
13478
13479 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
13480 Exprs.append(InitList->inits().begin(), InitList->inits().end());
13481 else if (isa<ObjCBoxedExpr>(OriginalE))
13483 else if (const auto *Call = dyn_cast<CallExpr>(E))
13484 Exprs.append(Call->arg_begin(), Call->arg_end());
13485 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
13486 Exprs.append(Message->arg_begin(), Message->arg_end());
13487 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
13488 Exprs.append(Construct->arg_begin(), Construct->arg_end());
13489 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
13490 Exprs.push_back(Temporary->getSubExpr());
13491 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
13492 Exprs.push_back(Array->getIdx());
13493 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
13494 Exprs.push_back(Compound->getInitializer());
13495 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
13496 New && New->isArray()) {
13497 if (auto ArraySize = New->getArraySize())
13498 Exprs.push_back(*ArraySize);
13499 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
13500 Exprs.push_back(MTE->getSubExpr());
13501 } while (!Exprs.empty());
13502}
13503
13504namespace {
13505
13506/// Visitor for expressions which looks for unsequenced operations on the
13507/// same object.
13508class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13509 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13510
13511 /// A tree of sequenced regions within an expression. Two regions are
13512 /// unsequenced if one is an ancestor or a descendent of the other. When we
13513 /// finish processing an expression with sequencing, such as a comma
13514 /// expression, we fold its tree nodes into its parent, since they are
13515 /// unsequenced with respect to nodes we will visit later.
13516 class SequenceTree {
13517 struct Value {
13518 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13519 unsigned Parent : 31;
13520 LLVM_PREFERRED_TYPE(bool)
13521 unsigned Merged : 1;
13522 };
13523 SmallVector<Value, 8> Values;
13524
13525 public:
13526 /// A region within an expression which may be sequenced with respect
13527 /// to some other region.
13528 class Seq {
13529 friend class SequenceTree;
13530
13531 unsigned Index;
13532
13533 explicit Seq(unsigned N) : Index(N) {}
13534
13535 public:
13536 Seq() : Index(0) {}
13537 };
13538
13539 SequenceTree() { Values.push_back(Value(0)); }
13540 Seq root() const { return Seq(0); }
13541
13542 /// Create a new sequence of operations, which is an unsequenced
13543 /// subset of \p Parent. This sequence of operations is sequenced with
13544 /// respect to other children of \p Parent.
13545 Seq allocate(Seq Parent) {
13546 Values.push_back(Value(Parent.Index));
13547 return Seq(Values.size() - 1);
13548 }
13549
13550 /// Merge a sequence of operations into its parent.
13551 void merge(Seq S) {
13552 Values[S.Index].Merged = true;
13553 }
13554
13555 /// Determine whether two operations are unsequenced. This operation
13556 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13557 /// should have been merged into its parent as appropriate.
13558 bool isUnsequenced(Seq Cur, Seq Old) {
13559 unsigned C = representative(Cur.Index);
13560 unsigned Target = representative(Old.Index);
13561 while (C >= Target) {
13562 if (C == Target)
13563 return true;
13564 C = Values[C].Parent;
13565 }
13566 return false;
13567 }
13568
13569 private:
13570 /// Pick a representative for a sequence.
13571 unsigned representative(unsigned K) {
13572 if (Values[K].Merged)
13573 // Perform path compression as we go.
13574 return Values[K].Parent = representative(Values[K].Parent);
13575 return K;
13576 }
13577 };
13578
13579 /// An object for which we can track unsequenced uses.
13580 using Object = const NamedDecl *;
13581
13582 /// Different flavors of object usage which we track. We only track the
13583 /// least-sequenced usage of each kind.
13584 enum UsageKind {
13585 /// A read of an object. Multiple unsequenced reads are OK.
13586 UK_Use,
13587
13588 /// A modification of an object which is sequenced before the value
13589 /// computation of the expression, such as ++n in C++.
13590 UK_ModAsValue,
13591
13592 /// A modification of an object which is not sequenced before the value
13593 /// computation of the expression, such as n++.
13594 UK_ModAsSideEffect,
13595
13596 UK_Count = UK_ModAsSideEffect + 1
13597 };
13598
13599 /// Bundle together a sequencing region and the expression corresponding
13600 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13601 struct Usage {
13602 const Expr *UsageExpr = nullptr;
13603 SequenceTree::Seq Seq;
13604
13605 Usage() = default;
13606 };
13607
13608 struct UsageInfo {
13609 Usage Uses[UK_Count];
13610
13611 /// Have we issued a diagnostic for this object already?
13612 bool Diagnosed = false;
13613
13614 UsageInfo();
13615 };
13616 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13617
13618 Sema &SemaRef;
13619
13620 /// Sequenced regions within the expression.
13621 SequenceTree Tree;
13622
13623 /// Declaration modifications and references which we have seen.
13624 UsageInfoMap UsageMap;
13625
13626 /// The region we are currently within.
13627 SequenceTree::Seq Region;
13628
13629 /// Filled in with declarations which were modified as a side-effect
13630 /// (that is, post-increment operations).
13631 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13632
13633 /// Expressions to check later. We defer checking these to reduce
13634 /// stack usage.
13635 SmallVectorImpl<const Expr *> &WorkList;
13636
13637 /// RAII object wrapping the visitation of a sequenced subexpression of an
13638 /// expression. At the end of this process, the side-effects of the evaluation
13639 /// become sequenced with respect to the value computation of the result, so
13640 /// we downgrade any UK_ModAsSideEffect within the evaluation to
13641 /// UK_ModAsValue.
13642 struct SequencedSubexpression {
13643 SequencedSubexpression(SequenceChecker &Self)
13644 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13645 Self.ModAsSideEffect = &ModAsSideEffect;
13646 }
13647
13648 ~SequencedSubexpression() {
13649 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13650 // Add a new usage with usage kind UK_ModAsValue, and then restore
13651 // the previous usage with UK_ModAsSideEffect (thus clearing it if
13652 // the previous one was empty).
13653 UsageInfo &UI = Self.UsageMap[M.first];
13654 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13655 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13656 SideEffectUsage = M.second;
13657 }
13658 Self.ModAsSideEffect = OldModAsSideEffect;
13659 }
13660
13661 SequenceChecker &Self;
13662 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13663 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13664 };
13665
13666 /// RAII object wrapping the visitation of a subexpression which we might
13667 /// choose to evaluate as a constant. If any subexpression is evaluated and
13668 /// found to be non-constant, this allows us to suppress the evaluation of
13669 /// the outer expression.
13670 class EvaluationTracker {
13671 public:
13672 EvaluationTracker(SequenceChecker &Self)
13673 : Self(Self), Prev(Self.EvalTracker) {
13674 Self.EvalTracker = this;
13675 }
13676
13677 ~EvaluationTracker() {
13678 Self.EvalTracker = Prev;
13679 if (Prev)
13680 Prev->EvalOK &= EvalOK;
13681 }
13682
13683 bool evaluate(const Expr *E, bool &Result) {
13684 if (!EvalOK || E->isValueDependent())
13685 return false;
13686 EvalOK = E->EvaluateAsBooleanCondition(
13687 Result, Self.SemaRef.Context,
13688 Self.SemaRef.isConstantEvaluatedContext());
13689 return EvalOK;
13690 }
13691
13692 private:
13693 SequenceChecker &Self;
13694 EvaluationTracker *Prev;
13695 bool EvalOK = true;
13696 } *EvalTracker = nullptr;
13697
13698 /// Find the object which is produced by the specified expression,
13699 /// if any.
13700 Object getObject(const Expr *E, bool Mod) const {
13701 E = E->IgnoreParenCasts();
13702 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13703 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13704 return getObject(UO->getSubExpr(), Mod);
13705 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13706 if (BO->getOpcode() == BO_Comma)
13707 return getObject(BO->getRHS(), Mod);
13708 if (Mod && BO->isAssignmentOp())
13709 return getObject(BO->getLHS(), Mod);
13710 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13711 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13712 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13713 return ME->getMemberDecl();
13714 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13715 // FIXME: If this is a reference, map through to its value.
13716 return DRE->getDecl();
13717 return nullptr;
13718 }
13719
13720 /// Note that an object \p O was modified or used by an expression
13721 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13722 /// the object \p O as obtained via the \p UsageMap.
13723 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13724 // Get the old usage for the given object and usage kind.
13725 Usage &U = UI.Uses[UK];
13726 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13727 // If we have a modification as side effect and are in a sequenced
13728 // subexpression, save the old Usage so that we can restore it later
13729 // in SequencedSubexpression::~SequencedSubexpression.
13730 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13731 ModAsSideEffect->push_back(std::make_pair(O, U));
13732 // Then record the new usage with the current sequencing region.
13733 U.UsageExpr = UsageExpr;
13734 U.Seq = Region;
13735 }
13736 }
13737
13738 /// Check whether a modification or use of an object \p O in an expression
13739 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13740 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13741 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13742 /// usage and false we are checking for a mod-use unsequenced usage.
13743 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13744 UsageKind OtherKind, bool IsModMod) {
13745 if (UI.Diagnosed)
13746 return;
13747
13748 const Usage &U = UI.Uses[OtherKind];
13749 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13750 return;
13751
13752 const Expr *Mod = U.UsageExpr;
13753 const Expr *ModOrUse = UsageExpr;
13754 if (OtherKind == UK_Use)
13755 std::swap(Mod, ModOrUse);
13756
13757 SemaRef.DiagRuntimeBehavior(
13758 Mod->getExprLoc(), {Mod, ModOrUse},
13759 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13760 : diag::warn_unsequenced_mod_use)
13761 << O << SourceRange(ModOrUse->getExprLoc()));
13762 UI.Diagnosed = true;
13763 }
13764
13765 // A note on note{Pre, Post}{Use, Mod}:
13766 //
13767 // (It helps to follow the algorithm with an expression such as
13768 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13769 // operations before C++17 and both are well-defined in C++17).
13770 //
13771 // When visiting a node which uses/modify an object we first call notePreUse
13772 // or notePreMod before visiting its sub-expression(s). At this point the
13773 // children of the current node have not yet been visited and so the eventual
13774 // uses/modifications resulting from the children of the current node have not
13775 // been recorded yet.
13776 //
13777 // We then visit the children of the current node. After that notePostUse or
13778 // notePostMod is called. These will 1) detect an unsequenced modification
13779 // as side effect (as in "k++ + k") and 2) add a new usage with the
13780 // appropriate usage kind.
13781 //
13782 // We also have to be careful that some operation sequences modification as
13783 // side effect as well (for example: || or ,). To account for this we wrap
13784 // the visitation of such a sub-expression (for example: the LHS of || or ,)
13785 // with SequencedSubexpression. SequencedSubexpression is an RAII object
13786 // which record usages which are modifications as side effect, and then
13787 // downgrade them (or more accurately restore the previous usage which was a
13788 // modification as side effect) when exiting the scope of the sequenced
13789 // subexpression.
13790
13791 void notePreUse(Object O, const Expr *UseExpr) {
13792 UsageInfo &UI = UsageMap[O];
13793 // Uses conflict with other modifications.
13794 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13795 }
13796
13797 void notePostUse(Object O, const Expr *UseExpr) {
13798 UsageInfo &UI = UsageMap[O];
13799 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13800 /*IsModMod=*/false);
13801 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13802 }
13803
13804 void notePreMod(Object O, const Expr *ModExpr) {
13805 UsageInfo &UI = UsageMap[O];
13806 // Modifications conflict with other modifications and with uses.
13807 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13808 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13809 }
13810
13811 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13812 UsageInfo &UI = UsageMap[O];
13813 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13814 /*IsModMod=*/true);
13815 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13816 }
13817
13818public:
13819 SequenceChecker(Sema &S, const Expr *E,
13820 SmallVectorImpl<const Expr *> &WorkList)
13821 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13822 Visit(E);
13823 // Silence a -Wunused-private-field since WorkList is now unused.
13824 // TODO: Evaluate if it can be used, and if not remove it.
13825 (void)this->WorkList;
13826 }
13827
13828 void VisitStmt(const Stmt *S) {
13829 // Skip all statements which aren't expressions for now.
13830 }
13831
13832 void VisitExpr(const Expr *E) {
13833 // By default, just recurse to evaluated subexpressions.
13834 Base::VisitStmt(E);
13835 }
13836
13837 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
13838 for (auto *Sub : CSE->children()) {
13839 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
13840 if (!ChildExpr)
13841 continue;
13842
13843 if (ChildExpr == CSE->getOperand())
13844 // Do not recurse over a CoroutineSuspendExpr's operand.
13845 // The operand is also a subexpression of getCommonExpr(), and
13846 // recursing into it directly could confuse object management
13847 // for the sake of sequence tracking.
13848 continue;
13849
13850 Visit(Sub);
13851 }
13852 }
13853
13854 void VisitCastExpr(const CastExpr *E) {
13855 Object O = Object();
13856 if (E->getCastKind() == CK_LValueToRValue)
13857 O = getObject(E->getSubExpr(), false);
13858
13859 if (O)
13860 notePreUse(O, E);
13861 VisitExpr(E);
13862 if (O)
13863 notePostUse(O, E);
13864 }
13865
13866 void VisitSequencedExpressions(const Expr *SequencedBefore,
13867 const Expr *SequencedAfter) {
13868 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13869 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13870 SequenceTree::Seq OldRegion = Region;
13871
13872 {
13873 SequencedSubexpression SeqBefore(*this);
13874 Region = BeforeRegion;
13875 Visit(SequencedBefore);
13876 }
13877
13878 Region = AfterRegion;
13879 Visit(SequencedAfter);
13880
13881 Region = OldRegion;
13882
13883 Tree.merge(BeforeRegion);
13884 Tree.merge(AfterRegion);
13885 }
13886
13887 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13888 // C++17 [expr.sub]p1:
13889 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13890 // expression E1 is sequenced before the expression E2.
13891 if (SemaRef.getLangOpts().CPlusPlus17)
13892 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13893 else {
13894 Visit(ASE->getLHS());
13895 Visit(ASE->getRHS());
13896 }
13897 }
13898
13899 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13900 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13901 void VisitBinPtrMem(const BinaryOperator *BO) {
13902 // C++17 [expr.mptr.oper]p4:
13903 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13904 // the expression E1 is sequenced before the expression E2.
13905 if (SemaRef.getLangOpts().CPlusPlus17)
13906 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13907 else {
13908 Visit(BO->getLHS());
13909 Visit(BO->getRHS());
13910 }
13911 }
13912
13913 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13914 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13915 void VisitBinShlShr(const BinaryOperator *BO) {
13916 // C++17 [expr.shift]p4:
13917 // The expression E1 is sequenced before the expression E2.
13918 if (SemaRef.getLangOpts().CPlusPlus17)
13919 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13920 else {
13921 Visit(BO->getLHS());
13922 Visit(BO->getRHS());
13923 }
13924 }
13925
13926 void VisitBinComma(const BinaryOperator *BO) {
13927 // C++11 [expr.comma]p1:
13928 // Every value computation and side effect associated with the left
13929 // expression is sequenced before every value computation and side
13930 // effect associated with the right expression.
13931 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13932 }
13933
13934 void VisitBinAssign(const BinaryOperator *BO) {
13935 SequenceTree::Seq RHSRegion;
13936 SequenceTree::Seq LHSRegion;
13937 if (SemaRef.getLangOpts().CPlusPlus17) {
13938 RHSRegion = Tree.allocate(Region);
13939 LHSRegion = Tree.allocate(Region);
13940 } else {
13941 RHSRegion = Region;
13942 LHSRegion = Region;
13943 }
13944 SequenceTree::Seq OldRegion = Region;
13945
13946 // C++11 [expr.ass]p1:
13947 // [...] the assignment is sequenced after the value computation
13948 // of the right and left operands, [...]
13949 //
13950 // so check it before inspecting the operands and update the
13951 // map afterwards.
13952 Object O = getObject(BO->getLHS(), /*Mod=*/true);
13953 if (O)
13954 notePreMod(O, BO);
13955
13956 if (SemaRef.getLangOpts().CPlusPlus17) {
13957 // C++17 [expr.ass]p1:
13958 // [...] The right operand is sequenced before the left operand. [...]
13959 {
13960 SequencedSubexpression SeqBefore(*this);
13961 Region = RHSRegion;
13962 Visit(BO->getRHS());
13963 }
13964
13965 Region = LHSRegion;
13966 Visit(BO->getLHS());
13967
13968 if (O && isa<CompoundAssignOperator>(BO))
13969 notePostUse(O, BO);
13970
13971 } else {
13972 // C++11 does not specify any sequencing between the LHS and RHS.
13973 Region = LHSRegion;
13974 Visit(BO->getLHS());
13975
13976 if (O && isa<CompoundAssignOperator>(BO))
13977 notePostUse(O, BO);
13978
13979 Region = RHSRegion;
13980 Visit(BO->getRHS());
13981 }
13982
13983 // C++11 [expr.ass]p1:
13984 // the assignment is sequenced [...] before the value computation of the
13985 // assignment expression.
13986 // C11 6.5.16/3 has no such rule.
13987 Region = OldRegion;
13988 if (O)
13989 notePostMod(O, BO,
13990 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13991 : UK_ModAsSideEffect);
13992 if (SemaRef.getLangOpts().CPlusPlus17) {
13993 Tree.merge(RHSRegion);
13994 Tree.merge(LHSRegion);
13995 }
13996 }
13997
13998 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13999 VisitBinAssign(CAO);
14000 }
14001
14002 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14003 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14004 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14005 Object O = getObject(UO->getSubExpr(), true);
14006 if (!O)
14007 return VisitExpr(UO);
14008
14009 notePreMod(O, UO);
14010 Visit(UO->getSubExpr());
14011 // C++11 [expr.pre.incr]p1:
14012 // the expression ++x is equivalent to x+=1
14013 notePostMod(O, UO,
14014 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14015 : UK_ModAsSideEffect);
14016 }
14017
14018 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14019 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14020 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14021 Object O = getObject(UO->getSubExpr(), true);
14022 if (!O)
14023 return VisitExpr(UO);
14024
14025 notePreMod(O, UO);
14026 Visit(UO->getSubExpr());
14027 notePostMod(O, UO, UK_ModAsSideEffect);
14028 }
14029
14030 void VisitBinLOr(const BinaryOperator *BO) {
14031 // C++11 [expr.log.or]p2:
14032 // If the second expression is evaluated, every value computation and
14033 // side effect associated with the first expression is sequenced before
14034 // every value computation and side effect associated with the
14035 // second expression.
14036 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14037 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14038 SequenceTree::Seq OldRegion = Region;
14039
14040 EvaluationTracker Eval(*this);
14041 {
14042 SequencedSubexpression Sequenced(*this);
14043 Region = LHSRegion;
14044 Visit(BO->getLHS());
14045 }
14046
14047 // C++11 [expr.log.or]p1:
14048 // [...] the second operand is not evaluated if the first operand
14049 // evaluates to true.
14050 bool EvalResult = false;
14051 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14052 bool ShouldVisitRHS = !EvalOK || !EvalResult;
14053 if (ShouldVisitRHS) {
14054 Region = RHSRegion;
14055 Visit(BO->getRHS());
14056 }
14057
14058 Region = OldRegion;
14059 Tree.merge(LHSRegion);
14060 Tree.merge(RHSRegion);
14061 }
14062
14063 void VisitBinLAnd(const BinaryOperator *BO) {
14064 // C++11 [expr.log.and]p2:
14065 // If the second expression is evaluated, every value computation and
14066 // side effect associated with the first expression is sequenced before
14067 // every value computation and side effect associated with the
14068 // second expression.
14069 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14070 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14071 SequenceTree::Seq OldRegion = Region;
14072
14073 EvaluationTracker Eval(*this);
14074 {
14075 SequencedSubexpression Sequenced(*this);
14076 Region = LHSRegion;
14077 Visit(BO->getLHS());
14078 }
14079
14080 // C++11 [expr.log.and]p1:
14081 // [...] the second operand is not evaluated if the first operand is false.
14082 bool EvalResult = false;
14083 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14084 bool ShouldVisitRHS = !EvalOK || EvalResult;
14085 if (ShouldVisitRHS) {
14086 Region = RHSRegion;
14087 Visit(BO->getRHS());
14088 }
14089
14090 Region = OldRegion;
14091 Tree.merge(LHSRegion);
14092 Tree.merge(RHSRegion);
14093 }
14094
14095 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14096 // C++11 [expr.cond]p1:
14097 // [...] Every value computation and side effect associated with the first
14098 // expression is sequenced before every value computation and side effect
14099 // associated with the second or third expression.
14100 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14101
14102 // No sequencing is specified between the true and false expression.
14103 // However since exactly one of both is going to be evaluated we can
14104 // consider them to be sequenced. This is needed to avoid warning on
14105 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14106 // both the true and false expressions because we can't evaluate x.
14107 // This will still allow us to detect an expression like (pre C++17)
14108 // "(x ? y += 1 : y += 2) = y".
14109 //
14110 // We don't wrap the visitation of the true and false expression with
14111 // SequencedSubexpression because we don't want to downgrade modifications
14112 // as side effect in the true and false expressions after the visition
14113 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14114 // not warn between the two "y++", but we should warn between the "y++"
14115 // and the "y".
14116 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14117 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14118 SequenceTree::Seq OldRegion = Region;
14119
14120 EvaluationTracker Eval(*this);
14121 {
14122 SequencedSubexpression Sequenced(*this);
14123 Region = ConditionRegion;
14124 Visit(CO->getCond());
14125 }
14126
14127 // C++11 [expr.cond]p1:
14128 // [...] The first expression is contextually converted to bool (Clause 4).
14129 // It is evaluated and if it is true, the result of the conditional
14130 // expression is the value of the second expression, otherwise that of the
14131 // third expression. Only one of the second and third expressions is
14132 // evaluated. [...]
14133 bool EvalResult = false;
14134 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14135 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
14136 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
14137 if (ShouldVisitTrueExpr) {
14138 Region = TrueRegion;
14139 Visit(CO->getTrueExpr());
14140 }
14141 if (ShouldVisitFalseExpr) {
14142 Region = FalseRegion;
14143 Visit(CO->getFalseExpr());
14144 }
14145
14146 Region = OldRegion;
14147 Tree.merge(ConditionRegion);
14148 Tree.merge(TrueRegion);
14149 Tree.merge(FalseRegion);
14150 }
14151
14152 void VisitCallExpr(const CallExpr *CE) {
14153 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14154
14155 if (CE->isUnevaluatedBuiltinCall(Context))
14156 return;
14157
14158 // C++11 [intro.execution]p15:
14159 // When calling a function [...], every value computation and side effect
14160 // associated with any argument expression, or with the postfix expression
14161 // designating the called function, is sequenced before execution of every
14162 // expression or statement in the body of the function [and thus before
14163 // the value computation of its result].
14164 SequencedSubexpression Sequenced(*this);
14165 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14166 // C++17 [expr.call]p5
14167 // The postfix-expression is sequenced before each expression in the
14168 // expression-list and any default argument. [...]
14169 SequenceTree::Seq CalleeRegion;
14170 SequenceTree::Seq OtherRegion;
14171 if (SemaRef.getLangOpts().CPlusPlus17) {
14172 CalleeRegion = Tree.allocate(Region);
14173 OtherRegion = Tree.allocate(Region);
14174 } else {
14175 CalleeRegion = Region;
14176 OtherRegion = Region;
14177 }
14178 SequenceTree::Seq OldRegion = Region;
14179
14180 // Visit the callee expression first.
14181 Region = CalleeRegion;
14182 if (SemaRef.getLangOpts().CPlusPlus17) {
14183 SequencedSubexpression Sequenced(*this);
14184 Visit(CE->getCallee());
14185 } else {
14186 Visit(CE->getCallee());
14187 }
14188
14189 // Then visit the argument expressions.
14190 Region = OtherRegion;
14191 for (const Expr *Argument : CE->arguments())
14192 Visit(Argument);
14193
14194 Region = OldRegion;
14195 if (SemaRef.getLangOpts().CPlusPlus17) {
14196 Tree.merge(CalleeRegion);
14197 Tree.merge(OtherRegion);
14198 }
14199 });
14200 }
14201
14202 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14203 // C++17 [over.match.oper]p2:
14204 // [...] the operator notation is first transformed to the equivalent
14205 // function-call notation as summarized in Table 12 (where @ denotes one
14206 // of the operators covered in the specified subclause). However, the
14207 // operands are sequenced in the order prescribed for the built-in
14208 // operator (Clause 8).
14209 //
14210 // From the above only overloaded binary operators and overloaded call
14211 // operators have sequencing rules in C++17 that we need to handle
14212 // separately.
14213 if (!SemaRef.getLangOpts().CPlusPlus17 ||
14214 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14215 return VisitCallExpr(CXXOCE);
14216
14217 enum {
14218 NoSequencing,
14219 LHSBeforeRHS,
14220 RHSBeforeLHS,
14221 LHSBeforeRest
14222 } SequencingKind;
14223 switch (CXXOCE->getOperator()) {
14224 case OO_Equal:
14225 case OO_PlusEqual:
14226 case OO_MinusEqual:
14227 case OO_StarEqual:
14228 case OO_SlashEqual:
14229 case OO_PercentEqual:
14230 case OO_CaretEqual:
14231 case OO_AmpEqual:
14232 case OO_PipeEqual:
14233 case OO_LessLessEqual:
14234 case OO_GreaterGreaterEqual:
14235 SequencingKind = RHSBeforeLHS;
14236 break;
14237
14238 case OO_LessLess:
14239 case OO_GreaterGreater:
14240 case OO_AmpAmp:
14241 case OO_PipePipe:
14242 case OO_Comma:
14243 case OO_ArrowStar:
14244 case OO_Subscript:
14245 SequencingKind = LHSBeforeRHS;
14246 break;
14247
14248 case OO_Call:
14249 SequencingKind = LHSBeforeRest;
14250 break;
14251
14252 default:
14253 SequencingKind = NoSequencing;
14254 break;
14255 }
14256
14257 if (SequencingKind == NoSequencing)
14258 return VisitCallExpr(CXXOCE);
14259
14260 // This is a call, so all subexpressions are sequenced before the result.
14261 SequencedSubexpression Sequenced(*this);
14262
14263 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14264 assert(SemaRef.getLangOpts().CPlusPlus17 &&
14265 "Should only get there with C++17 and above!");
14266 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14267 "Should only get there with an overloaded binary operator"
14268 " or an overloaded call operator!");
14269
14270 if (SequencingKind == LHSBeforeRest) {
14271 assert(CXXOCE->getOperator() == OO_Call &&
14272 "We should only have an overloaded call operator here!");
14273
14274 // This is very similar to VisitCallExpr, except that we only have the
14275 // C++17 case. The postfix-expression is the first argument of the
14276 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14277 // are in the following arguments.
14278 //
14279 // Note that we intentionally do not visit the callee expression since
14280 // it is just a decayed reference to a function.
14281 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14282 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14283 SequenceTree::Seq OldRegion = Region;
14284
14285 assert(CXXOCE->getNumArgs() >= 1 &&
14286 "An overloaded call operator must have at least one argument"
14287 " for the postfix-expression!");
14288 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14289 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14290 CXXOCE->getNumArgs() - 1);
14291
14292 // Visit the postfix-expression first.
14293 {
14294 Region = PostfixExprRegion;
14295 SequencedSubexpression Sequenced(*this);
14296 Visit(PostfixExpr);
14297 }
14298
14299 // Then visit the argument expressions.
14300 Region = ArgsRegion;
14301 for (const Expr *Arg : Args)
14302 Visit(Arg);
14303
14304 Region = OldRegion;
14305 Tree.merge(PostfixExprRegion);
14306 Tree.merge(ArgsRegion);
14307 } else {
14308 assert(CXXOCE->getNumArgs() == 2 &&
14309 "Should only have two arguments here!");
14310 assert((SequencingKind == LHSBeforeRHS ||
14311 SequencingKind == RHSBeforeLHS) &&
14312 "Unexpected sequencing kind!");
14313
14314 // We do not visit the callee expression since it is just a decayed
14315 // reference to a function.
14316 const Expr *E1 = CXXOCE->getArg(0);
14317 const Expr *E2 = CXXOCE->getArg(1);
14318 if (SequencingKind == RHSBeforeLHS)
14319 std::swap(E1, E2);
14320
14321 return VisitSequencedExpressions(E1, E2);
14322 }
14323 });
14324 }
14325
14326 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14327 // This is a call, so all subexpressions are sequenced before the result.
14328 SequencedSubexpression Sequenced(*this);
14329
14330 if (!CCE->isListInitialization())
14331 return VisitExpr(CCE);
14332
14333 // In C++11, list initializations are sequenced.
14334 SequenceExpressionsInOrder(
14335 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
14336 }
14337
14338 void VisitInitListExpr(const InitListExpr *ILE) {
14339 if (!SemaRef.getLangOpts().CPlusPlus11)
14340 return VisitExpr(ILE);
14341
14342 // In C++11, list initializations are sequenced.
14343 SequenceExpressionsInOrder(ILE->inits());
14344 }
14345
14346 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
14347 // C++20 parenthesized list initializations are sequenced. See C++20
14348 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
14349 SequenceExpressionsInOrder(PLIE->getInitExprs());
14350 }
14351
14352private:
14353 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
14355 SequenceTree::Seq Parent = Region;
14356 for (const Expr *E : ExpressionList) {
14357 if (!E)
14358 continue;
14359 Region = Tree.allocate(Parent);
14360 Elts.push_back(Region);
14361 Visit(E);
14362 }
14363
14364 // Forget that the initializers are sequenced.
14365 Region = Parent;
14366 for (unsigned I = 0; I < Elts.size(); ++I)
14367 Tree.merge(Elts[I]);
14368 }
14369};
14370
14371SequenceChecker::UsageInfo::UsageInfo() = default;
14372
14373} // namespace
14374
14375void Sema::CheckUnsequencedOperations(const Expr *E) {
14376 SmallVector<const Expr *, 8> WorkList;
14377 WorkList.push_back(E);
14378 while (!WorkList.empty()) {
14379 const Expr *Item = WorkList.pop_back_val();
14380 SequenceChecker(*this, Item, WorkList);
14381 }
14382}
14383
14384void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14385 bool IsConstexpr) {
14386 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
14387 IsConstexpr || isa<ConstantExpr>(E));
14388 CheckImplicitConversions(E, CheckLoc);
14389 if (!E->isInstantiationDependent())
14390 CheckUnsequencedOperations(E);
14391 if (!IsConstexpr && !E->isValueDependent())
14392 CheckForIntOverflow(E);
14393}
14394
14395void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14396 FieldDecl *BitField,
14397 Expr *Init) {
14398 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14399}
14400
14402 SourceLocation Loc) {
14403 if (!PType->isVariablyModifiedType())
14404 return;
14405 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14406 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14407 return;
14408 }
14409 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14410 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14411 return;
14412 }
14413 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14414 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14415 return;
14416 }
14417
14418 const ArrayType *AT = S.Context.getAsArrayType(PType);
14419 if (!AT)
14420 return;
14421
14424 return;
14425 }
14426
14427 S.Diag(Loc, diag::err_array_star_in_function_definition);
14428}
14429
14431 bool CheckParameterNames) {
14432 bool HasInvalidParm = false;
14433 for (ParmVarDecl *Param : Parameters) {
14434 assert(Param && "null in a parameter list");
14435 // C99 6.7.5.3p4: the parameters in a parameter type list in a
14436 // function declarator that is part of a function definition of
14437 // that function shall not have incomplete type.
14438 //
14439 // C++23 [dcl.fct.def.general]/p2
14440 // The type of a parameter [...] for a function definition
14441 // shall not be a (possibly cv-qualified) class type that is incomplete
14442 // or abstract within the function body unless the function is deleted.
14443 if (!Param->isInvalidDecl() &&
14444 (RequireCompleteType(Param->getLocation(), Param->getType(),
14445 diag::err_typecheck_decl_incomplete_type) ||
14446 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
14447 diag::err_abstract_type_in_decl,
14449 Param->setInvalidDecl();
14450 HasInvalidParm = true;
14451 }
14452
14453 // C99 6.9.1p5: If the declarator includes a parameter type list, the
14454 // declaration of each parameter shall include an identifier.
14455 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14456 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14457 // Diagnose this as an extension in C17 and earlier.
14458 if (!getLangOpts().C23)
14459 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
14460 }
14461
14462 // C99 6.7.5.3p12:
14463 // If the function declarator is not part of a definition of that
14464 // function, parameters may have incomplete type and may use the [*]
14465 // notation in their sequences of declarator specifiers to specify
14466 // variable length array types.
14467 QualType PType = Param->getOriginalType();
14468 // FIXME: This diagnostic should point the '[*]' if source-location
14469 // information is added for it.
14470 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14471
14472 // If the parameter is a c++ class type and it has to be destructed in the
14473 // callee function, declare the destructor so that it can be called by the
14474 // callee function. Do not perform any direct access check on the dtor here.
14475 if (!Param->isInvalidDecl()) {
14476 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14477 if (!ClassDecl->isInvalidDecl() &&
14478 !ClassDecl->hasIrrelevantDestructor() &&
14479 !ClassDecl->isDependentContext() &&
14480 ClassDecl->isParamDestroyedInCallee()) {
14482 MarkFunctionReferenced(Param->getLocation(), Destructor);
14483 DiagnoseUseOfDecl(Destructor, Param->getLocation());
14484 }
14485 }
14486 }
14487
14488 // Parameters with the pass_object_size attribute only need to be marked
14489 // constant at function definitions. Because we lack information about
14490 // whether we're on a declaration or definition when we're instantiating the
14491 // attribute, we need to check for constness here.
14492 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14493 if (!Param->getType().isConstQualified())
14494 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14495 << Attr->getSpelling() << 1;
14496
14497 // Check for parameter names shadowing fields from the class.
14498 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14499 // The owning context for the parameter should be the function, but we
14500 // want to see if this function's declaration context is a record.
14501 DeclContext *DC = Param->getDeclContext();
14502 if (DC && DC->isFunctionOrMethod()) {
14503 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14504 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14505 RD, /*DeclIsField*/ false);
14506 }
14507 }
14508
14509 if (!Param->isInvalidDecl() &&
14510 Param->getOriginalType()->isWebAssemblyTableType()) {
14511 Param->setInvalidDecl();
14512 HasInvalidParm = true;
14513 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
14514 }
14515 }
14516
14517 return HasInvalidParm;
14518}
14519
14520std::optional<std::pair<
14522 *E,
14524 &Ctx);
14525
14526/// Compute the alignment and offset of the base class object given the
14527/// derived-to-base cast expression and the alignment and offset of the derived
14528/// class object.
14529static std::pair<CharUnits, CharUnits>
14531 CharUnits BaseAlignment, CharUnits Offset,
14532 ASTContext &Ctx) {
14533 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14534 ++PathI) {
14535 const CXXBaseSpecifier *Base = *PathI;
14536 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14537 if (Base->isVirtual()) {
14538 // The complete object may have a lower alignment than the non-virtual
14539 // alignment of the base, in which case the base may be misaligned. Choose
14540 // the smaller of the non-virtual alignment and BaseAlignment, which is a
14541 // conservative lower bound of the complete object alignment.
14542 CharUnits NonVirtualAlignment =
14544 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14545 Offset = CharUnits::Zero();
14546 } else {
14547 const ASTRecordLayout &RL =
14548 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14549 Offset += RL.getBaseClassOffset(BaseDecl);
14550 }
14551 DerivedType = Base->getType();
14552 }
14553
14554 return std::make_pair(BaseAlignment, Offset);
14555}
14556
14557/// Compute the alignment and offset of a binary additive operator.
14558static std::optional<std::pair<CharUnits, CharUnits>>
14560 bool IsSub, ASTContext &Ctx) {
14561 QualType PointeeType = PtrE->getType()->getPointeeType();
14562
14563 if (!PointeeType->isConstantSizeType())
14564 return std::nullopt;
14565
14566 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14567
14568 if (!P)
14569 return std::nullopt;
14570
14571 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14572 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14573 CharUnits Offset = EltSize * IdxRes->getExtValue();
14574 if (IsSub)
14575 Offset = -Offset;
14576 return std::make_pair(P->first, P->second + Offset);
14577 }
14578
14579 // If the integer expression isn't a constant expression, compute the lower
14580 // bound of the alignment using the alignment and offset of the pointer
14581 // expression and the element size.
14582 return std::make_pair(
14583 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14584 CharUnits::Zero());
14585}
14586
14587/// This helper function takes an lvalue expression and returns the alignment of
14588/// a VarDecl and a constant offset from the VarDecl.
14589std::optional<std::pair<
14590 CharUnits,
14592 ASTContext &Ctx) {
14593 E = E->IgnoreParens();
14594 switch (E->getStmtClass()) {
14595 default:
14596 break;
14597 case Stmt::CStyleCastExprClass:
14598 case Stmt::CXXStaticCastExprClass:
14599 case Stmt::ImplicitCastExprClass: {
14600 auto *CE = cast<CastExpr>(E);
14601 const Expr *From = CE->getSubExpr();
14602 switch (CE->getCastKind()) {
14603 default:
14604 break;
14605 case CK_NoOp:
14606 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14607 case CK_UncheckedDerivedToBase:
14608 case CK_DerivedToBase: {
14609 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14610 if (!P)
14611 break;
14612 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14613 P->second, Ctx);
14614 }
14615 }
14616 break;
14617 }
14618 case Stmt::ArraySubscriptExprClass: {
14619 auto *ASE = cast<ArraySubscriptExpr>(E);
14621 false, Ctx);
14622 }
14623 case Stmt::DeclRefExprClass: {
14624 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14625 // FIXME: If VD is captured by copy or is an escaping __block variable,
14626 // use the alignment of VD's type.
14627 if (!VD->getType()->isReferenceType()) {
14628 // Dependent alignment cannot be resolved -> bail out.
14629 if (VD->hasDependentAlignment())
14630 break;
14631 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14632 }
14633 if (VD->hasInit())
14634 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14635 }
14636 break;
14637 }
14638 case Stmt::MemberExprClass: {
14639 auto *ME = cast<MemberExpr>(E);
14640 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14641 if (!FD || FD->getType()->isReferenceType() ||
14642 FD->getParent()->isInvalidDecl())
14643 break;
14644 std::optional<std::pair<CharUnits, CharUnits>> P;
14645 if (ME->isArrow())
14646 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14647 else
14648 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14649 if (!P)
14650 break;
14651 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14652 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14653 return std::make_pair(P->first,
14654 P->second + CharUnits::fromQuantity(Offset));
14655 }
14656 case Stmt::UnaryOperatorClass: {
14657 auto *UO = cast<UnaryOperator>(E);
14658 switch (UO->getOpcode()) {
14659 default:
14660 break;
14661 case UO_Deref:
14663 }
14664 break;
14665 }
14666 case Stmt::BinaryOperatorClass: {
14667 auto *BO = cast<BinaryOperator>(E);
14668 auto Opcode = BO->getOpcode();
14669 switch (Opcode) {
14670 default:
14671 break;
14672 case BO_Comma:
14674 }
14675 break;
14676 }
14677 }
14678 return std::nullopt;
14679}
14680
14681/// This helper function takes a pointer expression and returns the alignment of
14682/// a VarDecl and a constant offset from the VarDecl.
14683std::optional<std::pair<
14685 *E,
14687 &Ctx) {
14688 E = E->IgnoreParens();
14689 switch (E->getStmtClass()) {
14690 default:
14691 break;
14692 case Stmt::CStyleCastExprClass:
14693 case Stmt::CXXStaticCastExprClass:
14694 case Stmt::ImplicitCastExprClass: {
14695 auto *CE = cast<CastExpr>(E);
14696 const Expr *From = CE->getSubExpr();
14697 switch (CE->getCastKind()) {
14698 default:
14699 break;
14700 case CK_NoOp:
14701 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14702 case CK_ArrayToPointerDecay:
14703 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14704 case CK_UncheckedDerivedToBase:
14705 case CK_DerivedToBase: {
14706 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14707 if (!P)
14708 break;
14710 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14711 }
14712 }
14713 break;
14714 }
14715 case Stmt::CXXThisExprClass: {
14716 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14718 return std::make_pair(Alignment, CharUnits::Zero());
14719 }
14720 case Stmt::UnaryOperatorClass: {
14721 auto *UO = cast<UnaryOperator>(E);
14722 if (UO->getOpcode() == UO_AddrOf)
14724 break;
14725 }
14726 case Stmt::BinaryOperatorClass: {
14727 auto *BO = cast<BinaryOperator>(E);
14728 auto Opcode = BO->getOpcode();
14729 switch (Opcode) {
14730 default:
14731 break;
14732 case BO_Add:
14733 case BO_Sub: {
14734 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14735 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14736 std::swap(LHS, RHS);
14737 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14738 Ctx);
14739 }
14740 case BO_Comma:
14741 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14742 }
14743 break;
14744 }
14745 }
14746 return std::nullopt;
14747}
14748
14750 // See if we can compute the alignment of a VarDecl and an offset from it.
14751 std::optional<std::pair<CharUnits, CharUnits>> P =
14753
14754 if (P)
14755 return P->first.alignmentAtOffset(P->second);
14756
14757 // If that failed, return the type's alignment.
14759}
14760
14762 // This is actually a lot of work to potentially be doing on every
14763 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14764 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14765 return;
14766
14767 // Ignore dependent types.
14768 if (T->isDependentType() || Op->getType()->isDependentType())
14769 return;
14770
14771 // Require that the destination be a pointer type.
14772 const PointerType *DestPtr = T->getAs<PointerType>();
14773 if (!DestPtr) return;
14774
14775 // If the destination has alignment 1, we're done.
14776 QualType DestPointee = DestPtr->getPointeeType();
14777 if (DestPointee->isIncompleteType()) return;
14778 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14779 if (DestAlign.isOne()) return;
14780
14781 // Require that the source be a pointer type.
14782 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14783 if (!SrcPtr) return;
14784 QualType SrcPointee = SrcPtr->getPointeeType();
14785
14786 // Explicitly allow casts from cv void*. We already implicitly
14787 // allowed casts to cv void*, since they have alignment 1.
14788 // Also allow casts involving incomplete types, which implicitly
14789 // includes 'void'.
14790 if (SrcPointee->isIncompleteType()) return;
14791
14792 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14793
14794 if (SrcAlign >= DestAlign) return;
14795
14796 Diag(TRange.getBegin(), diag::warn_cast_align)
14797 << Op->getType() << T
14798 << static_cast<unsigned>(SrcAlign.getQuantity())
14799 << static_cast<unsigned>(DestAlign.getQuantity())
14800 << TRange << Op->getSourceRange();
14801}
14802
14803void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14804 const ArraySubscriptExpr *ASE,
14805 bool AllowOnePastEnd, bool IndexNegated) {
14806 // Already diagnosed by the constant evaluator.
14808 return;
14809
14810 IndexExpr = IndexExpr->IgnoreParenImpCasts();
14811 if (IndexExpr->isValueDependent())
14812 return;
14813
14814 const Type *EffectiveType =
14816 BaseExpr = BaseExpr->IgnoreParenCasts();
14817 const ConstantArrayType *ArrayTy =
14818 Context.getAsConstantArrayType(BaseExpr->getType());
14819
14821 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
14822
14823 const Type *BaseType =
14824 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14825 bool IsUnboundedArray =
14826 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
14827 Context, StrictFlexArraysLevel,
14828 /*IgnoreTemplateOrMacroSubstitution=*/true);
14829 if (EffectiveType->isDependentType() ||
14830 (!IsUnboundedArray && BaseType->isDependentType()))
14831 return;
14832
14834 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14835 return;
14836
14837 llvm::APSInt index = Result.Val.getInt();
14838 if (IndexNegated) {
14839 index.setIsUnsigned(false);
14840 index = -index;
14841 }
14842
14843 if (IsUnboundedArray) {
14844 if (EffectiveType->isFunctionType())
14845 return;
14846 if (index.isUnsigned() || !index.isNegative()) {
14847 const auto &ASTC = getASTContext();
14848 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
14849 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
14850 if (index.getBitWidth() < AddrBits)
14851 index = index.zext(AddrBits);
14852 std::optional<CharUnits> ElemCharUnits =
14853 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14854 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14855 // pointer) bounds-checking isn't meaningful.
14856 if (!ElemCharUnits || ElemCharUnits->isZero())
14857 return;
14858 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14859 // If index has more active bits than address space, we already know
14860 // we have a bounds violation to warn about. Otherwise, compute
14861 // address of (index + 1)th element, and warn about bounds violation
14862 // only if that address exceeds address space.
14863 if (index.getActiveBits() <= AddrBits) {
14864 bool Overflow;
14865 llvm::APInt Product(index);
14866 Product += 1;
14867 Product = Product.umul_ov(ElemBytes, Overflow);
14868 if (!Overflow && Product.getActiveBits() <= AddrBits)
14869 return;
14870 }
14871
14872 // Need to compute max possible elements in address space, since that
14873 // is included in diag message.
14874 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14875 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14876 MaxElems += 1;
14877 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14878 MaxElems = MaxElems.udiv(ElemBytes);
14879
14880 unsigned DiagID =
14881 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14882 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14883
14884 // Diag message shows element size in bits and in "bytes" (platform-
14885 // dependent CharUnits)
14886 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14887 PDiag(DiagID) << index << AddrBits
14888 << (unsigned)ASTC.toBits(*ElemCharUnits)
14889 << ElemBytes << MaxElems
14890 << MaxElems.getZExtValue()
14891 << IndexExpr->getSourceRange());
14892
14893 const NamedDecl *ND = nullptr;
14894 // Try harder to find a NamedDecl to point at in the note.
14895 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14896 BaseExpr = ASE->getBase()->IgnoreParenCasts();
14897 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14898 ND = DRE->getDecl();
14899 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14900 ND = ME->getMemberDecl();
14901
14902 if (ND)
14903 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14904 PDiag(diag::note_array_declared_here) << ND);
14905 }
14906 return;
14907 }
14908
14909 if (index.isUnsigned() || !index.isNegative()) {
14910 // It is possible that the type of the base expression after
14911 // IgnoreParenCasts is incomplete, even though the type of the base
14912 // expression before IgnoreParenCasts is complete (see PR39746 for an
14913 // example). In this case we have no information about whether the array
14914 // access exceeds the array bounds. However we can still diagnose an array
14915 // access which precedes the array bounds.
14916 if (BaseType->isIncompleteType())
14917 return;
14918
14919 llvm::APInt size = ArrayTy->getSize();
14920
14921 if (BaseType != EffectiveType) {
14922 // Make sure we're comparing apples to apples when comparing index to
14923 // size.
14924 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14925 uint64_t array_typesize = Context.getTypeSize(BaseType);
14926
14927 // Handle ptrarith_typesize being zero, such as when casting to void*.
14928 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
14929 if (!ptrarith_typesize)
14930 ptrarith_typesize = Context.getCharWidth();
14931
14932 if (ptrarith_typesize != array_typesize) {
14933 // There's a cast to a different size type involved.
14934 uint64_t ratio = array_typesize / ptrarith_typesize;
14935
14936 // TODO: Be smarter about handling cases where array_typesize is not a
14937 // multiple of ptrarith_typesize.
14938 if (ptrarith_typesize * ratio == array_typesize)
14939 size *= llvm::APInt(size.getBitWidth(), ratio);
14940 }
14941 }
14942
14943 if (size.getBitWidth() > index.getBitWidth())
14944 index = index.zext(size.getBitWidth());
14945 else if (size.getBitWidth() < index.getBitWidth())
14946 size = size.zext(index.getBitWidth());
14947
14948 // For array subscripting the index must be less than size, but for pointer
14949 // arithmetic also allow the index (offset) to be equal to size since
14950 // computing the next address after the end of the array is legal and
14951 // commonly done e.g. in C++ iterators and range-based for loops.
14952 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14953 return;
14954
14955 // Suppress the warning if the subscript expression (as identified by the
14956 // ']' location) and the index expression are both from macro expansions
14957 // within a system header.
14958 if (ASE) {
14959 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14960 ASE->getRBracketLoc());
14961 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14962 SourceLocation IndexLoc =
14963 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14964 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14965 return;
14966 }
14967 }
14968
14969 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
14970 : diag::warn_ptr_arith_exceeds_bounds;
14971 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
14972 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
14973
14974 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14975 PDiag(DiagID)
14976 << index << ArrayTy->desugar() << CastMsg
14977 << CastMsgTy << IndexExpr->getSourceRange());
14978 } else {
14979 unsigned DiagID = diag::warn_array_index_precedes_bounds;
14980 if (!ASE) {
14981 DiagID = diag::warn_ptr_arith_precedes_bounds;
14982 if (index.isNegative()) index = -index;
14983 }
14984
14985 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14986 PDiag(DiagID) << index << IndexExpr->getSourceRange());
14987 }
14988
14989 const NamedDecl *ND = nullptr;
14990 // Try harder to find a NamedDecl to point at in the note.
14991 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14992 BaseExpr = ASE->getBase()->IgnoreParenCasts();
14993 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14994 ND = DRE->getDecl();
14995 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14996 ND = ME->getMemberDecl();
14997
14998 if (ND)
14999 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15000 PDiag(diag::note_array_declared_here) << ND);
15001}
15002
15003void Sema::CheckArrayAccess(const Expr *expr) {
15004 int AllowOnePastEnd = 0;
15005 while (expr) {
15006 expr = expr->IgnoreParenImpCasts();
15007 switch (expr->getStmtClass()) {
15008 case Stmt::ArraySubscriptExprClass: {
15009 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15010 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15011 AllowOnePastEnd > 0);
15012 expr = ASE->getBase();
15013 break;
15014 }
15015 case Stmt::MemberExprClass: {
15016 expr = cast<MemberExpr>(expr)->getBase();
15017 break;
15018 }
15019 case Stmt::ArraySectionExprClass: {
15020 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
15021 // FIXME: We should probably be checking all of the elements to the
15022 // 'length' here as well.
15023 if (ASE->getLowerBound())
15024 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15025 /*ASE=*/nullptr, AllowOnePastEnd > 0);
15026 return;
15027 }
15028 case Stmt::UnaryOperatorClass: {
15029 // Only unwrap the * and & unary operators
15030 const UnaryOperator *UO = cast<UnaryOperator>(expr);
15031 expr = UO->getSubExpr();
15032 switch (UO->getOpcode()) {
15033 case UO_AddrOf:
15034 AllowOnePastEnd++;
15035 break;
15036 case UO_Deref:
15037 AllowOnePastEnd--;
15038 break;
15039 default:
15040 return;
15041 }
15042 break;
15043 }
15044 case Stmt::ConditionalOperatorClass: {
15045 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15046 if (const Expr *lhs = cond->getLHS())
15047 CheckArrayAccess(lhs);
15048 if (const Expr *rhs = cond->getRHS())
15049 CheckArrayAccess(rhs);
15050 return;
15051 }
15052 case Stmt::CXXOperatorCallExprClass: {
15053 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15054 for (const auto *Arg : OCE->arguments())
15055 CheckArrayAccess(Arg);
15056 return;
15057 }
15058 default:
15059 return;
15060 }
15061 }
15062}
15063
15065 Expr *RHS, bool isProperty) {
15066 // Check if RHS is an Objective-C object literal, which also can get
15067 // immediately zapped in a weak reference. Note that we explicitly
15068 // allow ObjCStringLiterals, since those are designed to never really die.
15069 RHS = RHS->IgnoreParenImpCasts();
15070
15071 // This enum needs to match with the 'select' in
15072 // warn_objc_arc_literal_assign (off-by-1).
15074 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
15075 return false;
15076
15077 S.Diag(Loc, diag::warn_arc_literal_assign)
15078 << (unsigned) Kind
15079 << (isProperty ? 0 : 1)
15080 << RHS->getSourceRange();
15081
15082 return true;
15083}
15084
15087 Expr *RHS, bool isProperty) {
15088 // Strip off any implicit cast added to get to the one ARC-specific.
15089 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15090 if (cast->getCastKind() == CK_ARCConsumeObject) {
15091 S.Diag(Loc, diag::warn_arc_retained_assign)
15093 << (isProperty ? 0 : 1)
15094 << RHS->getSourceRange();
15095 return true;
15096 }
15097 RHS = cast->getSubExpr();
15098 }
15099
15100 if (LT == Qualifiers::OCL_Weak &&
15101 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15102 return true;
15103
15104 return false;
15105}
15106
15108 QualType LHS, Expr *RHS) {
15110
15112 return false;
15113
15114 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15115 return true;
15116
15117 return false;
15118}
15119
15121 Expr *LHS, Expr *RHS) {
15122 QualType LHSType;
15123 // PropertyRef on LHS type need be directly obtained from
15124 // its declaration as it has a PseudoType.
15126 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15127 if (PRE && !PRE->isImplicitProperty()) {
15128 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15129 if (PD)
15130 LHSType = PD->getType();
15131 }
15132
15133 if (LHSType.isNull())
15134 LHSType = LHS->getType();
15135
15137
15138 if (LT == Qualifiers::OCL_Weak) {
15139 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15141 }
15142
15143 if (checkUnsafeAssigns(Loc, LHSType, RHS))
15144 return;
15145
15146 // FIXME. Check for other life times.
15147 if (LT != Qualifiers::OCL_None)
15148 return;
15149
15150 if (PRE) {
15151 if (PRE->isImplicitProperty())
15152 return;
15153 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15154 if (!PD)
15155 return;
15156
15157 unsigned Attributes = PD->getPropertyAttributes();
15158 if (Attributes & ObjCPropertyAttribute::kind_assign) {
15159 // when 'assign' attribute was not explicitly specified
15160 // by user, ignore it and rely on property type itself
15161 // for lifetime info.
15162 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15163 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15164 LHSType->isObjCRetainableType())
15165 return;
15166
15167 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15168 if (cast->getCastKind() == CK_ARCConsumeObject) {
15169 Diag(Loc, diag::warn_arc_retained_property_assign)
15170 << RHS->getSourceRange();
15171 return;
15172 }
15173 RHS = cast->getSubExpr();
15174 }
15175 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15176 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15177 return;
15178 }
15179 }
15180}
15181
15182//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15183
15184static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15185 SourceLocation StmtLoc,
15186 const NullStmt *Body) {
15187 // Do not warn if the body is a macro that expands to nothing, e.g:
15188 //
15189 // #define CALL(x)
15190 // if (condition)
15191 // CALL(0);
15192 if (Body->hasLeadingEmptyMacro())
15193 return false;
15194
15195 // Get line numbers of statement and body.
15196 bool StmtLineInvalid;
15197 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15198 &StmtLineInvalid);
15199 if (StmtLineInvalid)
15200 return false;
15201
15202 bool BodyLineInvalid;
15203 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15204 &BodyLineInvalid);
15205 if (BodyLineInvalid)
15206 return false;
15207
15208 // Warn if null statement and body are on the same line.
15209 if (StmtLine != BodyLine)
15210 return false;
15211
15212 return true;
15213}
15214
15216 const Stmt *Body,
15217 unsigned DiagID) {
15218 // Since this is a syntactic check, don't emit diagnostic for template
15219 // instantiations, this just adds noise.
15221 return;
15222
15223 // The body should be a null statement.
15224 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15225 if (!NBody)
15226 return;
15227
15228 // Do the usual checks.
15229 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15230 return;
15231
15232 Diag(NBody->getSemiLoc(), DiagID);
15233 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15234}
15235
15237 const Stmt *PossibleBody) {
15238 assert(!CurrentInstantiationScope); // Ensured by caller
15239
15240 SourceLocation StmtLoc;
15241 const Stmt *Body;
15242 unsigned DiagID;
15243 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15244 StmtLoc = FS->getRParenLoc();
15245 Body = FS->getBody();
15246 DiagID = diag::warn_empty_for_body;
15247 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15248 StmtLoc = WS->getRParenLoc();
15249 Body = WS->getBody();
15250 DiagID = diag::warn_empty_while_body;
15251 } else
15252 return; // Neither `for' nor `while'.
15253
15254 // The body should be a null statement.
15255 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15256 if (!NBody)
15257 return;
15258
15259 // Skip expensive checks if diagnostic is disabled.
15260 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15261 return;
15262
15263 // Do the usual checks.
15264 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15265 return;
15266
15267 // `for(...);' and `while(...);' are popular idioms, so in order to keep
15268 // noise level low, emit diagnostics only if for/while is followed by a
15269 // CompoundStmt, e.g.:
15270 // for (int i = 0; i < n; i++);
15271 // {
15272 // a(i);
15273 // }
15274 // or if for/while is followed by a statement with more indentation
15275 // than for/while itself:
15276 // for (int i = 0; i < n; i++);
15277 // a(i);
15278 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15279 if (!ProbableTypo) {
15280 bool BodyColInvalid;
15281 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15282 PossibleBody->getBeginLoc(), &BodyColInvalid);
15283 if (BodyColInvalid)
15284 return;
15285
15286 bool StmtColInvalid;
15287 unsigned StmtCol =
15288 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15289 if (StmtColInvalid)
15290 return;
15291
15292 if (BodyCol > StmtCol)
15293 ProbableTypo = true;
15294 }
15295
15296 if (ProbableTypo) {
15297 Diag(NBody->getSemiLoc(), DiagID);
15298 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15299 }
15300}
15301
15302//===--- CHECK: Warn on self move with std::move. -------------------------===//
15303
15304void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15305 SourceLocation OpLoc) {
15306 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15307 return;
15308
15310 return;
15311
15312 // Strip parens and casts away.
15313 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15314 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15315
15316 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
15317 // which we can treat as an inlined std::move
15318 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
15319 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
15320 RHSExpr = CE->getArg(0);
15321 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
15322 CXXSCE && CXXSCE->isXValue())
15323 RHSExpr = CXXSCE->getSubExpr();
15324 else
15325 return;
15326
15327 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15328 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15329
15330 // Two DeclRefExpr's, check that the decls are the same.
15331 if (LHSDeclRef && RHSDeclRef) {
15332 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15333 return;
15334 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15335 RHSDeclRef->getDecl()->getCanonicalDecl())
15336 return;
15337
15338 auto D = Diag(OpLoc, diag::warn_self_move)
15339 << LHSExpr->getType() << LHSExpr->getSourceRange()
15340 << RHSExpr->getSourceRange();
15341 if (const FieldDecl *F =
15343 D << 1 << F
15344 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15345 else
15346 D << 0;
15347 return;
15348 }
15349
15350 // Member variables require a different approach to check for self moves.
15351 // MemberExpr's are the same if every nested MemberExpr refers to the same
15352 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15353 // the base Expr's are CXXThisExpr's.
15354 const Expr *LHSBase = LHSExpr;
15355 const Expr *RHSBase = RHSExpr;
15356 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15357 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15358 if (!LHSME || !RHSME)
15359 return;
15360
15361 while (LHSME && RHSME) {
15362 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15363 RHSME->getMemberDecl()->getCanonicalDecl())
15364 return;
15365
15366 LHSBase = LHSME->getBase();
15367 RHSBase = RHSME->getBase();
15368 LHSME = dyn_cast<MemberExpr>(LHSBase);
15369 RHSME = dyn_cast<MemberExpr>(RHSBase);
15370 }
15371
15372 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15373 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15374 if (LHSDeclRef && RHSDeclRef) {
15375 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15376 return;
15377 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15378 RHSDeclRef->getDecl()->getCanonicalDecl())
15379 return;
15380
15381 Diag(OpLoc, diag::warn_self_move)
15382 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15383 << RHSExpr->getSourceRange();
15384 return;
15385 }
15386
15387 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15388 Diag(OpLoc, diag::warn_self_move)
15389 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15390 << RHSExpr->getSourceRange();
15391}
15392
15393//===--- Layout compatibility ----------------------------------------------//
15394
15395static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
15396
15397/// Check if two enumeration types are layout-compatible.
15398static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
15399 const EnumDecl *ED2) {
15400 // C++11 [dcl.enum] p8:
15401 // Two enumeration types are layout-compatible if they have the same
15402 // underlying type.
15403 return ED1->isComplete() && ED2->isComplete() &&
15404 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15405}
15406
15407/// Check if two fields are layout-compatible.
15408/// Can be used on union members, which are exempt from alignment requirement
15409/// of common initial sequence.
15410static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
15411 const FieldDecl *Field2,
15412 bool AreUnionMembers = false) {
15413#ifndef NDEBUG
15414 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
15415 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
15416 assert(((Field1Parent->isStructureOrClassType() &&
15417 Field2Parent->isStructureOrClassType()) ||
15418 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
15419 "Can't evaluate layout compatibility between a struct field and a "
15420 "union field.");
15421 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
15422 (AreUnionMembers && Field1Parent->isUnionType())) &&
15423 "AreUnionMembers should be 'true' for union fields (only).");
15424#endif
15425
15426 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15427 return false;
15428
15429 if (Field1->isBitField() != Field2->isBitField())
15430 return false;
15431
15432 if (Field1->isBitField()) {
15433 // Make sure that the bit-fields are the same length.
15434 unsigned Bits1 = Field1->getBitWidthValue();
15435 unsigned Bits2 = Field2->getBitWidthValue();
15436
15437 if (Bits1 != Bits2)
15438 return false;
15439 }
15440
15441 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
15442 Field2->hasAttr<clang::NoUniqueAddressAttr>())
15443 return false;
15444
15445 if (!AreUnionMembers &&
15446 Field1->getMaxAlignment() != Field2->getMaxAlignment())
15447 return false;
15448
15449 return true;
15450}
15451
15452/// Check if two standard-layout structs are layout-compatible.
15453/// (C++11 [class.mem] p17)
15454static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
15455 const RecordDecl *RD2) {
15456 // Get to the class where the fields are declared
15457 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
15458 RD1 = D1CXX->getStandardLayoutBaseWithFields();
15459
15460 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
15461 RD2 = D2CXX->getStandardLayoutBaseWithFields();
15462
15463 // Check the fields.
15464 return llvm::equal(RD1->fields(), RD2->fields(),
15465 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
15466 return isLayoutCompatible(C, F1, F2);
15467 });
15468}
15469
15470/// Check if two standard-layout unions are layout-compatible.
15471/// (C++11 [class.mem] p18)
15472static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
15473 const RecordDecl *RD2) {
15474 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
15475 RD2->fields());
15476
15477 for (auto *Field1 : RD1->fields()) {
15478 auto I = UnmatchedFields.begin();
15479 auto E = UnmatchedFields.end();
15480
15481 for ( ; I != E; ++I) {
15482 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
15483 bool Result = UnmatchedFields.erase(*I);
15484 (void) Result;
15485 assert(Result);
15486 break;
15487 }
15488 }
15489 if (I == E)
15490 return false;
15491 }
15492
15493 return UnmatchedFields.empty();
15494}
15495
15496static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
15497 const RecordDecl *RD2) {
15498 if (RD1->isUnion() != RD2->isUnion())
15499 return false;
15500
15501 if (RD1->isUnion())
15502 return isLayoutCompatibleUnion(C, RD1, RD2);
15503 else
15504 return isLayoutCompatibleStruct(C, RD1, RD2);
15505}
15506
15507/// Check if two types are layout-compatible in C++11 sense.
15508static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
15509 if (T1.isNull() || T2.isNull())
15510 return false;
15511
15512 // C++20 [basic.types] p11:
15513 // Two types cv1 T1 and cv2 T2 are layout-compatible types
15514 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
15515 // or layout-compatible standard-layout class types (11.4).
15518
15519 if (C.hasSameType(T1, T2))
15520 return true;
15521
15522 const Type::TypeClass TC1 = T1->getTypeClass();
15523 const Type::TypeClass TC2 = T2->getTypeClass();
15524
15525 if (TC1 != TC2)
15526 return false;
15527
15528 if (TC1 == Type::Enum)
15529 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
15530 if (TC1 == Type::Record) {
15531 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15532 return false;
15533
15535 T2->castAsRecordDecl());
15536 }
15537
15538 return false;
15539}
15540
15542 return isLayoutCompatible(getASTContext(), T1, T2);
15543}
15544
15545//===-------------- Pointer interconvertibility ----------------------------//
15546
15548 const TypeSourceInfo *Derived) {
15549 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
15550 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
15551
15552 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
15553 getASTContext().hasSameType(BaseT, DerivedT))
15554 return true;
15555
15556 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
15557 return false;
15558
15559 // Per [basic.compound]/4.3, containing object has to be standard-layout.
15560 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
15561 return true;
15562
15563 return false;
15564}
15565
15566//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15567
15568/// Given a type tag expression find the type tag itself.
15569///
15570/// \param TypeExpr Type tag expression, as it appears in user's code.
15571///
15572/// \param VD Declaration of an identifier that appears in a type tag.
15573///
15574/// \param MagicValue Type tag magic value.
15575///
15576/// \param isConstantEvaluated whether the evalaution should be performed in
15577
15578/// constant context.
15579static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15580 const ValueDecl **VD, uint64_t *MagicValue,
15581 bool isConstantEvaluated) {
15582 while(true) {
15583 if (!TypeExpr)
15584 return false;
15585
15586 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15587
15588 switch (TypeExpr->getStmtClass()) {
15589 case Stmt::UnaryOperatorClass: {
15590 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15591 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15592 TypeExpr = UO->getSubExpr();
15593 continue;
15594 }
15595 return false;
15596 }
15597
15598 case Stmt::DeclRefExprClass: {
15599 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15600 *VD = DRE->getDecl();
15601 return true;
15602 }
15603
15604 case Stmt::IntegerLiteralClass: {
15605 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15606 llvm::APInt MagicValueAPInt = IL->getValue();
15607 if (MagicValueAPInt.getActiveBits() <= 64) {
15608 *MagicValue = MagicValueAPInt.getZExtValue();
15609 return true;
15610 } else
15611 return false;
15612 }
15613
15614 case Stmt::BinaryConditionalOperatorClass:
15615 case Stmt::ConditionalOperatorClass: {
15616 const AbstractConditionalOperator *ACO =
15618 bool Result;
15619 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15620 isConstantEvaluated)) {
15621 if (Result)
15622 TypeExpr = ACO->getTrueExpr();
15623 else
15624 TypeExpr = ACO->getFalseExpr();
15625 continue;
15626 }
15627 return false;
15628 }
15629
15630 case Stmt::BinaryOperatorClass: {
15631 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15632 if (BO->getOpcode() == BO_Comma) {
15633 TypeExpr = BO->getRHS();
15634 continue;
15635 }
15636 return false;
15637 }
15638
15639 default:
15640 return false;
15641 }
15642 }
15643}
15644
15645/// Retrieve the C type corresponding to type tag TypeExpr.
15646///
15647/// \param TypeExpr Expression that specifies a type tag.
15648///
15649/// \param MagicValues Registered magic values.
15650///
15651/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15652/// kind.
15653///
15654/// \param TypeInfo Information about the corresponding C type.
15655///
15656/// \param isConstantEvaluated whether the evalaution should be performed in
15657/// constant context.
15658///
15659/// \returns true if the corresponding C type was found.
15661 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15662 const ASTContext &Ctx,
15663 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15664 *MagicValues,
15665 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15666 bool isConstantEvaluated) {
15667 FoundWrongKind = false;
15668
15669 // Variable declaration that has type_tag_for_datatype attribute.
15670 const ValueDecl *VD = nullptr;
15671
15672 uint64_t MagicValue;
15673
15674 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15675 return false;
15676
15677 if (VD) {
15678 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15679 if (I->getArgumentKind() != ArgumentKind) {
15680 FoundWrongKind = true;
15681 return false;
15682 }
15683 TypeInfo.Type = I->getMatchingCType();
15684 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15685 TypeInfo.MustBeNull = I->getMustBeNull();
15686 return true;
15687 }
15688 return false;
15689 }
15690
15691 if (!MagicValues)
15692 return false;
15693
15694 llvm::DenseMap<Sema::TypeTagMagicValue,
15696 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15697 if (I == MagicValues->end())
15698 return false;
15699
15700 TypeInfo = I->second;
15701 return true;
15702}
15703
15705 uint64_t MagicValue, QualType Type,
15706 bool LayoutCompatible,
15707 bool MustBeNull) {
15708 if (!TypeTagForDatatypeMagicValues)
15709 TypeTagForDatatypeMagicValues.reset(
15710 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15711
15712 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15713 (*TypeTagForDatatypeMagicValues)[Magic] =
15714 TypeTagData(Type, LayoutCompatible, MustBeNull);
15715}
15716
15717static bool IsSameCharType(QualType T1, QualType T2) {
15718 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15719 if (!BT1)
15720 return false;
15721
15722 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15723 if (!BT2)
15724 return false;
15725
15726 BuiltinType::Kind T1Kind = BT1->getKind();
15727 BuiltinType::Kind T2Kind = BT2->getKind();
15728
15729 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
15730 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
15731 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15732 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15733}
15734
15735void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15736 const ArrayRef<const Expr *> ExprArgs,
15737 SourceLocation CallSiteLoc) {
15738 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15739 bool IsPointerAttr = Attr->getIsPointer();
15740
15741 // Retrieve the argument representing the 'type_tag'.
15742 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15743 if (TypeTagIdxAST >= ExprArgs.size()) {
15744 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15745 << 0 << Attr->getTypeTagIdx().getSourceIndex();
15746 return;
15747 }
15748 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15749 bool FoundWrongKind;
15750 TypeTagData TypeInfo;
15751 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15752 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15753 TypeInfo, isConstantEvaluatedContext())) {
15754 if (FoundWrongKind)
15755 Diag(TypeTagExpr->getExprLoc(),
15756 diag::warn_type_tag_for_datatype_wrong_kind)
15757 << TypeTagExpr->getSourceRange();
15758 return;
15759 }
15760
15761 // Retrieve the argument representing the 'arg_idx'.
15762 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15763 if (ArgumentIdxAST >= ExprArgs.size()) {
15764 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15765 << 1 << Attr->getArgumentIdx().getSourceIndex();
15766 return;
15767 }
15768 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15769 if (IsPointerAttr) {
15770 // Skip implicit cast of pointer to `void *' (as a function argument).
15771 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15772 if (ICE->getType()->isVoidPointerType() &&
15773 ICE->getCastKind() == CK_BitCast)
15774 ArgumentExpr = ICE->getSubExpr();
15775 }
15776 QualType ArgumentType = ArgumentExpr->getType();
15777
15778 // Passing a `void*' pointer shouldn't trigger a warning.
15779 if (IsPointerAttr && ArgumentType->isVoidPointerType())
15780 return;
15781
15782 if (TypeInfo.MustBeNull) {
15783 // Type tag with matching void type requires a null pointer.
15784 if (!ArgumentExpr->isNullPointerConstant(Context,
15786 Diag(ArgumentExpr->getExprLoc(),
15787 diag::warn_type_safety_null_pointer_required)
15788 << ArgumentKind->getName()
15789 << ArgumentExpr->getSourceRange()
15790 << TypeTagExpr->getSourceRange();
15791 }
15792 return;
15793 }
15794
15795 QualType RequiredType = TypeInfo.Type;
15796 if (IsPointerAttr)
15797 RequiredType = Context.getPointerType(RequiredType);
15798
15799 bool mismatch = false;
15800 if (!TypeInfo.LayoutCompatible) {
15801 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15802
15803 // C++11 [basic.fundamental] p1:
15804 // Plain char, signed char, and unsigned char are three distinct types.
15805 //
15806 // But we treat plain `char' as equivalent to `signed char' or `unsigned
15807 // char' depending on the current char signedness mode.
15808 if (mismatch)
15809 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15810 RequiredType->getPointeeType())) ||
15811 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15812 mismatch = false;
15813 } else
15814 if (IsPointerAttr)
15815 mismatch = !isLayoutCompatible(Context,
15816 ArgumentType->getPointeeType(),
15817 RequiredType->getPointeeType());
15818 else
15819 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15820
15821 if (mismatch)
15822 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15823 << ArgumentType << ArgumentKind
15824 << TypeInfo.LayoutCompatible << RequiredType
15825 << ArgumentExpr->getSourceRange()
15826 << TypeTagExpr->getSourceRange();
15827}
15828
15829void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15830 CharUnits Alignment) {
15831 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
15832 Alignment);
15833}
15834
15836 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
15837 const NamedDecl *ND = m.RD;
15838 if (ND->getName().empty()) {
15839 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15840 ND = TD;
15841 }
15842 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15843 << m.MD << ND << m.E->getSourceRange();
15844 }
15846}
15847
15849 E = E->IgnoreParens();
15850 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
15851 return;
15852 if (isa<UnaryOperator>(E) &&
15853 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15854 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15855 if (isa<MemberExpr>(Op)) {
15856 auto &MisalignedMembersForExpr =
15858 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
15859 if (MA != MisalignedMembersForExpr.end() &&
15860 (T->isDependentType() || T->isIntegerType() ||
15861 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15862 Context.getTypeAlignInChars(
15863 T->getPointeeType()) <= MA->Alignment))))
15864 MisalignedMembersForExpr.erase(MA);
15865 }
15866 }
15867}
15868
15870 Expr *E,
15871 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15872 Action) {
15873 const auto *ME = dyn_cast<MemberExpr>(E);
15874 if (!ME)
15875 return;
15876
15877 // No need to check expressions with an __unaligned-qualified type.
15878 if (E->getType().getQualifiers().hasUnaligned())
15879 return;
15880
15881 // For a chain of MemberExpr like "a.b.c.d" this list
15882 // will keep FieldDecl's like [d, c, b].
15883 SmallVector<FieldDecl *, 4> ReverseMemberChain;
15884 const MemberExpr *TopME = nullptr;
15885 bool AnyIsPacked = false;
15886 do {
15887 QualType BaseType = ME->getBase()->getType();
15888 if (BaseType->isDependentType())
15889 return;
15890 if (ME->isArrow())
15891 BaseType = BaseType->getPointeeType();
15892 auto *RD = BaseType->castAsRecordDecl();
15893 if (RD->isInvalidDecl())
15894 return;
15895
15896 ValueDecl *MD = ME->getMemberDecl();
15897 auto *FD = dyn_cast<FieldDecl>(MD);
15898 // We do not care about non-data members.
15899 if (!FD || FD->isInvalidDecl())
15900 return;
15901
15902 AnyIsPacked =
15903 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15904 ReverseMemberChain.push_back(FD);
15905
15906 TopME = ME;
15907 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15908 } while (ME);
15909 assert(TopME && "We did not compute a topmost MemberExpr!");
15910
15911 // Not the scope of this diagnostic.
15912 if (!AnyIsPacked)
15913 return;
15914
15915 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15916 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15917 // TODO: The innermost base of the member expression may be too complicated.
15918 // For now, just disregard these cases. This is left for future
15919 // improvement.
15920 if (!DRE && !isa<CXXThisExpr>(TopBase))
15921 return;
15922
15923 // Alignment expected by the whole expression.
15924 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15925
15926 // No need to do anything else with this case.
15927 if (ExpectedAlignment.isOne())
15928 return;
15929
15930 // Synthesize offset of the whole access.
15931 CharUnits Offset;
15932 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
15933 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
15934
15935 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15936 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15937 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
15938
15939 // The base expression of the innermost MemberExpr may give
15940 // stronger guarantees than the class containing the member.
15941 if (DRE && !TopME->isArrow()) {
15942 const ValueDecl *VD = DRE->getDecl();
15943 if (!VD->getType()->isReferenceType())
15944 CompleteObjectAlignment =
15945 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15946 }
15947
15948 // Check if the synthesized offset fulfills the alignment.
15949 if (!Offset.isMultipleOf(ExpectedAlignment) ||
15950 // It may fulfill the offset it but the effective alignment may still be
15951 // lower than the expected expression alignment.
15952 CompleteObjectAlignment < ExpectedAlignment) {
15953 // If this happens, we want to determine a sensible culprit of this.
15954 // Intuitively, watching the chain of member expressions from right to
15955 // left, we start with the required alignment (as required by the field
15956 // type) but some packed attribute in that chain has reduced the alignment.
15957 // It may happen that another packed structure increases it again. But if
15958 // we are here such increase has not been enough. So pointing the first
15959 // FieldDecl that either is packed or else its RecordDecl is,
15960 // seems reasonable.
15961 FieldDecl *FD = nullptr;
15962 CharUnits Alignment;
15963 for (FieldDecl *FDI : ReverseMemberChain) {
15964 if (FDI->hasAttr<PackedAttr>() ||
15965 FDI->getParent()->hasAttr<PackedAttr>()) {
15966 FD = FDI;
15967 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
15968 Context.getTypeAlignInChars(
15969 Context.getCanonicalTagType(FD->getParent())));
15970 break;
15971 }
15972 }
15973 assert(FD && "We did not find a packed FieldDecl!");
15974 Action(E, FD->getParent(), FD, Alignment);
15975 }
15976}
15977
15978void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15979 using namespace std::placeholders;
15980
15982 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15983 _2, _3, _4));
15984}
15985
15986// Performs a similar job to Sema::UsualUnaryConversions, but without any
15987// implicit promotion of integral/enumeration types.
15989 // First, convert to an r-value.
15991 if (Res.isInvalid())
15992 return ExprError();
15993
15994 // Promote floating-point types.
15995 return S.UsualUnaryFPConversions(Res.get());
15996}
15997
15999 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16000 if (checkArgCount(TheCall, 1))
16001 return true;
16002
16003 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
16004 if (A.isInvalid())
16005 return true;
16006
16007 TheCall->setArg(0, A.get());
16008 QualType TyA = A.get()->getType();
16009
16010 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
16011 ArgTyRestr, 1))
16012 return true;
16013
16014 TheCall->setType(TyA);
16015 return false;
16016}
16017
16018bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
16019 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16020 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
16021 TheCall->setType(*Res);
16022 return false;
16023 }
16024 return true;
16025}
16026
16028 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
16029 if (!Res)
16030 return true;
16031
16032 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
16033 TheCall->setType(VecTy0->getElementType());
16034 else
16035 TheCall->setType(*Res);
16036
16037 return false;
16038}
16039
16041 SourceLocation Loc) {
16043 R = RHS->getEnumCoercedType(S.Context);
16044 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
16046 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
16047 << LHS->getSourceRange() << RHS->getSourceRange()
16048 << /*Arithmetic Between*/ 0 << L << R;
16049 }
16050 return false;
16051}
16052
16053/// Check if all arguments have the same type. If the types don't match, emit an
16054/// error message and return true. Otherwise return false.
16055///
16056/// For scalars we directly compare their unqualified types. But even if we
16057/// compare unqualified vector types, a difference in qualifiers in the element
16058/// types can make the vector types be considered not equal. For example,
16059/// vector of 4 'const float' values vs vector of 4 'float' values.
16060/// So we compare unqualified types of their elements and number of elements.
16062 ArrayRef<Expr *> Args) {
16063 assert(!Args.empty() && "Should have at least one argument.");
16064
16065 Expr *Arg0 = Args.front();
16066 QualType Ty0 = Arg0->getType();
16067
16068 auto EmitError = [&](Expr *ArgI) {
16069 SemaRef.Diag(Arg0->getBeginLoc(),
16070 diag::err_typecheck_call_different_arg_types)
16071 << Arg0->getType() << ArgI->getType();
16072 };
16073
16074 // Compare scalar types.
16075 if (!Ty0->isVectorType()) {
16076 for (Expr *ArgI : Args.drop_front())
16077 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
16078 EmitError(ArgI);
16079 return true;
16080 }
16081
16082 return false;
16083 }
16084
16085 // Compare vector types.
16086 const auto *Vec0 = Ty0->castAs<VectorType>();
16087 for (Expr *ArgI : Args.drop_front()) {
16088 const auto *VecI = ArgI->getType()->getAs<VectorType>();
16089 if (!VecI ||
16090 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
16091 VecI->getElementType()) ||
16092 Vec0->getNumElements() != VecI->getNumElements()) {
16093 EmitError(ArgI);
16094 return true;
16095 }
16096 }
16097
16098 return false;
16099}
16100
16101std::optional<QualType>
16103 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16104 if (checkArgCount(TheCall, 2))
16105 return std::nullopt;
16106
16108 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
16109 return std::nullopt;
16110
16111 Expr *Args[2];
16112 for (int I = 0; I < 2; ++I) {
16113 ExprResult Converted =
16114 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16115 if (Converted.isInvalid())
16116 return std::nullopt;
16117 Args[I] = Converted.get();
16118 }
16119
16120 SourceLocation LocA = Args[0]->getBeginLoc();
16121 QualType TyA = Args[0]->getType();
16122
16123 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
16124 return std::nullopt;
16125
16126 if (checkBuiltinVectorMathArgTypes(*this, Args))
16127 return std::nullopt;
16128
16129 TheCall->setArg(0, Args[0]);
16130 TheCall->setArg(1, Args[1]);
16131 return TyA;
16132}
16133
16135 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16136 if (checkArgCount(TheCall, 3))
16137 return true;
16138
16139 SourceLocation Loc = TheCall->getExprLoc();
16140 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
16141 TheCall->getArg(1), Loc) ||
16142 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
16143 TheCall->getArg(2), Loc))
16144 return true;
16145
16146 Expr *Args[3];
16147 for (int I = 0; I < 3; ++I) {
16148 ExprResult Converted =
16149 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16150 if (Converted.isInvalid())
16151 return true;
16152 Args[I] = Converted.get();
16153 }
16154
16155 int ArgOrdinal = 1;
16156 for (Expr *Arg : Args) {
16157 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
16158 ArgTyRestr, ArgOrdinal++))
16159 return true;
16160 }
16161
16162 if (checkBuiltinVectorMathArgTypes(*this, Args))
16163 return true;
16164
16165 for (int I = 0; I < 3; ++I)
16166 TheCall->setArg(I, Args[I]);
16167
16168 TheCall->setType(Args[0]->getType());
16169 return false;
16170}
16171
16172bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16173 if (checkArgCount(TheCall, 1))
16174 return true;
16175
16176 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16177 if (A.isInvalid())
16178 return true;
16179
16180 TheCall->setArg(0, A.get());
16181 return false;
16182}
16183
16184bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
16185 if (checkArgCount(TheCall, 1))
16186 return true;
16187
16188 ExprResult Arg = TheCall->getArg(0);
16189 QualType TyArg = Arg.get()->getType();
16190
16191 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
16192 return Diag(TheCall->getArg(0)->getBeginLoc(),
16193 diag::err_builtin_invalid_arg_type)
16194 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
16195
16196 TheCall->setType(TyArg);
16197 return false;
16198}
16199
16200ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
16201 ExprResult CallResult) {
16202 if (checkArgCount(TheCall, 1))
16203 return ExprError();
16204
16205 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16206 if (MatrixArg.isInvalid())
16207 return MatrixArg;
16208 Expr *Matrix = MatrixArg.get();
16209
16210 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16211 if (!MType) {
16212 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16213 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
16214 << Matrix->getType();
16215 return ExprError();
16216 }
16217
16218 // Create returned matrix type by swapping rows and columns of the argument
16219 // matrix type.
16220 QualType ResultType = Context.getConstantMatrixType(
16221 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16222
16223 // Change the return type to the type of the returned matrix.
16224 TheCall->setType(ResultType);
16225
16226 // Update call argument to use the possibly converted matrix argument.
16227 TheCall->setArg(0, Matrix);
16228 return CallResult;
16229}
16230
16231// Get and verify the matrix dimensions.
16232static std::optional<unsigned>
16234 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
16235 if (!Value) {
16236 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16237 << Name;
16238 return {};
16239 }
16240 uint64_t Dim = Value->getZExtValue();
16242 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16244 return {};
16245 }
16246 return Dim;
16247}
16248
16249ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16250 ExprResult CallResult) {
16251 if (!getLangOpts().MatrixTypes) {
16252 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16253 return ExprError();
16254 }
16255
16256 if (checkArgCount(TheCall, 4))
16257 return ExprError();
16258
16259 unsigned PtrArgIdx = 0;
16260 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16261 Expr *RowsExpr = TheCall->getArg(1);
16262 Expr *ColumnsExpr = TheCall->getArg(2);
16263 Expr *StrideExpr = TheCall->getArg(3);
16264
16265 bool ArgError = false;
16266
16267 // Check pointer argument.
16268 {
16270 if (PtrConv.isInvalid())
16271 return PtrConv;
16272 PtrExpr = PtrConv.get();
16273 TheCall->setArg(0, PtrExpr);
16274 if (PtrExpr->isTypeDependent()) {
16275 TheCall->setType(Context.DependentTy);
16276 return TheCall;
16277 }
16278 }
16279
16280 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16281 QualType ElementTy;
16282 if (!PtrTy) {
16283 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16284 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
16285 << PtrExpr->getType();
16286 ArgError = true;
16287 } else {
16288 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16289
16291 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16292 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
16293 << /* no fp */ 0 << PtrExpr->getType();
16294 ArgError = true;
16295 }
16296 }
16297
16298 // Apply default Lvalue conversions and convert the expression to size_t.
16299 auto ApplyArgumentConversions = [this](Expr *E) {
16301 if (Conv.isInvalid())
16302 return Conv;
16303
16304 return tryConvertExprToType(Conv.get(), Context.getSizeType());
16305 };
16306
16307 // Apply conversion to row and column expressions.
16308 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16309 if (!RowsConv.isInvalid()) {
16310 RowsExpr = RowsConv.get();
16311 TheCall->setArg(1, RowsExpr);
16312 } else
16313 RowsExpr = nullptr;
16314
16315 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16316 if (!ColumnsConv.isInvalid()) {
16317 ColumnsExpr = ColumnsConv.get();
16318 TheCall->setArg(2, ColumnsExpr);
16319 } else
16320 ColumnsExpr = nullptr;
16321
16322 // If any part of the result matrix type is still pending, just use
16323 // Context.DependentTy, until all parts are resolved.
16324 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16325 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16326 TheCall->setType(Context.DependentTy);
16327 return CallResult;
16328 }
16329
16330 // Check row and column dimensions.
16331 std::optional<unsigned> MaybeRows;
16332 if (RowsExpr)
16333 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16334
16335 std::optional<unsigned> MaybeColumns;
16336 if (ColumnsExpr)
16337 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16338
16339 // Check stride argument.
16340 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16341 if (StrideConv.isInvalid())
16342 return ExprError();
16343 StrideExpr = StrideConv.get();
16344 TheCall->setArg(3, StrideExpr);
16345
16346 if (MaybeRows) {
16347 if (std::optional<llvm::APSInt> Value =
16348 StrideExpr->getIntegerConstantExpr(Context)) {
16349 uint64_t Stride = Value->getZExtValue();
16350 if (Stride < *MaybeRows) {
16351 Diag(StrideExpr->getBeginLoc(),
16352 diag::err_builtin_matrix_stride_too_small);
16353 ArgError = true;
16354 }
16355 }
16356 }
16357
16358 if (ArgError || !MaybeRows || !MaybeColumns)
16359 return ExprError();
16360
16361 TheCall->setType(
16362 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16363 return CallResult;
16364}
16365
16366ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16367 ExprResult CallResult) {
16368 if (checkArgCount(TheCall, 3))
16369 return ExprError();
16370
16371 unsigned PtrArgIdx = 1;
16372 Expr *MatrixExpr = TheCall->getArg(0);
16373 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16374 Expr *StrideExpr = TheCall->getArg(2);
16375
16376 bool ArgError = false;
16377
16378 {
16379 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16380 if (MatrixConv.isInvalid())
16381 return MatrixConv;
16382 MatrixExpr = MatrixConv.get();
16383 TheCall->setArg(0, MatrixExpr);
16384 }
16385 if (MatrixExpr->isTypeDependent()) {
16386 TheCall->setType(Context.DependentTy);
16387 return TheCall;
16388 }
16389
16390 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16391 if (!MatrixTy) {
16392 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16393 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
16394 ArgError = true;
16395 }
16396
16397 {
16399 if (PtrConv.isInvalid())
16400 return PtrConv;
16401 PtrExpr = PtrConv.get();
16402 TheCall->setArg(1, PtrExpr);
16403 if (PtrExpr->isTypeDependent()) {
16404 TheCall->setType(Context.DependentTy);
16405 return TheCall;
16406 }
16407 }
16408
16409 // Check pointer argument.
16410 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16411 if (!PtrTy) {
16412 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16413 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
16414 << PtrExpr->getType();
16415 ArgError = true;
16416 } else {
16417 QualType ElementTy = PtrTy->getPointeeType();
16418 if (ElementTy.isConstQualified()) {
16419 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16420 ArgError = true;
16421 }
16422 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16423 if (MatrixTy &&
16424 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16425 Diag(PtrExpr->getBeginLoc(),
16426 diag::err_builtin_matrix_pointer_arg_mismatch)
16427 << ElementTy << MatrixTy->getElementType();
16428 ArgError = true;
16429 }
16430 }
16431
16432 // Apply default Lvalue conversions and convert the stride expression to
16433 // size_t.
16434 {
16435 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16436 if (StrideConv.isInvalid())
16437 return StrideConv;
16438
16439 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16440 if (StrideConv.isInvalid())
16441 return StrideConv;
16442 StrideExpr = StrideConv.get();
16443 TheCall->setArg(2, StrideExpr);
16444 }
16445
16446 // Check stride argument.
16447 if (MatrixTy) {
16448 if (std::optional<llvm::APSInt> Value =
16449 StrideExpr->getIntegerConstantExpr(Context)) {
16450 uint64_t Stride = Value->getZExtValue();
16451 if (Stride < MatrixTy->getNumRows()) {
16452 Diag(StrideExpr->getBeginLoc(),
16453 diag::err_builtin_matrix_stride_too_small);
16454 ArgError = true;
16455 }
16456 }
16457 }
16458
16459 if (ArgError)
16460 return ExprError();
16461
16462 return CallResult;
16463}
16464
16466 const NamedDecl *Callee) {
16467 // This warning does not make sense in code that has no runtime behavior.
16469 return;
16470
16471 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
16472
16473 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
16474 return;
16475
16476 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16477 // all TCBs the callee is a part of.
16478 llvm::StringSet<> CalleeTCBs;
16479 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
16480 CalleeTCBs.insert(A->getTCBName());
16481 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
16482 CalleeTCBs.insert(A->getTCBName());
16483
16484 // Go through the TCBs the caller is a part of and emit warnings if Caller
16485 // is in a TCB that the Callee is not.
16486 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
16487 StringRef CallerTCB = A->getTCBName();
16488 if (CalleeTCBs.count(CallerTCB) == 0) {
16489 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
16490 << Callee << CallerTCB;
16491 }
16492 }
16493}
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 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 CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg, unsigned Pos, bool AllowConst, bool AllowAS)
static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn)
Check that the user is calling the appropriate va_start builtin for the target and calling convention...
static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call, PointerAuthOpKind OpKind, bool RequireConstant)
static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S)
static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr, int ArgOrdinal)
static bool GetMatchingCType(const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, const ASTContext &Ctx, const llvm::DenseMap< Sema::TypeTagMagicValue, Sema::TypeTagData > *MagicValues, bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, bool isConstantEvaluated)
Retrieve the C type corresponding to type tag TypeExpr.
static QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall)
MathCheck
static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall)
static bool isNonNullType(QualType type)
Determine whether the given type has a non-null nullability annotation.
static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A, Sema::FormatArgumentPassingKind B)
static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall)
Check that the first argument to __builtin_annotation is an integer and the second argument is a non-...
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx)
This helper function takes a pointer expression and returns the alignment of a VarDecl and a constant...
static bool IsShiftedByte(llvm::APSInt Value)
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, unsigned AbsFunctionKind)
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
checkBuiltinArgument - Given a call to a builtin function, perform normal type-checking on the given ...
static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E)
Analyze the operands of the given comparison.
static 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:220
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.
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:772
Builtin::Context & BuiltinInfo
Definition ASTContext.h:774
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:825
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:891
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:3722
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3736
QualType getElementType() const
Definition TypeBase.h:3734
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:3542
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:5143
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5183
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:3760
QualType desugar() const
Definition TypeBase.h:3861
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3816
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:4407
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition TypeBase.h:4402
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:5326
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:809
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:951
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3423
Represents an enum.
Definition Decl.h:4007
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4230
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4171
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:4267
Represents a member of a struct/union/class.
Definition Decl.h:3160
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3263
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4740
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3276
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
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:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
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:103
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:2000
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4541
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3750
param_iterator param_end()
Definition Decl.h:2787
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3853
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
param_iterator param_begin()
Definition Decl.h:2786
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:4317
bool isStatic() const
Definition Decl.h:2929
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4132
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4118
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3814
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5266
unsigned getNumParams() const
Definition TypeBase.h:5544
QualType getParamType(unsigned i) const
Definition TypeBase.h:5546
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5670
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5555
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5665
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5551
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4462
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4771
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4767
QualType getReturnType() const
Definition TypeBase.h:4802
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:4358
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:3653
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1930
Represent a C++ namespace.
Definition Decl.h:592
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:1790
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 isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8371
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:8287
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8413
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8327
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:8339
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8381
void removeLocalVolatile()
Definition TypeBase.h:8403
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1179
void removeLocalConst()
Definition TypeBase.h:8395
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8360
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8408
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1670
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8333
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:4312
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4398
field_range fields() const
Definition Decl.h:4515
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4390
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:12960
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 pushCodeSynthesisContext(CodeSynthesisContext Ctx)
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...
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:15260
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:13813
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:3832
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3812
bool isUnion() const
Definition Decl.h:3922
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:6177
A container of type source information.
Definition TypeBase.h:8258
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:8269
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isBlockPointerType() const
Definition TypeBase.h:8544
bool isVoidType() const
Definition TypeBase.h:8880
bool isBooleanType() const
Definition TypeBase.h:9010
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:9060
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:9040
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:8623
bool isCharType() const
Definition Type.cpp:2132
bool isFunctionPointerType() const
Definition TypeBase.h:8591
bool isPointerType() const
Definition TypeBase.h:8524
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8924
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9167
bool isReferenceType() const
Definition TypeBase.h:8548
bool isEnumeralType() const
Definition TypeBase.h:8655
bool isScalarType() const
Definition TypeBase.h:8982
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:8635
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:8667
bool isExtVectorBoolType() const
Definition TypeBase.h:8671
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:8789
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8849
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8647
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:8706
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:8697
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9153
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9016
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:8520
bool isObjCObjectPointerType() const
Definition TypeBase.h:8693
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:8663
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:8532
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:9100
bool isNullPtrType() const
Definition TypeBase.h:8917
bool isRecordType() const
Definition TypeBase.h:8651
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:3562
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:712
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5500
Represents a variable declaration or definition.
Definition Decl.h:926
Represents a GCC generic vector type.
Definition TypeBase.h:4175
unsigned getNumElements() const
Definition TypeBase.h:4190
QualType getElementType() const
Definition TypeBase.h:4189
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:2501
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:4136
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5886
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5879
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1746
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:5351
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:13100
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13126
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13116
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13075
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