clang 24.0.0git
SemaChecking.cpp
Go to the documentation of this file.
1//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements extra semantic analysis beyond what is enforced
10// by the C type system.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CheckExprLifetime.h"
15#include "clang/AST/APValue.h"
18#include "clang/AST/Attr.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclObjC.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprObjC.h"
32#include "clang/AST/NSAPI.h"
36#include "clang/AST/Stmt.h"
39#include "clang/AST/Type.h"
40#include "clang/AST/TypeBase.h"
41#include "clang/AST/TypeLoc.h"
48#include "clang/Basic/LLVM.h"
58#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
60#include "clang/Sema/Lookup.h"
62#include "clang/Sema/Scope.h"
64#include "clang/Sema/Sema.h"
66#include "clang/Sema/SemaARM.h"
67#include "clang/Sema/SemaBPF.h"
69#include "clang/Sema/SemaHLSL.h"
72#include "clang/Sema/SemaMIPS.h"
74#include "clang/Sema/SemaObjC.h"
76#include "clang/Sema/SemaPPC.h"
79#include "clang/Sema/SemaSYCL.h"
81#include "clang/Sema/SemaWasm.h"
82#include "clang/Sema/SemaX86.h"
83#include "llvm/ADT/APFloat.h"
84#include "llvm/ADT/APInt.h"
85#include "llvm/ADT/APSInt.h"
86#include "llvm/ADT/ArrayRef.h"
87#include "llvm/ADT/DenseMap.h"
88#include "llvm/ADT/FoldingSet.h"
89#include "llvm/ADT/STLExtras.h"
90#include "llvm/ADT/STLForwardCompat.h"
91#include "llvm/ADT/SmallBitVector.h"
92#include "llvm/ADT/SmallPtrSet.h"
93#include "llvm/ADT/SmallString.h"
94#include "llvm/ADT/SmallVector.h"
95#include "llvm/ADT/StringExtras.h"
96#include "llvm/ADT/StringRef.h"
97#include "llvm/ADT/StringSet.h"
98#include "llvm/ADT/StringSwitch.h"
99#include "llvm/Support/AtomicOrdering.h"
100#include "llvm/Support/Compiler.h"
101#include "llvm/Support/ConvertUTF.h"
102#include "llvm/Support/ErrorHandling.h"
103#include "llvm/Support/Format.h"
104#include "llvm/Support/Locale.h"
105#include "llvm/Support/MathExtras.h"
106#include "llvm/Support/SaveAndRestore.h"
107#include "llvm/Support/raw_ostream.h"
108#include "llvm/TargetParser/RISCVTargetParser.h"
109#include "llvm/TargetParser/Triple.h"
110#include <algorithm>
111#include <cassert>
112#include <cctype>
113#include <cstddef>
114#include <cstdint>
115#include <functional>
116#include <limits>
117#include <optional>
118#include <string>
119#include <tuple>
120#include <utility>
121
122using namespace clang;
123using namespace sema;
124
126 unsigned ByteNo) const {
127 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
128 Context.getTargetInfo());
129}
130
131static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
133 return (A << 8) | B;
134}
135
136bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
137 unsigned ArgCount = Call->getNumArgs();
138 if (ArgCount >= MinArgCount)
139 return false;
140
141 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
142 << 0 /*function call*/ << MinArgCount << ArgCount
143 << /*is non object*/ 0 << Call->getSourceRange();
144}
145
146bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
147 unsigned ArgCount = Call->getNumArgs();
148 if (ArgCount <= MaxArgCount)
149 return false;
150 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)
151 << 0 /*function call*/ << MaxArgCount << ArgCount
152 << /*is non object*/ 0 << Call->getSourceRange();
153}
154
155bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
156 unsigned MaxArgCount) {
157 return checkArgCountAtLeast(Call, MinArgCount) ||
158 checkArgCountAtMost(Call, MaxArgCount);
159}
160
161bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
162 unsigned ArgCount = Call->getNumArgs();
163 if (ArgCount == DesiredArgCount)
164 return false;
165
166 if (checkArgCountAtLeast(Call, DesiredArgCount))
167 return true;
168 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
169
170 // Highlight all the excess arguments.
171 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
172 Call->getArg(ArgCount - 1)->getEndLoc());
173
174 return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
175 << 0 /*function call*/ << DesiredArgCount << ArgCount
176 << /*is non object*/ 0 << Range;
177}
178
180 bool HasError = false;
181
182 for (const Expr *Arg : Call->arguments()) {
183 if (Arg->isValueDependent())
184 continue;
185
186 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
187 int DiagMsgKind = -1;
188 // Arguments must be pointers to constant strings and cannot use '$'.
189 if (!ArgString.has_value())
190 DiagMsgKind = 0;
191 else if (ArgString->find('$') != std::string::npos)
192 DiagMsgKind = 1;
193
194 if (DiagMsgKind >= 0) {
195 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
196 << DiagMsgKind << Arg->getSourceRange();
197 HasError = true;
198 }
199 }
200
201 return !HasError;
202}
203
205 if (Value->isTypeDependent())
206 return false;
207
208 InitializedEntity Entity =
212 if (Result.isInvalid())
213 return true;
214 Value = Result.get();
215 return false;
216}
217
218/// Check that the first argument to __builtin_annotation is an integer
219/// and the second argument is a non-wide string literal.
220static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
221 if (S.checkArgCount(TheCall, 2))
222 return true;
223
224 // First argument should be an integer.
225 Expr *ValArg = TheCall->getArg(0);
226 QualType Ty = ValArg->getType();
227 if (!Ty->isIntegerType()) {
228 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
229 << ValArg->getSourceRange();
230 return true;
231 }
232
233 // Second argument should be a constant string.
234 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
235 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
236 if (!Literal || !Literal->isOrdinary()) {
237 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
238 << StrArg->getSourceRange();
239 return true;
240 }
241
242 TheCall->setType(Ty);
243 return false;
244}
245
246static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
247 // We need at least one argument.
248 if (TheCall->getNumArgs() < 1) {
249 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
250 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
251 << TheCall->getCallee()->getSourceRange();
252 return true;
253 }
254
255 // All arguments should be wide string literals.
256 for (Expr *Arg : TheCall->arguments()) {
257 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
258 if (!Literal || !Literal->isWide()) {
259 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
260 << Arg->getSourceRange();
261 return true;
262 }
263 }
264
265 return false;
266}
267
268/// Check that the argument to __builtin_addressof is a glvalue, and set the
269/// result type to the corresponding pointer type.
270static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
271 if (S.checkArgCount(TheCall, 1))
272 return true;
273
274 ExprResult Arg(TheCall->getArg(0));
275
276 // Unlike '&', nothing resolves the overload set later, so resolve it now.
277 // FIXME: Resolve the overload set from the target type, like '&' does.
278 if (Arg.get()->getType() == S.Context.OverloadTy) {
279 Arg = S.CheckPlaceholderExpr(Arg.get());
280 if (Arg.isInvalid())
281 return true;
282 }
283
284 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
285 if (ResultType.isNull())
286 return true;
287
288 TheCall->setArg(0, Arg.get());
289 TheCall->setType(ResultType);
290 return false;
291}
292
293/// Check that the argument to __builtin_function_start is a function.
294static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
295 if (S.checkArgCount(TheCall, 1))
296 return true;
297
298 if (TheCall->getArg(0)->containsErrors())
299 return true;
300
302 if (Arg.isInvalid())
303 return true;
304
305 TheCall->setArg(0, Arg.get());
306 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
308
309 if (!FD) {
310 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
311 << TheCall->getSourceRange();
312 return true;
313 }
314
315 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
316 TheCall->getBeginLoc());
317}
318
319/// Check the number of arguments and set the result type to
320/// the argument type.
321static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
322 if (S.checkArgCount(TheCall, 1))
323 return true;
324
325 TheCall->setType(TheCall->getArg(0)->getType());
326 return false;
327}
328
329/// Check that the value argument for __builtin_is_aligned(value, alignment) and
330/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
331/// type (but not a function pointer) and that the alignment is a power-of-two.
332static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
333 if (S.checkArgCount(TheCall, 2))
334 return true;
335
336 clang::Expr *Source = TheCall->getArg(0);
337 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
338
339 auto IsValidIntegerType = [](QualType Ty) {
340 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
341 };
342 QualType SrcTy = Source->getType();
343 // We should also be able to use it with arrays (but not functions!).
344 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
345 SrcTy = S.Context.getDecayedType(SrcTy);
346 }
347 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
348 SrcTy->isFunctionPointerType()) {
349 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
350 << SrcTy;
351 if (SrcTy->isFloatingType())
352 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_type);
353 else if (SrcTy->isMemberPointerType())
354 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_member_pointer);
355 else if (SrcTy->isFunctionPointerType())
356 S.Diag(Source->getExprLoc(),
357 diag::note_alignment_invalid_function_pointer);
358 return true;
359 }
360
361 clang::Expr *AlignOp = TheCall->getArg(1);
362 if (!IsValidIntegerType(AlignOp->getType())) {
363 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
364 << AlignOp->getType();
365 return true;
366 }
367 Expr::EvalResult AlignResult;
368 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
369 // We can't check validity of alignment if it is value dependent.
370 if (!AlignOp->isValueDependent() &&
371 AlignOp->EvaluateAsInt(AlignResult, S.Context,
373 llvm::APSInt AlignValue = AlignResult.Val.getInt();
374 llvm::APSInt MaxValue(
375 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
376 if (AlignValue < 1) {
377 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
378 return true;
379 }
380 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
381 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
382 << toString(MaxValue, 10);
383 return true;
384 }
385 if (!AlignValue.isPowerOf2()) {
386 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
387 return true;
388 }
389 if (AlignValue == 1) {
390 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
391 << IsBooleanAlignBuiltin;
392 }
393 }
394
397 SourceLocation(), Source);
398 if (SrcArg.isInvalid())
399 return true;
400 TheCall->setArg(0, SrcArg.get());
401 ExprResult AlignArg =
403 S.Context, AlignOp->getType(), false),
404 SourceLocation(), AlignOp);
405 if (AlignArg.isInvalid())
406 return true;
407 TheCall->setArg(1, AlignArg.get());
408 // For align_up/align_down, the return type is the same as the (potentially
409 // decayed) argument type including qualifiers. For is_aligned(), the result
410 // is always bool.
411 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
412 return false;
413}
414
415static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
416 if (S.checkArgCount(TheCall, 3))
417 return true;
418
419 std::pair<unsigned, const char *> Builtins[] = {
420 { Builtin::BI__builtin_add_overflow, "ckd_add" },
421 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
422 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
423 };
424
425 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
426 const char *> &P) {
427 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
429 S.getSourceManager(), S.getLangOpts()) == P.second;
430 });
431
432 auto ValidCkdIntType = [](QualType QT) {
433 // A valid checked integer type is an integer type other than a plain char,
434 // bool, a bit-precise type, or an enumeration type.
435 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
436 return (BT->getKind() >= BuiltinType::Short &&
437 BT->getKind() <= BuiltinType::Int128) || (
438 BT->getKind() >= BuiltinType::UShort &&
439 BT->getKind() <= BuiltinType::UInt128) ||
440 BT->getKind() == BuiltinType::UChar ||
441 BT->getKind() == BuiltinType::SChar;
442 return false;
443 };
444
445 // First two arguments should be integers.
446 for (unsigned I = 0; I < 2; ++I) {
448 if (Arg.isInvalid()) return true;
449 TheCall->setArg(I, Arg.get());
450
451 QualType Ty = Arg.get()->getType();
452 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
453 if (!IsValid) {
454 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
455 << CkdOperation << Ty << Arg.get()->getSourceRange();
456 return true;
457 }
458 }
459
460 // Third argument should be a pointer to a non-const integer.
461 // IRGen correctly handles volatile, restrict, and address spaces, and
462 // the other qualifiers aren't possible.
463 {
465 if (Arg.isInvalid()) return true;
466 TheCall->setArg(2, Arg.get());
467
468 QualType Ty = Arg.get()->getType();
469 const auto *PtrTy = Ty->getAs<PointerType>();
470 if (!PtrTy ||
471 !PtrTy->getPointeeType()->isIntegerType() ||
472 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
473 PtrTy->getPointeeType().isConstQualified()) {
474 S.Diag(Arg.get()->getBeginLoc(),
475 diag::err_overflow_builtin_must_be_ptr_int)
476 << CkdOperation << Ty << Arg.get()->getSourceRange();
477 return true;
478 }
479 }
480
481 // Disallow signed bit-precise integer args larger than 128 bits to mul
482 // function until we improve backend support.
483 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
484 for (unsigned I = 0; I < 3; ++I) {
485 const auto Arg = TheCall->getArg(I);
486 // Third argument will be a pointer.
487 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
488 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
489 S.getASTContext().getIntWidth(Ty) > 128)
490 return S.Diag(Arg->getBeginLoc(),
491 diag::err_overflow_builtin_bit_int_max_size)
492 << 128;
493 }
494 }
495
496 return false;
497}
498
499namespace {
500struct BuiltinDumpStructGenerator {
501 Sema &S;
502 CallExpr *TheCall;
503 SourceLocation Loc = TheCall->getBeginLoc();
504 SmallVector<Expr *, 32> Actions;
505 DiagnosticErrorTrap ErrorTracker;
506 PrintingPolicy Policy;
507
508 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
509 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
510 Policy(S.Context.getPrintingPolicy()) {
511 Policy.AnonymousTagNameStyle =
512 llvm::to_underlying(PrintingPolicy::AnonymousTagMode::Plain);
513 }
514
515 Expr *makeOpaqueValueExpr(Expr *Inner) {
516 auto *OVE = new (S.Context)
517 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
518 Inner->getObjectKind(), Inner);
519 Actions.push_back(OVE);
520 return OVE;
521 }
522
523 Expr *getStringLiteral(llvm::StringRef Str) {
525 // Wrap the literal in parentheses to attach a source location.
526 return new (S.Context) ParenExpr(Loc, Loc, Lit);
527 }
528
529 bool callPrintFunction(llvm::StringRef Format,
530 llvm::ArrayRef<Expr *> Exprs = {}) {
531 SmallVector<Expr *, 8> Args;
532 assert(TheCall->getNumArgs() >= 2);
533 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
534 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
535 Args.push_back(getStringLiteral(Format));
536 llvm::append_range(Args, Exprs);
537
538 // Register a note to explain why we're performing the call.
539 Sema::CodeSynthesisContext Ctx;
541 Ctx.PointOfInstantiation = Loc;
542 Ctx.CallArgs = Args.data();
543 Ctx.NumCallArgs = Args.size();
545
546 ExprResult RealCall =
547 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
548 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
549
551 if (!RealCall.isInvalid())
552 Actions.push_back(RealCall.get());
553 // Bail out if we've hit any unrecoverable errors, even if we managed
554 // to build the call.
555 return RealCall.isInvalid() || ErrorTracker.hasUnrecoverableErrorOccurred();
556 }
557
558 Expr *getIndentString(unsigned Depth) {
559 if (!Depth)
560 return nullptr;
561
562 llvm::SmallString<32> Indent;
563 Indent.resize(Depth * Policy.Indentation, ' ');
564 return getStringLiteral(Indent);
565 }
566
567 Expr *getTypeString(QualType T) {
568 return getStringLiteral(T.getAsString(Policy));
569 }
570
571 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
572 llvm::raw_svector_ostream OS(Str);
573
574 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
575 // than trying to print a single character.
576 if (auto *BT = T->getAs<BuiltinType>()) {
577 switch (BT->getKind()) {
578 case BuiltinType::Bool:
579 OS << "%d";
580 return true;
581 case BuiltinType::Char_U:
582 case BuiltinType::UChar:
583 OS << "%hhu";
584 return true;
585 case BuiltinType::Char_S:
586 case BuiltinType::SChar:
587 OS << "%hhd";
588 return true;
589 default:
590 break;
591 }
592 }
593
594 analyze_printf::PrintfSpecifier Specifier;
595 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
596 // We were able to guess how to format this.
597 if (Specifier.getConversionSpecifier().getKind() ==
598 analyze_printf::PrintfConversionSpecifier::sArg) {
599 // Wrap double-quotes around a '%s' specifier and limit its maximum
600 // length. Ideally we'd also somehow escape special characters in the
601 // contents but printf doesn't support that.
602 // FIXME: '%s' formatting is not safe in general.
603 OS << '"';
604 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
605 Specifier.toString(OS);
606 OS << '"';
607 // FIXME: It would be nice to include a '...' if the string doesn't fit
608 // in the length limit.
609 } else {
610 Specifier.toString(OS);
611 }
612 return true;
613 }
614
615 if (T->isPointerType()) {
616 // Format all pointers with '%p'.
617 OS << "%p";
618 return true;
619 }
620
621 return false;
622 }
623
624 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
625 Expr *IndentLit = getIndentString(Depth);
626 Expr *TypeLit = getTypeString(S.Context.getCanonicalTagType(RD));
627 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
628 : callPrintFunction("%s", {TypeLit}))
629 return true;
630
631 return dumpRecordValue(RD, E, IndentLit, Depth);
632 }
633
634 // Dump a record value. E should be a pointer or lvalue referring to an RD.
635 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
636 unsigned Depth) {
637 // FIXME: Decide what to do if RD is a union. At least we should probably
638 // turn off printing `const char*` members with `%s`, because that is very
639 // likely to crash if that's not the active member. Whatever we decide, we
640 // should document it.
641
642 // Build an OpaqueValueExpr so we can refer to E more than once without
643 // triggering re-evaluation.
644 Expr *RecordArg = makeOpaqueValueExpr(E);
645 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
646
647 if (callPrintFunction(" {\n"))
648 return true;
649
650 // Dump each base class, regardless of whether they're aggregates.
651 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
652 for (const auto &Base : CXXRD->bases()) {
653 QualType BaseType =
654 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
655 : S.Context.getLValueReferenceType(Base.getType());
657 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
658 RecordArg);
659 if (BasePtr.isInvalid() ||
660 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
661 Depth + 1))
662 return true;
663 }
664 }
665
666 Expr *FieldIndentArg = getIndentString(Depth + 1);
667
668 // Dump each field.
669 for (auto *D : RD->decls()) {
670 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
671 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
672 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
673 continue;
674
675 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
676 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
677 getTypeString(FD->getType()),
678 getStringLiteral(FD->getName())};
679
680 if (FD->isBitField()) {
681 Format += ": %zu ";
682 QualType SizeT = S.Context.getSizeType();
683 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
684 FD->getBitWidthValue());
685 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
686 }
687
688 Format += "=";
689
692 CXXScopeSpec(), Loc, IFD,
693 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
695 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
697 DeclarationNameInfo(FD->getDeclName(), Loc));
698 if (Field.isInvalid())
699 return true;
700
701 auto *InnerRD = FD->getType()->getAsRecordDecl();
702 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
703 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
704 // Recursively print the values of members of aggregate record type.
705 if (callPrintFunction(Format, Args) ||
706 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
707 return true;
708 } else {
709 Format += " ";
710 if (appendFormatSpecifier(FD->getType(), Format)) {
711 // We know how to print this field.
712 Args.push_back(Field.get());
713 } else {
714 // We don't know how to print this field. Print out its address
715 // with a format specifier that a smart tool will be able to
716 // recognize and treat specially.
717 Format += "*%p";
718 ExprResult FieldAddr =
719 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
720 if (FieldAddr.isInvalid())
721 return true;
722 Args.push_back(FieldAddr.get());
723 }
724 Format += "\n";
725 if (callPrintFunction(Format, Args))
726 return true;
727 }
728 }
729
730 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
731 : callPrintFunction("}\n");
732 }
733
734 Expr *buildWrapper() {
735 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
737 TheCall->setType(Wrapper->getType());
738 TheCall->setValueKind(Wrapper->getValueKind());
739 return Wrapper;
740 }
741};
742} // namespace
743
745 if (S.checkArgCountAtLeast(TheCall, 2))
746 return ExprError();
747
748 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
749 if (PtrArgResult.isInvalid())
750 return ExprError();
751 TheCall->setArg(0, PtrArgResult.get());
752
753 // First argument should be a pointer to a struct.
754 QualType PtrArgType = PtrArgResult.get()->getType();
755 if (!PtrArgType->isPointerType() ||
756 !PtrArgType->getPointeeType()->isRecordType()) {
757 S.Diag(PtrArgResult.get()->getBeginLoc(),
758 diag::err_expected_struct_pointer_argument)
759 << 1 << TheCall->getDirectCallee() << PtrArgType;
760 return ExprError();
761 }
762 QualType Pointee = PtrArgType->getPointeeType();
763 const RecordDecl *RD = Pointee->getAsRecordDecl();
764 // Try to instantiate the class template as appropriate; otherwise, access to
765 // its data() may lead to a crash.
766 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
767 diag::err_incomplete_type))
768 return ExprError();
769 // Second argument is a callable, but we can't fully validate it until we try
770 // calling it.
771 QualType FnArgType = TheCall->getArg(1)->getType();
772 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
773 !FnArgType->isBlockPointerType() &&
774 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
775 auto *BT = FnArgType->getAs<BuiltinType>();
776 switch (BT ? BT->getKind() : BuiltinType::Void) {
777 case BuiltinType::Dependent:
778 case BuiltinType::Overload:
779 case BuiltinType::BoundMember:
780 case BuiltinType::PseudoObject:
781 case BuiltinType::UnknownAny:
782 case BuiltinType::BuiltinFn:
783 // This might be a callable.
784 break;
785
786 default:
787 S.Diag(TheCall->getArg(1)->getBeginLoc(),
788 diag::err_expected_callable_argument)
789 << 2 << TheCall->getDirectCallee() << FnArgType;
790 return ExprError();
791 }
792 }
793
794 BuiltinDumpStructGenerator Generator(S, TheCall);
795
796 // Wrap parentheses around the given pointer. This is not necessary for
797 // correct code generation, but it means that when we pretty-print the call
798 // arguments in our diagnostics we will produce '(&s)->n' instead of the
799 // incorrect '&s->n'.
800 Expr *PtrArg = PtrArgResult.get();
801 PtrArg = new (S.Context)
802 ParenExpr(PtrArg->getBeginLoc(),
803 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
804 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
805 return ExprError();
806
807 return Generator.buildWrapper();
808}
809
810static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
811 if (S.checkArgCount(BuiltinCall, 2))
812 return true;
813
814 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
815 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
816 Expr *Call = BuiltinCall->getArg(0);
817 Expr *Chain = BuiltinCall->getArg(1);
818
819 if (Call->getStmtClass() != Stmt::CallExprClass) {
820 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
821 << Call->getSourceRange();
822 return true;
823 }
824
825 auto CE = cast<CallExpr>(Call);
826 if (CE->getCallee()->getType()->isBlockPointerType()) {
827 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
828 << Call->getSourceRange();
829 return true;
830 }
831
832 const Decl *TargetDecl = CE->getCalleeDecl();
833 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
834 if (FD->getBuiltinID()) {
835 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
836 << Call->getSourceRange();
837 return true;
838 }
839
840 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
841 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
842 << Call->getSourceRange();
843 return true;
844 }
845
846 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
847 if (ChainResult.isInvalid())
848 return true;
849 if (!ChainResult.get()->getType()->isPointerType()) {
850 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
851 << Chain->getSourceRange();
852 return true;
853 }
854
855 QualType ReturnTy = CE->getCallReturnType(S.Context);
856 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
857 QualType BuiltinTy = S.Context.getFunctionType(
858 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
859 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
860
861 Builtin =
862 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
863
864 BuiltinCall->setType(CE->getType());
865 BuiltinCall->setValueKind(CE->getValueKind());
866 BuiltinCall->setObjectKind(CE->getObjectKind());
867 BuiltinCall->setCallee(Builtin);
868 BuiltinCall->setArg(1, ChainResult.get());
869
870 return false;
871}
872
873namespace {
874
875class ScanfDiagnosticFormatHandler
877 // Accepts the argument index (relative to the first destination index) of the
878 // argument whose size we want.
879 using ComputeSizeFunction =
880 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
881
882 // Accepts the argument index (relative to the first destination index), the
883 // destination size, and the source size).
884 using DiagnoseFunction =
885 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
886
887 ComputeSizeFunction ComputeSizeArgument;
888 DiagnoseFunction Diagnose;
889
890public:
891 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
892 DiagnoseFunction Diagnose)
893 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
894
895 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
896 const char *StartSpecifier,
897 unsigned specifierLen) override {
898 if (!FS.consumesDataArgument())
899 return true;
900
901 unsigned NulByte = 0;
902 switch ((FS.getConversionSpecifier().getKind())) {
903 default:
904 return true;
907 NulByte = 1;
908 break;
910 break;
911 }
912
913 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
914 if (FW.getHowSpecified() !=
915 analyze_format_string::OptionalAmount::HowSpecified::Constant)
916 return true;
917
918 unsigned SourceSize = FW.getConstantAmount() + NulByte;
919
920 std::optional<llvm::APSInt> DestSizeAPS =
921 ComputeSizeArgument(FS.getArgIndex());
922 if (!DestSizeAPS)
923 return true;
924
925 unsigned DestSize = DestSizeAPS->getZExtValue();
926
927 if (DestSize < SourceSize)
928 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
929
930 return true;
931 }
932};
933
934class EstimateSizeFormatHandler
936 size_t Size;
937 /// Whether the format string contains Linux kernel's format specifier
938 /// extension.
939 bool IsKernelCompatible = true;
940
941public:
942 EstimateSizeFormatHandler(StringRef Format)
943 : Size(std::min(Format.find(0), Format.size()) +
944 1 /* null byte always written by sprintf */) {}
945
946 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
947 const char *, unsigned SpecifierLen,
948 const TargetInfo &) override {
949
950 const size_t FieldWidth = computeFieldWidth(FS);
951 const size_t Precision = computePrecision(FS);
952
953 // The actual format.
954 switch (FS.getConversionSpecifier().getKind()) {
955 // Just a char.
958 Size += std::max(FieldWidth, (size_t)1);
959 break;
960 // Just an integer.
970 Size += std::max(FieldWidth, Precision);
971 break;
972
973 // %g style conversion switches between %f or %e style dynamically.
974 // %g removes trailing zeros, and does not print decimal point if there are
975 // no digits that follow it. Thus %g can print a single digit.
976 // FIXME: If it is alternative form:
977 // For g and G conversions, trailing zeros are not removed from the result.
980 Size += 1;
981 break;
982
983 // Floating point number in the form '[+]ddd.ddd'.
986 Size += std::max(FieldWidth, 1 /* integer part */ +
987 (Precision ? 1 + Precision
988 : 0) /* period + decimal */);
989 break;
990
991 // Floating point number in the form '[-]d.ddde[+-]dd'.
994 Size +=
995 std::max(FieldWidth,
996 1 /* integer part */ +
997 (Precision ? 1 + Precision : 0) /* period + decimal */ +
998 1 /* e or E letter */ + 2 /* exponent */);
999 break;
1000
1001 // Floating point number in the form '[-]0xh.hhhhp±dd'.
1004 Size +=
1005 std::max(FieldWidth,
1006 2 /* 0x */ + 1 /* integer part */ +
1007 (Precision ? 1 + Precision : 0) /* period + decimal */ +
1008 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
1009 break;
1010
1011 // Just a string.
1014 Size += FieldWidth;
1015 break;
1016
1017 // Just a pointer in the form '0xddd'.
1019 // Linux kernel has its own extension for `%p` specifier.
1020 // Kernel Document:
1021 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1022 IsKernelCompatible = false;
1023 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1024 break;
1025
1026 // A plain percent.
1028 Size += 1;
1029 break;
1030
1031 default:
1032 break;
1033 }
1034
1035 // If field width is specified, the sign/space is already accounted for
1036 // within the field width, so no additional size is needed.
1037 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1038 Size += 1;
1039
1040 if (FS.hasAlternativeForm()) {
1041 switch (FS.getConversionSpecifier().getKind()) {
1042 // For o conversion, it increases the precision, if and only if necessary,
1043 // to force the first digit of the result to be a zero
1044 // (if the value and precision are both 0, a single 0 is printed)
1046 // For b conversion, a nonzero result has 0b prefixed to it.
1048 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1049 // it.
1052 // Note: even when the prefix is added, if
1053 // (prefix_width <= FieldWidth - formatted_length) holds,
1054 // the prefix does not increase the format
1055 // size. e.g.(("%#3x", 0xf) is "0xf")
1056
1057 // If the result is zero, o, b, x, X adds nothing.
1058 break;
1059 // For a, A, e, E, f, F, g, and G conversions,
1060 // the result of converting a floating-point number always contains a
1061 // decimal-point
1070 Size += (Precision ? 0 : 1);
1071 break;
1072 // For other conversions, the behavior is undefined.
1073 default:
1074 break;
1075 }
1076 }
1077 assert(SpecifierLen <= Size && "no underflow");
1078 Size -= SpecifierLen;
1079 return true;
1080 }
1081
1082 size_t getSizeLowerBound() const { return Size; }
1083 bool isKernelCompatible() const { return IsKernelCompatible; }
1084
1085private:
1086 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1087 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1088 size_t FieldWidth = 0;
1090 FieldWidth = FW.getConstantAmount();
1091 return FieldWidth;
1092 }
1093
1094 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1095 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1096 size_t Precision = 0;
1097
1098 // See man 3 printf for default precision value based on the specifier.
1099 switch (FW.getHowSpecified()) {
1101 switch (FS.getConversionSpecifier().getKind()) {
1102 default:
1103 break;
1107 Precision = 1;
1108 break;
1115 Precision = 1;
1116 break;
1123 Precision = 6;
1124 break;
1126 Precision = 1;
1127 break;
1128 }
1129 break;
1131 Precision = FW.getConstantAmount();
1132 break;
1133 default:
1134 break;
1135 }
1136 return Precision;
1137 }
1138};
1139
1140} // namespace
1141
1142static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1143 StringRef &FormatStrRef, size_t &StrLen,
1144 ASTContext &Context) {
1145 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1146 Format && (Format->isOrdinary() || Format->isUTF8())) {
1147 FormatStrRef = Format->getString();
1148 const ConstantArrayType *T =
1149 Context.getAsConstantArrayType(Format->getType());
1150 assert(T && "String literal not of constant array type!");
1151 size_t TypeSize = T->getZExtSize();
1152 // In case there's a null byte somewhere.
1153 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1154 return true;
1155 }
1156 return false;
1157}
1158
1159namespace {
1160/// Helper class for buffer overflow/overread checking in fortified functions.
1161class FortifiedBufferChecker {
1162public:
1163 FortifiedBufferChecker(Sema &S, FunctionDecl *FD, CallExpr *TheCall)
1164 : S(S), TheCall(TheCall), FD(FD),
1165 DABAttr(FD ? FD->getAttr<DiagnoseAsBuiltinAttr>() : nullptr) {
1166 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1167 SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1168 }
1169
1170 std::optional<unsigned> TranslateIndex(unsigned Index) {
1171 // If we refer to a diagnose_as_builtin attribute, we need to change the
1172 // argument index to refer to the arguments of the called function. Unless
1173 // the index is out of bounds, which presumably means it's a variadic
1174 // function.
1175 unsigned NewIndex = Index;
1176 if (DABAttr) {
1177 unsigned DABIndices = DABAttr->argIndices_size();
1178 NewIndex = Index < DABIndices ? DABAttr->argIndices_begin()[Index]
1179 : Index - DABIndices + FD->getNumParams();
1180 }
1181 if (NewIndex >= TheCall->getNumArgs())
1182 return std::nullopt;
1183 return NewIndex;
1184 }
1185
1186 /// Evaluate the argument at Index as an integer constant while preserving
1187 /// its signedness, or return std::nullopt if it cannot be evaluated.
1188 std::optional<llvm::APSInt> EvaluateIntegerArgument(unsigned Index) {
1189 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1190 if (!IndexOptional)
1191 return std::nullopt;
1192 Expr::EvalResult Result;
1193 Expr *Arg = TheCall->getArg(*IndexOptional);
1194 if (!Arg->EvaluateAsInt(Result, S.getASTContext()))
1195 return std::nullopt;
1196
1197 return Result.Val.getInt();
1198 }
1199
1200 std::optional<llvm::APSInt>
1201 ComputeExplicitObjectSizeArgument(unsigned Index) {
1202 std::optional<llvm::APSInt> Integer = EvaluateIntegerArgument(Index);
1203 if (!Integer)
1204 return std::nullopt;
1205 *Integer = Integer->extOrTrunc(SizeTypeWidth);
1206 Integer->setIsUnsigned(true);
1207 return Integer;
1208 }
1209
1210 std::optional<llvm::APSInt> ComputeSizeArgument(unsigned Index) {
1211 // If the parameter has a pass_object_size attribute, then we should use its
1212 // (potentially) more strict checking mode. Otherwise, conservatively assume
1213 // type 0.
1214 int BOSType = 0;
1215 // This check can fail for variadic functions.
1216 if (Index < FD->getNumParams()) {
1217 if (const auto *POS =
1218 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1219 BOSType = POS->getType();
1220 }
1221
1222 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1223 if (!IndexOptional)
1224 return std::nullopt;
1225
1226 const Expr *ObjArg = TheCall->getArg(*IndexOptional);
1227 if (std::optional<uint64_t> ObjSize =
1228 ObjArg->tryEvaluateObjectSize(S.getASTContext(), BOSType)) {
1229 // Get the object size in the target's size_t width.
1230 return llvm::APSInt::getUnsigned(*ObjSize).extOrTrunc(SizeTypeWidth);
1231 }
1232 return std::nullopt;
1233 }
1234
1235 std::optional<llvm::APSInt>
1236 ComputeExplicitObjectSizeArgumentProduct(unsigned LIndex, unsigned RIndex) {
1237 auto L = ComputeExplicitObjectSizeArgument(LIndex);
1238 auto R = ComputeExplicitObjectSizeArgument(RIndex);
1239 if (!L || !R)
1240 return std::nullopt;
1241
1242 unsigned W =
1243 2 * std::max({L->getBitWidth(), R->getBitWidth(), SizeTypeWidth});
1244
1245 llvm::APSInt LE = L->extOrTrunc(W);
1246 llvm::APSInt RE = R->extOrTrunc(W);
1247
1248 return LE * RE;
1249 }
1250
1251 std::optional<llvm::APSInt> ComputeStrLenArgument(unsigned Index) {
1252 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1253 if (!IndexOptional)
1254 return std::nullopt;
1255 unsigned NewIndex = *IndexOptional;
1256
1257 const Expr *ObjArg = TheCall->getArg(NewIndex);
1258
1259 if (std::optional<uint64_t> Result =
1260 ObjArg->tryEvaluateStrLen(S.getASTContext())) {
1261 // Add 1 for null byte.
1262 return llvm::APSInt::getUnsigned(*Result + 1).extOrTrunc(SizeTypeWidth);
1263 }
1264 return std::nullopt;
1265 }
1266
1267 unsigned getSizeTypeWidth() const { return SizeTypeWidth; }
1268
1269 unsigned getBuiltinID() const {
1270 const FunctionDecl *UseDecl = FD;
1271 if (DABAttr) {
1272 UseDecl = DABAttr->getFunction();
1273 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1274 }
1275 return UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1276 }
1277
1278 /// Return function name after stripping __builtin_ and _chk affixes.
1279 std::string getFunctionName() const {
1280 unsigned ID = getBuiltinID();
1281 if (!ID) {
1282 // Use callee name directly if not a builtin.
1283 const FunctionDecl *Callee = TheCall->getDirectCallee();
1284 assert(Callee && "expected callee");
1285 return Callee->getName().str();
1286 }
1287 std::string Name = S.getASTContext().BuiltinInfo.getName(ID);
1288 StringRef Ref = Name;
1289 // Strip __builtin___*_chk or __builtin_ prefix.
1290 if (!(Ref.consume_front("__builtin___") && Ref.consume_back("_chk")))
1291 Ref.consume_front("__builtin_");
1292 assert(!Ref.empty() && "expected non-empty function name");
1293 return Ref.str();
1294 }
1295
1296 /// Check for source buffer overread in memory functions.
1297 void checkSourceOverread(unsigned SrcArgIdx, unsigned SizeArgIdx) {
1299 return;
1300
1301 const Expr *SrcArg = TheCall->getArg(SrcArgIdx);
1302 const Expr *SizeArg = TheCall->getArg(SizeArgIdx);
1303 if (SrcArg->isInstantiationDependent() ||
1304 SizeArg->isInstantiationDependent())
1305 return;
1306
1307 std::optional<llvm::APSInt> CopyLen =
1308 ComputeExplicitObjectSizeArgument(SizeArgIdx);
1309 std::optional<llvm::APSInt> SrcBufSize = ComputeSizeArgument(SrcArgIdx);
1310
1311 if (!CopyLen || !SrcBufSize)
1312 return;
1313
1314 // Warn only if copy length exceeds source buffer size.
1315 if (llvm::APSInt::compareValues(*CopyLen, *SrcBufSize) <= 0)
1316 return;
1317
1318 S.DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1319 S.PDiag(diag::warn_stringop_overread)
1320 << getFunctionName() << CopyLen->getZExtValue()
1321 << SrcBufSize->getZExtValue());
1322 }
1323
1324private:
1325 Sema &S;
1326 CallExpr *TheCall;
1327 FunctionDecl *FD;
1328 const DiagnoseAsBuiltinAttr *DABAttr;
1329 unsigned SizeTypeWidth;
1330};
1331} // anonymous namespace
1332
1333void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1334 CallExpr *TheCall) {
1336 return;
1337
1338 FortifiedBufferChecker Checker(*this, FD, TheCall);
1339
1340 unsigned BuiltinID = Checker.getBuiltinID();
1341 if (!BuiltinID)
1342 return;
1343
1344 unsigned SizeTypeWidth = Checker.getSizeTypeWidth();
1345
1346 std::optional<llvm::APSInt> AccessSize;
1347 std::optional<llvm::APSInt> BufferSize;
1348 unsigned DiagID = 0;
1349
1350 switch (BuiltinID) {
1351 default:
1352 return;
1353 case Builtin::BI__builtin_strcat:
1354 case Builtin::BIstrcat:
1355 case Builtin::BI__builtin_stpcpy:
1356 case Builtin::BIstpcpy:
1357 case Builtin::BI__builtin_strcpy:
1358 case Builtin::BIstrcpy: {
1359 DiagID = diag::warn_fortify_strlen_overflow;
1360 AccessSize = Checker.ComputeStrLenArgument(1);
1361 BufferSize = Checker.ComputeSizeArgument(0);
1362 break;
1363 }
1364
1365 case Builtin::BI__builtin___strcat_chk:
1366 case Builtin::BI__builtin___stpcpy_chk:
1367 case Builtin::BI__builtin___strcpy_chk: {
1368 DiagID = diag::warn_fortify_strlen_overflow;
1369 AccessSize = Checker.ComputeStrLenArgument(1);
1370 BufferSize = Checker.ComputeExplicitObjectSizeArgument(2);
1371 break;
1372 }
1373
1374 case Builtin::BIscanf:
1375 case Builtin::BIfscanf:
1376 case Builtin::BIsscanf: {
1377 unsigned FormatIndex = 1;
1378 unsigned DataIndex = 2;
1379 if (BuiltinID == Builtin::BIscanf) {
1380 FormatIndex = 0;
1381 DataIndex = 1;
1382 }
1383
1384 const auto *FormatExpr =
1385 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1386
1387 StringRef FormatStrRef;
1388 size_t StrLen;
1389 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1390 return;
1391
1392 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1393 unsigned SourceSize) {
1394 DiagID = diag::warn_fortify_scanf_overflow;
1395 unsigned Index = ArgIndex + DataIndex;
1396 std::string FunctionName = Checker.getFunctionName();
1397 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1398 PDiag(DiagID) << FunctionName << (Index + 1)
1399 << DestSize << SourceSize);
1400 };
1401
1402 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1403 return Checker.ComputeSizeArgument(Index + DataIndex);
1404 };
1405 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1406 const char *FormatBytes = FormatStrRef.data();
1408 FormatBytes + StrLen, getLangOpts(),
1409 Context.getTargetInfo());
1410
1411 // Unlike the other cases, in this one we have already issued the diagnostic
1412 // here, so no need to continue (because unlike the other cases, here the
1413 // diagnostic refers to the argument number).
1414 return;
1415 }
1416
1417 case Builtin::BIsprintf:
1418 case Builtin::BI__builtin_sprintf:
1419 case Builtin::BI__builtin___sprintf_chk:
1420 case Builtin::BIvsprintf:
1421 case Builtin::BI__builtin_vsprintf:
1422 case Builtin::BI__builtin___vsprintf_chk: {
1423 bool IsChk = BuiltinID == Builtin::BI__builtin___sprintf_chk ||
1424 BuiltinID == Builtin::BI__builtin___vsprintf_chk;
1425 std::optional<unsigned> FormatIndex = Checker.TranslateIndex(IsChk ? 3 : 1);
1426 if (!FormatIndex)
1427 return;
1428 const auto *FormatExpr =
1429 TheCall->getArg(*FormatIndex)->IgnoreParenImpCasts();
1430
1431 StringRef FormatStrRef;
1432 size_t StrLen;
1433 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1434 EstimateSizeFormatHandler H(FormatStrRef);
1435 const char *FormatBytes = FormatStrRef.data();
1437 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1438 Context.getTargetInfo(), false)) {
1439 DiagID = H.isKernelCompatible()
1440 ? diag::warn_format_overflow
1441 : diag::warn_format_overflow_non_kprintf;
1442 AccessSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1443 .extOrTrunc(SizeTypeWidth);
1444 if (IsChk) {
1445 BufferSize = Checker.ComputeExplicitObjectSizeArgument(2);
1446 } else {
1447 BufferSize = Checker.ComputeSizeArgument(0);
1448 }
1449 break;
1450 }
1451 }
1452 return;
1453 }
1454 case Builtin::BI__builtin___memcpy_chk:
1455 case Builtin::BI__builtin___memmove_chk:
1456 case Builtin::BI__builtin___memset_chk:
1457 case Builtin::BI__builtin___strlcat_chk:
1458 case Builtin::BI__builtin___strlcpy_chk:
1459 case Builtin::BI__builtin___strncat_chk:
1460 case Builtin::BI__builtin___strncpy_chk:
1461 case Builtin::BI__builtin___stpncpy_chk:
1462 case Builtin::BI__builtin___memccpy_chk:
1463 case Builtin::BI__builtin___mempcpy_chk: {
1464 DiagID = diag::warn_builtin_chk_overflow;
1465 AccessSize =
1466 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1467 BufferSize =
1468 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1469
1470 if (BuiltinID == Builtin::BI__builtin___memcpy_chk ||
1471 BuiltinID == Builtin::BI__builtin___memmove_chk ||
1472 BuiltinID == Builtin::BI__builtin___mempcpy_chk) {
1473 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1474 }
1475 break;
1476 }
1477
1478 case Builtin::BI__builtin___snprintf_chk:
1479 case Builtin::BI__builtin___vsnprintf_chk: {
1480 DiagID = diag::warn_builtin_chk_overflow;
1481 AccessSize = Checker.ComputeExplicitObjectSizeArgument(1);
1482 BufferSize = Checker.ComputeExplicitObjectSizeArgument(3);
1483 break;
1484 }
1485
1486 case Builtin::BImemccpy: {
1487 // Whether memccpy overflows depends on whether the stop character appears
1488 // in the source buffer before reaching n, not just the buffer size.
1489 DiagID = diag::warn_fortify_source_size_mismatch;
1490 AccessSize = Checker.ComputeExplicitObjectSizeArgument(3);
1491 BufferSize = Checker.ComputeSizeArgument(0);
1492 break;
1493 }
1494
1495 case Builtin::BIstrncat:
1496 case Builtin::BI__builtin_strncat:
1497 case Builtin::BIstrncpy:
1498 case Builtin::BI__builtin_strncpy:
1499 case Builtin::BIstpncpy:
1500 case Builtin::BI__builtin_stpncpy:
1501 case Builtin::BIstrlcat:
1502 case Builtin::BI__builtin_strlcat:
1503 case Builtin::BIstrlcpy:
1504 case Builtin::BI__builtin_strlcpy: {
1505 // Whether these functions overflow depends on the runtime strlen of the
1506 // string, not just the buffer size, so emitting the "always overflow"
1507 // diagnostic isn't quite right. We should still diagnose passing a buffer
1508 // size larger than the destination buffer though; this is a runtime abort
1509 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1510 DiagID = diag::warn_fortify_source_size_mismatch;
1511 AccessSize = Checker.ComputeExplicitObjectSizeArgument(2);
1512 BufferSize = Checker.ComputeSizeArgument(0);
1513 break;
1514 }
1515
1516 case Builtin::BIrecv:
1517 case Builtin::BIrecvfrom: {
1518 unsigned ExpectedArgs = BuiltinID == Builtin::BIrecv ? 4 : 6;
1519 if (TheCall->getNumArgs() != ExpectedArgs ||
1520 !TheCall->getArg(1)->getType()->isPointerType() ||
1521 !TheCall->getArg(2)->getType()->isIntegerType())
1522 return;
1523 DiagID = diag::warn_fortify_source_size_mismatch;
1524 AccessSize = Checker.ComputeExplicitObjectSizeArgument(2);
1525 BufferSize = Checker.ComputeSizeArgument(1);
1526 break;
1527 }
1528
1529 case Builtin::BIgetlogin_r: {
1530 DiagID = diag::warn_fortify_source_size_mismatch;
1531 AccessSize = Checker.ComputeExplicitObjectSizeArgument(1);
1532 BufferSize = Checker.ComputeSizeArgument(0);
1533 break;
1534 }
1535
1536 case Builtin::BIttyname_r:
1537 case Builtin::BIptsname_r:
1538 case Builtin::BIconfstr: {
1539 DiagID = diag::warn_fortify_source_size_mismatch;
1540 AccessSize = Checker.ComputeExplicitObjectSizeArgument(2);
1541 BufferSize = Checker.ComputeSizeArgument(1);
1542 break;
1543 }
1544
1545 case Builtin::BIpoll:
1546 case Builtin::BIppoll:
1547 case Builtin::BIppoll64: {
1548 unsigned ExpectedArgs = BuiltinID == Builtin::BIpoll ? 3 : 4;
1549 if (TheCall->getNumArgs() != ExpectedArgs ||
1550 !TheCall->getArg(1)->getType()->isIntegerType())
1551 return;
1552 QualType PointeeTy = TheCall->getArg(0)->getType()->getPointeeType();
1553 if (PointeeTy.isNull())
1554 return;
1555 const RecordDecl *RD = PointeeTy->getAsRecordDecl();
1556 if (!RD || !RD->getIdentifier() || RD->getName() != "pollfd")
1557 return;
1558 if (BuiltinID == Builtin::BIpoll) {
1559 if (!TheCall->getArg(2)->getType()->isIntegerType())
1560 return;
1561 } else {
1562 QualType TmoPointeeTy = TheCall->getArg(2)->getType()->getPointeeType();
1563 if (TmoPointeeTy.isNull())
1564 return;
1565 const RecordDecl *TmoRD = TmoPointeeTy->getAsRecordDecl();
1566 if (!TmoRD || !TmoRD->getIdentifier() || TmoRD->getName() != "timespec" ||
1567 !TheCall->getArg(3)->getType()->isPointerType())
1568 return;
1569 }
1570 std::optional<CharUnits> ElemSize =
1571 Context.getTypeSizeInCharsIfKnown(PointeeTy);
1572 if (!ElemSize)
1573 return;
1574 std::optional<llvm::APSInt> Count =
1575 Checker.ComputeExplicitObjectSizeArgument(1);
1576 if (!Count)
1577 return;
1578 DiagID = diag::warn_fortify_source_size_mismatch;
1579 unsigned WideWidth = SizeTypeWidth * 2;
1580 AccessSize = Count->extOrTrunc(WideWidth) *
1581 llvm::APSInt(llvm::APInt(WideWidth, ElemSize->getQuantity()),
1582 /*isUnsigned=*/true);
1583 BufferSize = Checker.ComputeSizeArgument(0);
1584 break;
1585 }
1586
1587 case Builtin::BIbzero:
1588 case Builtin::BI__builtin_bzero:
1589 case Builtin::BIexplicit_bzero: {
1590 DiagID = diag::warn_fortify_source_overflow;
1591 AccessSize = Checker.ComputeExplicitObjectSizeArgument(1);
1592 BufferSize = Checker.ComputeSizeArgument(0);
1593 break;
1594 }
1595
1596 case Builtin::BImemcpy:
1597 case Builtin::BI__builtin_memcpy:
1598 case Builtin::BImemmove:
1599 case Builtin::BI__builtin_memmove:
1600 case Builtin::BImemset:
1601 case Builtin::BI__builtin_memset:
1602 case Builtin::BImemset_explicit:
1603 case Builtin::BImempcpy:
1604 case Builtin::BI__builtin_mempcpy: {
1605 DiagID = diag::warn_fortify_source_overflow;
1606 AccessSize = Checker.ComputeExplicitObjectSizeArgument(2);
1607 BufferSize = Checker.ComputeSizeArgument(0);
1608
1609 // Buffer overread doesn't make sense for memset.
1610 if (BuiltinID != Builtin::BImemset &&
1611 BuiltinID != Builtin::BI__builtin_memset &&
1612 BuiltinID != Builtin::BImemset_explicit) {
1613 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1614 }
1615 break;
1616 }
1617 case Builtin::BIbcopy:
1618 case Builtin::BI__builtin_bcopy: {
1619 DiagID = diag::warn_fortify_source_overflow;
1620 AccessSize =
1621 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1622 BufferSize = Checker.ComputeSizeArgument(1);
1623 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1624 break;
1625 }
1626 case Builtin::BIfread:
1627 case Builtin::BIfread_unlocked: {
1628 DiagID = diag::warn_fortify_source_overflow;
1629 AccessSize = Checker.ComputeExplicitObjectSizeArgumentProduct(1, 2);
1630 BufferSize = Checker.ComputeSizeArgument(0);
1631 break;
1632 }
1633 case Builtin::BIfwrite:
1634 case Builtin::BIfwrite_unlocked: {
1635 DiagID = diag::warn_fortify_source_overread;
1636 AccessSize = Checker.ComputeExplicitObjectSizeArgumentProduct(1, 2);
1637 BufferSize = Checker.ComputeSizeArgument(0);
1638 break;
1639 }
1640 case Builtin::BIfgets:
1641 case Builtin::BIfgets_unlocked: {
1642 AccessSize = Checker.EvaluateIntegerArgument(1);
1643
1644 if (AccessSize && AccessSize->isNegative()) {
1645 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1646 PDiag(diag::warn_fortify_source_negative_size)
1647 << Checker.getFunctionName());
1648 return;
1649 }
1650
1651 DiagID = diag::warn_fortify_source_size_mismatch;
1652 BufferSize = Checker.ComputeSizeArgument(0);
1653 break;
1654 }
1655 // memchr(buf, val, size)
1656 case Builtin::BImemchr:
1657 case Builtin::BI__builtin_memchr: {
1658 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1659 return;
1660 }
1661
1662 // memcmp/bcmp(buf0, buf1, size)
1663 // Two checks since each buffer is read
1664 case Builtin::BImemcmp:
1665 case Builtin::BI__builtin_memcmp:
1666 case Builtin::BIbcmp:
1667 case Builtin::BI__builtin_bcmp: {
1668 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1669 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1670 return;
1671 }
1672 case Builtin::BIsnprintf:
1673 case Builtin::BI__builtin_snprintf:
1674 case Builtin::BIvsnprintf:
1675 case Builtin::BI__builtin_vsnprintf: {
1676 DiagID = diag::warn_fortify_source_size_mismatch;
1677 AccessSize = Checker.ComputeExplicitObjectSizeArgument(1);
1678 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1679 StringRef FormatStrRef;
1680 size_t StrLen;
1681 if (AccessSize &&
1682 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1683 EstimateSizeFormatHandler H(FormatStrRef);
1684 const char *FormatBytes = FormatStrRef.data();
1686 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1687 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1688 llvm::APSInt FormatSize =
1689 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1690 .extOrTrunc(SizeTypeWidth);
1691 if (FormatSize > *AccessSize && *AccessSize != 0) {
1692 unsigned TruncationDiagID =
1693 H.isKernelCompatible() ? diag::warn_format_truncation
1694 : diag::warn_format_truncation_non_kprintf;
1695 SmallString<16> SpecifiedSizeStr;
1696 SmallString<16> FormatSizeStr;
1697 AccessSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1698 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1699 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1700 PDiag(TruncationDiagID)
1701 << Checker.getFunctionName()
1702 << SpecifiedSizeStr << FormatSizeStr);
1703 }
1704 }
1705 }
1706 BufferSize = Checker.ComputeSizeArgument(0);
1707 const Expr *LenArg = TheCall->getArg(1)->IgnoreCasts();
1708 const Expr *Dest = TheCall->getArg(0)->IgnoreCasts();
1709 IdentifierInfo *FnInfo = FD->getIdentifier();
1710 CheckSizeofMemaccessArgument(LenArg, Dest, FnInfo);
1711 }
1712 }
1713
1714 if (!AccessSize || !BufferSize ||
1715 llvm::APSInt::compareValues(*AccessSize, *BufferSize) <= 0)
1716 return;
1717
1718 std::string FunctionName = Checker.getFunctionName();
1719
1720 SmallString<16> BufferSizeStr;
1721 SmallString<16> AccessSizeStr;
1722 BufferSize->toString(BufferSizeStr, /*Radix=*/10);
1723 AccessSize->toString(AccessSizeStr, /*Radix=*/10);
1724 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1725 PDiag(DiagID)
1726 << FunctionName << BufferSizeStr << AccessSizeStr);
1727}
1728
1729void Sema::checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall) {
1730 if (TheCall->isValueDependent() || TheCall->isTypeDependent())
1731 return;
1732
1733 // Recognize the libc function by builtin identity rather than by name and
1734 // system-header origin. umask is a LibBuiltin marked IgnoreSignature, so the
1735 // builtin id is attached to any file-scope, C-linkage declaration of umask
1736 // regardless of the libc's mode_t spelling -- including a hand-written
1737 // forward declaration without <sys/stat.h>. A static/local lookalike or a
1738 // C++ (non-extern-"C") declaration keeps a zero builtin id and is ignored.
1739 if (FD->getBuiltinID() != Builtin::BIumask)
1740 return;
1741
1742 // umask(mode_t): warn when the constant-evaluated argument has bits set
1743 // outside the file-permission mask (0777). Those bits are ignored.
1744 if (TheCall->getNumArgs() != 1)
1745 return;
1746 Expr *Arg = TheCall->getArg(0);
1747 // POSIX mode_t is at least 16 bits; bail out if the argument has a narrower
1748 // integer type (which is not POSIX umask and would otherwise assert
1749 // constructing the 0777 bitmask for widths under 9 bits).
1750 if (!Arg->getType()->isIntegerType() ||
1751 getASTContext().getIntWidth(Arg->getType()) < 16)
1752 return;
1753 Expr::EvalResult R;
1754 if (!Arg->EvaluateAsInt(R, getASTContext()))
1755 return;
1756 // Operate on the raw two's-complement bit pattern so that negative literals
1757 // (which convert to large unsigned mode_t values) are caught.
1758 llvm::APInt RawValue = R.Val.getInt();
1759 llvm::APInt Mask(RawValue.getBitWidth(), 0777);
1760 llvm::APInt Extra = RawValue & ~Mask;
1761 if (Extra == 0)
1762 return;
1763 SmallString<16> ExtraStr;
1764 Extra.toString(ExtraStr, /*Radix=*/8, /*Signed=*/false);
1765 Diag(TheCall->getBeginLoc(), diag::warn_fortify_umask_unused_bits)
1766 << ExtraStr;
1767}
1768
1769static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1770 Scope::ScopeFlags NeededScopeFlags,
1771 unsigned DiagID) {
1772 // Scopes aren't available during instantiation. Fortunately, builtin
1773 // functions cannot be template args so they cannot be formed through template
1774 // instantiation. Therefore checking once during the parse is sufficient.
1775 if (SemaRef.inTemplateInstantiation())
1776 return false;
1777
1778 Scope *S = SemaRef.getCurScope();
1779 while (S && !S->isSEHExceptScope())
1780 S = S->getParent();
1781 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1782 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1783 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1784 << DRE->getDecl()->getIdentifier();
1785 return true;
1786 }
1787
1788 return false;
1789}
1790
1791// In OpenCL, __builtin_alloca_* should return a pointer to address space
1792// that corresponds to the stack address space i.e private address space.
1793static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1794 QualType RT = TheCall->getType();
1795 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1796 "__builtin_alloca has invalid address space");
1797
1798 RT = RT->getPointeeType();
1800 TheCall->setType(S.Context.getPointerType(RT));
1801}
1802
1803static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1804 if (S.checkArgCountAtLeast(TheCall, 1))
1805 return true;
1806
1807 for (Expr *Arg : TheCall->arguments()) {
1808 // If argument is dependent on a template parameter, we can't resolve now.
1809 if (Arg->isTypeDependent() || Arg->isValueDependent())
1810 continue;
1811 // Reject void types.
1812 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1813 if (ArgTy->isVoidType())
1814 return S.Diag(Arg->getBeginLoc(), diag::err_param_with_void_type);
1815 }
1816
1817 TheCall->setType(S.Context.getSizeType());
1818 return false;
1819}
1820
1821namespace {
1822enum PointerAuthOpKind {
1823 PAO_Strip,
1824 PAO_Sign,
1825 PAO_Auth,
1826 PAO_SignGeneric,
1827 PAO_Discriminator,
1828 PAO_BlendPointer,
1829 PAO_BlendInteger,
1830 PAO_BlendPC
1831};
1832}
1833
1835 if (getLangOpts().PointerAuthIntrinsics)
1836 return false;
1837
1838 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1839 return true;
1840}
1841
1842static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1844}
1845
1846static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1847 // Convert it to type 'int'.
1848 if (S.convertArgumentToType(Arg, S.Context.IntTy))
1849 return true;
1850
1851 // Value-dependent expressions are okay; wait for template instantiation.
1852 if (Arg->isValueDependent())
1853 return false;
1854
1855 unsigned KeyValue;
1856 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1857}
1858
1860 // Attempt to constant-evaluate the expression.
1861 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1862 if (!KeyValue) {
1863 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1864 << 0 << Arg->getSourceRange();
1865 return true;
1866 }
1867
1868 // Ask the target to validate the key parameter.
1869 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1871 {
1872 llvm::raw_svector_ostream Str(Value);
1873 Str << *KeyValue;
1874 }
1875
1876 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1877 << Value << Arg->getSourceRange();
1878 return true;
1879 }
1880
1881 Result = KeyValue->getZExtValue();
1882 return false;
1883}
1884
1887 unsigned &IntVal) {
1888 if (!Arg) {
1889 IntVal = 0;
1890 return true;
1891 }
1892
1893 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
1894 if (!Result) {
1895 Diag(Arg->getExprLoc(), diag::err_ptrauth_arg_not_ice);
1896 return false;
1897 }
1898
1899 unsigned Max;
1900 bool IsAddrDiscArg = false;
1901
1902 switch (Kind) {
1904 Max = 1;
1905 IsAddrDiscArg = true;
1906 break;
1909 break;
1910 };
1911
1913 if (IsAddrDiscArg)
1914 Diag(Arg->getExprLoc(), diag::err_ptrauth_address_discrimination_invalid)
1915 << Result->getExtValue();
1916 else
1917 Diag(Arg->getExprLoc(), diag::err_ptrauth_extra_discriminator_invalid)
1918 << Result->getExtValue() << Max;
1919
1920 return false;
1921 };
1922
1923 IntVal = Result->getZExtValue();
1924 return true;
1925}
1926
1927static std::pair<const ValueDecl *, CharUnits>
1929 // Must evaluate as a pointer.
1931 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1932 return {nullptr, CharUnits()};
1933
1934 const auto *BaseDecl =
1935 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1936 if (!BaseDecl)
1937 return {nullptr, CharUnits()};
1938
1939 return {BaseDecl, Result.Val.getLValueOffset()};
1940}
1941
1942static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1943 bool RequireConstant = false) {
1944 if (Arg->hasPlaceholderType()) {
1946 if (R.isInvalid())
1947 return true;
1948 Arg = R.get();
1949 }
1950
1951 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1952 return OpKind != PAO_BlendInteger;
1953 };
1954 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1955 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1956 OpKind == PAO_SignGeneric || OpKind == PAO_BlendPC;
1957 };
1958
1959 // Require the value to have the right range of type.
1960 QualType ExpectedTy;
1961 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1962 ExpectedTy = Arg->getType().getUnqualifiedType();
1963 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1964 ExpectedTy = S.Context.VoidPtrTy;
1965 } else if (AllowsInteger(OpKind) &&
1967 ExpectedTy = S.Context.getUIntPtrType();
1968
1969 } else {
1970 // Diagnose the failures.
1971 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1972 << unsigned(OpKind == PAO_Discriminator ? 1
1973 : OpKind == PAO_BlendPointer ? 2
1974 : OpKind == PAO_BlendInteger ? 3
1975 : OpKind == PAO_BlendPC ? 4
1976 : 0)
1977 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1978 << Arg->getType() << Arg->getSourceRange();
1979 return true;
1980 }
1981
1982 // Convert to that type. This should just be an lvalue-to-rvalue
1983 // conversion.
1984 if (S.convertArgumentToType(Arg, ExpectedTy))
1985 return true;
1986
1987 if (!RequireConstant) {
1988 // Warn about null pointers for non-generic sign and auth operations.
1989 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1991 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1992 ? diag::warn_ptrauth_sign_null_pointer
1993 : diag::warn_ptrauth_auth_null_pointer)
1994 << Arg->getSourceRange();
1995 }
1996
1997 return false;
1998 }
1999
2000 // Perform special checking on the arguments to ptrauth_sign_constant.
2001
2002 // The main argument.
2003 if (OpKind == PAO_Sign) {
2004 // Require the value we're signing to have a special form.
2005 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
2006 bool Invalid;
2007
2008 // Must be rooted in a declaration reference.
2009 if (!BaseDecl)
2010 Invalid = true;
2011
2012 // If it's a function declaration, we can't have an offset.
2013 else if (isa<FunctionDecl>(BaseDecl))
2014 Invalid = !Offset.isZero();
2015
2016 // Otherwise we're fine.
2017 else
2018 Invalid = false;
2019
2020 if (Invalid)
2021 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
2022 return Invalid;
2023 }
2024
2025 // The discriminator argument.
2026 assert(OpKind == PAO_Discriminator);
2027
2028 // Must be a pointer or integer or blend thereof.
2029 Expr *Pointer = nullptr;
2030 Expr *Integer = nullptr;
2031 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
2032 if (Call->getBuiltinCallee() ==
2033 Builtin::BI__builtin_ptrauth_blend_discriminator) {
2034 Pointer = Call->getArg(0);
2035 Integer = Call->getArg(1);
2036 }
2037 }
2038 if (!Pointer && !Integer) {
2039 if (Arg->getType()->isPointerType())
2040 Pointer = Arg;
2041 else
2042 Integer = Arg;
2043 }
2044
2045 // Check the pointer.
2046 bool Invalid = false;
2047 if (Pointer) {
2048 assert(Pointer->getType()->isPointerType());
2049
2050 // TODO: if we're initializing a global, check that the address is
2051 // somehow related to what we're initializing. This probably will
2052 // never really be feasible and we'll have to catch it at link-time.
2053 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
2054 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
2055 Invalid = true;
2056 }
2057
2058 // Check the integer.
2059 if (Integer) {
2060 assert(Integer->getType()->isIntegerType());
2061 if (!Integer->isEvaluatable(S.Context))
2062 Invalid = true;
2063 }
2064
2065 if (Invalid)
2066 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
2067 return Invalid;
2068}
2069
2071 if (S.checkArgCount(Call, 2))
2072 return ExprError();
2074 return ExprError();
2075 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
2076 checkPointerAuthKey(S, Call->getArgs()[1]))
2077 return ExprError();
2078
2079 Call->setType(Call->getArgs()[0]->getType());
2080 return Call;
2081}
2082
2084 if (S.checkArgCount(Call, 2))
2085 return ExprError();
2087 return ExprError();
2088 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
2089 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
2090 return ExprError();
2091
2092 Call->setType(S.Context.getUIntPtrType());
2093 return Call;
2094}
2095
2097 if (S.checkArgCount(Call, 2))
2098 return ExprError();
2100 return ExprError();
2101 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
2102 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
2103 return ExprError();
2104
2105 Call->setType(S.Context.getUIntPtrType());
2106 return Call;
2107}
2108
2110 PointerAuthOpKind OpKind,
2111 bool RequireConstant) {
2112 if (S.checkArgCount(Call, 3))
2113 return ExprError();
2115 return ExprError();
2116 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
2117 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2118 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
2119 RequireConstant))
2120 return ExprError();
2121
2122 Call->setType(Call->getArgs()[0]->getType());
2123 return Call;
2124}
2125
2127 if (S.checkArgCount(Call, 5))
2128 return ExprError();
2130 return ExprError();
2131 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
2132 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2133 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
2134 checkPointerAuthKey(S, Call->getArgs()[3]) ||
2135 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
2136 return ExprError();
2137
2138 Call->setType(Call->getArgs()[0]->getType());
2139 return Call;
2140}
2141
2143 if (S.checkArgCount(Call, 6))
2144 return ExprError();
2146 return ExprError();
2147 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
2148 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2149 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
2150 checkPointerAuthValue(S, Call->getArgs()[3], PAO_BlendPC) ||
2151 checkPointerAuthKey(S, Call->getArgs()[4]) ||
2152 checkPointerAuthValue(S, Call->getArgs()[5], PAO_Discriminator))
2153 return ExprError();
2154
2155 // Validate that the oldKey is IA or IB, not DA or DB.
2156 // This enforces the constraint that auth_with_pc_and_resign only supports
2157 // IA/IB keys for authentication, as only those keys support the PC-based
2158 // signing instructions (paciasppc/pacibsppc).
2159 unsigned OldKey = 0;
2160 if (!S.checkConstantPointerAuthKey(Call->getArgs()[1], OldKey)) {
2162 if (OldKey != static_cast<unsigned>(AK::ASIA) &&
2163 OldKey != static_cast<unsigned>(AK::ASIB)) {
2164 S.Diag(Call->getArgs()[1]->getExprLoc(),
2165 diag::err_ptrauth_auth_with_pc_and_resign_invalid_key)
2166 << OldKey << Call->getArgs()[1]->getSourceRange();
2167 return ExprError();
2168 }
2169 }
2170
2171 Call->setType(Call->getArgs()[0]->getType());
2172 return Call;
2173}
2174
2176 if (S.checkArgCount(Call, 6))
2177 return ExprError();
2179 return ExprError();
2180 const Expr *AddendExpr = Call->getArg(5);
2181 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(S.Context);
2182 if (!AddendIsConstInt) {
2183 const Expr *Arg = Call->getArg(5)->IgnoreParenImpCasts();
2184 DeclRefExpr *DRE = cast<DeclRefExpr>(Call->getCallee()->IgnoreParenCasts());
2185 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2186 S.Diag(Arg->getBeginLoc(), diag::err_constant_integer_last_arg_type)
2187 << FDecl->getDeclName() << Arg->getSourceRange();
2188 }
2189 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
2190 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2191 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
2192 checkPointerAuthKey(S, Call->getArgs()[3]) ||
2193 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator) ||
2194 !AddendIsConstInt)
2195 return ExprError();
2196
2197 Call->setType(Call->getArgs()[0]->getType());
2198 return Call;
2199}
2200
2203 return ExprError();
2204
2205 // We've already performed normal call type-checking.
2206 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
2207
2208 // Operand must be an ordinary or UTF-8 string literal.
2209 const auto *Literal = dyn_cast<StringLiteral>(Arg);
2210 if (!Literal || Literal->getCharByteWidth() != 1) {
2211 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
2212 << (Literal ? 1 : 0) << Arg->getSourceRange();
2213 return ExprError();
2214 }
2215
2216 return Call;
2217}
2218
2220 if (S.checkArgCount(Call, 1))
2221 return ExprError();
2222 Expr *FirstArg = Call->getArg(0);
2223 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(FirstArg);
2224 if (FirstValue.isInvalid())
2225 return ExprError();
2226 Call->setArg(0, FirstValue.get());
2227 QualType FirstArgType = FirstArg->getType();
2228 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
2229 FirstArgType = S.Context.getDecayedType(FirstArgType);
2230
2231 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
2232 if (!FirstArgRecord) {
2233 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
2234 << /*isPolymorphic=*/0 << FirstArgType;
2235 return ExprError();
2236 }
2237 if (S.RequireCompleteType(
2238 FirstArg->getBeginLoc(), FirstArgType->getPointeeType(),
2239 diag::err_get_vtable_pointer_requires_complete_type)) {
2240 return ExprError();
2241 }
2242
2243 if (!FirstArgRecord->isPolymorphic()) {
2244 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
2245 << /*isPolymorphic=*/1 << FirstArgRecord;
2246 return ExprError();
2247 }
2249 Call->setType(ReturnType);
2250 return Call;
2251}
2252
2254 if (S.checkArgCount(TheCall, 1))
2255 return ExprError();
2256
2257 // Compute __builtin_launder's parameter type from the argument.
2258 // The parameter type is:
2259 // * The type of the argument if it's not an array or function type,
2260 // Otherwise,
2261 // * The decayed argument type.
2262 QualType ParamTy = [&]() {
2263 QualType ArgTy = TheCall->getArg(0)->getType();
2264 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
2265 return S.Context.getPointerType(Ty->getElementType());
2266 if (ArgTy->isFunctionType()) {
2267 return S.Context.getPointerType(ArgTy);
2268 }
2269 return ArgTy;
2270 }();
2271
2272 TheCall->setType(ParamTy);
2273
2274 auto DiagSelect = [&]() -> std::optional<unsigned> {
2275 if (!ParamTy->isPointerType())
2276 return 0;
2277 if (ParamTy->isFunctionPointerType())
2278 return 1;
2279 if (ParamTy->isVoidPointerType())
2280 return 2;
2281 return std::optional<unsigned>{};
2282 }();
2283 if (DiagSelect) {
2284 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
2285 << *DiagSelect << TheCall->getSourceRange();
2286 return ExprError();
2287 }
2288
2289 // We either have an incomplete class type, or we have a class template
2290 // whose instantiation has not been forced. Example:
2291 //
2292 // template <class T> struct Foo { T value; };
2293 // Foo<int> *p = nullptr;
2294 // auto *d = __builtin_launder(p);
2295 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
2296 diag::err_incomplete_type))
2297 return ExprError();
2298
2299 assert(ParamTy->getPointeeType()->isObjectType() &&
2300 "Unhandled non-object pointer case");
2301
2302 InitializedEntity Entity =
2304 ExprResult Arg =
2305 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
2306 if (Arg.isInvalid())
2307 return ExprError();
2308 TheCall->setArg(0, Arg.get());
2309
2310 return TheCall;
2311}
2312
2314 if (S.checkArgCount(TheCall, 1))
2315 return ExprError();
2316
2318 if (Arg.isInvalid())
2319 return ExprError();
2320 QualType ParamTy = Arg.get()->getType();
2321 TheCall->setArg(0, Arg.get());
2322 TheCall->setType(S.Context.BoolTy);
2323
2324 // Only accept pointers to objects as arguments, which should have object
2325 // pointer or void pointer types.
2326 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2327 // LWG4138: Function pointer types not allowed
2328 if (PT->getPointeeType()->isFunctionType()) {
2329 S.Diag(TheCall->getArg(0)->getExprLoc(),
2330 diag::err_builtin_is_within_lifetime_invalid_arg)
2331 << 1;
2332 return ExprError();
2333 }
2334 // Disallow VLAs too since those shouldn't be able to
2335 // be a template parameter for `std::is_within_lifetime`
2336 if (PT->getPointeeType()->isVariableArrayType()) {
2337 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
2338 << 1 << "__builtin_is_within_lifetime";
2339 return ExprError();
2340 }
2341 } else {
2342 S.Diag(TheCall->getArg(0)->getExprLoc(),
2343 diag::err_builtin_is_within_lifetime_invalid_arg)
2344 << 0;
2345 return ExprError();
2346 }
2347 return TheCall;
2348}
2349
2351 if (S.checkArgCount(TheCall, 3))
2352 return ExprError();
2353
2354 QualType Dest = TheCall->getArg(0)->getType();
2355 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2356 S.Diag(TheCall->getArg(0)->getExprLoc(),
2357 diag::err_builtin_trivially_relocate_invalid_arg_type)
2358 << /*a pointer*/ 0;
2359 return ExprError();
2360 }
2361
2362 QualType T = Dest->getPointeeType();
2363 if (S.RequireCompleteType(TheCall->getBeginLoc(), T,
2364 diag::err_incomplete_type))
2365 return ExprError();
2366
2367 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2368 T->isIncompleteArrayType()) {
2369 S.Diag(TheCall->getArg(0)->getExprLoc(),
2370 diag::err_builtin_trivially_relocate_invalid_arg_type)
2371 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2372 return ExprError();
2373 }
2374
2375 TheCall->setType(Dest);
2376
2377 QualType Src = TheCall->getArg(1)->getType();
2378 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2379 S.Diag(TheCall->getArg(1)->getExprLoc(),
2380 diag::err_builtin_trivially_relocate_invalid_arg_type)
2381 << /*the same*/ 3;
2382 return ExprError();
2383 }
2384
2385 Expr *SizeExpr = TheCall->getArg(2);
2386 ExprResult Size = S.DefaultLvalueConversion(SizeExpr);
2387 if (Size.isInvalid())
2388 return ExprError();
2389
2390 Size = S.tryConvertExprToType(Size.get(), S.getASTContext().getSizeType());
2391 if (Size.isInvalid())
2392 return ExprError();
2393 SizeExpr = Size.get();
2394 TheCall->setArg(2, SizeExpr);
2395
2396 return TheCall;
2397}
2398
2399// Emit an error and return true if the current object format type is in the
2400// list of unsupported types.
2402 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2403 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2404 llvm::Triple::ObjectFormatType CurObjFormat =
2405 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2406 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2407 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2408 << TheCall->getSourceRange();
2409 return true;
2410 }
2411 return false;
2412}
2413
2414// Emit an error and return true if the current architecture is not in the list
2415// of supported architectures.
2416static bool
2418 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2419 llvm::Triple::ArchType CurArch =
2420 S.getASTContext().getTargetInfo().getTriple().getArch();
2421 if (llvm::is_contained(SupportedArchs, CurArch))
2422 return false;
2423 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2424 << TheCall->getSourceRange();
2425 return true;
2426}
2427
2428static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2429 SourceLocation CallSiteLoc);
2430
2431bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2432 CallExpr *TheCall) {
2433 switch (TI.getTriple().getArch()) {
2434 default:
2435 // Some builtins don't require additional checking, so just consider these
2436 // acceptable.
2437 return false;
2438 case llvm::Triple::arm:
2439 case llvm::Triple::armeb:
2440 case llvm::Triple::thumb:
2441 case llvm::Triple::thumbeb:
2442 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2443 case llvm::Triple::aarch64:
2444 case llvm::Triple::aarch64_32:
2445 case llvm::Triple::aarch64_be:
2446 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2447 case llvm::Triple::bpfeb:
2448 case llvm::Triple::bpfel:
2449 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2450 case llvm::Triple::dxil:
2451 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2452 case llvm::Triple::hexagon:
2453 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2454 case llvm::Triple::mips:
2455 case llvm::Triple::mipsel:
2456 case llvm::Triple::mips64:
2457 case llvm::Triple::mips64el:
2458 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2459 case llvm::Triple::spirv:
2460 case llvm::Triple::spirv32:
2461 case llvm::Triple::spirv64:
2462 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2463 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2464 return false;
2465 case llvm::Triple::systemz:
2466 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2467 case llvm::Triple::x86:
2468 case llvm::Triple::x86_64:
2469 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2470 case llvm::Triple::ppc:
2471 case llvm::Triple::ppcle:
2472 case llvm::Triple::ppc64:
2473 case llvm::Triple::ppc64le:
2474 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2475 case llvm::Triple::amdgpu:
2476 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(TI, BuiltinID, TheCall);
2477 case llvm::Triple::riscv32:
2478 case llvm::Triple::riscv64:
2479 case llvm::Triple::riscv32be:
2480 case llvm::Triple::riscv64be:
2481 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2482 case llvm::Triple::loongarch32:
2483 case llvm::Triple::loongarch64:
2484 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2485 TheCall);
2486 case llvm::Triple::wasm32:
2487 case llvm::Triple::wasm64:
2488 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2489 case llvm::Triple::nvptx:
2490 case llvm::Triple::nvptx64:
2491 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2492 }
2493}
2494
2496 return T->isDependentType() ||
2497 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2498}
2499
2500// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2501// not a valid type, emit an error message and return true. Otherwise return
2502// false.
2503static bool
2506 int ArgOrdinal) {
2507 clang::QualType EltTy =
2508 ArgTy->isVectorType() ? ArgTy->getAs<VectorType>()->getElementType()
2509 : ArgTy->isMatrixType() ? ArgTy->getAs<MatrixType>()->getElementType()
2510 : ArgTy;
2511
2512 switch (ArgTyRestr) {
2514 if (!ArgTy->getAs<VectorType>() && !ArgTy->getAs<MatrixType>() &&
2515 !isValidMathElementType(ArgTy)) {
2516 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2517 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2518 << ArgTy;
2519 }
2520 break;
2522 if (!EltTy->isRealFloatingType()) {
2523 // FIXME: make diagnostic's wording correct for matrices
2524 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2525 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2526 << /* floating-point */ 1 << ArgTy;
2527 }
2528 break;
2530 if (!EltTy->isIntegerType()) {
2531 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2532 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2533 << /* no fp */ 0 << ArgTy;
2534 }
2535 break;
2537 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2538 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2539 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2540 << /* or fp */ 1 << ArgTy;
2541 }
2542 break;
2543 }
2544
2545 return false;
2546}
2547
2548/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2549/// This checks that the target supports the builtin and that the string
2550/// argument is constant and valid.
2551static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2552 const TargetInfo *AuxTI, unsigned BuiltinID) {
2553 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2554 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2555 "Expecting __builtin_cpu_...");
2556
2557 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2558 const TargetInfo *TheTI = &TI;
2559 auto SupportsBI = [=](const TargetInfo *TInfo) {
2560 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2561 (!IsCPUSupports && TInfo->supportsCpuIs()));
2562 };
2563 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2564 TheTI = AuxTI;
2565
2566 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2567 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2568 return S.Diag(TheCall->getBeginLoc(),
2569 TI.getTriple().isOSAIX()
2570 ? diag::err_builtin_aix_os_unsupported
2571 : diag::err_builtin_target_unsupported)
2572 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2573
2574 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2575 // Check if the argument is a string literal.
2576 if (!isa<StringLiteral>(Arg))
2577 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2578 << Arg->getSourceRange();
2579
2580 // Check the contents of the string.
2581 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2582 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2583 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2584 << Arg->getSourceRange();
2585 return false;
2586 }
2587 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2588 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2589 << Arg->getSourceRange();
2590 return false;
2591}
2592
2593/// Checks that __builtin_bswapg was called with a single argument, which is an
2594/// unsigned integer, and overrides the return value type to the integer type.
2595static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2596 if (S.checkArgCount(TheCall, 1))
2597 return true;
2598 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2599 if (ArgRes.isInvalid())
2600 return true;
2601
2602 Expr *Arg = ArgRes.get();
2603 TheCall->setArg(0, Arg);
2604 if (Arg->isTypeDependent())
2605 return false;
2606
2607 QualType ArgTy = Arg->getType();
2608
2609 if (!ArgTy->isIntegerType()) {
2610 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2611 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2612 << ArgTy;
2613 return true;
2614 }
2615 if (const auto *BT = dyn_cast<BitIntType>(ArgTy)) {
2616 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2617 BT->getNumBits() != 1) {
2618 S.Diag(Arg->getBeginLoc(), diag::err_bswapg_invalid_bit_width)
2619 << ArgTy << BT->getNumBits();
2620 return true;
2621 }
2622 }
2623 TheCall->setType(ArgTy);
2624 return false;
2625}
2626
2627/// Checks that __builtin_bitreverseg was called with a single argument, which
2628/// is an integer
2629static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2630 if (S.checkArgCount(TheCall, 1))
2631 return true;
2632 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2633 if (ArgRes.isInvalid())
2634 return true;
2635
2636 Expr *Arg = ArgRes.get();
2637 TheCall->setArg(0, Arg);
2638 if (Arg->isTypeDependent())
2639 return false;
2640
2641 QualType ArgTy = Arg->getType();
2642
2643 if (!ArgTy->isIntegerType()) {
2644 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2645 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2646 << ArgTy;
2647 return true;
2648 }
2649 TheCall->setType(ArgTy);
2650 return false;
2651}
2652
2653/// Checks that __builtin_popcountg was called with a single argument, which is
2654/// an unsigned integer.
2655static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2656 if (S.checkArgCount(TheCall, 1))
2657 return true;
2658
2659 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2660 if (ArgRes.isInvalid())
2661 return true;
2662
2663 Expr *Arg = ArgRes.get();
2664 TheCall->setArg(0, Arg);
2665
2666 QualType ArgTy = Arg->getType();
2667
2668 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2669 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2670 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2671 << ArgTy;
2672 return true;
2673 }
2674 return false;
2675}
2676
2677/// Checks the __builtin_stdc_* builtins that take a single unsigned integer
2678/// argument and return either int, bool, or the argument type.
2679static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall,
2680 QualType ReturnType) {
2681 if (S.checkArgCount(TheCall, 1))
2682 return true;
2683
2684 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2685 if (ArgRes.isInvalid())
2686 return true;
2687
2688 Expr *Arg = ArgRes.get();
2689 TheCall->setArg(0, Arg);
2690
2691 QualType ArgTy = Arg->getType();
2692 // C23 stdbit.h functions do not permit bool or enumeration types.
2693 if (ArgTy->isBooleanType() || ArgTy->isEnumeralType())
2694 return S.Diag(Arg->getBeginLoc(),
2695 diag::err_builtin_stdc_invalid_arg_type_bool_or_enum)
2696 << 1 /*1st argument*/ << ArgTy;
2697 if (!ArgTy->isUnsignedIntegerType())
2698 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_invalid_arg_type)
2699 << 1 /*1st argument*/ << ArgTy;
2700
2701 // For builtins returning unsigned int, verify the argument's bit width fits.
2702 // On targets where unsigned int is 16 bits, a large _BitInt argument could
2703 // produce a count that overflows the return type.
2704 if (!ReturnType.isNull() && ReturnType == S.Context.UnsignedIntTy) {
2705 uint64_t ArgWidth = S.Context.getIntWidth(ArgTy);
2706 uint64_t ReturnTypeWidth = S.Context.getIntWidth(S.Context.UnsignedIntTy);
2707 if (!llvm::isUIntN(ReturnTypeWidth, ArgWidth))
2708 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_result_overflow)
2709 << ArgTy;
2710 }
2711
2712 TheCall->setType(ReturnType.isNull() ? ArgTy : ReturnType);
2713 return false;
2714}
2715
2716/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2717/// an unsigned integer, and an optional second argument, which is promoted to
2718/// an 'int'.
2719static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2720 if (S.checkArgCountRange(TheCall, 1, 2))
2721 return true;
2722
2723 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2724 if (Arg0Res.isInvalid())
2725 return true;
2726
2727 Expr *Arg0 = Arg0Res.get();
2728 TheCall->setArg(0, Arg0);
2729
2730 QualType Arg0Ty = Arg0->getType();
2731
2732 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2733 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2734 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2735 << Arg0Ty;
2736 return true;
2737 }
2738
2739 if (TheCall->getNumArgs() > 1) {
2740 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2741 if (Arg1Res.isInvalid())
2742 return true;
2743
2744 Expr *Arg1 = Arg1Res.get();
2745 TheCall->setArg(1, Arg1);
2746
2747 QualType Arg1Ty = Arg1->getType();
2748
2749 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2750 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2751 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2752 return true;
2753 }
2754 }
2755
2756 return false;
2757}
2758
2760 unsigned ArgIndex;
2761 bool OnlyUnsigned;
2762
2764 QualType T) {
2765 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2766 << ArgIndex << /*scalar*/ 1
2767 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2768 << /*no fp*/ 0 << T;
2769 }
2770
2771public:
2772 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2773 : ContextualImplicitConverter(/*Suppress=*/false,
2774 /*SuppressConversion=*/true),
2775 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2776
2777 bool match(QualType T) override {
2778 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2779 }
2780
2782 QualType T) override {
2783 return emitError(S, Loc, T);
2784 }
2785
2787 QualType T) override {
2788 return emitError(S, Loc, T);
2789 }
2790
2792 QualType T,
2793 QualType ConvTy) override {
2794 return emitError(S, Loc, T);
2795 }
2796
2798 QualType ConvTy) override {
2799 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2800 }
2801
2803 QualType T) override {
2804 return emitError(S, Loc, T);
2805 }
2806
2808 QualType ConvTy) override {
2809 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2810 }
2811
2813 QualType T,
2814 QualType ConvTy) override {
2815 llvm_unreachable("conversion functions are permitted");
2816 }
2817};
2818
2819/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2820/// arguments, that the first argument is an unsigned integer type, and that
2821/// the second argument is an integer type.
2822static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2823 if (S.checkArgCount(TheCall, 2))
2824 return true;
2825
2826 // First argument (value to rotate) must be unsigned integer type.
2827 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2829 TheCall->getArg(0)->getBeginLoc(), TheCall->getArg(0), Arg0Converter);
2830 if (Arg0Res.isInvalid())
2831 return true;
2832
2833 Expr *Arg0 = Arg0Res.get();
2834 TheCall->setArg(0, Arg0);
2835
2836 QualType Arg0Ty = Arg0->getType();
2837 if (!Arg0Ty->isUnsignedIntegerType())
2838 return true;
2839
2840 // Second argument (rotation count) must be integer type.
2841 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2843 TheCall->getArg(1)->getBeginLoc(), TheCall->getArg(1), Arg1Converter);
2844 if (Arg1Res.isInvalid())
2845 return true;
2846
2847 Expr *Arg1 = Arg1Res.get();
2848 TheCall->setArg(1, Arg1);
2849
2850 QualType Arg1Ty = Arg1->getType();
2851 if (!Arg1Ty->isIntegerType())
2852 return true;
2853
2854 TheCall->setType(Arg0Ty);
2855 return false;
2856}
2857
2858static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2859 unsigned Pos, bool AllowConst,
2860 bool AllowAS) {
2861 QualType MaskTy = MaskArg->getType();
2862 if (!MaskTy->isExtVectorBoolType())
2863 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2864 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2865 << MaskTy;
2866
2867 QualType PtrTy = PtrArg->getType();
2868 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2869 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2870 << Pos << "scalar pointer";
2871
2872 QualType PointeeTy = PtrTy->getPointeeType();
2873 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2874 (!AllowConst && PointeeTy.isConstQualified()) ||
2875 (!AllowAS && PointeeTy.hasAddressSpace())) {
2878 return S.Diag(PtrArg->getExprLoc(),
2879 diag::err_typecheck_convert_incompatible)
2880 << PtrTy << Target << /*different qualifiers=*/5
2881 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2882 << PtrTy << Target;
2883 }
2884 return false;
2885}
2886
2887static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2888 bool TypeDependent = false;
2889 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2890 ExprResult Converted =
2892 if (Converted.isInvalid())
2893 return true;
2894 TheCall->setArg(Arg, Converted.get());
2895 TypeDependent |= Converted.get()->isTypeDependent();
2896 }
2897
2898 if (TypeDependent)
2899 TheCall->setType(S.Context.DependentTy);
2900 return false;
2901}
2902
2904 if (S.checkArgCountRange(TheCall, 2, 3))
2905 return ExprError();
2906
2907 if (ConvertMaskedBuiltinArgs(S, TheCall))
2908 return ExprError();
2909
2910 Expr *MaskArg = TheCall->getArg(0);
2911 Expr *PtrArg = TheCall->getArg(1);
2912 if (TheCall->isTypeDependent())
2913 return TheCall;
2914
2915 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2916 TheCall->getBuiltinCallee() ==
2917 Builtin::BI__builtin_masked_load))
2918 return ExprError();
2919
2920 QualType MaskTy = MaskArg->getType();
2921 QualType PtrTy = PtrArg->getType();
2922 QualType PointeeTy = PtrTy->getPointeeType();
2923 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2924
2926 MaskVecTy->getNumElements());
2927 if (TheCall->getNumArgs() == 3) {
2928 Expr *PassThruArg = TheCall->getArg(2);
2929 QualType PassThruTy = PassThruArg->getType();
2930 if (!S.Context.hasSameType(PassThruTy, RetTy))
2931 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2932 << /* third argument */ 3 << RetTy;
2933 }
2934
2935 TheCall->setType(RetTy);
2936 return TheCall;
2937}
2938
2940 if (S.checkArgCount(TheCall, 3))
2941 return ExprError();
2942
2943 if (ConvertMaskedBuiltinArgs(S, TheCall))
2944 return ExprError();
2945
2946 Expr *MaskArg = TheCall->getArg(0);
2947 Expr *ValArg = TheCall->getArg(1);
2948 Expr *PtrArg = TheCall->getArg(2);
2949 if (TheCall->isTypeDependent())
2950 return TheCall;
2951
2952 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2953 TheCall->getBuiltinCallee() ==
2954 Builtin::BI__builtin_masked_store))
2955 return ExprError();
2956
2957 QualType MaskTy = MaskArg->getType();
2958 QualType PtrTy = PtrArg->getType();
2959 QualType ValTy = ValArg->getType();
2960 if (!ValTy->isVectorType())
2961 return ExprError(
2962 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2963 << 2 << "vector");
2964
2965 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2966 const VectorType *ValVecTy = ValTy->getAs<VectorType>();
2967
2968 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements()) {
2969 return ExprError(
2970 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2972 TheCall->getBuiltinCallee())
2973 << MaskTy << ValTy);
2974 }
2975
2976 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
2977 PtrTy->getPointeeType().getUnqualifiedType()))
2978 return ExprError(S.Diag(TheCall->getBeginLoc(),
2979 diag::err_vec_builtin_incompatible_vector)
2980 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2981 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2982 TheCall->getArg(1)->getEndLoc()));
2983
2984 TheCall->setType(S.Context.VoidTy);
2985 return TheCall;
2986}
2987
2989 if (S.checkArgCountRange(TheCall, 3, 4))
2990 return ExprError();
2991
2992 if (ConvertMaskedBuiltinArgs(S, TheCall))
2993 return ExprError();
2994
2995 Expr *MaskArg = TheCall->getArg(0);
2996 Expr *IdxArg = TheCall->getArg(1);
2997 Expr *PtrArg = TheCall->getArg(2);
2998 if (TheCall->isTypeDependent())
2999 return TheCall;
3000
3001 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
3002 /*AllowAS=*/true))
3003 return ExprError();
3004
3005 QualType IdxTy = IdxArg->getType();
3006 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
3007 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
3008 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3009 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
3010 << IdxTy;
3011
3012 QualType MaskTy = MaskArg->getType();
3013 QualType PtrTy = PtrArg->getType();
3014 QualType PointeeTy = PtrTy->getPointeeType();
3015 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
3016 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
3017 return ExprError(
3018 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
3020 TheCall->getBuiltinCallee())
3021 << MaskTy << IdxTy);
3022
3024 MaskVecTy->getNumElements());
3025 if (TheCall->getNumArgs() == 4) {
3026 Expr *PassThruArg = TheCall->getArg(3);
3027 QualType PassThruTy = PassThruArg->getType();
3028 if (!S.Context.hasSameType(PassThruTy, RetTy))
3029 return S.Diag(PassThruArg->getExprLoc(),
3030 diag::err_vec_masked_load_store_ptr)
3031 << /* fourth argument */ 4 << RetTy;
3032 }
3033
3034 TheCall->setType(RetTy);
3035 return TheCall;
3036}
3037
3039 if (S.checkArgCount(TheCall, 4))
3040 return ExprError();
3041
3042 if (ConvertMaskedBuiltinArgs(S, TheCall))
3043 return ExprError();
3044
3045 Expr *MaskArg = TheCall->getArg(0);
3046 Expr *IdxArg = TheCall->getArg(1);
3047 Expr *ValArg = TheCall->getArg(2);
3048 Expr *PtrArg = TheCall->getArg(3);
3049 if (TheCall->isTypeDependent())
3050 return TheCall;
3051
3052 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
3053 /*AllowAS=*/true))
3054 return ExprError();
3055
3056 QualType IdxTy = IdxArg->getType();
3057 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
3058 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
3059 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3060 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
3061 << IdxTy;
3062
3063 QualType ValTy = ValArg->getType();
3064 QualType MaskTy = MaskArg->getType();
3065 QualType PtrTy = PtrArg->getType();
3066
3067 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
3068 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
3069 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
3070 return ExprError(
3071 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
3073 TheCall->getBuiltinCallee())
3074 << MaskTy << IdxTy);
3075 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
3076 return ExprError(
3077 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
3079 TheCall->getBuiltinCallee())
3080 << MaskTy << ValTy);
3081
3082 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
3083 PtrTy->getPointeeType().getUnqualifiedType()))
3084 return ExprError(S.Diag(TheCall->getBeginLoc(),
3085 diag::err_vec_builtin_incompatible_vector)
3086 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
3087 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
3088 TheCall->getArg(1)->getEndLoc()));
3089
3090 TheCall->setType(S.Context.VoidTy);
3091 return TheCall;
3092}
3093
3095 SourceLocation Loc = TheCall->getBeginLoc();
3096 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
3097 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
3098
3099 if (Args.size() == 0) {
3100 S.Diag(TheCall->getBeginLoc(),
3101 diag::err_typecheck_call_too_few_args_at_least)
3102 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
3103 << /*is_non_object=*/0 << TheCall->getSourceRange();
3104 return ExprError();
3105 }
3106
3107 QualType FuncT = Args[0]->getType();
3108
3109 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
3110 if (Args.size() < 2) {
3111 S.Diag(TheCall->getBeginLoc(),
3112 diag::err_typecheck_call_too_few_args_at_least)
3113 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
3114 << /*is_non_object=*/0 << TheCall->getSourceRange();
3115 return ExprError();
3116 }
3117
3118 const Type *MemPtrClass = MPT->getQualifier().getAsType();
3119 QualType ObjectT = Args[1]->getType();
3120
3121 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
3122 return ExprError();
3123
3124 ExprResult ObjectArg = [&]() -> ExprResult {
3125 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
3126 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
3127 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
3128 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
3129 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
3130 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
3131 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
3132 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
3133 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
3134 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
3135 return Args[1];
3136 }
3137
3138 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
3139 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
3140 // reference_wrapper;
3141 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
3142 if (RD->isInStdNamespace() &&
3143 RD->getDeclName().getAsString() == "reference_wrapper") {
3144 CXXScopeSpec SS;
3145 IdentifierInfo *GetName = &S.Context.Idents.get("get");
3146 UnqualifiedId GetID;
3147 GetID.setIdentifier(GetName, Loc);
3148
3150 S.getCurScope(), Args[1], Loc, tok::period, SS,
3151 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
3152
3153 if (MemExpr.isInvalid())
3154 return ExprError();
3155
3156 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
3157 }
3158 }
3159
3160 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
3161 // class T and t1 does not satisfy the previous two items;
3162
3163 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
3164 }();
3165
3166 if (ObjectArg.isInvalid())
3167 return ExprError();
3168
3169 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
3170 tok::periodstar, ObjectArg.get(), Args[0]);
3171 if (BinOp.isInvalid())
3172 return ExprError();
3173
3174 if (MPT->isMemberDataPointer())
3175 return BinOp;
3176
3177 // Give the synthesized expression a valid source range for diagnostics.
3178 auto *MemCall = new (S.Context)
3179 ParenExpr(TheCall->getBeginLoc(), TheCall->getRParenLoc(), BinOp.get());
3180
3181 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
3182 Args.drop_front(2), TheCall->getRParenLoc());
3183 }
3184 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
3185 Args.drop_front(), TheCall->getRParenLoc());
3186}
3187
3188// Performs a similar job to Sema::UsualUnaryConversions, but without any
3189// implicit promotion of integral/enumeration types.
3191 // First, convert to an r-value.
3193 if (Res.isInvalid())
3194 return ExprError();
3195
3196 // Promote floating-point types.
3197 return S.UsualUnaryFPConversions(Res.get());
3198}
3199
3201 if (const auto *TyA = VecTy->getAs<VectorType>())
3202 return TyA->getElementType();
3203 if (VecTy->isSizelessVectorType())
3204 return VecTy->getSizelessVectorEltType(Context);
3205 return QualType();
3206}
3207
3209 unsigned ArgNum,
3210 const llvm::APSInt &Result, int Low,
3211 int High, bool RangeIsError) {
3213 return false;
3214
3215 // We can't check the value of a dependent argument.
3216 Expr *Arg = TheCall->getArg(ArgNum);
3217 if (Arg->isTypeDependent() || Arg->isValueDependent())
3218 return false;
3219
3220 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
3221 if (RangeIsError) {
3222 return S.Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
3223 << toString(Result, 10) << Low << High << Arg->getSourceRange();
3224 }
3225
3226 // Defer the warning until we know if the code will be emitted so that
3227 // dead code can ignore this.
3228 S.DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
3229 S.PDiag(diag::warn_argument_invalid_range)
3230 << toString(Result, 10) << Low << High
3231 << Arg->getSourceRange());
3232 }
3233
3234 return false;
3235}
3236
3238Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
3239 CallExpr *TheCall) {
3240 ExprResult TheCallResult(TheCall);
3241
3242 // Find out if any arguments are required to be integer constant expressions.
3243 unsigned ICEArguments = 0;
3245 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
3246 SmallVector<Builtin::Context::ArgRange, 2> ArgRanges;
3248 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
3249 else if (ICEArguments)
3250 Context.BuiltinInfo.getArgRanges(BuiltinID, ArgRanges);
3251
3252 // If any arguments are required to be ICE's, check and diagnose.
3253 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
3254 // Skip arguments not required to be ICE's.
3255 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
3256
3257 ICEArguments &= ~(1 << ArgNo);
3258
3259 // If we don't have enough arguments, continue so we can issue better
3260 // diagnostic in checkArgCount(...)
3261 if (ArgNo >= TheCall->getNumArgs())
3262 continue;
3263
3264 llvm::APSInt Result;
3265 if (BuiltinConstantArg(TheCall, ArgNo, Result))
3266 return true;
3267
3268 for (const Builtin::Context::ArgRange &Range : ArgRanges) {
3269 if (Range.Index == ArgNo &&
3270 checkConstantArgValueRange(*this, TheCall, ArgNo, Result, Range.Lower,
3271 Range.Upper - 1,
3272 /*RangeIsError=*/true))
3273 return true;
3274 }
3275 }
3276
3277 FPOptions FPO;
3278 switch (BuiltinID) {
3279 case Builtin::BI__builtin___get_unsafe_stack_start:
3280 case Builtin::BI__builtin___get_unsafe_stack_bottom:
3281 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3282 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3283 << "__safestack_get_unsafe_stack_bottom";
3284 break;
3285 case Builtin::BI__builtin___get_unsafe_stack_top:
3286 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3287 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3288 << "__safestack_get_unsafe_stack_top";
3289 break;
3290 case Builtin::BI__builtin___get_unsafe_stack_ptr:
3291 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3292 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3293 << "__safestack_get_unsafe_stack_ptr";
3294 break;
3295 case Builtin::BI__builtin_cpu_supports:
3296 case Builtin::BI__builtin_cpu_is:
3297 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
3298 Context.getAuxTargetInfo(), BuiltinID))
3299 return ExprError();
3300 break;
3301 case Builtin::BI__builtin_cpu_init:
3302 if (!Context.getTargetInfo().supportsCpuInit()) {
3303 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
3304 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
3305 return ExprError();
3306 }
3307 break;
3308 case Builtin::BI__builtin___CFStringMakeConstantString:
3309 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
3310 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
3312 *this, BuiltinID, TheCall,
3313 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
3314 return ExprError();
3315 assert(TheCall->getNumArgs() == 1 &&
3316 "Wrong # arguments to builtin CFStringMakeConstantString");
3317 if (ObjC().CheckObjCString(TheCall->getArg(0)))
3318 return ExprError();
3319 break;
3320 case Builtin::BI__builtin_ms_va_start:
3321 case Builtin::BI__builtin_zos_va_start:
3322 case Builtin::BI__builtin_stdarg_start:
3323 case Builtin::BI__builtin_va_start:
3324 case Builtin::BI__builtin_c23_va_start:
3325 if (BuiltinVAStart(BuiltinID, TheCall))
3326 return ExprError();
3327 break;
3328 case Builtin::BI__va_start: {
3329 switch (Context.getTargetInfo().getTriple().getArch()) {
3330 case llvm::Triple::aarch64:
3331 case llvm::Triple::arm:
3332 case llvm::Triple::thumb:
3333 if (BuiltinVAStartARMMicrosoft(TheCall))
3334 return ExprError();
3335 break;
3336 default:
3337 if (BuiltinVAStart(BuiltinID, TheCall))
3338 return ExprError();
3339 break;
3340 }
3341 break;
3342 }
3343
3344 // The acquire, release, and no fence variants are ARM and AArch64 only.
3345 case Builtin::BI_interlockedbittestandset_acq:
3346 case Builtin::BI_interlockedbittestandset_rel:
3347 case Builtin::BI_interlockedbittestandset_nf:
3348 case Builtin::BI_interlockedbittestandreset_acq:
3349 case Builtin::BI_interlockedbittestandreset_rel:
3350 case Builtin::BI_interlockedbittestandreset_nf:
3352 *this, TheCall,
3353 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
3354 return ExprError();
3355 break;
3356
3357 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
3358 case Builtin::BI_bittest64:
3359 case Builtin::BI_bittestandcomplement64:
3360 case Builtin::BI_bittestandreset64:
3361 case Builtin::BI_bittestandset64:
3362 case Builtin::BI_interlockedbittestandreset64:
3363 case Builtin::BI_interlockedbittestandset64:
3365 *this, TheCall,
3366 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
3367 llvm::Triple::aarch64, llvm::Triple::amdgpu}))
3368 return ExprError();
3369 break;
3370
3371 // The 64-bit acquire, release, and no fence variants are AArch64 only.
3372 case Builtin::BI_interlockedbittestandreset64_acq:
3373 case Builtin::BI_interlockedbittestandreset64_rel:
3374 case Builtin::BI_interlockedbittestandreset64_nf:
3375 case Builtin::BI_interlockedbittestandset64_acq:
3376 case Builtin::BI_interlockedbittestandset64_rel:
3377 case Builtin::BI_interlockedbittestandset64_nf:
3378 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
3379 return ExprError();
3380 break;
3381
3382 case Builtin::BI__builtin_set_flt_rounds:
3384 *this, TheCall,
3385 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
3386 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgpu,
3387 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
3388 llvm::Triple::ppc64le}))
3389 return ExprError();
3390 break;
3391
3392 case Builtin::BI__builtin_isgreater:
3393 case Builtin::BI__builtin_isgreaterequal:
3394 case Builtin::BI__builtin_isless:
3395 case Builtin::BI__builtin_islessequal:
3396 case Builtin::BI__builtin_islessgreater:
3397 case Builtin::BI__builtin_isunordered:
3398 case Builtin::BI__builtin_iseqsig:
3399 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
3400 return ExprError();
3401 break;
3402 case Builtin::BI__builtin_fpclassify:
3403 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
3404 return ExprError();
3405 break;
3406 case Builtin::BI__builtin_isfpclass:
3407 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
3408 return ExprError();
3409 break;
3410 case Builtin::BI__builtin_isfinite:
3411 case Builtin::BI__builtin_isinf:
3412 case Builtin::BI__builtin_isinf_sign:
3413 case Builtin::BI__builtin_isnan:
3414 case Builtin::BI__builtin_issignaling:
3415 case Builtin::BI__builtin_isnormal:
3416 case Builtin::BI__builtin_issubnormal:
3417 case Builtin::BI__builtin_iszero:
3418 case Builtin::BI__builtin_signbit:
3419 case Builtin::BI__builtin_signbitf:
3420 case Builtin::BI__builtin_signbitl:
3421 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
3422 return ExprError();
3423 break;
3424 case Builtin::BI__builtin_shufflevector:
3425 return BuiltinShuffleVector(TheCall);
3426 // TheCall will be freed by the smart pointer here, but that's fine, since
3427 // BuiltinShuffleVector guts it, but then doesn't release it.
3428 case Builtin::BI__builtin_masked_load:
3429 case Builtin::BI__builtin_masked_expand_load:
3430 return BuiltinMaskedLoad(*this, TheCall);
3431 case Builtin::BI__builtin_masked_store:
3432 case Builtin::BI__builtin_masked_compress_store:
3433 return BuiltinMaskedStore(*this, TheCall);
3434 case Builtin::BI__builtin_masked_gather:
3435 return BuiltinMaskedGather(*this, TheCall);
3436 case Builtin::BI__builtin_masked_scatter:
3437 return BuiltinMaskedScatter(*this, TheCall);
3438 case Builtin::BI__builtin_invoke:
3439 return BuiltinInvoke(*this, TheCall);
3440 case Builtin::BI__builtin_prefetch:
3441 if (BuiltinPrefetch(TheCall))
3442 return ExprError();
3443 break;
3444 case Builtin::BI__builtin_alloca_with_align:
3445 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3446 if (BuiltinAllocaWithAlign(TheCall))
3447 return ExprError();
3448 [[fallthrough]];
3449 case Builtin::BI__builtin_alloca:
3450 case Builtin::BI__builtin_alloca_uninitialized:
3451 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
3452 << TheCall->getDirectCallee();
3453 if (getLangOpts().OpenCL) {
3454 builtinAllocaAddrSpace(*this, TheCall);
3455 }
3456 break;
3457 case Builtin::BI__builtin_infer_alloc_token:
3458 if (checkBuiltinInferAllocToken(*this, TheCall))
3459 return ExprError();
3460 break;
3461 case Builtin::BI__arithmetic_fence:
3462 if (BuiltinArithmeticFence(TheCall))
3463 return ExprError();
3464 break;
3465 case Builtin::BI__assume:
3466 case Builtin::BI__builtin_assume:
3467 if (BuiltinAssume(TheCall))
3468 return ExprError();
3469 break;
3470 case Builtin::BI__builtin_assume_aligned:
3471 if (BuiltinAssumeAligned(TheCall))
3472 return ExprError();
3473 break;
3474 case Builtin::BI__builtin_dynamic_object_size:
3475 case Builtin::BI__builtin_object_size:
3476 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
3477 return ExprError();
3478 break;
3479 case Builtin::BI__builtin_longjmp:
3480 if (BuiltinLongjmp(TheCall))
3481 return ExprError();
3482 break;
3483 case Builtin::BI__builtin_setjmp:
3484 if (BuiltinSetjmp(TheCall))
3485 return ExprError();
3486 break;
3487 case Builtin::BI__builtin_complex:
3488 if (BuiltinComplex(TheCall))
3489 return ExprError();
3490 break;
3491 case Builtin::BI__builtin_classify_type:
3492 case Builtin::BI__builtin_constant_p: {
3493 if (checkArgCount(TheCall, 1))
3494 return true;
3496 if (Arg.isInvalid()) return true;
3497 TheCall->setArg(0, Arg.get());
3498 TheCall->setType(Context.IntTy);
3499 break;
3500 }
3501 case Builtin::BI__builtin_launder:
3502 return BuiltinLaunder(*this, TheCall);
3503 case Builtin::BI__builtin_is_within_lifetime:
3504 return BuiltinIsWithinLifetime(*this, TheCall);
3505 case Builtin::BI__builtin_trivially_relocate:
3506 return BuiltinTriviallyRelocate(*this, TheCall);
3507 case Builtin::BI__builtin_clear_padding: {
3508 if (checkArgCount(TheCall, 1))
3509 return ExprError();
3510
3511 const Expr *PtrArg = TheCall->getArg(0);
3512 const QualType PtrArgType = PtrArg->getType();
3513 if (!PtrArgType->isPointerType()) {
3514 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
3515 << PtrArgType << "pointer" << 1 << 0 << 3 << 1 << PtrArgType
3516 << "pointer";
3517 return ExprError();
3518 }
3519 QualType PointeeType = PtrArgType->getPointeeType();
3520 if (PointeeType.isConstQualified()) {
3521 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_assign_const)
3522 << TheCall->getSourceRange() << 4 /*ConstUnknown*/;
3523 return ExprError();
3524 }
3525 if (RequireCompleteType(PtrArg->getBeginLoc(), PointeeType,
3526 diag::err_typecheck_decl_incomplete_type))
3527 return ExprError();
3528
3529 // For non trivially copyable types, we try to match gcc's behaviour.
3530 // i.e. __builtin_clear_padding(&var) is OK as long as var is a complete
3531 // object, either a local variable or a function parameter passed by value
3532 auto IsAddrOfDeclExpr = [&]() {
3533 const Expr *Inner = PtrArg->IgnoreParenNoopCasts(Context);
3534 const auto *UnaryOp = dyn_cast<UnaryOperator>(Inner);
3535 if (!UnaryOp || UnaryOp->getOpcode() != UO_AddrOf)
3536 return false;
3537
3538 const Expr *Operand =
3539 UnaryOp->getSubExpr()->IgnoreParenNoopCasts(Context);
3540 const auto *DeclRef = dyn_cast<DeclRefExpr>(Operand);
3541 if (!DeclRef)
3542 return false;
3543
3544 const auto *VarDecl = dyn_cast<::clang::VarDecl>(DeclRef->getDecl());
3545 if (!VarDecl || VarDecl->getType()->isReferenceType())
3546 return false;
3547
3548 // matching GCC behaviour
3549 // __builtin_clear_padding((X*)&var) is fine as long X is the type of var
3550 QualType VarQType = VarDecl->getType();
3551 return PointeeType.getTypePtr() == VarQType.getTypePtr() ||
3552 Context.hasSameUnqualifiedType(PointeeType, VarQType);
3553 };
3554
3555 if (!PointeeType.isTriviallyCopyableType(Context) &&
3556 !PointeeType->isAtomicType() // _Atomic is not copyable
3557 && !IsAddrOfDeclExpr()) {
3558 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_needs_trivial_copy)
3559 << PtrArg->getType() << PtrArg->getSourceRange();
3560 return ExprError();
3561 }
3562
3563 if (auto *Record = PointeeType->getAsRecordDecl();
3565 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_no_flexible_array)
3566 << PointeeType << PtrArg->getSourceRange();
3567 return ExprError();
3568 }
3569
3570 break;
3571 }
3572 case Builtin::BI__sync_fetch_and_add:
3573 case Builtin::BI__sync_fetch_and_add_1:
3574 case Builtin::BI__sync_fetch_and_add_2:
3575 case Builtin::BI__sync_fetch_and_add_4:
3576 case Builtin::BI__sync_fetch_and_add_8:
3577 case Builtin::BI__sync_fetch_and_add_16:
3578 case Builtin::BI__sync_fetch_and_sub:
3579 case Builtin::BI__sync_fetch_and_sub_1:
3580 case Builtin::BI__sync_fetch_and_sub_2:
3581 case Builtin::BI__sync_fetch_and_sub_4:
3582 case Builtin::BI__sync_fetch_and_sub_8:
3583 case Builtin::BI__sync_fetch_and_sub_16:
3584 case Builtin::BI__sync_fetch_and_or:
3585 case Builtin::BI__sync_fetch_and_or_1:
3586 case Builtin::BI__sync_fetch_and_or_2:
3587 case Builtin::BI__sync_fetch_and_or_4:
3588 case Builtin::BI__sync_fetch_and_or_8:
3589 case Builtin::BI__sync_fetch_and_or_16:
3590 case Builtin::BI__sync_fetch_and_and:
3591 case Builtin::BI__sync_fetch_and_and_1:
3592 case Builtin::BI__sync_fetch_and_and_2:
3593 case Builtin::BI__sync_fetch_and_and_4:
3594 case Builtin::BI__sync_fetch_and_and_8:
3595 case Builtin::BI__sync_fetch_and_and_16:
3596 case Builtin::BI__sync_fetch_and_xor:
3597 case Builtin::BI__sync_fetch_and_xor_1:
3598 case Builtin::BI__sync_fetch_and_xor_2:
3599 case Builtin::BI__sync_fetch_and_xor_4:
3600 case Builtin::BI__sync_fetch_and_xor_8:
3601 case Builtin::BI__sync_fetch_and_xor_16:
3602 case Builtin::BI__sync_fetch_and_nand:
3603 case Builtin::BI__sync_fetch_and_nand_1:
3604 case Builtin::BI__sync_fetch_and_nand_2:
3605 case Builtin::BI__sync_fetch_and_nand_4:
3606 case Builtin::BI__sync_fetch_and_nand_8:
3607 case Builtin::BI__sync_fetch_and_nand_16:
3608 case Builtin::BI__sync_add_and_fetch:
3609 case Builtin::BI__sync_add_and_fetch_1:
3610 case Builtin::BI__sync_add_and_fetch_2:
3611 case Builtin::BI__sync_add_and_fetch_4:
3612 case Builtin::BI__sync_add_and_fetch_8:
3613 case Builtin::BI__sync_add_and_fetch_16:
3614 case Builtin::BI__sync_sub_and_fetch:
3615 case Builtin::BI__sync_sub_and_fetch_1:
3616 case Builtin::BI__sync_sub_and_fetch_2:
3617 case Builtin::BI__sync_sub_and_fetch_4:
3618 case Builtin::BI__sync_sub_and_fetch_8:
3619 case Builtin::BI__sync_sub_and_fetch_16:
3620 case Builtin::BI__sync_and_and_fetch:
3621 case Builtin::BI__sync_and_and_fetch_1:
3622 case Builtin::BI__sync_and_and_fetch_2:
3623 case Builtin::BI__sync_and_and_fetch_4:
3624 case Builtin::BI__sync_and_and_fetch_8:
3625 case Builtin::BI__sync_and_and_fetch_16:
3626 case Builtin::BI__sync_or_and_fetch:
3627 case Builtin::BI__sync_or_and_fetch_1:
3628 case Builtin::BI__sync_or_and_fetch_2:
3629 case Builtin::BI__sync_or_and_fetch_4:
3630 case Builtin::BI__sync_or_and_fetch_8:
3631 case Builtin::BI__sync_or_and_fetch_16:
3632 case Builtin::BI__sync_xor_and_fetch:
3633 case Builtin::BI__sync_xor_and_fetch_1:
3634 case Builtin::BI__sync_xor_and_fetch_2:
3635 case Builtin::BI__sync_xor_and_fetch_4:
3636 case Builtin::BI__sync_xor_and_fetch_8:
3637 case Builtin::BI__sync_xor_and_fetch_16:
3638 case Builtin::BI__sync_nand_and_fetch:
3639 case Builtin::BI__sync_nand_and_fetch_1:
3640 case Builtin::BI__sync_nand_and_fetch_2:
3641 case Builtin::BI__sync_nand_and_fetch_4:
3642 case Builtin::BI__sync_nand_and_fetch_8:
3643 case Builtin::BI__sync_nand_and_fetch_16:
3644 case Builtin::BI__sync_val_compare_and_swap:
3645 case Builtin::BI__sync_val_compare_and_swap_1:
3646 case Builtin::BI__sync_val_compare_and_swap_2:
3647 case Builtin::BI__sync_val_compare_and_swap_4:
3648 case Builtin::BI__sync_val_compare_and_swap_8:
3649 case Builtin::BI__sync_val_compare_and_swap_16:
3650 case Builtin::BI__sync_bool_compare_and_swap:
3651 case Builtin::BI__sync_bool_compare_and_swap_1:
3652 case Builtin::BI__sync_bool_compare_and_swap_2:
3653 case Builtin::BI__sync_bool_compare_and_swap_4:
3654 case Builtin::BI__sync_bool_compare_and_swap_8:
3655 case Builtin::BI__sync_bool_compare_and_swap_16:
3656 case Builtin::BI__sync_lock_test_and_set:
3657 case Builtin::BI__sync_lock_test_and_set_1:
3658 case Builtin::BI__sync_lock_test_and_set_2:
3659 case Builtin::BI__sync_lock_test_and_set_4:
3660 case Builtin::BI__sync_lock_test_and_set_8:
3661 case Builtin::BI__sync_lock_test_and_set_16:
3662 case Builtin::BI__sync_lock_release:
3663 case Builtin::BI__sync_lock_release_1:
3664 case Builtin::BI__sync_lock_release_2:
3665 case Builtin::BI__sync_lock_release_4:
3666 case Builtin::BI__sync_lock_release_8:
3667 case Builtin::BI__sync_lock_release_16:
3668 case Builtin::BI__sync_swap:
3669 case Builtin::BI__sync_swap_1:
3670 case Builtin::BI__sync_swap_2:
3671 case Builtin::BI__sync_swap_4:
3672 case Builtin::BI__sync_swap_8:
3673 case Builtin::BI__sync_swap_16:
3674 return BuiltinAtomicOverloaded(TheCallResult);
3675 case Builtin::BI__sync_synchronize:
3676 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
3677 << TheCall->getCallee()->getSourceRange();
3678 break;
3679 case Builtin::BI__builtin_nontemporal_load:
3680 case Builtin::BI__builtin_nontemporal_store:
3681 return BuiltinNontemporalOverloaded(TheCallResult);
3682 case Builtin::BI__builtin_memcpy_inline: {
3683 clang::Expr *SizeOp = TheCall->getArg(2);
3684 // We warn about copying to or from `nullptr` pointers when `size` is
3685 // greater than 0. When `size` is value dependent we cannot evaluate its
3686 // value so we bail out.
3687 if (SizeOp->isValueDependent())
3688 break;
3689 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
3690 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3691 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
3692 }
3693 break;
3694 }
3695 case Builtin::BI__builtin_memset_inline: {
3696 clang::Expr *SizeOp = TheCall->getArg(2);
3697 // We warn about filling to `nullptr` pointers when `size` is greater than
3698 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3699 // out.
3700 if (SizeOp->isValueDependent())
3701 break;
3702 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
3703 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3704 break;
3705 }
3706#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3707 case Builtin::BI##ID: \
3708 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3709#include "clang/Basic/Builtins.inc"
3710 case Builtin::BI__annotation: {
3711 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3712 if (!TT.isOSWindows() && !TT.isUEFI()) {
3713 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
3714 << TheCall->getSourceRange();
3715 return ExprError();
3716 }
3717 if (BuiltinMSVCAnnotation(*this, TheCall))
3718 return ExprError();
3719 break;
3720 }
3721 case Builtin::BI__builtin_annotation:
3722 if (BuiltinAnnotation(*this, TheCall))
3723 return ExprError();
3724 break;
3725 case Builtin::BI__builtin_addressof:
3726 if (BuiltinAddressof(*this, TheCall))
3727 return ExprError();
3728 break;
3729 case Builtin::BI__builtin_function_start:
3730 if (BuiltinFunctionStart(*this, TheCall))
3731 return ExprError();
3732 break;
3733 case Builtin::BI__builtin_is_aligned:
3734 case Builtin::BI__builtin_align_up:
3735 case Builtin::BI__builtin_align_down:
3736 if (BuiltinAlignment(*this, TheCall, BuiltinID))
3737 return ExprError();
3738 break;
3739 case Builtin::BI__builtin_add_overflow:
3740 case Builtin::BI__builtin_sub_overflow:
3741 case Builtin::BI__builtin_mul_overflow:
3742 if (BuiltinOverflow(*this, TheCall, BuiltinID))
3743 return ExprError();
3744 break;
3745 case Builtin::BI__builtin_operator_new:
3746 case Builtin::BI__builtin_operator_delete: {
3747 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3748 ExprResult Res =
3749 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3750 return Res;
3751 }
3752 case Builtin::BI__builtin_dump_struct:
3753 return BuiltinDumpStruct(*this, TheCall);
3754 case Builtin::BI__builtin_expect_with_probability: {
3755 // We first want to ensure we are called with 3 arguments
3756 if (checkArgCount(TheCall, 3))
3757 return ExprError();
3758 // then check probability is constant float in range [0.0, 1.0]
3759 const Expr *ProbArg = TheCall->getArg(2);
3760 SmallVector<PartialDiagnosticAt, 8> Notes;
3761 Expr::EvalResult Eval;
3762 Eval.Diag = &Notes;
3763 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3764 !Eval.Val.isFloat()) {
3765 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3766 << ProbArg->getSourceRange();
3767 for (const PartialDiagnosticAt &PDiag : Notes)
3768 Diag(PDiag.first, PDiag.second);
3769 return ExprError();
3770 }
3771 llvm::APFloat Probability = Eval.Val.getFloat();
3772 bool LoseInfo = false;
3773 Probability.convert(llvm::APFloat::IEEEdouble(),
3774 llvm::RoundingMode::Dynamic, &LoseInfo);
3775 if (!(Probability >= llvm::APFloat(0.0) &&
3776 Probability <= llvm::APFloat(1.0))) {
3777 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3778 << ProbArg->getSourceRange();
3779 return ExprError();
3780 }
3781 break;
3782 }
3783 case Builtin::BI__builtin_preserve_access_index:
3784 if (BuiltinPreserveAI(*this, TheCall))
3785 return ExprError();
3786 break;
3787 case Builtin::BI__builtin_call_with_static_chain:
3788 if (BuiltinCallWithStaticChain(*this, TheCall))
3789 return ExprError();
3790 break;
3791 case Builtin::BI__exception_code:
3792 case Builtin::BI_exception_code:
3793 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3794 diag::err_seh___except_block))
3795 return ExprError();
3796 break;
3797 case Builtin::BI__exception_info:
3798 case Builtin::BI_exception_info:
3799 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3800 diag::err_seh___except_filter))
3801 return ExprError();
3802 break;
3803 case Builtin::BI__GetExceptionInfo:
3804 if (checkArgCount(TheCall, 1))
3805 return ExprError();
3806
3808 TheCall->getBeginLoc(),
3809 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3810 TheCall))
3811 return ExprError();
3812
3813 TheCall->setType(Context.VoidPtrTy);
3814 break;
3815 case Builtin::BIaddressof:
3816 case Builtin::BI__addressof:
3817 case Builtin::BIforward:
3818 case Builtin::BIforward_like:
3819 case Builtin::BImove:
3820 case Builtin::BImove_if_noexcept:
3821 case Builtin::BIas_const: {
3822 // These are all expected to be of the form
3823 // T &/&&/* f(U &/&&)
3824 // where T and U only differ in qualification.
3825 if (checkArgCount(TheCall, 1))
3826 return ExprError();
3827 QualType Param = FDecl->getParamDecl(0)->getType();
3828 QualType Result = FDecl->getReturnType();
3829 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3830 BuiltinID == Builtin::BI__addressof;
3831 if (!(Param->isReferenceType() &&
3832 (ReturnsPointer ? Result->isAnyPointerType()
3833 : Result->isReferenceType()) &&
3834 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3835 Result->getPointeeType()))) {
3836 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3837 << FDecl;
3838 return ExprError();
3839 }
3840 break;
3841 }
3842 case Builtin::BI__builtin_ptrauth_strip:
3843 return PointerAuthStrip(*this, TheCall);
3844 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3845 return PointerAuthBlendDiscriminator(*this, TheCall);
3846 case Builtin::BI__builtin_ptrauth_sign_constant:
3847 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3848 /*RequireConstant=*/true);
3849 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3850 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3851 /*RequireConstant=*/false);
3852 case Builtin::BI__builtin_ptrauth_auth:
3853 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3854 /*RequireConstant=*/false);
3855 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3856 return PointerAuthSignGenericData(*this, TheCall);
3857 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3858 return PointerAuthAuthAndResign(*this, TheCall);
3859 case Builtin::BI__builtin_ptrauth_auth_with_pc_and_resign:
3860 return PointerAuthAuthWithPCAndResign(*this, TheCall);
3861 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3862 return PointerAuthAuthLoadRelativeAndSign(*this, TheCall);
3863 case Builtin::BI__builtin_ptrauth_string_discriminator:
3864 return PointerAuthStringDiscriminator(*this, TheCall);
3865
3866 case Builtin::BI__builtin_get_vtable_pointer:
3867 return GetVTablePointer(*this, TheCall);
3868
3869 // OpenCL v2.0, s6.13.16 - Pipe functions
3870 case Builtin::BIread_pipe:
3871 case Builtin::BIwrite_pipe:
3872 // Since those two functions are declared with var args, we need a semantic
3873 // check for the argument.
3874 if (OpenCL().checkBuiltinRWPipe(TheCall))
3875 return ExprError();
3876 break;
3877 case Builtin::BIreserve_read_pipe:
3878 case Builtin::BIreserve_write_pipe:
3879 case Builtin::BIwork_group_reserve_read_pipe:
3880 case Builtin::BIwork_group_reserve_write_pipe:
3881 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3882 return ExprError();
3883 break;
3884 case Builtin::BIsub_group_reserve_read_pipe:
3885 case Builtin::BIsub_group_reserve_write_pipe:
3886 if (OpenCL().checkSubgroupExt(TheCall) ||
3887 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3888 return ExprError();
3889 break;
3890 case Builtin::BIcommit_read_pipe:
3891 case Builtin::BIcommit_write_pipe:
3892 case Builtin::BIwork_group_commit_read_pipe:
3893 case Builtin::BIwork_group_commit_write_pipe:
3894 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3895 return ExprError();
3896 break;
3897 case Builtin::BIsub_group_commit_read_pipe:
3898 case Builtin::BIsub_group_commit_write_pipe:
3899 if (OpenCL().checkSubgroupExt(TheCall) ||
3900 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3901 return ExprError();
3902 break;
3903 case Builtin::BIget_pipe_num_packets:
3904 case Builtin::BIget_pipe_max_packets:
3905 if (OpenCL().checkBuiltinPipePackets(TheCall))
3906 return ExprError();
3907 break;
3908 case Builtin::BIto_global:
3909 case Builtin::BIto_local:
3910 case Builtin::BIto_private:
3911 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3912 return ExprError();
3913 break;
3914 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3915 case Builtin::BIenqueue_kernel:
3916 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3917 return ExprError();
3918 break;
3919 case Builtin::BIget_kernel_work_group_size:
3920 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3921 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3922 return ExprError();
3923 break;
3924 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3925 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3926 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3927 return ExprError();
3928 break;
3929 case Builtin::BI__builtin_os_log_format:
3930 Cleanup.setExprNeedsCleanups(true);
3931 [[fallthrough]];
3932 case Builtin::BI__builtin_os_log_format_buffer_size:
3933 if (BuiltinOSLogFormat(TheCall))
3934 return ExprError();
3935 break;
3936 case Builtin::BI__builtin_frame_address:
3937 case Builtin::BI__builtin_return_address: {
3938 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3939 return ExprError();
3940
3941 // -Wframe-address warning if non-zero passed to builtin
3942 // return/frame address.
3943 Expr::EvalResult Result;
3944 if (!TheCall->getArg(0)->isValueDependent() &&
3945 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3946 Result.Val.getInt() != 0)
3947 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3948 << ((BuiltinID == Builtin::BI__builtin_return_address)
3949 ? "__builtin_return_address"
3950 : "__builtin_frame_address")
3951 << TheCall->getSourceRange();
3952 break;
3953 }
3954
3955 case Builtin::BI__builtin_nondeterministic_value: {
3956 if (BuiltinNonDeterministicValue(TheCall))
3957 return ExprError();
3958 break;
3959 }
3960
3961 // __builtin_elementwise_abs restricts the element type to signed integers or
3962 // floating point types only.
3963 case Builtin::BI__builtin_elementwise_abs:
3966 return ExprError();
3967 break;
3968
3969 // These builtins restrict the element type to floating point
3970 // types only.
3971 case Builtin::BI__builtin_elementwise_acos:
3972 case Builtin::BI__builtin_elementwise_asin:
3973 case Builtin::BI__builtin_elementwise_atan:
3974 case Builtin::BI__builtin_elementwise_ceil:
3975 case Builtin::BI__builtin_elementwise_cos:
3976 case Builtin::BI__builtin_elementwise_cosh:
3977 case Builtin::BI__builtin_elementwise_exp:
3978 case Builtin::BI__builtin_elementwise_exp2:
3979 case Builtin::BI__builtin_elementwise_exp10:
3980 case Builtin::BI__builtin_elementwise_floor:
3981 case Builtin::BI__builtin_elementwise_log:
3982 case Builtin::BI__builtin_elementwise_log2:
3983 case Builtin::BI__builtin_elementwise_log10:
3984 case Builtin::BI__builtin_elementwise_roundeven:
3985 case Builtin::BI__builtin_elementwise_round:
3986 case Builtin::BI__builtin_elementwise_rint:
3987 case Builtin::BI__builtin_elementwise_nearbyint:
3988 case Builtin::BI__builtin_elementwise_sin:
3989 case Builtin::BI__builtin_elementwise_sinh:
3990 case Builtin::BI__builtin_elementwise_sqrt:
3991 case Builtin::BI__builtin_elementwise_tan:
3992 case Builtin::BI__builtin_elementwise_tanh:
3993 case Builtin::BI__builtin_elementwise_trunc:
3994 case Builtin::BI__builtin_elementwise_canonicalize:
3997 return ExprError();
3998 break;
3999 case Builtin::BI__builtin_elementwise_fma:
4000 if (BuiltinElementwiseTernaryMath(TheCall))
4001 return ExprError();
4002 break;
4003
4004 case Builtin::BI__builtin_elementwise_ldexp: {
4005 if (checkArgCount(TheCall, 2))
4006 return ExprError();
4007
4008 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
4009 if (A.isInvalid())
4010 return ExprError();
4011 QualType TyA = A.get()->getType();
4012 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
4014 return ExprError();
4015
4016 ExprResult Exp = UsualUnaryConversions(TheCall->getArg(1));
4017 if (Exp.isInvalid())
4018 return ExprError();
4019 QualType TyExp = Exp.get()->getType();
4020 if (checkMathBuiltinElementType(*this, Exp.get()->getBeginLoc(), TyExp,
4022 2))
4023 return ExprError();
4024
4025 // Check the two arguments are either scalars or vectors of equal length.
4026 const auto *Vec0 = TyA->getAs<VectorType>();
4027 const auto *Vec1 = TyExp->getAs<VectorType>();
4028 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
4029 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
4030 if (Arg0Length != Arg1Length) {
4031 Diag(Exp.get()->getBeginLoc(),
4032 diag::err_typecheck_vector_lengths_not_equal)
4033 << TyA << TyExp << A.get()->getSourceRange()
4034 << Exp.get()->getSourceRange();
4035 return ExprError();
4036 }
4037
4038 TheCall->setArg(0, A.get());
4039 TheCall->setArg(1, Exp.get());
4040 TheCall->setType(TyA);
4041 break;
4042 }
4043
4044 // These builtins restrict the element type to floating point
4045 // types only, and take in two arguments.
4046 case Builtin::BI__builtin_elementwise_minnum:
4047 case Builtin::BI__builtin_elementwise_maxnum:
4048 case Builtin::BI__builtin_elementwise_minimum:
4049 case Builtin::BI__builtin_elementwise_maximum:
4050 case Builtin::BI__builtin_elementwise_minimumnum:
4051 case Builtin::BI__builtin_elementwise_maximumnum:
4052 case Builtin::BI__builtin_elementwise_atan2:
4053 case Builtin::BI__builtin_elementwise_fmod:
4054 case Builtin::BI__builtin_elementwise_pow:
4055 if (BuiltinElementwiseMath(TheCall,
4057 return ExprError();
4058 break;
4059 // These builtins restrict the element type to integer
4060 // types only.
4061 case Builtin::BI__builtin_elementwise_add_sat:
4062 case Builtin::BI__builtin_elementwise_sub_sat:
4063 case Builtin::BI__builtin_elementwise_clmul:
4064 case Builtin::BI__builtin_elementwise_pext:
4065 case Builtin::BI__builtin_elementwise_pdep:
4066 if (BuiltinElementwiseMath(TheCall,
4068 return ExprError();
4069 break;
4070 case Builtin::BI__builtin_elementwise_fshl:
4071 case Builtin::BI__builtin_elementwise_fshr:
4074 return ExprError();
4075 break;
4076 case Builtin::BI__builtin_elementwise_min:
4077 case Builtin::BI__builtin_elementwise_max: {
4078 if (BuiltinElementwiseMath(TheCall))
4079 return ExprError();
4080 Expr *Arg0 = TheCall->getArg(0);
4081 Expr *Arg1 = TheCall->getArg(1);
4082 QualType Ty0 = Arg0->getType();
4083 QualType Ty1 = Arg1->getType();
4084 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
4085 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
4086 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
4087 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
4088 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
4089 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin_no_suggestion)
4090 << Context.BuiltinInfo.getQuotedName(BuiltinID);
4091 break;
4092 }
4093 case Builtin::BI__builtin_elementwise_popcount:
4094 case Builtin::BI__builtin_elementwise_bitreverse:
4097 return ExprError();
4098 break;
4099 case Builtin::BI__builtin_elementwise_copysign: {
4100 if (checkArgCount(TheCall, 2))
4101 return ExprError();
4102
4103 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
4104 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
4105 if (Magnitude.isInvalid() || Sign.isInvalid())
4106 return ExprError();
4107
4108 QualType MagnitudeTy = Magnitude.get()->getType();
4109 QualType SignTy = Sign.get()->getType();
4111 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
4114 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
4116 return ExprError();
4117 }
4118
4119 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
4120 return Diag(Sign.get()->getBeginLoc(),
4121 diag::err_typecheck_call_different_arg_types)
4122 << MagnitudeTy << SignTy;
4123 }
4124
4125 TheCall->setArg(0, Magnitude.get());
4126 TheCall->setArg(1, Sign.get());
4127 TheCall->setType(Magnitude.get()->getType());
4128 break;
4129 }
4130 case Builtin::BI__builtin_elementwise_clzg:
4131 case Builtin::BI__builtin_elementwise_ctzg:
4132 // These builtins can be unary or binary. Note for empty calls we call the
4133 // unary checker in order to not emit an error that says the function
4134 // expects 2 arguments, which would be misleading.
4135 if (TheCall->getNumArgs() <= 1) {
4138 return ExprError();
4139 } else if (BuiltinElementwiseMath(
4141 return ExprError();
4142 break;
4143 case Builtin::BI__builtin_reduce_max:
4144 case Builtin::BI__builtin_reduce_min:
4145 case Builtin::BI__builtin_reduce_maximum:
4146 case Builtin::BI__builtin_reduce_minimum:
4147 // These builtins support vectors of integers only.
4148 // TODO: ADD/MUL should support floating-point types.
4149 case Builtin::BI__builtin_reduce_add:
4150 case Builtin::BI__builtin_reduce_mul:
4151 case Builtin::BI__builtin_reduce_xor:
4152 case Builtin::BI__builtin_reduce_or:
4153 case Builtin::BI__builtin_reduce_and: {
4154 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
4155 return ExprError();
4156
4157 const Expr *Arg = TheCall->getArg(0);
4158 QualType ElTy = getVectorElementType(Context, Arg->getType());
4159
4160 bool FloatOnly = BuiltinID == Builtin::BI__builtin_reduce_maximum ||
4161 BuiltinID == Builtin::BI__builtin_reduce_minimum;
4162
4163 bool IntOnly = BuiltinID == Builtin::BI__builtin_reduce_add ||
4164 BuiltinID == Builtin::BI__builtin_reduce_mul ||
4165 BuiltinID == Builtin::BI__builtin_reduce_xor ||
4166 BuiltinID == Builtin::BI__builtin_reduce_or ||
4167 BuiltinID == Builtin::BI__builtin_reduce_and;
4168
4169 if (FloatOnly) {
4170 if (ElTy.isNull() || !ElTy->isFloatingType()) {
4171 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4172 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
4173 << Arg->getType();
4174 return ExprError();
4175 }
4176 } else if (IntOnly) {
4177 if (ElTy.isNull() || !ElTy->isIntegerType()) {
4178 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4179 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
4180 << Arg->getType();
4181 return ExprError();
4182 }
4183 } else if (ElTy.isNull()) {
4184 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4185 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
4186 << Arg->getType();
4187 return ExprError();
4188 }
4189
4190 TheCall->setType(ElTy);
4191 break;
4192 }
4193
4194 case Builtin::BI__builtin_reduce_assoc_fadd:
4195 case Builtin::BI__builtin_reduce_in_order_fadd: {
4196 // For in-order reductions require the user to specify the start value.
4197 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
4198 if (InOrder ? checkArgCount(TheCall, 2) : checkArgCountRange(TheCall, 1, 2))
4199 return ExprError();
4200
4201 ExprResult Vec = UsualUnaryConversions(TheCall->getArg(0));
4202 if (Vec.isInvalid())
4203 return ExprError();
4204
4205 TheCall->setArg(0, Vec.get());
4206
4207 QualType ElTy = getVectorElementType(Context, Vec.get()->getType());
4208 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
4209 Diag(Vec.get()->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4210 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
4211 << Vec.get()->getType();
4212 return ExprError();
4213 }
4214
4215 if (TheCall->getNumArgs() == 2) {
4216 ExprResult StartValue = UsualUnaryConversions(TheCall->getArg(1));
4217 if (StartValue.isInvalid())
4218 return ExprError();
4219
4220 if (!StartValue.get()->getType()->isRealFloatingType()) {
4221 Diag(StartValue.get()->getBeginLoc(),
4222 diag::err_builtin_invalid_arg_type)
4223 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
4224 << StartValue.get()->getType();
4225 return ExprError();
4226 }
4227 TheCall->setArg(1, StartValue.get());
4228 }
4229
4230 TheCall->setType(ElTy);
4231 break;
4232 }
4233
4234 case Builtin::BI__builtin_matrix_transpose:
4235 return BuiltinMatrixTranspose(TheCall, TheCallResult);
4236
4237 case Builtin::BI__builtin_matrix_column_major_load:
4238 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
4239
4240 case Builtin::BI__builtin_matrix_column_major_store:
4241 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
4242
4243 case Builtin::BI__builtin_verbose_trap:
4244 if (!checkBuiltinVerboseTrap(TheCall, *this))
4245 return ExprError();
4246 break;
4247
4248 case Builtin::BI__builtin_get_device_side_mangled_name: {
4249 auto Check = [](CallExpr *TheCall) {
4250 if (TheCall->getNumArgs() != 1)
4251 return false;
4252 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
4253 if (!DRE)
4254 return false;
4255 auto *D = DRE->getDecl();
4256 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
4257 return false;
4258 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4259 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
4260 };
4261 if (!Check(TheCall)) {
4262 Diag(TheCall->getBeginLoc(),
4263 diag::err_hip_invalid_args_builtin_mangled_name);
4264 return ExprError();
4265 }
4266 break;
4267 }
4268 case Builtin::BI__builtin_bswapg:
4269 if (BuiltinBswapg(*this, TheCall))
4270 return ExprError();
4271 break;
4272 case Builtin::BI__builtin_bitreverseg:
4273 if (BuiltinBitreverseg(*this, TheCall))
4274 return ExprError();
4275 break;
4276 case Builtin::BI__builtin_popcountg:
4277 if (BuiltinPopcountg(*this, TheCall))
4278 return ExprError();
4279 break;
4280 case Builtin::BI__builtin_clzg:
4281 case Builtin::BI__builtin_ctzg:
4282 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
4283 return ExprError();
4284 break;
4285
4286 case Builtin::BI__builtin_stdc_rotate_left:
4287 case Builtin::BI__builtin_stdc_rotate_right:
4288 if (BuiltinRotateGeneric(*this, TheCall))
4289 return ExprError();
4290 break;
4291
4292 case Builtin::BI__builtin_stdc_memreverse8:
4293 case Builtin::BIstdc_memreverse8:
4294 case Builtin::BIstdc_memreverse8u8:
4295 case Builtin::BIstdc_memreverse8u16:
4296 case Builtin::BIstdc_memreverse8u32:
4297 case Builtin::BIstdc_memreverse8u64:
4298 case Builtin::BIstdc_load8_leu8:
4299 case Builtin::BIstdc_load8_leu16:
4300 case Builtin::BIstdc_load8_leu32:
4301 case Builtin::BIstdc_load8_leu64:
4302 case Builtin::BIstdc_load8_les8:
4303 case Builtin::BIstdc_load8_les16:
4304 case Builtin::BIstdc_load8_les32:
4305 case Builtin::BIstdc_load8_les64:
4306 case Builtin::BIstdc_load8_beu8:
4307 case Builtin::BIstdc_load8_beu16:
4308 case Builtin::BIstdc_load8_beu32:
4309 case Builtin::BIstdc_load8_beu64:
4310 case Builtin::BIstdc_load8_bes8:
4311 case Builtin::BIstdc_load8_bes16:
4312 case Builtin::BIstdc_load8_bes32:
4313 case Builtin::BIstdc_load8_bes64:
4314 case Builtin::BIstdc_load8_aligned_leu8:
4315 case Builtin::BIstdc_load8_aligned_leu16:
4316 case Builtin::BIstdc_load8_aligned_leu32:
4317 case Builtin::BIstdc_load8_aligned_leu64:
4318 case Builtin::BIstdc_load8_aligned_les8:
4319 case Builtin::BIstdc_load8_aligned_les16:
4320 case Builtin::BIstdc_load8_aligned_les32:
4321 case Builtin::BIstdc_load8_aligned_les64:
4322 case Builtin::BIstdc_load8_aligned_beu8:
4323 case Builtin::BIstdc_load8_aligned_beu16:
4324 case Builtin::BIstdc_load8_aligned_beu32:
4325 case Builtin::BIstdc_load8_aligned_beu64:
4326 case Builtin::BIstdc_load8_aligned_bes8:
4327 case Builtin::BIstdc_load8_aligned_bes16:
4328 case Builtin::BIstdc_load8_aligned_bes32:
4329 case Builtin::BIstdc_load8_aligned_bes64:
4330 if (Context.getTargetInfo().getCharWidth() != 8) {
4331 Diag(TheCall->getBeginLoc(), diag::err_builtin_requires_char_bit_8)
4332 << TheCall->getDirectCallee()->getName();
4333 return ExprError();
4334 }
4335 break;
4336
4337 case Builtin::BI__builtin_stdc_bit_floor:
4338 case Builtin::BI__builtin_stdc_bit_ceil:
4339 if (BuiltinStdCBuiltin(*this, TheCall, QualType()))
4340 return ExprError();
4341 break;
4342 case Builtin::BI__builtin_stdc_has_single_bit:
4343 if (BuiltinStdCBuiltin(*this, TheCall, Context.BoolTy))
4344 return ExprError();
4345 break;
4346 case Builtin::BI__builtin_stdc_leading_zeros:
4347 case Builtin::BI__builtin_stdc_leading_ones:
4348 case Builtin::BI__builtin_stdc_trailing_zeros:
4349 case Builtin::BI__builtin_stdc_trailing_ones:
4350 case Builtin::BI__builtin_stdc_first_leading_zero:
4351 case Builtin::BI__builtin_stdc_first_leading_one:
4352 case Builtin::BI__builtin_stdc_first_trailing_zero:
4353 case Builtin::BI__builtin_stdc_first_trailing_one:
4354 case Builtin::BI__builtin_stdc_count_zeros:
4355 case Builtin::BI__builtin_stdc_count_ones:
4356 case Builtin::BI__builtin_stdc_bit_width:
4357 if (BuiltinStdCBuiltin(*this, TheCall, Context.UnsignedIntTy))
4358 return ExprError();
4359 break;
4360
4361 case Builtin::BI__builtin_allow_runtime_check: {
4362 Expr *Arg = TheCall->getArg(0);
4363 // Check if the argument is a string literal.
4365 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4366 << Arg->getSourceRange();
4367 return ExprError();
4368 }
4369 break;
4370 }
4371
4372 case Builtin::BI__builtin_allow_sanitize_check: {
4373 if (checkArgCount(TheCall, 1))
4374 return ExprError();
4375
4376 Expr *Arg = TheCall->getArg(0);
4377 // Check if the argument is a string literal.
4378 const StringLiteral *SanitizerName =
4379 dyn_cast<StringLiteral>(Arg->IgnoreParenImpCasts());
4380 if (!SanitizerName) {
4381 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4382 << Arg->getSourceRange();
4383 return ExprError();
4384 }
4385 // Validate the sanitizer name.
4386 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
4387 .Cases({"address", "thread", "memory", "hwaddress",
4388 "kernel-address", "kernel-memory", "kernel-hwaddress"},
4389 true)
4390 .Default(false)) {
4391 Diag(TheCall->getBeginLoc(), diag::err_invalid_builtin_argument)
4392 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
4393 << Arg->getSourceRange();
4394 return ExprError();
4395 }
4396 break;
4397 }
4398 case Builtin::BI__builtin_counted_by_ref:
4399 if (BuiltinCountedByRef(TheCall))
4400 return ExprError();
4401 break;
4402 }
4403
4404 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
4405 return ExprError();
4406
4407 // Since the target specific builtins for each arch overlap, only check those
4408 // of the arch we are compiling for.
4409 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
4410 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
4411 assert(Context.getAuxTargetInfo() &&
4412 "Aux Target Builtin, but not an aux target?");
4413
4414 // Host target builtins cannot be lowered for a SYCL device. Defer the
4415 // diagnostic so that they are still accepted in code that is not
4416 // reachable from device code.
4417 if (getLangOpts().SYCLIsDevice && !isUnevaluatedContext())
4418 SYCL().DiagIfDeviceCode(TheCall->getBeginLoc(),
4419 diag::err_builtin_target_unsupported)
4420 << TheCall->getSourceRange();
4421
4422 if (CheckTSBuiltinFunctionCall(
4423 *Context.getAuxTargetInfo(),
4424 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
4425 return ExprError();
4426 } else {
4427 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
4428 TheCall))
4429 return ExprError();
4430 }
4431 }
4432
4433 return TheCallResult;
4434}
4435
4436bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
4437 llvm::APSInt Result;
4438 // We can't check the value of a dependent argument.
4439 Expr *Arg = TheCall->getArg(ArgNum);
4440 if (Arg->isTypeDependent() || Arg->isValueDependent())
4441 return false;
4442
4443 // Check constant-ness first.
4444 if (BuiltinConstantArg(TheCall, ArgNum, Result))
4445 return true;
4446
4447 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
4448 if (Result.isShiftedMask() || (~Result).isShiftedMask())
4449 return false;
4450
4451 return Diag(TheCall->getBeginLoc(),
4452 diag::err_argument_not_contiguous_bit_field)
4453 << ArgNum << Arg->getSourceRange();
4454}
4455
4456bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
4457 unsigned FirstArg, FormatStringInfo *FSI) {
4458 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
4459 bool IsVariadic = false;
4460 if (const FunctionType *FnTy = D->getFunctionType())
4461 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
4462 else if (const auto *BD = dyn_cast<BlockDecl>(D))
4463 IsVariadic = BD->isVariadic();
4464 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
4465 IsVariadic = OMD->isVariadic();
4466
4467 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
4468 IsVariadic, FSI);
4469}
4470
4471bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
4472 bool HasImplicitThisParam, bool IsVariadic,
4473 FormatStringInfo *FSI) {
4474 if (FirstArg == 0)
4476 else if (IsVariadic)
4478 else
4480 FSI->FormatIdx = FormatIdx - 1;
4481 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
4482
4483 // The way the format attribute works in GCC, the implicit this argument
4484 // of member functions is counted. However, it doesn't appear in our own
4485 // lists, so decrement format_idx in that case.
4486 if (HasImplicitThisParam) {
4487 if(FSI->FormatIdx == 0)
4488 return false;
4489 --FSI->FormatIdx;
4490 if (FSI->FirstDataArg != 0)
4491 --FSI->FirstDataArg;
4492 }
4493 return true;
4494}
4495
4496/// Checks if a the given expression evaluates to null.
4497///
4498/// Returns true if the value evaluates to null.
4499static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4500 // Treat (smart) pointers constructed from nullptr as null, whether we can
4501 // const-evaluate them or not.
4502 // This must happen first: the smart pointer expr might have _Nonnull type!
4506 return true;
4507
4508 // If the expression has non-null type, it doesn't evaluate to null.
4509 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
4510 if (*nullability == NullabilityKind::NonNull)
4511 return false;
4512 }
4513
4514 // As a special case, transparent unions initialized with zero are
4515 // considered null for the purposes of the nonnull attribute.
4516 if (const RecordType *UT = Expr->getType()->getAsUnionType();
4517 UT &&
4518 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
4519 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
4520 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
4521 Expr = ILE->getInit(0);
4522 }
4523
4524 bool Result;
4525 return (!Expr->isValueDependent() &&
4527 !Result);
4528}
4529
4531 const Expr *ArgExpr,
4532 SourceLocation CallSiteLoc) {
4533 if (CheckNonNullExpr(S, ArgExpr))
4534 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4535 S.PDiag(diag::warn_null_arg)
4536 << ArgExpr->getSourceRange());
4537}
4538
4539/// Determine whether the given type has a non-null nullability annotation.
4541 if (auto nullability = type->getNullability())
4542 return *nullability == NullabilityKind::NonNull;
4543
4544 return false;
4545}
4546
4548 const NamedDecl *FDecl,
4549 const FunctionProtoType *Proto,
4551 SourceLocation CallSiteLoc) {
4552 assert((FDecl || Proto) && "Need a function declaration or prototype");
4553
4554 // Already checked by constant evaluator.
4556 return;
4557 // Check the attributes attached to the method/function itself.
4558 llvm::SmallBitVector NonNullArgs;
4559 if (FDecl) {
4560 // Handle the nonnull attribute on the function/method declaration itself.
4561 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4562 if (!NonNull->args_size()) {
4563 // Easy case: all pointer arguments are nonnull.
4564 for (const auto *Arg : Args)
4565 if (S.isValidPointerAttrType(Arg->getType()))
4566 CheckNonNullArgument(S, Arg, CallSiteLoc);
4567 return;
4568 }
4569
4570 for (const ParamIdx &Idx : NonNull->args()) {
4571 unsigned IdxAST = Idx.getASTIndex();
4572 if (IdxAST >= Args.size())
4573 continue;
4574 if (NonNullArgs.empty())
4575 NonNullArgs.resize(Args.size());
4576 NonNullArgs.set(IdxAST);
4577 }
4578 }
4579 }
4580
4581 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4582 // Handle the nonnull attribute on the parameters of the
4583 // function/method.
4585 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4586 parms = FD->parameters();
4587 else
4588 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4589
4590 unsigned ParamIndex = 0;
4591 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4592 I != E; ++I, ++ParamIndex) {
4593 const ParmVarDecl *PVD = *I;
4594 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
4595 if (NonNullArgs.empty())
4596 NonNullArgs.resize(Args.size());
4597
4598 NonNullArgs.set(ParamIndex);
4599 }
4600 }
4601 } else {
4602 // If we have a non-function, non-method declaration but no
4603 // function prototype, try to dig out the function prototype.
4604 if (!Proto) {
4605 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4606 QualType type = VD->getType().getNonReferenceType();
4607 if (auto pointerType = type->getAs<PointerType>())
4608 type = pointerType->getPointeeType();
4609 else if (auto blockType = type->getAs<BlockPointerType>())
4610 type = blockType->getPointeeType();
4611 // FIXME: data member pointers?
4612
4613 // Dig out the function prototype, if there is one.
4614 Proto = type->getAs<FunctionProtoType>();
4615 }
4616 }
4617
4618 // Fill in non-null argument information from the nullability
4619 // information on the parameter types (if we have them).
4620 if (Proto) {
4621 unsigned Index = 0;
4622 for (auto paramType : Proto->getParamTypes()) {
4623 if (isNonNullType(paramType)) {
4624 if (NonNullArgs.empty())
4625 NonNullArgs.resize(Args.size());
4626
4627 NonNullArgs.set(Index);
4628 }
4629
4630 ++Index;
4631 }
4632 }
4633 }
4634
4635 // Check for non-null arguments.
4636 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4637 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4638 if (NonNullArgs[ArgIndex])
4639 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
4640 }
4641}
4642
4643void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4644 StringRef ParamName, QualType ArgTy,
4645 QualType ParamTy) {
4646
4647 // If a function accepts a pointer or reference type
4648 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4649 return;
4650
4651 // If the parameter is a pointer type, get the pointee type for the
4652 // argument too. If the parameter is a reference type, don't try to get
4653 // the pointee type for the argument.
4654 if (ParamTy->isPointerType())
4655 ArgTy = ArgTy->getPointeeType();
4656
4657 // Remove reference or pointer
4658 ParamTy = ParamTy->getPointeeType();
4659
4660 // Find expected alignment, and the actual alignment of the passed object.
4661 // getTypeAlignInChars requires complete types
4662 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4663 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4664 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4665 return;
4666
4667 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4668 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4669
4670 // If the argument is less aligned than the parameter, there is a
4671 // potential alignment issue.
4672 if (ArgAlign < ParamAlign)
4673 Diag(Loc, diag::warn_param_mismatched_alignment)
4674 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4675 << ParamName << (FDecl != nullptr) << FDecl;
4676}
4677
4678void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4679 const Expr *ThisArg,
4681 if (!FD || Args.empty())
4682 return;
4683 auto GetArgAt = [&](int Idx) -> const Expr * {
4684 if (Idx == LifetimeCaptureByAttr::Global ||
4685 Idx == LifetimeCaptureByAttr::Unknown)
4686 return nullptr;
4687 if (IsMemberFunction && Idx == 0)
4688 return ThisArg;
4689 return Args[Idx - IsMemberFunction];
4690 };
4691 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4692 unsigned ArgIdx) {
4693 if (!Attr)
4694 return;
4695
4696 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4697 for (int CapturingParamIdx : Attr->params()) {
4698 if (CapturingParamIdx == LifetimeCaptureByAttr::Invalid)
4699 continue;
4700 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4701 // initialization codepath.
4702 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4704 continue;
4705 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4706 CapturingEntity CE{Capturing};
4707 // Ensure that 'Captured' outlives the 'Capturing' entity.
4708 checkCaptureByLifetime(*this, CE, Captured);
4709 }
4710 };
4711 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4712 for (const auto *A :
4713 FD->getParamDecl(I)->specific_attrs<LifetimeCaptureByAttr>())
4714 HandleCaptureByAttr(A, I + IsMemberFunction);
4715 // Check when the implicit object param is captured.
4716 if (IsMemberFunction) {
4717 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4718 if (!TSI)
4719 return;
4721 for (TypeLoc TL = TSI->getTypeLoc();
4722 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4723 TL = ATL.getModifiedLoc())
4724 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4725 }
4726}
4727
4729 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4730 bool IsMemberFunction, SourceLocation Loc,
4731 SourceRange Range, VariadicCallType CallType) {
4732
4733 if ((ThisArg && ThisArg->isInstantiationDependent()) ||
4734 llvm::any_of(Args, [](const Expr *E) {
4735 return E && E->isInstantiationDependent();
4736 }))
4737 return;
4738
4739 // Printf and scanf checking.
4740 llvm::SmallBitVector CheckedVarArgs;
4741 if (FDecl) {
4742 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4743 // Only create vector if there are format attributes.
4744 CheckedVarArgs.resize(Args.size());
4745 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
4746 CheckedVarArgs);
4747 }
4748
4749 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4750 CheckedVarArgs.resize(Args.size());
4751 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4752 CheckedVarArgs);
4753 }
4754 }
4755
4756 // Refuse POD arguments that weren't caught by the format string
4757 // checks above.
4758 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4759 if (CallType != VariadicCallType::DoesNotApply &&
4760 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4761 unsigned NumParams = Proto ? Proto->getNumParams()
4762 : isa_and_nonnull<FunctionDecl>(FDecl)
4763 ? cast<FunctionDecl>(FDecl)->getNumParams()
4764 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
4765 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4766 : 0;
4767
4768 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4769 // Args[ArgIdx] can be null in malformed code.
4770 if (const Expr *Arg = Args[ArgIdx]) {
4771 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4772 checkVariadicArgument(Arg, CallType);
4773 }
4774 }
4775 }
4776 if (FD)
4777 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4778 if (FDecl || Proto) {
4779 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4780
4781 // Type safety checking.
4782 if (FDecl) {
4783 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4784 CheckArgumentWithTypeTag(I, Args, Loc);
4785 }
4786 }
4787
4788 // Check that passed arguments match the alignment of original arguments.
4789 // Try to get the missing prototype from the declaration.
4790 if (!Proto && FDecl) {
4791 const auto *FT = FDecl->getFunctionType();
4792 if (isa_and_nonnull<FunctionProtoType>(FT))
4793 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4794 }
4795 if (Proto) {
4796 // For variadic functions, we may have more args than parameters.
4797 // For some K&R functions, we may have less args than parameters.
4798 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4799 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4800 bool IsScalableArg = false;
4801 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4802 // Args[ArgIdx] can be null in malformed code.
4803 if (const Expr *Arg = Args[ArgIdx]) {
4804 if (Arg->containsErrors())
4805 continue;
4806
4807 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4808 FDecl->hasLinkage() &&
4809 FDecl->getFormalLinkage() != Linkage::Internal &&
4811 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
4812
4813 QualType ParamTy = Proto->getParamType(ArgIdx);
4814 if (ParamTy->isSizelessVectorType())
4815 IsScalableArg = true;
4816 QualType ArgTy = Arg->getType();
4817 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4818 ArgTy, ParamTy);
4819 }
4820 }
4821
4822 // If the callee has an AArch64 SME attribute to indicate that it is an
4823 // __arm_streaming function, then the caller requires SME to be available.
4826 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
4827 llvm::StringMap<bool> CallerFeatureMap;
4828 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
4829 if (!CallerFeatureMap.contains("sme"))
4830 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4831 } else if (!Context.getTargetInfo().hasFeature("sme")) {
4832 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4833 }
4834 }
4835
4836 // If the call requires a streaming-mode change and has scalable vector
4837 // arguments or return values, then warn the user that the streaming and
4838 // non-streaming vector lengths may be different.
4839 // When both streaming and non-streaming vector lengths are defined and
4840 // mismatched, produce an error.
4841 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
4842 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4843 (IsScalableArg || IsScalableRet)) {
4844 bool IsCalleeStreaming =
4846 bool IsCalleeStreamingCompatible =
4847 ExtInfo.AArch64SMEAttributes &
4849 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
4850 if (!IsCalleeStreamingCompatible &&
4851 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4852 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4853 const LangOptions &LO = getLangOpts();
4854 unsigned VL = LO.VScaleMin * 128;
4855 unsigned SVL = LO.VScaleStreamingMin * 128;
4856 bool IsVLMismatch = VL && SVL && VL != SVL;
4857
4858 auto EmitDiag = [&](bool IsArg) {
4859 if (IsVLMismatch) {
4860 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4861 // Emit warning for streaming-compatible callers
4862 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
4863 << IsArg << IsCalleeStreaming << SVL << VL;
4864 else
4865 // Emit error otherwise
4866 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4867 << IsArg << SVL << VL;
4868 } else
4869 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4870 << IsArg;
4871 };
4872
4873 if (IsScalableArg)
4874 EmitDiag(true);
4875 if (IsScalableRet)
4876 EmitDiag(false);
4877 }
4878 }
4879
4880 FunctionType::ArmStateValue CalleeArmZAState =
4882 FunctionType::ArmStateValue CalleeArmZT0State =
4884 if (CalleeArmZAState != FunctionType::ARM_None ||
4885 CalleeArmZT0State != FunctionType::ARM_None) {
4886 bool CallerHasZAState = false;
4887 bool CallerHasZT0State = false;
4888 if (CallerFD) {
4889 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4890 if (Attr && Attr->isNewZA())
4891 CallerHasZAState = true;
4892 if (Attr && Attr->isNewZT0())
4893 CallerHasZT0State = true;
4894 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4895 CallerHasZAState |=
4897 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4899 CallerHasZT0State |=
4901 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4903 }
4904 }
4905
4906 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4907 Diag(Loc, diag::err_sme_za_call_no_za_state);
4908
4909 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4910 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4911
4912 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4913 CalleeArmZT0State != FunctionType::ARM_None) {
4914 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4915 Diag(Loc, diag::note_sme_use_preserves_za);
4916 }
4917 }
4918 }
4919
4920 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4921 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4922 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4923 if (!Arg->isValueDependent()) {
4924 Expr::EvalResult Align;
4925 if (Arg->EvaluateAsInt(Align, Context)) {
4926 const llvm::APSInt &I = Align.Val.getInt();
4927 if (!I.isPowerOf2())
4928 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4929 << Arg->getSourceRange();
4930
4931 if (I > Sema::MaximumAlignment)
4932 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4933 << Arg->getSourceRange() << Sema::MaximumAlignment;
4934 }
4935 }
4936 }
4937
4938 if (FD && FD->isVariadic() && getLangOpts().SYCLIsDevice &&
4940 SYCL().DiagIfDeviceCode(Loc, diag::err_variadic_device_fn)
4941 << diag::OffloadLang::SYCL;
4942
4943 // A calling convention that is supported only by the host is accepted on the
4944 // declaration, but cannot be used for a call from device code.
4945 if (Proto && getLangOpts().SYCLIsDevice && !isUnevaluatedContext()) {
4946 CallingConv CC = Proto->getCallConv();
4947 if (Context.getTargetInfo().checkCallingConvention(CC) !=
4949 SYCL().DiagIfDeviceCode(Loc, diag::warn_cconv_unsupported)
4950 << &Context.Idents.get(FunctionType::getNameForCallConv(CC))
4952 }
4953
4954 if (FD)
4955 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4956}
4957
4958void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4959 if (TemplateDecl *Decl =
4960 AutoT->getTypeConstraintConcept().getAsTemplateDecl()) {
4961 DiagnoseUseOfDecl(Decl, Loc);
4962 }
4963}
4964
4965void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4967 const FunctionProtoType *Proto,
4968 SourceLocation Loc) {
4969 VariadicCallType CallType = Proto->isVariadic()
4972
4973 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4974 CheckArgAlignment(
4975 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4976 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4977
4978 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4979 Loc, SourceRange(), CallType);
4980}
4981
4983 const FunctionProtoType *Proto) {
4984 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4985 isa<CXXMethodDecl>(FDecl);
4986 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4987 IsMemberOperatorCall;
4988 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4989 TheCall->getCallee());
4990 Expr** Args = TheCall->getArgs();
4991 unsigned NumArgs = TheCall->getNumArgs();
4992
4993 Expr *ImplicitThis = nullptr;
4994 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4995 // If this is a call to a member operator, hide the first
4996 // argument from checkCall.
4997 // FIXME: Our choice of AST representation here is less than ideal.
4998 ImplicitThis = Args[0];
4999 ++Args;
5000 --NumArgs;
5001 } else if (IsMemberFunction && !FDecl->isStatic() &&
5003 ImplicitThis =
5004 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5005
5006 if (ImplicitThis) {
5007 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5008 // used.
5009 QualType ThisType = ImplicitThis->getType();
5010 if (!ThisType->isPointerType()) {
5011 assert(!ThisType->isReferenceType());
5012 ThisType = Context.getPointerType(ThisType);
5013 }
5014
5015 QualType ThisTypeFromDecl = Context.getPointerType(
5016 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
5017
5018 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5019 ThisTypeFromDecl);
5020 }
5021
5022 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
5023 IsMemberFunction, TheCall->getRParenLoc(),
5024 TheCall->getCallee()->getSourceRange(), CallType);
5025
5026 IdentifierInfo *FnInfo = FDecl->getIdentifier();
5027 // None of the checks below are needed for functions that don't have
5028 // simple names (e.g., C++ conversion functions).
5029 if (!FnInfo)
5030 return false;
5031
5032 // Enforce TCB except for builtin calls, which are always allowed.
5033 if (FDecl->getBuiltinID() == 0)
5034 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
5035
5036 CheckAbsoluteValueFunction(TheCall, FDecl);
5037 CheckMaxUnsignedZero(TheCall, FDecl);
5038 CheckInfNaNFunction(TheCall, FDecl);
5039
5040 if (getLangOpts().ObjC)
5041 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
5042
5043 unsigned CMId = FDecl->getMemoryFunctionKind();
5044
5045 // Handle memory setting and copying functions.
5046 switch (CMId) {
5047 case 0:
5048 return false;
5049 case Builtin::BIstrlcpy: // fallthrough
5050 case Builtin::BIstrlcat:
5051 CheckStrlcpycatArguments(TheCall, FnInfo);
5052 break;
5053 case Builtin::BIstrncat:
5054 CheckStrncatArguments(TheCall, FnInfo);
5055 break;
5056 case Builtin::BIfree:
5057 CheckFreeArguments(TheCall);
5058 break;
5059 default:
5060 CheckMemaccessArguments(TheCall, CMId, FnInfo);
5061 }
5062
5063 return false;
5064}
5065
5066bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5067 const FunctionProtoType *Proto) {
5068 QualType Ty;
5069 if (const auto *V = dyn_cast<VarDecl>(NDecl))
5070 Ty = V->getType().getNonReferenceType();
5071 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5072 Ty = F->getType().getNonReferenceType();
5073 else
5074 return false;
5075
5076 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5077 !Ty->isFunctionProtoType())
5078 return false;
5079
5080 VariadicCallType CallType;
5081 if (!Proto || !Proto->isVariadic()) {
5083 } else if (Ty->isBlockPointerType()) {
5084 CallType = VariadicCallType::Block;
5085 } else { // Ty->isFunctionPointerType()
5086 CallType = VariadicCallType::Function;
5087 }
5088
5089 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5090 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5091 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5092 TheCall->getCallee()->getSourceRange(), CallType);
5093
5094 return false;
5095}
5096
5097bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5098 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5099 TheCall->getCallee());
5100 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5101 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5102 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5103 TheCall->getCallee()->getSourceRange(), CallType);
5104
5105 return false;
5106}
5107
5109 if (!llvm::isValidAtomicOrderingCABI(Ordering))
5110 return false;
5111
5112 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5113 switch (Op) {
5114 case AtomicExpr::AO__c11_atomic_init:
5115 case AtomicExpr::AO__opencl_atomic_init:
5116 llvm_unreachable("There is no ordering argument for an init");
5117
5118 case AtomicExpr::AO__c11_atomic_load:
5119 case AtomicExpr::AO__opencl_atomic_load:
5120 case AtomicExpr::AO__hip_atomic_load:
5121 case AtomicExpr::AO__atomic_load_n:
5122 case AtomicExpr::AO__atomic_load:
5123 case AtomicExpr::AO__scoped_atomic_load_n:
5124 case AtomicExpr::AO__scoped_atomic_load:
5125 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5126 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5127
5128 case AtomicExpr::AO__c11_atomic_store:
5129 case AtomicExpr::AO__opencl_atomic_store:
5130 case AtomicExpr::AO__hip_atomic_store:
5131 case AtomicExpr::AO__atomic_store:
5132 case AtomicExpr::AO__atomic_store_n:
5133 case AtomicExpr::AO__scoped_atomic_store:
5134 case AtomicExpr::AO__scoped_atomic_store_n:
5135 case AtomicExpr::AO__atomic_clear:
5136 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5137 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5138 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5139
5140 default:
5141 return true;
5142 }
5143}
5144
5145ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
5147 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5148 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5149 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5150 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5151 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5152 Op);
5153}
5154
5155/// Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_*
5156/// equivalents. Provide a fixit when the scope is a compile-time constant and
5157/// there is a direct mapping from the HIP builtin to a Clang builtin. The
5158/// compare_exchange builtins differ in how they accept the desired value, so
5159/// only a warning (without a fixit) is emitted for those.
5161 MultiExprArg Args,
5163 StringRef OldName;
5164 StringRef NewName;
5165 bool CanFixIt;
5166
5167 switch (Op) {
5168#define HIP_ATOMIC_FIXABLE(hip, scoped) \
5169 case AtomicExpr::AO__hip_atomic_##hip: \
5170 OldName = "__hip_atomic_" #hip; \
5171 NewName = "__scoped_atomic_" #scoped; \
5172 CanFixIt = true; \
5173 break;
5174 HIP_ATOMIC_FIXABLE(load, load_n)
5175 HIP_ATOMIC_FIXABLE(store, store_n)
5176 HIP_ATOMIC_FIXABLE(exchange, exchange_n)
5177 HIP_ATOMIC_FIXABLE(fetch_add, fetch_add)
5178 HIP_ATOMIC_FIXABLE(fetch_sub, fetch_sub)
5179 HIP_ATOMIC_FIXABLE(fetch_and, fetch_and)
5180 HIP_ATOMIC_FIXABLE(fetch_or, fetch_or)
5181 HIP_ATOMIC_FIXABLE(fetch_xor, fetch_xor)
5182 HIP_ATOMIC_FIXABLE(fetch_min, fetch_min)
5183 HIP_ATOMIC_FIXABLE(fetch_max, fetch_max)
5184#undef HIP_ATOMIC_FIXABLE
5185 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5186 OldName = "__hip_atomic_compare_exchange_weak";
5187 NewName = "__scoped_atomic_compare_exchange";
5188 CanFixIt = false;
5189 break;
5190 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5191 OldName = "__hip_atomic_compare_exchange_strong";
5192 NewName = "__scoped_atomic_compare_exchange";
5193 CanFixIt = false;
5194 break;
5195 default:
5196 llvm_unreachable("unhandled HIP atomic op");
5197 }
5198
5199 auto DB = S.Diag(ExprRange.getBegin(), diag::warn_hip_deprecated_builtin)
5200 << OldName << NewName;
5201 if (!CanFixIt)
5202 return;
5203
5204 DB << FixItHint::CreateReplacement(ExprRange, NewName);
5205
5206 Expr *Scope = Args[Args.size() - 1];
5207 std::optional<llvm::APSInt> ScopeVal =
5208 Scope->getIntegerConstantExpr(S.Context);
5209 if (!ScopeVal)
5210 return;
5211
5212 StringRef ScopeName;
5213 switch (ScopeVal->getZExtValue()) {
5215 ScopeName = "__MEMORY_SCOPE_SINGLE";
5216 break;
5218 ScopeName = "__MEMORY_SCOPE_WVFRNT";
5219 break;
5221 ScopeName = "__MEMORY_SCOPE_WRKGRP";
5222 break;
5224 ScopeName = "__MEMORY_SCOPE_DEVICE";
5225 break;
5227 ScopeName = "__MEMORY_SCOPE_SYSTEM";
5228 break;
5230 ScopeName = "__MEMORY_SCOPE_CLUSTR";
5231 break;
5232 default:
5233 return;
5234 }
5235
5237 CharSourceRange::getTokenRange(Scope->getSourceRange()), ScopeName);
5238}
5239
5241 SourceLocation RParenLoc, MultiExprArg Args,
5243 AtomicArgumentOrder ArgOrder) {
5244 // All the non-OpenCL operations take one of the following forms.
5245 // The OpenCL operations take the __c11 forms with one extra argument for
5246 // synchronization scope.
5247 enum {
5248 // C __c11_atomic_init(A *, C)
5249 Init,
5250
5251 // C __c11_atomic_load(A *, int)
5252 Load,
5253
5254 // void __atomic_load(A *, CP, int)
5255 LoadCopy,
5256
5257 // void __atomic_store(A *, CP, int)
5258 Copy,
5259
5260 // C __c11_atomic_add(A *, M, int)
5261 Arithmetic,
5262
5263 // C __atomic_exchange_n(A *, CP, int)
5264 Xchg,
5265
5266 // void __atomic_exchange(A *, C *, CP, int)
5267 GNUXchg,
5268
5269 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5270 C11CmpXchg,
5271
5272 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5273 GNUCmpXchg,
5274
5275 // bool __atomic_test_and_set(A *, int)
5276 TestAndSetByte,
5277
5278 // void __atomic_clear(A *, int)
5279 ClearByte,
5280 } Form = Init;
5281
5282 const unsigned NumForm = ClearByte + 1;
5283 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
5284 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
5285 // where:
5286 // C is an appropriate type,
5287 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5288 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5289 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5290 // the int parameters are for orderings.
5291
5292 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5293 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5294 "need to update code for modified forms");
5295 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
5296 AtomicExpr::AO__atomic_xor_fetch + 1 ==
5297 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
5298 "need to update code for modified C11 atomics");
5299 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
5300 Op <= AtomicExpr::AO__opencl_atomic_store;
5301 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
5302 Op <= AtomicExpr::AO__hip_atomic_store;
5303 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
5304 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
5305 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
5306 Op <= AtomicExpr::AO__c11_atomic_store) ||
5307 IsOpenCL;
5308 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5309 Op == AtomicExpr::AO__atomic_store_n ||
5310 Op == AtomicExpr::AO__atomic_exchange_n ||
5311 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
5312 Op == AtomicExpr::AO__scoped_atomic_load_n ||
5313 Op == AtomicExpr::AO__scoped_atomic_store_n ||
5314 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
5315 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
5316 // Bit mask for extra allowed value types other than integers for atomic
5317 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
5318 // allow floating point.
5319 enum ArithOpExtraValueType {
5320 AOEVT_None = 0,
5321 AOEVT_Pointer = 1,
5322 AOEVT_FP = 2,
5323 AOEVT_Int = 4,
5324 };
5325 unsigned ArithAllows = AOEVT_None;
5326
5327 switch (Op) {
5328 case AtomicExpr::AO__c11_atomic_init:
5329 case AtomicExpr::AO__opencl_atomic_init:
5330 Form = Init;
5331 break;
5332
5333 case AtomicExpr::AO__c11_atomic_load:
5334 case AtomicExpr::AO__opencl_atomic_load:
5335 case AtomicExpr::AO__hip_atomic_load:
5336 case AtomicExpr::AO__atomic_load_n:
5337 case AtomicExpr::AO__scoped_atomic_load_n:
5338 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5339 Form = Load;
5340 break;
5341
5342 case AtomicExpr::AO__atomic_load:
5343 case AtomicExpr::AO__scoped_atomic_load:
5344 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5345 Form = LoadCopy;
5346 break;
5347
5348 case AtomicExpr::AO__c11_atomic_store:
5349 case AtomicExpr::AO__opencl_atomic_store:
5350 case AtomicExpr::AO__hip_atomic_store:
5351 case AtomicExpr::AO__atomic_store:
5352 case AtomicExpr::AO__atomic_store_n:
5353 case AtomicExpr::AO__scoped_atomic_store:
5354 case AtomicExpr::AO__scoped_atomic_store_n:
5355 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5356 Form = Copy;
5357 break;
5358 case AtomicExpr::AO__atomic_fetch_add:
5359 case AtomicExpr::AO__atomic_fetch_sub:
5360 case AtomicExpr::AO__atomic_add_fetch:
5361 case AtomicExpr::AO__atomic_sub_fetch:
5362 case AtomicExpr::AO__scoped_atomic_fetch_add:
5363 case AtomicExpr::AO__scoped_atomic_fetch_sub:
5364 case AtomicExpr::AO__scoped_atomic_add_fetch:
5365 case AtomicExpr::AO__scoped_atomic_sub_fetch:
5366 case AtomicExpr::AO__c11_atomic_fetch_add:
5367 case AtomicExpr::AO__c11_atomic_fetch_sub:
5368 case AtomicExpr::AO__opencl_atomic_fetch_add:
5369 case AtomicExpr::AO__opencl_atomic_fetch_sub:
5370 case AtomicExpr::AO__hip_atomic_fetch_add:
5371 case AtomicExpr::AO__hip_atomic_fetch_sub:
5372 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5373 Form = Arithmetic;
5374 break;
5375 case AtomicExpr::AO__atomic_fetch_fminimum:
5376 case AtomicExpr::AO__atomic_fetch_fmaximum:
5377 case AtomicExpr::AO__atomic_fetch_fminimum_num:
5378 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
5379 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
5380 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
5381 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
5382 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
5383 ArithAllows = AOEVT_FP;
5384 Form = Arithmetic;
5385 break;
5386 case AtomicExpr::AO__atomic_fetch_max:
5387 case AtomicExpr::AO__atomic_fetch_min:
5388 case AtomicExpr::AO__atomic_max_fetch:
5389 case AtomicExpr::AO__atomic_min_fetch:
5390 case AtomicExpr::AO__scoped_atomic_fetch_max:
5391 case AtomicExpr::AO__scoped_atomic_fetch_min:
5392 case AtomicExpr::AO__scoped_atomic_max_fetch:
5393 case AtomicExpr::AO__scoped_atomic_min_fetch:
5394 case AtomicExpr::AO__c11_atomic_fetch_max:
5395 case AtomicExpr::AO__c11_atomic_fetch_min:
5396 case AtomicExpr::AO__opencl_atomic_fetch_max:
5397 case AtomicExpr::AO__opencl_atomic_fetch_min:
5398 case AtomicExpr::AO__hip_atomic_fetch_max:
5399 case AtomicExpr::AO__hip_atomic_fetch_min:
5400 ArithAllows = AOEVT_Int | AOEVT_FP;
5401 Form = Arithmetic;
5402 break;
5403 case AtomicExpr::AO__c11_atomic_fetch_and:
5404 case AtomicExpr::AO__c11_atomic_fetch_or:
5405 case AtomicExpr::AO__c11_atomic_fetch_xor:
5406 case AtomicExpr::AO__hip_atomic_fetch_and:
5407 case AtomicExpr::AO__hip_atomic_fetch_or:
5408 case AtomicExpr::AO__hip_atomic_fetch_xor:
5409 case AtomicExpr::AO__c11_atomic_fetch_nand:
5410 case AtomicExpr::AO__opencl_atomic_fetch_and:
5411 case AtomicExpr::AO__opencl_atomic_fetch_or:
5412 case AtomicExpr::AO__opencl_atomic_fetch_xor:
5413 case AtomicExpr::AO__atomic_fetch_and:
5414 case AtomicExpr::AO__atomic_fetch_or:
5415 case AtomicExpr::AO__atomic_fetch_xor:
5416 case AtomicExpr::AO__atomic_fetch_nand:
5417 case AtomicExpr::AO__atomic_and_fetch:
5418 case AtomicExpr::AO__atomic_or_fetch:
5419 case AtomicExpr::AO__atomic_xor_fetch:
5420 case AtomicExpr::AO__atomic_nand_fetch:
5421 case AtomicExpr::AO__atomic_fetch_uinc:
5422 case AtomicExpr::AO__atomic_fetch_udec:
5423 case AtomicExpr::AO__scoped_atomic_fetch_and:
5424 case AtomicExpr::AO__scoped_atomic_fetch_or:
5425 case AtomicExpr::AO__scoped_atomic_fetch_xor:
5426 case AtomicExpr::AO__scoped_atomic_fetch_nand:
5427 case AtomicExpr::AO__scoped_atomic_and_fetch:
5428 case AtomicExpr::AO__scoped_atomic_or_fetch:
5429 case AtomicExpr::AO__scoped_atomic_xor_fetch:
5430 case AtomicExpr::AO__scoped_atomic_nand_fetch:
5431 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
5432 case AtomicExpr::AO__scoped_atomic_fetch_udec:
5433 Form = Arithmetic;
5434 break;
5435
5436 case AtomicExpr::AO__c11_atomic_exchange:
5437 case AtomicExpr::AO__hip_atomic_exchange:
5438 case AtomicExpr::AO__opencl_atomic_exchange:
5439 case AtomicExpr::AO__atomic_exchange_n:
5440 case AtomicExpr::AO__scoped_atomic_exchange_n:
5441 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5442 Form = Xchg;
5443 break;
5444
5445 case AtomicExpr::AO__atomic_exchange:
5446 case AtomicExpr::AO__scoped_atomic_exchange:
5447 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5448 Form = GNUXchg;
5449 break;
5450
5451 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5452 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5453 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5454 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5455 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5456 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5457 Form = C11CmpXchg;
5458 break;
5459
5460 case AtomicExpr::AO__atomic_compare_exchange:
5461 case AtomicExpr::AO__atomic_compare_exchange_n:
5462 case AtomicExpr::AO__scoped_atomic_compare_exchange:
5463 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
5464 ArithAllows = AOEVT_Pointer;
5465 Form = GNUCmpXchg;
5466 break;
5467
5468 case AtomicExpr::AO__atomic_test_and_set:
5469 Form = TestAndSetByte;
5470 break;
5471
5472 case AtomicExpr::AO__atomic_clear:
5473 Form = ClearByte;
5474 break;
5475 }
5476
5477 unsigned AdjustedNumArgs = NumArgs[Form];
5478 if ((IsOpenCL || IsHIP || IsScoped) &&
5479 Op != AtomicExpr::AO__opencl_atomic_init)
5480 ++AdjustedNumArgs;
5481 // Check we have the right number of arguments.
5482 if (Args.size() < AdjustedNumArgs) {
5483 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5484 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5485 << /*is non object*/ 0 << ExprRange;
5486 return ExprError();
5487 } else if (Args.size() > AdjustedNumArgs) {
5488 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5489 diag::err_typecheck_call_too_many_args)
5490 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5491 << /*is non object*/ 0 << ExprRange;
5492 return ExprError();
5493 }
5494
5495 // Inspect the first argument of the atomic operation.
5496 Expr *Ptr = Args[0];
5498 if (ConvertedPtr.isInvalid())
5499 return ExprError();
5500
5501 Ptr = ConvertedPtr.get();
5502 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5503 if (!pointerType) {
5504 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5505 << Ptr->getType() << 0 << Ptr->getSourceRange();
5506 return ExprError();
5507 }
5508
5509 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5510 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5511 QualType ValType = AtomTy; // 'C'
5512 if (IsC11) {
5513 if (!AtomTy->isAtomicType()) {
5514 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5515 << Ptr->getType() << Ptr->getSourceRange();
5516 return ExprError();
5517 }
5518 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5520 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5521 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5522 << Ptr->getSourceRange();
5523 return ExprError();
5524 }
5525 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5526 } else if (Form != Load && Form != LoadCopy) {
5527 if (ValType.isConstQualified()) {
5528 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5529 << Ptr->getType() << Ptr->getSourceRange();
5530 return ExprError();
5531 }
5532 }
5533
5534 if (Form != TestAndSetByte && Form != ClearByte) {
5535 // Pointer to object of size zero is not allowed.
5536 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
5537 diag::err_incomplete_type))
5538 return ExprError();
5539
5540 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
5541 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5542 << Ptr->getType() << 1 << Ptr->getSourceRange();
5543 return ExprError();
5544 }
5545 } else {
5546 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
5547 // non-const pointer type, including void* and pointers to incomplete
5548 // structs, but only access the first byte.
5549 AtomTy = Context.CharTy;
5550 AtomTy = AtomTy.withCVRQualifiers(
5551 pointerType->getPointeeType().getCVRQualifiers());
5552 QualType PointerQT = Context.getPointerType(AtomTy);
5553 pointerType = PointerQT->getAs<PointerType>();
5554 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
5555 ValType = AtomTy;
5556 }
5557
5558 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
5559 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5560 Diag(ExprRange.getBegin(),
5561 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5562 << 0 << Ptr->getType() << Ptr->getSourceRange();
5563 return ExprError();
5564 }
5565
5566 // For an arithmetic operation, the implied arithmetic must be well-formed.
5567 // For _n operations, the value type must also be a valid atomic type.
5568 if (Form == Arithmetic || IsN) {
5569 // GCC does not enforce these rules for GNU atomics, but we do to help catch
5570 // trivial type errors.
5571 auto IsAllowedValueType = [&](QualType ValType,
5572 unsigned AllowedType) -> bool {
5573 bool IsX87LongDouble =
5574 ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5575 &Context.getTargetInfo().getLongDoubleFormat() ==
5576 &llvm::APFloat::x87DoubleExtended();
5577 if (ValType->isIntegerType())
5578 // Special case: f-prefixed operations (AOEVT_FP exactly) reject
5579 // integers. Explicit AOEVT_Int or other combinations allow integers.
5580 return (AllowedType & AOEVT_Int) || AllowedType != AOEVT_FP;
5581 if (ValType->isPointerType())
5582 return AllowedType & AOEVT_Pointer;
5583 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
5584 return false;
5585 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5586 if (IsX87LongDouble)
5587 return false;
5588 return true;
5589 };
5590 if (!IsAllowedValueType(ValType, ArithAllows)) {
5591 auto DID =
5592 ArithAllows == AOEVT_FP
5593 ? diag::err_atomic_op_needs_atomic_fp
5594 : (ArithAllows & AOEVT_FP
5595 ? (ArithAllows & AOEVT_Pointer
5596 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
5597 : diag::err_atomic_op_needs_atomic_int_or_fp)
5598 : (ArithAllows & AOEVT_Pointer
5599 ? diag::err_atomic_op_needs_atomic_int_or_ptr
5600 : diag::err_atomic_op_needs_atomic_int));
5601 Diag(ExprRange.getBegin(), DID)
5602 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5603 return ExprError();
5604 }
5605 if (IsC11 && ValType->isPointerType() &&
5606 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5607 diag::err_incomplete_type)) {
5608 return ExprError();
5609 }
5610 }
5611
5612 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5613 !AtomTy->isScalarType()) {
5614 // For GNU atomics, require a trivially-copyable type. This is not part of
5615 // the GNU atomics specification but we enforce it for consistency with
5616 // other atomics which generally all require a trivially-copyable type. This
5617 // is because atomics just copy bits.
5618 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5619 << Ptr->getType() << Ptr->getSourceRange();
5620 return ExprError();
5621 }
5622
5623 switch (ValType.getObjCLifetime()) {
5626 // okay
5627 break;
5628
5632 // FIXME: Can this happen? By this point, ValType should be known
5633 // to be trivially copyable.
5634 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5635 << ValType << Ptr->getSourceRange();
5636 return ExprError();
5637 }
5638
5639 // All atomic operations have an overload which takes a pointer to a volatile
5640 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
5641 // into the result or the other operands. Similarly atomic_load takes a
5642 // pointer to a const 'A'.
5643 ValType.removeLocalVolatile();
5644 ValType.removeLocalConst();
5645 QualType ResultType = ValType;
5646 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
5647 Form == ClearByte)
5648 ResultType = Context.VoidTy;
5649 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
5650 ResultType = Context.BoolTy;
5651
5652 // The type of a parameter passed 'by value'. In the GNU atomics, such
5653 // arguments are actually passed as pointers.
5654 QualType ByValType = ValType; // 'CP'
5655 bool IsPassedByAddress = false;
5656 if (!IsC11 && !IsHIP && !IsN) {
5657 ByValType = Ptr->getType();
5658 IsPassedByAddress = true;
5659 }
5660
5661 SmallVector<Expr *, 5> APIOrderedArgs;
5662 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5663 APIOrderedArgs.push_back(Args[0]);
5664 switch (Form) {
5665 case Init:
5666 case Load:
5667 APIOrderedArgs.push_back(Args[1]); // Val1/Order
5668 break;
5669 case LoadCopy:
5670 case Copy:
5671 case Arithmetic:
5672 case Xchg:
5673 APIOrderedArgs.push_back(Args[2]); // Val1
5674 APIOrderedArgs.push_back(Args[1]); // Order
5675 break;
5676 case GNUXchg:
5677 APIOrderedArgs.push_back(Args[2]); // Val1
5678 APIOrderedArgs.push_back(Args[3]); // Val2
5679 APIOrderedArgs.push_back(Args[1]); // Order
5680 break;
5681 case C11CmpXchg:
5682 APIOrderedArgs.push_back(Args[2]); // Val1
5683 APIOrderedArgs.push_back(Args[4]); // Val2
5684 APIOrderedArgs.push_back(Args[1]); // Order
5685 APIOrderedArgs.push_back(Args[3]); // OrderFail
5686 break;
5687 case GNUCmpXchg:
5688 APIOrderedArgs.push_back(Args[2]); // Val1
5689 APIOrderedArgs.push_back(Args[4]); // Val2
5690 APIOrderedArgs.push_back(Args[5]); // Weak
5691 APIOrderedArgs.push_back(Args[1]); // Order
5692 APIOrderedArgs.push_back(Args[3]); // OrderFail
5693 break;
5694 case TestAndSetByte:
5695 case ClearByte:
5696 APIOrderedArgs.push_back(Args[1]); // Order
5697 break;
5698 }
5699 } else
5700 APIOrderedArgs.append(Args.begin(), Args.end());
5701
5702 // The first argument's non-CV pointer type is used to deduce the type of
5703 // subsequent arguments, except for:
5704 // - weak flag (always converted to bool)
5705 // - memory order (always converted to int)
5706 // - scope (always converted to int)
5707 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5708 QualType Ty;
5709 if (i < NumVals[Form] + 1) {
5710 switch (i) {
5711 case 0:
5712 // The first argument is always a pointer. It has a fixed type.
5713 // It is always dereferenced, a nullptr is undefined.
5714 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5715 // Nothing else to do: we already know all we want about this pointer.
5716 continue;
5717 case 1:
5718 // The second argument is the non-atomic operand. For arithmetic, this
5719 // is always passed by value, and for a compare_exchange it is always
5720 // passed by address. For the rest, GNU uses by-address and C11 uses
5721 // by-value.
5722 assert(Form != Load);
5723 if (Form == Arithmetic && ValType->isPointerType())
5724 Ty = Context.getPointerDiffType();
5725 else if (Form == Init || Form == Arithmetic)
5726 Ty = ValType;
5727 else if (Form == Copy || Form == Xchg) {
5728 if (IsPassedByAddress) {
5729 // The value pointer is always dereferenced, a nullptr is undefined.
5730 CheckNonNullArgument(*this, APIOrderedArgs[i],
5731 ExprRange.getBegin());
5732 }
5733 Ty = ByValType;
5734 } else {
5735 Expr *ValArg = APIOrderedArgs[i];
5736 // The value pointer is always dereferenced, a nullptr is undefined.
5737 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5739 // Keep address space of non-atomic pointer type.
5740 if (const PointerType *PtrTy =
5741 ValArg->getType()->getAs<PointerType>()) {
5742 AS = PtrTy->getPointeeType().getAddressSpace();
5743 }
5744 Ty = Context.getPointerType(
5745 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5746 }
5747 break;
5748 case 2:
5749 // The third argument to compare_exchange / GNU exchange is the desired
5750 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5751 if (IsPassedByAddress)
5752 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5753 Ty = ByValType;
5754 break;
5755 case 3:
5756 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5757 Ty = Context.BoolTy;
5758 break;
5759 }
5760 } else {
5761 // The order(s) and scope are always converted to int.
5762 Ty = Context.IntTy;
5763 }
5764
5765 InitializedEntity Entity =
5767 ExprResult Arg = APIOrderedArgs[i];
5768 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5769 if (Arg.isInvalid())
5770 return true;
5771 APIOrderedArgs[i] = Arg.get();
5772 }
5773
5774 // Permute the arguments into a 'consistent' order.
5775 SmallVector<Expr*, 5> SubExprs;
5776 SubExprs.push_back(Ptr);
5777 switch (Form) {
5778 case Init:
5779 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5780 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5781 break;
5782 case Load:
5783 case TestAndSetByte:
5784 case ClearByte:
5785 SubExprs.push_back(APIOrderedArgs[1]); // Order
5786 break;
5787 case LoadCopy:
5788 case Copy:
5789 case Arithmetic:
5790 case Xchg:
5791 SubExprs.push_back(APIOrderedArgs[2]); // Order
5792 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5793 break;
5794 case GNUXchg:
5795 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5796 SubExprs.push_back(APIOrderedArgs[3]); // Order
5797 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5798 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5799 break;
5800 case C11CmpXchg:
5801 SubExprs.push_back(APIOrderedArgs[3]); // Order
5802 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5803 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5804 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5805 break;
5806 case GNUCmpXchg:
5807 SubExprs.push_back(APIOrderedArgs[4]); // Order
5808 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5809 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5810 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5811 SubExprs.push_back(APIOrderedArgs[3]); // Weak
5812 break;
5813 }
5814
5815 // If the memory orders are constants, check they are valid.
5816 if (SubExprs.size() >= 2 && Form != Init) {
5817 std::optional<llvm::APSInt> Success =
5818 SubExprs[1]->getIntegerConstantExpr(Context);
5819 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
5820 Diag(SubExprs[1]->getBeginLoc(),
5821 diag::warn_atomic_op_has_invalid_memory_order)
5822 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5823 << SubExprs[1]->getSourceRange();
5824 }
5825 if (SubExprs.size() >= 5) {
5826 if (std::optional<llvm::APSInt> Failure =
5827 SubExprs[3]->getIntegerConstantExpr(Context)) {
5828 if (!llvm::is_contained(
5829 {llvm::AtomicOrderingCABI::relaxed,
5830 llvm::AtomicOrderingCABI::consume,
5831 llvm::AtomicOrderingCABI::acquire,
5832 llvm::AtomicOrderingCABI::seq_cst},
5833 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5834 Diag(SubExprs[3]->getBeginLoc(),
5835 diag::warn_atomic_op_has_invalid_memory_order)
5836 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5837 }
5838 }
5839 }
5840 }
5841
5842 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5843 auto *Scope = Args[Args.size() - 1];
5844 if (std::optional<llvm::APSInt> Result =
5845 Scope->getIntegerConstantExpr(Context)) {
5846 if (!ScopeModel->isValid(Result->getZExtValue()))
5847 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
5848 << Scope->getSourceRange();
5849 }
5850 SubExprs.push_back(Scope);
5851 }
5852
5853 if (IsHIP)
5854 DiagnoseDeprecatedHIPAtomic(*this, ExprRange, Args, Op);
5855
5856 AtomicExpr *AE = new (Context)
5857 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5858
5859 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5860 Op == AtomicExpr::AO__c11_atomic_store ||
5861 Op == AtomicExpr::AO__opencl_atomic_load ||
5862 Op == AtomicExpr::AO__hip_atomic_load ||
5863 Op == AtomicExpr::AO__opencl_atomic_store ||
5864 Op == AtomicExpr::AO__hip_atomic_store) &&
5865 Context.AtomicUsesUnsupportedLibcall(AE))
5866 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5867 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5868 Op == AtomicExpr::AO__opencl_atomic_load ||
5869 Op == AtomicExpr::AO__hip_atomic_load)
5870 ? 0
5871 : 1);
5872
5873 if (ValType->isBitIntType()) {
5874 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5875 return ExprError();
5876 }
5877
5878 return AE;
5879}
5880
5881/// checkBuiltinArgument - Given a call to a builtin function, perform
5882/// normal type-checking on the given argument, updating the call in
5883/// place. This is useful when a builtin function requires custom
5884/// type-checking for some of its arguments but not necessarily all of
5885/// them.
5886///
5887/// Returns true on error.
5888static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5889 FunctionDecl *Fn = E->getDirectCallee();
5890 assert(Fn && "builtin call without direct callee!");
5891
5892 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5893 InitializedEntity Entity =
5895
5896 ExprResult Arg = E->getArg(ArgIndex);
5897 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5898 if (Arg.isInvalid())
5899 return true;
5900
5901 E->setArg(ArgIndex, Arg.get());
5902 return false;
5903}
5904
5905ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5906 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5907 Expr *Callee = TheCall->getCallee();
5908 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5909 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5910
5911 // Ensure that we have at least one argument to do type inference from.
5912 if (TheCall->getNumArgs() < 1) {
5913 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5914 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5915 << Callee->getSourceRange();
5916 return ExprError();
5917 }
5918
5919 // Inspect the first argument of the atomic builtin. This should always be
5920 // a pointer type, whose element is an integral scalar or pointer type.
5921 // Because it is a pointer type, we don't have to worry about any implicit
5922 // casts here.
5923 // FIXME: We don't allow floating point scalars as input.
5924 Expr *FirstArg = TheCall->getArg(0);
5925 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5926 if (FirstArgResult.isInvalid())
5927 return ExprError();
5928 FirstArg = FirstArgResult.get();
5929 TheCall->setArg(0, FirstArg);
5930
5931 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5932 if (!pointerType) {
5933 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5934 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5935 return ExprError();
5936 }
5937
5938 QualType ValType = pointerType->getPointeeType();
5939 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5940 !ValType->isBlockPointerType()) {
5941 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5942 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5943 return ExprError();
5944 }
5945 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5946 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5947 Diag(FirstArg->getBeginLoc(),
5948 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5949 << 1 << ValType << FirstArg->getSourceRange();
5950 return ExprError();
5951 }
5952
5953 if (ValType.isConstQualified()) {
5954 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5955 << FirstArg->getType() << FirstArg->getSourceRange();
5956 return ExprError();
5957 }
5958
5959 switch (ValType.getObjCLifetime()) {
5962 // okay
5963 break;
5964
5968 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5969 << ValType << FirstArg->getSourceRange();
5970
5971 return ExprError();
5972 }
5973
5974 // Strip any qualifiers off ValType.
5975 ValType = ValType.getUnqualifiedType();
5976
5977 // The majority of builtins return a value, but a few have special return
5978 // types, so allow them to override appropriately below.
5979 QualType ResultType = ValType;
5980
5981 // We need to figure out which concrete builtin this maps onto. For example,
5982 // __sync_fetch_and_add with a 2 byte object turns into
5983 // __sync_fetch_and_add_2.
5984#define BUILTIN_ROW(x) \
5985 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5986 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5987
5988 static const unsigned BuiltinIndices[][5] = {
5989 BUILTIN_ROW(__sync_fetch_and_add),
5990 BUILTIN_ROW(__sync_fetch_and_sub),
5991 BUILTIN_ROW(__sync_fetch_and_or),
5992 BUILTIN_ROW(__sync_fetch_and_and),
5993 BUILTIN_ROW(__sync_fetch_and_xor),
5994 BUILTIN_ROW(__sync_fetch_and_nand),
5995
5996 BUILTIN_ROW(__sync_add_and_fetch),
5997 BUILTIN_ROW(__sync_sub_and_fetch),
5998 BUILTIN_ROW(__sync_and_and_fetch),
5999 BUILTIN_ROW(__sync_or_and_fetch),
6000 BUILTIN_ROW(__sync_xor_and_fetch),
6001 BUILTIN_ROW(__sync_nand_and_fetch),
6002
6003 BUILTIN_ROW(__sync_val_compare_and_swap),
6004 BUILTIN_ROW(__sync_bool_compare_and_swap),
6005 BUILTIN_ROW(__sync_lock_test_and_set),
6006 BUILTIN_ROW(__sync_lock_release),
6007 BUILTIN_ROW(__sync_swap)
6008 };
6009#undef BUILTIN_ROW
6010
6011 // Determine the index of the size.
6012 unsigned SizeIndex;
6013 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
6014 case 1: SizeIndex = 0; break;
6015 case 2: SizeIndex = 1; break;
6016 case 4: SizeIndex = 2; break;
6017 case 8: SizeIndex = 3; break;
6018 case 16: SizeIndex = 4; break;
6019 default:
6020 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
6021 << FirstArg->getType() << FirstArg->getSourceRange();
6022 return ExprError();
6023 }
6024
6025 // Each of these builtins has one pointer argument, followed by some number of
6026 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
6027 // that we ignore. Find out which row of BuiltinIndices to read from as well
6028 // as the number of fixed args.
6029 unsigned BuiltinID = FDecl->getBuiltinID();
6030 unsigned BuiltinIndex, NumFixed = 1;
6031 bool WarnAboutSemanticsChange = false;
6032 switch (BuiltinID) {
6033 default: llvm_unreachable("Unknown overloaded atomic builtin!");
6034 case Builtin::BI__sync_fetch_and_add:
6035 case Builtin::BI__sync_fetch_and_add_1:
6036 case Builtin::BI__sync_fetch_and_add_2:
6037 case Builtin::BI__sync_fetch_and_add_4:
6038 case Builtin::BI__sync_fetch_and_add_8:
6039 case Builtin::BI__sync_fetch_and_add_16:
6040 BuiltinIndex = 0;
6041 break;
6042
6043 case Builtin::BI__sync_fetch_and_sub:
6044 case Builtin::BI__sync_fetch_and_sub_1:
6045 case Builtin::BI__sync_fetch_and_sub_2:
6046 case Builtin::BI__sync_fetch_and_sub_4:
6047 case Builtin::BI__sync_fetch_and_sub_8:
6048 case Builtin::BI__sync_fetch_and_sub_16:
6049 BuiltinIndex = 1;
6050 break;
6051
6052 case Builtin::BI__sync_fetch_and_or:
6053 case Builtin::BI__sync_fetch_and_or_1:
6054 case Builtin::BI__sync_fetch_and_or_2:
6055 case Builtin::BI__sync_fetch_and_or_4:
6056 case Builtin::BI__sync_fetch_and_or_8:
6057 case Builtin::BI__sync_fetch_and_or_16:
6058 BuiltinIndex = 2;
6059 break;
6060
6061 case Builtin::BI__sync_fetch_and_and:
6062 case Builtin::BI__sync_fetch_and_and_1:
6063 case Builtin::BI__sync_fetch_and_and_2:
6064 case Builtin::BI__sync_fetch_and_and_4:
6065 case Builtin::BI__sync_fetch_and_and_8:
6066 case Builtin::BI__sync_fetch_and_and_16:
6067 BuiltinIndex = 3;
6068 break;
6069
6070 case Builtin::BI__sync_fetch_and_xor:
6071 case Builtin::BI__sync_fetch_and_xor_1:
6072 case Builtin::BI__sync_fetch_and_xor_2:
6073 case Builtin::BI__sync_fetch_and_xor_4:
6074 case Builtin::BI__sync_fetch_and_xor_8:
6075 case Builtin::BI__sync_fetch_and_xor_16:
6076 BuiltinIndex = 4;
6077 break;
6078
6079 case Builtin::BI__sync_fetch_and_nand:
6080 case Builtin::BI__sync_fetch_and_nand_1:
6081 case Builtin::BI__sync_fetch_and_nand_2:
6082 case Builtin::BI__sync_fetch_and_nand_4:
6083 case Builtin::BI__sync_fetch_and_nand_8:
6084 case Builtin::BI__sync_fetch_and_nand_16:
6085 BuiltinIndex = 5;
6086 WarnAboutSemanticsChange = true;
6087 break;
6088
6089 case Builtin::BI__sync_add_and_fetch:
6090 case Builtin::BI__sync_add_and_fetch_1:
6091 case Builtin::BI__sync_add_and_fetch_2:
6092 case Builtin::BI__sync_add_and_fetch_4:
6093 case Builtin::BI__sync_add_and_fetch_8:
6094 case Builtin::BI__sync_add_and_fetch_16:
6095 BuiltinIndex = 6;
6096 break;
6097
6098 case Builtin::BI__sync_sub_and_fetch:
6099 case Builtin::BI__sync_sub_and_fetch_1:
6100 case Builtin::BI__sync_sub_and_fetch_2:
6101 case Builtin::BI__sync_sub_and_fetch_4:
6102 case Builtin::BI__sync_sub_and_fetch_8:
6103 case Builtin::BI__sync_sub_and_fetch_16:
6104 BuiltinIndex = 7;
6105 break;
6106
6107 case Builtin::BI__sync_and_and_fetch:
6108 case Builtin::BI__sync_and_and_fetch_1:
6109 case Builtin::BI__sync_and_and_fetch_2:
6110 case Builtin::BI__sync_and_and_fetch_4:
6111 case Builtin::BI__sync_and_and_fetch_8:
6112 case Builtin::BI__sync_and_and_fetch_16:
6113 BuiltinIndex = 8;
6114 break;
6115
6116 case Builtin::BI__sync_or_and_fetch:
6117 case Builtin::BI__sync_or_and_fetch_1:
6118 case Builtin::BI__sync_or_and_fetch_2:
6119 case Builtin::BI__sync_or_and_fetch_4:
6120 case Builtin::BI__sync_or_and_fetch_8:
6121 case Builtin::BI__sync_or_and_fetch_16:
6122 BuiltinIndex = 9;
6123 break;
6124
6125 case Builtin::BI__sync_xor_and_fetch:
6126 case Builtin::BI__sync_xor_and_fetch_1:
6127 case Builtin::BI__sync_xor_and_fetch_2:
6128 case Builtin::BI__sync_xor_and_fetch_4:
6129 case Builtin::BI__sync_xor_and_fetch_8:
6130 case Builtin::BI__sync_xor_and_fetch_16:
6131 BuiltinIndex = 10;
6132 break;
6133
6134 case Builtin::BI__sync_nand_and_fetch:
6135 case Builtin::BI__sync_nand_and_fetch_1:
6136 case Builtin::BI__sync_nand_and_fetch_2:
6137 case Builtin::BI__sync_nand_and_fetch_4:
6138 case Builtin::BI__sync_nand_and_fetch_8:
6139 case Builtin::BI__sync_nand_and_fetch_16:
6140 BuiltinIndex = 11;
6141 WarnAboutSemanticsChange = true;
6142 break;
6143
6144 case Builtin::BI__sync_val_compare_and_swap:
6145 case Builtin::BI__sync_val_compare_and_swap_1:
6146 case Builtin::BI__sync_val_compare_and_swap_2:
6147 case Builtin::BI__sync_val_compare_and_swap_4:
6148 case Builtin::BI__sync_val_compare_and_swap_8:
6149 case Builtin::BI__sync_val_compare_and_swap_16:
6150 BuiltinIndex = 12;
6151 NumFixed = 2;
6152 break;
6153
6154 case Builtin::BI__sync_bool_compare_and_swap:
6155 case Builtin::BI__sync_bool_compare_and_swap_1:
6156 case Builtin::BI__sync_bool_compare_and_swap_2:
6157 case Builtin::BI__sync_bool_compare_and_swap_4:
6158 case Builtin::BI__sync_bool_compare_and_swap_8:
6159 case Builtin::BI__sync_bool_compare_and_swap_16:
6160 BuiltinIndex = 13;
6161 NumFixed = 2;
6162 ResultType = Context.BoolTy;
6163 break;
6164
6165 case Builtin::BI__sync_lock_test_and_set:
6166 case Builtin::BI__sync_lock_test_and_set_1:
6167 case Builtin::BI__sync_lock_test_and_set_2:
6168 case Builtin::BI__sync_lock_test_and_set_4:
6169 case Builtin::BI__sync_lock_test_and_set_8:
6170 case Builtin::BI__sync_lock_test_and_set_16:
6171 BuiltinIndex = 14;
6172 break;
6173
6174 case Builtin::BI__sync_lock_release:
6175 case Builtin::BI__sync_lock_release_1:
6176 case Builtin::BI__sync_lock_release_2:
6177 case Builtin::BI__sync_lock_release_4:
6178 case Builtin::BI__sync_lock_release_8:
6179 case Builtin::BI__sync_lock_release_16:
6180 BuiltinIndex = 15;
6181 NumFixed = 0;
6182 ResultType = Context.VoidTy;
6183 break;
6184
6185 case Builtin::BI__sync_swap:
6186 case Builtin::BI__sync_swap_1:
6187 case Builtin::BI__sync_swap_2:
6188 case Builtin::BI__sync_swap_4:
6189 case Builtin::BI__sync_swap_8:
6190 case Builtin::BI__sync_swap_16:
6191 BuiltinIndex = 16;
6192 break;
6193 }
6194
6195 // Now that we know how many fixed arguments we expect, first check that we
6196 // have at least that many.
6197 if (TheCall->getNumArgs() < 1+NumFixed) {
6198 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6199 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
6200 << Callee->getSourceRange();
6201 return ExprError();
6202 }
6203
6204 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6205 << Callee->getSourceRange();
6206
6207 if (WarnAboutSemanticsChange) {
6208 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6209 << Callee->getSourceRange();
6210 }
6211
6212 // Get the decl for the concrete builtin from this, we can tell what the
6213 // concrete integer type we should convert to is.
6214 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6215 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6216 FunctionDecl *NewBuiltinDecl;
6217 if (NewBuiltinID == BuiltinID)
6218 NewBuiltinDecl = FDecl;
6219 else {
6220 // Perform builtin lookup to avoid redeclaring it.
6221 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6222 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6223 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6224 assert(Res.getFoundDecl());
6225 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6226 if (!NewBuiltinDecl)
6227 return ExprError();
6228 }
6229
6230 // The first argument --- the pointer --- has a fixed type; we
6231 // deduce the types of the rest of the arguments accordingly. Walk
6232 // the remaining arguments, converting them to the deduced value type.
6233 for (unsigned i = 0; i != NumFixed; ++i) {
6234 ExprResult Arg = TheCall->getArg(i+1);
6235
6236 // GCC does an implicit conversion to the pointer or integer ValType. This
6237 // can fail in some cases (1i -> int**), check for this error case now.
6238 // Initialize the argument.
6239 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6240 ValType, /*consume*/ false);
6241 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6242 if (Arg.isInvalid())
6243 return ExprError();
6244
6245 // Okay, we have something that *can* be converted to the right type. Check
6246 // to see if there is a potentially weird extension going on here. This can
6247 // happen when you do an atomic operation on something like an char* and
6248 // pass in 42. The 42 gets converted to char. This is even more strange
6249 // for things like 45.123 -> char, etc.
6250 // FIXME: Do this check.
6251 TheCall->setArg(i+1, Arg.get());
6252 }
6253
6254 // Create a new DeclRefExpr to refer to the new decl.
6255 DeclRefExpr *NewDRE = DeclRefExpr::Create(
6256 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6257 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6258 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6259
6260 // Set the callee in the CallExpr.
6261 // FIXME: This loses syntactic information.
6262 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6263 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6264 CK_BuiltinFnToFnPtr);
6265 TheCall->setCallee(PromotedCall.get());
6266
6267 // Change the result type of the call to match the original value type. This
6268 // is arbitrary, but the codegen for these builtins ins design to handle it
6269 // gracefully.
6270 TheCall->setType(ResultType);
6271
6272 // Prohibit problematic uses of bit-precise integer types with atomic
6273 // builtins. The arguments would have already been converted to the first
6274 // argument's type, so only need to check the first argument.
6275 const auto *BitIntValType = ValType->getAs<BitIntType>();
6276 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6277 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6278 return ExprError();
6279 }
6280
6281 return TheCallResult;
6282}
6283
6284ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6285 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6286 DeclRefExpr *DRE =
6288 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6289 unsigned BuiltinID = FDecl->getBuiltinID();
6290 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6291 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6292 "Unexpected nontemporal load/store builtin!");
6293 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6294 unsigned numArgs = isStore ? 2 : 1;
6295
6296 // Ensure that we have the proper number of arguments.
6297 if (checkArgCount(TheCall, numArgs))
6298 return ExprError();
6299
6300 // Inspect the last argument of the nontemporal builtin. This should always
6301 // be a pointer type, from which we imply the type of the memory access.
6302 // Because it is a pointer type, we don't have to worry about any implicit
6303 // casts here.
6304 Expr *PointerArg = TheCall->getArg(numArgs - 1);
6305 ExprResult PointerArgResult =
6307
6308 if (PointerArgResult.isInvalid())
6309 return ExprError();
6310 PointerArg = PointerArgResult.get();
6311 TheCall->setArg(numArgs - 1, PointerArg);
6312
6313 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6314 if (!pointerType) {
6315 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6316 << PointerArg->getType() << PointerArg->getSourceRange();
6317 return ExprError();
6318 }
6319
6320 QualType ValType = pointerType->getPointeeType();
6321
6322 // Strip any qualifiers off ValType.
6323 ValType = ValType.getUnqualifiedType();
6324 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6325 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6326 !ValType->isVectorType()) {
6327 Diag(DRE->getBeginLoc(),
6328 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6329 << PointerArg->getType() << PointerArg->getSourceRange();
6330 return ExprError();
6331 }
6332
6333 if (!isStore) {
6334 TheCall->setType(ValType);
6335 return TheCallResult;
6336 }
6337
6338 ExprResult ValArg = TheCall->getArg(0);
6339 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6340 Context, ValType, /*consume*/ false);
6341 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6342 if (ValArg.isInvalid())
6343 return ExprError();
6344
6345 TheCall->setArg(0, ValArg.get());
6346 TheCall->setType(Context.VoidTy);
6347 return TheCallResult;
6348}
6349
6350/// CheckObjCString - Checks that the format string argument to the os_log()
6351/// and os_trace() functions is correct, and converts it to const char *.
6352ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6353 Arg = Arg->IgnoreParenCasts();
6354 auto *Literal = dyn_cast<StringLiteral>(Arg);
6355 if (!Literal) {
6356 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6357 Literal = ObjcLiteral->getString();
6358 }
6359 }
6360
6361 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
6362 return ExprError(
6363 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6364 << Arg->getSourceRange());
6365 }
6366
6367 ExprResult Result(Literal);
6368 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6369 InitializedEntity Entity =
6371 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6372 return Result;
6373}
6374
6375/// Check that the user is calling the appropriate va_start builtin for the
6376/// target and calling convention.
6377static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6378 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6379 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6380 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6381 TT.getArch() == llvm::Triple::aarch64_32);
6382 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
6383 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6384 if (IsX64 || IsAArch64) {
6385 CallingConv CC = CC_C;
6386 if (const FunctionDecl *FD = S.getCurFunctionDecl())
6387 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6388 if (IsMSVAStart) {
6389 // Don't allow this in System V ABI functions.
6390 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
6391 return S.Diag(Fn->getBeginLoc(),
6392 diag::err_ms_va_start_used_in_sysv_function);
6393 } else {
6394 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6395 // On x64 Windows, don't allow this in System V ABI functions.
6396 // (Yes, that means there's no corresponding way to support variadic
6397 // System V ABI functions on Windows.)
6398 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
6399 (!IsWindowsOrUEFI && CC == CC_Win64))
6400 return S.Diag(Fn->getBeginLoc(),
6401 diag::err_va_start_used_in_wrong_abi_function)
6402 << !IsWindowsOrUEFI;
6403 }
6404 return false;
6405 }
6406
6407 if (IsMSVAStart)
6408 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6409 return false;
6410}
6411
6413 ParmVarDecl **LastParam = nullptr) {
6414 // Determine whether the current function, block, or obj-c method is variadic
6415 // and get its parameter list.
6416 bool IsVariadic = false;
6418 DeclContext *Caller =
6420 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6421 IsVariadic = Block->isVariadic();
6422 Params = Block->parameters();
6423 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6424 IsVariadic = FD->isVariadic();
6425 Params = FD->parameters();
6426 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6427 IsVariadic = MD->isVariadic();
6428 // FIXME: This isn't correct for methods (results in bogus warning).
6429 Params = MD->parameters();
6430 } else if (isa<CapturedDecl>(Caller)) {
6431 // We don't support va_start in a CapturedDecl.
6432 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6433 return true;
6434 } else {
6435 // This must be some other declcontext that parses exprs.
6436 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6437 return true;
6438 }
6439
6440 if (!IsVariadic) {
6441 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6442 return true;
6443 }
6444
6445 if (LastParam)
6446 *LastParam = Params.empty() ? nullptr : Params.back();
6447
6448 return false;
6449}
6450
6451bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6452 Expr *Fn = TheCall->getCallee();
6453 if (checkVAStartABI(*this, BuiltinID, Fn))
6454 return true;
6455
6456 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
6457 // This builtin requires one argument (the va_list), allows two arguments,
6458 // but diagnoses more than two arguments. e.g.,
6459 // __builtin_c23_va_start(); // error
6460 // __builtin_c23_va_start(list); // ok
6461 // __builtin_c23_va_start(list, param); // ok
6462 // __builtin_c23_va_start(list, anything, anything); // error
6463 // This differs from the GCC behavior in that they accept the last case
6464 // with a warning, but it doesn't seem like a useful behavior to allow.
6465 if (checkArgCountRange(TheCall, 1, 2))
6466 return true;
6467 } else {
6468 // In C23 mode, va_start only needs one argument. However, the builtin still
6469 // requires two arguments (which matches the behavior of the GCC builtin),
6470 // <stdarg.h> passes `0` as the second argument in C23 mode.
6471 if (checkArgCount(TheCall, 2))
6472 return true;
6473 }
6474
6475 // Type-check the first argument normally.
6476 if (checkBuiltinArgument(*this, TheCall, 0))
6477 return true;
6478
6479 // Check that the current function is variadic, and get its last parameter.
6480 ParmVarDecl *LastParam;
6481 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6482 return true;
6483
6484 // Verify that the second argument to the builtin is the last non-variadic
6485 // argument of the current function or method. In C23 mode, if the call is
6486 // not to __builtin_c23_va_start, and the second argument is an integer
6487 // constant expression with value 0, then we don't bother with this check.
6488 // For __builtin_c23_va_start, we only perform the check for the second
6489 // argument being the last argument to the current function if there is a
6490 // second argument present.
6491 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
6492 TheCall->getNumArgs() < 2) {
6493 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6494 return false;
6495 }
6496
6497 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6498 if (std::optional<llvm::APSInt> Val =
6500 Val && LangOpts.C23 && *Val == 0 &&
6501 BuiltinID != Builtin::BI__builtin_c23_va_start) {
6502 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6503 return false;
6504 }
6505
6506 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
6507 // next block.
6508 QualType Type;
6509 SourceLocation ParamLoc;
6510 bool IsCRegister = false;
6511 bool SecondArgIsLastNonVariadicArgument = false;
6512 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6513 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6514 SecondArgIsLastNonVariadicArgument = PV == LastParam;
6515
6516 Type = PV->getType();
6517 ParamLoc = PV->getLocation();
6518 IsCRegister =
6519 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6520 }
6521 }
6522
6523 if (!SecondArgIsLastNonVariadicArgument)
6524 Diag(TheCall->getArg(1)->getBeginLoc(),
6525 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
6526 else if (IsCRegister || Type->isReferenceType() ||
6527 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6528 // Promotable integers are UB, but enumerations need a bit of
6529 // extra checking to see what their promotable type actually is.
6530 if (!Context.isPromotableIntegerType(Type))
6531 return false;
6532 const auto *ED = Type->getAsEnumDecl();
6533 if (!ED)
6534 return true;
6535 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
6536 }()) {
6537 unsigned Reason = 0;
6538 if (Type->isReferenceType()) Reason = 1;
6539 else if (IsCRegister) Reason = 2;
6540 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6541 Diag(ParamLoc, diag::note_parameter_type) << Type;
6542 }
6543
6544 return false;
6545}
6546
6547bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
6548 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6549 const LangOptions &LO = getLangOpts();
6550
6551 if (LO.CPlusPlus)
6552 return Arg->getType()
6554 .getTypePtr()
6555 ->getPointeeType()
6557
6558 // In C, allow aliasing through `char *`, this is required for AArch64 at
6559 // least.
6560 return true;
6561 };
6562
6563 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6564 // const char *named_addr);
6565
6566 Expr *Func = Call->getCallee();
6567
6568 if (Call->getNumArgs() < 3)
6569 return Diag(Call->getEndLoc(),
6570 diag::err_typecheck_call_too_few_args_at_least)
6571 << 0 /*function call*/ << 3 << Call->getNumArgs()
6572 << /*is non object*/ 0;
6573
6574 // Type-check the first argument normally.
6575 if (checkBuiltinArgument(*this, Call, 0))
6576 return true;
6577
6578 // Check that the current function is variadic.
6580 return true;
6581
6582 // __va_start on Windows does not validate the parameter qualifiers
6583
6584 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6585 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6586
6587 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6588 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6589
6590 const QualType &ConstCharPtrTy =
6591 Context.getPointerType(Context.CharTy.withConst());
6592 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6593 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6594 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6595 << 0 /* qualifier difference */
6596 << 3 /* parameter mismatch */
6597 << 2 << Arg1->getType() << ConstCharPtrTy;
6598
6599 const QualType SizeTy = Context.getSizeType();
6600 if (!Context.hasSameType(
6602 SizeTy))
6603 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6604 << Arg2->getType() << SizeTy << 1 /* different class */
6605 << 0 /* qualifier difference */
6606 << 3 /* parameter mismatch */
6607 << 3 << Arg2->getType() << SizeTy;
6608
6609 return false;
6610}
6611
6612bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
6613 if (checkArgCount(TheCall, 2))
6614 return true;
6615
6616 if (BuiltinID == Builtin::BI__builtin_isunordered &&
6617 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
6618 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6619 << 1 << 0 << TheCall->getSourceRange();
6620
6621 ExprResult OrigArg0 = TheCall->getArg(0);
6622 ExprResult OrigArg1 = TheCall->getArg(1);
6623
6624 // Do standard promotions between the two arguments, returning their common
6625 // type.
6626 QualType Res = UsualArithmeticConversions(
6627 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
6628 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6629 return true;
6630
6631 // Make sure any conversions are pushed back into the call; this is
6632 // type safe since unordered compare builtins are declared as "_Bool
6633 // foo(...)".
6634 TheCall->setArg(0, OrigArg0.get());
6635 TheCall->setArg(1, OrigArg1.get());
6636
6637 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6638 return false;
6639
6640 // If the common type isn't a real floating type, then the arguments were
6641 // invalid for this operation.
6642 if (Res.isNull() || !Res->isRealFloatingType())
6643 return Diag(OrigArg0.get()->getBeginLoc(),
6644 diag::err_typecheck_call_invalid_ordered_compare)
6645 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6646 << SourceRange(OrigArg0.get()->getBeginLoc(),
6647 OrigArg1.get()->getEndLoc());
6648
6649 return false;
6650}
6651
6652bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
6653 unsigned BuiltinID) {
6654 if (checkArgCount(TheCall, NumArgs))
6655 return true;
6656
6657 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
6658 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
6659 BuiltinID == Builtin::BI__builtin_isinf ||
6660 BuiltinID == Builtin::BI__builtin_isinf_sign))
6661 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6662 << 0 << 0 << TheCall->getSourceRange();
6663
6664 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
6665 BuiltinID == Builtin::BI__builtin_isunordered))
6666 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6667 << 1 << 0 << TheCall->getSourceRange();
6668
6669 bool IsFPClass = NumArgs == 2;
6670
6671 // Find out position of floating-point argument.
6672 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
6673
6674 // We can count on all parameters preceding the floating-point just being int.
6675 // Try all of those.
6676 for (unsigned i = 0; i < FPArgNo; ++i) {
6677 Expr *Arg = TheCall->getArg(i);
6678
6679 if (Arg->isTypeDependent())
6680 return false;
6681
6684
6685 if (Res.isInvalid())
6686 return true;
6687 TheCall->setArg(i, Res.get());
6688 }
6689
6690 Expr *OrigArg = TheCall->getArg(FPArgNo);
6691
6692 if (OrigArg->isTypeDependent())
6693 return false;
6694
6695 // We want to leave the type how it is, but do normal L->Rvalue conversions.
6697 if (!Res.isUsable())
6698 return true;
6699 OrigArg = Res.get();
6700
6701 TheCall->setArg(FPArgNo, OrigArg);
6702
6703 QualType VectorResultTy;
6704 QualType ElementTy = OrigArg->getType();
6705 // TODO: When all classification function are implemented with is_fpclass,
6706 // vector argument can be supported in all of them.
6707 if (ElementTy->isVectorType() && IsFPClass) {
6708 VectorResultTy = GetSignedVectorType(ElementTy);
6709 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6710 }
6711
6712 // This operation requires a non-_Complex floating-point number.
6713 if (!ElementTy->isRealFloatingType())
6714 return Diag(OrigArg->getBeginLoc(),
6715 diag::err_typecheck_call_invalid_unary_fp)
6716 << OrigArg->getType() << OrigArg->getSourceRange();
6717
6718 // __builtin_isfpclass has integer parameter that specify test mask. It is
6719 // passed in (...), so it should be analyzed completely here.
6720 if (IsFPClass) {
6721 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
6722 return true;
6723
6725 TheCall->getArg(NumArgs - 1), Context.IntTy, AssignmentAction::Passing);
6726 if (!MaskRes.isUsable())
6727 return true;
6728 TheCall->setArg(NumArgs - 1, MaskRes.get());
6729 }
6730
6731 // TODO: enable this code to all classification functions.
6732 if (IsFPClass) {
6733 QualType ResultTy;
6734 if (!VectorResultTy.isNull())
6735 ResultTy = VectorResultTy;
6736 else
6737 ResultTy = Context.IntTy;
6738 TheCall->setType(ResultTy);
6739 }
6740
6741 return false;
6742}
6743
6744bool Sema::BuiltinComplex(CallExpr *TheCall) {
6745 if (checkArgCount(TheCall, 2))
6746 return true;
6747
6748 bool Dependent = false;
6749 for (unsigned I = 0; I != 2; ++I) {
6750 Expr *Arg = TheCall->getArg(I);
6751 QualType T = Arg->getType();
6752 if (T->isDependentType()) {
6753 Dependent = true;
6754 continue;
6755 }
6756
6757 // Despite supporting _Complex int, GCC requires a real floating point type
6758 // for the operands of __builtin_complex.
6759 if (!T->isRealFloatingType()) {
6760 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6761 << Arg->getType() << Arg->getSourceRange();
6762 }
6763
6764 ExprResult Converted = DefaultLvalueConversion(Arg);
6765 if (Converted.isInvalid())
6766 return true;
6767 TheCall->setArg(I, Converted.get());
6768 }
6769
6770 if (Dependent) {
6771 TheCall->setType(Context.DependentTy);
6772 return false;
6773 }
6774
6775 Expr *Real = TheCall->getArg(0);
6776 Expr *Imag = TheCall->getArg(1);
6777 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6778 return Diag(Real->getBeginLoc(),
6779 diag::err_typecheck_call_different_arg_types)
6780 << Real->getType() << Imag->getType()
6781 << Real->getSourceRange() << Imag->getSourceRange();
6782 }
6783
6784 TheCall->setType(Context.getComplexType(Real->getType()));
6785 return false;
6786}
6787
6788/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6789// This is declared to take (...), so we have to check everything.
6791 unsigned NumArgs = TheCall->getNumArgs();
6792 if (NumArgs < 2)
6793 return ExprError(Diag(TheCall->getEndLoc(),
6794 diag::err_typecheck_call_too_few_args_at_least)
6795 << 0 /*function call*/ << 2 << NumArgs
6796 << /*is non object*/ 0 << TheCall->getSourceRange());
6797
6798 // Determine which of the following types of shufflevector we're checking:
6799 // 1) unary, vector mask: (lhs, mask)
6800 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6801 QualType ResType = TheCall->getArg(0)->getType();
6802 unsigned NumElements = 0;
6803
6804 if (!TheCall->getArg(0)->isTypeDependent() &&
6805 !TheCall->getArg(1)->isTypeDependent()) {
6806 QualType LHSType = TheCall->getArg(0)->getType();
6807 QualType RHSType = TheCall->getArg(1)->getType();
6808
6809 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6810 return ExprError(
6811 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6812 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6813 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6814 TheCall->getArg(1)->getEndLoc()));
6815
6816 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6817 unsigned NumResElements = NumArgs - 2;
6818
6819 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6820 // with mask. If so, verify that RHS is an integer vector type with the
6821 // same number of elts as lhs.
6822 if (NumArgs == 2) {
6823 auto *RHSVecType = RHSType->castAs<VectorType>();
6824 if (RHSVecType->getElementType()->isBooleanType() ||
6825 !RHSVecType->getElementType()->isIntegerType()) {
6826 return ExprError(
6827 Diag(TheCall->getBeginLoc(), diag::err_builtin_invalid_arg_type)
6828 << /* Arg ordinal */ 2 << /*vector of*/ 4 << /*integer*/ 1
6829 << /*no fp*/ 0 << RHSType
6830 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6831 TheCall->getArg(1)->getEndLoc()));
6832 }
6833
6834 if (RHSVecType->getNumElements() != NumElements)
6835 return ExprError(Diag(TheCall->getBeginLoc(),
6836 diag::err_typecheck_vector_lengths_not_equal)
6837 << LHSType << RHSType << /*isMoreThanTwoArgs*/ false
6838 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6839 TheCall->getArg(1)->getEndLoc()));
6840 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6841 return ExprError(Diag(TheCall->getBeginLoc(),
6842 diag::err_vec_builtin_incompatible_vector)
6843 << TheCall->getDirectCallee()
6844 << /*isMoreThanTwoArgs*/ false
6845 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6846 TheCall->getArg(1)->getEndLoc()));
6847 } else if (NumElements != NumResElements) {
6848 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6849 ResType = ResType->isExtVectorType()
6850 ? Context.getExtVectorType(EltType, NumResElements)
6851 : Context.getVectorType(EltType, NumResElements,
6853 }
6854 }
6855
6856 for (unsigned I = 2; I != NumArgs; ++I) {
6857 Expr *Arg = TheCall->getArg(I);
6858 if (Arg->isTypeDependent() || Arg->isValueDependent())
6859 continue;
6860
6861 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
6862 if (!Result)
6863 return ExprError(Diag(TheCall->getBeginLoc(),
6864 diag::err_shufflevector_nonconstant_argument)
6865 << Arg->getSourceRange());
6866
6867 // Allow -1 which will be translated to undef in the IR.
6868 if (Result->isSigned() && Result->isAllOnes())
6869 ;
6870 else if (Result->getActiveBits() > 64 ||
6871 Result->getZExtValue() >= NumElements * 2)
6872 return ExprError(Diag(TheCall->getBeginLoc(),
6873 diag::err_shufflevector_argument_too_large)
6874 << Arg->getSourceRange());
6875
6876 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
6877 }
6878
6879 auto *Result = new (Context) ShuffleVectorExpr(
6880 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6881 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6882
6883 // All moved to Result.
6884 TheCall->shrinkNumArgs(0);
6885 return Result;
6886}
6887
6889 SourceLocation BuiltinLoc,
6890 SourceLocation RParenLoc) {
6893 QualType DstTy = TInfo->getType();
6894 QualType SrcTy = E->getType();
6895
6896 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6897 return ExprError(Diag(BuiltinLoc,
6898 diag::err_convertvector_non_vector)
6899 << E->getSourceRange());
6900 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6901 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
6902 << "second"
6903 << "__builtin_convertvector");
6904
6905 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6906 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6907 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6908 if (SrcElts != DstElts)
6909 return ExprError(Diag(BuiltinLoc,
6910 diag::err_convertvector_incompatible_vector)
6911 << E->getSourceRange());
6912 }
6913
6914 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
6915 RParenLoc, CurFPFeatureOverrides());
6916}
6917
6918bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6919 unsigned NumArgs = TheCall->getNumArgs();
6920
6921 if (NumArgs > 3)
6922 return Diag(TheCall->getEndLoc(),
6923 diag::err_typecheck_call_too_many_args_at_most)
6924 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6925 << TheCall->getSourceRange();
6926
6927 // Argument 0 is checked for us and the remaining arguments must be
6928 // constant integers.
6929 for (unsigned i = 1; i != NumArgs; ++i) {
6930 if (convertArgumentToType(TheCall->getArgs()[i], Context.IntTy))
6931 return true;
6932 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6933 return true;
6934 }
6935
6936 return false;
6937}
6938
6939bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6940 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6941 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6942 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6943 if (checkArgCount(TheCall, 1))
6944 return true;
6945 Expr *Arg = TheCall->getArg(0);
6946 if (Arg->isInstantiationDependent())
6947 return false;
6948
6949 QualType ArgTy = Arg->getType();
6950 if (!ArgTy->hasFloatingRepresentation())
6951 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6952 << ArgTy;
6953 if (Arg->isLValue()) {
6954 ExprResult FirstArg = DefaultLvalueConversion(Arg);
6955 TheCall->setArg(0, FirstArg.get());
6956 }
6957 TheCall->setType(TheCall->getArg(0)->getType());
6958 return false;
6959}
6960
6961bool Sema::BuiltinAssume(CallExpr *TheCall) {
6962 Expr *Arg = TheCall->getArg(0);
6963 if (Arg->isInstantiationDependent()) return false;
6964
6965 if (Arg->HasSideEffects(Context))
6966 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6967 << Arg->getSourceRange()
6968 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6969
6970 return false;
6971}
6972
6973bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6974 // The alignment must be a constant integer.
6975 Expr *Arg = TheCall->getArg(1);
6976
6977 // We can't check the value of a dependent argument.
6978 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6979 if (const auto *UE =
6980 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6981 if (UE->getKind() == UETT_AlignOf ||
6982 UE->getKind() == UETT_PreferredAlignOf)
6983 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6984 << Arg->getSourceRange();
6985
6986 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6987
6988 if (!Result.isPowerOf2())
6989 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6990 << Arg->getSourceRange();
6991
6992 if (Result < Context.getCharWidth())
6993 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6994 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6995
6996 if (Result > std::numeric_limits<int32_t>::max())
6997 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6998 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6999 }
7000
7001 return false;
7002}
7003
7004bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
7005 if (checkArgCountRange(TheCall, 2, 3))
7006 return true;
7007
7008 unsigned NumArgs = TheCall->getNumArgs();
7009 Expr *FirstArg = TheCall->getArg(0);
7010
7011 {
7012 ExprResult FirstArgResult =
7014 if (FirstArgResult.isInvalid())
7015 return true;
7016 if (!FirstArgResult.get()->getType()->isPointerType()) {
7017 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
7018 << TheCall->getSourceRange();
7019 return true;
7020 }
7021 TheCall->setArg(0, FirstArgResult.get());
7022 }
7023
7024 // The alignment must be a constant integer.
7025 Expr *SecondArg = TheCall->getArg(1);
7026
7027 // We can't check the value of a dependent argument.
7028 if (!SecondArg->isValueDependent()) {
7029 llvm::APSInt Result;
7030 if (BuiltinConstantArg(TheCall, 1, Result))
7031 return true;
7032
7033 if (!Result.isPowerOf2())
7034 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
7035 << SecondArg->getSourceRange();
7036
7038 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
7039 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
7040
7041 TheCall->setArg(1,
7043 }
7044
7045 if (NumArgs > 2) {
7046 Expr *ThirdArg = TheCall->getArg(2);
7047 if (convertArgumentToType(ThirdArg, Context.getSizeType()))
7048 return true;
7049 TheCall->setArg(2, ThirdArg);
7050 }
7051
7052 return false;
7053}
7054
7055bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
7056 unsigned BuiltinID =
7057 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
7058 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
7059
7060 unsigned NumArgs = TheCall->getNumArgs();
7061 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7062 if (NumArgs < NumRequiredArgs) {
7063 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
7064 << 0 /* function call */ << NumRequiredArgs << NumArgs
7065 << /*is non object*/ 0 << TheCall->getSourceRange();
7066 }
7067 if (NumArgs >= NumRequiredArgs + 0x100) {
7068 return Diag(TheCall->getEndLoc(),
7069 diag::err_typecheck_call_too_many_args_at_most)
7070 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7071 << /*is non object*/ 0 << TheCall->getSourceRange();
7072 }
7073 unsigned i = 0;
7074
7075 // For formatting call, check buffer arg.
7076 if (!IsSizeCall) {
7077 ExprResult Arg(TheCall->getArg(i));
7078 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7079 Context, Context.VoidPtrTy, false);
7080 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7081 if (Arg.isInvalid())
7082 return true;
7083 TheCall->setArg(i, Arg.get());
7084 i++;
7085 }
7086
7087 // Check string literal arg.
7088 unsigned FormatIdx = i;
7089 {
7090 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7091 if (Arg.isInvalid())
7092 return true;
7093 TheCall->setArg(i, Arg.get());
7094 i++;
7095 }
7096
7097 // Make sure variadic args are scalar.
7098 unsigned FirstDataArg = i;
7099 while (i < NumArgs) {
7101 TheCall->getArg(i), VariadicCallType::Function, nullptr);
7102 if (Arg.isInvalid())
7103 return true;
7104 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7105 if (ArgSize.getQuantity() >= 0x100) {
7106 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7107 << i << (int)ArgSize.getQuantity() << 0xff
7108 << TheCall->getSourceRange();
7109 }
7110 TheCall->setArg(i, Arg.get());
7111 i++;
7112 }
7113
7114 // Check formatting specifiers. NOTE: We're only doing this for the non-size
7115 // call to avoid duplicate diagnostics.
7116 if (!IsSizeCall) {
7117 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7118 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7119 bool Success = CheckFormatArguments(
7120 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
7122 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
7123 if (!Success)
7124 return true;
7125 }
7126
7127 if (IsSizeCall) {
7128 TheCall->setType(Context.getSizeType());
7129 } else {
7130 TheCall->setType(Context.VoidPtrTy);
7131 }
7132 return false;
7133}
7134
7135bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
7136 llvm::APSInt &Result) {
7137 Expr *Arg = TheCall->getArg(ArgNum);
7138
7139 if (Arg->isTypeDependent() || Arg->isValueDependent())
7140 return false;
7141
7142 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
7143 if (!R) {
7144 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7145 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
7146 Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7147 << FDecl->getDeclName() << Arg->getSourceRange();
7149 return true;
7150 }
7151 Result = *R;
7152
7153 return false;
7154}
7155
7156bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
7157 int High, bool RangeIsError) {
7159 return false;
7160
7161 // Check constant-ness first.
7162 llvm::APSInt Result;
7163 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7164 return true;
7165
7166 return checkConstantArgValueRange(*this, TheCall, ArgNum, Result, Low, High,
7167 RangeIsError);
7168}
7169
7170bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
7171 unsigned Num) {
7172 llvm::APSInt Result;
7173
7174 // We can't check the value of a dependent argument.
7175 Expr *Arg = TheCall->getArg(ArgNum);
7176 if (Arg->isTypeDependent() || Arg->isValueDependent())
7177 return false;
7178
7179 // Check constant-ness first.
7180 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7181 return true;
7182
7183 if (Result.getSExtValue() % Num != 0)
7184 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7185 << Num << Arg->getSourceRange();
7186
7187 return false;
7188}
7189
7190bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
7191 llvm::APSInt Result;
7192
7193 // We can't check the value of a dependent argument.
7194 Expr *Arg = TheCall->getArg(ArgNum);
7195 if (Arg->isTypeDependent() || Arg->isValueDependent())
7196 return false;
7197
7198 // Check constant-ness first.
7199 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7200 return true;
7201
7202 if (Result.isPowerOf2())
7203 return false;
7204
7205 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7206 << Arg->getSourceRange();
7207}
7208
7209static bool IsShiftedByte(llvm::APSInt Value) {
7210 if (Value.isNegative())
7211 return false;
7212
7213 // Check if it's a shifted byte, by shifting it down
7214 while (true) {
7215 // If the value fits in the bottom byte, the check passes.
7216 if (Value < 0x100)
7217 return true;
7218
7219 // Otherwise, if the value has _any_ bits in the bottom byte, the check
7220 // fails.
7221 if ((Value & 0xFF) != 0)
7222 return false;
7223
7224 // If the bottom 8 bits are all 0, but something above that is nonzero,
7225 // then shifting the value right by 8 bits won't affect whether it's a
7226 // shifted byte or not. So do that, and go round again.
7227 Value >>= 8;
7228 }
7229}
7230
7231bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
7232 unsigned ArgBits) {
7233 llvm::APSInt Result;
7234
7235 // We can't check the value of a dependent argument.
7236 Expr *Arg = TheCall->getArg(ArgNum);
7237 if (Arg->isTypeDependent() || Arg->isValueDependent())
7238 return false;
7239
7240 // Check constant-ness first.
7241 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7242 return true;
7243
7244 // Truncate to the given size.
7245 Result = Result.getLoBits(ArgBits);
7246 Result.setIsUnsigned(true);
7247
7248 if (IsShiftedByte(Result))
7249 return false;
7250
7251 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7252 << Arg->getSourceRange();
7253}
7254
7256 unsigned ArgNum,
7257 unsigned ArgBits) {
7258 llvm::APSInt Result;
7259
7260 // We can't check the value of a dependent argument.
7261 Expr *Arg = TheCall->getArg(ArgNum);
7262 if (Arg->isTypeDependent() || Arg->isValueDependent())
7263 return false;
7264
7265 // Check constant-ness first.
7266 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7267 return true;
7268
7269 // Truncate to the given size.
7270 Result = Result.getLoBits(ArgBits);
7271 Result.setIsUnsigned(true);
7272
7273 // Check to see if it's in either of the required forms.
7274 if (IsShiftedByte(Result) ||
7275 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7276 return false;
7277
7278 return Diag(TheCall->getBeginLoc(),
7279 diag::err_argument_not_shifted_byte_or_xxff)
7280 << Arg->getSourceRange();
7281}
7282
7283bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
7284 if (!Context.getTargetInfo().hasSjLjLowering())
7285 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7286 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7287
7288 Expr *Arg = TheCall->getArg(1);
7289 llvm::APSInt Result;
7290
7291 // TODO: This is less than ideal. Overload this to take a value.
7292 if (BuiltinConstantArg(TheCall, 1, Result))
7293 return true;
7294
7295 if (Result != 1)
7296 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7297 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7298
7299 return false;
7300}
7301
7302bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
7303 if (!Context.getTargetInfo().hasSjLjLowering())
7304 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7305 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7306 return false;
7307}
7308
7309bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
7310 if (checkArgCount(TheCall, 1))
7311 return true;
7312
7313 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
7314 if (ArgRes.isInvalid())
7315 return true;
7316
7317 // For simplicity, we support only limited expressions for the argument.
7318 // Specifically a flexible array member or a pointer with counted_by:
7319 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
7320 // complex casting, which really shouldn't be a huge problem.
7321 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
7322 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
7323 return Diag(Arg->getBeginLoc(),
7324 diag::err_builtin_counted_by_ref_invalid_arg)
7325 << Arg->getSourceRange();
7326
7327 if (Arg->HasSideEffects(Context))
7328 return Diag(Arg->getBeginLoc(),
7329 diag::err_builtin_counted_by_ref_has_side_effects)
7330 << Arg->getSourceRange();
7331
7332 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
7333 const auto *CATy =
7334 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
7335
7336 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
7337 // Member has counted_by attribute - return pointer to count field
7338 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
7339 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
7340 if (CountFD->isBitField()) {
7341 Diag(ME->getBeginLoc(),
7342 diag::err_builtin_counted_by_ref_counter_field_is_bitfield)
7343 << Arg << CountFD << ME->getSourceRange();
7344 return Diag(CountFD->getBeginLoc(),
7345 diag::note_counted_by_counter_field)
7346 << CountFD << CountFD->getSourceRange();
7347 }
7348
7349 TheCall->setType(Context.getPointerType(CountFD->getType()));
7350 return false;
7351 }
7352 }
7353
7354 // FAMs and pointers without counted_by return void*
7355 QualType MemberTy = ME->getMemberDecl()->getType();
7356 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
7357 return Diag(Arg->getBeginLoc(),
7358 diag::err_builtin_counted_by_ref_invalid_arg)
7359 << Arg->getSourceRange();
7360 } else {
7361 return Diag(Arg->getBeginLoc(),
7362 diag::err_builtin_counted_by_ref_invalid_arg)
7363 << Arg->getSourceRange();
7364 }
7365
7366 TheCall->setType(Context.getPointerType(Context.VoidTy));
7367 return false;
7368}
7369
7370/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
7371/// It allows leaking and modification of bounds safety information.
7372bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
7374 const CallExpr *CE =
7375 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
7376 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
7377 return false;
7378
7379 switch (K) {
7382 Diag(E->getExprLoc(),
7383 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7384 << 0 << E->getSourceRange();
7385 break;
7387 Diag(E->getExprLoc(),
7388 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7389 << 1 << E->getSourceRange();
7390 break;
7392 Diag(E->getExprLoc(),
7393 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7394 << 2 << E->getSourceRange();
7395 break;
7397 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
7398 << 0 << E->getSourceRange();
7399 break;
7401 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
7402 << 1 << E->getSourceRange();
7403 break;
7404 }
7405
7406 return true;
7407}
7408
7409namespace {
7410
7411class UncoveredArgHandler {
7412 enum { Unknown = -1, AllCovered = -2 };
7413
7414 signed FirstUncoveredArg = Unknown;
7415 SmallVector<const Expr *, 4> DiagnosticExprs;
7416
7417public:
7418 UncoveredArgHandler() = default;
7419
7420 bool hasUncoveredArg() const {
7421 return (FirstUncoveredArg >= 0);
7422 }
7423
7424 unsigned getUncoveredArg() const {
7425 assert(hasUncoveredArg() && "no uncovered argument");
7426 return FirstUncoveredArg;
7427 }
7428
7429 void setAllCovered() {
7430 // A string has been found with all arguments covered, so clear out
7431 // the diagnostics.
7432 DiagnosticExprs.clear();
7433 FirstUncoveredArg = AllCovered;
7434 }
7435
7436 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7437 assert(NewFirstUncoveredArg >= 0 && "Outside range");
7438
7439 // Don't update if a previous string covers all arguments.
7440 if (FirstUncoveredArg == AllCovered)
7441 return;
7442
7443 // UncoveredArgHandler tracks the highest uncovered argument index
7444 // and with it all the strings that match this index.
7445 if (NewFirstUncoveredArg == FirstUncoveredArg)
7446 DiagnosticExprs.push_back(StrExpr);
7447 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7448 DiagnosticExprs.clear();
7449 DiagnosticExprs.push_back(StrExpr);
7450 FirstUncoveredArg = NewFirstUncoveredArg;
7451 }
7452 }
7453
7454 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7455};
7456
7457enum StringLiteralCheckType {
7458 SLCT_NotALiteral,
7459 SLCT_UncheckedLiteral,
7460 SLCT_CheckedLiteral
7461};
7462
7463} // namespace
7464
7465static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7466 BinaryOperatorKind BinOpKind,
7467 bool AddendIsRight) {
7468 unsigned BitWidth = Offset.getBitWidth();
7469 unsigned AddendBitWidth = Addend.getBitWidth();
7470 // There might be negative interim results.
7471 if (Addend.isUnsigned()) {
7472 Addend = Addend.zext(++AddendBitWidth);
7473 Addend.setIsSigned(true);
7474 }
7475 // Adjust the bit width of the APSInts.
7476 if (AddendBitWidth > BitWidth) {
7477 Offset = Offset.sext(AddendBitWidth);
7478 BitWidth = AddendBitWidth;
7479 } else if (BitWidth > AddendBitWidth) {
7480 Addend = Addend.sext(BitWidth);
7481 }
7482
7483 bool Ov = false;
7484 llvm::APSInt ResOffset = Offset;
7485 if (BinOpKind == BO_Add)
7486 ResOffset = Offset.sadd_ov(Addend, Ov);
7487 else {
7488 assert(AddendIsRight && BinOpKind == BO_Sub &&
7489 "operator must be add or sub with addend on the right");
7490 ResOffset = Offset.ssub_ov(Addend, Ov);
7491 }
7492
7493 // We add an offset to a pointer here so we should support an offset as big as
7494 // possible.
7495 if (Ov) {
7496 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7497 "index (intermediate) result too big");
7498 Offset = Offset.sext(2 * BitWidth);
7499 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7500 return;
7501 }
7502
7503 Offset = std::move(ResOffset);
7504}
7505
7506namespace {
7507
7508// This is a wrapper class around StringLiteral to support offsetted string
7509// literals as format strings. It takes the offset into account when returning
7510// the string and its length or the source locations to display notes correctly.
7511class FormatStringLiteral {
7512 const StringLiteral *FExpr;
7513 int64_t Offset;
7514
7515public:
7516 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7517 : FExpr(fexpr), Offset(Offset) {}
7518
7519 const StringLiteral *getFormatString() const { return FExpr; }
7520
7521 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
7522
7523 unsigned getByteLength() const {
7524 return FExpr->getByteLength() - getCharByteWidth() * Offset;
7525 }
7526
7527 unsigned getLength() const { return FExpr->getLength() - Offset; }
7528 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7529
7530 StringLiteralKind getKind() const { return FExpr->getKind(); }
7531
7532 QualType getType() const { return FExpr->getType(); }
7533
7534 bool isAscii() const { return FExpr->isOrdinary(); }
7535 bool isWide() const { return FExpr->isWide(); }
7536 bool isUTF8() const { return FExpr->isUTF8(); }
7537 bool isUTF16() const { return FExpr->isUTF16(); }
7538 bool isUTF32() const { return FExpr->isUTF32(); }
7539 bool isPascal() const { return FExpr->isPascal(); }
7540
7541 SourceLocation getLocationOfByte(
7542 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7543 const TargetInfo &Target, unsigned *StartToken = nullptr,
7544 unsigned *StartTokenByteOffset = nullptr) const {
7545 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7546 StartToken, StartTokenByteOffset);
7547 }
7548
7549 SourceLocation getBeginLoc() const LLVM_READONLY {
7550 return FExpr->getBeginLoc().getLocWithOffset(Offset);
7551 }
7552
7553 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7554};
7555
7556} // namespace
7557
7558static void CheckFormatString(
7559 Sema &S, const FormatStringLiteral *FExpr,
7560 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
7562 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
7563 bool inFunctionCall, VariadicCallType CallType,
7564 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7565 bool IgnoreStringsWithoutSpecifiers);
7566
7567static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7568 const Expr *E);
7569
7570// Determine if an expression is a string literal or constant string.
7571// If this function returns false on the arguments to a function expecting a
7572// format string, we will usually need to emit a warning.
7573// True string literals are then checked by CheckFormatString.
7574static StringLiteralCheckType
7575checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
7576 const Expr *E, ArrayRef<const Expr *> Args,
7577 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
7578 unsigned firstDataArg, FormatStringType Type,
7579 VariadicCallType CallType, bool InFunctionCall,
7580 llvm::SmallBitVector &CheckedVarArgs,
7581 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
7582 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
7583 bool IgnoreStringsWithoutSpecifiers = false) {
7585 return SLCT_NotALiteral;
7586tryAgain:
7587 assert(Offset.isSigned() && "invalid offset");
7588
7589 if (E->isTypeDependent() || E->isValueDependent())
7590 return SLCT_NotALiteral;
7591
7592 E = E->IgnoreParenCasts();
7593
7595 // Technically -Wformat-nonliteral does not warn about this case.
7596 // The behavior of printf and friends in this case is implementation
7597 // dependent. Ideally if the format string cannot be null then
7598 // it should have a 'nonnull' attribute in the function prototype.
7599 return SLCT_UncheckedLiteral;
7600
7601 switch (E->getStmtClass()) {
7602 case Stmt::InitListExprClass:
7603 // Handle expressions like {"foobar"}.
7604 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
7605 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7606 format_idx, firstDataArg, Type, CallType,
7607 /*InFunctionCall*/ false, CheckedVarArgs,
7608 UncoveredArg, Offset, CallerFormatParamIdx,
7609 IgnoreStringsWithoutSpecifiers);
7610 }
7611 return SLCT_NotALiteral;
7612 case Stmt::BinaryConditionalOperatorClass:
7613 case Stmt::ConditionalOperatorClass: {
7614 // The expression is a literal if both sub-expressions were, and it was
7615 // completely checked only if both sub-expressions were checked.
7618
7619 // Determine whether it is necessary to check both sub-expressions, for
7620 // example, because the condition expression is a constant that can be
7621 // evaluated at compile time.
7622 bool CheckLeft = true, CheckRight = true;
7623
7624 bool Cond;
7625 if (C->getCond()->EvaluateAsBooleanCondition(
7626 Cond, S.getASTContext(), S.isConstantEvaluatedContext())) {
7627 if (Cond)
7628 CheckRight = false;
7629 else
7630 CheckLeft = false;
7631 }
7632
7633 // We need to maintain the offsets for the right and the left hand side
7634 // separately to check if every possible indexed expression is a valid
7635 // string literal. They might have different offsets for different string
7636 // literals in the end.
7637 StringLiteralCheckType Left;
7638 if (!CheckLeft)
7639 Left = SLCT_UncheckedLiteral;
7640 else {
7641 Left = checkFormatStringExpr(S, ReferenceFormatString, C->getTrueExpr(),
7642 Args, APK, format_idx, firstDataArg, Type,
7643 CallType, InFunctionCall, CheckedVarArgs,
7644 UncoveredArg, Offset, CallerFormatParamIdx,
7645 IgnoreStringsWithoutSpecifiers);
7646 if (Left == SLCT_NotALiteral || !CheckRight) {
7647 return Left;
7648 }
7649 }
7650
7651 StringLiteralCheckType Right = checkFormatStringExpr(
7652 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
7653 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7654 UncoveredArg, Offset, CallerFormatParamIdx,
7655 IgnoreStringsWithoutSpecifiers);
7656
7657 return (CheckLeft && Left < Right) ? Left : Right;
7658 }
7659
7660 case Stmt::ImplicitCastExprClass:
7661 E = cast<ImplicitCastExpr>(E)->getSubExpr();
7662 goto tryAgain;
7663
7664 case Stmt::OpaqueValueExprClass:
7665 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7666 E = src;
7667 goto tryAgain;
7668 }
7669 return SLCT_NotALiteral;
7670
7671 case Stmt::PredefinedExprClass:
7672 // While __func__, etc., are technically not string literals, they
7673 // cannot contain format specifiers and thus are not a security
7674 // liability.
7675 return SLCT_UncheckedLiteral;
7676
7677 case Stmt::DeclRefExprClass: {
7678 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7679
7680 // As an exception, do not flag errors for variables binding to
7681 // const string literals.
7682 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7683 bool isConstant = false;
7684 QualType T = DR->getType();
7685
7686 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7687 isConstant = AT->getElementType().isConstant(S.Context);
7688 } else if (const PointerType *PT = T->getAs<PointerType>()) {
7689 isConstant = T.isConstant(S.Context) &&
7690 PT->getPointeeType().isConstant(S.Context);
7691 } else if (T->isObjCObjectPointerType()) {
7692 // In ObjC, there is usually no "const ObjectPointer" type,
7693 // so don't check if the pointee type is constant.
7694 isConstant = T.isConstant(S.Context);
7695 }
7696
7697 if (isConstant) {
7698 if (const Expr *Init = VD->getAnyInitializer()) {
7699 // Look through initializers like const char c[] = { "foo" }
7700 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7701 if (InitList->isStringLiteralInit())
7702 Init = InitList->getInit(0)->IgnoreParenImpCasts();
7703 }
7704 return checkFormatStringExpr(
7705 S, ReferenceFormatString, Init, Args, APK, format_idx,
7706 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7707 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7708 }
7709 }
7710
7711 // When the format argument is an argument of this function, and this
7712 // function also has the format attribute, there are several interactions
7713 // for which there shouldn't be a warning. For instance, when calling
7714 // v*printf from a function that has the printf format attribute, we
7715 // should not emit a warning about using `fmt`, even though it's not
7716 // constant, because the arguments have already been checked for the
7717 // caller of `logmessage`:
7718 //
7719 // __attribute__((format(printf, 1, 2)))
7720 // void logmessage(char const *fmt, ...) {
7721 // va_list ap;
7722 // va_start(ap, fmt);
7723 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7724 // ...
7725 // }
7726 //
7727 // Another interaction that we need to support is using a format string
7728 // specified by the format_matches attribute:
7729 //
7730 // __attribute__((format_matches(printf, 1, "%s %d")))
7731 // void logmessage(char const *fmt, const char *a, int b) {
7732 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7733 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7734 // ...
7735 // }
7736 //
7737 // Yet another interaction that we need to support is calling a variadic
7738 // format function from a format function that has fixed arguments. For
7739 // instance:
7740 //
7741 // __attribute__((format(printf, 1, 2)))
7742 // void logstring(char const *fmt, char const *str) {
7743 // printf(fmt, str); /* do not emit a warning about "fmt" */
7744 // }
7745 //
7746 // Same (and perhaps more relatably) for the variadic template case:
7747 //
7748 // template<typename... Args>
7749 // __attribute__((format(printf, 1, 2)))
7750 // void log(const char *fmt, Args&&... args) {
7751 // printf(fmt, forward<Args>(args)...);
7752 // /* do not emit a warning about "fmt" */
7753 // }
7754 //
7755 // Due to implementation difficulty, we only check the format, not the
7756 // format arguments, in all cases.
7757 //
7758 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
7759 if (CallerFormatParamIdx)
7760 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7761 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
7762 for (const auto *PVFormatMatches :
7763 D->specific_attrs<FormatMatchesAttr>()) {
7764 Sema::FormatStringInfo CalleeFSI;
7765 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
7766 0, &CalleeFSI))
7767 continue;
7768 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7769 // If using the wrong type of format string, emit a diagnostic
7770 // here and stop checking to avoid irrelevant diagnostics.
7771 if (Type != S.GetFormatStringType(PVFormatMatches)) {
7772 S.Diag(Args[format_idx]->getBeginLoc(),
7773 diag::warn_format_string_type_incompatible)
7774 << PVFormatMatches->getType()->getName()
7776 if (!InFunctionCall) {
7777 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
7778 diag::note_format_string_defined);
7779 }
7780 return SLCT_UncheckedLiteral;
7781 }
7782 return checkFormatStringExpr(
7783 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
7784 Args, APK, format_idx, firstDataArg, Type, CallType,
7785 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7786 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7787 }
7788 }
7789
7790 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7791 Sema::FormatStringInfo CallerFSI;
7792 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
7793 PVFormat->getFirstArg(), &CallerFSI))
7794 continue;
7795 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7796 // We also check if the formats are compatible.
7797 // We can't pass a 'scanf' string to a 'printf' function.
7798 if (Type != S.GetFormatStringType(PVFormat)) {
7799 S.Diag(Args[format_idx]->getBeginLoc(),
7800 diag::warn_format_string_type_incompatible)
7801 << PVFormat->getType()->getName()
7803 if (!InFunctionCall) {
7804 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
7805 }
7806 return SLCT_UncheckedLiteral;
7807 }
7808 // Lastly, check that argument passing kinds transition in a
7809 // way that makes sense:
7810 // from a caller with FAPK_VAList, allow FAPK_VAList
7811 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7812 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7813 // from a caller with FAPK_Variadic, allow FAPK_VAList
7814 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
7819 return SLCT_UncheckedLiteral;
7820 }
7821 }
7822 }
7823 }
7824 }
7825 }
7826
7827 return SLCT_NotALiteral;
7828 }
7829
7830 case Stmt::CallExprClass:
7831 case Stmt::CXXMemberCallExprClass: {
7832 const CallExpr *CE = cast<CallExpr>(E);
7833 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7834 bool IsFirst = true;
7835 StringLiteralCheckType CommonResult;
7836 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7837 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7838 StringLiteralCheckType Result = checkFormatStringExpr(
7839 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7840 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7841 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7842 if (IsFirst) {
7843 CommonResult = Result;
7844 IsFirst = false;
7845 }
7846 }
7847 if (!IsFirst)
7848 return CommonResult;
7849
7850 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7851 unsigned BuiltinID = FD->getBuiltinID();
7852 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7853 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7854 const Expr *Arg = CE->getArg(0);
7855 return checkFormatStringExpr(
7856 S, ReferenceFormatString, Arg, Args, APK, format_idx,
7857 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7858 UncoveredArg, Offset, CallerFormatParamIdx,
7859 IgnoreStringsWithoutSpecifiers);
7860 }
7861 }
7862 }
7863 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
7864 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7865 format_idx, firstDataArg, Type, CallType,
7866 /*InFunctionCall*/ false, CheckedVarArgs,
7867 UncoveredArg, Offset, CallerFormatParamIdx,
7868 IgnoreStringsWithoutSpecifiers);
7869 return SLCT_NotALiteral;
7870 }
7871 case Stmt::ObjCMessageExprClass: {
7872 const auto *ME = cast<ObjCMessageExpr>(E);
7873 if (const auto *MD = ME->getMethodDecl()) {
7874 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7875 // As a special case heuristic, if we're using the method -[NSBundle
7876 // localizedStringForKey:value:table:], ignore any key strings that lack
7877 // format specifiers. The idea is that if the key doesn't have any
7878 // format specifiers then its probably just a key to map to the
7879 // localized strings. If it does have format specifiers though, then its
7880 // likely that the text of the key is the format string in the
7881 // programmer's language, and should be checked.
7882 const ObjCInterfaceDecl *IFace;
7883 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7884 IFace->getIdentifier()->isStr("NSBundle") &&
7885 MD->getSelector().isKeywordSelector(
7886 {"localizedStringForKey", "value", "table"})) {
7887 IgnoreStringsWithoutSpecifiers = true;
7888 }
7889
7890 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7891 return checkFormatStringExpr(
7892 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7893 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7894 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7895 }
7896 }
7897
7898 return SLCT_NotALiteral;
7899 }
7900 case Stmt::ObjCStringLiteralClass:
7901 case Stmt::StringLiteralClass: {
7902 const StringLiteral *StrE = nullptr;
7903
7904 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7905 StrE = ObjCFExpr->getString();
7906 else
7907 StrE = cast<StringLiteral>(E);
7908
7909 if (StrE) {
7910 if (Offset.isNegative() || Offset > StrE->getLength()) {
7911 // TODO: It would be better to have an explicit warning for out of
7912 // bounds literals.
7913 return SLCT_NotALiteral;
7914 }
7915 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7916 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
7917 format_idx, firstDataArg, Type, InFunctionCall,
7918 CallType, CheckedVarArgs, UncoveredArg,
7919 IgnoreStringsWithoutSpecifiers);
7920 return SLCT_CheckedLiteral;
7921 }
7922
7923 return SLCT_NotALiteral;
7924 }
7925 case Stmt::BinaryOperatorClass: {
7926 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7927
7928 // A string literal + an int offset is still a string literal.
7929 if (BinOp->isAdditiveOp()) {
7930 Expr::EvalResult LResult, RResult;
7931
7932 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7933 LResult, S.Context, Expr::SE_NoSideEffects,
7935 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7936 RResult, S.Context, Expr::SE_NoSideEffects,
7938
7939 if (LIsInt != RIsInt) {
7940 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7941
7942 if (LIsInt) {
7943 if (BinOpKind == BO_Add) {
7944 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7945 E = BinOp->getRHS();
7946 goto tryAgain;
7947 }
7948 } else {
7949 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7950 E = BinOp->getLHS();
7951 goto tryAgain;
7952 }
7953 }
7954 }
7955
7956 return SLCT_NotALiteral;
7957 }
7958 case Stmt::UnaryOperatorClass: {
7959 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7960 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7961 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7962 Expr::EvalResult IndexResult;
7963 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7966 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7967 /*RHS is int*/ true);
7968 E = ASE->getBase();
7969 goto tryAgain;
7970 }
7971 }
7972
7973 return SLCT_NotALiteral;
7974 }
7975
7976 default:
7977 return SLCT_NotALiteral;
7978 }
7979}
7980
7981// If this expression can be evaluated at compile-time,
7982// check if the result is a StringLiteral and return it
7983// otherwise return nullptr
7985 const Expr *E) {
7987 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
7988 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7989 if (isa_and_nonnull<StringLiteral>(LVE))
7990 return LVE;
7991 }
7992 return nullptr;
7993}
7994
7996 switch (FST) {
7998 return "scanf";
8000 return "printf";
8002 return "NSString";
8004 return "strftime";
8006 return "strfmon";
8008 return "kprintf";
8010 return "freebsd_kprintf";
8012 return "os_log";
8013 default:
8014 return "<unknown>";
8015 }
8016}
8017
8019 return llvm::StringSwitch<FormatStringType>(Flavor)
8020 .Cases({"gnu_scanf", "scanf"}, FormatStringType::Scanf)
8021 .Cases({"gnu_printf", "printf", "printf0", "syslog"},
8023 .Cases({"NSString", "CFString"}, FormatStringType::NSString)
8024 .Cases({"gnu_strftime", "strftime"}, FormatStringType::Strftime)
8025 .Cases({"gnu_strfmon", "strfmon"}, FormatStringType::Strfmon)
8026 .Cases({"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
8028 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
8029 .Case("os_trace", FormatStringType::OSLog)
8030 .Case("os_log", FormatStringType::OSLog)
8031 .Default(FormatStringType::Unknown);
8032}
8033
8035 return GetFormatStringType(Format->getType()->getName());
8036}
8037
8038FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
8039 return GetFormatStringType(Format->getType()->getName());
8040}
8041
8042bool Sema::CheckFormatArguments(const FormatAttr *Format,
8043 ArrayRef<const Expr *> Args, bool IsCXXMember,
8044 VariadicCallType CallType, SourceLocation Loc,
8045 SourceRange Range,
8046 llvm::SmallBitVector &CheckedVarArgs) {
8047 FormatStringInfo FSI;
8048 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
8049 IsCXXMember,
8050 CallType != VariadicCallType::DoesNotApply, &FSI))
8051 return CheckFormatArguments(
8052 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
8053 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
8054 return false;
8055}
8056
8057bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
8058 ArrayRef<const Expr *> Args, bool IsCXXMember,
8059 VariadicCallType CallType, SourceLocation Loc,
8060 SourceRange Range,
8061 llvm::SmallBitVector &CheckedVarArgs) {
8062 FormatStringInfo FSI;
8063 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
8064 &FSI)) {
8065 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
8066 return CheckFormatArguments(Args, FSI.ArgPassingKind,
8067 Format->getFormatString(), FSI.FormatIdx,
8068 FSI.FirstDataArg, GetFormatStringType(Format),
8069 CallType, Loc, Range, CheckedVarArgs);
8070 }
8071 return false;
8072}
8073
8076 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
8077 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
8078 SourceLocation Loc) {
8079 if (S->getDiagnostics().isIgnored(diag::warn_missing_format_attribute, Loc))
8080 return false;
8081
8083 if (!isa<ObjCMethodDecl>(DC) && !isa<FunctionDecl>(DC) && !isa<BlockDecl>(DC))
8084 return false;
8085 Decl *Caller = cast<Decl>(DC)->getCanonicalDecl();
8086
8087 unsigned NumCallerParams = getFunctionOrMethodNumParams(Caller);
8088
8089 // Find the offset to convert between attribute and parameter indexes.
8090 unsigned CallerArgumentIndexOffset =
8091 hasImplicitObjectParameter(Caller) ? 2 : 1;
8092
8093 unsigned FirstArgumentIndex = -1;
8094 switch (APK) {
8097 // As an extension, clang allows the format attribute on non-variadic
8098 // functions.
8099 // Caller must have fixed arguments to pass them to a fixed or variadic
8100 // function. Try to match caller and callee arguments. If successful, then
8101 // emit a diag with the caller idx, otherwise we can't determine the callee
8102 // arguments.
8103 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
8104 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
8105 // There aren't enough arguments in the caller to pass to callee.
8106 return false;
8107 }
8108 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
8109 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
8110 const auto *Arg =
8111 dyn_cast<DeclRefExpr>(Args[CalleeIdx]->IgnoreParenCasts());
8112 if (!Arg)
8113 return false;
8114 const auto *Param = dyn_cast<ParmVarDecl>(Arg->getDecl());
8115 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
8116 return false;
8117 }
8118 FirstArgumentIndex =
8119 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
8120 break;
8121 }
8123 // Caller arguments are either variadic or a va_list.
8124 FirstArgumentIndex = isFunctionOrMethodVariadic(Caller)
8125 ? (NumCallerParams + CallerArgumentIndexOffset)
8126 : 0;
8127 break;
8129 // The callee has a format_matches attribute. We will emit that instead.
8130 if (!ReferenceFormatString)
8131 return false;
8132 break;
8133 }
8134
8135 // Emit the diagnostic and fixit.
8136 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
8137 StringRef FormatTypeName = S->GetFormatStringTypeName(FormatType);
8138 NamedDecl *ND = dyn_cast<NamedDecl>(Caller);
8139 do {
8140 std::string Attr, Fixit;
8141 llvm::raw_string_ostream AttrOS(Attr);
8143 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
8144 << FirstArgumentIndex << ")";
8145 } else {
8146 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
8147 << ", \"";
8148 AttrOS.write_escaped(ReferenceFormatString->getString());
8149 AttrOS << "\")";
8150 }
8151 AttrOS.flush();
8152 auto DB = S->Diag(Loc, diag::warn_missing_format_attribute) << Attr;
8153 if (ND)
8154 DB << ND;
8155 else
8156 DB << "block";
8157
8158 // Blocks don't provide a correct end loc, so skip emitting a fixit.
8159 if (isa<BlockDecl>(Caller))
8160 break;
8161
8162 SourceLocation SL;
8163 llvm::raw_string_ostream IS(Fixit);
8164 // The attribute goes at the start of the declaration in C/C++ functions
8165 // and methods, but after the declaration for Objective-C methods.
8166 if (isa<ObjCMethodDecl>(Caller)) {
8167 IS << ' ';
8168 SL = Caller->getEndLoc();
8169 }
8170 const LangOptions &LO = S->getLangOpts();
8171 if (LO.C23 || LO.CPlusPlus11)
8172 IS << "[[gnu::" << Attr << "]]";
8173 else if (LO.ObjC || LO.GNUMode)
8174 IS << "__attribute__((" << Attr << "))";
8175 else
8176 break;
8177 if (!isa<ObjCMethodDecl>(Caller)) {
8178 IS << ' ';
8179 SL = Caller->getBeginLoc();
8180 }
8181 IS.flush();
8182
8183 DB << FixItHint::CreateInsertion(SL, Fixit);
8184 } while (false);
8185
8186 // Add implicit format or format_matches attribute.
8188 Caller->addAttr(FormatAttr::CreateImplicit(
8189 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
8190 FormatStringIndex, FirstArgumentIndex));
8191 } else {
8192 Caller->addAttr(FormatMatchesAttr::CreateImplicit(
8193 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
8194 FormatStringIndex, ReferenceFormatString));
8195 }
8196
8197 {
8198 auto DB = S->Diag(Caller->getLocation(), diag::note_entity_declared_at);
8199 if (ND)
8200 DB << ND;
8201 else
8202 DB << "block";
8203 }
8204 return true;
8205}
8206
8207bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8209 StringLiteral *ReferenceFormatString,
8210 unsigned format_idx, unsigned firstDataArg,
8212 VariadicCallType CallType, SourceLocation Loc,
8213 SourceRange Range,
8214 llvm::SmallBitVector &CheckedVarArgs) {
8215 // CHECK: printf/scanf-like function is called with no format string.
8216 if (format_idx >= Args.size()) {
8217 Diag(Loc, diag::warn_missing_format_string) << Range;
8218 return false;
8219 }
8220
8221 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8222
8223 // CHECK: format string is not a string literal.
8224 //
8225 // Dynamically generated format strings are difficult to
8226 // automatically vet at compile time. Requiring that format strings
8227 // are string literals: (1) permits the checking of format strings by
8228 // the compiler and thereby (2) can practically remove the source of
8229 // many format string exploits.
8230
8231 // Format string can be either ObjC string (e.g. @"%d") or
8232 // C string (e.g. "%d")
8233 // ObjC string uses the same format specifiers as C string, so we can use
8234 // the same format string checking logic for both ObjC and C strings.
8235 UncoveredArgHandler UncoveredArg;
8236 std::optional<unsigned> CallerParamIdx;
8237 StringLiteralCheckType CT = checkFormatStringExpr(
8238 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
8239 firstDataArg, Type, CallType,
8240 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
8241 /*no string offset*/ llvm::APSInt(64, false) = 0, &CallerParamIdx);
8242
8243 // Generate a diagnostic where an uncovered argument is detected.
8244 if (UncoveredArg.hasUncoveredArg()) {
8245 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8246 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8247 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8248 }
8249
8250 if (CT != SLCT_NotALiteral)
8251 // Literal format string found, check done!
8252 return CT == SLCT_CheckedLiteral;
8253
8254 // Do not emit diag when the string param is a macro expansion and the
8255 // format is either NSString or CFString. This is a hack to prevent
8256 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8257 // which are usually used in place of NS and CF string literals.
8258 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8260 SourceMgr.isInSystemMacro(FormatLoc))
8261 return false;
8262
8263 if (CallerParamIdx && CheckMissingFormatAttribute(
8264 this, Args, APK, ReferenceFormatString, format_idx,
8265 firstDataArg, Type, *CallerParamIdx, Loc))
8266 return false;
8267
8268 // Strftime is particular as it always uses a single 'time' argument,
8269 // so it is safe to pass a non-literal string.
8271 return false;
8272
8273 // If there are no arguments specified, warn with -Wformat-security, otherwise
8274 // warn only with -Wformat-nonliteral.
8275 if (Args.size() == firstDataArg) {
8276 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8277 << OrigFormatExpr->getSourceRange();
8278 switch (Type) {
8279 default:
8280 break;
8284 Diag(FormatLoc, diag::note_format_security_fixit)
8285 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8286 break;
8288 Diag(FormatLoc, diag::note_format_security_fixit)
8289 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8290 break;
8291 }
8292 } else {
8293 Diag(FormatLoc, diag::warn_format_nonliteral)
8294 << OrigFormatExpr->getSourceRange();
8295 }
8296 return false;
8297}
8298
8299namespace {
8300
8301class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8302protected:
8303 Sema &S;
8304 const FormatStringLiteral *FExpr;
8305 const Expr *OrigFormatExpr;
8306 const FormatStringType FSType;
8307 const unsigned FirstDataArg;
8308 const unsigned NumDataArgs;
8309 const char *Beg; // Start of format string.
8310 const Sema::FormatArgumentPassingKind ArgPassingKind;
8311 ArrayRef<const Expr *> Args;
8312 unsigned FormatIdx;
8313 llvm::SmallBitVector CoveredArgs;
8314 bool usesPositionalArgs = false;
8315 bool atFirstArg = true;
8316 bool inFunctionCall;
8317 VariadicCallType CallType;
8318 llvm::SmallBitVector &CheckedVarArgs;
8319 UncoveredArgHandler &UncoveredArg;
8320
8321public:
8322 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8323 const Expr *origFormatExpr, const FormatStringType type,
8324 unsigned firstDataArg, unsigned numDataArgs,
8325 const char *beg, Sema::FormatArgumentPassingKind APK,
8326 ArrayRef<const Expr *> Args, unsigned formatIdx,
8327 bool inFunctionCall, VariadicCallType callType,
8328 llvm::SmallBitVector &CheckedVarArgs,
8329 UncoveredArgHandler &UncoveredArg)
8330 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8331 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8332 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
8333 inFunctionCall(inFunctionCall), CallType(callType),
8334 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8335 CoveredArgs.resize(numDataArgs);
8336 CoveredArgs.reset();
8337 }
8338
8339 bool HasFormatArguments() const {
8340 return ArgPassingKind == Sema::FAPK_Fixed ||
8341 ArgPassingKind == Sema::FAPK_Variadic;
8342 }
8343
8344 void DoneProcessing();
8345
8346 void HandleIncompleteSpecifier(const char *startSpecifier,
8347 unsigned specifierLen) override;
8348
8349 void HandleInvalidLengthModifier(
8350 const analyze_format_string::FormatSpecifier &FS,
8351 const analyze_format_string::ConversionSpecifier &CS,
8352 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
8353
8354 void HandleNonStandardLengthModifier(
8355 const analyze_format_string::FormatSpecifier &FS,
8356 const char *startSpecifier, unsigned specifierLen);
8357
8358 void HandleNonStandardConversionSpecifier(
8359 const analyze_format_string::ConversionSpecifier &CS,
8360 const char *startSpecifier, unsigned specifierLen);
8361
8362 void HandlePosition(const char *startPos, unsigned posLen) override;
8363
8364 void HandleInvalidPosition(const char *startSpecifier, unsigned specifierLen,
8366
8367 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8368
8369 void HandleNullChar(const char *nullCharacter) override;
8370
8371 template <typename Range>
8372 static void
8373 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8374 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8375 bool IsStringLocation, Range StringRange,
8376 ArrayRef<FixItHint> Fixit = {});
8377
8378protected:
8379 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8380 const char *startSpec,
8381 unsigned specifierLen,
8382 const char *csStart, unsigned csLen);
8383
8384 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8385 const char *startSpec,
8386 unsigned specifierLen);
8387
8388 SourceRange getFormatStringRange();
8389 CharSourceRange getSpecifierRange(const char *startSpecifier,
8390 unsigned specifierLen);
8391 SourceLocation getLocationOfByte(const char *x);
8392
8393 const Expr *getDataArg(unsigned i) const;
8394
8395 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8396 const analyze_format_string::ConversionSpecifier &CS,
8397 const char *startSpecifier, unsigned specifierLen,
8398 unsigned argIndex);
8399
8400 bool CheckUnsupportedType(const analyze_format_string::ArgType &AT,
8401 const Expr *E, const char *startSpecifier,
8402 unsigned specifierLen);
8403
8404 template <typename Range>
8405 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8406 bool IsStringLocation, Range StringRange,
8407 ArrayRef<FixItHint> Fixit = {});
8408};
8409
8410} // namespace
8411
8412SourceRange CheckFormatHandler::getFormatStringRange() {
8413 return OrigFormatExpr->getSourceRange();
8414}
8415
8417CheckFormatHandler::getSpecifierRange(const char *startSpecifier,
8418 unsigned specifierLen) {
8419 SourceLocation Start = getLocationOfByte(startSpecifier);
8420 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
8421
8422 // Advance the end SourceLocation by one due to half-open ranges.
8423 End = End.getLocWithOffset(1);
8424
8425 return CharSourceRange::getCharRange(Start, End);
8426}
8427
8428SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8429 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8431}
8432
8433void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8434 unsigned specifierLen) {
8435 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8436 getLocationOfByte(startSpecifier),
8437 /*IsStringLocation*/ true,
8438 getSpecifierRange(startSpecifier, specifierLen));
8439}
8440
8441bool CheckFormatHandler::CheckUnsupportedType(
8442 const analyze_format_string::ArgType &AT, const Expr *E,
8443 const char *StartSpecifier, unsigned SpecifierLen) {
8444 if (!AT.isUnsupported())
8445 return false;
8446
8447 EmitFormatDiagnostic(S.PDiag(diag::warn_format_unsupported_type)
8449 E->getExprLoc(), /*IsStringLocation=*/false,
8450 getSpecifierRange(StartSpecifier, SpecifierLen));
8451 return true;
8452}
8453
8454void CheckFormatHandler::HandleInvalidLengthModifier(
8457 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8458 using namespace analyze_format_string;
8459
8460 const LengthModifier &LM = FS.getLengthModifier();
8461 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8462
8463 // See if we know how to fix this length modifier.
8464 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8465 if (FixedLM) {
8466 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8467 getLocationOfByte(LM.getStart()),
8468 /*IsStringLocation*/ true,
8469 getSpecifierRange(startSpecifier, specifierLen));
8470
8471 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8472 << FixedLM->toString()
8473 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8474
8475 } else {
8476 FixItHint Hint;
8477 if (DiagID == diag::warn_format_nonsensical_length)
8478 Hint = FixItHint::CreateRemoval(LMRange);
8479
8480 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8481 getLocationOfByte(LM.getStart()),
8482 /*IsStringLocation*/ true,
8483 getSpecifierRange(startSpecifier, specifierLen), Hint);
8484 }
8485}
8486
8487void CheckFormatHandler::HandleNonStandardLengthModifier(
8489 const char *startSpecifier, unsigned specifierLen) {
8490 using namespace analyze_format_string;
8491
8492 const LengthModifier &LM = FS.getLengthModifier();
8493 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8494
8495 // See if we know how to fix this length modifier.
8496 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8497 if (FixedLM) {
8498 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8499 << LM.toString() << 0,
8500 getLocationOfByte(LM.getStart()),
8501 /*IsStringLocation*/ true,
8502 getSpecifierRange(startSpecifier, specifierLen));
8503
8504 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8505 << FixedLM->toString()
8506 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8507
8508 } else {
8509 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8510 << LM.toString() << 0,
8511 getLocationOfByte(LM.getStart()),
8512 /*IsStringLocation*/ true,
8513 getSpecifierRange(startSpecifier, specifierLen));
8514 }
8515}
8516
8517void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8519 const char *startSpecifier, unsigned specifierLen) {
8520 using namespace analyze_format_string;
8521
8522 // See if we know how to fix this conversion specifier.
8523 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8524 if (FixedCS) {
8525 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8526 << CS.toString() << /*conversion specifier*/ 1,
8527 getLocationOfByte(CS.getStart()),
8528 /*IsStringLocation*/ true,
8529 getSpecifierRange(startSpecifier, specifierLen));
8530
8531 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8532 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8533 << FixedCS->toString()
8534 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8535 } else {
8536 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8537 << CS.toString() << /*conversion specifier*/ 1,
8538 getLocationOfByte(CS.getStart()),
8539 /*IsStringLocation*/ true,
8540 getSpecifierRange(startSpecifier, specifierLen));
8541 }
8542}
8543
8544void CheckFormatHandler::HandlePosition(const char *startPos, unsigned posLen) {
8545 if (!S.getDiagnostics().isIgnored(
8546 diag::warn_format_non_standard_positional_arg, SourceLocation()))
8547 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8548 getLocationOfByte(startPos),
8549 /*IsStringLocation*/ true,
8550 getSpecifierRange(startPos, posLen));
8551}
8552
8553void CheckFormatHandler::HandleInvalidPosition(
8554 const char *startSpecifier, unsigned specifierLen,
8556 if (!S.getDiagnostics().isIgnored(
8557 diag::warn_format_invalid_positional_specifier, SourceLocation()))
8558 EmitFormatDiagnostic(
8559 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
8560 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
8561 getSpecifierRange(startSpecifier, specifierLen));
8562}
8563
8564void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8565 unsigned posLen) {
8566 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
8567 SourceLocation()))
8568 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8569 getLocationOfByte(startPos),
8570 /*IsStringLocation*/ true,
8571 getSpecifierRange(startPos, posLen));
8572}
8573
8574void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8575 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8576 // The presence of a null character is likely an error.
8577 EmitFormatDiagnostic(
8578 S.PDiag(diag::warn_printf_format_string_contains_null_char),
8579 getLocationOfByte(nullCharacter), /*IsStringLocation*/ true,
8580 getFormatStringRange());
8581 }
8582}
8583
8584// Note that this may return NULL if there was an error parsing or building
8585// one of the argument expressions.
8586const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8587 return Args[FirstDataArg + i];
8588}
8589
8590void CheckFormatHandler::DoneProcessing() {
8591 // Does the number of data arguments exceed the number of
8592 // format conversions in the format string?
8593 if (HasFormatArguments()) {
8594 // Find any arguments that weren't covered.
8595 CoveredArgs.flip();
8596 signed notCoveredArg = CoveredArgs.find_first();
8597 if (notCoveredArg >= 0) {
8598 assert((unsigned)notCoveredArg < NumDataArgs);
8599 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8600 } else {
8601 UncoveredArg.setAllCovered();
8602 }
8603 }
8604}
8605
8606void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8607 const Expr *ArgExpr) {
8608 assert(hasUncoveredArg() && !DiagnosticExprs.empty() && "Invalid state");
8609
8610 if (!ArgExpr)
8611 return;
8612
8613 SourceLocation Loc = ArgExpr->getBeginLoc();
8614
8615 if (S.getSourceManager().isInSystemMacro(Loc))
8616 return;
8617
8618 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8619 for (auto E : DiagnosticExprs)
8620 PDiag << E->getSourceRange();
8621
8622 CheckFormatHandler::EmitFormatDiagnostic(
8623 S, IsFunctionCall, DiagnosticExprs[0], PDiag, Loc,
8624 /*IsStringLocation*/ false, DiagnosticExprs[0]->getSourceRange());
8625}
8626
8627bool CheckFormatHandler::HandleInvalidConversionSpecifier(
8628 unsigned argIndex, SourceLocation Loc, const char *startSpec,
8629 unsigned specifierLen, const char *csStart, unsigned csLen) {
8630 bool keepGoing = true;
8631 if (argIndex < NumDataArgs) {
8632 // Consider the argument coverered, even though the specifier doesn't
8633 // make sense.
8634 CoveredArgs.set(argIndex);
8635 } else {
8636 // If argIndex exceeds the number of data arguments we
8637 // don't issue a warning because that is just a cascade of warnings (and
8638 // they may have intended '%%' anyway). We don't want to continue processing
8639 // the format string after this point, however, as we will like just get
8640 // gibberish when trying to match arguments.
8641 keepGoing = false;
8642 }
8643
8644 StringRef Specifier(csStart, csLen);
8645
8646 // If the specifier in non-printable, it could be the first byte of a UTF-8
8647 // sequence. In that case, print the UTF-8 code point. If not, print the byte
8648 // hex value.
8649 std::string CodePointStr;
8650 if (!llvm::sys::locale::isPrint(*csStart)) {
8651 llvm::UTF32 CodePoint;
8652 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8653 const llvm::UTF8 *E = reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8654 llvm::ConversionResult Result =
8655 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8656
8657 if (Result != llvm::conversionOK) {
8658 unsigned char FirstChar = *csStart;
8659 CodePoint = (llvm::UTF32)FirstChar;
8660 }
8661
8662 llvm::raw_string_ostream OS(CodePointStr);
8663 if (CodePoint < 256)
8664 OS << "\\x" << llvm::format("%02x", CodePoint);
8665 else if (CodePoint <= 0xFFFF)
8666 OS << "\\u" << llvm::format("%04x", CodePoint);
8667 else
8668 OS << "\\U" << llvm::format("%08x", CodePoint);
8669 Specifier = CodePointStr;
8670 }
8671
8672 EmitFormatDiagnostic(
8673 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8674 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8675
8676 return keepGoing;
8677}
8678
8679void CheckFormatHandler::HandlePositionalNonpositionalArgs(
8680 SourceLocation Loc, const char *startSpec, unsigned specifierLen) {
8681 EmitFormatDiagnostic(
8682 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), Loc,
8683 /*isStringLoc*/ true, getSpecifierRange(startSpec, specifierLen));
8684}
8685
8686bool CheckFormatHandler::CheckNumArgs(
8689 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8690
8691 if (HasFormatArguments() && argIndex >= NumDataArgs) {
8692 PartialDiagnostic PDiag =
8694 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8695 << (argIndex + 1) << NumDataArgs)
8696 : S.PDiag(diag::warn_printf_insufficient_data_args);
8697 EmitFormatDiagnostic(PDiag, getLocationOfByte(CS.getStart()),
8698 /*IsStringLocation*/ true,
8699 getSpecifierRange(startSpecifier, specifierLen));
8700
8701 // Since more arguments than conversion tokens are given, by extension
8702 // all arguments are covered, so mark this as so.
8703 UncoveredArg.setAllCovered();
8704 return false;
8705 }
8706 return true;
8707}
8708
8709template <typename Range>
8710void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8711 SourceLocation Loc,
8712 bool IsStringLocation,
8713 Range StringRange,
8714 ArrayRef<FixItHint> FixIt) {
8715 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, Loc,
8716 IsStringLocation, StringRange, FixIt);
8717}
8718
8719/// If the format string is not within the function call, emit a note
8720/// so that the function call and string are in diagnostic messages.
8721///
8722/// \param InFunctionCall if true, the format string is within the function
8723/// call and only one diagnostic message will be produced. Otherwise, an
8724/// extra note will be emitted pointing to location of the format string.
8725///
8726/// \param ArgumentExpr the expression that is passed as the format string
8727/// argument in the function call. Used for getting locations when two
8728/// diagnostics are emitted.
8729///
8730/// \param PDiag the callee should already have provided any strings for the
8731/// diagnostic message. This function only adds locations and fixits
8732/// to diagnostics.
8733///
8734/// \param Loc primary location for diagnostic. If two diagnostics are
8735/// required, one will be at Loc and a new SourceLocation will be created for
8736/// the other one.
8737///
8738/// \param IsStringLocation if true, Loc points to the format string should be
8739/// used for the note. Otherwise, Loc points to the argument list and will
8740/// be used with PDiag.
8741///
8742/// \param StringRange some or all of the string to highlight. This is
8743/// templated so it can accept either a CharSourceRange or a SourceRange.
8744///
8745/// \param FixIt optional fix it hint for the format string.
8746template <typename Range>
8747void CheckFormatHandler::EmitFormatDiagnostic(
8748 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8749 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8750 Range StringRange, ArrayRef<FixItHint> FixIt) {
8751 if (InFunctionCall) {
8752 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8753 D << StringRange;
8754 D << FixIt;
8755 } else {
8756 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8757 << ArgumentExpr->getSourceRange();
8758
8760 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8761 diag::note_format_string_defined);
8762
8763 Note << StringRange;
8764 Note << FixIt;
8765 }
8766}
8767
8768//===--- CHECK: Printf format string checking -----------------------------===//
8769
8770namespace {
8771
8772class CheckPrintfHandler : public CheckFormatHandler {
8773public:
8774 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8775 const Expr *origFormatExpr, const FormatStringType type,
8776 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8777 const char *beg, Sema::FormatArgumentPassingKind APK,
8778 ArrayRef<const Expr *> Args, unsigned formatIdx,
8779 bool inFunctionCall, VariadicCallType CallType,
8780 llvm::SmallBitVector &CheckedVarArgs,
8781 UncoveredArgHandler &UncoveredArg)
8782 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8783 numDataArgs, beg, APK, Args, formatIdx,
8784 inFunctionCall, CallType, CheckedVarArgs,
8785 UncoveredArg) {}
8786
8787 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8788
8789 /// Returns true if '%@' specifiers are allowed in the format string.
8790 bool allowsObjCArg() const {
8791 return FSType == FormatStringType::NSString ||
8792 FSType == FormatStringType::OSLog ||
8793 FSType == FormatStringType::OSTrace;
8794 }
8795
8796 bool HandleInvalidPrintfConversionSpecifier(
8797 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8798 unsigned specifierLen) override;
8799
8800 void handleInvalidMaskType(StringRef MaskType) override;
8801
8802 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8803 const char *startSpecifier, unsigned specifierLen,
8804 const TargetInfo &Target) override;
8805 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8806 const char *StartSpecifier, unsigned SpecifierLen,
8807 const Expr *E);
8808
8809 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt,
8810 unsigned k, const char *startSpecifier,
8811 unsigned specifierLen);
8812 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8813 const analyze_printf::OptionalAmount &Amt,
8814 unsigned type, const char *startSpecifier,
8815 unsigned specifierLen);
8816 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8817 const analyze_printf::OptionalFlag &flag,
8818 const char *startSpecifier, unsigned specifierLen);
8819 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8820 const analyze_printf::OptionalFlag &ignoredFlag,
8821 const analyze_printf::OptionalFlag &flag,
8822 const char *startSpecifier, unsigned specifierLen);
8823 bool checkForCStrMembers(const analyze_printf::ArgType &AT, const Expr *E);
8824
8825 void HandleEmptyObjCModifierFlag(const char *startFlag,
8826 unsigned flagLen) override;
8827
8828 void HandleInvalidObjCModifierFlag(const char *startFlag,
8829 unsigned flagLen) override;
8830
8831 void
8832 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8833 const char *flagsEnd,
8834 const char *conversionPosition) override;
8835};
8836
8837/// Keeps around the information needed to verify that two specifiers are
8838/// compatible.
8839class EquatableFormatArgument {
8840public:
8841 enum SpecifierSensitivity : unsigned {
8842 SS_None,
8843 SS_Private,
8844 SS_Public,
8845 SS_Sensitive
8846 };
8847
8848 enum FormatArgumentRole : unsigned {
8849 FAR_Data,
8850 FAR_FieldWidth,
8851 FAR_Precision,
8852 FAR_Auxiliary, // FreeBSD kernel %b and %D
8853 };
8854
8855private:
8856 analyze_format_string::ArgType ArgType;
8857 analyze_format_string::LengthModifier LengthMod;
8858 StringRef SpecifierLetter;
8859 CharSourceRange Range;
8860 SourceLocation ElementLoc;
8861 FormatArgumentRole Role : 2;
8862 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8863 unsigned Position : 14;
8864 unsigned ModifierFor : 14; // not set for FAR_Data
8865
8866 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8867 bool InFunctionCall) const;
8868
8869public:
8870 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8871 analyze_format_string::LengthModifier LengthMod,
8872 StringRef SpecifierLetter,
8873 analyze_format_string::ArgType ArgType,
8874 FormatArgumentRole Role,
8875 SpecifierSensitivity Sensitivity, unsigned Position,
8876 unsigned ModifierFor)
8877 : ArgType(ArgType), LengthMod(LengthMod),
8878 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8879 Role(Role), Sensitivity(Sensitivity), Position(Position),
8880 ModifierFor(ModifierFor) {}
8881
8882 unsigned getPosition() const { return Position; }
8883 SourceLocation getSourceLocation() const { return ElementLoc; }
8884 CharSourceRange getSourceRange() const { return Range; }
8885 analyze_format_string::LengthModifier getLengthModifier() const {
8886 return LengthMod;
8887 }
8888 void setModifierFor(unsigned V) { ModifierFor = V; }
8889
8890 std::string buildFormatSpecifier() const {
8891 std::string result;
8892 llvm::raw_string_ostream(result)
8893 << getLengthModifier().toString() << SpecifierLetter;
8894 return result;
8895 }
8896
8897 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8898 const Expr *FmtExpr, bool InFunctionCall) const;
8899};
8900
8901/// Turns format strings into lists of EquatableSpecifier objects.
8902class DecomposePrintfHandler : public CheckPrintfHandler {
8903 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8904 bool HadError;
8905
8906 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8907 const Expr *origFormatExpr,
8908 const FormatStringType type, unsigned firstDataArg,
8909 unsigned numDataArgs, bool isObjC, const char *beg,
8911 ArrayRef<const Expr *> Args, unsigned formatIdx,
8912 bool inFunctionCall, VariadicCallType CallType,
8913 llvm::SmallBitVector &CheckedVarArgs,
8914 UncoveredArgHandler &UncoveredArg,
8915 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8916 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8917 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8918 inFunctionCall, CallType, CheckedVarArgs,
8919 UncoveredArg),
8920 Specs(Specs), HadError(false) {}
8921
8922public:
8923 static bool
8924 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8925 FormatStringType type, bool IsObjC, bool InFunctionCall,
8926 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8927
8928 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8929 const char *startSpecifier,
8930 unsigned specifierLen,
8931 const TargetInfo &Target) override;
8932};
8933
8934} // namespace
8935
8936bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8937 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8938 unsigned specifierLen) {
8941
8942 return HandleInvalidConversionSpecifier(
8943 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
8944 specifierLen, CS.getStart(), CS.getLength());
8945}
8946
8947void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8948 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8949}
8950
8951// Error out if struct or complex type argments are passed to os_log.
8953 QualType T) {
8954 if (FSType != FormatStringType::OSLog)
8955 return false;
8956 return T->isRecordType() || T->isComplexType();
8957}
8958
8959bool CheckPrintfHandler::HandleAmount(
8960 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8961 const char *startSpecifier, unsigned specifierLen) {
8962 if (Amt.hasDataArgument()) {
8963 if (HasFormatArguments()) {
8964 unsigned argIndex = Amt.getArgIndex();
8965 if (argIndex >= NumDataArgs) {
8966 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8967 << k,
8968 getLocationOfByte(Amt.getStart()),
8969 /*IsStringLocation*/ true,
8970 getSpecifierRange(startSpecifier, specifierLen));
8971 // Don't do any more checking. We will just emit
8972 // spurious errors.
8973 return false;
8974 }
8975
8976 // Type check the data argument. It should be an 'int'.
8977 // Although not in conformance with C99, we also allow the argument to be
8978 // an 'unsigned int' as that is a reasonably safe case. GCC also
8979 // doesn't emit a warning for that case.
8980 CoveredArgs.set(argIndex);
8981 const Expr *Arg = getDataArg(argIndex);
8982 if (!Arg)
8983 return false;
8984
8985 QualType T = Arg->getType();
8986
8987 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8988 assert(AT.isValid());
8989
8990 if (!AT.matchesType(S.Context, T)) {
8991 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8992 ? diag::err_printf_asterisk_wrong_type
8993 : diag::warn_printf_asterisk_wrong_type;
8994 EmitFormatDiagnostic(S.PDiag(DiagID)
8996 << T << Arg->getSourceRange(),
8997 getLocationOfByte(Amt.getStart()),
8998 /*IsStringLocation*/ true,
8999 getSpecifierRange(startSpecifier, specifierLen));
9000 // Don't do any more checking. We will just emit
9001 // spurious errors.
9002 return false;
9003 }
9004 }
9005 }
9006 return true;
9007}
9008
9009void CheckPrintfHandler::HandleInvalidAmount(
9011 const analyze_printf::OptionalAmount &Amt, unsigned type,
9012 const char *startSpecifier, unsigned specifierLen) {
9015
9016 FixItHint fixit =
9019 getSpecifierRange(Amt.getStart(), Amt.getConstantLength()))
9020 : FixItHint();
9021
9022 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
9023 << type << CS.toString(),
9024 getLocationOfByte(Amt.getStart()),
9025 /*IsStringLocation*/ true,
9026 getSpecifierRange(startSpecifier, specifierLen), fixit);
9027}
9028
9029void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9030 const analyze_printf::OptionalFlag &flag,
9031 const char *startSpecifier,
9032 unsigned specifierLen) {
9033 // Warn about pointless flag with a fixit removal.
9036 EmitFormatDiagnostic(
9037 S.PDiag(diag::warn_printf_nonsensical_flag)
9038 << flag.toString() << CS.toString(),
9039 getLocationOfByte(flag.getPosition()),
9040 /*IsStringLocation*/ true,
9041 getSpecifierRange(startSpecifier, specifierLen),
9042 FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1)));
9043}
9044
9045void CheckPrintfHandler::HandleIgnoredFlag(
9047 const analyze_printf::OptionalFlag &ignoredFlag,
9048 const analyze_printf::OptionalFlag &flag, const char *startSpecifier,
9049 unsigned specifierLen) {
9050 // Warn about ignored flag with a fixit removal.
9051 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
9052 << ignoredFlag.toString() << flag.toString(),
9053 getLocationOfByte(ignoredFlag.getPosition()),
9054 /*IsStringLocation*/ true,
9055 getSpecifierRange(startSpecifier, specifierLen),
9057 getSpecifierRange(ignoredFlag.getPosition(), 1)));
9058}
9059
9060void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
9061 unsigned flagLen) {
9062 // Warn about an empty flag.
9063 EmitFormatDiagnostic(
9064 S.PDiag(diag::warn_printf_empty_objc_flag), getLocationOfByte(startFlag),
9065 /*IsStringLocation*/ true, getSpecifierRange(startFlag, flagLen));
9066}
9067
9068void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
9069 unsigned flagLen) {
9070 // Warn about an invalid flag.
9071 auto Range = getSpecifierRange(startFlag, flagLen);
9072 StringRef flag(startFlag, flagLen);
9073 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
9074 getLocationOfByte(startFlag),
9075 /*IsStringLocation*/ true, Range,
9077}
9078
9079void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
9080 const char *flagsStart, const char *flagsEnd,
9081 const char *conversionPosition) {
9082 // Warn about using '[...]' without a '@' conversion.
9083 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
9084 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
9085 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
9086 getLocationOfByte(conversionPosition),
9087 /*IsStringLocation*/ true, Range,
9089}
9090
9091void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
9092 const Expr *FmtExpr,
9093 bool InFunctionCall) const {
9094 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
9095 ElementLoc, true, Range);
9096}
9097
9098bool EquatableFormatArgument::VerifyCompatible(
9099 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
9100 bool InFunctionCall) const {
9102 if (Role != Other.Role) {
9103 // diagnose and stop
9104 EmitDiagnostic(
9105 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
9106 FmtExpr, InFunctionCall);
9107 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
9108 return false;
9109 }
9110
9111 if (Role != FAR_Data) {
9112 if (ModifierFor != Other.ModifierFor) {
9113 // diagnose and stop
9114 EmitDiagnostic(S,
9115 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
9116 << (ModifierFor + 1) << (Other.ModifierFor + 1),
9117 FmtExpr, InFunctionCall);
9118 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
9119 return false;
9120 }
9121 return true;
9122 }
9123
9124 bool HadError = false;
9125 if (Sensitivity != Other.Sensitivity) {
9126 // diagnose and continue
9127 EmitDiagnostic(S,
9128 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
9129 << Sensitivity << Other.Sensitivity,
9130 FmtExpr, InFunctionCall);
9131 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
9132 << 0 << Other.Range;
9133 }
9134
9135 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
9136 case MK::Match:
9137 break;
9138
9139 case MK::MatchPromotion:
9140 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
9141 // MatchPromotion is treated as a failure by format_matches.
9142 case MK::NoMatch:
9143 case MK::NoMatchTypeConfusion:
9144 case MK::NoMatchPromotionTypeConfusion:
9145 EmitDiagnostic(S,
9146 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
9147 << buildFormatSpecifier()
9148 << Other.buildFormatSpecifier(),
9149 FmtExpr, InFunctionCall);
9150 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
9151 << 0 << Other.Range;
9152 break;
9153
9154 case MK::NoMatchPedantic:
9155 EmitDiagnostic(S,
9156 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
9157 << buildFormatSpecifier()
9158 << Other.buildFormatSpecifier(),
9159 FmtExpr, InFunctionCall);
9160 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
9161 << 0 << Other.Range;
9162 break;
9163
9164 case MK::NoMatchSignedness:
9165 EmitDiagnostic(S,
9166 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
9167 << buildFormatSpecifier()
9168 << Other.buildFormatSpecifier(),
9169 FmtExpr, InFunctionCall);
9170 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
9171 << 0 << Other.Range;
9172 break;
9173 }
9174 return !HadError;
9175}
9176
9177bool DecomposePrintfHandler::GetSpecifiers(
9178 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
9179 FormatStringType Type, bool IsObjC, bool InFunctionCall,
9181 StringRef Data = FSL->getString();
9182 const char *Str = Data.data();
9183 llvm::SmallBitVector BV;
9184 UncoveredArgHandler UA;
9185 const Expr *PrintfArgs[] = {FSL->getFormatString()};
9186 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
9187 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
9188 InFunctionCall, VariadicCallType::DoesNotApply, BV,
9189 UA, Args);
9190
9192 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
9194 H.DoneProcessing();
9195 if (H.HadError)
9196 return false;
9197
9198 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
9199 const EquatableFormatArgument &B) {
9200 return A.getPosition() < B.getPosition();
9201 });
9202 return true;
9203}
9204
9205bool DecomposePrintfHandler::HandlePrintfSpecifier(
9206 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9207 unsigned specifierLen, const TargetInfo &Target) {
9208 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
9209 specifierLen, Target)) {
9210 HadError = true;
9211 return false;
9212 }
9213
9214 // Do not add any specifiers to the list for %%. This is possibly incorrect
9215 // if using a precision/width with a data argument, but that combination is
9216 // meaningless and we wouldn't know which format to attach the
9217 // precision/width to.
9218 const auto &CS = FS.getConversionSpecifier();
9220 return true;
9221
9222 // have to patch these to have the right ModifierFor if they are used
9223 const unsigned Unset = ~0;
9224 unsigned FieldWidthIndex = Unset;
9225 unsigned PrecisionIndex = Unset;
9226
9227 // field width?
9228 const auto &FieldWidth = FS.getFieldWidth();
9229 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
9230 FieldWidthIndex = Specs.size();
9231 Specs.emplace_back(
9232 getSpecifierRange(startSpecifier, specifierLen),
9233 getLocationOfByte(FieldWidth.getStart()),
9234 analyze_format_string::LengthModifier(), FieldWidth.getCharacters(),
9235 FieldWidth.getArgType(S.Context),
9236 EquatableFormatArgument::FAR_FieldWidth,
9237 EquatableFormatArgument::SS_None,
9238 FieldWidth.usesPositionalArg() ? FieldWidth.getPositionalArgIndex() - 1
9239 : FieldWidthIndex,
9240 0);
9241 }
9242 // precision?
9243 const auto &Precision = FS.getPrecision();
9244 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
9245 PrecisionIndex = Specs.size();
9246 Specs.emplace_back(
9247 getSpecifierRange(startSpecifier, specifierLen),
9248 getLocationOfByte(Precision.getStart()),
9249 analyze_format_string::LengthModifier(), Precision.getCharacters(),
9250 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
9251 EquatableFormatArgument::SS_None,
9252 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
9253 : PrecisionIndex,
9254 0);
9255 }
9256
9257 // this specifier
9258 unsigned SpecIndex =
9259 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
9260 if (FieldWidthIndex != Unset)
9261 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
9262 if (PrecisionIndex != Unset)
9263 Specs[PrecisionIndex].setModifierFor(SpecIndex);
9264
9265 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
9266 if (FS.isPrivate())
9267 Sensitivity = EquatableFormatArgument::SS_Private;
9268 else if (FS.isPublic())
9269 Sensitivity = EquatableFormatArgument::SS_Public;
9270 else if (FS.isSensitive())
9271 Sensitivity = EquatableFormatArgument::SS_Sensitive;
9272 else
9273 Sensitivity = EquatableFormatArgument::SS_None;
9274
9275 Specs.emplace_back(
9276 getSpecifierRange(startSpecifier, specifierLen),
9277 getLocationOfByte(CS.getStart()), FS.getLengthModifier(),
9278 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
9279 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
9280
9281 // auxiliary argument?
9284 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
9285 getLocationOfByte(CS.getStart()),
9287 CS.getCharacters(),
9289 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
9290 SpecIndex + 1, SpecIndex);
9291 }
9292 return true;
9293}
9294
9295// Determines if the specified is a C++ class or struct containing
9296// a member with the specified name and kind (e.g. a CXXMethodDecl named
9297// "c_str()").
9298template<typename MemberKind>
9300CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9301 auto *RD = Ty->getAsCXXRecordDecl();
9303
9304 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
9305 return Results;
9306
9307 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9309 R.suppressDiagnostics();
9310
9311 // We just need to include all members of the right kind turned up by the
9312 // filter, at this point.
9313 if (S.LookupQualifiedName(R, RD))
9314 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9315 NamedDecl *decl = (*I)->getUnderlyingDecl();
9316 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9317 Results.insert(FK);
9318 }
9319 return Results;
9320}
9321
9322/// Check if we could call '.c_str()' on an object.
9323///
9324/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9325/// allow the call, or if it would be ambiguous).
9327 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9328
9329 MethodSet Results =
9330 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9331 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9332 MI != ME; ++MI)
9333 if ((*MI)->getMinRequiredArguments() == 0)
9334 return true;
9335 return false;
9336}
9337
9338// Check if a (w)string was passed when a (w)char* was needed, and offer a
9339// better diagnostic if so. AT is assumed to be valid.
9340// Returns true when a c_str() conversion method is found.
9341bool CheckPrintfHandler::checkForCStrMembers(
9342 const analyze_printf::ArgType &AT, const Expr *E) {
9343 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9344
9345 MethodSet Results =
9347
9348 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9349 MI != ME; ++MI) {
9350 const CXXMethodDecl *Method = *MI;
9351 if (Method->getMinRequiredArguments() == 0 &&
9352 AT.matchesType(S.Context, Method->getReturnType())) {
9353 // FIXME: Suggest parens if the expression needs them.
9355 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9356 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9357 return true;
9358 }
9359 }
9360
9361 return false;
9362}
9363
9364bool CheckPrintfHandler::HandlePrintfSpecifier(
9365 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9366 unsigned specifierLen, const TargetInfo &Target) {
9367 using namespace analyze_format_string;
9368 using namespace analyze_printf;
9369
9370 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9371
9372 if (FS.consumesDataArgument()) {
9373 if (atFirstArg) {
9374 atFirstArg = false;
9375 usesPositionalArgs = FS.usesPositionalArg();
9376 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9377 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9378 startSpecifier, specifierLen);
9379 return false;
9380 }
9381 }
9382
9383 // First check if the field width, precision, and conversion specifier
9384 // have matching data arguments.
9385 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, startSpecifier,
9386 specifierLen)) {
9387 return false;
9388 }
9389
9390 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, startSpecifier,
9391 specifierLen)) {
9392 return false;
9393 }
9394
9395 if (!CS.consumesDataArgument()) {
9396 // FIXME: Technically specifying a precision or field width here
9397 // makes no sense. Worth issuing a warning at some point.
9398 return true;
9399 }
9400
9401 // Consume the argument.
9402 unsigned argIndex = FS.getArgIndex();
9403 if (argIndex < NumDataArgs) {
9404 // The check to see if the argIndex is valid will come later.
9405 // We set the bit here because we may exit early from this
9406 // function if we encounter some other error.
9407 CoveredArgs.set(argIndex);
9408 }
9409
9410 // FreeBSD kernel extensions.
9411 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9412 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9413 // We need at least two arguments.
9414 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9415 return false;
9416
9417 if (HasFormatArguments()) {
9418 // Claim the second argument.
9419 CoveredArgs.set(argIndex + 1);
9420
9421 // Type check the first argument (int for %b, pointer for %D)
9422 const Expr *Ex = getDataArg(argIndex);
9423 const analyze_printf::ArgType &AT =
9424 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
9425 ? ArgType(S.Context.IntTy)
9426 : ArgType::CPointerTy;
9427 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9428 EmitFormatDiagnostic(
9429 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9430 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9431 << false << Ex->getSourceRange(),
9432 Ex->getBeginLoc(), /*IsStringLocation*/ false,
9433 getSpecifierRange(startSpecifier, specifierLen));
9434
9435 // Type check the second argument (char * for both %b and %D)
9436 Ex = getDataArg(argIndex + 1);
9438 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9439 EmitFormatDiagnostic(
9440 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9441 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9442 << false << Ex->getSourceRange(),
9443 Ex->getBeginLoc(), /*IsStringLocation*/ false,
9444 getSpecifierRange(startSpecifier, specifierLen));
9445 }
9446 return true;
9447 }
9448
9449 // Check for using an Objective-C specific conversion specifier
9450 // in a non-ObjC literal.
9451 if (!allowsObjCArg() && CS.isObjCArg()) {
9452 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9453 specifierLen);
9454 }
9455
9456 // %P can only be used with os_log.
9457 if (FSType != FormatStringType::OSLog &&
9458 CS.getKind() == ConversionSpecifier::PArg) {
9459 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9460 specifierLen);
9461 }
9462
9463 // %n is not allowed with os_log.
9464 if (FSType == FormatStringType::OSLog &&
9465 CS.getKind() == ConversionSpecifier::nArg) {
9466 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9467 getLocationOfByte(CS.getStart()),
9468 /*IsStringLocation*/ false,
9469 getSpecifierRange(startSpecifier, specifierLen));
9470
9471 return true;
9472 }
9473
9474 // Only scalars are allowed for os_trace.
9475 if (FSType == FormatStringType::OSTrace &&
9476 (CS.getKind() == ConversionSpecifier::PArg ||
9477 CS.getKind() == ConversionSpecifier::sArg ||
9478 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9479 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9480 specifierLen);
9481 }
9482
9483 // Check for use of public/private annotation outside of os_log().
9484 if (FSType != FormatStringType::OSLog) {
9485 if (FS.isPublic().isSet()) {
9486 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9487 << "public",
9488 getLocationOfByte(FS.isPublic().getPosition()),
9489 /*IsStringLocation*/ false,
9490 getSpecifierRange(startSpecifier, specifierLen));
9491 }
9492 if (FS.isPrivate().isSet()) {
9493 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9494 << "private",
9495 getLocationOfByte(FS.isPrivate().getPosition()),
9496 /*IsStringLocation*/ false,
9497 getSpecifierRange(startSpecifier, specifierLen));
9498 }
9499 }
9500
9501 const llvm::Triple &Triple = Target.getTriple();
9502 if (CS.getKind() == ConversionSpecifier::nArg &&
9503 (Triple.isAndroid() || Triple.isOSFuchsia())) {
9504 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9505 getLocationOfByte(CS.getStart()),
9506 /*IsStringLocation*/ false,
9507 getSpecifierRange(startSpecifier, specifierLen));
9508 }
9509
9510 // Check for invalid use of field width
9511 if (!FS.hasValidFieldWidth()) {
9512 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9513 startSpecifier, specifierLen);
9514 }
9515
9516 // Check for invalid use of precision
9517 if (!FS.hasValidPrecision()) {
9518 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9519 startSpecifier, specifierLen);
9520 }
9521
9522 // Precision is mandatory for %P specifier.
9523 if (CS.getKind() == ConversionSpecifier::PArg &&
9525 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9526 getLocationOfByte(startSpecifier),
9527 /*IsStringLocation*/ false,
9528 getSpecifierRange(startSpecifier, specifierLen));
9529 }
9530
9531 // Check each flag does not conflict with any other component.
9533 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9534 if (!FS.hasValidLeadingZeros())
9535 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9536 if (!FS.hasValidPlusPrefix())
9537 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9538 if (!FS.hasValidSpacePrefix())
9539 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9540 if (!FS.hasValidAlternativeForm())
9541 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9542 if (!FS.hasValidLeftJustified())
9543 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9544
9545 // Check that flags are not ignored by another flag
9546 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9547 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9548 startSpecifier, specifierLen);
9549 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9550 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9551 startSpecifier, specifierLen);
9552
9553 // Check the length modifier is valid with the given conversion specifier.
9555 S.getLangOpts()))
9556 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9557 diag::warn_format_nonsensical_length);
9558 else if (!FS.hasStandardLengthModifier())
9559 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9561 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9562 diag::warn_format_non_standard_conversion_spec);
9563
9565 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9566
9567 // The remaining checks depend on the data arguments.
9568 if (!HasFormatArguments())
9569 return true;
9570
9571 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9572 return false;
9573
9574 const Expr *Arg = getDataArg(argIndex);
9575 if (!Arg)
9576 return true;
9577
9578 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9579}
9580
9581static bool requiresParensToAddCast(const Expr *E) {
9582 // FIXME: We should have a general way to reason about operator
9583 // precedence and whether parens are actually needed here.
9584 // Take care of a few common cases where they aren't.
9585 const Expr *Inside = E->IgnoreImpCasts();
9586 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9587 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9588
9589 switch (Inside->getStmtClass()) {
9590 case Stmt::ArraySubscriptExprClass:
9591 case Stmt::CallExprClass:
9592 case Stmt::CharacterLiteralClass:
9593 case Stmt::CXXBoolLiteralExprClass:
9594 case Stmt::DeclRefExprClass:
9595 case Stmt::FloatingLiteralClass:
9596 case Stmt::IntegerLiteralClass:
9597 case Stmt::MemberExprClass:
9598 case Stmt::ObjCArrayLiteralClass:
9599 case Stmt::ObjCBoolLiteralExprClass:
9600 case Stmt::ObjCBoxedExprClass:
9601 case Stmt::ObjCDictionaryLiteralClass:
9602 case Stmt::ObjCEncodeExprClass:
9603 case Stmt::ObjCIvarRefExprClass:
9604 case Stmt::ObjCMessageExprClass:
9605 case Stmt::ObjCPropertyRefExprClass:
9606 case Stmt::ObjCStringLiteralClass:
9607 case Stmt::ObjCSubscriptRefExprClass:
9608 case Stmt::ParenExprClass:
9609 case Stmt::StringLiteralClass:
9610 case Stmt::UnaryOperatorClass:
9611 return false;
9612 default:
9613 return true;
9614 }
9615}
9616
9617static std::pair<QualType, StringRef>
9618shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy,
9619 const Expr *E) {
9620 // Use a 'while' to peel off layers of typedefs.
9621 QualType TyTy = IntendedTy;
9622 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9623 StringRef Name = UserTy->getDecl()->getName();
9624 QualType CastTy = llvm::StringSwitch<QualType>(Name)
9625 .Case("CFIndex", Context.getNSIntegerType())
9626 .Case("NSInteger", Context.getNSIntegerType())
9627 .Case("NSUInteger", Context.getNSUIntegerType())
9628 .Case("SInt32", Context.IntTy)
9629 .Case("UInt32", Context.UnsignedIntTy)
9630 .Default(QualType());
9631
9632 if (!CastTy.isNull())
9633 return std::make_pair(CastTy, Name);
9634
9635 TyTy = UserTy->desugar();
9636 }
9637
9638 // Strip parens if necessary.
9639 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9640 return shouldNotPrintDirectly(Context, PE->getSubExpr()->getType(),
9641 PE->getSubExpr());
9642
9643 // If this is a conditional expression, then its result type is constructed
9644 // via usual arithmetic conversions and thus there might be no necessary
9645 // typedef sugar there. Recurse to operands to check for NSInteger &
9646 // Co. usage condition.
9647 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9648 QualType TrueTy, FalseTy;
9649 StringRef TrueName, FalseName;
9650
9651 std::tie(TrueTy, TrueName) = shouldNotPrintDirectly(
9652 Context, CO->getTrueExpr()->getType(), CO->getTrueExpr());
9653 std::tie(FalseTy, FalseName) = shouldNotPrintDirectly(
9654 Context, CO->getFalseExpr()->getType(), CO->getFalseExpr());
9655
9656 if (TrueTy == FalseTy)
9657 return std::make_pair(TrueTy, TrueName);
9658 else if (TrueTy.isNull())
9659 return std::make_pair(FalseTy, FalseName);
9660 else if (FalseTy.isNull())
9661 return std::make_pair(TrueTy, TrueName);
9662 }
9663
9664 return std::make_pair(QualType(), StringRef());
9665}
9666
9667/// Return true if \p ICE is an implicit argument promotion of an arithmetic
9668/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9669/// type do not count.
9671 const ImplicitCastExpr *ICE) {
9672 QualType From = ICE->getSubExpr()->getType();
9673 QualType To = ICE->getType();
9674 // It's an integer promotion if the destination type is the promoted
9675 // source type.
9676 if (ICE->getCastKind() == CK_IntegralCast &&
9678 S.Context.getPromotedIntegerType(From) == To)
9679 return true;
9680 // Look through vector types, since we do default argument promotion for
9681 // those in OpenCL.
9682 if (const auto *VecTy = From->getAs<ExtVectorType>())
9683 From = VecTy->getElementType();
9684 if (const auto *VecTy = To->getAs<ExtVectorType>())
9685 To = VecTy->getElementType();
9686 // It's a floating promotion if the source type is a lower rank.
9687 return ICE->getCastKind() == CK_FloatingCast &&
9688 S.Context.getFloatingTypeOrder(From, To) < 0;
9689}
9690
9693 DiagnosticsEngine &Diags, SourceLocation Loc) {
9695 if (Diags.isIgnored(
9696 diag::warn_format_conversion_argument_type_mismatch_signedness,
9697 Loc) ||
9698 Diags.isIgnored(
9699 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9700 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9702 }
9703 }
9704 return Match;
9705}
9706
9707bool CheckPrintfHandler::checkFormatExpr(
9708 const analyze_printf::PrintfSpecifier &FS, const char *StartSpecifier,
9709 unsigned SpecifierLen, const Expr *E) {
9710 using namespace analyze_format_string;
9711 using namespace analyze_printf;
9712
9713 // Now type check the data expression that matches the
9714 // format specifier.
9715 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9716 if (!AT.isValid())
9717 return true;
9718
9719 QualType ExprTy = E->getType();
9720 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9721 ExprTy = TET->getUnderlyingExpr()->getType();
9722 }
9723
9724 if (const OverflowBehaviorType *OBT =
9725 dyn_cast<OverflowBehaviorType>(ExprTy.getCanonicalType()))
9726 ExprTy = OBT->getUnderlyingType();
9727
9728 // When using the format attribute in C++, you can receive a function or an
9729 // array that will necessarily decay to a pointer when passed to the final
9730 // format consumer. Apply decay before type comparison.
9731 if (ExprTy->canDecayToPointerType())
9732 ExprTy = S.Context.getDecayedType(ExprTy);
9733
9734 // Diagnose attempts to print a boolean value as a character. Unlike other
9735 // -Wformat diagnostics, this is fine from a type perspective, but it still
9736 // doesn't make sense.
9739 const CharSourceRange &CSR =
9740 getSpecifierRange(StartSpecifier, SpecifierLen);
9741 SmallString<4> FSString;
9742 llvm::raw_svector_ostream os(FSString);
9743 FS.toString(os);
9744 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9745 << FSString,
9746 E->getExprLoc(), false, CSR);
9747 return true;
9748 }
9749
9750 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9751 // dumping raw class data (like is-a pointer), not actual data.
9753 ExprTy->isObjCObjectPointerType()) {
9754 const CharSourceRange &CSR =
9755 getSpecifierRange(StartSpecifier, SpecifierLen);
9756 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
9757 E->getExprLoc(), false, CSR);
9758 return true;
9759 }
9760
9761 if (CheckUnsupportedType(AT, E, StartSpecifier, SpecifierLen))
9762 return true;
9763
9764 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9766 ArgType::MatchKind OrigMatch = Match;
9767
9769 if (Match == ArgType::Match)
9770 return true;
9771
9772 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9773 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9774
9775 // Look through argument promotions for our error message's reported type.
9776 // This includes the integral and floating promotions, but excludes array
9777 // and function pointer decay (seeing that an argument intended to be a
9778 // string has type 'char [6]' is probably more confusing than 'char *') and
9779 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9780 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9781 if (isArithmeticArgumentPromotion(S, ICE)) {
9782 E = ICE->getSubExpr();
9783 ExprTy = E->getType();
9784
9785 // Check if we didn't match because of an implicit cast from a 'char'
9786 // or 'short' to an 'int'. This is done because printf is a varargs
9787 // function.
9788 if (ICE->getType() == S.Context.IntTy ||
9789 ICE->getType() == S.Context.UnsignedIntTy) {
9790 // All further checking is done on the subexpression
9791 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
9792 if (OrigMatch == ArgType::NoMatchSignedness &&
9793 ImplicitMatch != ArgType::NoMatchSignedness)
9794 // If the original match was a signedness match this match on the
9795 // implicit cast type also need to be signedness match otherwise we
9796 // might introduce new unexpected warnings from -Wformat-signedness.
9797 return true;
9798 ImplicitMatch = handleFormatSignedness(
9799 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
9800 if (ImplicitMatch == ArgType::Match)
9801 return true;
9802 }
9803 }
9804 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9805 // Special case for 'a', which has type 'int' in C.
9806 // Note, however, that we do /not/ want to treat multibyte constants like
9807 // 'MooV' as characters! This form is deprecated but still exists. In
9808 // addition, don't treat expressions as of type 'char' if one byte length
9809 // modifier is provided.
9810 if (ExprTy == S.Context.IntTy &&
9812 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
9813 ExprTy = S.Context.CharTy;
9814 // To improve check results, we consider a character literal in C
9815 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9816 // more likely a type confusion situation, so we will suggest to
9817 // use '%hhd' instead by discarding the MatchPromotion.
9818 if (Match == ArgType::MatchPromotion)
9820 }
9821 }
9822 if (Match == ArgType::MatchPromotion) {
9823 // WG14 N2562 only clarified promotions in *printf
9824 // For NSLog in ObjC, just preserve -Wformat behavior
9825 if (!S.getLangOpts().ObjC &&
9826 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9827 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9828 return true;
9830 }
9831 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9832 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9833 Match = ImplicitMatch;
9834 assert(Match != ArgType::MatchPromotion);
9835
9836 // Look through unscoped enums to their underlying type.
9837 bool IsEnum = false;
9838 bool IsScopedEnum = false;
9839 QualType IntendedTy = ExprTy;
9840 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9841 IntendedTy = ED->getIntegerType();
9842 if (!ED->isScoped()) {
9843 ExprTy = IntendedTy;
9844 // This controls whether we're talking about the underlying type or not,
9845 // which we only want to do when it's an unscoped enum.
9846 IsEnum = true;
9847 } else {
9848 IsScopedEnum = true;
9849 }
9850 }
9851
9852 // %C in an Objective-C context prints a unichar, not a wchar_t.
9853 // If the argument is an integer of some kind, believe the %C and suggest
9854 // a cast instead of changing the conversion specifier.
9855 if (isObjCContext() &&
9857 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9858 !ExprTy->isCharType()) {
9859 // 'unichar' is defined as a typedef of unsigned short, but we should
9860 // prefer using the typedef if it is visible.
9861 IntendedTy = S.Context.UnsignedShortTy;
9862
9863 // While we are here, check if the value is an IntegerLiteral that happens
9864 // to be within the valid range.
9865 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9866 const llvm::APInt &V = IL->getValue();
9867 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9868 return true;
9869 }
9870
9871 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9873 if (S.LookupName(Result, S.getCurScope())) {
9874 NamedDecl *ND = Result.getFoundDecl();
9875 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9876 if (TD->getUnderlyingType() == IntendedTy)
9877 IntendedTy =
9879 /*Qualifier=*/std::nullopt, TD);
9880 }
9881 }
9882 }
9883
9884 // Special-case some of Darwin's platform-independence types by suggesting
9885 // casts to primitive types that are known to be large enough.
9886 bool ShouldNotPrintDirectly = false;
9887 StringRef CastTyName;
9888 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9889 QualType CastTy;
9890 std::tie(CastTy, CastTyName) =
9891 shouldNotPrintDirectly(S.Context, IntendedTy, E);
9892 if (!CastTy.isNull()) {
9893 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9894 // (long in ASTContext). Only complain to pedants or when they're the
9895 // underlying type of a scoped enum (which always needs a cast).
9896 if (!IsScopedEnum &&
9897 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9898 (AT.isSizeT() || AT.isPtrdiffT()) &&
9899 AT.matchesType(S.Context, CastTy))
9901 IntendedTy = CastTy;
9902 ShouldNotPrintDirectly = true;
9903 }
9904 }
9905
9906 // We may be able to offer a FixItHint if it is a supported type.
9907 PrintfSpecifier fixedFS = FS;
9908 bool Success =
9909 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9910
9911 if (Success) {
9912 // Get the fix string from the fixed format specifier
9913 SmallString<16> buf;
9914 llvm::raw_svector_ostream os(buf);
9915 fixedFS.toString(os);
9916
9917 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9918
9919 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9920 unsigned Diag;
9921 switch (Match) {
9922 case ArgType::Match:
9925 llvm_unreachable("expected non-matching");
9927 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9928 break;
9930 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9931 break;
9933 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9934 break;
9935 case ArgType::NoMatch:
9936 Diag = diag::warn_format_conversion_argument_type_mismatch;
9937 break;
9938 }
9939
9940 // In this case, the specifier is wrong and should be changed to match
9941 // the argument.
9942 EmitFormatDiagnostic(S.PDiag(Diag)
9944 << IntendedTy << IsEnum << E->getSourceRange(),
9945 E->getBeginLoc(),
9946 /*IsStringLocation*/ false, SpecRange,
9947 FixItHint::CreateReplacement(SpecRange, os.str()));
9948 } else {
9949 // The canonical type for formatting this value is different from the
9950 // actual type of the expression. (This occurs, for example, with Darwin's
9951 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9952 // should be printed as 'long' for 64-bit compatibility.)
9953 // Rather than emitting a normal format/argument mismatch, we want to
9954 // add a cast to the recommended type (and correct the format string
9955 // if necessary). We should also do so for scoped enumerations.
9956 SmallString<16> CastBuf;
9957 llvm::raw_svector_ostream CastFix(CastBuf);
9958 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9959 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9960 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9961
9963 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
9964 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
9965 E->getExprLoc());
9966 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9967 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9968
9969 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9970 // If there's already a cast present, just replace it.
9971 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9972 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9973
9974 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9975 // If the expression has high enough precedence,
9976 // just write the C-style cast.
9977 Hints.push_back(
9978 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9979 } else {
9980 // Otherwise, add parens around the expression as well as the cast.
9981 CastFix << "(";
9982 Hints.push_back(
9983 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9984
9985 // We don't use getLocForEndOfToken because it returns invalid source
9986 // locations for macro expansions (by design).
9990 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9991 }
9992
9993 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9994 // The expression has a type that should not be printed directly.
9995 // We extract the name from the typedef because we don't want to show
9996 // the underlying type in the diagnostic.
9997 StringRef Name;
9998 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9999 Name = TypedefTy->getDecl()->getName();
10000 else
10001 Name = CastTyName;
10002 unsigned Diag = Match == ArgType::NoMatchPedantic
10003 ? diag::warn_format_argument_needs_cast_pedantic
10004 : diag::warn_format_argument_needs_cast;
10005 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
10006 << E->getSourceRange(),
10007 E->getBeginLoc(), /*IsStringLocation=*/false,
10008 SpecRange, Hints);
10009 } else {
10010 // In this case, the expression could be printed using a different
10011 // specifier, but we've decided that the specifier is probably correct
10012 // and we should cast instead. Just use the normal warning message.
10013
10014 unsigned Diag =
10015 IsScopedEnum
10016 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10017 : diag::warn_format_conversion_argument_type_mismatch;
10018
10019 EmitFormatDiagnostic(
10020 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
10021 << IsEnum << E->getSourceRange(),
10022 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
10023 }
10024 }
10025 } else {
10026 const CharSourceRange &CSR =
10027 getSpecifierRange(StartSpecifier, SpecifierLen);
10028 // Since the warning for passing non-POD types to variadic functions
10029 // was deferred until now, we emit a warning for non-POD
10030 // arguments here.
10031 bool EmitTypeMismatch = false;
10032 // Record and complex type arguments cannot be code generated for os_log
10033 // and would crash CodeGen, so they are rejected with a hard error emitted
10034 // after the switch below.
10035 bool EmitOSLogError = false;
10036 switch (S.isValidVarArgType(ExprTy)) {
10037 case VarArgKind::Valid:
10039 unsigned Diag;
10040 switch (Match) {
10041 case ArgType::Match:
10044 llvm_unreachable("expected non-matching");
10046 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
10047 break;
10049 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
10050 break;
10052 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
10053 break;
10054 case ArgType::NoMatch:
10055 EmitOSLogError = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy);
10056 Diag = diag::warn_format_conversion_argument_type_mismatch;
10057 break;
10058 }
10059
10060 if (!EmitOSLogError)
10061 EmitFormatDiagnostic(
10062 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
10063 << IsEnum << CSR << E->getSourceRange(),
10064 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
10065 break;
10066 }
10069 if (CallType == VariadicCallType::DoesNotApply) {
10070 EmitTypeMismatch = true;
10071 } else if (isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)) {
10072 // Emit a hard error rather than the -Wnon-pod-varargs warning, which
10073 // does not stop compilation.
10074 EmitOSLogError = true;
10075 } else {
10076 EmitFormatDiagnostic(
10077 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
10078 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
10079 << AT.getRepresentativeTypeName(S.Context) << CSR
10080 << E->getSourceRange(),
10081 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
10082 checkForCStrMembers(AT, E);
10083 }
10084 break;
10085
10087 if (CallType == VariadicCallType::DoesNotApply)
10088 EmitTypeMismatch = true;
10089 else if (ExprTy->isObjCObjectType())
10090 EmitFormatDiagnostic(
10091 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
10092 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
10093 << AT.getRepresentativeTypeName(S.Context) << CSR
10094 << E->getSourceRange(),
10095 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
10096 else
10097 // FIXME: If this is an initializer list, suggest removing the braces
10098 // or inserting a cast to the target type.
10099 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
10100 << isa<InitListExpr>(E) << ExprTy << CallType
10102 break;
10103 }
10104
10105 if (EmitOSLogError)
10106 EmitFormatDiagnostic(
10107 S.PDiag(diag::err_format_conversion_argument_type_mismatch)
10108 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
10109 << CSR << E->getSourceRange(),
10110 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
10111
10112 if (EmitTypeMismatch) {
10113 // The function is not variadic, so we do not generate warnings about
10114 // being allowed to pass that object as a variadic argument. Instead,
10115 // since there are inherently no printf specifiers for types which cannot
10116 // be passed as variadic arguments, emit a plain old specifier mismatch
10117 // argument.
10118 EmitFormatDiagnostic(
10119 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
10120 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
10121 << E->getSourceRange(),
10122 E->getBeginLoc(), false, CSR);
10123 }
10124
10125 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
10126 "format string specifier index out of range");
10127 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
10128 }
10129
10130 return true;
10131}
10132
10133//===--- CHECK: Scanf format string checking ------------------------------===//
10134
10135namespace {
10136
10137class CheckScanfHandler : public CheckFormatHandler {
10138public:
10139 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
10140 const Expr *origFormatExpr, FormatStringType type,
10141 unsigned firstDataArg, unsigned numDataArgs,
10142 const char *beg, Sema::FormatArgumentPassingKind APK,
10143 ArrayRef<const Expr *> Args, unsigned formatIdx,
10144 bool inFunctionCall, VariadicCallType CallType,
10145 llvm::SmallBitVector &CheckedVarArgs,
10146 UncoveredArgHandler &UncoveredArg)
10147 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
10148 numDataArgs, beg, APK, Args, formatIdx,
10149 inFunctionCall, CallType, CheckedVarArgs,
10150 UncoveredArg) {}
10151
10152 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
10153 const char *startSpecifier,
10154 unsigned specifierLen) override;
10155
10156 bool
10157 HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier &FS,
10158 const char *startSpecifier,
10159 unsigned specifierLen) override;
10160
10161 void HandleIncompleteScanList(const char *start, const char *end) override;
10162};
10163
10164} // namespace
10165
10166void CheckScanfHandler::HandleIncompleteScanList(const char *start,
10167 const char *end) {
10168 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
10169 getLocationOfByte(end), /*IsStringLocation*/ true,
10170 getSpecifierRange(start, end - start));
10171}
10172
10173bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
10174 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
10175 unsigned specifierLen) {
10178
10179 return HandleInvalidConversionSpecifier(
10180 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
10181 specifierLen, CS.getStart(), CS.getLength());
10182}
10183
10184bool CheckScanfHandler::HandleScanfSpecifier(
10185 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
10186 unsigned specifierLen) {
10187 using namespace analyze_scanf;
10188 using namespace analyze_format_string;
10189
10190 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
10191
10192 // Handle case where '%' and '*' don't consume an argument. These shouldn't
10193 // be used to decide if we are using positional arguments consistently.
10194 if (FS.consumesDataArgument()) {
10195 if (atFirstArg) {
10196 atFirstArg = false;
10197 usesPositionalArgs = FS.usesPositionalArg();
10198 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
10199 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
10200 startSpecifier, specifierLen);
10201 return false;
10202 }
10203 }
10204
10205 // Check if the field with is non-zero.
10206 const OptionalAmount &Amt = FS.getFieldWidth();
10208 if (Amt.getConstantAmount() == 0) {
10209 const CharSourceRange &R =
10210 getSpecifierRange(Amt.getStart(), Amt.getConstantLength());
10211 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
10212 getLocationOfByte(Amt.getStart()),
10213 /*IsStringLocation*/ true, R,
10215 }
10216 }
10217
10218 if (!FS.consumesDataArgument()) {
10219 // FIXME: Technically specifying a precision or field width here
10220 // makes no sense. Worth issuing a warning at some point.
10221 return true;
10222 }
10223
10224 // Consume the argument.
10225 unsigned argIndex = FS.getArgIndex();
10226 if (argIndex < NumDataArgs) {
10227 // The check to see if the argIndex is valid will come later.
10228 // We set the bit here because we may exit early from this
10229 // function if we encounter some other error.
10230 CoveredArgs.set(argIndex);
10231 }
10232
10233 // Check the length modifier is valid with the given conversion specifier.
10235 S.getLangOpts()))
10236 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10237 diag::warn_format_nonsensical_length);
10238 else if (!FS.hasStandardLengthModifier())
10239 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
10241 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10242 diag::warn_format_non_standard_conversion_spec);
10243
10245 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
10246
10247 // The remaining checks depend on the data arguments.
10248 if (!HasFormatArguments())
10249 return true;
10250
10251 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10252 return false;
10253
10254 // Check that the argument type matches the format specifier.
10255 const Expr *Ex = getDataArg(argIndex);
10256 if (!Ex)
10257 return true;
10258
10260
10261 if (!AT.isValid()) {
10262 return true;
10263 }
10264
10265 if (CheckUnsupportedType(AT, Ex, startSpecifier, specifierLen))
10266 return true;
10267
10269 AT.matchesType(S.Context, Ex->getType());
10272 return true;
10275
10276 ScanfSpecifier fixedFS = FS;
10277 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
10278 S.getLangOpts(), S.Context);
10279
10280 unsigned Diag =
10281 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10282 : Signedness
10283 ? diag::warn_format_conversion_argument_type_mismatch_signedness
10284 : diag::warn_format_conversion_argument_type_mismatch;
10285
10286 if (Success) {
10287 // Get the fix string from the fixed format specifier.
10288 SmallString<128> buf;
10289 llvm::raw_svector_ostream os(buf);
10290 fixedFS.toString(os);
10291
10292 EmitFormatDiagnostic(
10294 << Ex->getType() << false << Ex->getSourceRange(),
10295 Ex->getBeginLoc(),
10296 /*IsStringLocation*/ false,
10297 getSpecifierRange(startSpecifier, specifierLen),
10299 getSpecifierRange(startSpecifier, specifierLen), os.str()));
10300 } else {
10301 EmitFormatDiagnostic(S.PDiag(Diag)
10303 << Ex->getType() << false << Ex->getSourceRange(),
10304 Ex->getBeginLoc(),
10305 /*IsStringLocation*/ false,
10306 getSpecifierRange(startSpecifier, specifierLen));
10307 }
10308
10309 return true;
10310}
10311
10312static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
10314 const StringLiteral *Fmt,
10316 const Expr *FmtExpr, bool InFunctionCall) {
10317 bool HadError = false;
10318 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
10319 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
10320 while (FmtIter < FmtEnd && RefIter < RefEnd) {
10321 // In positional-style format strings, the same specifier can appear
10322 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
10323 // are sorted by getPosition(), and we process each range of equal
10324 // getPosition() values as one group.
10325 // RefArgs are taken from a string literal that was given to
10326 // attribute(format_matches), and if we got this far, we have already
10327 // verified that if it has positional specifiers that appear in multiple
10328 // locations, then they are all mutually compatible. What's left for us to
10329 // do is verify that all specifiers with the same position in FmtArgs are
10330 // compatible with the RefArgs specifiers. We check each specifier from
10331 // FmtArgs against the first member of the RefArgs group.
10332 for (; FmtIter < FmtEnd; ++FmtIter) {
10333 // Clang does not diagnose missing format specifiers in positional-style
10334 // strings (TODO: which it probably should do, as it is UB to skip over a
10335 // format argument). Skip specifiers if needed.
10336 if (FmtIter->getPosition() < RefIter->getPosition())
10337 continue;
10338
10339 // Delimits a new getPosition() value.
10340 if (FmtIter->getPosition() > RefIter->getPosition())
10341 break;
10342
10343 HadError |=
10344 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
10345 }
10346
10347 // Jump RefIter to the start of the next group.
10348 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
10349 return Arg.getPosition() != RefIter->getPosition();
10350 });
10351 }
10352
10353 if (FmtIter < FmtEnd) {
10354 CheckFormatHandler::EmitFormatDiagnostic(
10355 S, InFunctionCall, FmtExpr,
10356 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
10357 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
10358 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
10359 } else if (RefIter < RefEnd) {
10360 CheckFormatHandler::EmitFormatDiagnostic(
10361 S, InFunctionCall, FmtExpr,
10362 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
10363 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
10364 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
10365 << 1 << RefIter->getSourceRange();
10366 }
10367 return !HadError;
10368}
10369
10371 Sema &S, const FormatStringLiteral *FExpr,
10372 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
10374 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
10375 bool inFunctionCall, VariadicCallType CallType,
10376 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
10377 bool IgnoreStringsWithoutSpecifiers) {
10378 // CHECK: is the format string a wide literal?
10379 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10380 CheckFormatHandler::EmitFormatDiagnostic(
10381 S, inFunctionCall, Args[format_idx],
10382 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
10383 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10384 return;
10385 }
10386
10387 // Str - The format string. NOTE: this is NOT null-terminated!
10388 StringRef StrRef = FExpr->getString();
10389 const char *Str = StrRef.data();
10390 // Account for cases where the string literal is truncated in a declaration.
10391 const ConstantArrayType *T =
10392 S.Context.getAsConstantArrayType(FExpr->getType());
10393 assert(T && "String literal not of constant array type!");
10394 size_t TypeSize = T->getZExtSize();
10395 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10396 const unsigned numDataArgs = Args.size() - firstDataArg;
10397
10398 if (IgnoreStringsWithoutSpecifiers &&
10400 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10401 return;
10402
10403 // Emit a warning if the string literal is truncated and does not contain an
10404 // embedded null character.
10405 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
10406 CheckFormatHandler::EmitFormatDiagnostic(
10407 S, inFunctionCall, Args[format_idx],
10408 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
10409 FExpr->getBeginLoc(),
10410 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
10411 return;
10412 }
10413
10414 // CHECK: empty format string?
10415 if (StrLen == 0 && numDataArgs > 0) {
10416 CheckFormatHandler::EmitFormatDiagnostic(
10417 S, inFunctionCall, Args[format_idx],
10418 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10419 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10420 return;
10421 }
10422
10427 bool IsObjC =
10429 if (ReferenceFormatString == nullptr) {
10430 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10431 numDataArgs, IsObjC, Str, APK, Args, format_idx,
10432 inFunctionCall, CallType, CheckedVarArgs,
10433 UncoveredArg);
10434
10436 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
10439 H.DoneProcessing();
10440 } else {
10442 Type, ReferenceFormatString, FExpr->getFormatString(),
10443 inFunctionCall ? nullptr : Args[format_idx]);
10444 }
10445 } else if (Type == FormatStringType::Scanf) {
10446 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10447 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
10448 CallType, CheckedVarArgs, UncoveredArg);
10449
10451 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10452 H.DoneProcessing();
10453 } // TODO: handle other formats
10454}
10455
10457 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
10458 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
10463 return true;
10464
10465 bool IsObjC =
10468 FormatStringLiteral RefLit = AuthoritativeFormatString;
10469 FormatStringLiteral TestLit = TestedFormatString;
10470 const Expr *Arg;
10471 bool DiagAtStringLiteral;
10472 if (FunctionCallArg) {
10473 Arg = FunctionCallArg;
10474 DiagAtStringLiteral = false;
10475 } else {
10476 Arg = TestedFormatString;
10477 DiagAtStringLiteral = true;
10478 }
10479 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
10480 AuthoritativeFormatString, Type,
10481 IsObjC, true, RefArgs) &&
10482 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
10483 DiagAtStringLiteral, FmtArgs)) {
10484 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
10485 TestedFormatString, FmtArgs, Arg,
10486 DiagAtStringLiteral);
10487 }
10488 return false;
10489}
10490
10492 const StringLiteral *Str) {
10497 return true;
10498
10499 FormatStringLiteral RefLit = Str;
10501 bool IsObjC =
10503 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
10504 true, Args))
10505 return false;
10506
10507 // Group arguments by getPosition() value, and check that each member of the
10508 // group is compatible with the first member. This verifies that when
10509 // positional arguments are used multiple times (such as %2$i %2$d), all uses
10510 // are mutually compatible. As an optimization, don't test the first member
10511 // against itself.
10512 bool HadError = false;
10513 auto Iter = Args.begin();
10514 auto End = Args.end();
10515 while (Iter != End) {
10516 const auto &FirstInGroup = *Iter;
10517 for (++Iter;
10518 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
10519 ++Iter) {
10520 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
10521 }
10522 }
10523 return !HadError;
10524}
10525
10527 // Str - The format string. NOTE: this is NOT null-terminated!
10528 StringRef StrRef = FExpr->getString();
10529 const char *Str = StrRef.data();
10530 // Account for cases where the string literal is truncated in a declaration.
10531 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10532 assert(T && "String literal not of constant array type!");
10533 size_t TypeSize = T->getZExtSize();
10534 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10536 Str, Str + StrLen, getLangOpts(), Context.getTargetInfo());
10537}
10538
10539//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10540
10541// Returns the related absolute value function that is larger, of 0 if one
10542// does not exist.
10543static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10544 switch (AbsFunction) {
10545 default:
10546 return 0;
10547
10548 case Builtin::BI__builtin_abs:
10549 return Builtin::BI__builtin_labs;
10550 case Builtin::BI__builtin_labs:
10551 return Builtin::BI__builtin_llabs;
10552 case Builtin::BI__builtin_llabs:
10553 return 0;
10554
10555 case Builtin::BI__builtin_fabsf:
10556 return Builtin::BI__builtin_fabs;
10557 case Builtin::BI__builtin_fabs:
10558 return Builtin::BI__builtin_fabsl;
10559 case Builtin::BI__builtin_fabsl:
10560 return 0;
10561
10562 case Builtin::BI__builtin_cabsf:
10563 return Builtin::BI__builtin_cabs;
10564 case Builtin::BI__builtin_cabs:
10565 return Builtin::BI__builtin_cabsl;
10566 case Builtin::BI__builtin_cabsl:
10567 return 0;
10568
10569 case Builtin::BIabs:
10570 return Builtin::BIlabs;
10571 case Builtin::BIlabs:
10572 return Builtin::BIllabs;
10573 case Builtin::BIllabs:
10574 return 0;
10575
10576 case Builtin::BIfabsf:
10577 return Builtin::BIfabs;
10578 case Builtin::BIfabs:
10579 return Builtin::BIfabsl;
10580 case Builtin::BIfabsl:
10581 return 0;
10582
10583 case Builtin::BIcabsf:
10584 return Builtin::BIcabs;
10585 case Builtin::BIcabs:
10586 return Builtin::BIcabsl;
10587 case Builtin::BIcabsl:
10588 return 0;
10589 }
10590}
10591
10592// Returns the argument type of the absolute value function.
10594 unsigned AbsType) {
10595 if (AbsType == 0)
10596 return QualType();
10597
10599 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10601 return QualType();
10602
10604 if (!FT)
10605 return QualType();
10606
10607 if (FT->getNumParams() != 1)
10608 return QualType();
10609
10610 return FT->getParamType(0);
10611}
10612
10613// Returns the best absolute value function, or zero, based on type and
10614// current absolute value function.
10615static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10616 unsigned AbsFunctionKind) {
10617 unsigned BestKind = 0;
10618 uint64_t ArgSize = Context.getTypeSize(ArgType);
10619 for (unsigned Kind = AbsFunctionKind; Kind != 0;
10620 Kind = getLargerAbsoluteValueFunction(Kind)) {
10621 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10622 if (Context.getTypeSize(ParamType) >= ArgSize) {
10623 if (BestKind == 0)
10624 BestKind = Kind;
10625 else if (Context.hasSameType(ParamType, ArgType)) {
10626 BestKind = Kind;
10627 break;
10628 }
10629 }
10630 }
10631 return BestKind;
10632}
10633
10639
10641 if (T->isIntegralOrEnumerationType())
10642 return AVK_Integer;
10643 if (T->isRealFloatingType())
10644 return AVK_Floating;
10645 if (T->isAnyComplexType())
10646 return AVK_Complex;
10647
10648 llvm_unreachable("Type not integer, floating, or complex");
10649}
10650
10651// Changes the absolute value function to a different type. Preserves whether
10652// the function is a builtin.
10653static unsigned changeAbsFunction(unsigned AbsKind,
10654 AbsoluteValueKind ValueKind) {
10655 switch (ValueKind) {
10656 case AVK_Integer:
10657 switch (AbsKind) {
10658 default:
10659 return 0;
10660 case Builtin::BI__builtin_fabsf:
10661 case Builtin::BI__builtin_fabs:
10662 case Builtin::BI__builtin_fabsl:
10663 case Builtin::BI__builtin_cabsf:
10664 case Builtin::BI__builtin_cabs:
10665 case Builtin::BI__builtin_cabsl:
10666 return Builtin::BI__builtin_abs;
10667 case Builtin::BIfabsf:
10668 case Builtin::BIfabs:
10669 case Builtin::BIfabsl:
10670 case Builtin::BIcabsf:
10671 case Builtin::BIcabs:
10672 case Builtin::BIcabsl:
10673 return Builtin::BIabs;
10674 }
10675 case AVK_Floating:
10676 switch (AbsKind) {
10677 default:
10678 return 0;
10679 case Builtin::BI__builtin_abs:
10680 case Builtin::BI__builtin_labs:
10681 case Builtin::BI__builtin_llabs:
10682 case Builtin::BI__builtin_cabsf:
10683 case Builtin::BI__builtin_cabs:
10684 case Builtin::BI__builtin_cabsl:
10685 return Builtin::BI__builtin_fabsf;
10686 case Builtin::BIabs:
10687 case Builtin::BIlabs:
10688 case Builtin::BIllabs:
10689 case Builtin::BIcabsf:
10690 case Builtin::BIcabs:
10691 case Builtin::BIcabsl:
10692 return Builtin::BIfabsf;
10693 }
10694 case AVK_Complex:
10695 switch (AbsKind) {
10696 default:
10697 return 0;
10698 case Builtin::BI__builtin_abs:
10699 case Builtin::BI__builtin_labs:
10700 case Builtin::BI__builtin_llabs:
10701 case Builtin::BI__builtin_fabsf:
10702 case Builtin::BI__builtin_fabs:
10703 case Builtin::BI__builtin_fabsl:
10704 return Builtin::BI__builtin_cabsf;
10705 case Builtin::BIabs:
10706 case Builtin::BIlabs:
10707 case Builtin::BIllabs:
10708 case Builtin::BIfabsf:
10709 case Builtin::BIfabs:
10710 case Builtin::BIfabsl:
10711 return Builtin::BIcabsf;
10712 }
10713 }
10714 llvm_unreachable("Unable to convert function");
10715}
10716
10717static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10718 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10719 if (!FnInfo)
10720 return 0;
10721
10722 switch (FDecl->getBuiltinID()) {
10723 default:
10724 return 0;
10725 case Builtin::BI__builtin_abs:
10726 case Builtin::BI__builtin_fabs:
10727 case Builtin::BI__builtin_fabsf:
10728 case Builtin::BI__builtin_fabsl:
10729 case Builtin::BI__builtin_labs:
10730 case Builtin::BI__builtin_llabs:
10731 case Builtin::BI__builtin_cabs:
10732 case Builtin::BI__builtin_cabsf:
10733 case Builtin::BI__builtin_cabsl:
10734 case Builtin::BIabs:
10735 case Builtin::BIlabs:
10736 case Builtin::BIllabs:
10737 case Builtin::BIfabs:
10738 case Builtin::BIfabsf:
10739 case Builtin::BIfabsl:
10740 case Builtin::BIcabs:
10741 case Builtin::BIcabsf:
10742 case Builtin::BIcabsl:
10743 return FDecl->getBuiltinID();
10744 }
10745 llvm_unreachable("Unknown Builtin type");
10746}
10747
10748// If the replacement is valid, emit a note with replacement function.
10749// Additionally, suggest including the proper header if not already included.
10751 unsigned AbsKind, QualType ArgType) {
10752 bool EmitHeaderHint = true;
10753 const char *HeaderName = nullptr;
10754 std::string FunctionName;
10755 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10756 FunctionName = "std::abs";
10757 if (ArgType->isIntegralOrEnumerationType()) {
10758 HeaderName = "cstdlib";
10759 } else if (ArgType->isRealFloatingType()) {
10760 HeaderName = "cmath";
10761 } else {
10762 llvm_unreachable("Invalid Type");
10763 }
10764
10765 // Lookup all std::abs
10766 if (NamespaceDecl *Std = S.getStdNamespace()) {
10767 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10768 R.suppressDiagnostics();
10769 S.LookupQualifiedName(R, Std);
10770
10771 for (const auto *I : R) {
10772 const FunctionDecl *FDecl = nullptr;
10773 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10774 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10775 } else {
10776 FDecl = dyn_cast<FunctionDecl>(I);
10777 }
10778 if (!FDecl)
10779 continue;
10780
10781 // Found std::abs(), check that they are the right ones.
10782 if (FDecl->getNumParams() != 1)
10783 continue;
10784
10785 // Check that the parameter type can handle the argument.
10786 QualType ParamType = FDecl->getParamDecl(0)->getType();
10787 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10788 S.Context.getTypeSize(ArgType) <=
10789 S.Context.getTypeSize(ParamType)) {
10790 // Found a function, don't need the header hint.
10791 EmitHeaderHint = false;
10792 break;
10793 }
10794 }
10795 }
10796 } else {
10797 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10798 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10799
10800 if (HeaderName) {
10801 DeclarationName DN(&S.Context.Idents.get(FunctionName));
10802 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10803 R.suppressDiagnostics();
10804 S.LookupName(R, S.getCurScope());
10805
10806 if (R.isSingleResult()) {
10807 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10808 if (FD && FD->getBuiltinID() == AbsKind) {
10809 EmitHeaderHint = false;
10810 } else {
10811 return;
10812 }
10813 } else if (!R.empty()) {
10814 return;
10815 }
10816 }
10817 }
10818
10819 S.Diag(Loc, diag::note_replace_abs_function)
10820 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10821
10822 if (!HeaderName)
10823 return;
10824
10825 if (!EmitHeaderHint)
10826 return;
10827
10828 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10829 << FunctionName;
10830}
10831
10832template <std::size_t StrLen>
10833static bool IsStdFunction(const FunctionDecl *FDecl,
10834 const char (&Str)[StrLen]) {
10835 if (!FDecl)
10836 return false;
10837 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10838 return false;
10839 if (!FDecl->isInStdNamespace())
10840 return false;
10841
10842 return true;
10843}
10844
10845enum class MathCheck { NaN, Inf };
10846static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10847 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10848 return llvm::is_contained(names, calleeName);
10849 };
10850
10851 switch (Check) {
10852 case MathCheck::NaN:
10853 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10854 "__builtin_nanf16", "__builtin_nanf128"});
10855 case MathCheck::Inf:
10856 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10857 "__builtin_inff16", "__builtin_inff128"});
10858 }
10859 llvm_unreachable("unknown MathCheck");
10860}
10861
10862static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10863 if (FDecl->getName() != "infinity")
10864 return false;
10865
10866 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
10867 const CXXRecordDecl *RDecl = MDecl->getParent();
10868 if (RDecl->getName() != "numeric_limits")
10869 return false;
10870
10871 if (const NamespaceDecl *NSDecl =
10872 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
10873 return NSDecl->isStdNamespace();
10874 }
10875
10876 return false;
10877}
10878
10879void Sema::CheckInfNaNFunction(const CallExpr *Call,
10880 const FunctionDecl *FDecl) {
10881 if (!FDecl->getIdentifier())
10882 return;
10883
10884 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
10885 if (FPO.getNoHonorNaNs() &&
10886 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
10888 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10889 << 1 << 0 << Call->getSourceRange();
10890 return;
10891 }
10892
10893 if (FPO.getNoHonorInfs() &&
10894 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
10895 IsInfinityFunction(FDecl) ||
10897 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10898 << 0 << 0 << Call->getSourceRange();
10899 }
10900}
10901
10902void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10903 const FunctionDecl *FDecl) {
10904 if (Call->getNumArgs() != 1)
10905 return;
10906
10907 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10908 bool IsStdAbs = IsStdFunction(FDecl, "abs");
10909 if (AbsKind == 0 && !IsStdAbs)
10910 return;
10911
10912 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10913 QualType ParamType = Call->getArg(0)->getType();
10914
10915 // Unsigned types cannot be negative. Suggest removing the absolute value
10916 // function call.
10917 if (ArgType->isUnsignedIntegerType()) {
10918 std::string FunctionName =
10919 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10920 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10921 Diag(Call->getExprLoc(), diag::note_remove_abs)
10922 << FunctionName
10923 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10924 return;
10925 }
10926
10927 // Taking the absolute value of a pointer is very suspicious, they probably
10928 // wanted to index into an array, dereference a pointer, call a function, etc.
10929 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10930 unsigned DiagType = 0;
10931 if (ArgType->isFunctionType())
10932 DiagType = 1;
10933 else if (ArgType->isArrayType())
10934 DiagType = 2;
10935
10936 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10937 return;
10938 }
10939
10940 // std::abs has overloads which prevent most of the absolute value problems
10941 // from occurring.
10942 if (IsStdAbs)
10943 return;
10944
10945 // Prevent reaching unreachable code in getAbsoluteValueKind for unsupported
10946 // types.
10947 if (!ArgType->isIntegralOrEnumerationType() &&
10948 !ArgType->isRealFloatingType() && !ArgType->isAnyComplexType())
10949 return;
10950
10951 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10952 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10953
10954 // The argument and parameter are the same kind. Check if they are the right
10955 // size.
10956 if (ArgValueKind == ParamValueKind) {
10957 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10958 return;
10959
10960 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10961 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10962 << FDecl << ArgType << ParamType;
10963
10964 if (NewAbsKind == 0)
10965 return;
10966
10967 emitReplacement(*this, Call->getExprLoc(),
10968 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10969 return;
10970 }
10971
10972 // ArgValueKind != ParamValueKind
10973 // The wrong type of absolute value function was used. Attempt to find the
10974 // proper one.
10975 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10976 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10977 if (NewAbsKind == 0)
10978 return;
10979
10980 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10981 << FDecl << ParamValueKind << ArgValueKind;
10982
10983 emitReplacement(*this, Call->getExprLoc(),
10984 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10985}
10986
10987//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10988void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10989 const FunctionDecl *FDecl) {
10990 if (!Call || !FDecl) return;
10991
10992 // Ignore template specializations and macros.
10993 if (inTemplateInstantiation()) return;
10994 if (Call->getExprLoc().isMacroID()) return;
10995
10996 // Only care about the one template argument, two function parameter std::max
10997 if (Call->getNumArgs() != 2) return;
10998 if (!IsStdFunction(FDecl, "max")) return;
10999 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
11000 if (!ArgList) return;
11001 if (ArgList->size() != 1) return;
11002
11003 // Check that template type argument is unsigned integer.
11004 const auto& TA = ArgList->get(0);
11005 if (TA.getKind() != TemplateArgument::Type) return;
11006 QualType ArgType = TA.getAsType();
11007 if (!ArgType->isUnsignedIntegerType()) return;
11008
11009 // See if either argument is a literal zero.
11010 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
11011 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
11012 if (!MTE) return false;
11013 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
11014 if (!Num) return false;
11015 if (Num->getValue() != 0) return false;
11016 return true;
11017 };
11018
11019 const Expr *FirstArg = Call->getArg(0);
11020 const Expr *SecondArg = Call->getArg(1);
11021 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
11022 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
11023
11024 // Only warn when exactly one argument is zero.
11025 if (IsFirstArgZero == IsSecondArgZero) return;
11026
11027 SourceRange FirstRange = FirstArg->getSourceRange();
11028 SourceRange SecondRange = SecondArg->getSourceRange();
11029
11030 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
11031
11032 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
11033 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
11034
11035 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
11036 SourceRange RemovalRange;
11037 if (IsFirstArgZero) {
11038 RemovalRange = SourceRange(FirstRange.getBegin(),
11039 SecondRange.getBegin().getLocWithOffset(-1));
11040 } else {
11041 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
11042 SecondRange.getEnd());
11043 }
11044
11045 Diag(Call->getExprLoc(), diag::note_remove_max_call)
11046 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
11047 << FixItHint::CreateRemoval(RemovalRange);
11048}
11049
11050//===--- CHECK: Standard memory functions ---------------------------------===//
11051
11052/// Takes the expression passed to the size_t parameter of functions
11053/// such as memcmp, strncat, etc and warns if it's a comparison.
11054///
11055/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
11057 const IdentifierInfo *FnName,
11058 SourceLocation FnLoc,
11059 SourceLocation RParenLoc) {
11060 const auto *Size = dyn_cast<BinaryOperator>(E);
11061 if (!Size)
11062 return false;
11063
11064 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
11065 if (!Size->isComparisonOp() && !Size->isLogicalOp())
11066 return false;
11067
11068 SourceRange SizeRange = Size->getSourceRange();
11069 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
11070 << SizeRange << FnName;
11071 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
11072 << FnName
11074 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
11075 << FixItHint::CreateRemoval(RParenLoc);
11076 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
11077 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
11079 ")");
11080
11081 return true;
11082}
11083
11084/// Determine whether the given type is or contains a dynamic class type
11085/// (e.g., whether it has a vtable).
11087 bool &IsContained) {
11088 // Look through array types while ignoring qualifiers.
11089 const Type *Ty = T->getBaseElementTypeUnsafe();
11090 IsContained = false;
11091
11092 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
11093 RD = RD ? RD->getDefinition() : nullptr;
11094 if (!RD || RD->isInvalidDecl())
11095 return nullptr;
11096
11097 if (RD->isDynamicClass())
11098 return RD;
11099
11100 // Check all the fields. If any bases were dynamic, the class is dynamic.
11101 // It's impossible for a class to transitively contain itself by value, so
11102 // infinite recursion is impossible.
11103 for (auto *FD : RD->fields()) {
11104 bool SubContained;
11105 if (const CXXRecordDecl *ContainedRD =
11106 getContainedDynamicClass(FD->getType(), SubContained)) {
11107 IsContained = true;
11108 return ContainedRD;
11109 }
11110 }
11111
11112 return nullptr;
11113}
11114
11116 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
11117 if (Unary->getKind() == UETT_SizeOf)
11118 return Unary;
11119 return nullptr;
11120}
11121
11122/// If E is a sizeof expression, returns its argument expression,
11123/// otherwise returns NULL.
11124static const Expr *getSizeOfExprArg(const Expr *E) {
11126 if (!SizeOf->isArgumentType())
11127 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
11128 return nullptr;
11129}
11130
11131/// If E is a sizeof expression, returns its argument type.
11134 return SizeOf->getTypeOfArgument();
11135 return QualType();
11136}
11137
11138namespace {
11139
11140struct SearchNonTrivialToInitializeField
11141 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
11142 using Super =
11143 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
11144
11145 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
11146
11147 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
11148 SourceLocation SL) {
11149 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
11150 asDerived().visitArray(PDIK, AT, SL);
11151 return;
11152 }
11153
11154 Super::visitWithKind(PDIK, FT, SL);
11155 }
11156
11157 void visitARCStrong(QualType FT, SourceLocation SL) {
11158 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
11159 }
11160 void visitARCWeak(QualType FT, SourceLocation SL) {
11161 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
11162 }
11163 void visitStruct(QualType FT, SourceLocation SL) {
11164 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
11165 visit(FD->getType(), FD->getLocation());
11166 }
11167 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
11168 const ArrayType *AT, SourceLocation SL) {
11169 visit(getContext().getBaseElementType(AT), SL);
11170 }
11171 void visitTrivial(QualType FT, SourceLocation SL) {}
11172
11173 static void diag(QualType RT, const Expr *E, Sema &S) {
11174 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
11175 }
11176
11177 ASTContext &getContext() { return S.getASTContext(); }
11178
11179 const Expr *E;
11180 Sema &S;
11181};
11182
11183struct SearchNonTrivialToCopyField
11184 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
11185 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
11186
11187 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
11188
11189 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
11190 SourceLocation SL) {
11191 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
11192 asDerived().visitArray(PCK, AT, SL);
11193 return;
11194 }
11195
11196 Super::visitWithKind(PCK, FT, SL);
11197 }
11198
11199 void visitARCStrong(QualType FT, SourceLocation SL) {
11200 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
11201 }
11202 void visitARCWeak(QualType FT, SourceLocation SL) {
11203 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
11204 }
11205 void visitPtrAuth(QualType FT, SourceLocation SL) {
11206 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
11207 }
11208 void visitStruct(QualType FT, SourceLocation SL) {
11209 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
11210 visit(FD->getType(), FD->getLocation());
11211 }
11212 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
11213 SourceLocation SL) {
11214 visit(getContext().getBaseElementType(AT), SL);
11215 }
11216 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
11217 SourceLocation SL) {}
11218 void visitTrivial(QualType FT, SourceLocation SL) {}
11219 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
11220
11221 static void diag(QualType RT, const Expr *E, Sema &S) {
11222 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
11223 }
11224
11225 ASTContext &getContext() { return S.getASTContext(); }
11226
11227 const Expr *E;
11228 Sema &S;
11229};
11230
11231}
11232
11233/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
11234static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
11235 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
11236
11237 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
11238 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
11239 return false;
11240
11241 return doesExprLikelyComputeSize(BO->getLHS()) ||
11242 doesExprLikelyComputeSize(BO->getRHS());
11243 }
11244
11245 return getAsSizeOfExpr(SizeofExpr) != nullptr;
11246}
11247
11248/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
11249///
11250/// \code
11251/// #define MACRO 0
11252/// foo(MACRO);
11253/// foo(0);
11254/// \endcode
11255///
11256/// This should return true for the first call to foo, but not for the second
11257/// (regardless of whether foo is a macro or function).
11259 SourceLocation CallLoc,
11260 SourceLocation ArgLoc) {
11261 if (!CallLoc.isMacroID())
11262 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
11263
11264 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
11266}
11267
11268/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
11269/// last two arguments transposed.
11270static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
11271 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
11272 return;
11273
11274 const Expr *SizeArg =
11275 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
11276
11277 auto isLiteralZero = [](const Expr *E) {
11278 return (isa<IntegerLiteral>(E) &&
11279 cast<IntegerLiteral>(E)->getValue() == 0) ||
11281 cast<CharacterLiteral>(E)->getValue() == 0);
11282 };
11283
11284 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
11285 SourceLocation CallLoc = Call->getRParenLoc();
11287 if (isLiteralZero(SizeArg) &&
11288 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
11289
11290 SourceLocation DiagLoc = SizeArg->getExprLoc();
11291
11292 // Some platforms #define bzero to __builtin_memset. See if this is the
11293 // case, and if so, emit a better diagnostic.
11294 if (BId == Builtin::BIbzero ||
11296 CallLoc, SM, S.getLangOpts()) == "bzero")) {
11297 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
11298 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
11299 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
11300 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
11301 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
11302 }
11303 return;
11304 }
11305
11306 // If the second argument to a memset is a sizeof expression and the third
11307 // isn't, this is also likely an error. This should catch
11308 // 'memset(buf, sizeof(buf), 0xff)'.
11309 if (BId == Builtin::BImemset &&
11310 doesExprLikelyComputeSize(Call->getArg(1)) &&
11311 !doesExprLikelyComputeSize(Call->getArg(2))) {
11312 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
11313 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
11314 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
11315 return;
11316 }
11317}
11318
11319void Sema::CheckMemaccessArguments(const CallExpr *Call,
11320 unsigned BId,
11321 IdentifierInfo *FnName) {
11322 assert(BId != 0);
11323
11324 // It is possible to have a non-standard definition of memset. Validate
11325 // we have enough arguments, and if not, abort further checking.
11326 unsigned ExpectedNumArgs =
11327 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
11328 if (Call->getNumArgs() < ExpectedNumArgs)
11329 return;
11330
11331 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
11332 BId == Builtin::BIstrndup ? 1 : 2);
11333 unsigned LenArg =
11334 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
11335 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
11336
11337 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
11338 Call->getBeginLoc(), Call->getRParenLoc()))
11339 return;
11340
11341 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
11342 CheckMemaccessSize(*this, BId, Call);
11343
11344 // We have special checking when the length is a sizeof expression.
11345 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
11346
11347 // Although widely used, 'bzero' is not a standard function. Be more strict
11348 // with the argument types before allowing diagnostics and only allow the
11349 // form bzero(ptr, sizeof(...)).
11350 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
11351 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
11352 return;
11353
11354 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
11355 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
11356 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
11357
11358 QualType DestTy = Dest->getType();
11359 QualType PointeeTy;
11360 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
11361 PointeeTy = DestPtrTy->getPointeeType();
11362
11363 // Never warn about void type pointers. This can be used to suppress
11364 // false positives.
11365 if (PointeeTy->isVoidType())
11366 continue;
11367
11368 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
11369 // actually comparing the expressions for equality. Because computing the
11370 // expression IDs can be expensive, we only do this if the diagnostic is
11371 // enabled.
11372 if (CheckSizeofMemaccessArgument(LenExpr, Dest, FnName))
11373 break;
11374
11375 // Also check for cases where the sizeof argument is the exact same
11376 // type as the memory argument, and where it points to a user-defined
11377 // record type.
11378 if (SizeOfArgTy != QualType()) {
11379 if (PointeeTy->isRecordType() &&
11380 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
11381 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
11382 PDiag(diag::warn_sizeof_pointer_type_memaccess)
11383 << FnName << SizeOfArgTy << ArgIdx
11384 << PointeeTy << Dest->getSourceRange()
11385 << LenExpr->getSourceRange());
11386 break;
11387 }
11388 }
11389 } else if (DestTy->isArrayType()) {
11390 PointeeTy = DestTy;
11391 }
11392
11393 if (PointeeTy == QualType())
11394 continue;
11395
11396 // Always complain about dynamic classes.
11397 bool IsContained;
11398 if (const CXXRecordDecl *ContainedRD =
11399 getContainedDynamicClass(PointeeTy, IsContained)) {
11400
11401 unsigned OperationType = 0;
11402 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11403 // "overwritten" if we're warning about the destination for any call
11404 // but memcmp; otherwise a verb appropriate to the call.
11405 if (ArgIdx != 0 || IsCmp) {
11406 if (BId == Builtin::BImemcpy)
11407 OperationType = 1;
11408 else if(BId == Builtin::BImemmove)
11409 OperationType = 2;
11410 else if (IsCmp)
11411 OperationType = 3;
11412 }
11413
11414 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11415 PDiag(diag::warn_dyn_class_memaccess)
11416 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11417 << IsContained << ContainedRD << OperationType
11418 << Call->getCallee()->getSourceRange());
11419 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11420 BId != Builtin::BImemset)
11422 Dest->getExprLoc(), Dest,
11423 PDiag(diag::warn_arc_object_memaccess)
11424 << ArgIdx << FnName << PointeeTy
11425 << Call->getCallee()->getSourceRange());
11426 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
11427
11428 // FIXME: Do not consider incomplete types even though they may be
11429 // completed later. GCC does not diagnose such code, but we may want to
11430 // consider diagnosing it in the future, perhaps under a different, but
11431 // related, diagnostic group.
11432 bool NonTriviallyCopyableCXXRecord =
11433 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
11434 !PointeeTy.isTriviallyCopyableType(Context);
11435
11436 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11438 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11439 PDiag(diag::warn_cstruct_memaccess)
11440 << ArgIdx << FnName << PointeeTy << 0);
11441 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
11442 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11443 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11444 // FIXME: Limiting this warning to dest argument until we decide
11445 // whether it's valid for source argument too.
11446 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11447 PDiag(diag::warn_cxxstruct_memaccess)
11448 << FnName << PointeeTy);
11449 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11451 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11452 PDiag(diag::warn_cstruct_memaccess)
11453 << ArgIdx << FnName << PointeeTy << 1);
11454 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
11455 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11456 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11457 // FIXME: Limiting this warning to dest argument until we decide
11458 // whether it's valid for source argument too.
11459 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11460 PDiag(diag::warn_cxxstruct_memaccess)
11461 << FnName << PointeeTy);
11462 } else {
11463 continue;
11464 }
11465 } else
11466 continue;
11467
11469 Dest->getExprLoc(), Dest,
11470 PDiag(diag::note_bad_memaccess_silence)
11471 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
11472 break;
11473 }
11474}
11475
11476bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
11477 IdentifierInfo *FnName) {
11478 llvm::FoldingSetNodeID SizeOfArgID;
11479 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
11480 if (!SizeOfArg)
11481 return false;
11482 // Computing this warning is expensive, so we only do so if the warning is
11483 // enabled.
11484 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
11485 SizeOfArg->getExprLoc()))
11486 return false;
11487 QualType DestTy = Dest->getType();
11488 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
11489 if (!DestPtrTy)
11490 return false;
11491
11492 QualType PointeeTy = DestPtrTy->getPointeeType();
11493
11494 if (SizeOfArgID == llvm::FoldingSetNodeID())
11495 SizeOfArg->Profile(SizeOfArgID, Context, true);
11496
11497 llvm::FoldingSetNodeID DestID;
11498 Dest->Profile(DestID, Context, true);
11499 if (DestID == SizeOfArgID) {
11500 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11501 // over sizeof(src) as well.
11502 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11503 StringRef ReadableName = FnName->getName();
11504
11505 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest);
11506 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
11507 ActionIdx = 1; // If its an address-of operator, just remove it.
11508 if (!PointeeTy->isIncompleteType() &&
11509 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
11510 ActionIdx = 2; // If the pointee's size is sizeof(char),
11511 // suggest an explicit length.
11512
11513 // If the function is defined as a builtin macro, do not show macro
11514 // expansion.
11515 SourceLocation SL = SizeOfArg->getExprLoc();
11516 SourceRange DSR = Dest->getSourceRange();
11517 SourceRange SSR = SizeOfArg->getSourceRange();
11518 SourceManager &SM = getSourceManager();
11519
11520 if (SM.isMacroArgExpansion(SL)) {
11521 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
11522 SL = SM.getSpellingLoc(SL);
11523 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
11524 SM.getSpellingLoc(DSR.getEnd()));
11525 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
11526 SM.getSpellingLoc(SSR.getEnd()));
11527 }
11528
11529 DiagRuntimeBehavior(SL, SizeOfArg,
11530 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
11531 << ReadableName << PointeeTy << DestTy << DSR
11532 << SSR);
11533 DiagRuntimeBehavior(SL, SizeOfArg,
11534 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
11535 << ActionIdx << SSR);
11536 return true;
11537 }
11538 return false;
11539}
11540
11541// A little helper routine: ignore addition and subtraction of integer literals.
11542// This intentionally does not ignore all integer constant expressions because
11543// we don't want to remove sizeof().
11544static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11545 Ex = Ex->IgnoreParenCasts();
11546
11547 while (true) {
11548 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11549 if (!BO || !BO->isAdditiveOp())
11550 break;
11551
11552 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11553 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11554
11555 if (isa<IntegerLiteral>(RHS))
11556 Ex = LHS;
11557 else if (isa<IntegerLiteral>(LHS))
11558 Ex = RHS;
11559 else
11560 break;
11561 }
11562
11563 return Ex;
11564}
11565
11567 ASTContext &Context) {
11568 // Only handle constant-sized or VLAs, but not flexible members.
11569 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11570 // Only issue the FIXIT for arrays of size > 1.
11571 if (CAT->getZExtSize() <= 1)
11572 return false;
11573 } else if (!Ty->isVariableArrayType()) {
11574 return false;
11575 }
11576 return true;
11577}
11578
11579void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11580 IdentifierInfo *FnName) {
11581
11582 // Don't crash if the user has the wrong number of arguments
11583 unsigned NumArgs = Call->getNumArgs();
11584 if ((NumArgs != 3) && (NumArgs != 4))
11585 return;
11586
11587 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11588 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11589 const Expr *CompareWithSrc = nullptr;
11590
11591 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11592 Call->getBeginLoc(), Call->getRParenLoc()))
11593 return;
11594
11595 // Look for 'strlcpy(dst, x, sizeof(x))'
11596 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11597 CompareWithSrc = Ex;
11598 else {
11599 // Look for 'strlcpy(dst, x, strlen(x))'
11600 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11601 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11602 SizeCall->getNumArgs() == 1)
11603 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11604 }
11605 }
11606
11607 if (!CompareWithSrc)
11608 return;
11609
11610 // Determine if the argument to sizeof/strlen is equal to the source
11611 // argument. In principle there's all kinds of things you could do
11612 // here, for instance creating an == expression and evaluating it with
11613 // EvaluateAsBooleanCondition, but this uses a more direct technique:
11614 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11615 if (!SrcArgDRE)
11616 return;
11617
11618 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11619 if (!CompareWithSrcDRE ||
11620 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11621 return;
11622
11623 const Expr *OriginalSizeArg = Call->getArg(2);
11624 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11625 << OriginalSizeArg->getSourceRange() << FnName;
11626
11627 // Output a FIXIT hint if the destination is an array (rather than a
11628 // pointer to an array). This could be enhanced to handle some
11629 // pointers if we know the actual size, like if DstArg is 'array+2'
11630 // we could say 'sizeof(array)-2'.
11631 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11633 return;
11634
11635 SmallString<128> sizeString;
11636 llvm::raw_svector_ostream OS(sizeString);
11637 OS << "sizeof(";
11638 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11639 OS << ")";
11640
11641 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11642 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11643 OS.str());
11644}
11645
11646/// Check if two expressions refer to the same declaration.
11647static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11648 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11649 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11650 return D1->getDecl() == D2->getDecl();
11651 return false;
11652}
11653
11654static const Expr *getStrlenExprArg(const Expr *E) {
11655 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11656 const FunctionDecl *FD = CE->getDirectCallee();
11657 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11658 return nullptr;
11659 return CE->getArg(0)->IgnoreParenCasts();
11660 }
11661 return nullptr;
11662}
11663
11664void Sema::CheckStrncatArguments(const CallExpr *CE,
11665 const IdentifierInfo *FnName) {
11666 // Don't crash if the user has the wrong number of arguments.
11667 if (CE->getNumArgs() < 3)
11668 return;
11669 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11670 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11671 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11672
11673 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11674 CE->getRParenLoc()))
11675 return;
11676
11677 // Identify common expressions, which are wrongly used as the size argument
11678 // to strncat and may lead to buffer overflows.
11679 unsigned PatternType = 0;
11680 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11681 // - sizeof(dst)
11682 if (referToTheSameDecl(SizeOfArg, DstArg))
11683 PatternType = 1;
11684 // - sizeof(src)
11685 else if (referToTheSameDecl(SizeOfArg, SrcArg))
11686 PatternType = 2;
11687 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11688 if (BE->getOpcode() == BO_Sub) {
11689 const Expr *L = BE->getLHS()->IgnoreParenCasts();
11690 const Expr *R = BE->getRHS()->IgnoreParenCasts();
11691 // - sizeof(dst) - strlen(dst)
11692 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11694 PatternType = 1;
11695 // - sizeof(src) - (anything)
11696 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11697 PatternType = 2;
11698 }
11699 }
11700
11701 if (PatternType == 0)
11702 return;
11703
11704 // Generate the diagnostic.
11705 SourceLocation SL = LenArg->getBeginLoc();
11706 SourceRange SR = LenArg->getSourceRange();
11707 SourceManager &SM = getSourceManager();
11708
11709 // If the function is defined as a builtin macro, do not show macro expansion.
11710 if (SM.isMacroArgExpansion(SL)) {
11711 SL = SM.getSpellingLoc(SL);
11712 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11713 SM.getSpellingLoc(SR.getEnd()));
11714 }
11715
11716 // Check if the destination is an array (rather than a pointer to an array).
11717 QualType DstTy = DstArg->getType();
11718 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11719 Context);
11720 if (!isKnownSizeArray) {
11721 if (PatternType == 1)
11722 Diag(SL, diag::warn_strncat_wrong_size) << SR;
11723 else
11724 Diag(SL, diag::warn_strncat_src_size) << SR;
11725 return;
11726 }
11727
11728 if (PatternType == 1)
11729 Diag(SL, diag::warn_strncat_large_size) << SR;
11730 else
11731 Diag(SL, diag::warn_strncat_src_size) << SR;
11732
11733 SmallString<128> sizeString;
11734 llvm::raw_svector_ostream OS(sizeString);
11735 OS << "sizeof(";
11736 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11737 OS << ") - ";
11738 OS << "strlen(";
11739 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11740 OS << ") - 1";
11741
11742 Diag(SL, diag::note_strncat_wrong_size)
11743 << FixItHint::CreateReplacement(SR, OS.str());
11744}
11745
11746namespace {
11747void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11748 const UnaryOperator *UnaryExpr, const Decl *D) {
11750 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11751 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11752 return;
11753 }
11754}
11755
11756void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11757 const UnaryOperator *UnaryExpr) {
11758 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11759 const Decl *D = Lvalue->getDecl();
11760 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11761 if (!DD->getType()->isReferenceType())
11762 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11763 }
11764 }
11765
11766 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11767 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11768 Lvalue->getMemberDecl());
11769}
11770
11771void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11772 const UnaryOperator *UnaryExpr) {
11773 const auto *Lambda = dyn_cast<LambdaExpr>(
11775 if (!Lambda)
11776 return;
11777
11778 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11779 << CalleeName << 2 /*object: lambda expression*/;
11780}
11781
11782void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11783 const DeclRefExpr *Lvalue) {
11784 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11785 if (Var == nullptr)
11786 return;
11787
11788 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11789 << CalleeName << 0 /*object: */ << Var;
11790}
11791
11792void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11793 const CastExpr *Cast) {
11794 SmallString<128> SizeString;
11795 llvm::raw_svector_ostream OS(SizeString);
11796
11797 clang::CastKind Kind = Cast->getCastKind();
11798 if (Kind == clang::CK_BitCast &&
11799 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11800 return;
11801 if (Kind == clang::CK_IntegralToPointer &&
11803 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11804 return;
11805
11806 switch (Cast->getCastKind()) {
11807 case clang::CK_BitCast:
11808 case clang::CK_IntegralToPointer:
11809 case clang::CK_FunctionToPointerDecay:
11810 OS << '\'';
11811 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11812 OS << '\'';
11813 break;
11814 default:
11815 return;
11816 }
11817
11818 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11819 << CalleeName << 0 /*object: */ << OS.str();
11820}
11821} // namespace
11822
11823void Sema::CheckFreeArguments(const CallExpr *E) {
11824 const std::string CalleeName =
11825 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11826
11827 { // Prefer something that doesn't involve a cast to make things simpler.
11828 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11829 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11830 switch (UnaryExpr->getOpcode()) {
11831 case UnaryOperator::Opcode::UO_AddrOf:
11832 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11833 case UnaryOperator::Opcode::UO_Plus:
11834 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11835 default:
11836 break;
11837 }
11838
11839 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11840 if (Lvalue->getType()->isArrayType())
11841 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11842
11843 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11844 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11845 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11846 return;
11847 }
11848
11849 if (isa<BlockExpr>(Arg)) {
11850 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11851 << CalleeName << 1 /*object: block*/;
11852 return;
11853 }
11854 }
11855 // Maybe the cast was important, check after the other cases.
11856 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11857 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11858}
11859
11860void
11861Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11862 SourceLocation ReturnLoc,
11863 bool isObjCMethod,
11864 const AttrVec *Attrs,
11865 const FunctionDecl *FD) {
11866 // Check if the return value is null but should not be.
11867 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11868 (!isObjCMethod && isNonNullType(lhsType))) &&
11869 CheckNonNullExpr(*this, RetValExp))
11870 Diag(ReturnLoc, diag::warn_null_ret)
11871 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11872
11873 // C++11 [basic.stc.dynamic.allocation]p4:
11874 // If an allocation function declared with a non-throwing
11875 // exception-specification fails to allocate storage, it shall return
11876 // a null pointer. Any other allocation function that fails to allocate
11877 // storage shall indicate failure only by throwing an exception [...]
11878 if (FD) {
11880 if (Op == OO_New || Op == OO_Array_New) {
11881 const FunctionProtoType *Proto
11882 = FD->getType()->castAs<FunctionProtoType>();
11883 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11884 CheckNonNullExpr(*this, RetValExp))
11885 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11886 << FD << getLangOpts().CPlusPlus11;
11887 }
11888 }
11889
11890 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11891 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
11892 }
11893
11894 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11895 // here prevent the user from using a PPC MMA type as trailing return type.
11896 if (Context.getTargetInfo().getTriple().isPPC64())
11897 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11898}
11899
11901 const Expr *RHS, BinaryOperatorKind Opcode) {
11902 if (!BinaryOperator::isEqualityOp(Opcode))
11903 return;
11904
11905 // Match and capture subexpressions such as "(float) X == 0.1".
11906 const FloatingLiteral *FPLiteral;
11907 const CastExpr *FPCast;
11908 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11909 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11910 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11911 return FPLiteral && FPCast;
11912 };
11913
11914 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11915 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11916 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11917 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11918 TargetTy->isFloatingPoint()) {
11919 bool Lossy;
11920 llvm::APFloat TargetC = FPLiteral->getValue();
11921 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11922 llvm::APFloat::rmNearestTiesToEven, &Lossy);
11923 if (Lossy) {
11924 // If the literal cannot be represented in the source type, then a
11925 // check for == is always false and check for != is always true.
11926 Diag(Loc, diag::warn_float_compare_literal)
11927 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11928 << LHS->getSourceRange() << RHS->getSourceRange();
11929 return;
11930 }
11931 }
11932 }
11933
11934 // Match a more general floating-point equality comparison (-Wfloat-equal).
11935 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11936 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11937
11938 // Special case: check for x == x (which is OK).
11939 // Do not emit warnings for such cases.
11940 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11941 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11942 if (DRL->getDecl() == DRR->getDecl())
11943 return;
11944
11945 // Special case: check for comparisons against literals that can be exactly
11946 // represented by APFloat. In such cases, do not emit a warning. This
11947 // is a heuristic: often comparison against such literals are used to
11948 // detect if a value in a variable has not changed. This clearly can
11949 // lead to false negatives.
11950 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11951 if (FLL->isExact())
11952 return;
11953 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11954 if (FLR->isExact())
11955 return;
11956
11957 // Check for comparisons with builtin types.
11958 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
11959 CL && CL->getBuiltinCallee())
11960 return;
11961
11962 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
11963 CR && CR->getBuiltinCallee())
11964 return;
11965
11966 // Emit the diagnostic.
11967 Diag(Loc, diag::warn_floatingpoint_eq)
11968 << LHS->getSourceRange() << RHS->getSourceRange();
11969}
11970
11971//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11972//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11973
11974namespace {
11975
11976/// Structure recording the 'active' range of an integer-valued
11977/// expression.
11978struct IntRange {
11979 /// The number of bits active in the int. Note that this includes exactly one
11980 /// sign bit if !NonNegative.
11981 unsigned Width;
11982
11983 /// True if the int is known not to have negative values. If so, all leading
11984 /// bits before Width are known zero, otherwise they are known to be the
11985 /// same as the MSB within Width.
11986 bool NonNegative;
11987
11988 IntRange(unsigned Width, bool NonNegative)
11989 : Width(Width), NonNegative(NonNegative) {}
11990
11991 /// Number of bits excluding the sign bit.
11992 unsigned valueBits() const {
11993 return NonNegative ? Width : Width - 1;
11994 }
11995
11996 /// Returns the range of the bool type.
11997 static IntRange forBoolType() {
11998 return IntRange(1, true);
11999 }
12000
12001 /// Returns the range of an opaque value of the given integral type.
12002 static IntRange forValueOfType(ASTContext &C, QualType T) {
12003 return forValueOfCanonicalType(C,
12005 }
12006
12007 /// Returns the range of an opaque value of a canonical integral type.
12008 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
12009 assert(T->isCanonicalUnqualified());
12010
12011 if (const auto *VT = dyn_cast<VectorType>(T))
12012 T = VT->getElementType().getTypePtr();
12013 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
12014 T = MT->getElementType().getTypePtr();
12015 if (const auto *CT = dyn_cast<ComplexType>(T))
12016 T = CT->getElementType().getTypePtr();
12017 if (const auto *AT = dyn_cast<AtomicType>(T))
12018 T = AT->getValueType().getTypePtr();
12019 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
12020 T = OBT->getUnderlyingType().getTypePtr();
12021
12022 if (!C.getLangOpts().CPlusPlus) {
12023 // For enum types in C code, use the underlying datatype.
12024 if (const auto *ED = T->getAsEnumDecl())
12025 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
12026 } else if (auto *Enum = T->getAsEnumDecl()) {
12027 // For enum types in C++, use the known bit width of the enumerators.
12028 // In C++11, enums can have a fixed underlying type. Use this type to
12029 // compute the range.
12030 if (Enum->isFixed()) {
12031 return IntRange(C.getIntWidth(QualType(T, 0)),
12032 !Enum->getIntegerType()->isSignedIntegerType());
12033 }
12034
12035 unsigned NumPositive = Enum->getNumPositiveBits();
12036 unsigned NumNegative = Enum->getNumNegativeBits();
12037
12038 if (NumNegative == 0)
12039 return IntRange(NumPositive, true/*NonNegative*/);
12040 else
12041 return IntRange(std::max(NumPositive + 1, NumNegative),
12042 false/*NonNegative*/);
12043 }
12044
12045 if (const auto *EIT = dyn_cast<BitIntType>(T))
12046 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
12047
12048 const BuiltinType *BT = cast<BuiltinType>(T);
12049 assert(BT->isInteger());
12050
12051 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
12052 }
12053
12054 /// Returns the "target" range of a canonical integral type, i.e.
12055 /// the range of values expressible in the type.
12056 ///
12057 /// This matches forValueOfCanonicalType except that enums have the
12058 /// full range of their type, not the range of their enumerators.
12059 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
12060 assert(T->isCanonicalUnqualified());
12061
12062 if (const VectorType *VT = dyn_cast<VectorType>(T))
12063 T = VT->getElementType().getTypePtr();
12064 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
12065 T = MT->getElementType().getTypePtr();
12066 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
12067 T = CT->getElementType().getTypePtr();
12068 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
12069 T = AT->getValueType().getTypePtr();
12070 if (const auto *ED = T->getAsEnumDecl())
12071 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
12072 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
12073 T = OBT->getUnderlyingType().getTypePtr();
12074
12075 if (const auto *EIT = dyn_cast<BitIntType>(T))
12076 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
12077
12078 const BuiltinType *BT = cast<BuiltinType>(T);
12079 assert(BT->isInteger());
12080
12081 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
12082 }
12083
12084 /// Returns the supremum of two ranges: i.e. their conservative merge.
12085 static IntRange join(IntRange L, IntRange R) {
12086 bool Unsigned = L.NonNegative && R.NonNegative;
12087 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
12088 L.NonNegative && R.NonNegative);
12089 }
12090
12091 /// Return the range of a bitwise-AND of the two ranges.
12092 static IntRange bit_and(IntRange L, IntRange R) {
12093 unsigned Bits = std::max(L.Width, R.Width);
12094 bool NonNegative = false;
12095 if (L.NonNegative) {
12096 Bits = std::min(Bits, L.Width);
12097 NonNegative = true;
12098 }
12099 if (R.NonNegative) {
12100 Bits = std::min(Bits, R.Width);
12101 NonNegative = true;
12102 }
12103 return IntRange(Bits, NonNegative);
12104 }
12105
12106 /// Return the range of a sum of the two ranges.
12107 static IntRange sum(IntRange L, IntRange R) {
12108 bool Unsigned = L.NonNegative && R.NonNegative;
12109 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
12110 Unsigned);
12111 }
12112
12113 /// Return the range of a difference of the two ranges.
12114 static IntRange difference(IntRange L, IntRange R) {
12115 // We need a 1-bit-wider range if:
12116 // 1) LHS can be negative: least value can be reduced.
12117 // 2) RHS can be negative: greatest value can be increased.
12118 bool CanWiden = !L.NonNegative || !R.NonNegative;
12119 bool Unsigned = L.NonNegative && R.Width == 0;
12120 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
12121 !Unsigned,
12122 Unsigned);
12123 }
12124
12125 /// Return the range of a product of the two ranges.
12126 static IntRange product(IntRange L, IntRange R) {
12127 // If both LHS and RHS can be negative, we can form
12128 // -2^L * -2^R = 2^(L + R)
12129 // which requires L + R + 1 value bits to represent.
12130 bool CanWiden = !L.NonNegative && !R.NonNegative;
12131 bool Unsigned = L.NonNegative && R.NonNegative;
12132 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
12133 Unsigned);
12134 }
12135
12136 /// Return the range of a remainder operation between the two ranges.
12137 static IntRange rem(IntRange L, IntRange R) {
12138 // The result of a remainder can't be larger than the result of
12139 // either side. The sign of the result is the sign of the LHS.
12140 bool Unsigned = L.NonNegative;
12141 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
12142 Unsigned);
12143 }
12144};
12145
12146} // namespace
12147
12148static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
12149 if (value.isSigned() && value.isNegative())
12150 return IntRange(value.getSignificantBits(), false);
12151
12152 if (value.getBitWidth() > MaxWidth)
12153 value = value.trunc(MaxWidth);
12154
12155 // isNonNegative() just checks the sign bit without considering
12156 // signedness.
12157 return IntRange(value.getActiveBits(), true);
12158}
12159
12160static std::optional<IntRange> GetValueRange(APValue &result, QualType Ty,
12161 unsigned MaxWidth) {
12162 if (result.isInt())
12163 return GetValueRange(result.getInt(), MaxWidth);
12164
12165 if (result.isVector()) {
12166 std::optional<IntRange> R =
12167 GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
12168 if (!R)
12169 return std::nullopt;
12170 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
12171 std::optional<IntRange> El =
12172 GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
12173 if (!El)
12174 return std::nullopt;
12175 R = IntRange::join(*R, *El);
12176 }
12177 return R;
12178 }
12179
12180 if (result.isComplexInt()) {
12181 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
12182 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
12183 return IntRange::join(R, I);
12184 }
12185
12186 // This can happen with lossless casts to intptr_t of "based" lvalues.
12187 // Assume it might use arbitrary bits.
12188 // FIXME: The only reason we need to pass the type in here is to get
12189 // the sign right on this one case. It would be nice if APValue
12190 // preserved this.
12191 if (result.isLValue() || result.isAddrLabelDiff())
12192 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
12193
12194 // Unsupported APValue kinds (e.g. floating) have no integer range.
12195 return std::nullopt;
12196}
12197
12198static QualType GetExprType(const Expr *E) {
12199 QualType Ty = E->getType();
12200 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
12201 Ty = AtomicRHS->getValueType();
12202 return Ty;
12203}
12204
12205/// Attempts to estimate an approximate range for the given integer expression.
12206/// Returns a range if successful, otherwise it returns \c std::nullopt if a
12207/// reliable estimation cannot be determined.
12208///
12209/// \param MaxWidth The width to which the value will be truncated.
12210/// \param InConstantContext If \c true, interpret the expression within a
12211/// constant context.
12212/// \param Approximate If \c true, provide a likely range of values by assuming
12213/// that arithmetic on narrower types remains within those types.
12214/// If \c false, return a range that includes all possible values
12215/// resulting from the expression.
12216/// \returns A range of values that the expression might take, or
12217/// std::nullopt if a reliable estimation cannot be determined.
12218static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12219 unsigned MaxWidth,
12220 bool InConstantContext,
12221 bool Approximate) {
12222 E = E->IgnoreParens();
12223
12224 // A BPF enumerator relocated at load time is not a constant. Use the range of
12225 // its local value, as if it were not relocated, if an approximate range is
12226 // allowed. Otherwise, use the range of its type, since its value is only
12227 // known at load time.
12228 if (Approximate && SemaBPF::isPreserveAIEnumeratorRef(E))
12229 E = cast<PseudoObjectExpr>(E)->getSyntacticForm();
12230
12231 // Try a full evaluation first.
12232 Expr::EvalResult result;
12233 if (E->EvaluateAsRValue(result, C, InConstantContext))
12234 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
12235
12236 // I think we only want to look through implicit casts here; if the
12237 // user has an explicit widening cast, we should treat the value as
12238 // being of the new, wider type.
12239 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
12240 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
12241 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
12242 Approximate);
12243
12244 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
12245
12246 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
12247 CE->getCastKind() == CK_BooleanToSignedIntegral;
12248
12249 // Assume that non-integer casts can span the full range of the type.
12250 if (!isIntegerCast)
12251 return OutputTypeRange;
12252
12253 std::optional<IntRange> SubRange = TryGetExprRange(
12254 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
12255 InConstantContext, Approximate);
12256 if (!SubRange)
12257 return std::nullopt;
12258
12259 // Bail out if the subexpr's range is as wide as the cast type.
12260 if (SubRange->Width >= OutputTypeRange.Width)
12261 return OutputTypeRange;
12262
12263 // Otherwise, we take the smaller width, and we're non-negative if
12264 // either the output type or the subexpr is.
12265 return IntRange(SubRange->Width,
12266 SubRange->NonNegative || OutputTypeRange.NonNegative);
12267 }
12268
12269 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12270 // If we can fold the condition, just take that operand.
12271 bool CondResult;
12272 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
12273 return TryGetExprRange(
12274 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
12275 InConstantContext, Approximate);
12276
12277 // Otherwise, conservatively merge.
12278 // TryGetExprRange requires an integer expression, but a throw expression
12279 // results in a void type.
12280 Expr *TrueExpr = CO->getTrueExpr();
12281 if (TrueExpr->getType()->isVoidType())
12282 return std::nullopt;
12283
12284 std::optional<IntRange> L =
12285 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
12286 if (!L)
12287 return std::nullopt;
12288
12289 Expr *FalseExpr = CO->getFalseExpr();
12290 if (FalseExpr->getType()->isVoidType())
12291 return std::nullopt;
12292
12293 std::optional<IntRange> R =
12294 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
12295 if (!R)
12296 return std::nullopt;
12297
12298 return IntRange::join(*L, *R);
12299 }
12300
12301 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12302 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
12303
12304 switch (BO->getOpcode()) {
12305 case BO_Cmp:
12306 llvm_unreachable("builtin <=> should have class type");
12307
12308 // Boolean-valued operations are single-bit and positive.
12309 case BO_LAnd:
12310 case BO_LOr:
12311 case BO_LT:
12312 case BO_GT:
12313 case BO_LE:
12314 case BO_GE:
12315 case BO_EQ:
12316 case BO_NE:
12317 return IntRange::forBoolType();
12318
12319 // The type of the assignments is the type of the LHS, so the RHS
12320 // is not necessarily the same type.
12321 case BO_MulAssign:
12322 case BO_DivAssign:
12323 case BO_RemAssign:
12324 case BO_AddAssign:
12325 case BO_SubAssign:
12326 case BO_XorAssign:
12327 case BO_OrAssign:
12328 // TODO: bitfields?
12329 return IntRange::forValueOfType(C, GetExprType(E));
12330
12331 // Simple assignments just pass through the RHS, which will have
12332 // been coerced to the LHS type.
12333 case BO_Assign:
12334 // TODO: bitfields?
12335 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
12336 Approximate);
12337
12338 // Operations with opaque sources are black-listed.
12339 case BO_PtrMemD:
12340 case BO_PtrMemI:
12341 return IntRange::forValueOfType(C, GetExprType(E));
12342
12343 // Bitwise-and uses the *infinum* of the two source ranges.
12344 case BO_And:
12345 case BO_AndAssign:
12346 Combine = IntRange::bit_and;
12347 break;
12348
12349 // Left shift gets black-listed based on a judgement call.
12350 case BO_Shl:
12351 // ...except that we want to treat '1 << (blah)' as logically
12352 // positive. It's an important idiom.
12353 if (IntegerLiteral *I
12354 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
12355 if (I->getValue() == 1) {
12356 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
12357 return IntRange(R.Width, /*NonNegative*/ true);
12358 }
12359 }
12360 [[fallthrough]];
12361
12362 case BO_ShlAssign:
12363 return IntRange::forValueOfType(C, GetExprType(E));
12364
12365 // Right shift by a constant can narrow its left argument.
12366 case BO_Shr:
12367 case BO_ShrAssign: {
12368 std::optional<IntRange> L = TryGetExprRange(
12369 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
12370 if (!L)
12371 return std::nullopt;
12372
12373 // If the shift amount is a positive constant, drop the width by
12374 // that much.
12375 if (std::optional<llvm::APSInt> shift =
12376 BO->getRHS()->getIntegerConstantExpr(C)) {
12377 if (shift->isNonNegative()) {
12378 if (shift->uge(L->Width))
12379 L->Width = (L->NonNegative ? 0 : 1);
12380 else
12381 L->Width -= shift->getZExtValue();
12382 }
12383 }
12384
12385 return L;
12386 }
12387
12388 // Comma acts as its right operand.
12389 case BO_Comma:
12390 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
12391 Approximate);
12392
12393 case BO_Add:
12394 if (!Approximate)
12395 Combine = IntRange::sum;
12396 break;
12397
12398 case BO_Sub:
12399 if (BO->getLHS()->getType()->isPointerType())
12400 return IntRange::forValueOfType(C, GetExprType(E));
12401 if (!Approximate)
12402 Combine = IntRange::difference;
12403 break;
12404
12405 case BO_Mul:
12406 if (!Approximate)
12407 Combine = IntRange::product;
12408 break;
12409
12410 // The width of a division result is mostly determined by the size
12411 // of the LHS.
12412 case BO_Div: {
12413 // Don't 'pre-truncate' the operands.
12414 unsigned opWidth = C.getIntWidth(GetExprType(E));
12415 std::optional<IntRange> L = TryGetExprRange(
12416 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
12417 if (!L)
12418 return std::nullopt;
12419
12420 // If the divisor is constant, use that.
12421 if (std::optional<llvm::APSInt> divisor =
12422 BO->getRHS()->getIntegerConstantExpr(C)) {
12423 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
12424 if (log2 >= L->Width)
12425 L->Width = (L->NonNegative ? 0 : 1);
12426 else
12427 L->Width = std::min(L->Width - log2, MaxWidth);
12428 return L;
12429 }
12430
12431 // Otherwise, just use the LHS's width.
12432 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
12433 // could be -1.
12434 std::optional<IntRange> R = TryGetExprRange(
12435 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
12436 if (!R)
12437 return std::nullopt;
12438
12439 return IntRange(L->Width, L->NonNegative && R->NonNegative);
12440 }
12441
12442 case BO_Rem:
12443 Combine = IntRange::rem;
12444 break;
12445
12446 // The default behavior is okay for these.
12447 case BO_Xor:
12448 case BO_Or:
12449 break;
12450 }
12451
12452 // Combine the two ranges, but limit the result to the type in which we
12453 // performed the computation.
12454 QualType T = GetExprType(E);
12455 unsigned opWidth = C.getIntWidth(T);
12456 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
12457 InConstantContext, Approximate);
12458 if (!L)
12459 return std::nullopt;
12460
12461 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
12462 InConstantContext, Approximate);
12463 if (!R)
12464 return std::nullopt;
12465
12466 IntRange C = Combine(*L, *R);
12467 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
12468 C.Width = std::min(C.Width, MaxWidth);
12469 return C;
12470 }
12471
12472 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12473 switch (UO->getOpcode()) {
12474 // Boolean-valued operations are white-listed.
12475 case UO_LNot:
12476 return IntRange::forBoolType();
12477
12478 // Operations with opaque sources are black-listed.
12479 case UO_Deref:
12480 case UO_AddrOf: // should be impossible
12481 return IntRange::forValueOfType(C, GetExprType(E));
12482
12483 case UO_Minus: {
12484 if (GetExprType(E)->hasUnsignedIntegerRepresentation()) {
12485 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12486 Approximate);
12487 }
12488
12489 std::optional<IntRange> SubRange = TryGetExprRange(
12490 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12491
12492 if (!SubRange)
12493 return std::nullopt;
12494
12495 // If the range was previously non-negative, we need an extra bit for the
12496 // sign bit. Otherwise, we need an extra bit because the negation of the
12497 // most-negative value is one bit wider than that value.
12498 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
12499 }
12500
12501 case UO_Not: {
12502 if (GetExprType(E)->hasUnsignedIntegerRepresentation()) {
12503 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12504 Approximate);
12505 }
12506
12507 std::optional<IntRange> SubRange = TryGetExprRange(
12508 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12509
12510 if (!SubRange)
12511 return std::nullopt;
12512
12513 // The width increments by 1 if the sub-expression cannot be negative
12514 // since it now can be.
12515 return IntRange(
12516 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
12517 false);
12518 }
12519
12520 default:
12521 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12522 Approximate);
12523 }
12524 }
12525
12526 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12527 // The source expression is null for the OpaqueValueExpr that stands in for
12528 // a non-type template argument of pointer or reference type; fall back to
12529 // the range of the type in that case.
12530 if (const Expr *SourceExpr = OVE->getSourceExpr())
12531 return TryGetExprRange(C, SourceExpr, MaxWidth, InConstantContext,
12532 Approximate);
12533 }
12534
12535 if (const auto *BitField = E->getSourceBitField())
12536 return IntRange(BitField->getBitWidthValue(),
12537 BitField->getType()->isUnsignedIntegerOrEnumerationType());
12538
12539 if (GetExprType(E)->isVoidType())
12540 return std::nullopt;
12541
12542 return IntRange::forValueOfType(C, GetExprType(E));
12543}
12544
12545static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12546 bool InConstantContext,
12547 bool Approximate) {
12548 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
12549 Approximate);
12550}
12551
12552/// Checks whether the given value, which currently has the given
12553/// source semantics, has the same value when coerced through the
12554/// target semantics.
12555static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12556 const llvm::fltSemantics &Src,
12557 const llvm::fltSemantics &Tgt) {
12558 llvm::APFloat truncated = value;
12559
12560 bool ignored;
12561 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
12562 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
12563
12564 return truncated.bitwiseIsEqual(value);
12565}
12566
12567/// Checks whether the given value, which currently has the given
12568/// source semantics, has the same value when coerced through the
12569/// target semantics.
12570///
12571/// The value might be a vector of floats (or a complex number).
12572static bool IsSameFloatAfterCast(const APValue &value,
12573 const llvm::fltSemantics &Src,
12574 const llvm::fltSemantics &Tgt) {
12575 if (value.isFloat())
12576 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
12577
12578 if (value.isVector()) {
12579 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12580 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
12581 return false;
12582 return true;
12583 }
12584
12585 if (value.isMatrix()) {
12586 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
12587 if (!IsSameFloatAfterCast(value.getMatrixElt(i), Src, Tgt))
12588 return false;
12589 return true;
12590 }
12591
12592 assert(value.isComplexFloat());
12593 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
12594 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
12595}
12596
12597static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12598 bool IsListInit = false);
12599
12600static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
12601 // Suppress cases where we are comparing against an enum constant.
12602 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
12603 if (isa<EnumConstantDecl>(DR->getDecl()))
12604 return true;
12605
12606 // Suppress cases where the value is expanded from a macro, unless that macro
12607 // is how a language represents a boolean literal. This is the case in both C
12608 // and Objective-C.
12609 SourceLocation BeginLoc = E->getBeginLoc();
12610 if (BeginLoc.isMacroID()) {
12611 StringRef MacroName = Lexer::getImmediateMacroName(
12612 BeginLoc, S.getSourceManager(), S.getLangOpts());
12613 return MacroName != "YES" && MacroName != "NO" &&
12614 MacroName != "true" && MacroName != "false";
12615 }
12616
12617 return false;
12618}
12619
12620static bool isKnownToHaveUnsignedValue(const Expr *E) {
12621 return E->getType()->isIntegerType() &&
12622 (!E->getType()->isSignedIntegerType() ||
12624}
12625
12626namespace {
12627/// The promoted range of values of a type. In general this has the
12628/// following structure:
12629///
12630/// |-----------| . . . |-----------|
12631/// ^ ^ ^ ^
12632/// Min HoleMin HoleMax Max
12633///
12634/// ... where there is only a hole if a signed type is promoted to unsigned
12635/// (in which case Min and Max are the smallest and largest representable
12636/// values).
12637struct PromotedRange {
12638 // Min, or HoleMax if there is a hole.
12639 llvm::APSInt PromotedMin;
12640 // Max, or HoleMin if there is a hole.
12641 llvm::APSInt PromotedMax;
12642
12643 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12644 if (R.Width == 0)
12645 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12646 else if (R.Width >= BitWidth && !Unsigned) {
12647 // Promotion made the type *narrower*. This happens when promoting
12648 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12649 // Treat all values of 'signed int' as being in range for now.
12650 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12651 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12652 } else {
12653 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12654 .extOrTrunc(BitWidth);
12655 PromotedMin.setIsUnsigned(Unsigned);
12656
12657 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12658 .extOrTrunc(BitWidth);
12659 PromotedMax.setIsUnsigned(Unsigned);
12660 }
12661 }
12662
12663 // Determine whether this range is contiguous (has no hole).
12664 bool isContiguous() const { return PromotedMin <= PromotedMax; }
12665
12666 // Where a constant value is within the range.
12667 enum ComparisonResult {
12668 LT = 0x1,
12669 LE = 0x2,
12670 GT = 0x4,
12671 GE = 0x8,
12672 EQ = 0x10,
12673 NE = 0x20,
12674 InRangeFlag = 0x40,
12675
12676 Less = LE | LT | NE,
12677 Min = LE | InRangeFlag,
12678 InRange = InRangeFlag,
12679 Max = GE | InRangeFlag,
12680 Greater = GE | GT | NE,
12681
12682 OnlyValue = LE | GE | EQ | InRangeFlag,
12683 InHole = NE
12684 };
12685
12686 ComparisonResult compare(const llvm::APSInt &Value) const {
12687 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12688 Value.isUnsigned() == PromotedMin.isUnsigned());
12689 if (!isContiguous()) {
12690 assert(Value.isUnsigned() && "discontiguous range for signed compare");
12691 if (Value.isMinValue()) return Min;
12692 if (Value.isMaxValue()) return Max;
12693 if (Value >= PromotedMin) return InRange;
12694 if (Value <= PromotedMax) return InRange;
12695 return InHole;
12696 }
12697
12698 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12699 case -1: return Less;
12700 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12701 case 1:
12702 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12703 case -1: return InRange;
12704 case 0: return Max;
12705 case 1: return Greater;
12706 }
12707 }
12708
12709 llvm_unreachable("impossible compare result");
12710 }
12711
12712 static std::optional<StringRef>
12713 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12714 if (Op == BO_Cmp) {
12715 ComparisonResult LTFlag = LT, GTFlag = GT;
12716 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12717
12718 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12719 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12720 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12721 return std::nullopt;
12722 }
12723
12724 ComparisonResult TrueFlag, FalseFlag;
12725 if (Op == BO_EQ) {
12726 TrueFlag = EQ;
12727 FalseFlag = NE;
12728 } else if (Op == BO_NE) {
12729 TrueFlag = NE;
12730 FalseFlag = EQ;
12731 } else {
12732 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12733 TrueFlag = LT;
12734 FalseFlag = GE;
12735 } else {
12736 TrueFlag = GT;
12737 FalseFlag = LE;
12738 }
12739 if (Op == BO_GE || Op == BO_LE)
12740 std::swap(TrueFlag, FalseFlag);
12741 }
12742 if (R & TrueFlag)
12743 return StringRef("true");
12744 if (R & FalseFlag)
12745 return StringRef("false");
12746 return std::nullopt;
12747 }
12748};
12749}
12750
12751static bool HasEnumType(const Expr *E) {
12752 // Strip off implicit integral promotions.
12753 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12754 if (ICE->getCastKind() != CK_IntegralCast &&
12755 ICE->getCastKind() != CK_NoOp)
12756 break;
12757 E = ICE->getSubExpr();
12758 }
12759
12760 return E->getType()->isEnumeralType();
12761}
12762
12764 // The values of this enumeration are used in the diagnostics
12765 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12766 enum ConstantValueKind {
12767 Miscellaneous = 0,
12768 LiteralTrue,
12769 LiteralFalse
12770 };
12771 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12772 return BL->getValue() ? ConstantValueKind::LiteralTrue
12773 : ConstantValueKind::LiteralFalse;
12774 return ConstantValueKind::Miscellaneous;
12775}
12776
12779 const llvm::APSInt &Value,
12780 bool RhsConstant) {
12782 return false;
12783
12784 Expr *OriginalOther = Other;
12785
12786 Constant = Constant->IgnoreParenImpCasts();
12787 Other = Other->IgnoreParenImpCasts();
12788
12789 // Suppress warnings on tautological comparisons between values of the same
12790 // enumeration type. There are only two ways we could warn on this:
12791 // - If the constant is outside the range of representable values of
12792 // the enumeration. In such a case, we should warn about the cast
12793 // to enumeration type, not about the comparison.
12794 // - If the constant is the maximum / minimum in-range value. For an
12795 // enumeratin type, such comparisons can be meaningful and useful.
12796 if (Constant->getType()->isEnumeralType() &&
12797 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12798 return false;
12799
12800 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12801 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
12802 if (!OtherValueRange)
12803 return false;
12804
12805 QualType OtherT = Other->getType();
12806 if (const auto *AT = OtherT->getAs<AtomicType>())
12807 OtherT = AT->getValueType();
12808 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12809
12810 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12811 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12812 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12813 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
12814 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12815
12816 // Whether we're treating Other as being a bool because of the form of
12817 // expression despite it having another type (typically 'int' in C).
12818 bool OtherIsBooleanDespiteType =
12819 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12820 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12821 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12822
12823 // Check if all values in the range of possible values of this expression
12824 // lead to the same comparison outcome.
12825 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12826 Value.isUnsigned());
12827 auto Cmp = OtherPromotedValueRange.compare(Value);
12828 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12829 if (!Result)
12830 return false;
12831
12832 // Also consider the range determined by the type alone. This allows us to
12833 // classify the warning under the proper diagnostic group.
12834 bool TautologicalTypeCompare = false;
12835 {
12836 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12837 Value.isUnsigned());
12838 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12839 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12840 RhsConstant)) {
12841 TautologicalTypeCompare = true;
12842 Cmp = TypeCmp;
12844 }
12845 }
12846
12847 // Don't warn if the non-constant operand actually always evaluates to the
12848 // same value.
12849 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12850 return false;
12851
12852 // Suppress the diagnostic for an in-range comparison if the constant comes
12853 // from a macro or enumerator. We don't want to diagnose
12854 //
12855 // some_long_value <= INT_MAX
12856 //
12857 // when sizeof(int) == sizeof(long).
12858 bool InRange = Cmp & PromotedRange::InRangeFlag;
12859 if (InRange && IsEnumConstOrFromMacro(S, Constant))
12860 return false;
12861
12862 // A comparison of an unsigned bit-field against 0 is really a type problem,
12863 // even though at the type level the bit-field might promote to 'signed int'.
12864 if (Other->refersToBitField() && InRange && Value == 0 &&
12865 Other->getType()->isUnsignedIntegerOrEnumerationType())
12866 TautologicalTypeCompare = true;
12867
12868 // If this is a comparison to an enum constant, include that
12869 // constant in the diagnostic.
12870 const EnumConstantDecl *ED = nullptr;
12871 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
12872 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12873
12874 // Should be enough for uint128 (39 decimal digits)
12875 SmallString<64> PrettySourceValue;
12876 llvm::raw_svector_ostream OS(PrettySourceValue);
12877 if (ED) {
12878 OS << '\'' << *ED << "' (" << Value << ")";
12879 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12880 Constant->IgnoreParenImpCasts())) {
12881 OS << (BL->getValue() ? "YES" : "NO");
12882 } else {
12883 OS << Value;
12884 }
12885
12886 if (!TautologicalTypeCompare) {
12887 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12888 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12889 << E->getOpcodeStr() << OS.str() << *Result
12890 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12891 return true;
12892 }
12893
12894 if (IsObjCSignedCharBool) {
12896 S.PDiag(diag::warn_tautological_compare_objc_bool)
12897 << OS.str() << *Result);
12898 return true;
12899 }
12900
12901 // FIXME: We use a somewhat different formatting for the in-range cases and
12902 // cases involving boolean values for historical reasons. We should pick a
12903 // consistent way of presenting these diagnostics.
12904 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12905
12907 E->getOperatorLoc(), E,
12908 S.PDiag(!InRange ? diag::warn_out_of_range_compare
12909 : diag::warn_tautological_bool_compare)
12910 << OS.str() << classifyConstantValue(Constant) << OtherT
12911 << OtherIsBooleanDespiteType << *Result
12912 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12913 } else {
12914 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12915 unsigned Diag =
12916 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12917 ? (HasEnumType(OriginalOther)
12918 ? diag::warn_unsigned_enum_always_true_comparison
12919 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12920 : diag::warn_unsigned_always_true_comparison)
12921 : diag::warn_tautological_constant_compare;
12922
12923 S.Diag(E->getOperatorLoc(), Diag)
12924 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12925 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12926 }
12927
12928 return true;
12929}
12930
12931/// Analyze the operands of the given comparison. Implements the
12932/// fallback case from AnalyzeComparison.
12937
12938/// Implements -Wsign-compare.
12939///
12940/// \param E the binary operator to check for warnings
12942 // The type the comparison is being performed in.
12943 QualType T = E->getLHS()->getType();
12944
12945 // Only analyze comparison operators where both sides have been converted to
12946 // the same type.
12948 return AnalyzeImpConvsInComparison(S, E);
12949
12950 // Don't analyze value-dependent comparisons directly.
12951 if (E->isValueDependent())
12952 return AnalyzeImpConvsInComparison(S, E);
12953
12954 Expr *LHS = E->getLHS();
12955 Expr *RHS = E->getRHS();
12956
12957 if (T->isIntegralType(S.Context)) {
12958 std::optional<llvm::APSInt> RHSValue =
12960 std::optional<llvm::APSInt> LHSValue =
12962
12963 // We don't care about expressions whose result is a constant.
12964 if (RHSValue && LHSValue)
12965 return AnalyzeImpConvsInComparison(S, E);
12966
12967 // We only care about expressions where just one side is literal
12968 if ((bool)RHSValue ^ (bool)LHSValue) {
12969 // Is the constant on the RHS or LHS?
12970 const bool RhsConstant = (bool)RHSValue;
12971 Expr *Const = RhsConstant ? RHS : LHS;
12972 Expr *Other = RhsConstant ? LHS : RHS;
12973 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12974
12975 // Check whether an integer constant comparison results in a value
12976 // of 'true' or 'false'.
12977 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12978 return AnalyzeImpConvsInComparison(S, E);
12979 }
12980 }
12981
12982 if (!T->hasUnsignedIntegerRepresentation()) {
12983 // We don't do anything special if this isn't an unsigned integral
12984 // comparison: we're only interested in integral comparisons, and
12985 // signed comparisons only happen in cases we don't care to warn about.
12986 return AnalyzeImpConvsInComparison(S, E);
12987 }
12988
12989 LHS = LHS->IgnoreParenImpCasts();
12990 RHS = RHS->IgnoreParenImpCasts();
12991
12992 if (!S.getLangOpts().CPlusPlus) {
12993 // Avoid warning about comparison of integers with different signs when
12994 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12995 // the type of `E`.
12996 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12997 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12998 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12999 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
13000 }
13001
13002 // Check to see if one of the (unmodified) operands is of different
13003 // signedness.
13004 Expr *signedOperand, *unsignedOperand;
13006 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
13007 "unsigned comparison between two signed integer expressions?");
13008 signedOperand = LHS;
13009 unsignedOperand = RHS;
13010 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
13011 signedOperand = RHS;
13012 unsignedOperand = LHS;
13013 } else {
13014 return AnalyzeImpConvsInComparison(S, E);
13015 }
13016
13017 // Otherwise, calculate the effective range of the signed operand.
13018 std::optional<IntRange> signedRange =
13020 /*Approximate=*/true);
13021 if (!signedRange)
13022 return;
13023
13024 // Go ahead and analyze implicit conversions in the operands. Note
13025 // that we skip the implicit conversions on both sides.
13028
13029 // If the signed range is non-negative, -Wsign-compare won't fire.
13030 if (signedRange->NonNegative)
13031 return;
13032
13033 // For (in)equality comparisons, if the unsigned operand is a
13034 // constant which cannot collide with a overflowed signed operand,
13035 // then reinterpreting the signed operand as unsigned will not
13036 // change the result of the comparison.
13037 if (E->isEqualityOp()) {
13038 unsigned comparisonWidth = S.Context.getIntWidth(T);
13039 std::optional<IntRange> unsignedRange = TryGetExprRange(
13040 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
13041 /*Approximate=*/true);
13042 if (!unsignedRange)
13043 return;
13044
13045 // We should never be unable to prove that the unsigned operand is
13046 // non-negative.
13047 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
13048
13049 if (unsignedRange->Width < comparisonWidth)
13050 return;
13051 }
13052
13054 S.PDiag(diag::warn_mixed_sign_comparison)
13055 << LHS->getType() << RHS->getType()
13056 << LHS->getSourceRange() << RHS->getSourceRange());
13057}
13058
13059/// Analyzes an attempt to assign the given value to a bitfield.
13060///
13061/// Returns true if there was something fishy about the attempt.
13063 SourceLocation InitLoc) {
13064 assert(Bitfield->isBitField());
13065 if (Bitfield->isInvalidDecl())
13066 return false;
13067
13068 // White-list bool bitfields.
13069 QualType BitfieldType = Bitfield->getType();
13070 if (BitfieldType->isBooleanType())
13071 return false;
13072
13073 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
13074 // If the underlying enum type was not explicitly specified as an unsigned
13075 // type and the enum contain only positive values, MSVC++ will cause an
13076 // inconsistency by storing this as a signed type.
13077 if (S.getLangOpts().CPlusPlus11 &&
13078 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
13079 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
13080 BitfieldEnumDecl->getNumNegativeBits() == 0) {
13081 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
13082 << BitfieldEnumDecl;
13083 }
13084 }
13085
13086 // Ignore value- or type-dependent expressions.
13087 if (Bitfield->getBitWidth()->isValueDependent() ||
13088 Bitfield->getBitWidth()->isTypeDependent() ||
13089 Init->isValueDependent() ||
13090 Init->isTypeDependent())
13091 return false;
13092
13093 Expr *OriginalInit = Init->IgnoreParenImpCasts();
13094 unsigned FieldWidth = Bitfield->getBitWidthValue();
13095
13097 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
13099 // The RHS is not constant. If the RHS has an enum type, make sure the
13100 // bitfield is wide enough to hold all the values of the enum without
13101 // truncation.
13102 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
13103 const PreferredTypeAttr *PTAttr = nullptr;
13104 if (!ED) {
13105 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
13106 if (PTAttr)
13107 ED = PTAttr->getType()->getAsEnumDecl();
13108 }
13109 if (ED) {
13110 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
13111
13112 // Enum types are implicitly signed on Windows, so check if there are any
13113 // negative enumerators to see if the enum was intended to be signed or
13114 // not.
13115 bool SignedEnum = ED->getNumNegativeBits() > 0;
13116
13117 // Check for surprising sign changes when assigning enum values to a
13118 // bitfield of different signedness. If the bitfield is signed and we
13119 // have exactly the right number of bits to store this unsigned enum,
13120 // suggest changing the enum to an unsigned type. This typically happens
13121 // on Windows where unfixed enums always use an underlying type of 'int'.
13122 unsigned DiagID = 0;
13123 if (SignedEnum && !SignedBitfield) {
13124 DiagID =
13125 PTAttr == nullptr
13126 ? diag::warn_unsigned_bitfield_assigned_signed_enum
13127 : diag::
13128 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
13129 } else if (SignedBitfield && !SignedEnum &&
13130 ED->getNumPositiveBits() == FieldWidth) {
13131 DiagID =
13132 PTAttr == nullptr
13133 ? diag::warn_signed_bitfield_enum_conversion
13134 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
13135 }
13136 if (DiagID) {
13137 S.Diag(InitLoc, DiagID) << Bitfield << ED;
13138 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
13139 SourceRange TypeRange =
13140 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
13141 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
13142 << SignedEnum << TypeRange;
13143 if (PTAttr)
13144 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
13145 << ED;
13146 }
13147
13148 // Compute the required bitwidth. If the enum has negative values, we need
13149 // one more bit than the normal number of positive bits to represent the
13150 // sign bit.
13151 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
13152 ED->getNumNegativeBits())
13153 : ED->getNumPositiveBits();
13154
13155 // Check the bitwidth.
13156 if (BitsNeeded > FieldWidth) {
13157 Expr *WidthExpr = Bitfield->getBitWidth();
13158 auto DiagID =
13159 PTAttr == nullptr
13160 ? diag::warn_bitfield_too_small_for_enum
13161 : diag::warn_preferred_type_bitfield_too_small_for_enum;
13162 S.Diag(InitLoc, DiagID) << Bitfield << ED;
13163 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
13164 << BitsNeeded << ED << WidthExpr->getSourceRange();
13165 if (PTAttr)
13166 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
13167 << ED;
13168 }
13169 }
13170
13171 return false;
13172 }
13173
13174 llvm::APSInt Value = Result.Val.getInt();
13175
13176 unsigned OriginalWidth = Value.getBitWidth();
13177
13178 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
13179 // false positives where the user is demonstrating they intend to use the
13180 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
13181 // to a one-bit bit-field to see if the value came from a macro named 'true'.
13182 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
13183 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
13184 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
13185 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
13186 S.findMacroSpelling(MaybeMacroLoc, "true"))
13187 return false;
13188 }
13189
13190 if (!Value.isSigned() || Value.isNegative())
13191 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
13192 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
13193 OriginalWidth = Value.getSignificantBits();
13194
13195 if (OriginalWidth <= FieldWidth)
13196 return false;
13197
13198 // Compute the value which the bitfield will contain.
13199 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
13200 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
13201
13202 // Check whether the stored value is equal to the original value.
13203 TruncatedValue = TruncatedValue.extend(OriginalWidth);
13204 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
13205 return false;
13206
13207 std::string PrettyValue = toString(Value, 10);
13208 std::string PrettyTrunc = toString(TruncatedValue, 10);
13209
13210 S.Diag(InitLoc, OneAssignedToOneBitBitfield
13211 ? diag::warn_impcast_single_bit_bitield_precision_constant
13212 : diag::warn_impcast_bitfield_precision_constant)
13213 << PrettyValue << PrettyTrunc << OriginalInit->getType()
13214 << Init->getSourceRange();
13215
13216 return true;
13217}
13218
13219/// Analyze the given simple or compound assignment for warning-worthy
13220/// operations.
13222 // Just recurse on the LHS.
13224
13225 // We want to recurse on the RHS as normal unless we're assigning to
13226 // a bitfield.
13227 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
13228 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
13229 E->getOperatorLoc())) {
13230 // Recurse, ignoring any implicit conversions on the RHS.
13232 E->getOperatorLoc());
13233 }
13234 }
13235
13236 // Set context flag for overflow behavior type assignment analysis, use RAII
13237 // pattern to handle nested assignments.
13238 llvm::SaveAndRestore OBTAssignmentContext(
13240
13242
13243 // Diagnose implicitly sequentially-consistent atomic assignment.
13244 if (E->getLHS()->getType()->isAtomicType())
13245 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13246}
13247
13248/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
13249static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
13250 QualType T, SourceLocation CContext, unsigned diag,
13251 bool PruneControlFlow = false) {
13252 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
13253 // address space annotations isn't really useful. The warnings aren't because
13254 // you're converting a `private int` to `unsigned int`, it is because you're
13255 // conerting `int` to `unsigned int`.
13256 if (SourceType.hasAddressSpace())
13257 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
13258 if (T.hasAddressSpace())
13260 if (PruneControlFlow) {
13262 S.PDiag(diag)
13263 << SourceType << T << E->getSourceRange()
13264 << SourceRange(CContext));
13265 return;
13266 }
13267 S.Diag(E->getExprLoc(), diag)
13268 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
13269}
13270
13271/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
13272static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
13273 SourceLocation CContext, unsigned diag,
13274 bool PruneControlFlow = false) {
13275 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
13276}
13277
13278/// Diagnose an implicit cast from a floating point value to an integer value.
13279static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
13280 SourceLocation CContext) {
13281 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
13282 bool PruneWarnings = S.inTemplateInstantiation();
13283
13284 const Expr *InnerE = E->IgnoreParenImpCasts();
13285 // We also want to warn on, e.g., "int i = -1.234"
13286 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
13287 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
13288 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
13289
13290 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
13291
13292 llvm::APFloat Value(0.0);
13293 bool IsConstant =
13295 if (!IsConstant) {
13296 if (S.ObjC().isSignedCharBool(T)) {
13298 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
13299 << E->getType());
13300 }
13301
13302 return DiagnoseImpCast(S, E, T, CContext,
13303 diag::warn_impcast_float_integer, PruneWarnings);
13304 }
13305
13306 bool isExact = false;
13307
13308 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
13309 T->hasUnsignedIntegerRepresentation());
13310 llvm::APFloat::opStatus Result = Value.convertToInteger(
13311 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
13312
13313 // FIXME: Force the precision of the source value down so we don't print
13314 // digits which are usually useless (we don't really care here if we
13315 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
13316 // would automatically print the shortest representation, but it's a bit
13317 // tricky to implement.
13318 SmallString<16> PrettySourceValue;
13319 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
13320 precision = (precision * 59 + 195) / 196;
13321 Value.toString(PrettySourceValue, precision);
13322
13323 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
13325 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
13326 << PrettySourceValue);
13327 }
13328
13329 if (Result == llvm::APFloat::opOK && isExact) {
13330 if (IsLiteral) return;
13331 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
13332 PruneWarnings);
13333 }
13334
13335 // Conversion of a floating-point value to a non-bool integer where the
13336 // integral part cannot be represented by the integer type is undefined.
13337 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
13338 return DiagnoseImpCast(
13339 S, E, T, CContext,
13340 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
13341 : diag::warn_impcast_float_to_integer_out_of_range,
13342 PruneWarnings);
13343
13344 unsigned DiagID = 0;
13345 if (IsLiteral) {
13346 // Warn on floating point literal to integer.
13347 DiagID = diag::warn_impcast_literal_float_to_integer;
13348 } else if (IntegerValue == 0) {
13349 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
13350 return DiagnoseImpCast(S, E, T, CContext,
13351 diag::warn_impcast_float_integer, PruneWarnings);
13352 }
13353 // Warn on non-zero to zero conversion.
13354 DiagID = diag::warn_impcast_float_to_integer_zero;
13355 } else {
13356 if (IntegerValue.isUnsigned()) {
13357 if (!IntegerValue.isMaxValue()) {
13358 return DiagnoseImpCast(S, E, T, CContext,
13359 diag::warn_impcast_float_integer, PruneWarnings);
13360 }
13361 } else { // IntegerValue.isSigned()
13362 if (!IntegerValue.isMaxSignedValue() &&
13363 !IntegerValue.isMinSignedValue()) {
13364 return DiagnoseImpCast(S, E, T, CContext,
13365 diag::warn_impcast_float_integer, PruneWarnings);
13366 }
13367 }
13368 // Warn on evaluatable floating point expression to integer conversion.
13369 DiagID = diag::warn_impcast_float_to_integer;
13370 }
13371
13372 SmallString<16> PrettyTargetValue;
13373 if (IsBool)
13374 PrettyTargetValue = Value.isZero() ? "false" : "true";
13375 else
13376 IntegerValue.toString(PrettyTargetValue);
13377
13378 if (PruneWarnings) {
13380 S.PDiag(DiagID)
13381 << E->getType() << T.getUnqualifiedType()
13382 << PrettySourceValue << PrettyTargetValue
13383 << E->getSourceRange() << SourceRange(CContext));
13384 } else {
13385 S.Diag(E->getExprLoc(), DiagID)
13386 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
13387 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
13388 }
13389}
13390
13391/// Analyze the given compound assignment for the possible losing of
13392/// floating-point precision.
13394 assert(isa<CompoundAssignOperator>(E) &&
13395 "Must be compound assignment operation");
13396 // Recurse on the LHS and RHS in here
13399
13400 if (E->getLHS()->getType()->isAtomicType())
13401 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
13402
13403 // Now check the outermost expression
13404 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
13405 const auto *RBT = cast<CompoundAssignOperator>(E)
13406 ->getComputationResultType()
13407 ->getAs<BuiltinType>();
13408
13409 // The below checks assume source is floating point.
13410 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
13411
13412 // If source is floating point but target is an integer.
13413 if (ResultBT->isInteger())
13414 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
13415 E->getExprLoc(), diag::warn_impcast_float_integer);
13416
13417 if (!ResultBT->isFloatingPoint())
13418 return;
13419
13420 // If both source and target are floating points, warn about losing precision.
13422 QualType(ResultBT, 0), QualType(RBT, 0));
13423 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
13424 // warn about dropping FP rank.
13425 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
13426 diag::warn_impcast_float_result_precision);
13427}
13428
13429static std::string PrettyPrintInRange(const llvm::APSInt &Value,
13430 IntRange Range) {
13431 if (!Range.Width) return "0";
13432
13433 llvm::APSInt ValueInRange = Value;
13434 ValueInRange.setIsSigned(!Range.NonNegative);
13435 ValueInRange = ValueInRange.trunc(Range.Width);
13436 return toString(ValueInRange, 10);
13437}
13438
13439static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
13440 bool ToBool) {
13441 if (!isa<ImplicitCastExpr>(Ex))
13442 return false;
13443
13444 const Expr *InnerE = Ex->IgnoreParenImpCasts();
13446 const Type *Source =
13448 if (Target->isDependentType())
13449 return false;
13450
13451 const auto *FloatCandidateBT =
13452 dyn_cast<BuiltinType>(ToBool ? Source : Target);
13453 const Type *BoolCandidateType = ToBool ? Target : Source;
13454
13455 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
13456 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
13457}
13458
13459static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
13460 SourceLocation CC) {
13461 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
13462 const Expr *CurrA = TheCall->getArg(I);
13463 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
13464 continue;
13465
13466 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
13467 S, TheCall->getArg(I - 1), false));
13468 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
13469 S, TheCall->getArg(I + 1), false));
13470 if (IsSwapped) {
13471 // Warn on this floating-point to bool conversion.
13473 CurrA->getType(), CC,
13474 diag::warn_impcast_floating_point_to_bool);
13475 }
13476 }
13477}
13478
13480 SourceLocation CC) {
13481 // Don't warn on functions which have return type nullptr_t.
13482 if (isa<CallExpr>(E))
13483 return;
13484
13485 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
13486 const Expr *NewE = E->IgnoreParenImpCasts();
13487 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
13488 bool HasNullPtrType = NewE->getType()->isNullPtrType();
13489 if (!IsGNUNullExpr && !HasNullPtrType)
13490 return;
13491
13492 // Return if target type is a safe conversion.
13493 if (T->isAnyPointerType() || T->isBlockPointerType() ||
13494 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
13495 return;
13496
13497 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
13498 E->getExprLoc()))
13499 return;
13500
13502
13503 // Venture through the macro stacks to get to the source of macro arguments.
13504 // The new location is a better location than the complete location that was
13505 // passed in.
13506 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
13508
13509 // __null is usually wrapped in a macro. Go up a macro if that is the case.
13510 if (IsGNUNullExpr && Loc.isMacroID()) {
13511 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13512 Loc, S.SourceMgr, S.getLangOpts());
13513 if (MacroName == "NULL")
13515 }
13516
13517 // Only warn if the null and context location are in the same macro expansion.
13518 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
13519 return;
13520
13521 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
13522 << HasNullPtrType << T << SourceRange(CC)
13525}
13526
13527// Helper function to filter out cases for constant width constant conversion.
13528// Don't warn on unsigned char array initialization or for non-decimal
13529// values.
13531 SourceLocation CC) {
13532 // If initializing from a constant, and the constant starts with '0',
13533 // then it is a binary, octal, or hexadecimal. Allow these constants
13534 // to fill all the bits, even if there is a sign change.
13535 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
13536 const char FirstLiteralCharacter =
13537 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
13538 if (FirstLiteralCharacter == '0')
13539 return false;
13540 }
13541
13542 // If the CC location points to a '{' and the type is an unsigned char
13543 // type, assume it is an array initialization.
13544 if (T->isCharType() && !T->isSignedIntegerType() && CC.isValid()) {
13545 const char FirstContextCharacter =
13547 if (FirstContextCharacter == '{')
13548 return false;
13549 }
13550
13551 return true;
13552}
13553
13555 const auto *IL = dyn_cast<IntegerLiteral>(E);
13556 if (!IL) {
13557 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
13558 if (UO->getOpcode() == UO_Minus)
13559 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13560 }
13561 }
13562
13563 return IL;
13564}
13565
13567 E = E->IgnoreParenImpCasts();
13568 SourceLocation ExprLoc = E->getExprLoc();
13569
13570 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13571 BinaryOperator::Opcode Opc = BO->getOpcode();
13573 // Do not diagnose unsigned shifts.
13574 if (Opc == BO_Shl) {
13575 const auto *LHS = getIntegerLiteral(BO->getLHS());
13576 const auto *RHS = getIntegerLiteral(BO->getRHS());
13577 if (LHS && LHS->getValue() == 0)
13578 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13579 else if (!E->isValueDependent() && LHS && RHS &&
13580 RHS->getValue().isNonNegative() &&
13582 S.Diag(ExprLoc, diag::warn_left_shift_always)
13583 << (Result.Val.getInt() != 0);
13584 else if (E->getType()->isSignedIntegerType())
13585 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
13588 ") != 0");
13589 }
13590 }
13591
13592 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13593 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13594 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13595 if (!LHS || !RHS)
13596 return;
13597 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13598 (RHS->getValue() == 0 || RHS->getValue() == 1))
13599 // Do not diagnose common idioms.
13600 return;
13601 if (LHS->getValue() != 0 && RHS->getValue() != 0)
13602 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13603 }
13604}
13605
13607 const Type *Target, Expr *E,
13608 QualType T,
13609 SourceLocation CC) {
13610 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
13611 Source != Target);
13612
13613 // Lone surrogates have a distinct representation in UTF-32.
13614 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
13615 // so don't warn on such conversion.
13616 if (Source->isChar16Type() && Target->isChar32Type())
13617 return;
13618
13622 llvm::APSInt Value(32);
13623 Value = Result.Val.getInt();
13624 bool IsASCII = Value <= 0x7F;
13625 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
13626 bool ConversionPreservesSemantics =
13627 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
13628
13629 if (!ConversionPreservesSemantics) {
13630 auto IsSingleCodeUnitCP = [](const QualType &T,
13631 const llvm::APSInt &Value) {
13632 if (T->isChar8Type())
13633 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
13634 if (T->isChar16Type())
13635 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
13636 assert(T->isChar32Type());
13637 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
13638 };
13639
13640 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
13641 << E->getType() << T
13642 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
13643 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
13644 }
13645 } else {
13646 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
13648 DiagnoseImpCast(S, E, T, CC,
13649 LosesPrecision ? diag::warn_impcast_unicode_precision
13650 : diag::warn_impcast_unicode_char_type);
13651 }
13652}
13653
13655 From = Context.getCanonicalType(From);
13656 To = Context.getCanonicalType(To);
13657 QualType MaybePointee = From->getPointeeType();
13658 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13659 From = MaybePointee;
13660 MaybePointee = To->getPointeeType();
13661 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13662 To = MaybePointee;
13663
13664 if (const auto *FromFn = From->getAs<FunctionType>()) {
13665 if (const auto *ToFn = To->getAs<FunctionType>()) {
13666 if (FromFn->getCFIUncheckedCalleeAttr() &&
13667 !ToFn->getCFIUncheckedCalleeAttr())
13668 return true;
13669 }
13670 }
13671 return false;
13672}
13673
13675 bool *ICContext, bool IsListInit) {
13676 if (E->isTypeDependent() || E->isValueDependent()) return;
13677
13678 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
13679 const Type *Target = Context.getCanonicalType(T).getTypePtr();
13680 if (Source == Target) return;
13681 if (Target->isDependentType()) return;
13682
13683 // If the conversion context location is invalid don't complain. We also
13684 // don't want to emit a warning if the issue occurs from the expansion of
13685 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13686 // delay this check as long as possible. Once we detect we are in that
13687 // scenario, we just return.
13688 if (CC.isInvalid())
13689 return;
13690
13691 if (Source->isAtomicType())
13692 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13693
13694 // Diagnose implicit casts to bool.
13695 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13696 if (isa<StringLiteral>(E))
13697 // Warn on string literal to bool. Checks for string literals in logical
13698 // and expressions, for instance, assert(0 && "error here"), are
13699 // prevented by a check in AnalyzeImplicitConversions().
13700 return DiagnoseImpCast(*this, E, T, CC,
13701 diag::warn_impcast_string_literal_to_bool);
13704 // This covers the literal expressions that evaluate to Objective-C
13705 // objects.
13706 return DiagnoseImpCast(*this, E, T, CC,
13707 diag::warn_impcast_objective_c_literal_to_bool);
13708 }
13709 if (Source->isPointerType() || Source->canDecayToPointerType()) {
13710 // Warn on pointer to bool conversion that is always true.
13712 SourceRange(CC));
13713 }
13714 }
13715
13717
13718 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13719 // is a typedef for signed char (macOS), then that constant value has to be 1
13720 // or 0.
13721 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
13724 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13726 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13727 << toString(Result.Val.getInt(), 10));
13728 }
13729 return;
13730 }
13731 }
13732
13733 // Check implicit casts from Objective-C collection literals to specialized
13734 // collection types, e.g., NSArray<NSString *> *.
13735 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13736 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
13737 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13738 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
13739
13740 // Strip complex types.
13741 if (isa<ComplexType>(Source)) {
13742 if (!isa<ComplexType>(Target)) {
13743 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13744 return;
13745
13746 if (!getLangOpts().CPlusPlus && Target->isVectorType()) {
13747 return DiagnoseImpCast(*this, E, T, CC,
13748 diag::err_impcast_incompatible_type);
13749 }
13750
13751 return DiagnoseImpCast(*this, E, T, CC,
13753 ? diag::err_impcast_complex_scalar
13754 : diag::warn_impcast_complex_scalar);
13755 }
13756
13757 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13758 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13759 }
13760
13761 // Strip vector types.
13762 if (isa<VectorType>(Source)) {
13763 if (Target->isSveVLSBuiltinType() &&
13764 (ARM().areCompatibleSveTypes(QualType(Target, 0),
13765 QualType(Source, 0)) ||
13766 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
13767 QualType(Source, 0))))
13768 return;
13769
13770 if (Target->isRVVVLSBuiltinType() &&
13771 (Context.areCompatibleRVVTypes(QualType(Target, 0),
13772 QualType(Source, 0)) ||
13773 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
13774 QualType(Source, 0))))
13775 return;
13776
13777 if (!isa<VectorType>(Target)) {
13778 if (SourceMgr.isInSystemMacro(CC))
13779 return;
13780 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
13781 }
13782 if (getLangOpts().HLSL &&
13783 Target->castAs<VectorType>()->getNumElements() <
13784 Source->castAs<VectorType>()->getNumElements()) {
13785 // Diagnose vector truncation but don't return. We may also want to
13786 // diagnose an element conversion.
13787 DiagnoseImpCast(*this, E, T, CC,
13788 diag::warn_hlsl_impcast_vector_truncation);
13789 }
13790
13791 // If the vector cast is cast between two vectors of the same size, it is
13792 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13793 if (!getLangOpts().HLSL &&
13794 Context.getTypeSize(Source) == Context.getTypeSize(Target))
13795 return;
13796
13797 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13798 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13799 }
13800 if (const auto *VecTy = dyn_cast<VectorType>(Target))
13801 Target = VecTy->getElementType().getTypePtr();
13802
13803 // Strip matrix types.
13804 if (isa<ConstantMatrixType>(Source)) {
13805 if (Target->isScalarType())
13806 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_matrix_scalar);
13807
13810 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13811 // Diagnose Matrix truncation but don't return. We may also want to
13812 // diagnose an element conversion.
13813 DiagnoseImpCast(*this, E, T, CC,
13814 diag::warn_hlsl_impcast_matrix_truncation);
13815 }
13816
13817 Source = cast<ConstantMatrixType>(Source)->getElementType().getTypePtr();
13818 Target = cast<ConstantMatrixType>(Target)->getElementType().getTypePtr();
13819 }
13820 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Target))
13821 Target = MatTy->getElementType().getTypePtr();
13822
13823 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13824 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13825
13826 // Strip SVE vector types
13827 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13828 // Need the original target type for vector type checks
13829 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13830 // Handle conversion from scalable to fixed when msve-vector-bits is
13831 // specified
13832 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
13833 QualType(Source, 0)) ||
13834 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
13835 QualType(Source, 0)))
13836 return;
13837
13838 // If the vector cast is cast between two vectors of the same size, it is
13839 // a bitcast, not a conversion.
13840 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
13841 return;
13842
13843 Source = SourceBT->getSveEltType(Context).getTypePtr();
13844 }
13845
13846 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13847 Target = TargetBT->getSveEltType(Context).getTypePtr();
13848
13849 // Nothing to diagnose if stripping the wrappers left identical element types
13850 // (e.g. a scalar splatted to a vector of its own type).
13851 if (Source == Target)
13852 return;
13853
13854 // If the source is floating point...
13855 if (SourceBT && SourceBT->isFloatingPoint()) {
13856 // ...and the target is floating point...
13857 if (TargetBT && TargetBT->isFloatingPoint()) {
13858 // ...then warn if we're dropping FP rank.
13859
13861 QualType(SourceBT, 0), QualType(TargetBT, 0));
13862 if (Order > 0) {
13863 // Don't warn about float constants that are precisely
13864 // representable in the target type.
13865 Expr::EvalResult result;
13866 if (E->EvaluateAsRValue(result, Context)) {
13867 // Value might be a float, a float vector, or a float complex.
13869 result.Val,
13870 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13871 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13872 return;
13873 }
13874
13875 if (SourceMgr.isInSystemMacro(CC))
13876 return;
13877
13878 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
13879 }
13880 // ... or possibly if we're increasing rank, too
13881 else if (Order < 0) {
13882 if (SourceMgr.isInSystemMacro(CC))
13883 return;
13884
13885 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
13886 }
13887 return;
13888 }
13889
13890 // If the target is integral, always warn.
13891 if (TargetBT && TargetBT->isInteger()) {
13892 if (SourceMgr.isInSystemMacro(CC))
13893 return;
13894
13895 DiagnoseFloatingImpCast(*this, E, T, CC);
13896 }
13897
13898 // Detect the case where a call result is converted from floating-point to
13899 // to bool, and the final argument to the call is converted from bool, to
13900 // discover this typo:
13901 //
13902 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13903 //
13904 // FIXME: This is an incredibly special case; is there some more general
13905 // way to detect this class of misplaced-parentheses bug?
13906 if (Target->isBooleanType() && isa<CallExpr>(E)) {
13907 // Check last argument of function call to see if it is an
13908 // implicit cast from a type matching the type the result
13909 // is being cast to.
13910 CallExpr *CEx = cast<CallExpr>(E);
13911 if (unsigned NumArgs = CEx->getNumArgs()) {
13912 Expr *LastA = CEx->getArg(NumArgs - 1);
13913 Expr *InnerE = LastA->IgnoreParenImpCasts();
13914 if (isa<ImplicitCastExpr>(LastA) &&
13915 InnerE->getType()->isBooleanType()) {
13916 // Warn on this floating-point to bool conversion
13917 DiagnoseImpCast(*this, E, T, CC,
13918 diag::warn_impcast_floating_point_to_bool);
13919 }
13920 }
13921 }
13922 return;
13923 }
13924
13925 // Valid casts involving fixed point types should be accounted for here.
13926 if (Source->isFixedPointType()) {
13927 if (Target->isUnsaturatedFixedPointType()) {
13931 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13932 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
13933 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
13934 if (Value > MaxVal || Value < MinVal) {
13936 PDiag(diag::warn_impcast_fixed_point_range)
13937 << Value.toString() << T
13938 << E->getSourceRange()
13939 << clang::SourceRange(CC));
13940 return;
13941 }
13942 }
13943 } else if (Target->isIntegerType()) {
13947 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13948
13949 bool Overflowed;
13950 llvm::APSInt IntResult = FXResult.convertToInt(
13951 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
13952 &Overflowed);
13953
13954 if (Overflowed) {
13956 PDiag(diag::warn_impcast_fixed_point_range)
13957 << FXResult.toString() << T
13958 << E->getSourceRange()
13959 << clang::SourceRange(CC));
13960 return;
13961 }
13962 }
13963 }
13964 } else if (Target->isUnsaturatedFixedPointType()) {
13965 if (Source->isIntegerType()) {
13969 llvm::APSInt Value = Result.Val.getInt();
13970
13971 bool Overflowed;
13972 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13973 Value, Context.getFixedPointSemantics(T), &Overflowed);
13974
13975 if (Overflowed) {
13977 PDiag(diag::warn_impcast_fixed_point_range)
13978 << toString(Value, /*Radix=*/10) << T
13979 << E->getSourceRange()
13980 << clang::SourceRange(CC));
13981 return;
13982 }
13983 }
13984 }
13985 }
13986
13987 // If we are casting an integer type to a floating point type without
13988 // initialization-list syntax, we might lose accuracy if the floating
13989 // point type has a narrower significand than the integer type.
13990 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13991 TargetBT->isFloatingType() && !IsListInit) {
13992 // Determine the number of precision bits in the source integer type.
13993 std::optional<IntRange> SourceRange =
13995 /*Approximate=*/true);
13996 if (!SourceRange)
13997 return;
13998 unsigned int SourcePrecision = SourceRange->Width;
13999
14000 // Determine the number of precision bits in the
14001 // target floating point type.
14002 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
14003 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
14004
14005 if (SourcePrecision > 0 && TargetPrecision > 0 &&
14006 SourcePrecision > TargetPrecision) {
14007
14008 if (std::optional<llvm::APSInt> SourceInt =
14010 // If the source integer is a constant, convert it to the target
14011 // floating point type. Issue a warning if the value changes
14012 // during the whole conversion.
14013 llvm::APFloat TargetFloatValue(
14014 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
14015 llvm::APFloat::opStatus ConversionStatus =
14016 TargetFloatValue.convertFromAPInt(
14017 *SourceInt, SourceBT->isSignedInteger(),
14018 llvm::APFloat::rmNearestTiesToEven);
14019
14020 if (ConversionStatus != llvm::APFloat::opOK) {
14021 SmallString<32> PrettySourceValue;
14022 SourceInt->toString(PrettySourceValue, 10);
14023 SmallString<32> PrettyTargetValue;
14024 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
14025
14027 E->getExprLoc(), E,
14028 PDiag(diag::warn_impcast_integer_float_precision_constant)
14029 << PrettySourceValue << PrettyTargetValue << E->getType() << T
14030 << E->getSourceRange() << clang::SourceRange(CC));
14031 }
14032 } else {
14033 // Otherwise, the implicit conversion may lose precision.
14034 DiagnoseImpCast(*this, E, T, CC,
14035 diag::warn_impcast_integer_float_precision);
14036 }
14037 }
14038 }
14039
14040 DiagnoseNullConversion(*this, E, T, CC);
14041
14043
14044 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
14045 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
14046 return;
14047 }
14048
14049 if (Target->isBooleanType())
14050 DiagnoseIntInBoolContext(*this, E);
14051
14053 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
14054 << QualType(Source, 0) << QualType(Target, 0);
14055 }
14056
14057 if (!Source->isIntegerType() || !Target->isIntegerType())
14058 return;
14059
14060 // TODO: remove this early return once the false positives for constant->bool
14061 // in templates, macros, etc, are reduced or removed.
14062 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
14063 return;
14064
14065 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
14066 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
14068 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
14069 << E->getType());
14070 }
14071 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
14072 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
14073 if (!LikelySourceRange)
14074 return;
14075
14076 IntRange SourceTypeRange =
14077 IntRange::forTargetOfCanonicalType(Context, Source);
14078 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
14079
14080 if (LikelySourceRange->Width > TargetRange.Width) {
14081 // Check if target is a wrapping OBT - if so, don't warn about constant
14082 // conversion as this type may be used intentionally with implicit
14083 // truncation, especially during assignments.
14084 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14085 if (TargetOBT->isWrapKind()) {
14086 return;
14087 }
14088 }
14089
14090 // Check if source expression has an explicit __ob_wrap cast because if so,
14091 // wrapping was explicitly requested and we shouldn't warn
14092 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
14093 if (SourceOBT->isWrapKind()) {
14094 return;
14095 }
14096 }
14097
14098 // If the source is a constant, use a default-on diagnostic.
14099 // TODO: this should happen for bitfield stores, too.
14103 llvm::APSInt Value(32);
14104 Value = Result.Val.getInt();
14105
14106 if (SourceMgr.isInSystemMacro(CC))
14107 return;
14108
14109 std::string PrettySourceValue = toString(Value, 10);
14110 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
14111
14113 PDiag(diag::warn_impcast_integer_precision_constant)
14114 << PrettySourceValue << PrettyTargetValue
14115 << E->getType() << T << E->getSourceRange()
14116 << SourceRange(CC));
14117 return;
14118 }
14119
14120 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
14121 if (SourceMgr.isInSystemMacro(CC))
14122 return;
14123
14124 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
14125 if (UO->getOpcode() == UO_Minus)
14126 return DiagnoseImpCast(
14127 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
14128 }
14129
14130 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
14131 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
14132 /* pruneControlFlow */ true);
14133 return DiagnoseImpCast(*this, E, T, CC,
14134 diag::warn_impcast_integer_precision);
14135 }
14136
14137 if (TargetRange.Width > SourceTypeRange.Width) {
14138 if (auto *UO = dyn_cast<UnaryOperator>(E))
14139 if (UO->getOpcode() == UO_Minus)
14140 if (Source->isUnsignedIntegerType()) {
14141 if (Target->isUnsignedIntegerType())
14142 return DiagnoseImpCast(*this, E, T, CC,
14143 diag::warn_impcast_high_order_zero_bits);
14144 if (Target->isSignedIntegerType())
14145 return DiagnoseImpCast(*this, E, T, CC,
14146 diag::warn_impcast_nonnegative_result);
14147 }
14148 }
14149
14150 if (TargetRange.Width == LikelySourceRange->Width &&
14151 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
14152 Source->isSignedIntegerType()) {
14153 // Warn when doing a signed to signed conversion, warn if the positive
14154 // source value is exactly the width of the target type, which will
14155 // cause a negative value to be stored.
14156
14159 !SourceMgr.isInSystemMacro(CC)) {
14160 llvm::APSInt Value = Result.Val.getInt();
14161 if (isSameWidthConstantConversion(*this, E, T, CC)) {
14162 std::string PrettySourceValue = toString(Value, 10);
14163 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
14164
14165 Diag(E->getExprLoc(),
14166 PDiag(diag::warn_impcast_integer_precision_constant)
14167 << PrettySourceValue << PrettyTargetValue << E->getType() << T
14168 << E->getSourceRange() << SourceRange(CC));
14169 return;
14170 }
14171 }
14172
14173 // Fall through for non-constants to give a sign conversion warning.
14174 }
14175
14176 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
14177 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
14178 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
14179 LikelySourceRange->Width == TargetRange.Width))) {
14180 if (SourceMgr.isInSystemMacro(CC))
14181 return;
14182
14183 if (SourceBT && SourceBT->isInteger() && TargetBT &&
14184 TargetBT->isInteger() &&
14185 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
14186 return;
14187 }
14188
14189 unsigned DiagID = diag::warn_impcast_integer_sign;
14190
14191 // Traditionally, gcc has warned about this under -Wsign-compare.
14192 // We also want to warn about it in -Wconversion.
14193 // So if -Wconversion is off, use a completely identical diagnostic
14194 // in the sign-compare group.
14195 // The conditional-checking code will
14196 if (ICContext) {
14197 DiagID = diag::warn_impcast_integer_sign_conditional;
14198 *ICContext = true;
14199 }
14200
14201 DiagnoseImpCast(*this, E, T, CC, DiagID);
14202 }
14203
14204 // If we're implicitly converting from an integer into an enumeration, that
14205 // is valid in C but invalid in C++.
14206 QualType SourceType = E->getEnumCoercedType(Context);
14207 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
14208 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
14209 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
14210
14211 // Diagnose conversions between different enumeration types.
14212 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
14213 // type, to give us better diagnostics.
14214 Source = Context.getCanonicalType(SourceType).getTypePtr();
14215
14216 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
14217 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
14218 if (SourceEnum->getDecl()->hasNameForLinkage() &&
14219 TargetEnum->getDecl()->hasNameForLinkage() &&
14220 SourceEnum != TargetEnum) {
14221 if (SourceMgr.isInSystemMacro(CC))
14222 return;
14223
14224 return DiagnoseImpCast(*this, E, SourceType, T, CC,
14225 diag::warn_impcast_different_enum_types);
14226 }
14227}
14228
14231
14233 SourceLocation CC, bool &ICContext) {
14234 E = E->IgnoreParenImpCasts();
14235 // Diagnose incomplete type for second or third operand in C.
14236 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
14237 S.RequireCompleteExprType(E, diag::err_incomplete_type);
14238
14239 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
14240 return CheckConditionalOperator(S, CO, CC, T);
14241
14243 if (E->getType() != T)
14244 return S.CheckImplicitConversion(E, T, CC, &ICContext);
14245}
14246
14250
14251 Expr *TrueExpr = E->getTrueExpr();
14252 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
14253 TrueExpr = BCO->getCommon();
14254
14255 bool Suspicious = false;
14256 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
14257 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
14258
14259 if (T->isBooleanType())
14261
14262 // If -Wconversion would have warned about either of the candidates
14263 // for a signedness conversion to the context type...
14264 if (!Suspicious) return;
14265
14266 // ...but it's currently ignored...
14267 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
14268 return;
14269
14270 // ...then check whether it would have warned about either of the
14271 // candidates for a signedness conversion to the condition type.
14272 if (E->getType() == T) return;
14273
14274 Suspicious = false;
14275 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
14276 &Suspicious);
14277 if (!Suspicious)
14279 E->getType(), CC, &Suspicious);
14280}
14281
14282/// Check conversion of given expression to boolean.
14283/// Input argument E is a logical expression.
14285 // Run the bool-like conversion checks only for C since there bools are
14286 // still not used as the return type from "boolean" operators or as the input
14287 // type for conditional operators.
14288 if (S.getLangOpts().CPlusPlus)
14289 return;
14291 return;
14293}
14294
14295namespace {
14296struct AnalyzeImplicitConversionsWorkItem {
14297 Expr *E;
14298 SourceLocation CC;
14299 bool IsListInit;
14300};
14301}
14302
14304 Sema &S, Expr *E, QualType T, SourceLocation CC,
14305 bool ExtraCheckForImplicitConversion,
14307 E = E->IgnoreParenImpCasts();
14308 WorkList.push_back({E, CC, false});
14309
14310 if (ExtraCheckForImplicitConversion && E->getType() != T)
14311 S.CheckImplicitConversion(E, T, CC);
14312}
14313
14314/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
14315/// that should be visited are added to WorkList.
14317 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
14319 Expr *OrigE = Item.E;
14320 SourceLocation CC = Item.CC;
14321
14322 QualType T = OrigE->getType();
14323 Expr *E = OrigE->IgnoreParenImpCasts();
14324
14325 // Propagate whether we are in a C++ list initialization expression.
14326 // If so, we do not issue warnings for implicit int-float conversion
14327 // precision loss, because C++11 narrowing already handles it.
14328 //
14329 // HLSL's initialization lists are special, so they shouldn't observe the C++
14330 // behavior here.
14331 bool IsListInit =
14332 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
14333 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
14334
14335 if (E->isTypeDependent() || E->isValueDependent())
14336 return;
14337
14338 Expr *SourceExpr = E;
14339 // Examine, but don't traverse into the source expression of an
14340 // OpaqueValueExpr, since it may have multiple parents and we don't want to
14341 // emit duplicate diagnostics. Its fine to examine the form or attempt to
14342 // evaluate it in the context of checking the specific conversion to T though.
14343 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
14344 if (auto *Src = OVE->getSourceExpr())
14345 SourceExpr = Src;
14346
14347 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
14348 if (UO->getOpcode() == UO_Not &&
14349 UO->getSubExpr()->isKnownToHaveBooleanValue())
14350 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
14351 << OrigE->getSourceRange() << T->isBooleanType()
14352 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
14353
14354 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
14355 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
14356 BO->getLHS()->isKnownToHaveBooleanValue() &&
14357 BO->getRHS()->isKnownToHaveBooleanValue() &&
14358 BO->getLHS()->HasSideEffects(S.Context) &&
14359 BO->getRHS()->HasSideEffects(S.Context)) {
14361 const LangOptions &LO = S.getLangOpts();
14362 SourceLocation BLoc = BO->getOperatorLoc();
14363 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
14364 StringRef SR = clang::Lexer::getSourceText(
14365 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
14366 // To reduce false positives, only issue the diagnostic if the operator
14367 // is explicitly spelled as a punctuator. This suppresses the diagnostic
14368 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
14369 // in C, along with other macro spellings the user might invent.
14370 if (SR.str() == "&" || SR.str() == "|") {
14371
14372 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
14373 << (BO->getOpcode() == BO_And ? "&" : "|")
14374 << OrigE->getSourceRange()
14376 BO->getOperatorLoc(),
14377 (BO->getOpcode() == BO_And ? "&&" : "||"));
14378 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
14379 }
14380 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
14381 /// Analyze the given comma operator. The basic idea behind the analysis
14382 /// is to analyze the left and right operands slightly differently. The
14383 /// left operand needs to check whether the operand itself has an implicit
14384 /// conversion, but not whether the left operand induces an implicit
14385 /// conversion for the entire comma expression itself. This is similar to
14386 /// how CheckConditionalOperand behaves; it's as-if the correct operand
14387 /// were directly used for the implicit conversion check.
14388 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
14389 /*ExtraCheckForImplicitConversion=*/false, WorkList);
14390 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
14391 /*ExtraCheckForImplicitConversion=*/true, WorkList);
14392 return;
14393 }
14394 }
14395
14396 // For conditional operators, we analyze the arguments as if they
14397 // were being fed directly into the output.
14398 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
14399 CheckConditionalOperator(S, CO, CC, T);
14400 return;
14401 }
14402
14403 // Check implicit argument conversions for function calls.
14404 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
14406
14407 // Go ahead and check any implicit conversions we might have skipped.
14408 // The non-canonical typecheck is just an optimization;
14409 // CheckImplicitConversion will filter out dead implicit conversions.
14410 if (SourceExpr->getType() != T)
14411 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
14412
14413 // Now continue drilling into this expression.
14414
14415 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
14416 // The bound subexpressions in a PseudoObjectExpr are not reachable
14417 // as transitive children.
14418 // FIXME: Use a more uniform representation for this.
14419 for (auto *SE : POE->semantics())
14420 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
14421 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
14422 }
14423
14424 // Skip past explicit casts.
14425 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
14426 E = CE->getSubExpr();
14427 // In the special case of a C++ function-style cast with braces,
14428 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
14429 // initializer. This InitListExpr basically belongs to the cast itself, so
14430 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
14432 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
14433 if (InitListE->getNumInits() == 1) {
14434 E = InitListE->getInit(0);
14435 }
14436 }
14437 }
14438 E = E->IgnoreParenImpCasts();
14439 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
14440 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
14441 WorkList.push_back({E, CC, IsListInit});
14442 return;
14443 }
14444
14445 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
14446 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
14447 // The base expression is only used to initialize the parameter for
14448 // arguments to `inout` parameters, so we only traverse down the base
14449 // expression for `inout` cases.
14450 if (OutArgE->isInOut())
14451 WorkList.push_back(
14452 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
14453 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
14454 return;
14455 }
14456
14457 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14458 // Do a somewhat different check with comparison operators.
14459 if (BO->isComparisonOp())
14460 return AnalyzeComparison(S, BO);
14461
14462 // And with simple assignments.
14463 if (BO->getOpcode() == BO_Assign)
14464 return AnalyzeAssignment(S, BO);
14465 // And with compound assignments.
14466 if (BO->isAssignmentOp())
14467 return AnalyzeCompoundAssignment(S, BO);
14468 }
14469
14470 // These break the otherwise-useful invariant below. Fortunately,
14471 // we don't really need to recurse into them, because any internal
14472 // expressions should have been analyzed already when they were
14473 // built into statements.
14474 if (isa<StmtExpr>(E)) return;
14475
14476 // Don't descend into unevaluated contexts.
14477 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
14478
14479 // Now just recurse over the expression's children.
14480 CC = E->getExprLoc();
14481 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
14482 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
14483 for (Stmt *SubStmt : E->children()) {
14484 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
14485 if (!ChildExpr)
14486 continue;
14487
14488 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
14489 if (ChildExpr == CSE->getOperand())
14490 // Do not recurse over a CoroutineSuspendExpr's operand.
14491 // The operand is also a subexpression of getCommonExpr(), and
14492 // recursing into it directly would produce duplicate diagnostics.
14493 continue;
14494
14495 if (IsLogicalAndOperator &&
14497 // Ignore checking string literals that are in logical and operators.
14498 // This is a common pattern for asserts.
14499 continue;
14500 WorkList.push_back({ChildExpr, CC, IsListInit});
14501 }
14502
14503 if (BO && BO->isLogicalOp()) {
14504 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
14505 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14506 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14507
14508 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
14509 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14510 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14511 }
14512
14513 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
14514 if (U->getOpcode() == UO_LNot) {
14515 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
14516 } else if (U->getOpcode() != UO_AddrOf) {
14517 if (U->getSubExpr()->getType()->isAtomicType())
14518 S.Diag(U->getSubExpr()->getBeginLoc(),
14519 diag::warn_atomic_implicit_seq_cst);
14520 }
14521 }
14522}
14523
14524/// AnalyzeImplicitConversions - Find and report any interesting
14525/// implicit conversions in the given expression. There are a couple
14526/// of competing diagnostics here, -Wconversion and -Wsign-compare.
14528 bool IsListInit/*= false*/) {
14530 WorkList.push_back({OrigE, CC, IsListInit});
14531 while (!WorkList.empty())
14532 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
14533}
14534
14535// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
14536// Returns true when emitting a warning about taking the address of a reference.
14537static bool CheckForReference(Sema &SemaRef, const Expr *E,
14538 const PartialDiagnostic &PD) {
14539 E = E->IgnoreParenImpCasts();
14540
14541 const FunctionDecl *FD = nullptr;
14542
14543 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14544 if (!DRE->getDecl()->getType()->isReferenceType())
14545 return false;
14546 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14547 if (!M->getMemberDecl()->getType()->isReferenceType())
14548 return false;
14549 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
14550 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
14551 return false;
14552 FD = Call->getDirectCallee();
14553 } else {
14554 return false;
14555 }
14556
14557 SemaRef.Diag(E->getExprLoc(), PD);
14558
14559 // If possible, point to location of function.
14560 if (FD) {
14561 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
14562 }
14563
14564 return true;
14565}
14566
14567// Returns true if the SourceLocation is expanded from any macro body.
14568// Returns false if the SourceLocation is invalid, is from not in a macro
14569// expansion, or is from expanded from a top-level macro argument.
14570static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
14571 if (Loc.isInvalid())
14572 return false;
14573
14574 while (Loc.isMacroID()) {
14575 if (SM.isMacroBodyExpansion(Loc))
14576 return true;
14577 Loc = SM.getImmediateMacroCallerLoc(Loc);
14578 }
14579
14580 return false;
14581}
14582
14585 bool IsEqual, SourceRange Range) {
14586 if (!E)
14587 return;
14588
14589 // Don't warn inside macros.
14590 if (E->getExprLoc().isMacroID()) {
14591 const SourceManager &SM = getSourceManager();
14592 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
14593 IsInAnyMacroBody(SM, Range.getBegin()))
14594 return;
14595 }
14596 E = E->IgnoreImpCasts();
14597
14598 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14599
14600 if (isa<CXXThisExpr>(E)) {
14601 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14602 : diag::warn_this_bool_conversion;
14603 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14604 return;
14605 }
14606
14607 bool IsAddressOf = false;
14608
14609 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
14610 if (UO->getOpcode() != UO_AddrOf)
14611 return;
14612 IsAddressOf = true;
14613 E = UO->getSubExpr();
14614 }
14615
14616 if (IsAddressOf) {
14617 unsigned DiagID = IsCompare
14618 ? diag::warn_address_of_reference_null_compare
14619 : diag::warn_address_of_reference_bool_conversion;
14620 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14621 << IsEqual;
14622 if (CheckForReference(*this, E, PD)) {
14623 return;
14624 }
14625 }
14626
14627 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14628 bool IsParam = isa<NonNullAttr>(NonnullAttr);
14629 std::string Str;
14630 llvm::raw_string_ostream S(Str);
14631 E->printPretty(S, nullptr, getPrintingPolicy());
14632 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14633 : diag::warn_cast_nonnull_to_bool;
14634 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
14635 << E->getSourceRange() << Range << IsEqual;
14636 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
14637 };
14638
14639 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14640 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
14641 if (auto *Callee = Call->getDirectCallee()) {
14642 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14643 ComplainAboutNonnullParamOrCall(A);
14644 return;
14645 }
14646 }
14647 }
14648
14649 // Complain if we are converting a lambda expression to a boolean value
14650 // outside of instantiation.
14651 if (!inTemplateInstantiation()) {
14652 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
14653 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
14654 MRecordDecl && MRecordDecl->isLambda()) {
14655 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
14656 << /*LambdaPointerConversionOperatorType=*/3
14657 << MRecordDecl->getSourceRange() << Range << IsEqual;
14658 return;
14659 }
14660 }
14661 }
14662
14663 // Expect to find a single Decl. Skip anything more complicated.
14664 ValueDecl *D = nullptr;
14665 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
14666 D = R->getDecl();
14667 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14668 D = M->getMemberDecl();
14669 }
14670
14671 // Weak Decls can be null.
14672 if (!D || D->isWeak())
14673 return;
14674
14675 // Check for parameter decl with nonnull attribute
14676 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
14677 if (getCurFunction() &&
14678 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
14679 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14680 ComplainAboutNonnullParamOrCall(A);
14681 return;
14682 }
14683
14684 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
14685 // Skip function template not specialized yet.
14687 return;
14688 auto ParamIter = llvm::find(FD->parameters(), PV);
14689 assert(ParamIter != FD->param_end());
14690 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
14691
14692 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14693 if (!NonNull->args_size()) {
14694 ComplainAboutNonnullParamOrCall(NonNull);
14695 return;
14696 }
14697
14698 for (const ParamIdx &ArgNo : NonNull->args()) {
14699 if (ArgNo.getASTIndex() == ParamNo) {
14700 ComplainAboutNonnullParamOrCall(NonNull);
14701 return;
14702 }
14703 }
14704 }
14705 }
14706 }
14707 }
14708
14709 QualType T = D->getType();
14710 // A reference to a function is never null either; look through it.
14711 const bool IsFunctionReference =
14712 T->isReferenceType() && T->getPointeeType()->isFunctionType();
14713 if (IsFunctionReference)
14714 T = T->getPointeeType();
14715 const bool IsArray = T->isArrayType();
14716 const bool IsFunction = T->isFunctionType();
14717
14718 // Address of function is used to silence the function warning.
14719 if (IsAddressOf && IsFunction) {
14720 return;
14721 }
14722
14723 // Found nothing.
14724 if (!IsAddressOf && !IsFunction && !IsArray)
14725 return;
14726
14727 // Pretty print the expression for the diagnostic.
14728 std::string Str;
14729 llvm::raw_string_ostream S(Str);
14730 E->printPretty(S, nullptr, getPrintingPolicy());
14731
14732 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14733 : diag::warn_impcast_pointer_to_bool;
14734 enum {
14735 AddressOf,
14736 FunctionPointer,
14737 ArrayPointer
14738 } DiagType;
14739 if (IsAddressOf)
14740 DiagType = AddressOf;
14741 else if (IsFunction)
14742 DiagType = FunctionPointer;
14743 else if (IsArray)
14744 DiagType = ArrayPointer;
14745 else
14746 llvm_unreachable("Could not determine diagnostic.");
14747 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14748 << Range << IsEqual;
14749
14750 // The fix-it notes below only apply to a bare function name, not a reference.
14751 if (!IsFunction || IsFunctionReference)
14752 return;
14753
14754 // Suggest '&' to silence the function warning.
14755 Diag(E->getExprLoc(), diag::note_function_warning_silence)
14757
14758 // Check to see if '()' fixit should be emitted.
14759 QualType ReturnType;
14760 UnresolvedSet<4> NonTemplateOverloads;
14761 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14762 if (ReturnType.isNull())
14763 return;
14764
14765 if (IsCompare) {
14766 // There are two cases here. If there is null constant, the only suggest
14767 // for a pointer return type. If the null is 0, then suggest if the return
14768 // type is a pointer or an integer type.
14769 if (!ReturnType->isPointerType()) {
14770 if (NullKind == Expr::NPCK_ZeroExpression ||
14771 NullKind == Expr::NPCK_ZeroLiteral) {
14772 if (!ReturnType->isIntegerType())
14773 return;
14774 } else {
14775 return;
14776 }
14777 }
14778 } else { // !IsCompare
14779 // For function to bool, only suggest if the function pointer has bool
14780 // return type.
14781 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14782 return;
14783 }
14784 Diag(E->getExprLoc(), diag::note_function_to_function_call)
14786}
14787
14789 SourceLocation CC) {
14790 QualType Source = E->getType();
14791 QualType Target = T;
14792
14793 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14794 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14795 // Overflow behavior type is being stripped - issue warning
14796 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14797 Target->isUnsignedIntegerType()) {
14798 // For unsigned wrap to unsigned conversions, use pedantic version
14799 unsigned DiagId =
14801 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14802 : diag::warn_impcast_overflow_behavior_pedantic;
14803 DiagnoseImpCast(*this, E, T, CC, DiagId);
14804 } else {
14805 unsigned DiagId = InOverflowBehaviorAssignmentContext
14806 ? diag::warn_impcast_overflow_behavior_assignment
14807 : diag::warn_impcast_overflow_behavior;
14808 DiagnoseImpCast(*this, E, T, CC, DiagId);
14809 }
14810 }
14811 }
14812
14813 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14814 if (TargetOBT->isWrapKind()) {
14815 return true;
14816 }
14817 }
14818
14819 return false;
14820}
14821
14822void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14823 // Don't diagnose in unevaluated contexts.
14825 return;
14826
14827 // Don't diagnose for value- or type-dependent expressions.
14828 if (E->isTypeDependent() || E->isValueDependent())
14829 return;
14830
14831 // Check for array bounds violations in cases where the check isn't triggered
14832 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14833 // ArraySubscriptExpr is on the RHS of a variable initialization.
14834 CheckArrayAccess(E);
14835
14836 // This is not the right CC for (e.g.) a variable initialization.
14837 AnalyzeImplicitConversions(*this, E, CC);
14838}
14839
14840void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14841 ::CheckBoolLikeConversion(*this, E, CC);
14842}
14843
14844void Sema::CheckForIntOverflow (const Expr *E) {
14845 // Use a work list to deal with nested struct initializers.
14846 SmallVector<const Expr *, 2> Exprs(1, E);
14847
14848 do {
14849 const Expr *OriginalE = Exprs.pop_back_val();
14850 const Expr *E = OriginalE->IgnoreParenCasts();
14851
14852 if (isa<BinaryOperator>(E) ||
14853 (isa<UnaryOperator>(E) && cast<UnaryOperator>(E)->canOverflow())) {
14855 continue;
14856 }
14857
14858 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
14859 Exprs.append(InitList->inits().begin(), InitList->inits().end());
14860 else if (isa<ObjCBoxedExpr>(OriginalE))
14862 else if (const auto *Call = dyn_cast<CallExpr>(E))
14863 Exprs.append(Call->arg_begin(), Call->arg_end());
14864 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
14865 Exprs.append(Message->arg_begin(), Message->arg_end());
14866 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
14867 Exprs.append(Construct->arg_begin(), Construct->arg_end());
14868 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
14869 Exprs.push_back(Temporary->getSubExpr());
14870 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
14871 Exprs.push_back(Array->getIdx());
14872 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
14873 Exprs.push_back(Compound->getInitializer());
14874 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
14875 New && New->isArray()) {
14876 if (auto ArraySize = New->getArraySize())
14877 Exprs.push_back(*ArraySize);
14878 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
14879 Exprs.push_back(MTE->getSubExpr());
14880 } while (!Exprs.empty());
14881}
14882
14883namespace {
14884
14885/// Visitor for expressions which looks for unsequenced operations on the
14886/// same object.
14887class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14888 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14889
14890 /// A tree of sequenced regions within an expression. Two regions are
14891 /// unsequenced if one is an ancestor or a descendent of the other. When we
14892 /// finish processing an expression with sequencing, such as a comma
14893 /// expression, we fold its tree nodes into its parent, since they are
14894 /// unsequenced with respect to nodes we will visit later.
14895 class SequenceTree {
14896 struct Value {
14897 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14898 unsigned Parent : 31;
14899 LLVM_PREFERRED_TYPE(bool)
14900 unsigned Merged : 1;
14901 };
14902 SmallVector<Value, 8> Values;
14903
14904 public:
14905 /// A region within an expression which may be sequenced with respect
14906 /// to some other region.
14907 class Seq {
14908 friend class SequenceTree;
14909
14910 unsigned Index;
14911
14912 explicit Seq(unsigned N) : Index(N) {}
14913
14914 public:
14915 Seq() : Index(0) {}
14916 };
14917
14918 SequenceTree() { Values.push_back(Value(0)); }
14919 Seq root() const { return Seq(0); }
14920
14921 /// Create a new sequence of operations, which is an unsequenced
14922 /// subset of \p Parent. This sequence of operations is sequenced with
14923 /// respect to other children of \p Parent.
14924 Seq allocate(Seq Parent) {
14925 Values.push_back(Value(Parent.Index));
14926 return Seq(Values.size() - 1);
14927 }
14928
14929 /// Merge a sequence of operations into its parent.
14930 void merge(Seq S) {
14931 Values[S.Index].Merged = true;
14932 }
14933
14934 /// Determine whether two operations are unsequenced. This operation
14935 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14936 /// should have been merged into its parent as appropriate.
14937 bool isUnsequenced(Seq Cur, Seq Old) {
14938 unsigned C = representative(Cur.Index);
14939 unsigned Target = representative(Old.Index);
14940 while (C >= Target) {
14941 if (C == Target)
14942 return true;
14943 C = Values[C].Parent;
14944 }
14945 return false;
14946 }
14947
14948 private:
14949 /// Pick a representative for a sequence.
14950 unsigned representative(unsigned K) {
14951 if (Values[K].Merged)
14952 // Perform path compression as we go.
14953 return Values[K].Parent = representative(Values[K].Parent);
14954 return K;
14955 }
14956 };
14957
14958 /// An object for which we can track unsequenced uses.
14959 using Object = const ValueDecl *;
14960
14961 /// Different flavors of object usage which we track. We only track the
14962 /// least-sequenced usage of each kind.
14963 enum UsageKind {
14964 /// A read of an object. Multiple unsequenced reads are OK.
14965 UK_Use,
14966
14967 /// A modification of an object which is sequenced before the value
14968 /// computation of the expression, such as ++n in C++.
14969 UK_ModAsValue,
14970
14971 /// A modification of an object which is not sequenced before the value
14972 /// computation of the expression, such as n++.
14973 UK_ModAsSideEffect,
14974
14975 UK_Count = UK_ModAsSideEffect + 1
14976 };
14977
14978 enum WarningKind {
14979 /// A warning message is one for unsequenced use and modification
14980 WK_UseAndMod,
14981
14982 /// A warning message is one for multiple unsequenced modification
14983 WK_ModAndMod,
14984
14985 /// A warning message is one for multiple unsequenced volatile use
14986 WK_Volatile_UseAndUse
14987 };
14988
14989 /// Bundle together a sequencing region and the expression corresponding
14990 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14991 struct Usage {
14992 const Expr *UsageExpr = nullptr;
14993 SequenceTree::Seq Seq;
14994
14995 Usage() = default;
14996 };
14997
14998 struct UsageInfo {
14999 Usage Uses[UK_Count];
15000
15001 /// Have we issued a diagnostic for this object already?
15002 bool Diagnosed = false;
15003
15004 UsageInfo();
15005 };
15006 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
15007
15008 Sema &SemaRef;
15009
15010 /// Sequenced regions within the expression.
15011 SequenceTree Tree;
15012
15013 /// Declaration modifications and references which we have seen.
15014 UsageInfoMap UsageMap;
15015
15016 /// The region we are currently within.
15017 SequenceTree::Seq Region;
15018
15019 /// Filled in with declarations which were modified as a side-effect
15020 /// (that is, post-increment operations).
15021 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
15022
15023 /// Expressions to check later. We defer checking these to reduce
15024 /// stack usage.
15025 SmallVectorImpl<const Expr *> &WorkList;
15026
15027 /// RAII object wrapping the visitation of a sequenced subexpression of an
15028 /// expression. At the end of this process, the side-effects of the evaluation
15029 /// become sequenced with respect to the value computation of the result, so
15030 /// we downgrade any UK_ModAsSideEffect within the evaluation to
15031 /// UK_ModAsValue.
15032 struct SequencedSubexpression {
15033 SequencedSubexpression(SequenceChecker &Self)
15034 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
15035 Self.ModAsSideEffect = &ModAsSideEffect;
15036 }
15037
15038 ~SequencedSubexpression() {
15039 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
15040 // Add a new usage with usage kind UK_ModAsValue, and then restore
15041 // the previous usage with UK_ModAsSideEffect (thus clearing it if
15042 // the previous one was empty).
15043 UsageInfo &UI = Self.UsageMap[M.first];
15044 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
15045 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
15046 SideEffectUsage = M.second;
15047 }
15048 Self.ModAsSideEffect = OldModAsSideEffect;
15049 }
15050
15051 SequenceChecker &Self;
15052 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
15053 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
15054 };
15055
15056 /// RAII object wrapping the visitation of a subexpression which we might
15057 /// choose to evaluate as a constant. If any subexpression is evaluated and
15058 /// found to be non-constant, this allows us to suppress the evaluation of
15059 /// the outer expression.
15060 class EvaluationTracker {
15061 public:
15062 EvaluationTracker(SequenceChecker &Self)
15063 : Self(Self), Prev(Self.EvalTracker) {
15064 Self.EvalTracker = this;
15065 }
15066
15067 ~EvaluationTracker() {
15068 Self.EvalTracker = Prev;
15069 if (Prev)
15070 Prev->EvalOK &= EvalOK;
15071 }
15072
15073 bool evaluate(const Expr *E, bool &Result) {
15074 if (!EvalOK || E->isValueDependent())
15075 return false;
15076 EvalOK = E->EvaluateAsBooleanCondition(
15077 Result, Self.SemaRef.Context,
15078 Self.SemaRef.isConstantEvaluatedContext());
15079 return EvalOK;
15080 }
15081
15082 private:
15083 SequenceChecker &Self;
15084 EvaluationTracker *Prev;
15085 bool EvalOK = true;
15086 } *EvalTracker = nullptr;
15087
15088 /// Find the object which is produced by the specified expression,
15089 /// if any.
15090 Object getObject(const Expr *E, bool Mod) const {
15091 E = E->IgnoreParenCasts();
15092 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
15093 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
15094 return getObject(UO->getSubExpr(), Mod);
15095 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
15096 if (BO->getOpcode() == BO_Comma)
15097 return getObject(BO->getRHS(), Mod);
15098 if (Mod && BO->isAssignmentOp())
15099 return getObject(BO->getLHS(), Mod);
15100 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15101 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
15102 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
15103 return ME->getMemberDecl();
15104 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
15105 // FIXME: If this is a reference, map through to its value.
15106 return DRE->getDecl();
15107 return nullptr;
15108 }
15109
15110 /// Note that an object \p O was modified or used by an expression
15111 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
15112 /// the object \p O as obtained via the \p UsageMap.
15113 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
15114 // Get the old usage for the given object and usage kind.
15115 Usage &U = UI.Uses[UK];
15116 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
15117 // If we have a modification as side effect and are in a sequenced
15118 // subexpression, save the old Usage so that we can restore it later
15119 // in SequencedSubexpression::~SequencedSubexpression.
15120 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
15121 ModAsSideEffect->push_back(std::make_pair(O, U));
15122 // Then record the new usage with the current sequencing region.
15123 U.UsageExpr = UsageExpr;
15124 U.Seq = Region;
15125 }
15126 }
15127
15128 /// Check whether a modification or use of an object \p O in an expression
15129 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
15130 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
15131 /// The message displayed in case of a conflict depends on \p WarnKind.
15132 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
15133 UsageKind OtherKind, WarningKind WarnKind) {
15134 if (UI.Diagnosed)
15135 return;
15136
15137 const Usage &U = UI.Uses[OtherKind];
15138 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
15139 return;
15140
15141 const Expr *Mod = U.UsageExpr;
15142 const Expr *ModOrUse = UsageExpr;
15143 if (OtherKind == UK_Use)
15144 std::swap(Mod, ModOrUse);
15145
15146 unsigned DiagID = 0;
15147 switch (WarnKind) {
15148 case WK_UseAndMod:
15149 DiagID = diag::warn_unsequenced_mod_use;
15150 break;
15151 case WK_ModAndMod:
15152 DiagID = diag::warn_unsequenced_mod_mod;
15153 break;
15154 case WK_Volatile_UseAndUse:
15155 DiagID = diag::warn_unsequenced_use_use_volatile;
15156 break;
15157 }
15158
15159 SemaRef.DiagRuntimeBehavior(
15160 Mod->getExprLoc(), {Mod, ModOrUse},
15161 SemaRef.PDiag(DiagID) << O << SourceRange(ModOrUse->getExprLoc()));
15162 UI.Diagnosed = true;
15163 }
15164
15165 // A note on note{Pre, Post}{Use, Mod}:
15166 //
15167 // (It helps to follow the algorithm with an expression such as
15168 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
15169 // operations before C++17 and both are well-defined in C++17).
15170 //
15171 // When visiting a node which uses/modify an object we first call notePreUse
15172 // or notePreMod before visiting its sub-expression(s). At this point the
15173 // children of the current node have not yet been visited and so the eventual
15174 // uses/modifications resulting from the children of the current node have not
15175 // been recorded yet.
15176 //
15177 // We then visit the children of the current node. After that notePostUse or
15178 // notePostMod is called. These will 1) detect an unsequenced modification
15179 // as side effect (as in "k++ + k") and 2) add a new usage with the
15180 // appropriate usage kind.
15181 //
15182 // We also have to be careful that some operation sequences modification as
15183 // side effect as well (for example: || or ,). To account for this we wrap
15184 // the visitation of such a sub-expression (for example: the LHS of || or ,)
15185 // with SequencedSubexpression. SequencedSubexpression is an RAII object
15186 // which record usages which are modifications as side effect, and then
15187 // downgrade them (or more accurately restore the previous usage which was a
15188 // modification as side effect) when exiting the scope of the sequenced
15189 // subexpression.
15190
15191 void notePreUse(Object O, const Expr *UseExpr) {
15192 UsageInfo &UI = UsageMap[O];
15193 // Uses conflict with other modifications.
15194 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, WK_UseAndMod);
15195 // Volatile uses conflict with other uses.
15196 if (O->getType().isVolatileQualified())
15197 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_Use, WK_Volatile_UseAndUse);
15198 }
15199
15200 void notePostUse(Object O, const Expr *UseExpr) {
15201 UsageInfo &UI = UsageMap[O];
15202 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, WK_UseAndMod);
15203 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
15204 }
15205
15206 void notePreMod(Object O, const Expr *ModExpr) {
15207 UsageInfo &UI = UsageMap[O];
15208 // Modifications conflict with other modifications and with uses.
15209 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, WK_ModAndMod);
15210 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, WK_UseAndMod);
15211 }
15212
15213 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
15214 UsageInfo &UI = UsageMap[O];
15215 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, WK_ModAndMod);
15216 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
15217 }
15218
15219public:
15220 SequenceChecker(Sema &S, const Expr *E,
15221 SmallVectorImpl<const Expr *> &WorkList)
15222 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
15223 Visit(E);
15224 // Silence a -Wunused-private-field since WorkList is now unused.
15225 // TODO: Evaluate if it can be used, and if not remove it.
15226 (void)this->WorkList;
15227 }
15228
15229 void VisitStmt(const Stmt *S) {
15230 // Skip all statements which aren't expressions for now.
15231 }
15232
15233 void VisitExpr(const Expr *E) {
15234 // By default, just recurse to evaluated subexpressions.
15235 Base::VisitStmt(E);
15236 }
15237
15238 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
15239 for (auto *Sub : CSE->children()) {
15240 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
15241 if (!ChildExpr)
15242 continue;
15243
15244 if (ChildExpr == CSE->getOperand())
15245 // Do not recurse over a CoroutineSuspendExpr's operand.
15246 // The operand is also a subexpression of getCommonExpr(), and
15247 // recursing into it directly could confuse object management
15248 // for the sake of sequence tracking.
15249 continue;
15250
15251 Visit(Sub);
15252 }
15253 }
15254
15255 void VisitCastExpr(const CastExpr *E) {
15256 Object O = Object();
15257 if (E->getCastKind() == CK_LValueToRValue)
15258 O = getObject(E->getSubExpr(), false);
15259
15260 if (O)
15261 notePreUse(O, E);
15262 VisitExpr(E);
15263 if (O)
15264 notePostUse(O, E);
15265 }
15266
15267 void VisitSequencedExpressions(const Expr *SequencedBefore,
15268 const Expr *SequencedAfter) {
15269 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
15270 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
15271 SequenceTree::Seq OldRegion = Region;
15272
15273 {
15274 SequencedSubexpression SeqBefore(*this);
15275 Region = BeforeRegion;
15276 Visit(SequencedBefore);
15277 }
15278
15279 Region = AfterRegion;
15280 Visit(SequencedAfter);
15281
15282 Region = OldRegion;
15283
15284 Tree.merge(BeforeRegion);
15285 Tree.merge(AfterRegion);
15286 }
15287
15288 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
15289 // C++17 [expr.sub]p1:
15290 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
15291 // expression E1 is sequenced before the expression E2.
15292 if (SemaRef.getLangOpts().CPlusPlus17)
15293 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
15294 else {
15295 Visit(ASE->getLHS());
15296 Visit(ASE->getRHS());
15297 }
15298 }
15299
15300 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15301 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15302 void VisitBinPtrMem(const BinaryOperator *BO) {
15303 // C++17 [expr.mptr.oper]p4:
15304 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
15305 // the expression E1 is sequenced before the expression E2.
15306 if (SemaRef.getLangOpts().CPlusPlus17)
15307 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15308 else {
15309 Visit(BO->getLHS());
15310 Visit(BO->getRHS());
15311 }
15312 }
15313
15314 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15315 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15316 void VisitBinShlShr(const BinaryOperator *BO) {
15317 // C++17 [expr.shift]p4:
15318 // The expression E1 is sequenced before the expression E2.
15319 if (SemaRef.getLangOpts().CPlusPlus17)
15320 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15321 else {
15322 Visit(BO->getLHS());
15323 Visit(BO->getRHS());
15324 }
15325 }
15326
15327 void VisitBinComma(const BinaryOperator *BO) {
15328 // C++11 [expr.comma]p1:
15329 // Every value computation and side effect associated with the left
15330 // expression is sequenced before every value computation and side
15331 // effect associated with the right expression.
15332 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15333 }
15334
15335 void VisitBinAssign(const BinaryOperator *BO) {
15336 SequenceTree::Seq RHSRegion;
15337 SequenceTree::Seq LHSRegion;
15338 if (SemaRef.getLangOpts().CPlusPlus17) {
15339 RHSRegion = Tree.allocate(Region);
15340 LHSRegion = Tree.allocate(Region);
15341 } else {
15342 RHSRegion = Region;
15343 LHSRegion = Region;
15344 }
15345 SequenceTree::Seq OldRegion = Region;
15346
15347 // C++11 [expr.ass]p1:
15348 // [...] the assignment is sequenced after the value computation
15349 // of the right and left operands, [...]
15350 //
15351 // so check it before inspecting the operands and update the
15352 // map afterwards.
15353 Object O = getObject(BO->getLHS(), /*Mod=*/true);
15354 if (O)
15355 notePreMod(O, BO);
15356
15357 if (SemaRef.getLangOpts().CPlusPlus17) {
15358 // C++17 [expr.ass]p1:
15359 // [...] The right operand is sequenced before the left operand. [...]
15360 {
15361 SequencedSubexpression SeqBefore(*this);
15362 Region = RHSRegion;
15363 Visit(BO->getRHS());
15364 }
15365
15366 Region = LHSRegion;
15367 Visit(BO->getLHS());
15368
15369 if (O && isa<CompoundAssignOperator>(BO))
15370 notePostUse(O, BO);
15371
15372 } else {
15373 // C++11 does not specify any sequencing between the LHS and RHS.
15374 Region = LHSRegion;
15375 Visit(BO->getLHS());
15376
15377 if (O && isa<CompoundAssignOperator>(BO))
15378 notePostUse(O, BO);
15379
15380 Region = RHSRegion;
15381 Visit(BO->getRHS());
15382 }
15383
15384 // C++11 [expr.ass]p1:
15385 // the assignment is sequenced [...] before the value computation of the
15386 // assignment expression.
15387 // C11 6.5.16/3 has no such rule.
15388 Region = OldRegion;
15389 if (O)
15390 notePostMod(O, BO,
15391 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15392 : UK_ModAsSideEffect);
15393 if (SemaRef.getLangOpts().CPlusPlus17) {
15394 Tree.merge(RHSRegion);
15395 Tree.merge(LHSRegion);
15396 }
15397 }
15398
15399 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
15400 VisitBinAssign(CAO);
15401 }
15402
15403 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15404 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15405 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
15406 Object O = getObject(UO->getSubExpr(), true);
15407 if (!O)
15408 return VisitExpr(UO);
15409
15410 notePreMod(O, UO);
15411 Visit(UO->getSubExpr());
15412 // C++11 [expr.pre.incr]p1:
15413 // the expression ++x is equivalent to x+=1
15414 notePostMod(O, UO,
15415 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15416 : UK_ModAsSideEffect);
15417 }
15418
15419 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15420 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15421 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
15422 Object O = getObject(UO->getSubExpr(), true);
15423 if (!O)
15424 return VisitExpr(UO);
15425
15426 notePreMod(O, UO);
15427 Visit(UO->getSubExpr());
15428 notePostMod(O, UO, UK_ModAsSideEffect);
15429 }
15430
15431 void VisitBinLOr(const BinaryOperator *BO) {
15432 // C++11 [expr.log.or]p2:
15433 // If the second expression is evaluated, every value computation and
15434 // side effect associated with the first expression is sequenced before
15435 // every value computation and side effect associated with the
15436 // second expression.
15437 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15438 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15439 SequenceTree::Seq OldRegion = Region;
15440
15441 EvaluationTracker Eval(*this);
15442 {
15443 SequencedSubexpression Sequenced(*this);
15444 Region = LHSRegion;
15445 Visit(BO->getLHS());
15446 }
15447
15448 // C++11 [expr.log.or]p1:
15449 // [...] the second operand is not evaluated if the first operand
15450 // evaluates to true.
15451 bool EvalResult = false;
15452 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15453 bool ShouldVisitRHS = !EvalOK || !EvalResult;
15454 if (ShouldVisitRHS) {
15455 Region = RHSRegion;
15456 Visit(BO->getRHS());
15457 }
15458
15459 Region = OldRegion;
15460 Tree.merge(LHSRegion);
15461 Tree.merge(RHSRegion);
15462 }
15463
15464 void VisitBinLAnd(const BinaryOperator *BO) {
15465 // C++11 [expr.log.and]p2:
15466 // If the second expression is evaluated, every value computation and
15467 // side effect associated with the first expression is sequenced before
15468 // every value computation and side effect associated with the
15469 // second expression.
15470 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15471 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15472 SequenceTree::Seq OldRegion = Region;
15473
15474 EvaluationTracker Eval(*this);
15475 {
15476 SequencedSubexpression Sequenced(*this);
15477 Region = LHSRegion;
15478 Visit(BO->getLHS());
15479 }
15480
15481 // C++11 [expr.log.and]p1:
15482 // [...] the second operand is not evaluated if the first operand is false.
15483 bool EvalResult = false;
15484 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15485 bool ShouldVisitRHS = !EvalOK || EvalResult;
15486 if (ShouldVisitRHS) {
15487 Region = RHSRegion;
15488 Visit(BO->getRHS());
15489 }
15490
15491 Region = OldRegion;
15492 Tree.merge(LHSRegion);
15493 Tree.merge(RHSRegion);
15494 }
15495
15496 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
15497 // C++11 [expr.cond]p1:
15498 // [...] Every value computation and side effect associated with the first
15499 // expression is sequenced before every value computation and side effect
15500 // associated with the second or third expression.
15501 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
15502
15503 // No sequencing is specified between the true and false expression.
15504 // However since exactly one of both is going to be evaluated we can
15505 // consider them to be sequenced. This is needed to avoid warning on
15506 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
15507 // both the true and false expressions because we can't evaluate x.
15508 // This will still allow us to detect an expression like (pre C++17)
15509 // "(x ? y += 1 : y += 2) = y".
15510 //
15511 // We don't wrap the visitation of the true and false expression with
15512 // SequencedSubexpression because we don't want to downgrade modifications
15513 // as side effect in the true and false expressions after the visition
15514 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
15515 // not warn between the two "y++", but we should warn between the "y++"
15516 // and the "y".
15517 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
15518 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
15519 SequenceTree::Seq OldRegion = Region;
15520
15521 EvaluationTracker Eval(*this);
15522 {
15523 SequencedSubexpression Sequenced(*this);
15524 Region = ConditionRegion;
15525 Visit(CO->getCond());
15526 }
15527
15528 // C++11 [expr.cond]p1:
15529 // [...] The first expression is contextually converted to bool (Clause 4).
15530 // It is evaluated and if it is true, the result of the conditional
15531 // expression is the value of the second expression, otherwise that of the
15532 // third expression. Only one of the second and third expressions is
15533 // evaluated. [...]
15534 bool EvalResult = false;
15535 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
15536 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
15537 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
15538 if (ShouldVisitTrueExpr) {
15539 Region = TrueRegion;
15540 Visit(CO->getTrueExpr());
15541 }
15542 if (ShouldVisitFalseExpr) {
15543 Region = FalseRegion;
15544 Visit(CO->getFalseExpr());
15545 }
15546
15547 Region = OldRegion;
15548 Tree.merge(ConditionRegion);
15549 Tree.merge(TrueRegion);
15550 Tree.merge(FalseRegion);
15551 }
15552
15553 void VisitCallExpr(const CallExpr *CE) {
15554 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
15555
15556 if (CE->isUnevaluatedBuiltinCall(Context))
15557 return;
15558
15559 // C++11 [intro.execution]p15:
15560 // When calling a function [...], every value computation and side effect
15561 // associated with any argument expression, or with the postfix expression
15562 // designating the called function, is sequenced before execution of every
15563 // expression or statement in the body of the function [and thus before
15564 // the value computation of its result].
15565 SequencedSubexpression Sequenced(*this);
15566 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
15567 // C++17 [expr.call]p5
15568 // The postfix-expression is sequenced before each expression in the
15569 // expression-list and any default argument. [...]
15570 SequenceTree::Seq CalleeRegion;
15571 SequenceTree::Seq OtherRegion;
15572 if (SemaRef.getLangOpts().CPlusPlus17) {
15573 CalleeRegion = Tree.allocate(Region);
15574 OtherRegion = Tree.allocate(Region);
15575 } else {
15576 CalleeRegion = Region;
15577 OtherRegion = Region;
15578 }
15579 SequenceTree::Seq OldRegion = Region;
15580
15581 // Visit the callee expression first.
15582 Region = CalleeRegion;
15583 if (SemaRef.getLangOpts().CPlusPlus17) {
15584 SequencedSubexpression Sequenced(*this);
15585 Visit(CE->getCallee());
15586 } else {
15587 Visit(CE->getCallee());
15588 }
15589
15590 // Then visit the argument expressions.
15591 Region = OtherRegion;
15592 for (const Expr *Argument : CE->arguments())
15593 Visit(Argument);
15594
15595 Region = OldRegion;
15596 if (SemaRef.getLangOpts().CPlusPlus17) {
15597 Tree.merge(CalleeRegion);
15598 Tree.merge(OtherRegion);
15599 }
15600 });
15601 }
15602
15603 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
15604 // C++17 [over.match.oper]p2:
15605 // [...] the operator notation is first transformed to the equivalent
15606 // function-call notation as summarized in Table 12 (where @ denotes one
15607 // of the operators covered in the specified subclause). However, the
15608 // operands are sequenced in the order prescribed for the built-in
15609 // operator (Clause 8).
15610 //
15611 // From the above only overloaded binary operators and overloaded call
15612 // operators have sequencing rules in C++17 that we need to handle
15613 // separately.
15614 if (!SemaRef.getLangOpts().CPlusPlus17 ||
15615 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15616 return VisitCallExpr(CXXOCE);
15617
15618 enum {
15619 NoSequencing,
15620 LHSBeforeRHS,
15621 RHSBeforeLHS,
15622 LHSBeforeRest
15623 } SequencingKind;
15624 switch (CXXOCE->getOperator()) {
15625 case OO_Equal:
15626 case OO_PlusEqual:
15627 case OO_MinusEqual:
15628 case OO_StarEqual:
15629 case OO_SlashEqual:
15630 case OO_PercentEqual:
15631 case OO_CaretEqual:
15632 case OO_AmpEqual:
15633 case OO_PipeEqual:
15634 case OO_LessLessEqual:
15635 case OO_GreaterGreaterEqual:
15636 SequencingKind = RHSBeforeLHS;
15637 break;
15638
15639 case OO_LessLess:
15640 case OO_GreaterGreater:
15641 case OO_AmpAmp:
15642 case OO_PipePipe:
15643 case OO_Comma:
15644 case OO_ArrowStar:
15645 case OO_Subscript:
15646 SequencingKind = LHSBeforeRHS;
15647 break;
15648
15649 case OO_Call:
15650 SequencingKind = LHSBeforeRest;
15651 break;
15652
15653 default:
15654 SequencingKind = NoSequencing;
15655 break;
15656 }
15657
15658 if (SequencingKind == NoSequencing)
15659 return VisitCallExpr(CXXOCE);
15660
15661 // This is a call, so all subexpressions are sequenced before the result.
15662 SequencedSubexpression Sequenced(*this);
15663
15664 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
15665 assert(SemaRef.getLangOpts().CPlusPlus17 &&
15666 "Should only get there with C++17 and above!");
15667 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15668 "Should only get there with an overloaded binary operator"
15669 " or an overloaded call operator!");
15670
15671 if (SequencingKind == LHSBeforeRest) {
15672 assert(CXXOCE->getOperator() == OO_Call &&
15673 "We should only have an overloaded call operator here!");
15674
15675 // This is very similar to VisitCallExpr, except that we only have the
15676 // C++17 case. The postfix-expression is the first argument of the
15677 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15678 // are in the following arguments.
15679 //
15680 // Note that we intentionally do not visit the callee expression since
15681 // it is just a decayed reference to a function.
15682 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
15683 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
15684 SequenceTree::Seq OldRegion = Region;
15685
15686 assert(CXXOCE->getNumArgs() >= 1 &&
15687 "An overloaded call operator must have at least one argument"
15688 " for the postfix-expression!");
15689 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15690 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15691 CXXOCE->getNumArgs() - 1);
15692
15693 // Visit the postfix-expression first.
15694 {
15695 Region = PostfixExprRegion;
15696 SequencedSubexpression Sequenced(*this);
15697 Visit(PostfixExpr);
15698 }
15699
15700 // Then visit the argument expressions.
15701 Region = ArgsRegion;
15702 for (const Expr *Arg : Args)
15703 Visit(Arg);
15704
15705 Region = OldRegion;
15706 Tree.merge(PostfixExprRegion);
15707 Tree.merge(ArgsRegion);
15708 } else {
15709 assert(CXXOCE->getNumArgs() == 2 &&
15710 "Should only have two arguments here!");
15711 assert((SequencingKind == LHSBeforeRHS ||
15712 SequencingKind == RHSBeforeLHS) &&
15713 "Unexpected sequencing kind!");
15714
15715 // We do not visit the callee expression since it is just a decayed
15716 // reference to a function.
15717 const Expr *E1 = CXXOCE->getArg(0);
15718 const Expr *E2 = CXXOCE->getArg(1);
15719 if (SequencingKind == RHSBeforeLHS)
15720 std::swap(E1, E2);
15721
15722 return VisitSequencedExpressions(E1, E2);
15723 }
15724 });
15725 }
15726
15727 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15728 // This is a call, so all subexpressions are sequenced before the result.
15729 SequencedSubexpression Sequenced(*this);
15730
15731 if (!CCE->isListInitialization())
15732 return VisitExpr(CCE);
15733
15734 // In C++11, list initializations are sequenced.
15735 SequenceExpressionsInOrder(
15736 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
15737 }
15738
15739 void VisitInitListExpr(const InitListExpr *ILE) {
15740 if (!SemaRef.getLangOpts().CPlusPlus11)
15741 return VisitExpr(ILE);
15742
15743 // In C++11, list initializations are sequenced.
15744 SequenceExpressionsInOrder(ILE->inits());
15745 }
15746
15747 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
15748 // C++20 parenthesized list initializations are sequenced. See C++20
15749 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
15750 SequenceExpressionsInOrder(PLIE->getInitExprs());
15751 }
15752
15753private:
15754 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
15756 SequenceTree::Seq Parent = Region;
15757 for (const Expr *E : ExpressionList) {
15758 if (!E)
15759 continue;
15760 Region = Tree.allocate(Parent);
15761 Elts.push_back(Region);
15762 Visit(E);
15763 }
15764
15765 // Forget that the initializers are sequenced.
15766 Region = Parent;
15767 for (unsigned I = 0; I < Elts.size(); ++I)
15768 Tree.merge(Elts[I]);
15769 }
15770};
15771
15772SequenceChecker::UsageInfo::UsageInfo() = default;
15773
15774} // namespace
15775
15776void Sema::CheckUnsequencedOperations(const Expr *E) {
15777 SmallVector<const Expr *, 8> WorkList;
15778 WorkList.push_back(E);
15779 while (!WorkList.empty()) {
15780 const Expr *Item = WorkList.pop_back_val();
15781 SequenceChecker(*this, Item, WorkList);
15782 }
15783}
15784
15785void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15786 bool IsConstexpr) {
15787 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15788 IsConstexpr || isa<ConstantExpr>(E));
15789 CheckImplicitConversions(E, CheckLoc);
15790 if (!E->isInstantiationDependent())
15791 CheckUnsequencedOperations(E);
15792 if (!IsConstexpr && !E->isValueDependent() && !isa<ConstantExpr>(E))
15793 CheckForIntOverflow(E);
15794}
15795
15796void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15797 FieldDecl *BitField,
15798 Expr *Init) {
15799 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
15800}
15801
15803 SourceLocation Loc) {
15804 if (!PType->isVariablyModifiedType())
15805 return;
15806 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
15807 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
15808 return;
15809 }
15810 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
15811 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
15812 return;
15813 }
15814 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
15815 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
15816 return;
15817 }
15818
15819 const ArrayType *AT = S.Context.getAsArrayType(PType);
15820 if (!AT)
15821 return;
15822
15825 return;
15826 }
15827
15828 S.Diag(Loc, diag::err_array_star_in_function_definition);
15829}
15830
15832 bool CheckParameterNames) {
15833 bool HasInvalidParm = false;
15834 for (ParmVarDecl *Param : Parameters) {
15835 assert(Param && "null in a parameter list");
15836 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15837 // function declarator that is part of a function definition of
15838 // that function shall not have incomplete type.
15839 //
15840 // C++23 [dcl.fct.def.general]/p2
15841 // The type of a parameter [...] for a function definition
15842 // shall not be a (possibly cv-qualified) class type that is incomplete
15843 // or abstract within the function body unless the function is deleted.
15844 if (!Param->isInvalidDecl() &&
15845 (RequireCompleteType(Param->getLocation(), Param->getType(),
15846 diag::err_typecheck_decl_incomplete_type) ||
15847 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
15848 diag::err_abstract_type_in_decl,
15850 Param->setInvalidDecl();
15851 HasInvalidParm = true;
15852 }
15853
15854 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15855 // declaration of each parameter shall include an identifier.
15856 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15857 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15858 // Diagnose this as an extension in C17 and earlier.
15859 if (!getLangOpts().C23)
15860 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
15861 }
15862
15863 // C99 6.7.5.3p12:
15864 // If the function declarator is not part of a definition of that
15865 // function, parameters may have incomplete type and may use the [*]
15866 // notation in their sequences of declarator specifiers to specify
15867 // variable length array types.
15868 QualType PType = Param->getOriginalType();
15869 // FIXME: This diagnostic should point the '[*]' if source-location
15870 // information is added for it.
15871 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15872
15873 // If the parameter is a c++ class type and it has to be destructed in the
15874 // callee function, declare the destructor so that it can be called by the
15875 // callee function. Do not perform any direct access check on the dtor here.
15876 if (!Param->isInvalidDecl()) {
15877 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15878 if (!ClassDecl->isInvalidDecl() &&
15879 !ClassDecl->hasIrrelevantDestructor() &&
15880 !ClassDecl->isDependentContext() &&
15881 ClassDecl->isParamDestroyedInCallee()) {
15883 MarkFunctionReferenced(Param->getLocation(), Destructor);
15884 DiagnoseUseOfDecl(Destructor, Param->getLocation());
15885 }
15886 }
15887 }
15888
15889 // Parameters with the pass_object_size attribute only need to be marked
15890 // constant at function definitions. Because we lack information about
15891 // whether we're on a declaration or definition when we're instantiating the
15892 // attribute, we need to check for constness here.
15893 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15894 if (!Param->getType().isConstQualified())
15895 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15896 << Attr->getSpelling() << 1;
15897
15898 // Check for parameter names shadowing fields from the class.
15899 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15900 // The owning context for the parameter should be the function, but we
15901 // want to see if this function's declaration context is a record.
15902 DeclContext *DC = Param->getDeclContext();
15903 if (DC && DC->isFunctionOrMethod()) {
15904 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15905 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15906 RD, /*DeclIsField*/ false);
15907 }
15908 }
15909
15910 if (!Param->isInvalidDecl() &&
15911 Param->getOriginalType()->isWebAssemblyTableType()) {
15912 Param->setInvalidDecl();
15913 HasInvalidParm = true;
15914 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
15915 }
15916 }
15917
15918 return HasInvalidParm;
15919}
15920
15921std::optional<std::pair<
15923 *E,
15925 &Ctx);
15926
15927/// Compute the alignment and offset of the base class object given the
15928/// derived-to-base cast expression and the alignment and offset of the derived
15929/// class object.
15930static std::pair<CharUnits, CharUnits>
15932 CharUnits BaseAlignment, CharUnits Offset,
15933 ASTContext &Ctx) {
15934 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15935 ++PathI) {
15936 const CXXBaseSpecifier *Base = *PathI;
15937 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15938 if (Base->isVirtual()) {
15939 // The complete object may have a lower alignment than the non-virtual
15940 // alignment of the base, in which case the base may be misaligned. Choose
15941 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15942 // conservative lower bound of the complete object alignment.
15943 CharUnits NonVirtualAlignment =
15945 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15946 Offset = CharUnits::Zero();
15947 } else {
15948 const ASTRecordLayout &RL =
15949 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15950 Offset += RL.getBaseClassOffset(BaseDecl);
15951 }
15952 DerivedType = Base->getType();
15953 }
15954
15955 return std::make_pair(BaseAlignment, Offset);
15956}
15957
15958/// Compute the alignment and offset of a binary additive operator.
15959static std::optional<std::pair<CharUnits, CharUnits>>
15961 bool IsSub, ASTContext &Ctx) {
15962 QualType PointeeType = PtrE->getType()->getPointeeType();
15963
15964 if (!PointeeType->isConstantSizeType())
15965 return std::nullopt;
15966
15967 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15968
15969 if (!P)
15970 return std::nullopt;
15971
15972 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15973 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15974 CharUnits Offset = EltSize * IdxRes->getExtValue();
15975 if (IsSub)
15976 Offset = -Offset;
15977 return std::make_pair(P->first, P->second + Offset);
15978 }
15979
15980 // If the integer expression isn't a constant expression, compute the lower
15981 // bound of the alignment using the alignment and offset of the pointer
15982 // expression and the element size.
15983 return std::make_pair(
15984 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15985 CharUnits::Zero());
15986}
15987
15988/// This helper function takes an lvalue expression and returns the alignment of
15989/// a VarDecl and a constant offset from the VarDecl.
15990std::optional<std::pair<
15991 CharUnits,
15993 ASTContext &Ctx) {
15994 E = E->IgnoreParens();
15995 switch (E->getStmtClass()) {
15996 default:
15997 break;
15998 case Stmt::CStyleCastExprClass:
15999 case Stmt::CXXStaticCastExprClass:
16000 case Stmt::ImplicitCastExprClass: {
16001 auto *CE = cast<CastExpr>(E);
16002 const Expr *From = CE->getSubExpr();
16003 switch (CE->getCastKind()) {
16004 default:
16005 break;
16006 case CK_NoOp:
16007 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
16008 case CK_UncheckedDerivedToBase:
16009 case CK_DerivedToBase: {
16010 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
16011 if (!P)
16012 break;
16013 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
16014 P->second, Ctx);
16015 }
16016 }
16017 break;
16018 }
16019 case Stmt::ArraySubscriptExprClass: {
16020 auto *ASE = cast<ArraySubscriptExpr>(E);
16022 false, Ctx);
16023 }
16024 case Stmt::DeclRefExprClass: {
16025 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
16026 // FIXME: If VD is captured by copy or is an escaping __block variable,
16027 // use the alignment of VD's type.
16028 if (!VD->getType()->isReferenceType()) {
16029 // Dependent alignment cannot be resolved -> bail out.
16030 if (VD->hasDependentAlignment())
16031 break;
16032 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
16033 }
16034 if (VD->hasInit())
16035 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
16036 }
16037 break;
16038 }
16039 case Stmt::MemberExprClass: {
16040 auto *ME = cast<MemberExpr>(E);
16041 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
16042 if (!FD || FD->getType()->isReferenceType() ||
16044 break;
16045 std::optional<std::pair<CharUnits, CharUnits>> P;
16046 if (ME->isArrow())
16047 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
16048 else
16049 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
16050 if (!P)
16051 break;
16052 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
16053 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
16054 return std::make_pair(P->first,
16055 P->second + CharUnits::fromQuantity(Offset));
16056 }
16057 case Stmt::UnaryOperatorClass: {
16058 auto *UO = cast<UnaryOperator>(E);
16059 switch (UO->getOpcode()) {
16060 default:
16061 break;
16062 case UO_Deref:
16064 }
16065 break;
16066 }
16067 case Stmt::BinaryOperatorClass: {
16068 auto *BO = cast<BinaryOperator>(E);
16069 auto Opcode = BO->getOpcode();
16070 switch (Opcode) {
16071 default:
16072 break;
16073 case BO_Comma:
16075 }
16076 break;
16077 }
16078 }
16079 return std::nullopt;
16080}
16081
16082/// This helper function takes a pointer expression and returns the alignment of
16083/// a VarDecl and a constant offset from the VarDecl.
16084std::optional<std::pair<
16086 *E,
16088 &Ctx) {
16089 E = E->IgnoreParens();
16090 switch (E->getStmtClass()) {
16091 default:
16092 break;
16093 case Stmt::CStyleCastExprClass:
16094 case Stmt::CXXStaticCastExprClass:
16095 case Stmt::ImplicitCastExprClass: {
16096 auto *CE = cast<CastExpr>(E);
16097 const Expr *From = CE->getSubExpr();
16098 switch (CE->getCastKind()) {
16099 default:
16100 break;
16101 case CK_NoOp:
16102 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
16103 case CK_ArrayToPointerDecay:
16104 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
16105 case CK_UncheckedDerivedToBase:
16106 case CK_DerivedToBase: {
16107 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
16108 if (!P)
16109 break;
16111 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
16112 }
16113 }
16114 break;
16115 }
16116 case Stmt::CXXThisExprClass: {
16117 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
16119 return std::make_pair(Alignment, CharUnits::Zero());
16120 }
16121 case Stmt::UnaryOperatorClass: {
16122 auto *UO = cast<UnaryOperator>(E);
16123 if (UO->getOpcode() == UO_AddrOf)
16125 break;
16126 }
16127 case Stmt::BinaryOperatorClass: {
16128 auto *BO = cast<BinaryOperator>(E);
16129 auto Opcode = BO->getOpcode();
16130 switch (Opcode) {
16131 default:
16132 break;
16133 case BO_Add:
16134 case BO_Sub: {
16135 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
16136 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
16137 std::swap(LHS, RHS);
16138 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
16139 Ctx);
16140 }
16141 case BO_Comma:
16142 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
16143 }
16144 break;
16145 }
16146 }
16147 return std::nullopt;
16148}
16149
16151 // See if we can compute the alignment of a VarDecl and an offset from it.
16152 std::optional<std::pair<CharUnits, CharUnits>> P =
16154
16155 if (P)
16156 return P->first.alignmentAtOffset(P->second);
16157
16158 // If that failed, return the type's alignment.
16160}
16161
16163 // This is actually a lot of work to potentially be doing on every
16164 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
16165 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
16166 return;
16167
16168 // Ignore dependent types.
16169 if (T->isDependentType() || Op->getType()->isDependentType())
16170 return;
16171
16172 // Require that the destination be a pointer type.
16173 const PointerType *DestPtr = T->getAs<PointerType>();
16174 if (!DestPtr) return;
16175
16176 // If the destination has alignment 1, we're done.
16177 QualType DestPointee = DestPtr->getPointeeType();
16178 if (DestPointee->isIncompleteType()) return;
16179 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
16180 if (DestAlign.isOne()) return;
16181
16182 // Require that the source be a pointer type.
16183 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
16184 if (!SrcPtr) return;
16185 QualType SrcPointee = SrcPtr->getPointeeType();
16186
16187 // Explicitly allow casts from cv void*. We already implicitly
16188 // allowed casts to cv void*, since they have alignment 1.
16189 // Also allow casts involving incomplete types, which implicitly
16190 // includes 'void'.
16191 if (SrcPointee->isIncompleteType()) return;
16192
16193 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
16194
16195 if (SrcAlign >= DestAlign) return;
16196
16197 Diag(TRange.getBegin(), diag::warn_cast_align)
16198 << Op->getType() << T
16199 << static_cast<unsigned>(SrcAlign.getQuantity())
16200 << static_cast<unsigned>(DestAlign.getQuantity())
16201 << TRange << Op->getSourceRange();
16202}
16203
16204void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
16205 const ArraySubscriptExpr *ASE,
16206 bool AllowOnePastEnd, bool IndexNegated) {
16207 // Already diagnosed by the constant evaluator.
16209 return;
16210
16211 IndexExpr = IndexExpr->IgnoreParenImpCasts();
16212 if (IndexExpr->isValueDependent())
16213 return;
16214
16215 const Type *EffectiveType =
16217 BaseExpr = BaseExpr->IgnoreParenCasts();
16218 const ConstantArrayType *ArrayTy =
16219 Context.getAsConstantArrayType(BaseExpr->getType());
16220
16222 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
16223
16224 const Type *BaseType =
16225 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
16226 bool IsUnboundedArray =
16227 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
16228 Context, StrictFlexArraysLevel,
16229 /*IgnoreTemplateOrMacroSubstitution=*/true);
16230 if (EffectiveType->isDependentType() ||
16231 (!IsUnboundedArray && BaseType->isDependentType()))
16232 return;
16233
16235 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
16236 return;
16237
16238 llvm::APSInt index = Result.Val.getInt();
16239 if (IndexNegated) {
16240 index.setIsUnsigned(false);
16241 index = -index;
16242 }
16243
16244 if (IsUnboundedArray) {
16245 if (EffectiveType->isFunctionType())
16246 return;
16247 if (index.isUnsigned() || !index.isNegative()) {
16248 const auto &ASTC = getASTContext();
16249 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
16250 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
16251 if (index.getBitWidth() < AddrBits)
16252 index = index.zext(AddrBits);
16253 std::optional<CharUnits> ElemCharUnits =
16254 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
16255 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
16256 // pointer) bounds-checking isn't meaningful.
16257 if (!ElemCharUnits || ElemCharUnits->isZero())
16258 return;
16259 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
16260 // If index has more active bits than address space, we already know
16261 // we have a bounds violation to warn about. Otherwise, compute
16262 // address of (index + 1)th element, and warn about bounds violation
16263 // only if that address exceeds address space.
16264 if (index.getActiveBits() <= AddrBits) {
16265 bool Overflow;
16266 llvm::APInt Product(index);
16267 Product += 1;
16268 Product = Product.umul_ov(ElemBytes, Overflow);
16269 if (!Overflow && Product.getActiveBits() <= AddrBits)
16270 return;
16271 }
16272
16273 // Need to compute max possible elements in address space, since that
16274 // is included in diag message.
16275 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
16276 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
16277 MaxElems += 1;
16278 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
16279 MaxElems = MaxElems.udiv(ElemBytes);
16280
16281 unsigned DiagID =
16282 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
16283 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
16284
16285 // Diag message shows element size in bits and in "bytes" (platform-
16286 // dependent CharUnits)
16287 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16288 PDiag(DiagID) << index << AddrBits
16289 << (unsigned)ASTC.toBits(*ElemCharUnits)
16290 << ElemBytes << MaxElems
16291 << MaxElems.getZExtValue()
16292 << IndexExpr->getSourceRange());
16293
16294 const NamedDecl *ND = nullptr;
16295 // Try harder to find a NamedDecl to point at in the note.
16296 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
16297 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16298 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
16299 ND = DRE->getDecl();
16300 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
16301 ND = ME->getMemberDecl();
16302
16303 if (ND)
16304 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
16305 PDiag(diag::note_array_declared_here) << ND);
16306 }
16307 return;
16308 }
16309
16310 if (index.isUnsigned() || !index.isNegative()) {
16311 // It is possible that the type of the base expression after
16312 // IgnoreParenCasts is incomplete, even though the type of the base
16313 // expression before IgnoreParenCasts is complete (see PR39746 for an
16314 // example). In this case we have no information about whether the array
16315 // access exceeds the array bounds. However we can still diagnose an array
16316 // access which precedes the array bounds.
16317 if (BaseType->isIncompleteType())
16318 return;
16319
16320 llvm::APInt size = ArrayTy->getSize();
16321
16322 if (BaseType != EffectiveType) {
16323 // Make sure we're comparing apples to apples when comparing index to
16324 // size.
16325 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
16326 uint64_t array_typesize = Context.getTypeSize(BaseType);
16327
16328 // Handle ptrarith_typesize being zero, such as when casting to void*.
16329 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
16330 if (!ptrarith_typesize)
16331 ptrarith_typesize = Context.getCharWidth();
16332
16333 if (ptrarith_typesize != array_typesize) {
16334 // There's a cast to a different size type involved.
16335 uint64_t ratio = array_typesize / ptrarith_typesize;
16336
16337 // TODO: Be smarter about handling cases where array_typesize is not a
16338 // multiple of ptrarith_typesize.
16339 if (ptrarith_typesize * ratio == array_typesize)
16340 size *= llvm::APInt(size.getBitWidth(), ratio);
16341 }
16342 }
16343
16344 if (size.getBitWidth() > index.getBitWidth())
16345 index = index.zext(size.getBitWidth());
16346 else if (size.getBitWidth() < index.getBitWidth())
16347 size = size.zext(index.getBitWidth());
16348
16349 // For array subscripting the index must be less than size, but for pointer
16350 // arithmetic also allow the index (offset) to be equal to size since
16351 // computing the next address after the end of the array is legal and
16352 // commonly done e.g. in C++ iterators and range-based for loops.
16353 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
16354 return;
16355
16356 // Suppress the warning if the subscript expression (as identified by the
16357 // ']' location) and the index expression are both from macro expansions
16358 // within a system header.
16359 if (ASE) {
16360 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
16361 ASE->getRBracketLoc());
16362 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
16363 SourceLocation IndexLoc =
16364 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
16365 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
16366 return;
16367 }
16368 }
16369
16370 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
16371 : diag::warn_ptr_arith_exceeds_bounds;
16372 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
16373 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
16374
16375 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16376 PDiag(DiagID)
16377 << index << ArrayTy->desugar() << CastMsg
16378 << CastMsgTy << IndexExpr->getSourceRange());
16379 } else {
16380 unsigned DiagID = diag::warn_array_index_precedes_bounds;
16381 if (!ASE) {
16382 DiagID = diag::warn_ptr_arith_precedes_bounds;
16383 if (index.isNegative()) index = -index;
16384 }
16385
16386 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16387 PDiag(DiagID) << index << IndexExpr->getSourceRange());
16388 }
16389
16390 const NamedDecl *ND = nullptr;
16391 // Try harder to find a NamedDecl to point at in the note.
16392 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
16393 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16394 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
16395 ND = DRE->getDecl();
16396 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
16397 ND = ME->getMemberDecl();
16398
16399 if (ND)
16400 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
16401 PDiag(diag::note_array_declared_here) << ND);
16402}
16403
16404void Sema::CheckArrayAccess(const Expr *expr) {
16405 int AllowOnePastEnd = 0;
16406 while (expr) {
16407 expr = expr->IgnoreParenImpCasts();
16408 switch (expr->getStmtClass()) {
16409 case Stmt::ArraySubscriptExprClass: {
16410 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
16411 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
16412 AllowOnePastEnd > 0);
16413 expr = ASE->getBase();
16414 break;
16415 }
16416 case Stmt::MemberExprClass: {
16417 expr = cast<MemberExpr>(expr)->getBase();
16418 break;
16419 }
16420 case Stmt::CXXMemberCallExprClass: {
16421 expr = cast<CXXMemberCallExpr>(expr)->getImplicitObjectArgument();
16422 break;
16423 }
16424 case Stmt::ArraySectionExprClass: {
16425 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
16426 // FIXME: We should probably be checking all of the elements to the
16427 // 'length' here as well.
16428 if (ASE->getLowerBound())
16429 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
16430 /*ASE=*/nullptr, AllowOnePastEnd > 0);
16431 return;
16432 }
16433 case Stmt::UnaryOperatorClass: {
16434 // Only unwrap the * and & unary operators
16435 const UnaryOperator *UO = cast<UnaryOperator>(expr);
16436 expr = UO->getSubExpr();
16437 switch (UO->getOpcode()) {
16438 case UO_AddrOf:
16439 AllowOnePastEnd++;
16440 break;
16441 case UO_Deref:
16442 AllowOnePastEnd--;
16443 break;
16444 default:
16445 return;
16446 }
16447 break;
16448 }
16449 case Stmt::ConditionalOperatorClass: {
16450 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
16451 if (const Expr *lhs = cond->getLHS())
16452 CheckArrayAccess(lhs);
16453 if (const Expr *rhs = cond->getRHS())
16454 CheckArrayAccess(rhs);
16455 return;
16456 }
16457 case Stmt::CXXOperatorCallExprClass: {
16458 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
16459 for (const auto *Arg : OCE->arguments())
16460 CheckArrayAccess(Arg);
16461 return;
16462 }
16463 default:
16464 return;
16465 }
16466 }
16467}
16468
16470 Expr *RHS, bool isProperty) {
16471 // Check if RHS is an Objective-C object literal, which also can get
16472 // immediately zapped in a weak reference. Note that we explicitly
16473 // allow ObjCStringLiterals, since those are designed to never really die.
16474 RHS = RHS->IgnoreParenImpCasts();
16475
16476 // This enum needs to match with the 'select' in
16477 // warn_objc_arc_literal_assign (off-by-1).
16479 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
16480 return false;
16481
16482 S.Diag(Loc, diag::warn_arc_literal_assign)
16483 << (unsigned) Kind
16484 << (isProperty ? 0 : 1)
16485 << RHS->getSourceRange();
16486
16487 return true;
16488}
16489
16492 Expr *RHS, bool isProperty) {
16493 // Strip off any implicit cast added to get to the one ARC-specific.
16494 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16495 if (cast->getCastKind() == CK_ARCConsumeObject) {
16496 S.Diag(Loc, diag::warn_arc_retained_assign)
16498 << (isProperty ? 0 : 1)
16499 << RHS->getSourceRange();
16500 return true;
16501 }
16502 RHS = cast->getSubExpr();
16503 }
16504
16505 if (LT == Qualifiers::OCL_Weak &&
16506 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16507 return true;
16508
16509 return false;
16510}
16511
16513 QualType LHS, Expr *RHS) {
16515
16517 return false;
16518
16519 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16520 return true;
16521
16522 return false;
16523}
16524
16526 Expr *LHS, Expr *RHS) {
16527 QualType LHSType;
16528 // PropertyRef on LHS type need be directly obtained from
16529 // its declaration as it has a PseudoType.
16531 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16532 if (PRE && !PRE->isImplicitProperty()) {
16533 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16534 if (PD)
16535 LHSType = PD->getType();
16536 }
16537
16538 if (LHSType.isNull())
16539 LHSType = LHS->getType();
16540
16542
16543 if (LT == Qualifiers::OCL_Weak) {
16544 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16546 }
16547
16548 if (checkUnsafeAssigns(Loc, LHSType, RHS))
16549 return;
16550
16551 // FIXME. Check for other life times.
16552 if (LT != Qualifiers::OCL_None)
16553 return;
16554
16555 if (PRE) {
16556 if (PRE->isImplicitProperty())
16557 return;
16558 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16559 if (!PD)
16560 return;
16561
16562 unsigned Attributes = PD->getPropertyAttributes();
16563 if (Attributes & ObjCPropertyAttribute::kind_assign) {
16564 // when 'assign' attribute was not explicitly specified
16565 // by user, ignore it and rely on property type itself
16566 // for lifetime info.
16567 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16568 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16569 LHSType->isObjCRetainableType())
16570 return;
16571
16572 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16573 if (cast->getCastKind() == CK_ARCConsumeObject) {
16574 Diag(Loc, diag::warn_arc_retained_property_assign)
16575 << RHS->getSourceRange();
16576 return;
16577 }
16578 RHS = cast->getSubExpr();
16579 }
16580 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16581 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16582 return;
16583 }
16584 }
16585}
16586
16587//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16588
16589static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16590 SourceLocation StmtLoc,
16591 const NullStmt *Body) {
16592 // Do not warn if the body is a macro that expands to nothing, e.g:
16593 //
16594 // #define CALL(x)
16595 // if (condition)
16596 // CALL(0);
16597 if (Body->hasLeadingEmptyMacro())
16598 return false;
16599
16600 // Get line numbers of statement and body.
16601 bool StmtLineInvalid;
16602 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16603 &StmtLineInvalid);
16604 if (StmtLineInvalid)
16605 return false;
16606
16607 bool BodyLineInvalid;
16608 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16609 &BodyLineInvalid);
16610 if (BodyLineInvalid)
16611 return false;
16612
16613 // Warn if null statement and body are on the same line.
16614 if (StmtLine != BodyLine)
16615 return false;
16616
16617 return true;
16618}
16619
16621 const Stmt *Body,
16622 unsigned DiagID) {
16623 // Since this is a syntactic check, don't emit diagnostic for template
16624 // instantiations, this just adds noise.
16626 return;
16627
16628 // The body should be a null statement.
16629 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16630 if (!NBody)
16631 return;
16632
16633 // Do the usual checks.
16634 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16635 return;
16636
16637 Diag(NBody->getSemiLoc(), DiagID);
16638 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16639}
16640
16642 const Stmt *PossibleBody) {
16643 assert(!CurrentInstantiationScope); // Ensured by caller
16644
16645 SourceLocation StmtLoc;
16646 const Stmt *Body;
16647 unsigned DiagID;
16648 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16649 StmtLoc = FS->getRParenLoc();
16650 Body = FS->getBody();
16651 DiagID = diag::warn_empty_for_body;
16652 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16653 StmtLoc = WS->getRParenLoc();
16654 Body = WS->getBody();
16655 DiagID = diag::warn_empty_while_body;
16656 } else
16657 return; // Neither `for' nor `while'.
16658
16659 // The body should be a null statement.
16660 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16661 if (!NBody)
16662 return;
16663
16664 // Skip expensive checks if diagnostic is disabled.
16665 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16666 return;
16667
16668 // Do the usual checks.
16669 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16670 return;
16671
16672 // `for(...);' and `while(...);' are popular idioms, so in order to keep
16673 // noise level low, emit diagnostics only if for/while is followed by a
16674 // CompoundStmt, e.g.:
16675 // for (int i = 0; i < n; i++);
16676 // {
16677 // a(i);
16678 // }
16679 // or if for/while is followed by a statement with more indentation
16680 // than for/while itself:
16681 // for (int i = 0; i < n; i++);
16682 // a(i);
16683 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16684 if (!ProbableTypo) {
16685 bool BodyColInvalid;
16686 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16687 PossibleBody->getBeginLoc(), &BodyColInvalid);
16688 if (BodyColInvalid)
16689 return;
16690
16691 bool StmtColInvalid;
16692 unsigned StmtCol =
16693 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16694 if (StmtColInvalid)
16695 return;
16696
16697 if (BodyCol > StmtCol)
16698 ProbableTypo = true;
16699 }
16700
16701 if (ProbableTypo) {
16702 Diag(NBody->getSemiLoc(), DiagID);
16703 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16704 }
16705}
16706
16707//===--- CHECK: Warn on self move with std::move. -------------------------===//
16708
16709void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16710 SourceLocation OpLoc) {
16711 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16712 return;
16713
16715 return;
16716
16717 // Strip parens and casts away.
16718 LHSExpr = LHSExpr->IgnoreParenImpCasts();
16719 RHSExpr = RHSExpr->IgnoreParenImpCasts();
16720
16721 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
16722 // which we can treat as an inlined std::move
16723 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
16724 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
16725 RHSExpr = CE->getArg(0);
16726 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
16727 CXXSCE && CXXSCE->isXValue())
16728 RHSExpr = CXXSCE->getSubExpr();
16729 else
16730 return;
16731
16732 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16733 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16734
16735 // Two DeclRefExpr's, check that the decls are the same.
16736 if (LHSDeclRef && RHSDeclRef) {
16737 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16738 return;
16739 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16740 RHSDeclRef->getDecl()->getCanonicalDecl())
16741 return;
16742
16743 auto D = Diag(OpLoc, diag::warn_self_move)
16744 << LHSExpr->getType() << LHSExpr->getSourceRange()
16745 << RHSExpr->getSourceRange();
16746 if (const FieldDecl *F =
16748 D << 1 << F
16749 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
16750 else
16751 D << 0;
16752 return;
16753 }
16754
16755 // Member variables require a different approach to check for self moves.
16756 // MemberExpr's are the same if every nested MemberExpr refers to the same
16757 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16758 // the base Expr's are CXXThisExpr's.
16759 const Expr *LHSBase = LHSExpr;
16760 const Expr *RHSBase = RHSExpr;
16761 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16762 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16763 if (!LHSME || !RHSME)
16764 return;
16765
16766 while (LHSME && RHSME) {
16767 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16768 RHSME->getMemberDecl()->getCanonicalDecl())
16769 return;
16770
16771 LHSBase = LHSME->getBase();
16772 RHSBase = RHSME->getBase();
16773 LHSME = dyn_cast<MemberExpr>(LHSBase);
16774 RHSME = dyn_cast<MemberExpr>(RHSBase);
16775 }
16776
16777 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16778 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16779 if (LHSDeclRef && RHSDeclRef) {
16780 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16781 return;
16782 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16783 RHSDeclRef->getDecl()->getCanonicalDecl())
16784 return;
16785
16786 Diag(OpLoc, diag::warn_self_move)
16787 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16788 << RHSExpr->getSourceRange();
16789 return;
16790 }
16791
16792 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16793 Diag(OpLoc, diag::warn_self_move)
16794 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16795 << RHSExpr->getSourceRange();
16796}
16797
16798//===--- Layout compatibility ----------------------------------------------//
16799
16800static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16801
16802/// Check if two enumeration types are layout-compatible.
16803static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16804 const EnumDecl *ED2) {
16805 // C++11 [dcl.enum] p8:
16806 // Two enumeration types are layout-compatible if they have the same
16807 // underlying type.
16808 return ED1->isComplete() && ED2->isComplete() &&
16809 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16810}
16811
16812/// Check if two fields are layout-compatible.
16813/// Can be used on union members, which are exempt from alignment requirement
16814/// of common initial sequence.
16815static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16816 const FieldDecl *Field2,
16817 bool AreUnionMembers = false) {
16818#ifndef NDEBUG
16819 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16820 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16821 assert(((Field1Parent->isStructureOrClassType() &&
16822 Field2Parent->isStructureOrClassType()) ||
16823 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16824 "Can't evaluate layout compatibility between a struct field and a "
16825 "union field.");
16826 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16827 (AreUnionMembers && Field1Parent->isUnionType())) &&
16828 "AreUnionMembers should be 'true' for union fields (only).");
16829#endif
16830
16831 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16832 return false;
16833
16834 if (Field1->isBitField() != Field2->isBitField())
16835 return false;
16836
16837 if (Field1->isBitField()) {
16838 // Make sure that the bit-fields are the same length.
16839 unsigned Bits1 = Field1->getBitWidthValue();
16840 unsigned Bits2 = Field2->getBitWidthValue();
16841
16842 if (Bits1 != Bits2)
16843 return false;
16844 }
16845
16846 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16847 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16848 return false;
16849
16850 if (!AreUnionMembers &&
16851 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16852 return false;
16853
16854 return true;
16855}
16856
16857/// Check if two standard-layout structs are layout-compatible.
16858/// (C++11 [class.mem] p17)
16859static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16860 const RecordDecl *RD2) {
16861 // Get to the class where the fields are declared
16862 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
16863 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16864
16865 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
16866 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16867
16868 // Check the fields.
16869 return llvm::equal(RD1->fields(), RD2->fields(),
16870 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16871 return isLayoutCompatible(C, F1, F2);
16872 });
16873}
16874
16875/// Check if two standard-layout unions are layout-compatible.
16876/// (C++11 [class.mem] p18)
16877static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16878 const RecordDecl *RD2) {
16879 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16880 RD2->fields());
16881
16882 for (auto *Field1 : RD1->fields()) {
16883 auto It = llvm::find_if(UnmatchedFields, [&](const FieldDecl *Field2) {
16884 return isLayoutCompatible(C, Field1, Field2, /*IsUnionMember=*/true);
16885 });
16886 if (It == UnmatchedFields.end())
16887 return false;
16888 [[maybe_unused]] bool Result = UnmatchedFields.erase(*It);
16889 assert(Result);
16890 }
16891
16892 return UnmatchedFields.empty();
16893}
16894
16895static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16896 const RecordDecl *RD2) {
16897 if (RD1->isUnion() != RD2->isUnion())
16898 return false;
16899
16900 if (RD1->isUnion())
16901 return isLayoutCompatibleUnion(C, RD1, RD2);
16902 else
16903 return isLayoutCompatibleStruct(C, RD1, RD2);
16904}
16905
16906/// Check if two types are layout-compatible in C++11 sense.
16907static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16908 if (T1.isNull() || T2.isNull())
16909 return false;
16910
16911 // C++20 [basic.types] p11:
16912 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16913 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16914 // or layout-compatible standard-layout class types (11.4).
16917
16918 if (C.hasSameType(T1, T2))
16919 return true;
16920
16921 const Type::TypeClass TC1 = T1->getTypeClass();
16922 const Type::TypeClass TC2 = T2->getTypeClass();
16923
16924 if (TC1 != TC2)
16925 return false;
16926
16927 if (TC1 == Type::Enum)
16928 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
16929 if (TC1 == Type::Record) {
16930 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16931 return false;
16932
16934 T2->castAsRecordDecl());
16935 }
16936
16937 return false;
16938}
16939
16941 return isLayoutCompatible(getASTContext(), T1, T2);
16942}
16943
16944//===-------------- Pointer interconvertibility ----------------------------//
16945
16947 const TypeSourceInfo *Derived) {
16948 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16949 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16950
16951 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16952 getASTContext().hasSameType(BaseT, DerivedT))
16953 return true;
16954
16955 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
16956 return false;
16957
16958 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16959 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16960 return true;
16961
16962 return false;
16963}
16964
16965//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16966
16967/// Given a type tag expression find the type tag itself.
16968///
16969/// \param TypeExpr Type tag expression, as it appears in user's code.
16970///
16971/// \param VD Declaration of an identifier that appears in a type tag.
16972///
16973/// \param MagicValue Type tag magic value.
16974///
16975/// \param isConstantEvaluated whether the evalaution should be performed in
16976
16977/// constant context.
16978static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16979 const ValueDecl **VD, uint64_t *MagicValue,
16980 bool isConstantEvaluated) {
16981 while(true) {
16982 if (!TypeExpr)
16983 return false;
16984
16985 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16986
16987 switch (TypeExpr->getStmtClass()) {
16988 case Stmt::UnaryOperatorClass: {
16989 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16990 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16991 TypeExpr = UO->getSubExpr();
16992 continue;
16993 }
16994 return false;
16995 }
16996
16997 case Stmt::DeclRefExprClass: {
16998 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16999 *VD = DRE->getDecl();
17000 return true;
17001 }
17002
17003 case Stmt::IntegerLiteralClass: {
17004 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
17005 llvm::APInt MagicValueAPInt = IL->getValue();
17006 if (MagicValueAPInt.getActiveBits() <= 64) {
17007 *MagicValue = MagicValueAPInt.getZExtValue();
17008 return true;
17009 } else
17010 return false;
17011 }
17012
17013 case Stmt::BinaryConditionalOperatorClass:
17014 case Stmt::ConditionalOperatorClass: {
17015 const AbstractConditionalOperator *ACO =
17017 bool Result;
17018 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
17019 isConstantEvaluated)) {
17020 if (Result)
17021 TypeExpr = ACO->getTrueExpr();
17022 else
17023 TypeExpr = ACO->getFalseExpr();
17024 continue;
17025 }
17026 return false;
17027 }
17028
17029 case Stmt::BinaryOperatorClass: {
17030 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
17031 if (BO->getOpcode() == BO_Comma) {
17032 TypeExpr = BO->getRHS();
17033 continue;
17034 }
17035 return false;
17036 }
17037
17038 default:
17039 return false;
17040 }
17041 }
17042}
17043
17044/// Retrieve the C type corresponding to type tag TypeExpr.
17045///
17046/// \param TypeExpr Expression that specifies a type tag.
17047///
17048/// \param MagicValues Registered magic values.
17049///
17050/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
17051/// kind.
17052///
17053/// \param TypeInfo Information about the corresponding C type.
17054///
17055/// \param isConstantEvaluated whether the evalaution should be performed in
17056/// constant context.
17057///
17058/// \returns true if the corresponding C type was found.
17060 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
17061 const ASTContext &Ctx,
17062 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
17063 *MagicValues,
17064 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
17065 bool isConstantEvaluated) {
17066 FoundWrongKind = false;
17067
17068 // Variable declaration that has type_tag_for_datatype attribute.
17069 const ValueDecl *VD = nullptr;
17070
17071 uint64_t MagicValue;
17072
17073 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
17074 return false;
17075
17076 if (VD) {
17077 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
17078 if (I->getArgumentKind() != ArgumentKind) {
17079 FoundWrongKind = true;
17080 return false;
17081 }
17082 TypeInfo.Type = I->getMatchingCType();
17083 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
17084 TypeInfo.MustBeNull = I->getMustBeNull();
17085 return true;
17086 }
17087 return false;
17088 }
17089
17090 if (!MagicValues)
17091 return false;
17092
17093 llvm::DenseMap<Sema::TypeTagMagicValue,
17095 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
17096 if (I == MagicValues->end())
17097 return false;
17098
17099 TypeInfo = I->second;
17100 return true;
17101}
17102
17104 uint64_t MagicValue, QualType Type,
17105 bool LayoutCompatible,
17106 bool MustBeNull) {
17107 if (!TypeTagForDatatypeMagicValues)
17108 TypeTagForDatatypeMagicValues.reset(
17109 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
17110
17111 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
17112 (*TypeTagForDatatypeMagicValues)[Magic] =
17113 TypeTagData(Type, LayoutCompatible, MustBeNull);
17114}
17115
17116static bool IsSameCharType(QualType T1, QualType T2) {
17117 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
17118 if (!BT1)
17119 return false;
17120
17121 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
17122 if (!BT2)
17123 return false;
17124
17125 BuiltinType::Kind T1Kind = BT1->getKind();
17126 BuiltinType::Kind T2Kind = BT2->getKind();
17127
17128 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
17129 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
17130 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
17131 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
17132}
17133
17134void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
17135 const ArrayRef<const Expr *> ExprArgs,
17136 SourceLocation CallSiteLoc) {
17137 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
17138 bool IsPointerAttr = Attr->getIsPointer();
17139
17140 // Retrieve the argument representing the 'type_tag'.
17141 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
17142 if (TypeTagIdxAST >= ExprArgs.size()) {
17143 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
17144 << 0 << Attr->getTypeTagIdx().getSourceIndex();
17145 return;
17146 }
17147 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
17148 bool FoundWrongKind;
17149 TypeTagData TypeInfo;
17150 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
17151 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
17152 TypeInfo, isConstantEvaluatedContext())) {
17153 if (FoundWrongKind)
17154 Diag(TypeTagExpr->getExprLoc(),
17155 diag::warn_type_tag_for_datatype_wrong_kind)
17156 << TypeTagExpr->getSourceRange();
17157 return;
17158 }
17159
17160 // Retrieve the argument representing the 'arg_idx'.
17161 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
17162 if (ArgumentIdxAST >= ExprArgs.size()) {
17163 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
17164 << 1 << Attr->getArgumentIdx().getSourceIndex();
17165 return;
17166 }
17167 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
17168 if (IsPointerAttr) {
17169 // Skip implicit cast of pointer to `void *' (as a function argument).
17170 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
17171 if (ICE->getType()->isVoidPointerType() &&
17172 ICE->getCastKind() == CK_BitCast)
17173 ArgumentExpr = ICE->getSubExpr();
17174 }
17175 QualType ArgumentType = ArgumentExpr->getType();
17176
17177 // Passing a `void*' pointer shouldn't trigger a warning.
17178 if (IsPointerAttr && ArgumentType->isVoidPointerType())
17179 return;
17180
17181 if (TypeInfo.MustBeNull) {
17182 // Type tag with matching void type requires a null pointer.
17183 if (!ArgumentExpr->isNullPointerConstant(Context,
17185 Diag(ArgumentExpr->getExprLoc(),
17186 diag::warn_type_safety_null_pointer_required)
17187 << ArgumentKind->getName()
17188 << ArgumentExpr->getSourceRange()
17189 << TypeTagExpr->getSourceRange();
17190 }
17191 return;
17192 }
17193
17194 QualType RequiredType = TypeInfo.Type;
17195 if (IsPointerAttr)
17196 RequiredType = Context.getPointerType(RequiredType);
17197
17198 bool mismatch = false;
17199 if (!TypeInfo.LayoutCompatible) {
17200 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
17201
17202 // C++11 [basic.fundamental] p1:
17203 // Plain char, signed char, and unsigned char are three distinct types.
17204 //
17205 // But we treat plain `char' as equivalent to `signed char' or `unsigned
17206 // char' depending on the current char signedness mode.
17207 if (mismatch)
17208 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
17209 RequiredType->getPointeeType())) ||
17210 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
17211 mismatch = false;
17212 } else
17213 if (IsPointerAttr)
17214 mismatch = !isLayoutCompatible(Context,
17215 ArgumentType->getPointeeType(),
17216 RequiredType->getPointeeType());
17217 else
17218 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
17219
17220 if (mismatch)
17221 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
17222 << ArgumentType << ArgumentKind
17223 << TypeInfo.LayoutCompatible << RequiredType
17224 << ArgumentExpr->getSourceRange()
17225 << TypeTagExpr->getSourceRange();
17226}
17227
17228void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
17229 CharUnits Alignment) {
17230 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
17231 Alignment);
17232}
17233
17235 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
17236 const NamedDecl *ND = m.RD;
17237 if (ND->getName().empty()) {
17238 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
17239 ND = TD;
17240 }
17241 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
17242 << m.MD << ND << m.E->getSourceRange();
17243 }
17245}
17246
17248 E = E->IgnoreParens();
17249 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
17250 return;
17251 if (isa<UnaryOperator>(E) &&
17252 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
17253 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
17254 if (isa<MemberExpr>(Op)) {
17255 auto &MisalignedMembersForExpr =
17257 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
17258 if (MA != MisalignedMembersForExpr.end() &&
17259 (T->isDependentType() || T->isIntegerType() ||
17260 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
17261 Context.getTypeAlignInChars(
17262 T->getPointeeType()) <= MA->Alignment))))
17263 MisalignedMembersForExpr.erase(MA);
17264 }
17265 }
17266}
17267
17269 Expr *E,
17270 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
17271 Action) {
17272 const auto *ME = dyn_cast<MemberExpr>(E);
17273 if (!ME)
17274 return;
17275
17276 // No need to check expressions with an __unaligned-qualified type.
17277 if (E->getType().getQualifiers().hasUnaligned())
17278 return;
17279
17280 // For a chain of MemberExpr like "a.b.c.d" this list
17281 // will keep FieldDecl's like [d, c, b].
17282 SmallVector<FieldDecl *, 4> ReverseMemberChain;
17283 const MemberExpr *TopME = nullptr;
17284 bool AnyIsPacked = false;
17285 do {
17286 QualType BaseType = ME->getBase()->getType();
17287 if (BaseType->isDependentType())
17288 return;
17289 if (ME->isArrow())
17290 BaseType = BaseType->getPointeeType();
17291 auto *RD = BaseType->castAsRecordDecl();
17292 if (RD->isInvalidDecl())
17293 return;
17294
17295 ValueDecl *MD = ME->getMemberDecl();
17296 auto *FD = dyn_cast<FieldDecl>(MD);
17297 // We do not care about non-data members.
17298 if (!FD || FD->isInvalidDecl())
17299 return;
17300
17301 AnyIsPacked =
17302 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
17303 ReverseMemberChain.push_back(FD);
17304
17305 TopME = ME;
17306 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
17307 } while (ME);
17308 assert(TopME && "We did not compute a topmost MemberExpr!");
17309
17310 // Not the scope of this diagnostic.
17311 if (!AnyIsPacked)
17312 return;
17313
17314 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
17315 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
17316 // TODO: The innermost base of the member expression may be too complicated.
17317 // For now, just disregard these cases. This is left for future
17318 // improvement.
17319 if (!DRE && !isa<CXXThisExpr>(TopBase))
17320 return;
17321
17322 // Alignment expected by the whole expression.
17323 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
17324
17325 // No need to do anything else with this case.
17326 if (ExpectedAlignment.isOne())
17327 return;
17328
17329 // Synthesize offset of the whole access.
17330 CharUnits Offset;
17331 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
17332 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
17333
17334 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
17335 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
17336 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
17337
17338 // The base expression of the innermost MemberExpr may give
17339 // stronger guarantees than the class containing the member.
17340 if (DRE && !TopME->isArrow()) {
17341 const ValueDecl *VD = DRE->getDecl();
17342 if (!VD->getType()->isReferenceType())
17343 CompleteObjectAlignment =
17344 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
17345 }
17346
17347 // Check if the synthesized offset fulfills the alignment.
17348 if (!Offset.isMultipleOf(ExpectedAlignment) ||
17349 // It may fulfill the offset it but the effective alignment may still be
17350 // lower than the expected expression alignment.
17351 CompleteObjectAlignment < ExpectedAlignment) {
17352 // If this happens, we want to determine a sensible culprit of this.
17353 // Intuitively, watching the chain of member expressions from right to
17354 // left, we start with the required alignment (as required by the field
17355 // type) but some packed attribute in that chain has reduced the alignment.
17356 // It may happen that another packed structure increases it again. But if
17357 // we are here such increase has not been enough. So pointing the first
17358 // FieldDecl that either is packed or else its RecordDecl is,
17359 // seems reasonable.
17360 FieldDecl *FD = nullptr;
17361 CharUnits Alignment;
17362 for (FieldDecl *FDI : ReverseMemberChain) {
17363 if (FDI->hasAttr<PackedAttr>() ||
17364 FDI->getParent()->hasAttr<PackedAttr>()) {
17365 FD = FDI;
17366 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
17367 Context.getTypeAlignInChars(
17368 Context.getCanonicalTagType(FD->getParent())));
17369 break;
17370 }
17371 }
17372 assert(FD && "We did not find a packed FieldDecl!");
17373 Action(E, FD->getParent(), FD, Alignment);
17374 }
17375}
17376
17377void Sema::CheckAddressOfPackedMember(Expr *rhs) {
17378 using namespace std::placeholders;
17379
17381 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
17382 _2, _3, _4));
17383}
17384
17386 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17387 if (checkArgCount(TheCall, 1))
17388 return true;
17389
17390 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
17391 if (A.isInvalid())
17392 return true;
17393
17394 TheCall->setArg(0, A.get());
17395 QualType TyA = A.get()->getType();
17396
17397 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
17398 ArgTyRestr, 1))
17399 return true;
17400
17401 TheCall->setType(TyA);
17402 return false;
17403}
17404
17405bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
17406 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17407 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
17408 TheCall->setType(*Res);
17409 return false;
17410 }
17411 return true;
17412}
17413
17415 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
17416 if (!Res)
17417 return true;
17418
17419 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
17420 TheCall->setType(VecTy0->getElementType());
17421 else
17422 TheCall->setType(*Res);
17423
17424 return false;
17425}
17426
17428 SourceLocation Loc) {
17430 R = RHS->getEnumCoercedType(S.Context);
17431 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
17433 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
17434 << LHS->getSourceRange() << RHS->getSourceRange()
17435 << /*Arithmetic Between*/ 0 << L << R;
17436 }
17437 return false;
17438}
17439
17440/// Check if all arguments have the same type. If the types don't match, emit an
17441/// error message and return true. Otherwise return false.
17442///
17443/// For scalars we directly compare their unqualified types. But even if we
17444/// compare unqualified vector types, a difference in qualifiers in the element
17445/// types can make the vector types be considered not equal. For example,
17446/// vector of 4 'const float' values vs vector of 4 'float' values.
17447/// So we compare unqualified types of their elements and number of elements.
17449 ArrayRef<Expr *> Args) {
17450 assert(!Args.empty() && "Should have at least one argument.");
17451
17452 Expr *Arg0 = Args.front();
17453 QualType Ty0 = Arg0->getType();
17454
17455 auto EmitError = [&](Expr *ArgI) {
17456 SemaRef.Diag(Arg0->getBeginLoc(),
17457 diag::err_typecheck_call_different_arg_types)
17458 << Arg0->getType() << ArgI->getType();
17459 };
17460
17461 // Compare scalar types.
17462 if (!Ty0->isVectorType()) {
17463 for (Expr *ArgI : Args.drop_front())
17464 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
17465 EmitError(ArgI);
17466 return true;
17467 }
17468
17469 return false;
17470 }
17471
17472 // Compare vector types.
17473 const auto *Vec0 = Ty0->castAs<VectorType>();
17474 for (Expr *ArgI : Args.drop_front()) {
17475 const auto *VecI = ArgI->getType()->getAs<VectorType>();
17476 if (!VecI ||
17477 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
17478 VecI->getElementType()) ||
17479 Vec0->getNumElements() != VecI->getNumElements()) {
17480 EmitError(ArgI);
17481 return true;
17482 }
17483 }
17484
17485 return false;
17486}
17487
17488std::optional<QualType>
17490 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17491 if (checkArgCount(TheCall, 2))
17492 return std::nullopt;
17493
17495 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
17496 return std::nullopt;
17497
17498 Expr *Args[2];
17499 for (int I = 0; I < 2; ++I) {
17500 ExprResult Converted =
17501 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
17502 if (Converted.isInvalid())
17503 return std::nullopt;
17504 Args[I] = Converted.get();
17505 }
17506
17507 SourceLocation LocA = Args[0]->getBeginLoc();
17508 QualType TyA = Args[0]->getType();
17509
17510 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
17511 return std::nullopt;
17512
17513 if (checkBuiltinVectorMathArgTypes(*this, Args))
17514 return std::nullopt;
17515
17516 TheCall->setArg(0, Args[0]);
17517 TheCall->setArg(1, Args[1]);
17518 return TyA;
17519}
17520
17522 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17523 if (checkArgCount(TheCall, 3))
17524 return true;
17525
17526 SourceLocation Loc = TheCall->getExprLoc();
17527 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
17528 TheCall->getArg(1), Loc) ||
17529 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
17530 TheCall->getArg(2), Loc))
17531 return true;
17532
17533 Expr *Args[3];
17534 for (int I = 0; I < 3; ++I) {
17535 ExprResult Converted =
17536 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
17537 if (Converted.isInvalid())
17538 return true;
17539 Args[I] = Converted.get();
17540 }
17541
17542 int ArgOrdinal = 1;
17543 for (Expr *Arg : Args) {
17544 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
17545 ArgTyRestr, ArgOrdinal++))
17546 return true;
17547 }
17548
17549 if (checkBuiltinVectorMathArgTypes(*this, Args))
17550 return true;
17551
17552 for (int I = 0; I < 3; ++I)
17553 TheCall->setArg(I, Args[I]);
17554
17555 TheCall->setType(Args[0]->getType());
17556 return false;
17557}
17558
17559bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17560 if (checkArgCount(TheCall, 1))
17561 return true;
17562
17563 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17564 if (A.isInvalid())
17565 return true;
17566
17567 TheCall->setArg(0, A.get());
17568 return false;
17569}
17570
17571bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
17572 if (checkArgCount(TheCall, 1))
17573 return true;
17574
17575 ExprResult Arg = TheCall->getArg(0);
17576 QualType TyArg = Arg.get()->getType();
17577
17578 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
17579 return Diag(TheCall->getArg(0)->getBeginLoc(),
17580 diag::err_builtin_invalid_arg_type)
17581 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
17582
17583 TheCall->setType(TyArg);
17584 return false;
17585}
17586
17587ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
17588 ExprResult CallResult) {
17589 if (checkArgCount(TheCall, 1))
17590 return ExprError();
17591
17592 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17593 if (MatrixArg.isInvalid())
17594 return MatrixArg;
17595 Expr *Matrix = MatrixArg.get();
17596
17597 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17598 if (!MType) {
17599 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17600 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
17601 << Matrix->getType();
17602 return ExprError();
17603 }
17604
17605 // Create returned matrix type by swapping rows and columns of the argument
17606 // matrix type.
17607 QualType ResultType = Context.getConstantMatrixType(
17608 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17609
17610 // Change the return type to the type of the returned matrix.
17611 TheCall->setType(ResultType);
17612
17613 // Update call argument to use the possibly converted matrix argument.
17614 TheCall->setArg(0, Matrix);
17615 return CallResult;
17616}
17617
17618// Get and verify the matrix dimensions.
17619static std::optional<unsigned>
17621 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
17622 if (!Value) {
17623 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17624 << Name;
17625 return {};
17626 }
17627 uint64_t Dim = Value->getZExtValue();
17628 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
17629 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17630 << Name << S.Context.getLangOpts().MaxMatrixDimension;
17631 return {};
17632 }
17633 return Dim;
17634}
17635
17636ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17637 ExprResult CallResult) {
17638 if (!getLangOpts().MatrixTypes) {
17639 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17640 return ExprError();
17641 }
17642
17643 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17645 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17646 << /*column*/ 1 << /*load*/ 0;
17647 return ExprError();
17648 }
17649
17650 if (checkArgCount(TheCall, 4))
17651 return ExprError();
17652
17653 unsigned PtrArgIdx = 0;
17654 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17655 Expr *RowsExpr = TheCall->getArg(1);
17656 Expr *ColumnsExpr = TheCall->getArg(2);
17657 Expr *StrideExpr = TheCall->getArg(3);
17658
17659 bool ArgError = false;
17660
17661 // Check pointer argument.
17662 {
17664 if (PtrConv.isInvalid())
17665 return PtrConv;
17666 PtrExpr = PtrConv.get();
17667 TheCall->setArg(0, PtrExpr);
17668 if (PtrExpr->isTypeDependent()) {
17669 TheCall->setType(Context.DependentTy);
17670 return TheCall;
17671 }
17672 }
17673
17674 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17675 QualType ElementTy;
17676 if (!PtrTy) {
17677 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17678 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
17679 << PtrExpr->getType();
17680 ArgError = true;
17681 } else {
17682 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17683
17685 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17686 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
17687 << /* no fp */ 0 << PtrExpr->getType();
17688 ArgError = true;
17689 }
17690 }
17691
17692 // Apply default Lvalue conversions and convert the expression to size_t.
17693 auto ApplyArgumentConversions = [this](Expr *E) {
17695 if (Conv.isInvalid())
17696 return Conv;
17697
17698 return tryConvertExprToType(Conv.get(), Context.getSizeType());
17699 };
17700
17701 // Apply conversion to row and column expressions.
17702 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17703 if (!RowsConv.isInvalid()) {
17704 RowsExpr = RowsConv.get();
17705 TheCall->setArg(1, RowsExpr);
17706 } else
17707 RowsExpr = nullptr;
17708
17709 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17710 if (!ColumnsConv.isInvalid()) {
17711 ColumnsExpr = ColumnsConv.get();
17712 TheCall->setArg(2, ColumnsExpr);
17713 } else
17714 ColumnsExpr = nullptr;
17715
17716 // If any part of the result matrix type is still pending, just use
17717 // Context.DependentTy, until all parts are resolved.
17718 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17719 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17720 TheCall->setType(Context.DependentTy);
17721 return CallResult;
17722 }
17723
17724 // Check row and column dimensions.
17725 std::optional<unsigned> MaybeRows;
17726 if (RowsExpr)
17727 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17728
17729 std::optional<unsigned> MaybeColumns;
17730 if (ColumnsExpr)
17731 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17732
17733 // Check stride argument.
17734 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17735 if (StrideConv.isInvalid())
17736 return ExprError();
17737 StrideExpr = StrideConv.get();
17738 TheCall->setArg(3, StrideExpr);
17739
17740 if (MaybeRows) {
17741 if (std::optional<llvm::APSInt> Value =
17742 StrideExpr->getIntegerConstantExpr(Context)) {
17743 uint64_t Stride = Value->getZExtValue();
17744 if (Stride < *MaybeRows) {
17745 Diag(StrideExpr->getBeginLoc(),
17746 diag::err_builtin_matrix_stride_too_small);
17747 ArgError = true;
17748 }
17749 }
17750 }
17751
17752 if (ArgError || !MaybeRows || !MaybeColumns)
17753 return ExprError();
17754
17755 TheCall->setType(
17756 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17757 return CallResult;
17758}
17759
17760ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17761 ExprResult CallResult) {
17762 if (!getLangOpts().MatrixTypes) {
17763 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17764 return ExprError();
17765 }
17766
17767 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17769 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17770 << /*column*/ 1 << /*store*/ 1;
17771 return ExprError();
17772 }
17773
17774 if (checkArgCount(TheCall, 3))
17775 return ExprError();
17776
17777 unsigned PtrArgIdx = 1;
17778 Expr *MatrixExpr = TheCall->getArg(0);
17779 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17780 Expr *StrideExpr = TheCall->getArg(2);
17781
17782 bool ArgError = false;
17783
17784 {
17785 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17786 if (MatrixConv.isInvalid())
17787 return MatrixConv;
17788 MatrixExpr = MatrixConv.get();
17789 TheCall->setArg(0, MatrixExpr);
17790 }
17791 if (MatrixExpr->isTypeDependent()) {
17792 TheCall->setType(Context.DependentTy);
17793 return TheCall;
17794 }
17795
17796 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17797 if (!MatrixTy) {
17798 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17799 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17800 ArgError = true;
17801 }
17802
17803 {
17805 if (PtrConv.isInvalid())
17806 return PtrConv;
17807 PtrExpr = PtrConv.get();
17808 TheCall->setArg(1, PtrExpr);
17809 if (PtrExpr->isTypeDependent()) {
17810 TheCall->setType(Context.DependentTy);
17811 return TheCall;
17812 }
17813 }
17814
17815 // Check pointer argument.
17816 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17817 if (!PtrTy) {
17818 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17819 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17820 << PtrExpr->getType();
17821 ArgError = true;
17822 } else {
17823 QualType ElementTy = PtrTy->getPointeeType();
17824 if (ElementTy.isConstQualified()) {
17825 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17826 ArgError = true;
17827 }
17828 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17829 if (MatrixTy &&
17830 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17831 Diag(PtrExpr->getBeginLoc(),
17832 diag::err_builtin_matrix_pointer_arg_mismatch)
17833 << ElementTy << MatrixTy->getElementType();
17834 ArgError = true;
17835 }
17836 }
17837
17838 // Apply default Lvalue conversions and convert the stride expression to
17839 // size_t.
17840 {
17841 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17842 if (StrideConv.isInvalid())
17843 return StrideConv;
17844
17845 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17846 if (StrideConv.isInvalid())
17847 return StrideConv;
17848 StrideExpr = StrideConv.get();
17849 TheCall->setArg(2, StrideExpr);
17850 }
17851
17852 // Check stride argument.
17853 if (MatrixTy) {
17854 if (std::optional<llvm::APSInt> Value =
17855 StrideExpr->getIntegerConstantExpr(Context)) {
17856 uint64_t Stride = Value->getZExtValue();
17857 if (Stride < MatrixTy->getNumRows()) {
17858 Diag(StrideExpr->getBeginLoc(),
17859 diag::err_builtin_matrix_stride_too_small);
17860 ArgError = true;
17861 }
17862 }
17863 }
17864
17865 if (ArgError)
17866 return ExprError();
17867
17868 return CallResult;
17869}
17870
17872 const NamedDecl *Callee) {
17873 // This warning does not make sense in code that has no runtime behavior.
17875 return;
17876
17877 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17878
17879 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17880 return;
17881
17882 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17883 // all TCBs the callee is a part of.
17884 llvm::StringSet<> CalleeTCBs;
17885 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17886 CalleeTCBs.insert(A->getTCBName());
17887 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17888 CalleeTCBs.insert(A->getTCBName());
17889
17890 // Go through the TCBs the caller is a part of and emit warnings if Caller
17891 // is in a TCB that the Callee is not.
17892 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17893 StringRef CallerTCB = A->getTCBName();
17894 if (CalleeTCBs.count(CallerTCB) == 0) {
17895 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17896 << Callee << CallerTCB;
17897 }
17898 }
17899}
Defines the clang::ASTContext interface.
#define V(N, I)
Provides definitions for the various language-specific address spaces.
Defines the Diagnostic-related interfaces.
Defines enumerations for traits support.
static bool getTypeString(SmallStringEnc &Enc, const Decl *D, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC)
The XCore ABI includes a type information section that communicates symbol type information to the li...
Definition XCore.cpp:630
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
std::shared_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token's formatting.
unsigned IsFirst
Indicates that this is the first token of the file.
TokenType getType() const
Returns the token's type, e.g.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Result
Implement __builtin_bit_cast and related operations.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::OpenCLOptions class.
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
llvm::json::Object Object
llvm::json::Array Array
static std::string getFunctionName(const CallEvent &Call)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis functions specific to BPF.
static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout unions are layout-compatible.
static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, const ValueDecl **VD, uint64_t *MagicValue, bool isConstantEvaluated)
Given a type tag expression find the type tag itself.
static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, SourceLocation CC, QualType T)
static QualType getSizeOfArgType(const Expr *E)
If E is a sizeof expression, returns its argument type.
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, SourceLocation CallSiteLoc)
static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind, bool RequireConstant=false)
static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall)
static const CXXRecordDecl * getContainedDynamicClass(QualType T, bool &IsContained)
Determine whether the given type is or contains a dynamic class type (e.g., whether it has a vtable).
static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call)
static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall)
static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call)
static bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType, QualType T)
static bool IsSameFloatAfterCast(const llvm::APFloat &value, const llvm::fltSemantics &Src, const llvm::fltSemantics &Tgt)
Checks whether the given value, which currently has the given source semantics, has the same value wh...
static void AnalyzeComparison(Sema &S, BinaryOperator *E)
Implements -Wsign-compare.
static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, BinaryOperatorKind BinOpKind, bool AddendIsRight)
static std::pair< QualType, StringRef > shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy, const Expr *E)
static QualType GetExprType(const Expr *E)
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx)
This helper function takes an lvalue expression and returns the alignment of a VarDecl and a constant...
static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, Expr *Other, const llvm::APSInt &Value, bool RhsConstant)
static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex, bool ToBool)
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, const IdentifierInfo *FnName, SourceLocation FnLoc, SourceLocation RParenLoc)
Takes the expression passed to the size_t parameter of functions such as memcmp, strncat,...
static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall)
static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_stdc_rotate_{left,right} was called with two arguments, that the first argument...
static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref, ArrayRef< EquatableFormatArgument > RefArgs, const StringLiteral *Fmt, ArrayRef< EquatableFormatArgument > FmtArgs, const Expr *FmtExpr, bool InFunctionCall)
static bool BuiltinBswapg(Sema &S, CallExpr *TheCall)
Checks that __builtin_bswapg was called with a single argument, which is an unsigned integer,...
static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall)
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op)
static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, Scope::ScopeFlags NeededScopeFlags, unsigned DiagID)
static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E)
Analyze the given compound assignment for the possible losing of floating-point precision.
static bool doesExprLikelyComputeSize(const Expr *SizeofExpr)
Detect if SizeofExpr is likely to calculate the sizeof an object.
static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, bool inFunctionCall, VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, bool IgnoreStringsWithoutSpecifiers)
static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall)
Check the number of arguments and set the result type to the argument type.
static bool CheckForReference(Sema &SemaRef, const Expr *E, const PartialDiagnostic &PD)
static const UnaryExprOrTypeTraitExpr * getAsSizeOfExpr(const Expr *E)
static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID)
Check that the value argument for __builtin_is_aligned(value, alignment) and __builtin_aligned_{up,...
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
static bool isKnownToHaveUnsignedValue(const Expr *E)
static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef, ArrayRef< Expr * > Args)
Check if all arguments have the same type.
static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call)
Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the last two arguments transpose...
static bool checkPointerAuthEnabled(Sema &S, Expr *E)
static std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range)
static ExprResult BuiltinMaskedStore(Sema &S, CallExpr *TheCall)
AbsoluteValueKind
@ AVK_Complex
@ AVK_Floating
@ AVK_Integer
static const Expr * getStrlenExprArg(const Expr *E)
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check)
static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall, const TargetInfo *AuxTI, unsigned BuiltinID)
BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
static bool isValidMathElementType(QualType T)
static void DiagnoseDeprecatedHIPAtomic(Sema &S, SourceRange ExprRange, MultiExprArg Args, AtomicExpr::AtomicOp Op)
Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_* equivalents.
static bool IsSameCharType(QualType T1, QualType T2)
static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E)
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall)
static bool isArgumentExpandedFromMacro(SourceManager &SM, SourceLocation CallLoc, SourceLocation ArgLoc)
Check if the ArgLoc originated from a macro passed to the call at CallLoc.
static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth)
static const IntegerLiteral * getIntegerLiteral(Expr *E)
#define HIP_ATOMIC_FIXABLE(hip, scoped)
static bool CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall, ArrayRef< llvm::Triple::ArchType > SupportedArchs)
static const Expr * maybeConstEvalStringLiteral(ASTContext &Context, const Expr *E)
static bool IsStdFunction(const FunctionDecl *FDecl, const char(&Str)[StrLen])
static void AnalyzeAssignment(Sema &S, BinaryOperator *E)
Analyze the given simple or compound assignment for warning-worthy operations.
static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_function_start is a function.
static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall)
static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, SourceLocation StmtLoc, const NullStmt *Body)
static std::pair< CharUnits, CharUnits > getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, CharUnits BaseAlignment, CharUnits Offset, ASTContext &Ctx)
Compute the alignment and offset of the base class object given the derived-to-base cast expression a...
static std::pair< const ValueDecl *, CharUnits > findConstantBaseAndOffset(Sema &S, Expr *E)
static QualType getVectorElementType(ASTContext &Context, QualType VecTy)
static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E)
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
static std::optional< IntRange > TryGetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, bool InConstantContext, bool Approximate)
Attempts to estimate an approximate range for the given integer expression.
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
static ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall)
static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall, SourceLocation CC)
static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall)
Checks that __builtin_bitreverseg was called with a single argument, which is an integer.
static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool &ICContext)
static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall)
static bool CheckMissingFormatAttribute(Sema *S, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, StringLiteral *ReferenceFormatString, unsigned FormatIdx, unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx, SourceLocation Loc)
static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call)
static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, SourceLocation InitLoc)
Analyzes an attempt to assign the given value to a bitfield.
static void CheckCommaOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool ExtraCheckForImplicitConversion, llvm::SmallVectorImpl< AnalyzeImplicitConversionsWorkItem > &WorkList)
static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T, SourceLocation CContext)
Diagnose an implicit cast from a floating point value to an integer value.
static int classifyConstantValue(Expr *Constant)
static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc)
static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, unsigned AbsKind, QualType ArgType)
static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2)
Check if two types are layout-compatible in C++11 sense.
static ExprResult PointerAuthAuthWithPCAndResign(Sema &S, CallExpr *Call)
static bool checkPointerAuthKey(Sema &S, Expr *&Arg)
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, Qualifiers::ObjCLifetime LT, Expr *RHS, bool isProperty)
static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID)
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl)
static llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool IsInfinityFunction(const FunctionDecl *FDecl)
static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType, QualType T, SourceLocation CContext, unsigned diag, bool PruneControlFlow=false)
Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr * > Args, SourceLocation CallSiteLoc)
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction)
static analyze_format_string::ArgType::MatchKind handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match, DiagnosticsEngine &Diags, SourceLocation Loc)
static bool referToTheSameDecl(const Expr *E1, const Expr *E2)
Check if two expressions refer to the same declaration.
static ExprResult BuiltinMaskedScatter(Sema &S, CallExpr *TheCall)
#define BUILTIN_ROW(x)
static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_{clzg,ctzg} was called with a first argument, which is an unsigned integer,...
static ExprResult GetVTablePointer(Sema &S, CallExpr *Call)
static bool requiresParensToAddCast(const Expr *E)
static bool HasEnumType(const Expr *E)
static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call)
static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall)
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
static StringLiteralCheckType checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString, const Expr *E, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset, std::optional< unsigned > *CallerFormatParamIdx=nullptr, bool IgnoreStringsWithoutSpecifiers=false)
static std::optional< unsigned > getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S)
static 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 checkConstantArgValueRange(Sema &S, CallExpr *TheCall, unsigned ArgNum, const llvm::APSInt &Result, int Low, int High, bool RangeIsError)
static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr, int ArgOrdinal)
static bool GetMatchingCType(const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, const ASTContext &Ctx, const llvm::DenseMap< Sema::TypeTagMagicValue, Sema::TypeTagData > *MagicValues, bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, bool isConstantEvaluated)
Retrieve the C type corresponding to type tag TypeExpr.
static QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall)
static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall)
static bool isNonNullType(QualType type)
Determine whether the given type has a non-null nullability annotation.
static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A, Sema::FormatArgumentPassingKind B)
static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall)
Check that the first argument to __builtin_annotation is an integer and the second argument is a non-...
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx)
This helper function takes a pointer expression and returns the alignment of a VarDecl and a constant...
static bool IsShiftedByte(llvm::APSInt Value)
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, unsigned AbsFunctionKind)
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
checkBuiltinArgument - Given a call to a builtin function, perform normal type-checking on the given ...
static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E)
Analyze the operands of the given comparison.
static ExprResult PointerAuthAuthLoadRelativeAndSign(Sema &S, CallExpr *Call)
static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall, QualType ReturnType)
Checks the __builtin_stdc_* builtins that take a single unsigned integer argument and return either i...
static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
static bool isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE)
Return true if ICE is an implicit argument promotion of an arithmetic type.
static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, bool IsListInit=false)
AnalyzeImplicitConversions - Find and report any interesting implicit conversions in the given expres...
static std::optional< std::pair< CharUnits, CharUnits > > getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, bool IsSub, ASTContext &Ctx)
Compute the alignment and offset of a binary additive operator.
static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
This file declares semantic analysis for DirectX constructs.
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis functions specific to Hexagon.
This file declares semantic analysis functions specific to LoongArch.
This file declares semantic analysis functions specific to MIPS.
This file declares semantic analysis functions specific to NVPTX.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis routines for OpenCL.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SPIRV constructs.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to SystemZ.
This file declares semantic analysis functions specific to Wasm.
This file declares semantic analysis functions specific to X86.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Provides definitions for the atomic synchronization scopes.
C Language Family Type Representation.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__DEVICE__ int min(int __a, int __b)
static bool hasLayout(const RecordDecl *D)
Whether layout (offset and size) information can be queried for D.
@ GE_None
No error.
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatch
The conversion specifier and the argument types are incompatible.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ MatchPromotion
The conversion specifier and the argument type are compatible because of default argument promotions.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
@ NoMatchTypeConfusion
The conversion specifier and the argument type are compatible, but still seems likely to be an error.
@ NoMatchPromotionTypeConfusion
The conversion specifier and the argument type are compatible but still seems likely to be an error.
unsigned getLength() const
const char * getStart() const
StringRef toString() const
const char * getStart() const
HowSpecified getHowSpecified() const
unsigned getConstantAmount() const
unsigned getConstantLength() const
bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx, bool IsObjCLiteral)
Changes the specifier and length according to a QualType, retaining any flags or options.
void toString(raw_ostream &os) const
Sema::SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when the only matching conversion function is explicit.
Sema::SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when the expression has incomplete class type.
Sema::SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for one of the candidate conversions.
Sema::SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when there are multiple possible conversion functions.
Sema::SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
Sema::SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
Sema::SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for the explicit conversion function.
bool match(QualType T) override
Determine whether the specified type is a valid destination type for this conversion.
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
void toString(raw_ostream &os) const
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
APSInt & getInt()
Definition APValue.h:577
bool isVector() const
Definition APValue.h:555
APSInt & getComplexIntImag()
Definition APValue.h:615
bool isComplexInt() const
Definition APValue.h:552
bool isFloat() const
Definition APValue.h:550
bool isComplexFloat() const
Definition APValue.h:553
APValue & getVectorElt(unsigned I)
Definition APValue.h:651
unsigned getVectorLength() const
Definition APValue.h:659
bool isLValue() const
Definition APValue.h:554
bool isInt() const
Definition APValue.h:549
APValue & getMatrixElt(unsigned Idx)
Definition APValue.h:675
APSInt & getComplexIntReal()
Definition APValue.h:607
APFloat & getComplexFloatImag()
Definition APValue.h:631
APFloat & getComplexFloatReal()
Definition APValue.h:623
APFloat & getFloat()
Definition APValue.h:591
bool isMatrix() const
Definition APValue.h:556
unsigned getMatrixNumElements() const
Definition APValue.h:672
bool isAddrLabelDiff() const
Definition APValue.h:561
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:855
Builtin::Context & BuiltinInfo
Definition ASTContext.h:857
const LangOptions & getLangOpts() const
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
CanQualType OverloadTy
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:908
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
CanQualType UnsignedIntTy
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
CanQualType UnsignedShortTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:974
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
@ GE_None
No error.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getNonVirtualAlignment() const
getNonVirtualAlignment - Get the non-virtual alignment (in chars) of an object, which is the alignmen...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4422
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4600
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4606
SourceLocation getQuestionLoc() const
Definition Expr.h:4449
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4612
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:7383
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7387
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2790
SourceLocation getRBracketLoc() const
Definition Expr.h:2838
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2819
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3834
QualType getElementType() const
Definition TypeBase.h:3832
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:7014
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:7163
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:7145
Attr - This represents one attribute.
Definition Attr.h:47
const char * getSpelling() const
Type source information for an attributed type.
Definition TypeLoc.h:1008
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1022
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4107
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4240
Expr * getLHS() const
Definition Expr.h:4157
SourceLocation getOperatorLoc() const
Definition Expr.h:4149
SourceLocation getExprLoc() const
Definition Expr.h:4148
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2170
Expr * getRHS() const
Definition Expr.h:4159
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4193
Opcode getOpcode() const
Definition Expr.h:4152
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4204
BinaryOperatorKind Opcode
Definition Expr.h:4112
Pointer to a block type.
Definition TypeBase.h:3653
This class is used for builtin types like 'int'.
Definition TypeBase.h:3245
bool isInteger() const
Definition TypeBase.h:3312
bool isFloatingPoint() const
Definition TypeBase.h:3324
bool isSignedInteger() const
Definition TypeBase.h:3316
bool isUnsignedInteger() const
Definition TypeBase.h:3320
Kind getKind() const
Definition TypeBase.h:3299
llvm::SmallString< 64 > getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:99
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:385
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition Builtins.cpp:94
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition Expr.h:4038
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition ExprCXX.h:1635
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1693
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2994
Represents a C++ destructor within a class.
Definition DeclCXX.h:2924
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:86
SourceLocation getExprLoc() const LLVM_READONLY
Definition ExprCXX.h:159
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:116
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5195
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5235
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:1235
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:549
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1224
bool isDynamicClass() const
Definition DeclCXX.h:575
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:77
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
SourceLocation getBeginLoc() const
Definition Expr.h:3346
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3229
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1624
arg_iterator arg_begin()
Definition Expr.h:3269
arg_iterator arg_end()
Definition Expr.h:3272
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3195
bool isCallToStdMove() const
Definition Expr.cpp:3682
Expr * getCallee()
Definition Expr.h:3159
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3203
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3305
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3206
arg_range arguments()
Definition Expr.h:3264
SourceLocation getEndLoc() const
Definition Expr.h:3365
SourceLocation getRParenLoc() const
Definition Expr.h:3343
Decl * getCalleeDecl()
Definition Expr.h:3189
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:1629
void setCallee(Expr *F)
Definition Expr.h:3161
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition Expr.h:3248
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:3745
path_iterator path_begin()
Definition Expr.h:3815
CastKind getCastKind() const
Definition Expr.h:3789
path_iterator path_end()
Definition Expr.h:3816
Expr * getSubExpr()
Definition Expr.h:3795
Represents a byte-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
bool isOne() const
Test whether the quantity equals one.
Definition CharUnits.h:104
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
static CharUnits Zero()
Construct a CharUnits quantity of zero.
Definition CharUnits.h:52
ConditionalOperator - The ?
Definition Expr.h:4460
Expr * getLHS() const
Definition Expr.h:4494
Expr * getRHS() const
Definition Expr.h:4495
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
QualType desugar() const
Definition TypeBase.h:3959
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3914
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4622
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4649
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:5731
Expr * getOperand() const
Definition ExprCXX.h:5378
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:1467
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2110
bool isStdNamespace() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2407
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2165
DeclContext * getEnclosingNonExpansionStatementContext()
Retrieve the innermost enclosing context that doesn't belong to an expansion statement.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
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:498
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1408
ValueDecl * getDecl()
Definition Expr.h:1383
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1513
SourceLocation getBeginLoc() const
Definition Expr.h:1394
SourceLocation getLocation() const
Definition Expr.h:1391
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:453
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:444
T * getAttr() const
Definition DeclBase.h:582
void addAttr(Attr *A)
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:572
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:597
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:568
SourceLocation getLocation() const
Definition DeclBase.h:448
DeclContext * getDeclContext()
Definition DeclBase.h:457
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:440
bool hasAttr() const
Definition DeclBase.h:586
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:436
The name of a declaration.
std::string getAsString() const
Retrieve the human-readable string for this name.
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2005
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:811
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred since this object instance was created.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:240
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3604
Represents an enum.
Definition Decl.h:4192
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4424
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4365
This represents one expression.
Definition Expr.h:114
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3156
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:703
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition Expr.h:700
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3134
void setType(QualType t)
Definition Expr.h:147
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:449
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:196
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3129
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3117
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:248
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:3125
bool isFlexibleArrayMemberLike(const ASTContext &Context, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution=false) const
Check whether this array fits the idiom of a flexible array member, depending on the value of -fstric...
Definition Expr.cpp:212
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:286
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4271
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:876
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:880
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:456
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreCasts() LLVM_READONLY
Skip past any casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3113
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3121
std::optional< uint64_t > tryEvaluateStrLen(const ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3728
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:225
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3109
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:847
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:856
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:859
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:849
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:4110
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:272
std::optional< uint64_t > tryEvaluateObjectSize(const ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:466
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:469
QualType getType() const
Definition Expr.h:146
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:528
const ValueDecl * getAsBuiltinConstantDeclRef(const ASTContext &Context) const
If this expression is an unambiguous reference to a single declaration, in the style of __builtin_fun...
Definition Expr.cpp:232
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition Expr.cpp:138
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition TypeBase.h:4497
Represents a member of a struct/union/class.
Definition Decl.h:3341
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3444
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4855
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3577
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3457
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:78
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:139
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:128
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:102
llvm::APFloat getValue() const
Definition Expr.h:1711
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2899
Represents a function declaration or definition.
Definition Decl.h:2082
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4650
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2974
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3836
param_iterator param_end()
Definition Decl.h:2960
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3944
QualType getReturnType() const
Definition Decl.h:3022
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2947
param_iterator param_begin()
Definition Decl.h:2959
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3137
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4405
bool isStatic() const
Definition Decl.h:3106
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4220
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4206
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3900
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
unsigned getNumParams() const
Definition TypeBase.h:5826
QualType getParamType(unsigned i) const
Definition TypeBase.h:5828
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5952
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5837
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5947
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5833
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4744
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3854
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:5053
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:5049
CallingConv getCallConv() const
Definition TypeBase.h:5099
QualType getReturnType() const
Definition TypeBase.h:5084
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:3922
Describes an C or C++ initializer list.
Definition Expr.h:5377
ArrayRef< Expr * > inits() const
Definition Expr.h:5441
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:985
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:1075
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1111
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:509
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1158
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:882
Represents the results of name lookup.
Definition Lookup.h:147
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4567
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4593
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3433
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3516
Expr * getBase() const
Definition Expr.h:3510
bool isArrow() const
Definition Expr.h:3617
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
This represents a decl that may have a name.
Definition Decl.h:276
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1209
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1945
Represent a C++ namespace.
Definition Decl.h:594
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition Stmt.h:1714
bool hasLeadingEmptyMacro() const
Definition Stmt.h:1728
SourceLocation getSemiLoc() const
Definition Stmt.h:1725
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:734
QualType getType() const
Definition DeclObjC.h:810
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition DeclObjC.h:833
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:821
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition ExprObjC.h:649
ObjCPropertyDecl * getExplicitProperty() const
Definition ExprObjC.h:738
bool isImplicitProperty() const
Definition ExprObjC.h:735
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:83
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:280
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2251
Represents a parameter to a function.
Definition Decl.h:1832
Pointer-authentication qualifiers.
Definition TypeBase.h:153
@ MaxDiscriminator
The maximum supported pointer-authentication discriminator.
Definition TypeBase.h:233
bool isAddressDiscriminated() const
Definition TypeBase.h:266
ARM8_3Key
Hardware pointer-signing keys in ARM8.3.
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6890
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5238
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8662
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:3099
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1469
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1230
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8578
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8704
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8618
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition TypeBase.h:8630
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8672
void removeLocalVolatile()
Definition TypeBase.h:8694
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1195
void removeLocalConst()
Definition TypeBase.h:8686
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8651
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8699
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1841
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8624
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1458
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
bool hasUnaligned() const
Definition TypeBase.h:512
Represents a struct/union/class.
Definition Decl.h:4506
bool hasFlexibleArrayMember() const
Definition Decl.h:4539
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4592
field_range fields() const
Definition Decl.h:4709
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4584
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:602
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
ScopeFlags
ScopeFlags - These are bitfields that are or'd together when creating a scope, which defines the sort...
Definition Scope.h:45
@ SEHFilterScope
We are currently in the filter expression of an SEH except block.
Definition Scope.h:131
@ SEHExceptScope
This scope corresponds to an SEH except.
Definition Scope.h:128
bool CheckAMDGCNBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1191
@ 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:1275
void notePreserveAIEnumerator(const Expr *E)
Definition SemaBPF.cpp:385
static bool isPreserveAIEnumeratorRef(const Expr *E)
Definition SemaBPF.cpp:338
bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Definition SemaBPF.cpp:134
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:120
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
bool CheckDirectXBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaMIPS.cpp:25
bool CheckNVPTXBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaNVPTX.cpp:21
void checkArrayLiteral(QualType TargetType, ObjCArrayLiteral *ArrayLiteral)
Check an Objective-C array literal being converted to the given target type.
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
void adornBoolConversionDiagWithTernaryFixit(const Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder)
bool isSignedCharBool(QualType Ty)
void DiagnoseCStringFormatDirectiveInCFAPI(const NamedDecl *FDecl, Expr **Args, unsigned NumArgs)
Diagnose use of s directive in an NSString which is being passed as formatting string to formatting m...
void checkDictionaryLiteral(QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaPPC.cpp:113
void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg)
Definition SemaPPC.cpp:32
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition SemaPPC.cpp:422
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSPIRVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
SemaDiagnosticBuilder DiagIfDeviceCode(SourceLocation Loc, unsigned DiagID)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as device c...
Definition SemaSYCL.cpp:31
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaWasm.cpp:289
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaX86.cpp:574
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10559
ContextualImplicitConverter(bool Suppress=false, bool SuppressConversion=false)
Definition Sema.h:10564
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
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:1493
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:13362
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1172
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:2914
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9568
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9576
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9613
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:7130
bool CheckFormatStringsCompatible(FormatStringType FST, const StringLiteral *AuthoritativeFormatString, const StringLiteral *TestedFormatString, const Expr *FunctionCallArg=nullptr)
Verify that two format strings (as understood by attribute(format) and attribute(format_matches) are ...
bool IsCXXTriviallyRelocatableType(QualType T)
Determines if a type is trivially relocatable according to the C++26 rules.
bool CheckOverflowBehaviorTypeConversion(Expr *E, QualType T, SourceLocation CC)
Check for overflow behavior type related implicit conversion diagnostics.
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2126
SemaHexagon & Hexagon()
Definition Sema.h:1533
SemaSYCL & SYCL()
Definition Sema.h:1603
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:1780
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition SemaExpr.cpp:851
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition Sema.h:1623
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:1339
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:231
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:932
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:1563
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1406
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:772
ASTContext & getASTContext() const
Definition Sema.h:935
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:774
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2765
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:1243
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
AtomicArgumentOrder
Definition Sema.h:2872
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low, int High, bool RangeIsError=true)
BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr TheCall is a constant express...
bool IsLayoutCompatible(QualType T1, QualType T2) const
const LangOptions & getLangOpts() const
Definition Sema.h:928
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:1508
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:1523
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:1337
static const uint64_t MaximumAlignment
Definition Sema.h:1266
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:970
SemaHLSL & HLSL()
Definition Sema.h:1528
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1548
SemaRISCV & RISCV()
Definition Sema.h:1593
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
bool convertArgumentToType(Expr *&Value, QualType Ty)
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:2938
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7166
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1792
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:1374
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:2845
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15798
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:2477
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:652
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:1491
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:1573
FormatArgumentPassingKind
Definition Sema.h:2775
@ FAPK_Elsewhere
Definition Sema.h:2779
@ FAPK_Fixed
Definition Sema.h:2776
@ FAPK_Variadic
Definition Sema.h:2777
@ FAPK_VAList
Definition Sema.h:2778
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:8400
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:14292
SourceManager & getSourceManager() const
Definition Sema.h:933
static FormatStringType GetFormatStringType(StringRef FormatFlavor)
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount, unsigned MaxArgCount)
Checks that a call expression's argument count is in the desired range.
bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str)
Verify that one format string (as understood by attribute(format)) is self-consistent; for instance,...
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Binary Operators. 'Tok' is the token for the operator.
bool isConstantEvaluatedContext() const
Definition Sema.h:2767
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:1583
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:1298
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx, unsigned FirstArg, FormatStringInfo *FSI)
Given a function and its FormatAttr or FormatMatchesAttr info, attempts to populate the FormatStringI...
SemaSystemZ & SystemZ()
Definition Sema.h:1613
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:1342
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:801
DiagnosticsEngine & Diags
Definition Sema.h:1341
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:1558
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:643
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:6476
SemaSPIRV & SPIRV()
Definition Sema.h:1598
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:1538
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6611
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:1618
SemaARM & ARM()
Definition Sema.h:1498
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:4712
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.
bool isMacroBodyExpansion(SourceLocation Loc) const
Tests whether the given source location represents the expansion of a macro body.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
bool isMacroArgExpansion(SourceLocation Loc, SourceLocation *StartLoc=nullptr) const
Tests whether the given source location represents a macro argument's expansion into the function-lik...
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const
Gets the location of the immediate macro caller, one level up the stack toward the initial macro type...
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:367
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
child_range children()
Definition Stmt.cpp:304
StmtClass getStmtClass() const
Definition Stmt.h:1504
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1844
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2042
bool isUTF8() const
Definition Expr.h:1979
bool isWide() const
Definition Expr.h:1978
bool isPascal() const
Definition Expr.h:1983
unsigned getLength() const
Definition Expr.h:1969
StringLiteralKind getKind() const
Definition Expr.h:1973
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
Return a source location that points to the specified byte of this string literal.
Definition Expr.cpp:1336
bool isUTF32() const
Definition Expr.h:1981
unsigned getByteLength() const
Definition Expr.h:1967
StringRef getString() const
Definition Expr.h:1912
bool isUTF16() const
Definition Expr.h:1980
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.h:2043
bool isOrdinary() const
Definition Expr.h:1977
unsigned getCharByteWidth() const
Definition Expr.h:1971
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:4019
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3999
bool isUnion() const
Definition Decl.h:4109
Exposes information about the current target.
Definition TargetInfo.h:228
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:396
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:2787
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:6458
A container of type source information.
Definition TypeBase.h:8549
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8560
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isBlockPointerType() const
Definition TypeBase.h:8835
bool isVoidType() const
Definition TypeBase.h:9200
bool isBooleanType() const
Definition TypeBase.h:9341
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2417
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9391
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:920
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2394
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2485
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2301
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:9371
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:845
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2652
bool isArrayType() const
Definition TypeBase.h:8914
bool isFunctionPointerType() const
Definition TypeBase.h:8882
bool isPointerType() const
Definition TypeBase.h:8815
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
bool isReferenceType() const
Definition TypeBase.h:8839
bool isEnumeralType() const
Definition TypeBase.h:8946
bool isScalarType() const
Definition TypeBase.h:9310
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:2080
bool isVariableArrayType() const
Definition TypeBase.h:8926
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2836
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9326
bool isExtVectorType() const
Definition TypeBase.h:8958
bool isExtVectorBoolType() const
Definition TypeBase.h:8962
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2873
bool isBitIntType() const
Definition TypeBase.h:9090
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9169
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8938
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8950
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2438
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3200
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2786
bool isMemberPointerType() const
Definition TypeBase.h:8896
bool isAtomicType() const
Definition TypeBase.h:9007
bool isFunctionProtoType() const
Definition TypeBase.h:2665
bool isMatrixType() const
Definition TypeBase.h:8978
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3341
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:2881
bool isUnscopedEnumerationType() const
Definition Type.cpp:2314
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9484
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9347
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2574
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:2662
bool isFunctionType() const
Definition TypeBase.h:8811
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2527
bool isStructureOrClassType() const
Definition Type.cpp:839
bool isVectorType() const
Definition TypeBase.h:8954
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2535
bool isFloatingType() const
Definition Type.cpp:2519
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:2462
bool isAnyPointerType() const
Definition TypeBase.h:8823
TypeClass getTypeClass() const
Definition TypeBase.h:2449
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2475
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
bool isNullPtrType() const
Definition TypeBase.h:9241
bool isRecordType() const
Definition TypeBase.h:8942
bool isObjCRetainableType() const
Definition Type.cpp:5616
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2798
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5332
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2861
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3743
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2694
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
Expr * getSubExpr() const
Definition Expr.h:2354
Opcode getOpcode() const
Definition Expr.h:2349
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2431
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1114
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1202
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3446
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5689
Represents a variable declaration or definition.
Definition Decl.h:934
Represents a GCC generic vector type.
Definition TypeBase.h:4398
unsigned getNumElements() const
Definition TypeBase.h:4413
QualType getElementType() const
Definition TypeBase.h:4412
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2708
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
std::optional< ConversionSpecifier > getStandardSpecifier() const
const OptionalAmount & getFieldWidth() const
bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const
const LengthModifier & getLengthModifier() const
bool hasValidLengthModifier(const TargetInfo &Target, const LangOptions &LO) const
std::optional< LengthModifier > getCorrectedLengthModifier() const
Represents the length modifier in a format string in scanf/printf.
ArgType getArgType(ASTContext &Ctx) const
Class representing optional flags with location and representation information.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
const OptionalFlag & isPrivate() const
const OptionalAmount & getPrecision() const
const OptionalFlag & hasSpacePrefix() const
const OptionalFlag & isSensitive() const
const OptionalFlag & isLeftJustified() const
const OptionalFlag & hasLeadingZeros() const
const OptionalFlag & hasAlternativeForm() const
const PrintfConversionSpecifier & getConversionSpecifier() const
const OptionalFlag & hasPlusPrefix() const
const OptionalFlag & hasThousandsGrouping() const
ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const
Returns the builtin type that a data argument paired with this format specifier should have.
const OptionalFlag & isPublic() const
const ScanfConversionSpecifier & getConversionSpecifier() const
ArgType getArgType(ASTContext &Ctx) const
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition SPIR.cpp:35
Definition SPIR.cpp:47
Common components of both fprintf and fscanf format strings.
bool parseFormatStringHasFormattingSpecifiers(const char *Begin, const char *End, const LangOptions &LO, const TargetInfo &Target)
Return true if the given string has at least one formatting specifier.
bool ParsePrintfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target, bool isFreeBSDKPrintf)
bool ParseScanfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
bool ParseFormatStringHasSArg(const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
Pieces specific to fprintf format strings.
Pieces specific to fscanf format strings.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< PointerType > pointerType
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
ComparisonResult
Indicates the result of a tentative comparison.
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition Types.cpp:240
@ 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:1520
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1505
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1498
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1512
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2842
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1451
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1527
SetTy< T > join(SetTy< T > A, SetTy< T > B, typename SetTy< T >::Factory &F)
Computes the union of two ImmutableSets.
Definition Utils.h:49
void checkCaptureByLifetime(Sema &SemaRef, const CapturingEntity &Entity, Expr *Init)
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition FixIt.h:32
RangeSelector merge(RangeSelector First, RangeSelector Second)
Selects the merge of the two ranges, i.e.
Top level wrappers for InstallAPI frontend operations.
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:824
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
Expr * IgnoreElidableImplicitConstructorSingleStep(Expr *E)
Definition IgnoreExpr.h:115
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
VariadicCallType
Definition Sema.h:507
bool hasSpecificAttr(const Container &container)
@ Arithmetic
An arithmetic operation.
Definition Sema.h:657
@ Comparison
A comparison.
Definition Sema.h:661
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:352
Expr * IgnoreExprNodes(Expr *E, FnTys &&... Fns)
Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *, Recursively apply each of the f...
Definition IgnoreExpr.h:24
@ Success
Annotation was successful.
Definition Parser.h:65
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:153
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:155
PointerAuthDiscArgKind
Definition Sema.h:588
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:128
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:261
@ 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:685
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:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
const FunctionProtoType * T
bool isFunctionOrMethodVariadic(const Decl *D)
Definition Attr.h:150
ExprResult ExprError()
Definition Ownership.h:265
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:493
CastKind
CastKind - The kind of operation required for a conversion.
unsigned getFunctionOrMethodNumParams(const Decl *D, bool IncludeThis=false)
getFunctionOrMethodNumParams - Return number of function or method parameters, optionally including t...
Definition Attr.h:66
BuiltinCountedByRefKind
Definition Sema.h:515
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool hasImplicitObjectParameter(const Decl *D)
Definition Attr.h:164
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:136
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
for(const auto &A :T->param_types())
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition IgnoreExpr.h:144
StringLiteralKind
Definition Expr.h:1808
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
@ CC_Win64
Definition Specifiers.h:289
@ CC_X86_64SysV
Definition Specifiers.h:290
@ Generic
not a target-specific vector type
Definition TypeBase.h:4234
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6167
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6160
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 unsigned
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669
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:651
Extra information about a function prototype.
Definition TypeBase.h:5633
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:13544
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13570
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13560
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13508
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:7024
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2787
#define log2(__x)
Definition tgmath.h:970