clang 23.0.0git
SemaChecking.cpp
Go to the documentation of this file.
1//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements extra semantic analysis beyond what is enforced
10// by the C type system.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CheckExprLifetime.h"
15#include "clang/AST/APValue.h"
18#include "clang/AST/Attr.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclObjC.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprObjC.h"
32#include "clang/AST/NSAPI.h"
36#include "clang/AST/Stmt.h"
39#include "clang/AST/Type.h"
40#include "clang/AST/TypeBase.h"
41#include "clang/AST/TypeLoc.h"
47#include "clang/Basic/LLVM.h"
58#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
60#include "clang/Sema/Lookup.h"
62#include "clang/Sema/Scope.h"
64#include "clang/Sema/Sema.h"
66#include "clang/Sema/SemaARM.h"
67#include "clang/Sema/SemaBPF.h"
69#include "clang/Sema/SemaHLSL.h"
72#include "clang/Sema/SemaMIPS.h"
74#include "clang/Sema/SemaObjC.h"
76#include "clang/Sema/SemaPPC.h"
79#include "clang/Sema/SemaSYCL.h"
81#include "clang/Sema/SemaWasm.h"
82#include "clang/Sema/SemaX86.h"
83#include "llvm/ADT/APFloat.h"
84#include "llvm/ADT/APInt.h"
85#include "llvm/ADT/APSInt.h"
86#include "llvm/ADT/ArrayRef.h"
87#include "llvm/ADT/DenseMap.h"
88#include "llvm/ADT/FoldingSet.h"
89#include "llvm/ADT/STLExtras.h"
90#include "llvm/ADT/STLForwardCompat.h"
91#include "llvm/ADT/SmallBitVector.h"
92#include "llvm/ADT/SmallPtrSet.h"
93#include "llvm/ADT/SmallString.h"
94#include "llvm/ADT/SmallVector.h"
95#include "llvm/ADT/StringExtras.h"
96#include "llvm/ADT/StringRef.h"
97#include "llvm/ADT/StringSet.h"
98#include "llvm/ADT/StringSwitch.h"
99#include "llvm/Support/AtomicOrdering.h"
100#include "llvm/Support/Compiler.h"
101#include "llvm/Support/ConvertUTF.h"
102#include "llvm/Support/ErrorHandling.h"
103#include "llvm/Support/Format.h"
104#include "llvm/Support/Locale.h"
105#include "llvm/Support/MathExtras.h"
106#include "llvm/Support/SaveAndRestore.h"
107#include "llvm/Support/raw_ostream.h"
108#include "llvm/TargetParser/RISCVTargetParser.h"
109#include "llvm/TargetParser/Triple.h"
110#include <algorithm>
111#include <cassert>
112#include <cctype>
113#include <cstddef>
114#include <cstdint>
115#include <functional>
116#include <limits>
117#include <optional>
118#include <string>
119#include <tuple>
120#include <utility>
121
122using namespace clang;
123using namespace sema;
124
126 unsigned ByteNo) const {
127 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
128 Context.getTargetInfo());
129}
130
131static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
133 return (A << 8) | B;
134}
135
136bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
137 unsigned ArgCount = Call->getNumArgs();
138 if (ArgCount >= MinArgCount)
139 return false;
140
141 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
142 << 0 /*function call*/ << MinArgCount << ArgCount
143 << /*is non object*/ 0 << Call->getSourceRange();
144}
145
146bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
147 unsigned ArgCount = Call->getNumArgs();
148 if (ArgCount <= MaxArgCount)
149 return false;
150 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)
151 << 0 /*function call*/ << MaxArgCount << ArgCount
152 << /*is non object*/ 0 << Call->getSourceRange();
153}
154
155bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
156 unsigned MaxArgCount) {
157 return checkArgCountAtLeast(Call, MinArgCount) ||
158 checkArgCountAtMost(Call, MaxArgCount);
159}
160
161bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
162 unsigned ArgCount = Call->getNumArgs();
163 if (ArgCount == DesiredArgCount)
164 return false;
165
166 if (checkArgCountAtLeast(Call, DesiredArgCount))
167 return true;
168 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
169
170 // Highlight all the excess arguments.
171 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
172 Call->getArg(ArgCount - 1)->getEndLoc());
173
174 return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
175 << 0 /*function call*/ << DesiredArgCount << ArgCount
176 << /*is non object*/ 0 << Range;
177}
178
180 bool HasError = false;
181
182 for (const Expr *Arg : Call->arguments()) {
183 if (Arg->isValueDependent())
184 continue;
185
186 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
187 int DiagMsgKind = -1;
188 // Arguments must be pointers to constant strings and cannot use '$'.
189 if (!ArgString.has_value())
190 DiagMsgKind = 0;
191 else if (ArgString->find('$') != std::string::npos)
192 DiagMsgKind = 1;
193
194 if (DiagMsgKind >= 0) {
195 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
196 << DiagMsgKind << Arg->getSourceRange();
197 HasError = true;
198 }
199 }
200
201 return !HasError;
202}
203
205 if (Value->isTypeDependent())
206 return false;
207
208 InitializedEntity Entity =
212 if (Result.isInvalid())
213 return true;
214 Value = Result.get();
215 return false;
216}
217
218/// Check that the first argument to __builtin_annotation is an integer
219/// and the second argument is a non-wide string literal.
220static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
221 if (S.checkArgCount(TheCall, 2))
222 return true;
223
224 // First argument should be an integer.
225 Expr *ValArg = TheCall->getArg(0);
226 QualType Ty = ValArg->getType();
227 if (!Ty->isIntegerType()) {
228 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
229 << ValArg->getSourceRange();
230 return true;
231 }
232
233 // Second argument should be a constant string.
234 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
235 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
236 if (!Literal || !Literal->isOrdinary()) {
237 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
238 << StrArg->getSourceRange();
239 return true;
240 }
241
242 TheCall->setType(Ty);
243 return false;
244}
245
246static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
247 // We need at least one argument.
248 if (TheCall->getNumArgs() < 1) {
249 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
250 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
251 << TheCall->getCallee()->getSourceRange();
252 return true;
253 }
254
255 // All arguments should be wide string literals.
256 for (Expr *Arg : TheCall->arguments()) {
257 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
258 if (!Literal || !Literal->isWide()) {
259 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
260 << Arg->getSourceRange();
261 return true;
262 }
263 }
264
265 return false;
266}
267
268/// Check that the argument to __builtin_addressof is a glvalue, and set the
269/// result type to the corresponding pointer type.
270static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
271 if (S.checkArgCount(TheCall, 1))
272 return true;
273
274 ExprResult Arg(TheCall->getArg(0));
275 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
276 if (ResultType.isNull())
277 return true;
278
279 TheCall->setArg(0, Arg.get());
280 TheCall->setType(ResultType);
281 return false;
282}
283
284/// Check that the argument to __builtin_function_start is a function.
285static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
286 if (S.checkArgCount(TheCall, 1))
287 return true;
288
289 if (TheCall->getArg(0)->containsErrors())
290 return true;
291
293 if (Arg.isInvalid())
294 return true;
295
296 TheCall->setArg(0, Arg.get());
297 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
299
300 if (!FD) {
301 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
302 << TheCall->getSourceRange();
303 return true;
304 }
305
306 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
307 TheCall->getBeginLoc());
308}
309
310/// Check the number of arguments and set the result type to
311/// the argument type.
312static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
313 if (S.checkArgCount(TheCall, 1))
314 return true;
315
316 TheCall->setType(TheCall->getArg(0)->getType());
317 return false;
318}
319
320/// Check that the value argument for __builtin_is_aligned(value, alignment) and
321/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
322/// type (but not a function pointer) and that the alignment is a power-of-two.
323static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
324 if (S.checkArgCount(TheCall, 2))
325 return true;
326
327 clang::Expr *Source = TheCall->getArg(0);
328 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
329
330 auto IsValidIntegerType = [](QualType Ty) {
331 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
332 };
333 QualType SrcTy = Source->getType();
334 // We should also be able to use it with arrays (but not functions!).
335 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
336 SrcTy = S.Context.getDecayedType(SrcTy);
337 }
338 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
339 SrcTy->isFunctionPointerType()) {
340 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
341 << SrcTy;
342 if (SrcTy->isFloatingType())
343 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_type);
344 else if (SrcTy->isMemberPointerType())
345 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_member_pointer);
346 else if (SrcTy->isFunctionPointerType())
347 S.Diag(Source->getExprLoc(),
348 diag::note_alignment_invalid_function_pointer);
349 return true;
350 }
351
352 clang::Expr *AlignOp = TheCall->getArg(1);
353 if (!IsValidIntegerType(AlignOp->getType())) {
354 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
355 << AlignOp->getType();
356 return true;
357 }
358 Expr::EvalResult AlignResult;
359 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
360 // We can't check validity of alignment if it is value dependent.
361 if (!AlignOp->isValueDependent() &&
362 AlignOp->EvaluateAsInt(AlignResult, S.Context,
364 llvm::APSInt AlignValue = AlignResult.Val.getInt();
365 llvm::APSInt MaxValue(
366 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
367 if (AlignValue < 1) {
368 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
369 return true;
370 }
371 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
372 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
373 << toString(MaxValue, 10);
374 return true;
375 }
376 if (!AlignValue.isPowerOf2()) {
377 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
378 return true;
379 }
380 if (AlignValue == 1) {
381 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
382 << IsBooleanAlignBuiltin;
383 }
384 }
385
388 SourceLocation(), Source);
389 if (SrcArg.isInvalid())
390 return true;
391 TheCall->setArg(0, SrcArg.get());
392 ExprResult AlignArg =
394 S.Context, AlignOp->getType(), false),
395 SourceLocation(), AlignOp);
396 if (AlignArg.isInvalid())
397 return true;
398 TheCall->setArg(1, AlignArg.get());
399 // For align_up/align_down, the return type is the same as the (potentially
400 // decayed) argument type including qualifiers. For is_aligned(), the result
401 // is always bool.
402 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
403 return false;
404}
405
406static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
407 if (S.checkArgCount(TheCall, 3))
408 return true;
409
410 std::pair<unsigned, const char *> Builtins[] = {
411 { Builtin::BI__builtin_add_overflow, "ckd_add" },
412 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
413 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
414 };
415
416 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
417 const char *> &P) {
418 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
420 S.getSourceManager(), S.getLangOpts()) == P.second;
421 });
422
423 auto ValidCkdIntType = [](QualType QT) {
424 // A valid checked integer type is an integer type other than a plain char,
425 // bool, a bit-precise type, or an enumeration type.
426 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
427 return (BT->getKind() >= BuiltinType::Short &&
428 BT->getKind() <= BuiltinType::Int128) || (
429 BT->getKind() >= BuiltinType::UShort &&
430 BT->getKind() <= BuiltinType::UInt128) ||
431 BT->getKind() == BuiltinType::UChar ||
432 BT->getKind() == BuiltinType::SChar;
433 return false;
434 };
435
436 // First two arguments should be integers.
437 for (unsigned I = 0; I < 2; ++I) {
439 if (Arg.isInvalid()) return true;
440 TheCall->setArg(I, Arg.get());
441
442 QualType Ty = Arg.get()->getType();
443 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
444 if (!IsValid) {
445 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
446 << CkdOperation << Ty << Arg.get()->getSourceRange();
447 return true;
448 }
449 }
450
451 // Third argument should be a pointer to a non-const integer.
452 // IRGen correctly handles volatile, restrict, and address spaces, and
453 // the other qualifiers aren't possible.
454 {
456 if (Arg.isInvalid()) return true;
457 TheCall->setArg(2, Arg.get());
458
459 QualType Ty = Arg.get()->getType();
460 const auto *PtrTy = Ty->getAs<PointerType>();
461 if (!PtrTy ||
462 !PtrTy->getPointeeType()->isIntegerType() ||
463 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
464 PtrTy->getPointeeType().isConstQualified()) {
465 S.Diag(Arg.get()->getBeginLoc(),
466 diag::err_overflow_builtin_must_be_ptr_int)
467 << CkdOperation << Ty << Arg.get()->getSourceRange();
468 return true;
469 }
470 }
471
472 // Disallow signed bit-precise integer args larger than 128 bits to mul
473 // function until we improve backend support.
474 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
475 for (unsigned I = 0; I < 3; ++I) {
476 const auto Arg = TheCall->getArg(I);
477 // Third argument will be a pointer.
478 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
479 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
480 S.getASTContext().getIntWidth(Ty) > 128)
481 return S.Diag(Arg->getBeginLoc(),
482 diag::err_overflow_builtin_bit_int_max_size)
483 << 128;
484 }
485 }
486
487 return false;
488}
489
490namespace {
491struct BuiltinDumpStructGenerator {
492 Sema &S;
493 CallExpr *TheCall;
494 SourceLocation Loc = TheCall->getBeginLoc();
495 SmallVector<Expr *, 32> Actions;
496 DiagnosticErrorTrap ErrorTracker;
497 PrintingPolicy Policy;
498
499 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
500 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
501 Policy(S.Context.getPrintingPolicy()) {
502 Policy.AnonymousTagNameStyle =
503 llvm::to_underlying(PrintingPolicy::AnonymousTagMode::Plain);
504 }
505
506 Expr *makeOpaqueValueExpr(Expr *Inner) {
507 auto *OVE = new (S.Context)
508 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
509 Inner->getObjectKind(), Inner);
510 Actions.push_back(OVE);
511 return OVE;
512 }
513
514 Expr *getStringLiteral(llvm::StringRef Str) {
516 // Wrap the literal in parentheses to attach a source location.
517 return new (S.Context) ParenExpr(Loc, Loc, Lit);
518 }
519
520 bool callPrintFunction(llvm::StringRef Format,
521 llvm::ArrayRef<Expr *> Exprs = {}) {
522 SmallVector<Expr *, 8> Args;
523 assert(TheCall->getNumArgs() >= 2);
524 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
525 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
526 Args.push_back(getStringLiteral(Format));
527 llvm::append_range(Args, Exprs);
528
529 // Register a note to explain why we're performing the call.
530 Sema::CodeSynthesisContext Ctx;
532 Ctx.PointOfInstantiation = Loc;
533 Ctx.CallArgs = Args.data();
534 Ctx.NumCallArgs = Args.size();
536
537 ExprResult RealCall =
538 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
539 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
540
542 if (!RealCall.isInvalid())
543 Actions.push_back(RealCall.get());
544 // Bail out if we've hit any errors, even if we managed to build the
545 // call. We don't want to produce more than one error.
546 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
547 }
548
549 Expr *getIndentString(unsigned Depth) {
550 if (!Depth)
551 return nullptr;
552
553 llvm::SmallString<32> Indent;
554 Indent.resize(Depth * Policy.Indentation, ' ');
555 return getStringLiteral(Indent);
556 }
557
558 Expr *getTypeString(QualType T) {
559 return getStringLiteral(T.getAsString(Policy));
560 }
561
562 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
563 llvm::raw_svector_ostream OS(Str);
564
565 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
566 // than trying to print a single character.
567 if (auto *BT = T->getAs<BuiltinType>()) {
568 switch (BT->getKind()) {
569 case BuiltinType::Bool:
570 OS << "%d";
571 return true;
572 case BuiltinType::Char_U:
573 case BuiltinType::UChar:
574 OS << "%hhu";
575 return true;
576 case BuiltinType::Char_S:
577 case BuiltinType::SChar:
578 OS << "%hhd";
579 return true;
580 default:
581 break;
582 }
583 }
584
585 analyze_printf::PrintfSpecifier Specifier;
586 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
587 // We were able to guess how to format this.
588 if (Specifier.getConversionSpecifier().getKind() ==
589 analyze_printf::PrintfConversionSpecifier::sArg) {
590 // Wrap double-quotes around a '%s' specifier and limit its maximum
591 // length. Ideally we'd also somehow escape special characters in the
592 // contents but printf doesn't support that.
593 // FIXME: '%s' formatting is not safe in general.
594 OS << '"';
595 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
596 Specifier.toString(OS);
597 OS << '"';
598 // FIXME: It would be nice to include a '...' if the string doesn't fit
599 // in the length limit.
600 } else {
601 Specifier.toString(OS);
602 }
603 return true;
604 }
605
606 if (T->isPointerType()) {
607 // Format all pointers with '%p'.
608 OS << "%p";
609 return true;
610 }
611
612 return false;
613 }
614
615 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
616 Expr *IndentLit = getIndentString(Depth);
617 Expr *TypeLit = getTypeString(S.Context.getCanonicalTagType(RD));
618 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
619 : callPrintFunction("%s", {TypeLit}))
620 return true;
621
622 return dumpRecordValue(RD, E, IndentLit, Depth);
623 }
624
625 // Dump a record value. E should be a pointer or lvalue referring to an RD.
626 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
627 unsigned Depth) {
628 // FIXME: Decide what to do if RD is a union. At least we should probably
629 // turn off printing `const char*` members with `%s`, because that is very
630 // likely to crash if that's not the active member. Whatever we decide, we
631 // should document it.
632
633 // Build an OpaqueValueExpr so we can refer to E more than once without
634 // triggering re-evaluation.
635 Expr *RecordArg = makeOpaqueValueExpr(E);
636 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
637
638 if (callPrintFunction(" {\n"))
639 return true;
640
641 // Dump each base class, regardless of whether they're aggregates.
642 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
643 for (const auto &Base : CXXRD->bases()) {
644 QualType BaseType =
645 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
646 : S.Context.getLValueReferenceType(Base.getType());
648 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
649 RecordArg);
650 if (BasePtr.isInvalid() ||
651 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
652 Depth + 1))
653 return true;
654 }
655 }
656
657 Expr *FieldIndentArg = getIndentString(Depth + 1);
658
659 // Dump each field.
660 for (auto *D : RD->decls()) {
661 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
662 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
663 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
664 continue;
665
666 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
667 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
668 getTypeString(FD->getType()),
669 getStringLiteral(FD->getName())};
670
671 if (FD->isBitField()) {
672 Format += ": %zu ";
673 QualType SizeT = S.Context.getSizeType();
674 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
675 FD->getBitWidthValue());
676 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
677 }
678
679 Format += "=";
680
683 CXXScopeSpec(), Loc, IFD,
684 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
686 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
688 DeclarationNameInfo(FD->getDeclName(), Loc));
689 if (Field.isInvalid())
690 return true;
691
692 auto *InnerRD = FD->getType()->getAsRecordDecl();
693 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
694 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
695 // Recursively print the values of members of aggregate record type.
696 if (callPrintFunction(Format, Args) ||
697 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
698 return true;
699 } else {
700 Format += " ";
701 if (appendFormatSpecifier(FD->getType(), Format)) {
702 // We know how to print this field.
703 Args.push_back(Field.get());
704 } else {
705 // We don't know how to print this field. Print out its address
706 // with a format specifier that a smart tool will be able to
707 // recognize and treat specially.
708 Format += "*%p";
709 ExprResult FieldAddr =
710 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
711 if (FieldAddr.isInvalid())
712 return true;
713 Args.push_back(FieldAddr.get());
714 }
715 Format += "\n";
716 if (callPrintFunction(Format, Args))
717 return true;
718 }
719 }
720
721 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
722 : callPrintFunction("}\n");
723 }
724
725 Expr *buildWrapper() {
726 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
728 TheCall->setType(Wrapper->getType());
729 TheCall->setValueKind(Wrapper->getValueKind());
730 return Wrapper;
731 }
732};
733} // namespace
734
736 if (S.checkArgCountAtLeast(TheCall, 2))
737 return ExprError();
738
739 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
740 if (PtrArgResult.isInvalid())
741 return ExprError();
742 TheCall->setArg(0, PtrArgResult.get());
743
744 // First argument should be a pointer to a struct.
745 QualType PtrArgType = PtrArgResult.get()->getType();
746 if (!PtrArgType->isPointerType() ||
747 !PtrArgType->getPointeeType()->isRecordType()) {
748 S.Diag(PtrArgResult.get()->getBeginLoc(),
749 diag::err_expected_struct_pointer_argument)
750 << 1 << TheCall->getDirectCallee() << PtrArgType;
751 return ExprError();
752 }
753 QualType Pointee = PtrArgType->getPointeeType();
754 const RecordDecl *RD = Pointee->getAsRecordDecl();
755 // Try to instantiate the class template as appropriate; otherwise, access to
756 // its data() may lead to a crash.
757 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
758 diag::err_incomplete_type))
759 return ExprError();
760 // Second argument is a callable, but we can't fully validate it until we try
761 // calling it.
762 QualType FnArgType = TheCall->getArg(1)->getType();
763 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
764 !FnArgType->isBlockPointerType() &&
765 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
766 auto *BT = FnArgType->getAs<BuiltinType>();
767 switch (BT ? BT->getKind() : BuiltinType::Void) {
768 case BuiltinType::Dependent:
769 case BuiltinType::Overload:
770 case BuiltinType::BoundMember:
771 case BuiltinType::PseudoObject:
772 case BuiltinType::UnknownAny:
773 case BuiltinType::BuiltinFn:
774 // This might be a callable.
775 break;
776
777 default:
778 S.Diag(TheCall->getArg(1)->getBeginLoc(),
779 diag::err_expected_callable_argument)
780 << 2 << TheCall->getDirectCallee() << FnArgType;
781 return ExprError();
782 }
783 }
784
785 BuiltinDumpStructGenerator Generator(S, TheCall);
786
787 // Wrap parentheses around the given pointer. This is not necessary for
788 // correct code generation, but it means that when we pretty-print the call
789 // arguments in our diagnostics we will produce '(&s)->n' instead of the
790 // incorrect '&s->n'.
791 Expr *PtrArg = PtrArgResult.get();
792 PtrArg = new (S.Context)
793 ParenExpr(PtrArg->getBeginLoc(),
794 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
795 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
796 return ExprError();
797
798 return Generator.buildWrapper();
799}
800
801static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
802 if (S.checkArgCount(BuiltinCall, 2))
803 return true;
804
805 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
806 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
807 Expr *Call = BuiltinCall->getArg(0);
808 Expr *Chain = BuiltinCall->getArg(1);
809
810 if (Call->getStmtClass() != Stmt::CallExprClass) {
811 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
812 << Call->getSourceRange();
813 return true;
814 }
815
816 auto CE = cast<CallExpr>(Call);
817 if (CE->getCallee()->getType()->isBlockPointerType()) {
818 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
819 << Call->getSourceRange();
820 return true;
821 }
822
823 const Decl *TargetDecl = CE->getCalleeDecl();
824 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
825 if (FD->getBuiltinID()) {
826 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
827 << Call->getSourceRange();
828 return true;
829 }
830
831 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
832 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
833 << Call->getSourceRange();
834 return true;
835 }
836
837 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
838 if (ChainResult.isInvalid())
839 return true;
840 if (!ChainResult.get()->getType()->isPointerType()) {
841 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
842 << Chain->getSourceRange();
843 return true;
844 }
845
846 QualType ReturnTy = CE->getCallReturnType(S.Context);
847 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
848 QualType BuiltinTy = S.Context.getFunctionType(
849 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
850 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
851
852 Builtin =
853 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
854
855 BuiltinCall->setType(CE->getType());
856 BuiltinCall->setValueKind(CE->getValueKind());
857 BuiltinCall->setObjectKind(CE->getObjectKind());
858 BuiltinCall->setCallee(Builtin);
859 BuiltinCall->setArg(1, ChainResult.get());
860
861 return false;
862}
863
864namespace {
865
866class ScanfDiagnosticFormatHandler
868 // Accepts the argument index (relative to the first destination index) of the
869 // argument whose size we want.
870 using ComputeSizeFunction =
871 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
872
873 // Accepts the argument index (relative to the first destination index), the
874 // destination size, and the source size).
875 using DiagnoseFunction =
876 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
877
878 ComputeSizeFunction ComputeSizeArgument;
879 DiagnoseFunction Diagnose;
880
881public:
882 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
883 DiagnoseFunction Diagnose)
884 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
885
886 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
887 const char *StartSpecifier,
888 unsigned specifierLen) override {
889 if (!FS.consumesDataArgument())
890 return true;
891
892 unsigned NulByte = 0;
893 switch ((FS.getConversionSpecifier().getKind())) {
894 default:
895 return true;
898 NulByte = 1;
899 break;
901 break;
902 }
903
904 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
905 if (FW.getHowSpecified() !=
906 analyze_format_string::OptionalAmount::HowSpecified::Constant)
907 return true;
908
909 unsigned SourceSize = FW.getConstantAmount() + NulByte;
910
911 std::optional<llvm::APSInt> DestSizeAPS =
912 ComputeSizeArgument(FS.getArgIndex());
913 if (!DestSizeAPS)
914 return true;
915
916 unsigned DestSize = DestSizeAPS->getZExtValue();
917
918 if (DestSize < SourceSize)
919 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
920
921 return true;
922 }
923};
924
925class EstimateSizeFormatHandler
927 size_t Size;
928 /// Whether the format string contains Linux kernel's format specifier
929 /// extension.
930 bool IsKernelCompatible = true;
931
932public:
933 EstimateSizeFormatHandler(StringRef Format)
934 : Size(std::min(Format.find(0), Format.size()) +
935 1 /* null byte always written by sprintf */) {}
936
937 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
938 const char *, unsigned SpecifierLen,
939 const TargetInfo &) override {
940
941 const size_t FieldWidth = computeFieldWidth(FS);
942 const size_t Precision = computePrecision(FS);
943
944 // The actual format.
945 switch (FS.getConversionSpecifier().getKind()) {
946 // Just a char.
949 Size += std::max(FieldWidth, (size_t)1);
950 break;
951 // Just an integer.
961 Size += std::max(FieldWidth, Precision);
962 break;
963
964 // %g style conversion switches between %f or %e style dynamically.
965 // %g removes trailing zeros, and does not print decimal point if there are
966 // no digits that follow it. Thus %g can print a single digit.
967 // FIXME: If it is alternative form:
968 // For g and G conversions, trailing zeros are not removed from the result.
971 Size += 1;
972 break;
973
974 // Floating point number in the form '[+]ddd.ddd'.
977 Size += std::max(FieldWidth, 1 /* integer part */ +
978 (Precision ? 1 + Precision
979 : 0) /* period + decimal */);
980 break;
981
982 // Floating point number in the form '[-]d.ddde[+-]dd'.
985 Size +=
986 std::max(FieldWidth,
987 1 /* integer part */ +
988 (Precision ? 1 + Precision : 0) /* period + decimal */ +
989 1 /* e or E letter */ + 2 /* exponent */);
990 break;
991
992 // Floating point number in the form '[-]0xh.hhhhp±dd'.
995 Size +=
996 std::max(FieldWidth,
997 2 /* 0x */ + 1 /* integer part */ +
998 (Precision ? 1 + Precision : 0) /* period + decimal */ +
999 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
1000 break;
1001
1002 // Just a string.
1005 Size += FieldWidth;
1006 break;
1007
1008 // Just a pointer in the form '0xddd'.
1010 // Linux kernel has its own extesion for `%p` specifier.
1011 // Kernel Document:
1012 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1013 IsKernelCompatible = false;
1014 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1015 break;
1016
1017 // A plain percent.
1019 Size += 1;
1020 break;
1021
1022 default:
1023 break;
1024 }
1025
1026 // If field width is specified, the sign/space is already accounted for
1027 // within the field width, so no additional size is needed.
1028 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1029 Size += 1;
1030
1031 if (FS.hasAlternativeForm()) {
1032 switch (FS.getConversionSpecifier().getKind()) {
1033 // For o conversion, it increases the precision, if and only if necessary,
1034 // to force the first digit of the result to be a zero
1035 // (if the value and precision are both 0, a single 0 is printed)
1037 // For b conversion, a nonzero result has 0b prefixed to it.
1039 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1040 // it.
1043 // Note: even when the prefix is added, if
1044 // (prefix_width <= FieldWidth - formatted_length) holds,
1045 // the prefix does not increase the format
1046 // size. e.g.(("%#3x", 0xf) is "0xf")
1047
1048 // If the result is zero, o, b, x, X adds nothing.
1049 break;
1050 // For a, A, e, E, f, F, g, and G conversions,
1051 // the result of converting a floating-point number always contains a
1052 // decimal-point
1061 Size += (Precision ? 0 : 1);
1062 break;
1063 // For other conversions, the behavior is undefined.
1064 default:
1065 break;
1066 }
1067 }
1068 assert(SpecifierLen <= Size && "no underflow");
1069 Size -= SpecifierLen;
1070 return true;
1071 }
1072
1073 size_t getSizeLowerBound() const { return Size; }
1074 bool isKernelCompatible() const { return IsKernelCompatible; }
1075
1076private:
1077 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1078 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1079 size_t FieldWidth = 0;
1081 FieldWidth = FW.getConstantAmount();
1082 return FieldWidth;
1083 }
1084
1085 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1086 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1087 size_t Precision = 0;
1088
1089 // See man 3 printf for default precision value based on the specifier.
1090 switch (FW.getHowSpecified()) {
1092 switch (FS.getConversionSpecifier().getKind()) {
1093 default:
1094 break;
1098 Precision = 1;
1099 break;
1106 Precision = 1;
1107 break;
1114 Precision = 6;
1115 break;
1117 Precision = 1;
1118 break;
1119 }
1120 break;
1122 Precision = FW.getConstantAmount();
1123 break;
1124 default:
1125 break;
1126 }
1127 return Precision;
1128 }
1129};
1130
1131} // namespace
1132
1133static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1134 StringRef &FormatStrRef, size_t &StrLen,
1135 ASTContext &Context) {
1136 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1137 Format && (Format->isOrdinary() || Format->isUTF8())) {
1138 FormatStrRef = Format->getString();
1139 const ConstantArrayType *T =
1140 Context.getAsConstantArrayType(Format->getType());
1141 assert(T && "String literal not of constant array type!");
1142 size_t TypeSize = T->getZExtSize();
1143 // In case there's a null byte somewhere.
1144 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1145 return true;
1146 }
1147 return false;
1148}
1149
1150void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1151 CallExpr *TheCall) {
1152 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1154 return;
1155
1156 bool UseDABAttr = false;
1157 const FunctionDecl *UseDecl = FD;
1158
1159 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1160 if (DABAttr) {
1161 UseDecl = DABAttr->getFunction();
1162 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1163 UseDABAttr = true;
1164 }
1165
1166 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1167
1168 if (!BuiltinID)
1169 return;
1170
1171 const TargetInfo &TI = getASTContext().getTargetInfo();
1172 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1173
1174 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1175 // If we refer to a diagnose_as_builtin attribute, we need to change the
1176 // argument index to refer to the arguments of the called function. Unless
1177 // the index is out of bounds, which presumably means it's a variadic
1178 // function.
1179 if (!UseDABAttr)
1180 return Index;
1181 unsigned DABIndices = DABAttr->argIndices_size();
1182 unsigned NewIndex = Index < DABIndices
1183 ? DABAttr->argIndices_begin()[Index]
1184 : Index - DABIndices + FD->getNumParams();
1185 if (NewIndex >= TheCall->getNumArgs())
1186 return std::nullopt;
1187 return NewIndex;
1188 };
1189
1190 auto ComputeExplicitObjectSizeArgument =
1191 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1192 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1193 if (!IndexOptional)
1194 return std::nullopt;
1195 unsigned NewIndex = *IndexOptional;
1196 Expr::EvalResult Result;
1197 Expr *SizeArg = TheCall->getArg(NewIndex);
1198 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1199 return std::nullopt;
1200 llvm::APSInt Integer = Result.Val.getInt();
1201 Integer.setIsUnsigned(true);
1202 return Integer;
1203 };
1204
1205 auto ComputeSizeArgument =
1206 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1207 // If the parameter has a pass_object_size attribute, then we should use its
1208 // (potentially) more strict checking mode. Otherwise, conservatively assume
1209 // type 0.
1210 int BOSType = 0;
1211 // This check can fail for variadic functions.
1212 if (Index < FD->getNumParams()) {
1213 if (const auto *POS =
1214 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1215 BOSType = POS->getType();
1216 }
1217
1218 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1219 if (!IndexOptional)
1220 return std::nullopt;
1221 unsigned NewIndex = *IndexOptional;
1222
1223 if (NewIndex >= TheCall->getNumArgs())
1224 return std::nullopt;
1225
1226 const Expr *ObjArg = TheCall->getArg(NewIndex);
1227 if (std::optional<uint64_t> ObjSize =
1228 ObjArg->tryEvaluateObjectSize(getASTContext(), BOSType)) {
1229 // Get the object size in the target's size_t width.
1230 return llvm::APSInt::getUnsigned(*ObjSize).extOrTrunc(SizeTypeWidth);
1231 }
1232 return std::nullopt;
1233 };
1234
1235 auto ComputeStrLenArgument =
1236 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1237 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1238 if (!IndexOptional)
1239 return std::nullopt;
1240 unsigned NewIndex = *IndexOptional;
1241
1242 const Expr *ObjArg = TheCall->getArg(NewIndex);
1243
1244 if (std::optional<uint64_t> Result =
1245 ObjArg->tryEvaluateStrLen(getASTContext())) {
1246 // Add 1 for null byte.
1247 return llvm::APSInt::getUnsigned(*Result + 1).extOrTrunc(SizeTypeWidth);
1248 }
1249 return std::nullopt;
1250 };
1251
1252 std::optional<llvm::APSInt> SourceSize;
1253 std::optional<llvm::APSInt> DestinationSize;
1254 unsigned DiagID = 0;
1255 bool IsChkVariant = false;
1256
1257 auto GetFunctionName = [&]() {
1258 std::string FunctionNameStr =
1259 getASTContext().BuiltinInfo.getName(BuiltinID);
1260 llvm::StringRef FunctionName = FunctionNameStr;
1261 // Skim off the details of whichever builtin was called to produce a better
1262 // diagnostic, as it's unlikely that the user wrote the __builtin
1263 // explicitly.
1264 if (IsChkVariant) {
1265 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1266 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1267 } else {
1268 FunctionName.consume_front("__builtin_");
1269 }
1270 return FunctionName.str();
1271 };
1272
1273 switch (BuiltinID) {
1274 default:
1275 return;
1276 case Builtin::BI__builtin_strcat:
1277 case Builtin::BIstrcat:
1278 case Builtin::BI__builtin_stpcpy:
1279 case Builtin::BIstpcpy:
1280 case Builtin::BI__builtin_strcpy:
1281 case Builtin::BIstrcpy: {
1282 DiagID = diag::warn_fortify_strlen_overflow;
1283 SourceSize = ComputeStrLenArgument(1);
1284 DestinationSize = ComputeSizeArgument(0);
1285 break;
1286 }
1287
1288 case Builtin::BI__builtin___strcat_chk:
1289 case Builtin::BI__builtin___stpcpy_chk:
1290 case Builtin::BI__builtin___strcpy_chk: {
1291 DiagID = diag::warn_fortify_strlen_overflow;
1292 SourceSize = ComputeStrLenArgument(1);
1293 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1294 IsChkVariant = true;
1295 break;
1296 }
1297
1298 case Builtin::BIscanf:
1299 case Builtin::BIfscanf:
1300 case Builtin::BIsscanf: {
1301 unsigned FormatIndex = 1;
1302 unsigned DataIndex = 2;
1303 if (BuiltinID == Builtin::BIscanf) {
1304 FormatIndex = 0;
1305 DataIndex = 1;
1306 }
1307
1308 const auto *FormatExpr =
1309 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1310
1311 StringRef FormatStrRef;
1312 size_t StrLen;
1313 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1314 return;
1315
1316 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1317 unsigned SourceSize) {
1318 DiagID = diag::warn_fortify_scanf_overflow;
1319 unsigned Index = ArgIndex + DataIndex;
1320 std::string FunctionName = GetFunctionName();
1321 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1322 PDiag(DiagID) << FunctionName << (Index + 1)
1323 << DestSize << SourceSize);
1324 };
1325
1326 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1327 return ComputeSizeArgument(Index + DataIndex);
1328 };
1329 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1330 const char *FormatBytes = FormatStrRef.data();
1332 FormatBytes + StrLen, getLangOpts(),
1333 Context.getTargetInfo());
1334
1335 // Unlike the other cases, in this one we have already issued the diagnostic
1336 // here, so no need to continue (because unlike the other cases, here the
1337 // diagnostic refers to the argument number).
1338 return;
1339 }
1340
1341 case Builtin::BIsprintf:
1342 case Builtin::BI__builtin___sprintf_chk: {
1343 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1344 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1345
1346 StringRef FormatStrRef;
1347 size_t StrLen;
1348 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1349 EstimateSizeFormatHandler H(FormatStrRef);
1350 const char *FormatBytes = FormatStrRef.data();
1352 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1353 Context.getTargetInfo(), false)) {
1354 DiagID = H.isKernelCompatible()
1355 ? diag::warn_format_overflow
1356 : diag::warn_format_overflow_non_kprintf;
1357 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1358 .extOrTrunc(SizeTypeWidth);
1359 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1360 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1361 IsChkVariant = true;
1362 } else {
1363 DestinationSize = ComputeSizeArgument(0);
1364 }
1365 break;
1366 }
1367 }
1368 return;
1369 }
1370 case Builtin::BI__builtin___memcpy_chk:
1371 case Builtin::BI__builtin___memmove_chk:
1372 case Builtin::BI__builtin___memset_chk:
1373 case Builtin::BI__builtin___strlcat_chk:
1374 case Builtin::BI__builtin___strlcpy_chk:
1375 case Builtin::BI__builtin___strncat_chk:
1376 case Builtin::BI__builtin___strncpy_chk:
1377 case Builtin::BI__builtin___stpncpy_chk:
1378 case Builtin::BI__builtin___memccpy_chk:
1379 case Builtin::BI__builtin___mempcpy_chk: {
1380 DiagID = diag::warn_builtin_chk_overflow;
1381 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1382 DestinationSize =
1383 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1384 IsChkVariant = true;
1385 break;
1386 }
1387
1388 case Builtin::BI__builtin___snprintf_chk:
1389 case Builtin::BI__builtin___vsnprintf_chk: {
1390 DiagID = diag::warn_builtin_chk_overflow;
1391 SourceSize = ComputeExplicitObjectSizeArgument(1);
1392 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1393 IsChkVariant = true;
1394 break;
1395 }
1396
1397 case Builtin::BIstrncat:
1398 case Builtin::BI__builtin_strncat:
1399 case Builtin::BIstrncpy:
1400 case Builtin::BI__builtin_strncpy:
1401 case Builtin::BIstpncpy:
1402 case Builtin::BI__builtin_stpncpy: {
1403 // Whether these functions overflow depends on the runtime strlen of the
1404 // string, not just the buffer size, so emitting the "always overflow"
1405 // diagnostic isn't quite right. We should still diagnose passing a buffer
1406 // size larger than the destination buffer though; this is a runtime abort
1407 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1408 DiagID = diag::warn_fortify_source_size_mismatch;
1409 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1410 DestinationSize = ComputeSizeArgument(0);
1411 break;
1412 }
1413
1414 case Builtin::BIbzero:
1415 case Builtin::BI__builtin_bzero:
1416 case Builtin::BImemcpy:
1417 case Builtin::BI__builtin_memcpy:
1418 case Builtin::BImemmove:
1419 case Builtin::BI__builtin_memmove:
1420 case Builtin::BImemset:
1421 case Builtin::BI__builtin_memset:
1422 case Builtin::BImempcpy:
1423 case Builtin::BI__builtin_mempcpy: {
1424 DiagID = diag::warn_fortify_source_overflow;
1425 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1426 DestinationSize = ComputeSizeArgument(0);
1427 break;
1428 }
1429 case Builtin::BIbcopy:
1430 case Builtin::BI__builtin_bcopy: {
1431 DiagID = diag::warn_fortify_source_overflow;
1432 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1433 DestinationSize = ComputeSizeArgument(1);
1434 break;
1435 }
1436 case Builtin::BIsnprintf:
1437 case Builtin::BI__builtin_snprintf:
1438 case Builtin::BIvsnprintf:
1439 case Builtin::BI__builtin_vsnprintf: {
1440 DiagID = diag::warn_fortify_source_size_mismatch;
1441 SourceSize = ComputeExplicitObjectSizeArgument(1);
1442 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1443 StringRef FormatStrRef;
1444 size_t StrLen;
1445 if (SourceSize &&
1446 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1447 EstimateSizeFormatHandler H(FormatStrRef);
1448 const char *FormatBytes = FormatStrRef.data();
1450 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1451 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1452 llvm::APSInt FormatSize =
1453 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1454 .extOrTrunc(SizeTypeWidth);
1455 if (FormatSize > *SourceSize && *SourceSize != 0) {
1456 unsigned TruncationDiagID =
1457 H.isKernelCompatible() ? diag::warn_format_truncation
1458 : diag::warn_format_truncation_non_kprintf;
1459 SmallString<16> SpecifiedSizeStr;
1460 SmallString<16> FormatSizeStr;
1461 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1462 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1463 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1464 PDiag(TruncationDiagID)
1465 << GetFunctionName() << SpecifiedSizeStr
1466 << FormatSizeStr);
1467 }
1468 }
1469 }
1470 DestinationSize = ComputeSizeArgument(0);
1471 const Expr *LenArg = TheCall->getArg(1)->IgnoreCasts();
1472 const Expr *Dest = TheCall->getArg(0)->IgnoreCasts();
1473 IdentifierInfo *FnInfo = FD->getIdentifier();
1474 CheckSizeofMemaccessArgument(LenArg, Dest, FnInfo);
1475 }
1476 }
1477
1478 if (!SourceSize || !DestinationSize ||
1479 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1480 return;
1481
1482 std::string FunctionName = GetFunctionName();
1483
1484 SmallString<16> DestinationStr;
1485 SmallString<16> SourceStr;
1486 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1487 SourceSize->toString(SourceStr, /*Radix=*/10);
1488 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1489 PDiag(DiagID)
1490 << FunctionName << DestinationStr << SourceStr);
1491}
1492
1493void Sema::checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall) {
1494 if (TheCall->isValueDependent() || TheCall->isTypeDependent())
1495 return;
1496
1497 // Recognize the libc function by builtin identity rather than by name and
1498 // system-header origin. umask is a LibBuiltin marked IgnoreSignature, so the
1499 // builtin id is attached to any file-scope, C-linkage declaration of umask
1500 // regardless of the libc's mode_t spelling -- including a hand-written
1501 // forward declaration without <sys/stat.h>. A static/local lookalike or a
1502 // C++ (non-extern-"C") declaration keeps a zero builtin id and is ignored.
1503 if (FD->getBuiltinID() != Builtin::BIumask)
1504 return;
1505
1506 // umask(mode_t): warn when the constant-evaluated argument has bits set
1507 // outside the file-permission mask (0777). Those bits are ignored.
1508 if (TheCall->getNumArgs() != 1)
1509 return;
1510 Expr *Arg = TheCall->getArg(0);
1511 if (!Arg->getType()->isIntegerType())
1512 return;
1513 Expr::EvalResult R;
1514 if (!Arg->EvaluateAsInt(R, getASTContext()))
1515 return;
1516 // Operate on the raw two's-complement bit pattern so that negative literals
1517 // (which convert to large unsigned mode_t values) are caught.
1518 llvm::APInt RawValue = R.Val.getInt();
1519 llvm::APInt Mask(RawValue.getBitWidth(), 0777);
1520 llvm::APInt Extra = RawValue & ~Mask;
1521 if (Extra == 0)
1522 return;
1523 SmallString<16> ExtraStr;
1524 Extra.toString(ExtraStr, /*Radix=*/8, /*Signed=*/false);
1525 Diag(TheCall->getBeginLoc(), diag::warn_fortify_umask_unused_bits)
1526 << ExtraStr;
1527}
1528
1529static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1530 Scope::ScopeFlags NeededScopeFlags,
1531 unsigned DiagID) {
1532 // Scopes aren't available during instantiation. Fortunately, builtin
1533 // functions cannot be template args so they cannot be formed through template
1534 // instantiation. Therefore checking once during the parse is sufficient.
1535 if (SemaRef.inTemplateInstantiation())
1536 return false;
1537
1538 Scope *S = SemaRef.getCurScope();
1539 while (S && !S->isSEHExceptScope())
1540 S = S->getParent();
1541 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1542 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1543 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1544 << DRE->getDecl()->getIdentifier();
1545 return true;
1546 }
1547
1548 return false;
1549}
1550
1551// In OpenCL, __builtin_alloca_* should return a pointer to address space
1552// that corresponds to the stack address space i.e private address space.
1553static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1554 QualType RT = TheCall->getType();
1555 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1556 "__builtin_alloca has invalid address space");
1557
1558 RT = RT->getPointeeType();
1560 TheCall->setType(S.Context.getPointerType(RT));
1561}
1562
1563static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1564 if (S.checkArgCountAtLeast(TheCall, 1))
1565 return true;
1566
1567 for (Expr *Arg : TheCall->arguments()) {
1568 // If argument is dependent on a template parameter, we can't resolve now.
1569 if (Arg->isTypeDependent() || Arg->isValueDependent())
1570 continue;
1571 // Reject void types.
1572 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1573 if (ArgTy->isVoidType())
1574 return S.Diag(Arg->getBeginLoc(), diag::err_param_with_void_type);
1575 }
1576
1577 TheCall->setType(S.Context.getSizeType());
1578 return false;
1579}
1580
1581namespace {
1582enum PointerAuthOpKind {
1583 PAO_Strip,
1584 PAO_Sign,
1585 PAO_Auth,
1586 PAO_SignGeneric,
1587 PAO_Discriminator,
1588 PAO_BlendPointer,
1589 PAO_BlendInteger
1590};
1591}
1592
1594 if (getLangOpts().PointerAuthIntrinsics)
1595 return false;
1596
1597 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1598 return true;
1599}
1600
1601static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1603}
1604
1605static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1606 // Convert it to type 'int'.
1607 if (convertArgumentToType(S, Arg, S.Context.IntTy))
1608 return true;
1609
1610 // Value-dependent expressions are okay; wait for template instantiation.
1611 if (Arg->isValueDependent())
1612 return false;
1613
1614 unsigned KeyValue;
1615 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1616}
1617
1619 // Attempt to constant-evaluate the expression.
1620 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1621 if (!KeyValue) {
1622 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1623 << 0 << Arg->getSourceRange();
1624 return true;
1625 }
1626
1627 // Ask the target to validate the key parameter.
1628 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1630 {
1631 llvm::raw_svector_ostream Str(Value);
1632 Str << *KeyValue;
1633 }
1634
1635 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1636 << Value << Arg->getSourceRange();
1637 return true;
1638 }
1639
1640 Result = KeyValue->getZExtValue();
1641 return false;
1642}
1643
1646 unsigned &IntVal) {
1647 if (!Arg) {
1648 IntVal = 0;
1649 return true;
1650 }
1651
1652 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
1653 if (!Result) {
1654 Diag(Arg->getExprLoc(), diag::err_ptrauth_arg_not_ice);
1655 return false;
1656 }
1657
1658 unsigned Max;
1659 bool IsAddrDiscArg = false;
1660
1661 switch (Kind) {
1663 Max = 1;
1664 IsAddrDiscArg = true;
1665 break;
1668 break;
1669 };
1670
1672 if (IsAddrDiscArg)
1673 Diag(Arg->getExprLoc(), diag::err_ptrauth_address_discrimination_invalid)
1674 << Result->getExtValue();
1675 else
1676 Diag(Arg->getExprLoc(), diag::err_ptrauth_extra_discriminator_invalid)
1677 << Result->getExtValue() << Max;
1678
1679 return false;
1680 };
1681
1682 IntVal = Result->getZExtValue();
1683 return true;
1684}
1685
1686static std::pair<const ValueDecl *, CharUnits>
1688 // Must evaluate as a pointer.
1690 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1691 return {nullptr, CharUnits()};
1692
1693 const auto *BaseDecl =
1694 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1695 if (!BaseDecl)
1696 return {nullptr, CharUnits()};
1697
1698 return {BaseDecl, Result.Val.getLValueOffset()};
1699}
1700
1701static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1702 bool RequireConstant = false) {
1703 if (Arg->hasPlaceholderType()) {
1705 if (R.isInvalid())
1706 return true;
1707 Arg = R.get();
1708 }
1709
1710 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1711 return OpKind != PAO_BlendInteger;
1712 };
1713 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1714 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1715 OpKind == PAO_SignGeneric;
1716 };
1717
1718 // Require the value to have the right range of type.
1719 QualType ExpectedTy;
1720 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1721 ExpectedTy = Arg->getType().getUnqualifiedType();
1722 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1723 ExpectedTy = S.Context.VoidPtrTy;
1724 } else if (AllowsInteger(OpKind) &&
1726 ExpectedTy = S.Context.getUIntPtrType();
1727
1728 } else {
1729 // Diagnose the failures.
1730 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1731 << unsigned(OpKind == PAO_Discriminator ? 1
1732 : OpKind == PAO_BlendPointer ? 2
1733 : OpKind == PAO_BlendInteger ? 3
1734 : 0)
1735 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1736 << Arg->getType() << Arg->getSourceRange();
1737 return true;
1738 }
1739
1740 // Convert to that type. This should just be an lvalue-to-rvalue
1741 // conversion.
1742 if (convertArgumentToType(S, Arg, ExpectedTy))
1743 return true;
1744
1745 if (!RequireConstant) {
1746 // Warn about null pointers for non-generic sign and auth operations.
1747 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1749 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1750 ? diag::warn_ptrauth_sign_null_pointer
1751 : diag::warn_ptrauth_auth_null_pointer)
1752 << Arg->getSourceRange();
1753 }
1754
1755 return false;
1756 }
1757
1758 // Perform special checking on the arguments to ptrauth_sign_constant.
1759
1760 // The main argument.
1761 if (OpKind == PAO_Sign) {
1762 // Require the value we're signing to have a special form.
1763 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1764 bool Invalid;
1765
1766 // Must be rooted in a declaration reference.
1767 if (!BaseDecl)
1768 Invalid = true;
1769
1770 // If it's a function declaration, we can't have an offset.
1771 else if (isa<FunctionDecl>(BaseDecl))
1772 Invalid = !Offset.isZero();
1773
1774 // Otherwise we're fine.
1775 else
1776 Invalid = false;
1777
1778 if (Invalid)
1779 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1780 return Invalid;
1781 }
1782
1783 // The discriminator argument.
1784 assert(OpKind == PAO_Discriminator);
1785
1786 // Must be a pointer or integer or blend thereof.
1787 Expr *Pointer = nullptr;
1788 Expr *Integer = nullptr;
1789 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1790 if (Call->getBuiltinCallee() ==
1791 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1792 Pointer = Call->getArg(0);
1793 Integer = Call->getArg(1);
1794 }
1795 }
1796 if (!Pointer && !Integer) {
1797 if (Arg->getType()->isPointerType())
1798 Pointer = Arg;
1799 else
1800 Integer = Arg;
1801 }
1802
1803 // Check the pointer.
1804 bool Invalid = false;
1805 if (Pointer) {
1806 assert(Pointer->getType()->isPointerType());
1807
1808 // TODO: if we're initializing a global, check that the address is
1809 // somehow related to what we're initializing. This probably will
1810 // never really be feasible and we'll have to catch it at link-time.
1811 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
1812 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
1813 Invalid = true;
1814 }
1815
1816 // Check the integer.
1817 if (Integer) {
1818 assert(Integer->getType()->isIntegerType());
1819 if (!Integer->isEvaluatable(S.Context))
1820 Invalid = true;
1821 }
1822
1823 if (Invalid)
1824 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
1825 return Invalid;
1826}
1827
1829 if (S.checkArgCount(Call, 2))
1830 return ExprError();
1832 return ExprError();
1833 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
1834 checkPointerAuthKey(S, Call->getArgs()[1]))
1835 return ExprError();
1836
1837 Call->setType(Call->getArgs()[0]->getType());
1838 return Call;
1839}
1840
1842 if (S.checkArgCount(Call, 2))
1843 return ExprError();
1845 return ExprError();
1846 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
1847 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
1848 return ExprError();
1849
1850 Call->setType(S.Context.getUIntPtrType());
1851 return Call;
1852}
1853
1855 if (S.checkArgCount(Call, 2))
1856 return ExprError();
1858 return ExprError();
1859 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
1860 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
1861 return ExprError();
1862
1863 Call->setType(S.Context.getUIntPtrType());
1864 return Call;
1865}
1866
1868 PointerAuthOpKind OpKind,
1869 bool RequireConstant) {
1870 if (S.checkArgCount(Call, 3))
1871 return ExprError();
1873 return ExprError();
1874 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
1875 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1876 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
1877 RequireConstant))
1878 return ExprError();
1879
1880 Call->setType(Call->getArgs()[0]->getType());
1881 return Call;
1882}
1883
1885 if (S.checkArgCount(Call, 5))
1886 return ExprError();
1888 return ExprError();
1889 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1890 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1891 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1892 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1893 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
1894 return ExprError();
1895
1896 Call->setType(Call->getArgs()[0]->getType());
1897 return Call;
1898}
1899
1901 if (S.checkArgCount(Call, 6))
1902 return ExprError();
1904 return ExprError();
1905 const Expr *AddendExpr = Call->getArg(5);
1906 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(S.Context);
1907 if (!AddendIsConstInt) {
1908 const Expr *Arg = Call->getArg(5)->IgnoreParenImpCasts();
1909 DeclRefExpr *DRE = cast<DeclRefExpr>(Call->getCallee()->IgnoreParenCasts());
1910 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1911 S.Diag(Arg->getBeginLoc(), diag::err_constant_integer_last_arg_type)
1912 << FDecl->getDeclName() << Arg->getSourceRange();
1913 }
1914 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1915 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1916 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1917 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1918 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator) ||
1919 !AddendIsConstInt)
1920 return ExprError();
1921
1922 Call->setType(Call->getArgs()[0]->getType());
1923 return Call;
1924}
1925
1928 return ExprError();
1929
1930 // We've already performed normal call type-checking.
1931 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
1932
1933 // Operand must be an ordinary or UTF-8 string literal.
1934 const auto *Literal = dyn_cast<StringLiteral>(Arg);
1935 if (!Literal || Literal->getCharByteWidth() != 1) {
1936 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
1937 << (Literal ? 1 : 0) << Arg->getSourceRange();
1938 return ExprError();
1939 }
1940
1941 return Call;
1942}
1943
1945 if (S.checkArgCount(Call, 1))
1946 return ExprError();
1947 Expr *FirstArg = Call->getArg(0);
1948 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(FirstArg);
1949 if (FirstValue.isInvalid())
1950 return ExprError();
1951 Call->setArg(0, FirstValue.get());
1952 QualType FirstArgType = FirstArg->getType();
1953 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
1954 FirstArgType = S.Context.getDecayedType(FirstArgType);
1955
1956 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
1957 if (!FirstArgRecord) {
1958 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1959 << /*isPolymorphic=*/0 << FirstArgType;
1960 return ExprError();
1961 }
1962 if (S.RequireCompleteType(
1963 FirstArg->getBeginLoc(), FirstArgType->getPointeeType(),
1964 diag::err_get_vtable_pointer_requires_complete_type)) {
1965 return ExprError();
1966 }
1967
1968 if (!FirstArgRecord->isPolymorphic()) {
1969 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1970 << /*isPolymorphic=*/1 << FirstArgRecord;
1971 return ExprError();
1972 }
1974 Call->setType(ReturnType);
1975 return Call;
1976}
1977
1979 if (S.checkArgCount(TheCall, 1))
1980 return ExprError();
1981
1982 // Compute __builtin_launder's parameter type from the argument.
1983 // The parameter type is:
1984 // * The type of the argument if it's not an array or function type,
1985 // Otherwise,
1986 // * The decayed argument type.
1987 QualType ParamTy = [&]() {
1988 QualType ArgTy = TheCall->getArg(0)->getType();
1989 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1990 return S.Context.getPointerType(Ty->getElementType());
1991 if (ArgTy->isFunctionType()) {
1992 return S.Context.getPointerType(ArgTy);
1993 }
1994 return ArgTy;
1995 }();
1996
1997 TheCall->setType(ParamTy);
1998
1999 auto DiagSelect = [&]() -> std::optional<unsigned> {
2000 if (!ParamTy->isPointerType())
2001 return 0;
2002 if (ParamTy->isFunctionPointerType())
2003 return 1;
2004 if (ParamTy->isVoidPointerType())
2005 return 2;
2006 return std::optional<unsigned>{};
2007 }();
2008 if (DiagSelect) {
2009 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
2010 << *DiagSelect << TheCall->getSourceRange();
2011 return ExprError();
2012 }
2013
2014 // We either have an incomplete class type, or we have a class template
2015 // whose instantiation has not been forced. Example:
2016 //
2017 // template <class T> struct Foo { T value; };
2018 // Foo<int> *p = nullptr;
2019 // auto *d = __builtin_launder(p);
2020 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
2021 diag::err_incomplete_type))
2022 return ExprError();
2023
2024 assert(ParamTy->getPointeeType()->isObjectType() &&
2025 "Unhandled non-object pointer case");
2026
2027 InitializedEntity Entity =
2029 ExprResult Arg =
2030 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
2031 if (Arg.isInvalid())
2032 return ExprError();
2033 TheCall->setArg(0, Arg.get());
2034
2035 return TheCall;
2036}
2037
2039 if (S.checkArgCount(TheCall, 1))
2040 return ExprError();
2041
2043 if (Arg.isInvalid())
2044 return ExprError();
2045 QualType ParamTy = Arg.get()->getType();
2046 TheCall->setArg(0, Arg.get());
2047 TheCall->setType(S.Context.BoolTy);
2048
2049 // Only accept pointers to objects as arguments, which should have object
2050 // pointer or void pointer types.
2051 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2052 // LWG4138: Function pointer types not allowed
2053 if (PT->getPointeeType()->isFunctionType()) {
2054 S.Diag(TheCall->getArg(0)->getExprLoc(),
2055 diag::err_builtin_is_within_lifetime_invalid_arg)
2056 << 1;
2057 return ExprError();
2058 }
2059 // Disallow VLAs too since those shouldn't be able to
2060 // be a template parameter for `std::is_within_lifetime`
2061 if (PT->getPointeeType()->isVariableArrayType()) {
2062 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
2063 << 1 << "__builtin_is_within_lifetime";
2064 return ExprError();
2065 }
2066 } else {
2067 S.Diag(TheCall->getArg(0)->getExprLoc(),
2068 diag::err_builtin_is_within_lifetime_invalid_arg)
2069 << 0;
2070 return ExprError();
2071 }
2072 return TheCall;
2073}
2074
2076 if (S.checkArgCount(TheCall, 3))
2077 return ExprError();
2078
2079 QualType Dest = TheCall->getArg(0)->getType();
2080 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2081 S.Diag(TheCall->getArg(0)->getExprLoc(),
2082 diag::err_builtin_trivially_relocate_invalid_arg_type)
2083 << /*a pointer*/ 0;
2084 return ExprError();
2085 }
2086
2087 QualType T = Dest->getPointeeType();
2088 if (S.RequireCompleteType(TheCall->getBeginLoc(), T,
2089 diag::err_incomplete_type))
2090 return ExprError();
2091
2092 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2093 T->isIncompleteArrayType()) {
2094 S.Diag(TheCall->getArg(0)->getExprLoc(),
2095 diag::err_builtin_trivially_relocate_invalid_arg_type)
2096 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2097 return ExprError();
2098 }
2099
2100 TheCall->setType(Dest);
2101
2102 QualType Src = TheCall->getArg(1)->getType();
2103 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2104 S.Diag(TheCall->getArg(1)->getExprLoc(),
2105 diag::err_builtin_trivially_relocate_invalid_arg_type)
2106 << /*the same*/ 3;
2107 return ExprError();
2108 }
2109
2110 Expr *SizeExpr = TheCall->getArg(2);
2111 ExprResult Size = S.DefaultLvalueConversion(SizeExpr);
2112 if (Size.isInvalid())
2113 return ExprError();
2114
2115 Size = S.tryConvertExprToType(Size.get(), S.getASTContext().getSizeType());
2116 if (Size.isInvalid())
2117 return ExprError();
2118 SizeExpr = Size.get();
2119 TheCall->setArg(2, SizeExpr);
2120
2121 return TheCall;
2122}
2123
2124// Emit an error and return true if the current object format type is in the
2125// list of unsupported types.
2127 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2128 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2129 llvm::Triple::ObjectFormatType CurObjFormat =
2130 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2131 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2132 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2133 << TheCall->getSourceRange();
2134 return true;
2135 }
2136 return false;
2137}
2138
2139// Emit an error and return true if the current architecture is not in the list
2140// of supported architectures.
2141static bool
2143 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2144 llvm::Triple::ArchType CurArch =
2145 S.getASTContext().getTargetInfo().getTriple().getArch();
2146 if (llvm::is_contained(SupportedArchs, CurArch))
2147 return false;
2148 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2149 << TheCall->getSourceRange();
2150 return true;
2151}
2152
2153static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2154 SourceLocation CallSiteLoc);
2155
2156bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2157 CallExpr *TheCall) {
2158 switch (TI.getTriple().getArch()) {
2159 default:
2160 // Some builtins don't require additional checking, so just consider these
2161 // acceptable.
2162 return false;
2163 case llvm::Triple::arm:
2164 case llvm::Triple::armeb:
2165 case llvm::Triple::thumb:
2166 case llvm::Triple::thumbeb:
2167 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2168 case llvm::Triple::aarch64:
2169 case llvm::Triple::aarch64_32:
2170 case llvm::Triple::aarch64_be:
2171 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2172 case llvm::Triple::bpfeb:
2173 case llvm::Triple::bpfel:
2174 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2175 case llvm::Triple::dxil:
2176 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2177 case llvm::Triple::hexagon:
2178 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2179 case llvm::Triple::mips:
2180 case llvm::Triple::mipsel:
2181 case llvm::Triple::mips64:
2182 case llvm::Triple::mips64el:
2183 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2184 case llvm::Triple::spirv:
2185 case llvm::Triple::spirv32:
2186 case llvm::Triple::spirv64:
2187 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2188 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2189 return false;
2190 case llvm::Triple::systemz:
2191 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2192 case llvm::Triple::x86:
2193 case llvm::Triple::x86_64:
2194 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2195 case llvm::Triple::ppc:
2196 case llvm::Triple::ppcle:
2197 case llvm::Triple::ppc64:
2198 case llvm::Triple::ppc64le:
2199 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2200 case llvm::Triple::amdgcn:
2201 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2202 case llvm::Triple::riscv32:
2203 case llvm::Triple::riscv64:
2204 case llvm::Triple::riscv32be:
2205 case llvm::Triple::riscv64be:
2206 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2207 case llvm::Triple::loongarch32:
2208 case llvm::Triple::loongarch64:
2209 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2210 TheCall);
2211 case llvm::Triple::wasm32:
2212 case llvm::Triple::wasm64:
2213 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2214 case llvm::Triple::nvptx:
2215 case llvm::Triple::nvptx64:
2216 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2217 }
2218}
2219
2221 return T->isDependentType() ||
2222 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2223}
2224
2225// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2226// not a valid type, emit an error message and return true. Otherwise return
2227// false.
2228static bool
2231 int ArgOrdinal) {
2232 clang::QualType EltTy =
2233 ArgTy->isVectorType() ? ArgTy->getAs<VectorType>()->getElementType()
2234 : ArgTy->isMatrixType() ? ArgTy->getAs<MatrixType>()->getElementType()
2235 : ArgTy;
2236
2237 switch (ArgTyRestr) {
2239 if (!ArgTy->getAs<VectorType>() && !isValidMathElementType(ArgTy)) {
2240 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2241 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2242 << ArgTy;
2243 }
2244 break;
2246 if (!EltTy->isRealFloatingType()) {
2247 // FIXME: make diagnostic's wording correct for matrices
2248 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2249 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2250 << /* floating-point */ 1 << ArgTy;
2251 }
2252 break;
2254 if (!EltTy->isIntegerType()) {
2255 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2256 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2257 << /* no fp */ 0 << ArgTy;
2258 }
2259 break;
2261 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2262 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2263 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2264 << /* or fp */ 1 << ArgTy;
2265 }
2266 break;
2267 }
2268
2269 return false;
2270}
2271
2272/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2273/// This checks that the target supports the builtin and that the string
2274/// argument is constant and valid.
2275static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2276 const TargetInfo *AuxTI, unsigned BuiltinID) {
2277 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2278 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2279 "Expecting __builtin_cpu_...");
2280
2281 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2282 const TargetInfo *TheTI = &TI;
2283 auto SupportsBI = [=](const TargetInfo *TInfo) {
2284 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2285 (!IsCPUSupports && TInfo->supportsCpuIs()));
2286 };
2287 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2288 TheTI = AuxTI;
2289
2290 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2291 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2292 return S.Diag(TheCall->getBeginLoc(),
2293 TI.getTriple().isOSAIX()
2294 ? diag::err_builtin_aix_os_unsupported
2295 : diag::err_builtin_target_unsupported)
2296 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2297
2298 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2299 // Check if the argument is a string literal.
2300 if (!isa<StringLiteral>(Arg))
2301 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2302 << Arg->getSourceRange();
2303
2304 // Check the contents of the string.
2305 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2306 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2307 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2308 << Arg->getSourceRange();
2309 return false;
2310 }
2311 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2312 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2313 << Arg->getSourceRange();
2314 return false;
2315}
2316
2317/// Checks that __builtin_bswapg was called with a single argument, which is an
2318/// unsigned integer, and overrides the return value type to the integer type.
2319static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2320 if (S.checkArgCount(TheCall, 1))
2321 return true;
2322 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2323 if (ArgRes.isInvalid())
2324 return true;
2325
2326 Expr *Arg = ArgRes.get();
2327 TheCall->setArg(0, Arg);
2328 if (Arg->isTypeDependent())
2329 return false;
2330
2331 QualType ArgTy = Arg->getType();
2332
2333 if (!ArgTy->isIntegerType()) {
2334 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2335 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2336 << ArgTy;
2337 return true;
2338 }
2339 if (const auto *BT = dyn_cast<BitIntType>(ArgTy)) {
2340 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2341 BT->getNumBits() != 1) {
2342 S.Diag(Arg->getBeginLoc(), diag::err_bswapg_invalid_bit_width)
2343 << ArgTy << BT->getNumBits();
2344 return true;
2345 }
2346 }
2347 TheCall->setType(ArgTy);
2348 return false;
2349}
2350
2351/// Checks that __builtin_bitreverseg was called with a single argument, which
2352/// is an integer
2353static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2354 if (S.checkArgCount(TheCall, 1))
2355 return true;
2356 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2357 if (ArgRes.isInvalid())
2358 return true;
2359
2360 Expr *Arg = ArgRes.get();
2361 TheCall->setArg(0, Arg);
2362 if (Arg->isTypeDependent())
2363 return false;
2364
2365 QualType ArgTy = Arg->getType();
2366
2367 if (!ArgTy->isIntegerType()) {
2368 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2369 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2370 << ArgTy;
2371 return true;
2372 }
2373 TheCall->setType(ArgTy);
2374 return false;
2375}
2376
2377/// Checks that __builtin_popcountg was called with a single argument, which is
2378/// an unsigned integer.
2379static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2380 if (S.checkArgCount(TheCall, 1))
2381 return true;
2382
2383 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2384 if (ArgRes.isInvalid())
2385 return true;
2386
2387 Expr *Arg = ArgRes.get();
2388 TheCall->setArg(0, Arg);
2389
2390 QualType ArgTy = Arg->getType();
2391
2392 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2393 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2394 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2395 << ArgTy;
2396 return true;
2397 }
2398 return false;
2399}
2400
2401/// Checks the __builtin_stdc_* builtins that take a single unsigned integer
2402/// argument and return either int, bool, or the argument type.
2403static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall,
2404 QualType ReturnType) {
2405 if (S.checkArgCount(TheCall, 1))
2406 return true;
2407
2408 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2409 if (ArgRes.isInvalid())
2410 return true;
2411
2412 Expr *Arg = ArgRes.get();
2413 TheCall->setArg(0, Arg);
2414
2415 QualType ArgTy = Arg->getType();
2416 // C23 stdbit.h functions do not permit bool or enumeration types.
2417 if (ArgTy->isBooleanType() || ArgTy->isEnumeralType())
2418 return S.Diag(Arg->getBeginLoc(),
2419 diag::err_builtin_stdc_invalid_arg_type_bool_or_enum)
2420 << 1 /*1st argument*/ << ArgTy;
2421 if (!ArgTy->isUnsignedIntegerType())
2422 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_invalid_arg_type)
2423 << 1 /*1st argument*/ << ArgTy;
2424
2425 // For builtins returning unsigned int, verify the argument's bit width fits.
2426 // On targets where unsigned int is 16 bits, a large _BitInt argument could
2427 // produce a count that overflows the return type.
2428 if (!ReturnType.isNull() && ReturnType == S.Context.UnsignedIntTy) {
2429 uint64_t ArgWidth = S.Context.getIntWidth(ArgTy);
2430 uint64_t ReturnTypeWidth = S.Context.getIntWidth(S.Context.UnsignedIntTy);
2431 if (!llvm::isUIntN(ReturnTypeWidth, ArgWidth))
2432 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_result_overflow)
2433 << ArgTy;
2434 }
2435
2436 TheCall->setType(ReturnType.isNull() ? ArgTy : ReturnType);
2437 return false;
2438}
2439
2440/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2441/// an unsigned integer, and an optional second argument, which is promoted to
2442/// an 'int'.
2443static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2444 if (S.checkArgCountRange(TheCall, 1, 2))
2445 return true;
2446
2447 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2448 if (Arg0Res.isInvalid())
2449 return true;
2450
2451 Expr *Arg0 = Arg0Res.get();
2452 TheCall->setArg(0, Arg0);
2453
2454 QualType Arg0Ty = Arg0->getType();
2455
2456 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2457 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2458 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2459 << Arg0Ty;
2460 return true;
2461 }
2462
2463 if (TheCall->getNumArgs() > 1) {
2464 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2465 if (Arg1Res.isInvalid())
2466 return true;
2467
2468 Expr *Arg1 = Arg1Res.get();
2469 TheCall->setArg(1, Arg1);
2470
2471 QualType Arg1Ty = Arg1->getType();
2472
2473 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2474 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2475 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2476 return true;
2477 }
2478 }
2479
2480 return false;
2481}
2482
2484 unsigned ArgIndex;
2485 bool OnlyUnsigned;
2486
2488 QualType T) {
2489 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2490 << ArgIndex << /*scalar*/ 1
2491 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2492 << /*no fp*/ 0 << T;
2493 }
2494
2495public:
2496 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2497 : ContextualImplicitConverter(/*Suppress=*/false,
2498 /*SuppressConversion=*/true),
2499 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2500
2501 bool match(QualType T) override {
2502 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2503 }
2504
2506 QualType T) override {
2507 return emitError(S, Loc, T);
2508 }
2509
2511 QualType T) override {
2512 return emitError(S, Loc, T);
2513 }
2514
2516 QualType T,
2517 QualType ConvTy) override {
2518 return emitError(S, Loc, T);
2519 }
2520
2522 QualType ConvTy) override {
2523 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2524 }
2525
2527 QualType T) override {
2528 return emitError(S, Loc, T);
2529 }
2530
2532 QualType ConvTy) override {
2533 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2534 }
2535
2537 QualType T,
2538 QualType ConvTy) override {
2539 llvm_unreachable("conversion functions are permitted");
2540 }
2541};
2542
2543/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2544/// arguments, that the first argument is an unsigned integer type, and that
2545/// the second argument is an integer type.
2546static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2547 if (S.checkArgCount(TheCall, 2))
2548 return true;
2549
2550 // First argument (value to rotate) must be unsigned integer type.
2551 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2553 TheCall->getArg(0)->getBeginLoc(), TheCall->getArg(0), Arg0Converter);
2554 if (Arg0Res.isInvalid())
2555 return true;
2556
2557 Expr *Arg0 = Arg0Res.get();
2558 TheCall->setArg(0, Arg0);
2559
2560 QualType Arg0Ty = Arg0->getType();
2561 if (!Arg0Ty->isUnsignedIntegerType())
2562 return true;
2563
2564 // Second argument (rotation count) must be integer type.
2565 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2567 TheCall->getArg(1)->getBeginLoc(), TheCall->getArg(1), Arg1Converter);
2568 if (Arg1Res.isInvalid())
2569 return true;
2570
2571 Expr *Arg1 = Arg1Res.get();
2572 TheCall->setArg(1, Arg1);
2573
2574 QualType Arg1Ty = Arg1->getType();
2575 if (!Arg1Ty->isIntegerType())
2576 return true;
2577
2578 TheCall->setType(Arg0Ty);
2579 return false;
2580}
2581
2582static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2583 unsigned Pos, bool AllowConst,
2584 bool AllowAS) {
2585 QualType MaskTy = MaskArg->getType();
2586 if (!MaskTy->isExtVectorBoolType())
2587 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2588 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2589 << MaskTy;
2590
2591 QualType PtrTy = PtrArg->getType();
2592 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2593 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2594 << Pos << "scalar pointer";
2595
2596 QualType PointeeTy = PtrTy->getPointeeType();
2597 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2598 (!AllowConst && PointeeTy.isConstQualified()) ||
2599 (!AllowAS && PointeeTy.hasAddressSpace())) {
2602 return S.Diag(PtrArg->getExprLoc(),
2603 diag::err_typecheck_convert_incompatible)
2604 << PtrTy << Target << /*different qualifiers=*/5
2605 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2606 << PtrTy << Target;
2607 }
2608 return false;
2609}
2610
2611static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2612 bool TypeDependent = false;
2613 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2614 ExprResult Converted =
2616 if (Converted.isInvalid())
2617 return true;
2618 TheCall->setArg(Arg, Converted.get());
2619 TypeDependent |= Converted.get()->isTypeDependent();
2620 }
2621
2622 if (TypeDependent)
2623 TheCall->setType(S.Context.DependentTy);
2624 return false;
2625}
2626
2628 if (S.checkArgCountRange(TheCall, 2, 3))
2629 return ExprError();
2630
2631 if (ConvertMaskedBuiltinArgs(S, TheCall))
2632 return ExprError();
2633
2634 Expr *MaskArg = TheCall->getArg(0);
2635 Expr *PtrArg = TheCall->getArg(1);
2636 if (TheCall->isTypeDependent())
2637 return TheCall;
2638
2639 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2640 TheCall->getBuiltinCallee() ==
2641 Builtin::BI__builtin_masked_load))
2642 return ExprError();
2643
2644 QualType MaskTy = MaskArg->getType();
2645 QualType PtrTy = PtrArg->getType();
2646 QualType PointeeTy = PtrTy->getPointeeType();
2647 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2648
2650 MaskVecTy->getNumElements());
2651 if (TheCall->getNumArgs() == 3) {
2652 Expr *PassThruArg = TheCall->getArg(2);
2653 QualType PassThruTy = PassThruArg->getType();
2654 if (!S.Context.hasSameType(PassThruTy, RetTy))
2655 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2656 << /* third argument */ 3 << RetTy;
2657 }
2658
2659 TheCall->setType(RetTy);
2660 return TheCall;
2661}
2662
2664 if (S.checkArgCount(TheCall, 3))
2665 return ExprError();
2666
2667 if (ConvertMaskedBuiltinArgs(S, TheCall))
2668 return ExprError();
2669
2670 Expr *MaskArg = TheCall->getArg(0);
2671 Expr *ValArg = TheCall->getArg(1);
2672 Expr *PtrArg = TheCall->getArg(2);
2673 if (TheCall->isTypeDependent())
2674 return TheCall;
2675
2676 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2677 TheCall->getBuiltinCallee() ==
2678 Builtin::BI__builtin_masked_store))
2679 return ExprError();
2680
2681 QualType MaskTy = MaskArg->getType();
2682 QualType PtrTy = PtrArg->getType();
2683 QualType ValTy = ValArg->getType();
2684 if (!ValTy->isVectorType())
2685 return ExprError(
2686 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2687 << 2 << "vector");
2688
2689 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2690 const VectorType *ValVecTy = ValTy->getAs<VectorType>();
2691
2692 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements()) {
2693 return ExprError(
2694 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2696 TheCall->getBuiltinCallee())
2697 << MaskTy << ValTy);
2698 }
2699
2700 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
2701 PtrTy->getPointeeType().getUnqualifiedType()))
2702 return ExprError(S.Diag(TheCall->getBeginLoc(),
2703 diag::err_vec_builtin_incompatible_vector)
2704 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2705 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2706 TheCall->getArg(1)->getEndLoc()));
2707
2708 TheCall->setType(S.Context.VoidTy);
2709 return TheCall;
2710}
2711
2713 if (S.checkArgCountRange(TheCall, 3, 4))
2714 return ExprError();
2715
2716 if (ConvertMaskedBuiltinArgs(S, TheCall))
2717 return ExprError();
2718
2719 Expr *MaskArg = TheCall->getArg(0);
2720 Expr *IdxArg = TheCall->getArg(1);
2721 Expr *PtrArg = TheCall->getArg(2);
2722 if (TheCall->isTypeDependent())
2723 return TheCall;
2724
2725 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
2726 /*AllowAS=*/true))
2727 return ExprError();
2728
2729 QualType IdxTy = IdxArg->getType();
2730 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2731 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2732 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2733 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2734 << IdxTy;
2735
2736 QualType MaskTy = MaskArg->getType();
2737 QualType PtrTy = PtrArg->getType();
2738 QualType PointeeTy = PtrTy->getPointeeType();
2739 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2740 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2741 return ExprError(
2742 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2744 TheCall->getBuiltinCallee())
2745 << MaskTy << IdxTy);
2746
2748 MaskVecTy->getNumElements());
2749 if (TheCall->getNumArgs() == 4) {
2750 Expr *PassThruArg = TheCall->getArg(3);
2751 QualType PassThruTy = PassThruArg->getType();
2752 if (!S.Context.hasSameType(PassThruTy, RetTy))
2753 return S.Diag(PassThruArg->getExprLoc(),
2754 diag::err_vec_masked_load_store_ptr)
2755 << /* fourth argument */ 4 << RetTy;
2756 }
2757
2758 TheCall->setType(RetTy);
2759 return TheCall;
2760}
2761
2763 if (S.checkArgCount(TheCall, 4))
2764 return ExprError();
2765
2766 if (ConvertMaskedBuiltinArgs(S, TheCall))
2767 return ExprError();
2768
2769 Expr *MaskArg = TheCall->getArg(0);
2770 Expr *IdxArg = TheCall->getArg(1);
2771 Expr *ValArg = TheCall->getArg(2);
2772 Expr *PtrArg = TheCall->getArg(3);
2773 if (TheCall->isTypeDependent())
2774 return TheCall;
2775
2776 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
2777 /*AllowAS=*/true))
2778 return ExprError();
2779
2780 QualType IdxTy = IdxArg->getType();
2781 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2782 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2783 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2784 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2785 << IdxTy;
2786
2787 QualType ValTy = ValArg->getType();
2788 QualType MaskTy = MaskArg->getType();
2789 QualType PtrTy = PtrArg->getType();
2790
2791 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2792 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2793 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2794 return ExprError(
2795 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2797 TheCall->getBuiltinCallee())
2798 << MaskTy << IdxTy);
2799 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2800 return ExprError(
2801 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2803 TheCall->getBuiltinCallee())
2804 << MaskTy << ValTy);
2805
2806 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
2807 PtrTy->getPointeeType().getUnqualifiedType()))
2808 return ExprError(S.Diag(TheCall->getBeginLoc(),
2809 diag::err_vec_builtin_incompatible_vector)
2810 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2811 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2812 TheCall->getArg(1)->getEndLoc()));
2813
2814 TheCall->setType(S.Context.VoidTy);
2815 return TheCall;
2816}
2817
2819 SourceLocation Loc = TheCall->getBeginLoc();
2820 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2821 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2822
2823 if (Args.size() == 0) {
2824 S.Diag(TheCall->getBeginLoc(),
2825 diag::err_typecheck_call_too_few_args_at_least)
2826 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2827 << /*is_non_object=*/0 << TheCall->getSourceRange();
2828 return ExprError();
2829 }
2830
2831 QualType FuncT = Args[0]->getType();
2832
2833 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2834 if (Args.size() < 2) {
2835 S.Diag(TheCall->getBeginLoc(),
2836 diag::err_typecheck_call_too_few_args_at_least)
2837 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2838 << /*is_non_object=*/0 << TheCall->getSourceRange();
2839 return ExprError();
2840 }
2841
2842 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2843 QualType ObjectT = Args[1]->getType();
2844
2845 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
2846 return ExprError();
2847
2848 ExprResult ObjectArg = [&]() -> ExprResult {
2849 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2850 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2851 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2852 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2853 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2854 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2855 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
2856 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
2857 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
2858 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
2859 return Args[1];
2860 }
2861
2862 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2863 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2864 // reference_wrapper;
2865 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2866 if (RD->isInStdNamespace() &&
2867 RD->getDeclName().getAsString() == "reference_wrapper") {
2868 CXXScopeSpec SS;
2869 IdentifierInfo *GetName = &S.Context.Idents.get("get");
2870 UnqualifiedId GetID;
2871 GetID.setIdentifier(GetName, Loc);
2872
2874 S.getCurScope(), Args[1], Loc, tok::period, SS,
2875 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
2876
2877 if (MemExpr.isInvalid())
2878 return ExprError();
2879
2880 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
2881 }
2882 }
2883
2884 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
2885 // class T and t1 does not satisfy the previous two items;
2886
2887 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
2888 }();
2889
2890 if (ObjectArg.isInvalid())
2891 return ExprError();
2892
2893 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
2894 tok::periodstar, ObjectArg.get(), Args[0]);
2895 if (BinOp.isInvalid())
2896 return ExprError();
2897
2898 if (MPT->isMemberDataPointer())
2899 return BinOp;
2900
2901 auto *MemCall = new (S.Context)
2903
2904 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
2905 Args.drop_front(2), TheCall->getRParenLoc());
2906 }
2907 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
2908 Args.drop_front(), TheCall->getRParenLoc());
2909}
2910
2911// Performs a similar job to Sema::UsualUnaryConversions, but without any
2912// implicit promotion of integral/enumeration types.
2914 // First, convert to an r-value.
2916 if (Res.isInvalid())
2917 return ExprError();
2918
2919 // Promote floating-point types.
2920 return S.UsualUnaryFPConversions(Res.get());
2921}
2922
2924 if (const auto *TyA = VecTy->getAs<VectorType>())
2925 return TyA->getElementType();
2926 if (VecTy->isSizelessVectorType())
2927 return VecTy->getSizelessVectorEltType(Context);
2928 return QualType();
2929}
2930
2932Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2933 CallExpr *TheCall) {
2934 ExprResult TheCallResult(TheCall);
2935
2936 // Find out if any arguments are required to be integer constant expressions.
2937 unsigned ICEArguments = 0;
2939 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2941 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2942
2943 // If any arguments are required to be ICE's, check and diagnose.
2944 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2945 // Skip arguments not required to be ICE's.
2946 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2947
2948 llvm::APSInt Result;
2949 // If we don't have enough arguments, continue so we can issue better
2950 // diagnostic in checkArgCount(...)
2951 if (ArgNo < TheCall->getNumArgs() &&
2952 BuiltinConstantArg(TheCall, ArgNo, Result))
2953 return true;
2954 ICEArguments &= ~(1 << ArgNo);
2955 }
2956
2957 FPOptions FPO;
2958 switch (BuiltinID) {
2959 case Builtin::BI__builtin___get_unsafe_stack_start:
2960 case Builtin::BI__builtin___get_unsafe_stack_bottom:
2961 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
2962 << Context.BuiltinInfo.getQuotedName(BuiltinID)
2963 << "__safestack_get_unsafe_stack_bottom";
2964 break;
2965 case Builtin::BI__builtin___get_unsafe_stack_top:
2966 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
2967 << Context.BuiltinInfo.getQuotedName(BuiltinID)
2968 << "__safestack_get_unsafe_stack_top";
2969 break;
2970 case Builtin::BI__builtin___get_unsafe_stack_ptr:
2971 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
2972 << Context.BuiltinInfo.getQuotedName(BuiltinID)
2973 << "__safestack_get_unsafe_stack_ptr";
2974 break;
2975 case Builtin::BI__builtin_cpu_supports:
2976 case Builtin::BI__builtin_cpu_is:
2977 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2978 Context.getAuxTargetInfo(), BuiltinID))
2979 return ExprError();
2980 break;
2981 case Builtin::BI__builtin_cpu_init:
2982 if (!Context.getTargetInfo().supportsCpuInit()) {
2983 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2984 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2985 return ExprError();
2986 }
2987 break;
2988 case Builtin::BI__builtin___CFStringMakeConstantString:
2989 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2990 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2992 *this, BuiltinID, TheCall,
2993 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2994 return ExprError();
2995 assert(TheCall->getNumArgs() == 1 &&
2996 "Wrong # arguments to builtin CFStringMakeConstantString");
2997 if (ObjC().CheckObjCString(TheCall->getArg(0)))
2998 return ExprError();
2999 break;
3000 case Builtin::BI__builtin_ms_va_start:
3001 case Builtin::BI__builtin_stdarg_start:
3002 case Builtin::BI__builtin_va_start:
3003 case Builtin::BI__builtin_c23_va_start:
3004 if (BuiltinVAStart(BuiltinID, TheCall))
3005 return ExprError();
3006 break;
3007 case Builtin::BI__va_start: {
3008 switch (Context.getTargetInfo().getTriple().getArch()) {
3009 case llvm::Triple::aarch64:
3010 case llvm::Triple::arm:
3011 case llvm::Triple::thumb:
3012 if (BuiltinVAStartARMMicrosoft(TheCall))
3013 return ExprError();
3014 break;
3015 default:
3016 if (BuiltinVAStart(BuiltinID, TheCall))
3017 return ExprError();
3018 break;
3019 }
3020 break;
3021 }
3022
3023 // The acquire, release, and no fence variants are ARM and AArch64 only.
3024 case Builtin::BI_interlockedbittestandset_acq:
3025 case Builtin::BI_interlockedbittestandset_rel:
3026 case Builtin::BI_interlockedbittestandset_nf:
3027 case Builtin::BI_interlockedbittestandreset_acq:
3028 case Builtin::BI_interlockedbittestandreset_rel:
3029 case Builtin::BI_interlockedbittestandreset_nf:
3031 *this, TheCall,
3032 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
3033 return ExprError();
3034 break;
3035
3036 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
3037 case Builtin::BI_bittest64:
3038 case Builtin::BI_bittestandcomplement64:
3039 case Builtin::BI_bittestandreset64:
3040 case Builtin::BI_bittestandset64:
3041 case Builtin::BI_interlockedbittestandreset64:
3042 case Builtin::BI_interlockedbittestandset64:
3044 *this, TheCall,
3045 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
3046 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
3047 return ExprError();
3048 break;
3049
3050 // The 64-bit acquire, release, and no fence variants are AArch64 only.
3051 case Builtin::BI_interlockedbittestandreset64_acq:
3052 case Builtin::BI_interlockedbittestandreset64_rel:
3053 case Builtin::BI_interlockedbittestandreset64_nf:
3054 case Builtin::BI_interlockedbittestandset64_acq:
3055 case Builtin::BI_interlockedbittestandset64_rel:
3056 case Builtin::BI_interlockedbittestandset64_nf:
3057 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
3058 return ExprError();
3059 break;
3060
3061 case Builtin::BI__builtin_set_flt_rounds:
3063 *this, TheCall,
3064 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
3065 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
3066 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
3067 llvm::Triple::ppc64le}))
3068 return ExprError();
3069 break;
3070
3071 case Builtin::BI__builtin_isgreater:
3072 case Builtin::BI__builtin_isgreaterequal:
3073 case Builtin::BI__builtin_isless:
3074 case Builtin::BI__builtin_islessequal:
3075 case Builtin::BI__builtin_islessgreater:
3076 case Builtin::BI__builtin_isunordered:
3077 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
3078 return ExprError();
3079 break;
3080 case Builtin::BI__builtin_fpclassify:
3081 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
3082 return ExprError();
3083 break;
3084 case Builtin::BI__builtin_isfpclass:
3085 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
3086 return ExprError();
3087 break;
3088 case Builtin::BI__builtin_isfinite:
3089 case Builtin::BI__builtin_isinf:
3090 case Builtin::BI__builtin_isinf_sign:
3091 case Builtin::BI__builtin_isnan:
3092 case Builtin::BI__builtin_issignaling:
3093 case Builtin::BI__builtin_isnormal:
3094 case Builtin::BI__builtin_issubnormal:
3095 case Builtin::BI__builtin_iszero:
3096 case Builtin::BI__builtin_signbit:
3097 case Builtin::BI__builtin_signbitf:
3098 case Builtin::BI__builtin_signbitl:
3099 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
3100 return ExprError();
3101 break;
3102 case Builtin::BI__builtin_shufflevector:
3103 return BuiltinShuffleVector(TheCall);
3104 // TheCall will be freed by the smart pointer here, but that's fine, since
3105 // BuiltinShuffleVector guts it, but then doesn't release it.
3106 case Builtin::BI__builtin_masked_load:
3107 case Builtin::BI__builtin_masked_expand_load:
3108 return BuiltinMaskedLoad(*this, TheCall);
3109 case Builtin::BI__builtin_masked_store:
3110 case Builtin::BI__builtin_masked_compress_store:
3111 return BuiltinMaskedStore(*this, TheCall);
3112 case Builtin::BI__builtin_masked_gather:
3113 return BuiltinMaskedGather(*this, TheCall);
3114 case Builtin::BI__builtin_masked_scatter:
3115 return BuiltinMaskedScatter(*this, TheCall);
3116 case Builtin::BI__builtin_invoke:
3117 return BuiltinInvoke(*this, TheCall);
3118 case Builtin::BI__builtin_prefetch:
3119 if (BuiltinPrefetch(TheCall))
3120 return ExprError();
3121 break;
3122 case Builtin::BI__builtin_alloca_with_align:
3123 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3124 if (BuiltinAllocaWithAlign(TheCall))
3125 return ExprError();
3126 [[fallthrough]];
3127 case Builtin::BI__builtin_alloca:
3128 case Builtin::BI__builtin_alloca_uninitialized:
3129 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
3130 << TheCall->getDirectCallee();
3131 if (getLangOpts().OpenCL) {
3132 builtinAllocaAddrSpace(*this, TheCall);
3133 }
3134 break;
3135 case Builtin::BI__builtin_infer_alloc_token:
3136 if (checkBuiltinInferAllocToken(*this, TheCall))
3137 return ExprError();
3138 break;
3139 case Builtin::BI__arithmetic_fence:
3140 if (BuiltinArithmeticFence(TheCall))
3141 return ExprError();
3142 break;
3143 case Builtin::BI__assume:
3144 case Builtin::BI__builtin_assume:
3145 if (BuiltinAssume(TheCall))
3146 return ExprError();
3147 break;
3148 case Builtin::BI__builtin_assume_aligned:
3149 if (BuiltinAssumeAligned(TheCall))
3150 return ExprError();
3151 break;
3152 case Builtin::BI__builtin_dynamic_object_size:
3153 case Builtin::BI__builtin_object_size:
3154 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
3155 return ExprError();
3156 break;
3157 case Builtin::BI__builtin_longjmp:
3158 if (BuiltinLongjmp(TheCall))
3159 return ExprError();
3160 break;
3161 case Builtin::BI__builtin_setjmp:
3162 if (BuiltinSetjmp(TheCall))
3163 return ExprError();
3164 break;
3165 case Builtin::BI__builtin_complex:
3166 if (BuiltinComplex(TheCall))
3167 return ExprError();
3168 break;
3169 case Builtin::BI__builtin_classify_type:
3170 case Builtin::BI__builtin_constant_p: {
3171 if (checkArgCount(TheCall, 1))
3172 return true;
3174 if (Arg.isInvalid()) return true;
3175 TheCall->setArg(0, Arg.get());
3176 TheCall->setType(Context.IntTy);
3177 break;
3178 }
3179 case Builtin::BI__builtin_launder:
3180 return BuiltinLaunder(*this, TheCall);
3181 case Builtin::BI__builtin_is_within_lifetime:
3182 return BuiltinIsWithinLifetime(*this, TheCall);
3183 case Builtin::BI__builtin_trivially_relocate:
3184 return BuiltinTriviallyRelocate(*this, TheCall);
3185 case Builtin::BI__builtin_clear_padding: {
3186 if (checkArgCount(TheCall, 1))
3187 return ExprError();
3188
3189 const Expr *PtrArg = TheCall->getArg(0);
3190 const QualType PtrArgType = PtrArg->getType();
3191 if (!PtrArgType->isPointerType()) {
3192 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
3193 << PtrArgType << "pointer" << 1 << 0 << 3 << 1 << PtrArgType
3194 << "pointer";
3195 return ExprError();
3196 }
3197 QualType PointeeType = PtrArgType->getPointeeType();
3198 if (PointeeType.isConstQualified()) {
3199 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_assign_const)
3200 << TheCall->getSourceRange() << 4 /*ConstUnknown*/;
3201 return ExprError();
3202 }
3203 if (RequireCompleteType(PtrArg->getBeginLoc(), PointeeType,
3204 diag::err_typecheck_decl_incomplete_type))
3205 return ExprError();
3206
3207 // For non trivially copyable types, we try to match gcc's behaviour.
3208 // i.e. __builtin_clear_padding(&var) is OK as long as var is a complete
3209 // object, either a local variable or a function parameter passed by value
3210 auto IsAddrOfDeclExpr = [&]() {
3211 const Expr *Inner = PtrArg->IgnoreParenNoopCasts(Context);
3212 const auto *UnaryOp = dyn_cast<UnaryOperator>(Inner);
3213 if (!UnaryOp || UnaryOp->getOpcode() != UO_AddrOf)
3214 return false;
3215
3216 const Expr *Operand =
3217 UnaryOp->getSubExpr()->IgnoreParenNoopCasts(Context);
3218 const auto *DeclRef = dyn_cast<DeclRefExpr>(Operand);
3219 if (!DeclRef)
3220 return false;
3221
3222 const auto *VarDecl = dyn_cast<::clang::VarDecl>(DeclRef->getDecl());
3223 if (!VarDecl || VarDecl->getType()->isReferenceType())
3224 return false;
3225
3226 // matching GCC behaviour
3227 // __builtin_clear_padding((X*)&var) is fine as long X is the type of var
3228 QualType VarQType = VarDecl->getType();
3229 return PointeeType.getTypePtr() == VarQType.getTypePtr() ||
3230 Context.hasSameUnqualifiedType(PointeeType, VarQType);
3231 };
3232
3233 if (!PointeeType.isTriviallyCopyableType(Context) &&
3234 !PointeeType->isAtomicType() // _Atomic is not copyable
3235 && !IsAddrOfDeclExpr()) {
3236 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_needs_trivial_copy)
3237 << PtrArg->getType() << PtrArg->getSourceRange();
3238 return ExprError();
3239 }
3240
3241 if (auto *Record = PointeeType->getAsRecordDecl();
3243 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_no_flexible_array)
3244 << PointeeType << PtrArg->getSourceRange();
3245 return ExprError();
3246 }
3247
3248 break;
3249 }
3250 case Builtin::BI__sync_fetch_and_add:
3251 case Builtin::BI__sync_fetch_and_add_1:
3252 case Builtin::BI__sync_fetch_and_add_2:
3253 case Builtin::BI__sync_fetch_and_add_4:
3254 case Builtin::BI__sync_fetch_and_add_8:
3255 case Builtin::BI__sync_fetch_and_add_16:
3256 case Builtin::BI__sync_fetch_and_sub:
3257 case Builtin::BI__sync_fetch_and_sub_1:
3258 case Builtin::BI__sync_fetch_and_sub_2:
3259 case Builtin::BI__sync_fetch_and_sub_4:
3260 case Builtin::BI__sync_fetch_and_sub_8:
3261 case Builtin::BI__sync_fetch_and_sub_16:
3262 case Builtin::BI__sync_fetch_and_or:
3263 case Builtin::BI__sync_fetch_and_or_1:
3264 case Builtin::BI__sync_fetch_and_or_2:
3265 case Builtin::BI__sync_fetch_and_or_4:
3266 case Builtin::BI__sync_fetch_and_or_8:
3267 case Builtin::BI__sync_fetch_and_or_16:
3268 case Builtin::BI__sync_fetch_and_and:
3269 case Builtin::BI__sync_fetch_and_and_1:
3270 case Builtin::BI__sync_fetch_and_and_2:
3271 case Builtin::BI__sync_fetch_and_and_4:
3272 case Builtin::BI__sync_fetch_and_and_8:
3273 case Builtin::BI__sync_fetch_and_and_16:
3274 case Builtin::BI__sync_fetch_and_xor:
3275 case Builtin::BI__sync_fetch_and_xor_1:
3276 case Builtin::BI__sync_fetch_and_xor_2:
3277 case Builtin::BI__sync_fetch_and_xor_4:
3278 case Builtin::BI__sync_fetch_and_xor_8:
3279 case Builtin::BI__sync_fetch_and_xor_16:
3280 case Builtin::BI__sync_fetch_and_nand:
3281 case Builtin::BI__sync_fetch_and_nand_1:
3282 case Builtin::BI__sync_fetch_and_nand_2:
3283 case Builtin::BI__sync_fetch_and_nand_4:
3284 case Builtin::BI__sync_fetch_and_nand_8:
3285 case Builtin::BI__sync_fetch_and_nand_16:
3286 case Builtin::BI__sync_add_and_fetch:
3287 case Builtin::BI__sync_add_and_fetch_1:
3288 case Builtin::BI__sync_add_and_fetch_2:
3289 case Builtin::BI__sync_add_and_fetch_4:
3290 case Builtin::BI__sync_add_and_fetch_8:
3291 case Builtin::BI__sync_add_and_fetch_16:
3292 case Builtin::BI__sync_sub_and_fetch:
3293 case Builtin::BI__sync_sub_and_fetch_1:
3294 case Builtin::BI__sync_sub_and_fetch_2:
3295 case Builtin::BI__sync_sub_and_fetch_4:
3296 case Builtin::BI__sync_sub_and_fetch_8:
3297 case Builtin::BI__sync_sub_and_fetch_16:
3298 case Builtin::BI__sync_and_and_fetch:
3299 case Builtin::BI__sync_and_and_fetch_1:
3300 case Builtin::BI__sync_and_and_fetch_2:
3301 case Builtin::BI__sync_and_and_fetch_4:
3302 case Builtin::BI__sync_and_and_fetch_8:
3303 case Builtin::BI__sync_and_and_fetch_16:
3304 case Builtin::BI__sync_or_and_fetch:
3305 case Builtin::BI__sync_or_and_fetch_1:
3306 case Builtin::BI__sync_or_and_fetch_2:
3307 case Builtin::BI__sync_or_and_fetch_4:
3308 case Builtin::BI__sync_or_and_fetch_8:
3309 case Builtin::BI__sync_or_and_fetch_16:
3310 case Builtin::BI__sync_xor_and_fetch:
3311 case Builtin::BI__sync_xor_and_fetch_1:
3312 case Builtin::BI__sync_xor_and_fetch_2:
3313 case Builtin::BI__sync_xor_and_fetch_4:
3314 case Builtin::BI__sync_xor_and_fetch_8:
3315 case Builtin::BI__sync_xor_and_fetch_16:
3316 case Builtin::BI__sync_nand_and_fetch:
3317 case Builtin::BI__sync_nand_and_fetch_1:
3318 case Builtin::BI__sync_nand_and_fetch_2:
3319 case Builtin::BI__sync_nand_and_fetch_4:
3320 case Builtin::BI__sync_nand_and_fetch_8:
3321 case Builtin::BI__sync_nand_and_fetch_16:
3322 case Builtin::BI__sync_val_compare_and_swap:
3323 case Builtin::BI__sync_val_compare_and_swap_1:
3324 case Builtin::BI__sync_val_compare_and_swap_2:
3325 case Builtin::BI__sync_val_compare_and_swap_4:
3326 case Builtin::BI__sync_val_compare_and_swap_8:
3327 case Builtin::BI__sync_val_compare_and_swap_16:
3328 case Builtin::BI__sync_bool_compare_and_swap:
3329 case Builtin::BI__sync_bool_compare_and_swap_1:
3330 case Builtin::BI__sync_bool_compare_and_swap_2:
3331 case Builtin::BI__sync_bool_compare_and_swap_4:
3332 case Builtin::BI__sync_bool_compare_and_swap_8:
3333 case Builtin::BI__sync_bool_compare_and_swap_16:
3334 case Builtin::BI__sync_lock_test_and_set:
3335 case Builtin::BI__sync_lock_test_and_set_1:
3336 case Builtin::BI__sync_lock_test_and_set_2:
3337 case Builtin::BI__sync_lock_test_and_set_4:
3338 case Builtin::BI__sync_lock_test_and_set_8:
3339 case Builtin::BI__sync_lock_test_and_set_16:
3340 case Builtin::BI__sync_lock_release:
3341 case Builtin::BI__sync_lock_release_1:
3342 case Builtin::BI__sync_lock_release_2:
3343 case Builtin::BI__sync_lock_release_4:
3344 case Builtin::BI__sync_lock_release_8:
3345 case Builtin::BI__sync_lock_release_16:
3346 case Builtin::BI__sync_swap:
3347 case Builtin::BI__sync_swap_1:
3348 case Builtin::BI__sync_swap_2:
3349 case Builtin::BI__sync_swap_4:
3350 case Builtin::BI__sync_swap_8:
3351 case Builtin::BI__sync_swap_16:
3352 return BuiltinAtomicOverloaded(TheCallResult);
3353 case Builtin::BI__sync_synchronize:
3354 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
3355 << TheCall->getCallee()->getSourceRange();
3356 break;
3357 case Builtin::BI__builtin_nontemporal_load:
3358 case Builtin::BI__builtin_nontemporal_store:
3359 return BuiltinNontemporalOverloaded(TheCallResult);
3360 case Builtin::BI__builtin_memcpy_inline: {
3361 clang::Expr *SizeOp = TheCall->getArg(2);
3362 // We warn about copying to or from `nullptr` pointers when `size` is
3363 // greater than 0. When `size` is value dependent we cannot evaluate its
3364 // value so we bail out.
3365 if (SizeOp->isValueDependent())
3366 break;
3367 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
3368 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3369 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
3370 }
3371 break;
3372 }
3373 case Builtin::BI__builtin_memset_inline: {
3374 clang::Expr *SizeOp = TheCall->getArg(2);
3375 // We warn about filling to `nullptr` pointers when `size` is greater than
3376 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3377 // out.
3378 if (SizeOp->isValueDependent())
3379 break;
3380 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
3381 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3382 break;
3383 }
3384#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3385 case Builtin::BI##ID: \
3386 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3387#include "clang/Basic/Builtins.inc"
3388 case Builtin::BI__annotation: {
3389 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3390 if (!TT.isOSWindows() && !TT.isUEFI()) {
3391 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
3392 << TheCall->getSourceRange();
3393 return ExprError();
3394 }
3395 if (BuiltinMSVCAnnotation(*this, TheCall))
3396 return ExprError();
3397 break;
3398 }
3399 case Builtin::BI__builtin_annotation:
3400 if (BuiltinAnnotation(*this, TheCall))
3401 return ExprError();
3402 break;
3403 case Builtin::BI__builtin_addressof:
3404 if (BuiltinAddressof(*this, TheCall))
3405 return ExprError();
3406 break;
3407 case Builtin::BI__builtin_function_start:
3408 if (BuiltinFunctionStart(*this, TheCall))
3409 return ExprError();
3410 break;
3411 case Builtin::BI__builtin_is_aligned:
3412 case Builtin::BI__builtin_align_up:
3413 case Builtin::BI__builtin_align_down:
3414 if (BuiltinAlignment(*this, TheCall, BuiltinID))
3415 return ExprError();
3416 break;
3417 case Builtin::BI__builtin_add_overflow:
3418 case Builtin::BI__builtin_sub_overflow:
3419 case Builtin::BI__builtin_mul_overflow:
3420 if (BuiltinOverflow(*this, TheCall, BuiltinID))
3421 return ExprError();
3422 break;
3423 case Builtin::BI__builtin_operator_new:
3424 case Builtin::BI__builtin_operator_delete: {
3425 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3426 ExprResult Res =
3427 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3428 return Res;
3429 }
3430 case Builtin::BI__builtin_dump_struct:
3431 return BuiltinDumpStruct(*this, TheCall);
3432 case Builtin::BI__builtin_expect_with_probability: {
3433 // We first want to ensure we are called with 3 arguments
3434 if (checkArgCount(TheCall, 3))
3435 return ExprError();
3436 // then check probability is constant float in range [0.0, 1.0]
3437 const Expr *ProbArg = TheCall->getArg(2);
3438 SmallVector<PartialDiagnosticAt, 8> Notes;
3439 Expr::EvalResult Eval;
3440 Eval.Diag = &Notes;
3441 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3442 !Eval.Val.isFloat()) {
3443 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3444 << ProbArg->getSourceRange();
3445 for (const PartialDiagnosticAt &PDiag : Notes)
3446 Diag(PDiag.first, PDiag.second);
3447 return ExprError();
3448 }
3449 llvm::APFloat Probability = Eval.Val.getFloat();
3450 bool LoseInfo = false;
3451 Probability.convert(llvm::APFloat::IEEEdouble(),
3452 llvm::RoundingMode::Dynamic, &LoseInfo);
3453 if (!(Probability >= llvm::APFloat(0.0) &&
3454 Probability <= llvm::APFloat(1.0))) {
3455 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3456 << ProbArg->getSourceRange();
3457 return ExprError();
3458 }
3459 break;
3460 }
3461 case Builtin::BI__builtin_preserve_access_index:
3462 if (BuiltinPreserveAI(*this, TheCall))
3463 return ExprError();
3464 break;
3465 case Builtin::BI__builtin_call_with_static_chain:
3466 if (BuiltinCallWithStaticChain(*this, TheCall))
3467 return ExprError();
3468 break;
3469 case Builtin::BI__exception_code:
3470 case Builtin::BI_exception_code:
3471 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3472 diag::err_seh___except_block))
3473 return ExprError();
3474 break;
3475 case Builtin::BI__exception_info:
3476 case Builtin::BI_exception_info:
3477 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3478 diag::err_seh___except_filter))
3479 return ExprError();
3480 break;
3481 case Builtin::BI__GetExceptionInfo:
3482 if (checkArgCount(TheCall, 1))
3483 return ExprError();
3484
3486 TheCall->getBeginLoc(),
3487 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3488 TheCall))
3489 return ExprError();
3490
3491 TheCall->setType(Context.VoidPtrTy);
3492 break;
3493 case Builtin::BIaddressof:
3494 case Builtin::BI__addressof:
3495 case Builtin::BIforward:
3496 case Builtin::BIforward_like:
3497 case Builtin::BImove:
3498 case Builtin::BImove_if_noexcept:
3499 case Builtin::BIas_const: {
3500 // These are all expected to be of the form
3501 // T &/&&/* f(U &/&&)
3502 // where T and U only differ in qualification.
3503 if (checkArgCount(TheCall, 1))
3504 return ExprError();
3505 QualType Param = FDecl->getParamDecl(0)->getType();
3506 QualType Result = FDecl->getReturnType();
3507 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3508 BuiltinID == Builtin::BI__addressof;
3509 if (!(Param->isReferenceType() &&
3510 (ReturnsPointer ? Result->isAnyPointerType()
3511 : Result->isReferenceType()) &&
3512 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3513 Result->getPointeeType()))) {
3514 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3515 << FDecl;
3516 return ExprError();
3517 }
3518 break;
3519 }
3520 case Builtin::BI__builtin_ptrauth_strip:
3521 return PointerAuthStrip(*this, TheCall);
3522 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3523 return PointerAuthBlendDiscriminator(*this, TheCall);
3524 case Builtin::BI__builtin_ptrauth_sign_constant:
3525 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3526 /*RequireConstant=*/true);
3527 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3528 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3529 /*RequireConstant=*/false);
3530 case Builtin::BI__builtin_ptrauth_auth:
3531 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3532 /*RequireConstant=*/false);
3533 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3534 return PointerAuthSignGenericData(*this, TheCall);
3535 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3536 return PointerAuthAuthAndResign(*this, TheCall);
3537 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3538 return PointerAuthAuthLoadRelativeAndSign(*this, TheCall);
3539 case Builtin::BI__builtin_ptrauth_string_discriminator:
3540 return PointerAuthStringDiscriminator(*this, TheCall);
3541
3542 case Builtin::BI__builtin_get_vtable_pointer:
3543 return GetVTablePointer(*this, TheCall);
3544
3545 // OpenCL v2.0, s6.13.16 - Pipe functions
3546 case Builtin::BIread_pipe:
3547 case Builtin::BIwrite_pipe:
3548 // Since those two functions are declared with var args, we need a semantic
3549 // check for the argument.
3550 if (OpenCL().checkBuiltinRWPipe(TheCall))
3551 return ExprError();
3552 break;
3553 case Builtin::BIreserve_read_pipe:
3554 case Builtin::BIreserve_write_pipe:
3555 case Builtin::BIwork_group_reserve_read_pipe:
3556 case Builtin::BIwork_group_reserve_write_pipe:
3557 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3558 return ExprError();
3559 break;
3560 case Builtin::BIsub_group_reserve_read_pipe:
3561 case Builtin::BIsub_group_reserve_write_pipe:
3562 if (OpenCL().checkSubgroupExt(TheCall) ||
3563 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3564 return ExprError();
3565 break;
3566 case Builtin::BIcommit_read_pipe:
3567 case Builtin::BIcommit_write_pipe:
3568 case Builtin::BIwork_group_commit_read_pipe:
3569 case Builtin::BIwork_group_commit_write_pipe:
3570 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3571 return ExprError();
3572 break;
3573 case Builtin::BIsub_group_commit_read_pipe:
3574 case Builtin::BIsub_group_commit_write_pipe:
3575 if (OpenCL().checkSubgroupExt(TheCall) ||
3576 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3577 return ExprError();
3578 break;
3579 case Builtin::BIget_pipe_num_packets:
3580 case Builtin::BIget_pipe_max_packets:
3581 if (OpenCL().checkBuiltinPipePackets(TheCall))
3582 return ExprError();
3583 break;
3584 case Builtin::BIto_global:
3585 case Builtin::BIto_local:
3586 case Builtin::BIto_private:
3587 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3588 return ExprError();
3589 break;
3590 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3591 case Builtin::BIenqueue_kernel:
3592 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3593 return ExprError();
3594 break;
3595 case Builtin::BIget_kernel_work_group_size:
3596 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3597 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3598 return ExprError();
3599 break;
3600 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3601 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3602 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3603 return ExprError();
3604 break;
3605 case Builtin::BI__builtin_os_log_format:
3606 Cleanup.setExprNeedsCleanups(true);
3607 [[fallthrough]];
3608 case Builtin::BI__builtin_os_log_format_buffer_size:
3609 if (BuiltinOSLogFormat(TheCall))
3610 return ExprError();
3611 break;
3612 case Builtin::BI__builtin_frame_address:
3613 case Builtin::BI__builtin_return_address: {
3614 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3615 return ExprError();
3616
3617 // -Wframe-address warning if non-zero passed to builtin
3618 // return/frame address.
3619 Expr::EvalResult Result;
3620 if (!TheCall->getArg(0)->isValueDependent() &&
3621 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3622 Result.Val.getInt() != 0)
3623 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3624 << ((BuiltinID == Builtin::BI__builtin_return_address)
3625 ? "__builtin_return_address"
3626 : "__builtin_frame_address")
3627 << TheCall->getSourceRange();
3628 break;
3629 }
3630
3631 case Builtin::BI__builtin_nondeterministic_value: {
3632 if (BuiltinNonDeterministicValue(TheCall))
3633 return ExprError();
3634 break;
3635 }
3636
3637 // __builtin_elementwise_abs restricts the element type to signed integers or
3638 // floating point types only.
3639 case Builtin::BI__builtin_elementwise_abs:
3642 return ExprError();
3643 break;
3644
3645 // These builtins restrict the element type to floating point
3646 // types only.
3647 case Builtin::BI__builtin_elementwise_acos:
3648 case Builtin::BI__builtin_elementwise_asin:
3649 case Builtin::BI__builtin_elementwise_atan:
3650 case Builtin::BI__builtin_elementwise_ceil:
3651 case Builtin::BI__builtin_elementwise_cos:
3652 case Builtin::BI__builtin_elementwise_cosh:
3653 case Builtin::BI__builtin_elementwise_exp:
3654 case Builtin::BI__builtin_elementwise_exp2:
3655 case Builtin::BI__builtin_elementwise_exp10:
3656 case Builtin::BI__builtin_elementwise_floor:
3657 case Builtin::BI__builtin_elementwise_log:
3658 case Builtin::BI__builtin_elementwise_log2:
3659 case Builtin::BI__builtin_elementwise_log10:
3660 case Builtin::BI__builtin_elementwise_roundeven:
3661 case Builtin::BI__builtin_elementwise_round:
3662 case Builtin::BI__builtin_elementwise_rint:
3663 case Builtin::BI__builtin_elementwise_nearbyint:
3664 case Builtin::BI__builtin_elementwise_sin:
3665 case Builtin::BI__builtin_elementwise_sinh:
3666 case Builtin::BI__builtin_elementwise_sqrt:
3667 case Builtin::BI__builtin_elementwise_tan:
3668 case Builtin::BI__builtin_elementwise_tanh:
3669 case Builtin::BI__builtin_elementwise_trunc:
3670 case Builtin::BI__builtin_elementwise_canonicalize:
3673 return ExprError();
3674 break;
3675 case Builtin::BI__builtin_elementwise_fma:
3676 if (BuiltinElementwiseTernaryMath(TheCall))
3677 return ExprError();
3678 break;
3679
3680 case Builtin::BI__builtin_elementwise_ldexp: {
3681 if (checkArgCount(TheCall, 2))
3682 return ExprError();
3683
3684 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
3685 if (A.isInvalid())
3686 return ExprError();
3687 QualType TyA = A.get()->getType();
3688 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
3690 return ExprError();
3691
3692 ExprResult Exp = UsualUnaryConversions(TheCall->getArg(1));
3693 if (Exp.isInvalid())
3694 return ExprError();
3695 QualType TyExp = Exp.get()->getType();
3696 if (checkMathBuiltinElementType(*this, Exp.get()->getBeginLoc(), TyExp,
3698 2))
3699 return ExprError();
3700
3701 // Check the two arguments are either scalars or vectors of equal length.
3702 const auto *Vec0 = TyA->getAs<VectorType>();
3703 const auto *Vec1 = TyExp->getAs<VectorType>();
3704 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3705 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3706 if (Arg0Length != Arg1Length) {
3707 Diag(Exp.get()->getBeginLoc(),
3708 diag::err_typecheck_vector_lengths_not_equal)
3709 << TyA << TyExp << A.get()->getSourceRange()
3710 << Exp.get()->getSourceRange();
3711 return ExprError();
3712 }
3713
3714 TheCall->setArg(0, A.get());
3715 TheCall->setArg(1, Exp.get());
3716 TheCall->setType(TyA);
3717 break;
3718 }
3719
3720 // These builtins restrict the element type to floating point
3721 // types only, and take in two arguments.
3722 case Builtin::BI__builtin_elementwise_minnum:
3723 case Builtin::BI__builtin_elementwise_maxnum:
3724 case Builtin::BI__builtin_elementwise_minimum:
3725 case Builtin::BI__builtin_elementwise_maximum:
3726 case Builtin::BI__builtin_elementwise_minimumnum:
3727 case Builtin::BI__builtin_elementwise_maximumnum:
3728 case Builtin::BI__builtin_elementwise_atan2:
3729 case Builtin::BI__builtin_elementwise_fmod:
3730 case Builtin::BI__builtin_elementwise_pow:
3731 if (BuiltinElementwiseMath(TheCall,
3733 return ExprError();
3734 break;
3735 // These builtins restrict the element type to integer
3736 // types only.
3737 case Builtin::BI__builtin_elementwise_add_sat:
3738 case Builtin::BI__builtin_elementwise_sub_sat:
3739 case Builtin::BI__builtin_elementwise_clmul:
3740 case Builtin::BI__builtin_elementwise_pext:
3741 case Builtin::BI__builtin_elementwise_pdep:
3742 if (BuiltinElementwiseMath(TheCall,
3744 return ExprError();
3745 break;
3746 case Builtin::BI__builtin_elementwise_fshl:
3747 case Builtin::BI__builtin_elementwise_fshr:
3750 return ExprError();
3751 break;
3752 case Builtin::BI__builtin_elementwise_min:
3753 case Builtin::BI__builtin_elementwise_max: {
3754 if (BuiltinElementwiseMath(TheCall))
3755 return ExprError();
3756 Expr *Arg0 = TheCall->getArg(0);
3757 Expr *Arg1 = TheCall->getArg(1);
3758 QualType Ty0 = Arg0->getType();
3759 QualType Ty1 = Arg1->getType();
3760 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
3761 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
3762 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
3763 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
3764 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
3765 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin_no_suggestion)
3766 << Context.BuiltinInfo.getQuotedName(BuiltinID);
3767 break;
3768 }
3769 case Builtin::BI__builtin_elementwise_popcount:
3770 case Builtin::BI__builtin_elementwise_bitreverse:
3773 return ExprError();
3774 break;
3775 case Builtin::BI__builtin_elementwise_copysign: {
3776 if (checkArgCount(TheCall, 2))
3777 return ExprError();
3778
3779 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3780 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3781 if (Magnitude.isInvalid() || Sign.isInvalid())
3782 return ExprError();
3783
3784 QualType MagnitudeTy = Magnitude.get()->getType();
3785 QualType SignTy = Sign.get()->getType();
3787 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
3790 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
3792 return ExprError();
3793 }
3794
3795 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3796 return Diag(Sign.get()->getBeginLoc(),
3797 diag::err_typecheck_call_different_arg_types)
3798 << MagnitudeTy << SignTy;
3799 }
3800
3801 TheCall->setArg(0, Magnitude.get());
3802 TheCall->setArg(1, Sign.get());
3803 TheCall->setType(Magnitude.get()->getType());
3804 break;
3805 }
3806 case Builtin::BI__builtin_elementwise_clzg:
3807 case Builtin::BI__builtin_elementwise_ctzg:
3808 // These builtins can be unary or binary. Note for empty calls we call the
3809 // unary checker in order to not emit an error that says the function
3810 // expects 2 arguments, which would be misleading.
3811 if (TheCall->getNumArgs() <= 1) {
3814 return ExprError();
3815 } else if (BuiltinElementwiseMath(
3817 return ExprError();
3818 break;
3819 case Builtin::BI__builtin_reduce_max:
3820 case Builtin::BI__builtin_reduce_min: {
3821 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3822 return ExprError();
3823
3824 const Expr *Arg = TheCall->getArg(0);
3825 const auto *TyA = Arg->getType()->getAs<VectorType>();
3826
3827 QualType ElTy;
3828 if (TyA)
3829 ElTy = TyA->getElementType();
3830 else if (Arg->getType()->isSizelessVectorType())
3832
3833 if (ElTy.isNull()) {
3834 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3835 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3836 << Arg->getType();
3837 return ExprError();
3838 }
3839
3840 TheCall->setType(ElTy);
3841 break;
3842 }
3843 case Builtin::BI__builtin_reduce_maximum:
3844 case Builtin::BI__builtin_reduce_minimum: {
3845 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3846 return ExprError();
3847
3848 const Expr *Arg = TheCall->getArg(0);
3849 const auto *TyA = Arg->getType()->getAs<VectorType>();
3850
3851 QualType ElTy;
3852 if (TyA)
3853 ElTy = TyA->getElementType();
3854 else if (Arg->getType()->isSizelessVectorType())
3856
3857 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3858 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3859 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3860 << Arg->getType();
3861 return ExprError();
3862 }
3863
3864 TheCall->setType(ElTy);
3865 break;
3866 }
3867
3868 // These builtins support vectors of integers only.
3869 // TODO: ADD/MUL should support floating-point types.
3870 case Builtin::BI__builtin_reduce_add:
3871 case Builtin::BI__builtin_reduce_mul:
3872 case Builtin::BI__builtin_reduce_xor:
3873 case Builtin::BI__builtin_reduce_or:
3874 case Builtin::BI__builtin_reduce_and: {
3875 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3876 return ExprError();
3877
3878 const Expr *Arg = TheCall->getArg(0);
3879
3880 QualType ElTy = getVectorElementType(Context, Arg->getType());
3881 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3882 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3883 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3884 << Arg->getType();
3885 return ExprError();
3886 }
3887
3888 TheCall->setType(ElTy);
3889 break;
3890 }
3891
3892 case Builtin::BI__builtin_reduce_assoc_fadd:
3893 case Builtin::BI__builtin_reduce_in_order_fadd: {
3894 // For in-order reductions require the user to specify the start value.
3895 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
3896 if (InOrder ? checkArgCount(TheCall, 2) : checkArgCountRange(TheCall, 1, 2))
3897 return ExprError();
3898
3899 ExprResult Vec = UsualUnaryConversions(TheCall->getArg(0));
3900 if (Vec.isInvalid())
3901 return ExprError();
3902
3903 TheCall->setArg(0, Vec.get());
3904
3905 QualType ElTy = getVectorElementType(Context, Vec.get()->getType());
3906 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
3907 Diag(Vec.get()->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3908 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3909 << Vec.get()->getType();
3910 return ExprError();
3911 }
3912
3913 if (TheCall->getNumArgs() == 2) {
3914 ExprResult StartValue = UsualUnaryConversions(TheCall->getArg(1));
3915 if (StartValue.isInvalid())
3916 return ExprError();
3917
3918 if (!StartValue.get()->getType()->isRealFloatingType()) {
3919 Diag(StartValue.get()->getBeginLoc(),
3920 diag::err_builtin_invalid_arg_type)
3921 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
3922 << StartValue.get()->getType();
3923 return ExprError();
3924 }
3925 TheCall->setArg(1, StartValue.get());
3926 }
3927
3928 TheCall->setType(ElTy);
3929 break;
3930 }
3931
3932 case Builtin::BI__builtin_matrix_transpose:
3933 return BuiltinMatrixTranspose(TheCall, TheCallResult);
3934
3935 case Builtin::BI__builtin_matrix_column_major_load:
3936 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
3937
3938 case Builtin::BI__builtin_matrix_column_major_store:
3939 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
3940
3941 case Builtin::BI__builtin_verbose_trap:
3942 if (!checkBuiltinVerboseTrap(TheCall, *this))
3943 return ExprError();
3944 break;
3945
3946 case Builtin::BI__builtin_get_device_side_mangled_name: {
3947 auto Check = [](CallExpr *TheCall) {
3948 if (TheCall->getNumArgs() != 1)
3949 return false;
3950 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
3951 if (!DRE)
3952 return false;
3953 auto *D = DRE->getDecl();
3954 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
3955 return false;
3956 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3957 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3958 };
3959 if (!Check(TheCall)) {
3960 Diag(TheCall->getBeginLoc(),
3961 diag::err_hip_invalid_args_builtin_mangled_name);
3962 return ExprError();
3963 }
3964 break;
3965 }
3966 case Builtin::BI__builtin_bswapg:
3967 if (BuiltinBswapg(*this, TheCall))
3968 return ExprError();
3969 break;
3970 case Builtin::BI__builtin_bitreverseg:
3971 if (BuiltinBitreverseg(*this, TheCall))
3972 return ExprError();
3973 break;
3974 case Builtin::BI__builtin_popcountg:
3975 if (BuiltinPopcountg(*this, TheCall))
3976 return ExprError();
3977 break;
3978 case Builtin::BI__builtin_clzg:
3979 case Builtin::BI__builtin_ctzg:
3980 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
3981 return ExprError();
3982 break;
3983
3984 case Builtin::BI__builtin_stdc_rotate_left:
3985 case Builtin::BI__builtin_stdc_rotate_right:
3986 if (BuiltinRotateGeneric(*this, TheCall))
3987 return ExprError();
3988 break;
3989
3990 case Builtin::BI__builtin_stdc_memreverse8:
3991 case Builtin::BIstdc_memreverse8:
3992 case Builtin::BIstdc_memreverse8u8:
3993 case Builtin::BIstdc_memreverse8u16:
3994 case Builtin::BIstdc_memreverse8u32:
3995 case Builtin::BIstdc_memreverse8u64:
3996 if (Context.getTargetInfo().getCharWidth() != 8) {
3997 Diag(TheCall->getBeginLoc(), diag::err_builtin_requires_char_bit_8)
3998 << TheCall->getDirectCallee()->getName();
3999 return ExprError();
4000 }
4001 break;
4002
4003 case Builtin::BI__builtin_stdc_bit_floor:
4004 case Builtin::BI__builtin_stdc_bit_ceil:
4005 if (BuiltinStdCBuiltin(*this, TheCall, QualType()))
4006 return ExprError();
4007 break;
4008 case Builtin::BI__builtin_stdc_has_single_bit:
4009 if (BuiltinStdCBuiltin(*this, TheCall, Context.BoolTy))
4010 return ExprError();
4011 break;
4012 case Builtin::BI__builtin_stdc_leading_zeros:
4013 case Builtin::BI__builtin_stdc_leading_ones:
4014 case Builtin::BI__builtin_stdc_trailing_zeros:
4015 case Builtin::BI__builtin_stdc_trailing_ones:
4016 case Builtin::BI__builtin_stdc_first_leading_zero:
4017 case Builtin::BI__builtin_stdc_first_leading_one:
4018 case Builtin::BI__builtin_stdc_first_trailing_zero:
4019 case Builtin::BI__builtin_stdc_first_trailing_one:
4020 case Builtin::BI__builtin_stdc_count_zeros:
4021 case Builtin::BI__builtin_stdc_count_ones:
4022 case Builtin::BI__builtin_stdc_bit_width:
4023 if (BuiltinStdCBuiltin(*this, TheCall, Context.UnsignedIntTy))
4024 return ExprError();
4025 break;
4026
4027 case Builtin::BI__builtin_allow_runtime_check: {
4028 Expr *Arg = TheCall->getArg(0);
4029 // Check if the argument is a string literal.
4031 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4032 << Arg->getSourceRange();
4033 return ExprError();
4034 }
4035 break;
4036 }
4037
4038 case Builtin::BI__builtin_allow_sanitize_check: {
4039 if (checkArgCount(TheCall, 1))
4040 return ExprError();
4041
4042 Expr *Arg = TheCall->getArg(0);
4043 // Check if the argument is a string literal.
4044 const StringLiteral *SanitizerName =
4045 dyn_cast<StringLiteral>(Arg->IgnoreParenImpCasts());
4046 if (!SanitizerName) {
4047 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4048 << Arg->getSourceRange();
4049 return ExprError();
4050 }
4051 // Validate the sanitizer name.
4052 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
4053 .Cases({"address", "thread", "memory", "hwaddress",
4054 "kernel-address", "kernel-memory", "kernel-hwaddress"},
4055 true)
4056 .Default(false)) {
4057 Diag(TheCall->getBeginLoc(), diag::err_invalid_builtin_argument)
4058 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
4059 << Arg->getSourceRange();
4060 return ExprError();
4061 }
4062 break;
4063 }
4064 case Builtin::BI__builtin_counted_by_ref:
4065 if (BuiltinCountedByRef(TheCall))
4066 return ExprError();
4067 break;
4068 }
4069
4070 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
4071 return ExprError();
4072
4073 // Since the target specific builtins for each arch overlap, only check those
4074 // of the arch we are compiling for.
4075 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
4076 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
4077 assert(Context.getAuxTargetInfo() &&
4078 "Aux Target Builtin, but not an aux target?");
4079
4080 if (CheckTSBuiltinFunctionCall(
4081 *Context.getAuxTargetInfo(),
4082 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
4083 return ExprError();
4084 } else {
4085 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
4086 TheCall))
4087 return ExprError();
4088 }
4089 }
4090
4091 return TheCallResult;
4092}
4093
4094bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
4095 llvm::APSInt Result;
4096 // We can't check the value of a dependent argument.
4097 Expr *Arg = TheCall->getArg(ArgNum);
4098 if (Arg->isTypeDependent() || Arg->isValueDependent())
4099 return false;
4100
4101 // Check constant-ness first.
4102 if (BuiltinConstantArg(TheCall, ArgNum, Result))
4103 return true;
4104
4105 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
4106 if (Result.isShiftedMask() || (~Result).isShiftedMask())
4107 return false;
4108
4109 return Diag(TheCall->getBeginLoc(),
4110 diag::err_argument_not_contiguous_bit_field)
4111 << ArgNum << Arg->getSourceRange();
4112}
4113
4114bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
4115 unsigned FirstArg, FormatStringInfo *FSI) {
4116 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
4117 bool IsVariadic = false;
4118 if (const FunctionType *FnTy = D->getFunctionType())
4119 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
4120 else if (const auto *BD = dyn_cast<BlockDecl>(D))
4121 IsVariadic = BD->isVariadic();
4122 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
4123 IsVariadic = OMD->isVariadic();
4124
4125 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
4126 IsVariadic, FSI);
4127}
4128
4129bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
4130 bool HasImplicitThisParam, bool IsVariadic,
4131 FormatStringInfo *FSI) {
4132 if (FirstArg == 0)
4134 else if (IsVariadic)
4136 else
4138 FSI->FormatIdx = FormatIdx - 1;
4139 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
4140
4141 // The way the format attribute works in GCC, the implicit this argument
4142 // of member functions is counted. However, it doesn't appear in our own
4143 // lists, so decrement format_idx in that case.
4144 if (HasImplicitThisParam) {
4145 if(FSI->FormatIdx == 0)
4146 return false;
4147 --FSI->FormatIdx;
4148 if (FSI->FirstDataArg != 0)
4149 --FSI->FirstDataArg;
4150 }
4151 return true;
4152}
4153
4154/// Checks if a the given expression evaluates to null.
4155///
4156/// Returns true if the value evaluates to null.
4157static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4158 // Treat (smart) pointers constructed from nullptr as null, whether we can
4159 // const-evaluate them or not.
4160 // This must happen first: the smart pointer expr might have _Nonnull type!
4164 return true;
4165
4166 // If the expression has non-null type, it doesn't evaluate to null.
4167 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
4168 if (*nullability == NullabilityKind::NonNull)
4169 return false;
4170 }
4171
4172 // As a special case, transparent unions initialized with zero are
4173 // considered null for the purposes of the nonnull attribute.
4174 if (const RecordType *UT = Expr->getType()->getAsUnionType();
4175 UT &&
4176 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
4177 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
4178 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
4179 Expr = ILE->getInit(0);
4180 }
4181
4182 bool Result;
4183 return (!Expr->isValueDependent() &&
4185 !Result);
4186}
4187
4189 const Expr *ArgExpr,
4190 SourceLocation CallSiteLoc) {
4191 if (CheckNonNullExpr(S, ArgExpr))
4192 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4193 S.PDiag(diag::warn_null_arg)
4194 << ArgExpr->getSourceRange());
4195}
4196
4197/// Determine whether the given type has a non-null nullability annotation.
4199 if (auto nullability = type->getNullability())
4200 return *nullability == NullabilityKind::NonNull;
4201
4202 return false;
4203}
4204
4206 const NamedDecl *FDecl,
4207 const FunctionProtoType *Proto,
4209 SourceLocation CallSiteLoc) {
4210 assert((FDecl || Proto) && "Need a function declaration or prototype");
4211
4212 // Already checked by constant evaluator.
4214 return;
4215 // Check the attributes attached to the method/function itself.
4216 llvm::SmallBitVector NonNullArgs;
4217 if (FDecl) {
4218 // Handle the nonnull attribute on the function/method declaration itself.
4219 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4220 if (!NonNull->args_size()) {
4221 // Easy case: all pointer arguments are nonnull.
4222 for (const auto *Arg : Args)
4223 if (S.isValidPointerAttrType(Arg->getType()))
4224 CheckNonNullArgument(S, Arg, CallSiteLoc);
4225 return;
4226 }
4227
4228 for (const ParamIdx &Idx : NonNull->args()) {
4229 unsigned IdxAST = Idx.getASTIndex();
4230 if (IdxAST >= Args.size())
4231 continue;
4232 if (NonNullArgs.empty())
4233 NonNullArgs.resize(Args.size());
4234 NonNullArgs.set(IdxAST);
4235 }
4236 }
4237 }
4238
4239 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4240 // Handle the nonnull attribute on the parameters of the
4241 // function/method.
4243 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4244 parms = FD->parameters();
4245 else
4246 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4247
4248 unsigned ParamIndex = 0;
4249 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4250 I != E; ++I, ++ParamIndex) {
4251 const ParmVarDecl *PVD = *I;
4252 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
4253 if (NonNullArgs.empty())
4254 NonNullArgs.resize(Args.size());
4255
4256 NonNullArgs.set(ParamIndex);
4257 }
4258 }
4259 } else {
4260 // If we have a non-function, non-method declaration but no
4261 // function prototype, try to dig out the function prototype.
4262 if (!Proto) {
4263 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4264 QualType type = VD->getType().getNonReferenceType();
4265 if (auto pointerType = type->getAs<PointerType>())
4266 type = pointerType->getPointeeType();
4267 else if (auto blockType = type->getAs<BlockPointerType>())
4268 type = blockType->getPointeeType();
4269 // FIXME: data member pointers?
4270
4271 // Dig out the function prototype, if there is one.
4272 Proto = type->getAs<FunctionProtoType>();
4273 }
4274 }
4275
4276 // Fill in non-null argument information from the nullability
4277 // information on the parameter types (if we have them).
4278 if (Proto) {
4279 unsigned Index = 0;
4280 for (auto paramType : Proto->getParamTypes()) {
4281 if (isNonNullType(paramType)) {
4282 if (NonNullArgs.empty())
4283 NonNullArgs.resize(Args.size());
4284
4285 NonNullArgs.set(Index);
4286 }
4287
4288 ++Index;
4289 }
4290 }
4291 }
4292
4293 // Check for non-null arguments.
4294 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4295 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4296 if (NonNullArgs[ArgIndex])
4297 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
4298 }
4299}
4300
4301void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4302 StringRef ParamName, QualType ArgTy,
4303 QualType ParamTy) {
4304
4305 // If a function accepts a pointer or reference type
4306 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4307 return;
4308
4309 // If the parameter is a pointer type, get the pointee type for the
4310 // argument too. If the parameter is a reference type, don't try to get
4311 // the pointee type for the argument.
4312 if (ParamTy->isPointerType())
4313 ArgTy = ArgTy->getPointeeType();
4314
4315 // Remove reference or pointer
4316 ParamTy = ParamTy->getPointeeType();
4317
4318 // Find expected alignment, and the actual alignment of the passed object.
4319 // getTypeAlignInChars requires complete types
4320 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4321 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4322 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4323 return;
4324
4325 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4326 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4327
4328 // If the argument is less aligned than the parameter, there is a
4329 // potential alignment issue.
4330 if (ArgAlign < ParamAlign)
4331 Diag(Loc, diag::warn_param_mismatched_alignment)
4332 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4333 << ParamName << (FDecl != nullptr) << FDecl;
4334}
4335
4336void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4337 const Expr *ThisArg,
4339 if (!FD || Args.empty())
4340 return;
4341 auto GetArgAt = [&](int Idx) -> const Expr * {
4342 if (Idx == LifetimeCaptureByAttr::Global ||
4343 Idx == LifetimeCaptureByAttr::Unknown)
4344 return nullptr;
4345 if (IsMemberFunction && Idx == 0)
4346 return ThisArg;
4347 return Args[Idx - IsMemberFunction];
4348 };
4349 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4350 unsigned ArgIdx) {
4351 if (!Attr)
4352 return;
4353
4354 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4355 for (int CapturingParamIdx : Attr->params()) {
4356 if (CapturingParamIdx == LifetimeCaptureByAttr::Invalid)
4357 continue;
4358 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4359 // initialization codepath.
4360 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4362 continue;
4363 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4364 CapturingEntity CE{Capturing};
4365 // Ensure that 'Captured' outlives the 'Capturing' entity.
4366 checkCaptureByLifetime(*this, CE, Captured);
4367 }
4368 };
4369 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4370 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(),
4371 I + IsMemberFunction);
4372 // Check when the implicit object param is captured.
4373 if (IsMemberFunction) {
4374 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4375 if (!TSI)
4376 return;
4378 for (TypeLoc TL = TSI->getTypeLoc();
4379 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4380 TL = ATL.getModifiedLoc())
4381 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4382 }
4383}
4384
4386 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4387 bool IsMemberFunction, SourceLocation Loc,
4388 SourceRange Range, VariadicCallType CallType) {
4389
4390 if ((ThisArg && ThisArg->isInstantiationDependent()) ||
4391 llvm::any_of(Args, [](const Expr *E) {
4392 return E && E->isInstantiationDependent();
4393 }))
4394 return;
4395
4396 // Printf and scanf checking.
4397 llvm::SmallBitVector CheckedVarArgs;
4398 if (FDecl) {
4399 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4400 // Only create vector if there are format attributes.
4401 CheckedVarArgs.resize(Args.size());
4402 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
4403 CheckedVarArgs);
4404 }
4405
4406 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4407 CheckedVarArgs.resize(Args.size());
4408 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4409 CheckedVarArgs);
4410 }
4411 }
4412
4413 // Refuse POD arguments that weren't caught by the format string
4414 // checks above.
4415 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4416 if (CallType != VariadicCallType::DoesNotApply &&
4417 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4418 unsigned NumParams = Proto ? Proto->getNumParams()
4419 : isa_and_nonnull<FunctionDecl>(FDecl)
4420 ? cast<FunctionDecl>(FDecl)->getNumParams()
4421 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
4422 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4423 : 0;
4424
4425 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4426 // Args[ArgIdx] can be null in malformed code.
4427 if (const Expr *Arg = Args[ArgIdx]) {
4428 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4429 checkVariadicArgument(Arg, CallType);
4430 }
4431 }
4432 }
4433 if (FD)
4434 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4435 if (FDecl || Proto) {
4436 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4437
4438 // Type safety checking.
4439 if (FDecl) {
4440 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4441 CheckArgumentWithTypeTag(I, Args, Loc);
4442 }
4443 }
4444
4445 // Check that passed arguments match the alignment of original arguments.
4446 // Try to get the missing prototype from the declaration.
4447 if (!Proto && FDecl) {
4448 const auto *FT = FDecl->getFunctionType();
4449 if (isa_and_nonnull<FunctionProtoType>(FT))
4450 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4451 }
4452 if (Proto) {
4453 // For variadic functions, we may have more args than parameters.
4454 // For some K&R functions, we may have less args than parameters.
4455 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4456 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4457 bool IsScalableArg = false;
4458 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4459 // Args[ArgIdx] can be null in malformed code.
4460 if (const Expr *Arg = Args[ArgIdx]) {
4461 if (Arg->containsErrors())
4462 continue;
4463
4464 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4465 FDecl->hasLinkage() &&
4466 FDecl->getFormalLinkage() != Linkage::Internal &&
4468 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
4469
4470 QualType ParamTy = Proto->getParamType(ArgIdx);
4471 if (ParamTy->isSizelessVectorType())
4472 IsScalableArg = true;
4473 QualType ArgTy = Arg->getType();
4474 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4475 ArgTy, ParamTy);
4476 }
4477 }
4478
4479 // If the callee has an AArch64 SME attribute to indicate that it is an
4480 // __arm_streaming function, then the caller requires SME to be available.
4483 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
4484 llvm::StringMap<bool> CallerFeatureMap;
4485 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
4486 if (!CallerFeatureMap.contains("sme"))
4487 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4488 } else if (!Context.getTargetInfo().hasFeature("sme")) {
4489 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4490 }
4491 }
4492
4493 // If the call requires a streaming-mode change and has scalable vector
4494 // arguments or return values, then warn the user that the streaming and
4495 // non-streaming vector lengths may be different.
4496 // When both streaming and non-streaming vector lengths are defined and
4497 // mismatched, produce an error.
4498 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
4499 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4500 (IsScalableArg || IsScalableRet)) {
4501 bool IsCalleeStreaming =
4503 bool IsCalleeStreamingCompatible =
4504 ExtInfo.AArch64SMEAttributes &
4506 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
4507 if (!IsCalleeStreamingCompatible &&
4508 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4509 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4510 const LangOptions &LO = getLangOpts();
4511 unsigned VL = LO.VScaleMin * 128;
4512 unsigned SVL = LO.VScaleStreamingMin * 128;
4513 bool IsVLMismatch = VL && SVL && VL != SVL;
4514
4515 auto EmitDiag = [&](bool IsArg) {
4516 if (IsVLMismatch) {
4517 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4518 // Emit warning for streaming-compatible callers
4519 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
4520 << IsArg << IsCalleeStreaming << SVL << VL;
4521 else
4522 // Emit error otherwise
4523 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4524 << IsArg << SVL << VL;
4525 } else
4526 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4527 << IsArg;
4528 };
4529
4530 if (IsScalableArg)
4531 EmitDiag(true);
4532 if (IsScalableRet)
4533 EmitDiag(false);
4534 }
4535 }
4536
4537 FunctionType::ArmStateValue CalleeArmZAState =
4539 FunctionType::ArmStateValue CalleeArmZT0State =
4541 if (CalleeArmZAState != FunctionType::ARM_None ||
4542 CalleeArmZT0State != FunctionType::ARM_None) {
4543 bool CallerHasZAState = false;
4544 bool CallerHasZT0State = false;
4545 if (CallerFD) {
4546 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4547 if (Attr && Attr->isNewZA())
4548 CallerHasZAState = true;
4549 if (Attr && Attr->isNewZT0())
4550 CallerHasZT0State = true;
4551 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4552 CallerHasZAState |=
4554 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4556 CallerHasZT0State |=
4558 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4560 }
4561 }
4562
4563 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4564 Diag(Loc, diag::err_sme_za_call_no_za_state);
4565
4566 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4567 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4568
4569 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4570 CalleeArmZT0State != FunctionType::ARM_None) {
4571 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4572 Diag(Loc, diag::note_sme_use_preserves_za);
4573 }
4574 }
4575 }
4576
4577 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4578 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4579 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4580 if (!Arg->isValueDependent()) {
4581 Expr::EvalResult Align;
4582 if (Arg->EvaluateAsInt(Align, Context)) {
4583 const llvm::APSInt &I = Align.Val.getInt();
4584 if (!I.isPowerOf2())
4585 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4586 << Arg->getSourceRange();
4587
4588 if (I > Sema::MaximumAlignment)
4589 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4590 << Arg->getSourceRange() << Sema::MaximumAlignment;
4591 }
4592 }
4593 }
4594
4595 if (FD && FD->isVariadic() && getLangOpts().SYCLIsDevice &&
4597 SYCL().DiagIfDeviceCode(Loc, diag::err_variadic_device_fn)
4598 << diag::OffloadLang::SYCL;
4599
4600 if (FD)
4601 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4602}
4603
4604void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4605 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4606 DiagnoseUseOfDecl(Decl, Loc);
4607 }
4608}
4609
4610void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4612 const FunctionProtoType *Proto,
4613 SourceLocation Loc) {
4614 VariadicCallType CallType = Proto->isVariadic()
4617
4618 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4619 CheckArgAlignment(
4620 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4621 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4622
4623 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4624 Loc, SourceRange(), CallType);
4625}
4626
4628 const FunctionProtoType *Proto) {
4629 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4630 isa<CXXMethodDecl>(FDecl);
4631 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4632 IsMemberOperatorCall;
4633 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4634 TheCall->getCallee());
4635 Expr** Args = TheCall->getArgs();
4636 unsigned NumArgs = TheCall->getNumArgs();
4637
4638 Expr *ImplicitThis = nullptr;
4639 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4640 // If this is a call to a member operator, hide the first
4641 // argument from checkCall.
4642 // FIXME: Our choice of AST representation here is less than ideal.
4643 ImplicitThis = Args[0];
4644 ++Args;
4645 --NumArgs;
4646 } else if (IsMemberFunction && !FDecl->isStatic() &&
4648 ImplicitThis =
4649 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4650
4651 if (ImplicitThis) {
4652 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4653 // used.
4654 QualType ThisType = ImplicitThis->getType();
4655 if (!ThisType->isPointerType()) {
4656 assert(!ThisType->isReferenceType());
4657 ThisType = Context.getPointerType(ThisType);
4658 }
4659
4660 QualType ThisTypeFromDecl = Context.getPointerType(
4661 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4662
4663 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4664 ThisTypeFromDecl);
4665 }
4666
4667 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4668 IsMemberFunction, TheCall->getRParenLoc(),
4669 TheCall->getCallee()->getSourceRange(), CallType);
4670
4671 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4672 // None of the checks below are needed for functions that don't have
4673 // simple names (e.g., C++ conversion functions).
4674 if (!FnInfo)
4675 return false;
4676
4677 // Enforce TCB except for builtin calls, which are always allowed.
4678 if (FDecl->getBuiltinID() == 0)
4679 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4680
4681 CheckAbsoluteValueFunction(TheCall, FDecl);
4682 CheckMaxUnsignedZero(TheCall, FDecl);
4683 CheckInfNaNFunction(TheCall, FDecl);
4684
4685 if (getLangOpts().ObjC)
4686 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4687
4688 unsigned CMId = FDecl->getMemoryFunctionKind();
4689
4690 // Handle memory setting and copying functions.
4691 switch (CMId) {
4692 case 0:
4693 return false;
4694 case Builtin::BIstrlcpy: // fallthrough
4695 case Builtin::BIstrlcat:
4696 CheckStrlcpycatArguments(TheCall, FnInfo);
4697 break;
4698 case Builtin::BIstrncat:
4699 CheckStrncatArguments(TheCall, FnInfo);
4700 break;
4701 case Builtin::BIfree:
4702 CheckFreeArguments(TheCall);
4703 break;
4704 default:
4705 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4706 }
4707
4708 return false;
4709}
4710
4711bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4712 const FunctionProtoType *Proto) {
4713 QualType Ty;
4714 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4715 Ty = V->getType().getNonReferenceType();
4716 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4717 Ty = F->getType().getNonReferenceType();
4718 else
4719 return false;
4720
4721 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4722 !Ty->isFunctionProtoType())
4723 return false;
4724
4725 VariadicCallType CallType;
4726 if (!Proto || !Proto->isVariadic()) {
4728 } else if (Ty->isBlockPointerType()) {
4729 CallType = VariadicCallType::Block;
4730 } else { // Ty->isFunctionPointerType()
4731 CallType = VariadicCallType::Function;
4732 }
4733
4734 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4735 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4736 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4737 TheCall->getCallee()->getSourceRange(), CallType);
4738
4739 return false;
4740}
4741
4742bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4743 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4744 TheCall->getCallee());
4745 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4746 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4747 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4748 TheCall->getCallee()->getSourceRange(), CallType);
4749
4750 return false;
4751}
4752
4753static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4754 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4755 return false;
4756
4757 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4758 switch (Op) {
4759 case AtomicExpr::AO__c11_atomic_init:
4760 case AtomicExpr::AO__opencl_atomic_init:
4761 llvm_unreachable("There is no ordering argument for an init");
4762
4763 case AtomicExpr::AO__c11_atomic_load:
4764 case AtomicExpr::AO__opencl_atomic_load:
4765 case AtomicExpr::AO__hip_atomic_load:
4766 case AtomicExpr::AO__atomic_load_n:
4767 case AtomicExpr::AO__atomic_load:
4768 case AtomicExpr::AO__scoped_atomic_load_n:
4769 case AtomicExpr::AO__scoped_atomic_load:
4770 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4771 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4772
4773 case AtomicExpr::AO__c11_atomic_store:
4774 case AtomicExpr::AO__opencl_atomic_store:
4775 case AtomicExpr::AO__hip_atomic_store:
4776 case AtomicExpr::AO__atomic_store:
4777 case AtomicExpr::AO__atomic_store_n:
4778 case AtomicExpr::AO__scoped_atomic_store:
4779 case AtomicExpr::AO__scoped_atomic_store_n:
4780 case AtomicExpr::AO__atomic_clear:
4781 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4782 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4783 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4784
4785 default:
4786 return true;
4787 }
4788}
4789
4790ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4792 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4793 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4794 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4795 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4796 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4797 Op);
4798}
4799
4800/// Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_*
4801/// equivalents. Provide a fixit when the scope is a compile-time constant and
4802/// there is a direct mapping from the HIP builtin to a Clang builtin. The
4803/// compare_exchange builtins differ in how they accept the desired value, so
4804/// only a warning (without a fixit) is emitted for those.
4806 MultiExprArg Args,
4808 StringRef OldName;
4809 StringRef NewName;
4810 bool CanFixIt;
4811
4812 switch (Op) {
4813#define HIP_ATOMIC_FIXABLE(hip, scoped) \
4814 case AtomicExpr::AO__hip_atomic_##hip: \
4815 OldName = "__hip_atomic_" #hip; \
4816 NewName = "__scoped_atomic_" #scoped; \
4817 CanFixIt = true; \
4818 break;
4819 HIP_ATOMIC_FIXABLE(load, load_n)
4820 HIP_ATOMIC_FIXABLE(store, store_n)
4821 HIP_ATOMIC_FIXABLE(exchange, exchange_n)
4822 HIP_ATOMIC_FIXABLE(fetch_add, fetch_add)
4823 HIP_ATOMIC_FIXABLE(fetch_sub, fetch_sub)
4824 HIP_ATOMIC_FIXABLE(fetch_and, fetch_and)
4825 HIP_ATOMIC_FIXABLE(fetch_or, fetch_or)
4826 HIP_ATOMIC_FIXABLE(fetch_xor, fetch_xor)
4827 HIP_ATOMIC_FIXABLE(fetch_min, fetch_min)
4828 HIP_ATOMIC_FIXABLE(fetch_max, fetch_max)
4829#undef HIP_ATOMIC_FIXABLE
4830 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4831 OldName = "__hip_atomic_compare_exchange_weak";
4832 NewName = "__scoped_atomic_compare_exchange";
4833 CanFixIt = false;
4834 break;
4835 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4836 OldName = "__hip_atomic_compare_exchange_strong";
4837 NewName = "__scoped_atomic_compare_exchange";
4838 CanFixIt = false;
4839 break;
4840 default:
4841 llvm_unreachable("unhandled HIP atomic op");
4842 }
4843
4844 auto DB = S.Diag(ExprRange.getBegin(), diag::warn_hip_deprecated_builtin)
4845 << OldName << NewName;
4846 if (!CanFixIt)
4847 return;
4848
4849 DB << FixItHint::CreateReplacement(ExprRange, NewName);
4850
4851 Expr *Scope = Args[Args.size() - 1];
4852 std::optional<llvm::APSInt> ScopeVal =
4853 Scope->getIntegerConstantExpr(S.Context);
4854 if (!ScopeVal)
4855 return;
4856
4857 StringRef ScopeName;
4858 switch (ScopeVal->getZExtValue()) {
4860 ScopeName = "__MEMORY_SCOPE_SINGLE";
4861 break;
4863 ScopeName = "__MEMORY_SCOPE_WVFRNT";
4864 break;
4866 ScopeName = "__MEMORY_SCOPE_WRKGRP";
4867 break;
4869 ScopeName = "__MEMORY_SCOPE_DEVICE";
4870 break;
4872 ScopeName = "__MEMORY_SCOPE_SYSTEM";
4873 break;
4875 ScopeName = "__MEMORY_SCOPE_CLUSTR";
4876 break;
4877 default:
4878 return;
4879 }
4880
4882 CharSourceRange::getTokenRange(Scope->getSourceRange()), ScopeName);
4883}
4884
4886 SourceLocation RParenLoc, MultiExprArg Args,
4888 AtomicArgumentOrder ArgOrder) {
4889 // All the non-OpenCL operations take one of the following forms.
4890 // The OpenCL operations take the __c11 forms with one extra argument for
4891 // synchronization scope.
4892 enum {
4893 // C __c11_atomic_init(A *, C)
4894 Init,
4895
4896 // C __c11_atomic_load(A *, int)
4897 Load,
4898
4899 // void __atomic_load(A *, CP, int)
4900 LoadCopy,
4901
4902 // void __atomic_store(A *, CP, int)
4903 Copy,
4904
4905 // C __c11_atomic_add(A *, M, int)
4906 Arithmetic,
4907
4908 // C __atomic_exchange_n(A *, CP, int)
4909 Xchg,
4910
4911 // void __atomic_exchange(A *, C *, CP, int)
4912 GNUXchg,
4913
4914 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4915 C11CmpXchg,
4916
4917 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4918 GNUCmpXchg,
4919
4920 // bool __atomic_test_and_set(A *, int)
4921 TestAndSetByte,
4922
4923 // void __atomic_clear(A *, int)
4924 ClearByte,
4925 } Form = Init;
4926
4927 const unsigned NumForm = ClearByte + 1;
4928 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4929 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4930 // where:
4931 // C is an appropriate type,
4932 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4933 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4934 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4935 // the int parameters are for orderings.
4936
4937 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4938 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4939 "need to update code for modified forms");
4940 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4941 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4942 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4943 "need to update code for modified C11 atomics");
4944 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4945 Op <= AtomicExpr::AO__opencl_atomic_store;
4946 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4947 Op <= AtomicExpr::AO__hip_atomic_store;
4948 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4949 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4950 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4951 Op <= AtomicExpr::AO__c11_atomic_store) ||
4952 IsOpenCL;
4953 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4954 Op == AtomicExpr::AO__atomic_store_n ||
4955 Op == AtomicExpr::AO__atomic_exchange_n ||
4956 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4957 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4958 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4959 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4960 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4961 // Bit mask for extra allowed value types other than integers for atomic
4962 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4963 // allow floating point.
4964 enum ArithOpExtraValueType {
4965 AOEVT_None = 0,
4966 AOEVT_Pointer = 1,
4967 AOEVT_FP = 2,
4968 AOEVT_Int = 4,
4969 };
4970 unsigned ArithAllows = AOEVT_None;
4971
4972 switch (Op) {
4973 case AtomicExpr::AO__c11_atomic_init:
4974 case AtomicExpr::AO__opencl_atomic_init:
4975 Form = Init;
4976 break;
4977
4978 case AtomicExpr::AO__c11_atomic_load:
4979 case AtomicExpr::AO__opencl_atomic_load:
4980 case AtomicExpr::AO__hip_atomic_load:
4981 case AtomicExpr::AO__atomic_load_n:
4982 case AtomicExpr::AO__scoped_atomic_load_n:
4983 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4984 Form = Load;
4985 break;
4986
4987 case AtomicExpr::AO__atomic_load:
4988 case AtomicExpr::AO__scoped_atomic_load:
4989 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4990 Form = LoadCopy;
4991 break;
4992
4993 case AtomicExpr::AO__c11_atomic_store:
4994 case AtomicExpr::AO__opencl_atomic_store:
4995 case AtomicExpr::AO__hip_atomic_store:
4996 case AtomicExpr::AO__atomic_store:
4997 case AtomicExpr::AO__atomic_store_n:
4998 case AtomicExpr::AO__scoped_atomic_store:
4999 case AtomicExpr::AO__scoped_atomic_store_n:
5000 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5001 Form = Copy;
5002 break;
5003 case AtomicExpr::AO__atomic_fetch_add:
5004 case AtomicExpr::AO__atomic_fetch_sub:
5005 case AtomicExpr::AO__atomic_add_fetch:
5006 case AtomicExpr::AO__atomic_sub_fetch:
5007 case AtomicExpr::AO__scoped_atomic_fetch_add:
5008 case AtomicExpr::AO__scoped_atomic_fetch_sub:
5009 case AtomicExpr::AO__scoped_atomic_add_fetch:
5010 case AtomicExpr::AO__scoped_atomic_sub_fetch:
5011 case AtomicExpr::AO__c11_atomic_fetch_add:
5012 case AtomicExpr::AO__c11_atomic_fetch_sub:
5013 case AtomicExpr::AO__opencl_atomic_fetch_add:
5014 case AtomicExpr::AO__opencl_atomic_fetch_sub:
5015 case AtomicExpr::AO__hip_atomic_fetch_add:
5016 case AtomicExpr::AO__hip_atomic_fetch_sub:
5017 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5018 Form = Arithmetic;
5019 break;
5020 case AtomicExpr::AO__atomic_fetch_fminimum:
5021 case AtomicExpr::AO__atomic_fetch_fmaximum:
5022 case AtomicExpr::AO__atomic_fetch_fminimum_num:
5023 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
5024 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
5025 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
5026 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
5027 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
5028 ArithAllows = AOEVT_FP;
5029 Form = Arithmetic;
5030 break;
5031 case AtomicExpr::AO__atomic_fetch_max:
5032 case AtomicExpr::AO__atomic_fetch_min:
5033 case AtomicExpr::AO__atomic_max_fetch:
5034 case AtomicExpr::AO__atomic_min_fetch:
5035 case AtomicExpr::AO__scoped_atomic_fetch_max:
5036 case AtomicExpr::AO__scoped_atomic_fetch_min:
5037 case AtomicExpr::AO__scoped_atomic_max_fetch:
5038 case AtomicExpr::AO__scoped_atomic_min_fetch:
5039 case AtomicExpr::AO__c11_atomic_fetch_max:
5040 case AtomicExpr::AO__c11_atomic_fetch_min:
5041 case AtomicExpr::AO__opencl_atomic_fetch_max:
5042 case AtomicExpr::AO__opencl_atomic_fetch_min:
5043 case AtomicExpr::AO__hip_atomic_fetch_max:
5044 case AtomicExpr::AO__hip_atomic_fetch_min:
5045 ArithAllows = AOEVT_Int | AOEVT_FP;
5046 Form = Arithmetic;
5047 break;
5048 case AtomicExpr::AO__c11_atomic_fetch_and:
5049 case AtomicExpr::AO__c11_atomic_fetch_or:
5050 case AtomicExpr::AO__c11_atomic_fetch_xor:
5051 case AtomicExpr::AO__hip_atomic_fetch_and:
5052 case AtomicExpr::AO__hip_atomic_fetch_or:
5053 case AtomicExpr::AO__hip_atomic_fetch_xor:
5054 case AtomicExpr::AO__c11_atomic_fetch_nand:
5055 case AtomicExpr::AO__opencl_atomic_fetch_and:
5056 case AtomicExpr::AO__opencl_atomic_fetch_or:
5057 case AtomicExpr::AO__opencl_atomic_fetch_xor:
5058 case AtomicExpr::AO__atomic_fetch_and:
5059 case AtomicExpr::AO__atomic_fetch_or:
5060 case AtomicExpr::AO__atomic_fetch_xor:
5061 case AtomicExpr::AO__atomic_fetch_nand:
5062 case AtomicExpr::AO__atomic_and_fetch:
5063 case AtomicExpr::AO__atomic_or_fetch:
5064 case AtomicExpr::AO__atomic_xor_fetch:
5065 case AtomicExpr::AO__atomic_nand_fetch:
5066 case AtomicExpr::AO__atomic_fetch_uinc:
5067 case AtomicExpr::AO__atomic_fetch_udec:
5068 case AtomicExpr::AO__scoped_atomic_fetch_and:
5069 case AtomicExpr::AO__scoped_atomic_fetch_or:
5070 case AtomicExpr::AO__scoped_atomic_fetch_xor:
5071 case AtomicExpr::AO__scoped_atomic_fetch_nand:
5072 case AtomicExpr::AO__scoped_atomic_and_fetch:
5073 case AtomicExpr::AO__scoped_atomic_or_fetch:
5074 case AtomicExpr::AO__scoped_atomic_xor_fetch:
5075 case AtomicExpr::AO__scoped_atomic_nand_fetch:
5076 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
5077 case AtomicExpr::AO__scoped_atomic_fetch_udec:
5078 Form = Arithmetic;
5079 break;
5080
5081 case AtomicExpr::AO__c11_atomic_exchange:
5082 case AtomicExpr::AO__hip_atomic_exchange:
5083 case AtomicExpr::AO__opencl_atomic_exchange:
5084 case AtomicExpr::AO__atomic_exchange_n:
5085 case AtomicExpr::AO__scoped_atomic_exchange_n:
5086 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5087 Form = Xchg;
5088 break;
5089
5090 case AtomicExpr::AO__atomic_exchange:
5091 case AtomicExpr::AO__scoped_atomic_exchange:
5092 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5093 Form = GNUXchg;
5094 break;
5095
5096 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5097 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5098 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5099 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5100 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5101 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5102 Form = C11CmpXchg;
5103 break;
5104
5105 case AtomicExpr::AO__atomic_compare_exchange:
5106 case AtomicExpr::AO__atomic_compare_exchange_n:
5107 case AtomicExpr::AO__scoped_atomic_compare_exchange:
5108 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
5109 ArithAllows = AOEVT_Pointer;
5110 Form = GNUCmpXchg;
5111 break;
5112
5113 case AtomicExpr::AO__atomic_test_and_set:
5114 Form = TestAndSetByte;
5115 break;
5116
5117 case AtomicExpr::AO__atomic_clear:
5118 Form = ClearByte;
5119 break;
5120 }
5121
5122 unsigned AdjustedNumArgs = NumArgs[Form];
5123 if ((IsOpenCL || IsHIP || IsScoped) &&
5124 Op != AtomicExpr::AO__opencl_atomic_init)
5125 ++AdjustedNumArgs;
5126 // Check we have the right number of arguments.
5127 if (Args.size() < AdjustedNumArgs) {
5128 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5129 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5130 << /*is non object*/ 0 << ExprRange;
5131 return ExprError();
5132 } else if (Args.size() > AdjustedNumArgs) {
5133 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5134 diag::err_typecheck_call_too_many_args)
5135 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5136 << /*is non object*/ 0 << ExprRange;
5137 return ExprError();
5138 }
5139
5140 // Inspect the first argument of the atomic operation.
5141 Expr *Ptr = Args[0];
5143 if (ConvertedPtr.isInvalid())
5144 return ExprError();
5145
5146 Ptr = ConvertedPtr.get();
5147 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5148 if (!pointerType) {
5149 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5150 << Ptr->getType() << 0 << Ptr->getSourceRange();
5151 return ExprError();
5152 }
5153
5154 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5155 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5156 QualType ValType = AtomTy; // 'C'
5157 if (IsC11) {
5158 if (!AtomTy->isAtomicType()) {
5159 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5160 << Ptr->getType() << Ptr->getSourceRange();
5161 return ExprError();
5162 }
5163 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5165 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5166 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5167 << Ptr->getSourceRange();
5168 return ExprError();
5169 }
5170 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5171 } else if (Form != Load && Form != LoadCopy) {
5172 if (ValType.isConstQualified()) {
5173 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5174 << Ptr->getType() << Ptr->getSourceRange();
5175 return ExprError();
5176 }
5177 }
5178
5179 if (Form != TestAndSetByte && Form != ClearByte) {
5180 // Pointer to object of size zero is not allowed.
5181 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
5182 diag::err_incomplete_type))
5183 return ExprError();
5184
5185 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
5186 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5187 << Ptr->getType() << 1 << Ptr->getSourceRange();
5188 return ExprError();
5189 }
5190 } else {
5191 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
5192 // non-const pointer type, including void* and pointers to incomplete
5193 // structs, but only access the first byte.
5194 AtomTy = Context.CharTy;
5195 AtomTy = AtomTy.withCVRQualifiers(
5196 pointerType->getPointeeType().getCVRQualifiers());
5197 QualType PointerQT = Context.getPointerType(AtomTy);
5198 pointerType = PointerQT->getAs<PointerType>();
5199 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
5200 ValType = AtomTy;
5201 }
5202
5203 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
5204 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5205 Diag(ExprRange.getBegin(),
5206 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5207 << 0 << Ptr->getType() << Ptr->getSourceRange();
5208 return ExprError();
5209 }
5210
5211 // For an arithmetic operation, the implied arithmetic must be well-formed.
5212 // For _n operations, the value type must also be a valid atomic type.
5213 if (Form == Arithmetic || IsN) {
5214 // GCC does not enforce these rules for GNU atomics, but we do to help catch
5215 // trivial type errors.
5216 auto IsAllowedValueType = [&](QualType ValType,
5217 unsigned AllowedType) -> bool {
5218 bool IsX87LongDouble =
5219 ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5220 &Context.getTargetInfo().getLongDoubleFormat() ==
5221 &llvm::APFloat::x87DoubleExtended();
5222 if (ValType->isIntegerType())
5223 // Special case: f-prefixed operations (AOEVT_FP exactly) reject
5224 // integers. Explicit AOEVT_Int or other combinations allow integers.
5225 return (AllowedType & AOEVT_Int) || AllowedType != AOEVT_FP;
5226 if (ValType->isPointerType())
5227 return AllowedType & AOEVT_Pointer;
5228 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
5229 return false;
5230 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5231 if (IsX87LongDouble)
5232 return false;
5233 return true;
5234 };
5235 if (!IsAllowedValueType(ValType, ArithAllows)) {
5236 auto DID =
5237 ArithAllows == AOEVT_FP
5238 ? diag::err_atomic_op_needs_atomic_fp
5239 : (ArithAllows & AOEVT_FP
5240 ? (ArithAllows & AOEVT_Pointer
5241 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
5242 : diag::err_atomic_op_needs_atomic_int_or_fp)
5243 : (ArithAllows & AOEVT_Pointer
5244 ? diag::err_atomic_op_needs_atomic_int_or_ptr
5245 : diag::err_atomic_op_needs_atomic_int));
5246 Diag(ExprRange.getBegin(), DID)
5247 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5248 return ExprError();
5249 }
5250 if (IsC11 && ValType->isPointerType() &&
5252 diag::err_incomplete_type)) {
5253 return ExprError();
5254 }
5255 }
5256
5257 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5258 !AtomTy->isScalarType()) {
5259 // For GNU atomics, require a trivially-copyable type. This is not part of
5260 // the GNU atomics specification but we enforce it for consistency with
5261 // other atomics which generally all require a trivially-copyable type. This
5262 // is because atomics just copy bits.
5263 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5264 << Ptr->getType() << Ptr->getSourceRange();
5265 return ExprError();
5266 }
5267
5268 switch (ValType.getObjCLifetime()) {
5271 // okay
5272 break;
5273
5277 // FIXME: Can this happen? By this point, ValType should be known
5278 // to be trivially copyable.
5279 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5280 << ValType << Ptr->getSourceRange();
5281 return ExprError();
5282 }
5283
5284 // All atomic operations have an overload which takes a pointer to a volatile
5285 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
5286 // into the result or the other operands. Similarly atomic_load takes a
5287 // pointer to a const 'A'.
5288 ValType.removeLocalVolatile();
5289 ValType.removeLocalConst();
5290 QualType ResultType = ValType;
5291 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
5292 Form == ClearByte)
5293 ResultType = Context.VoidTy;
5294 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
5295 ResultType = Context.BoolTy;
5296
5297 // The type of a parameter passed 'by value'. In the GNU atomics, such
5298 // arguments are actually passed as pointers.
5299 QualType ByValType = ValType; // 'CP'
5300 bool IsPassedByAddress = false;
5301 if (!IsC11 && !IsHIP && !IsN) {
5302 ByValType = Ptr->getType();
5303 IsPassedByAddress = true;
5304 }
5305
5306 SmallVector<Expr *, 5> APIOrderedArgs;
5307 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5308 APIOrderedArgs.push_back(Args[0]);
5309 switch (Form) {
5310 case Init:
5311 case Load:
5312 APIOrderedArgs.push_back(Args[1]); // Val1/Order
5313 break;
5314 case LoadCopy:
5315 case Copy:
5316 case Arithmetic:
5317 case Xchg:
5318 APIOrderedArgs.push_back(Args[2]); // Val1
5319 APIOrderedArgs.push_back(Args[1]); // Order
5320 break;
5321 case GNUXchg:
5322 APIOrderedArgs.push_back(Args[2]); // Val1
5323 APIOrderedArgs.push_back(Args[3]); // Val2
5324 APIOrderedArgs.push_back(Args[1]); // Order
5325 break;
5326 case C11CmpXchg:
5327 APIOrderedArgs.push_back(Args[2]); // Val1
5328 APIOrderedArgs.push_back(Args[4]); // Val2
5329 APIOrderedArgs.push_back(Args[1]); // Order
5330 APIOrderedArgs.push_back(Args[3]); // OrderFail
5331 break;
5332 case GNUCmpXchg:
5333 APIOrderedArgs.push_back(Args[2]); // Val1
5334 APIOrderedArgs.push_back(Args[4]); // Val2
5335 APIOrderedArgs.push_back(Args[5]); // Weak
5336 APIOrderedArgs.push_back(Args[1]); // Order
5337 APIOrderedArgs.push_back(Args[3]); // OrderFail
5338 break;
5339 case TestAndSetByte:
5340 case ClearByte:
5341 APIOrderedArgs.push_back(Args[1]); // Order
5342 break;
5343 }
5344 } else
5345 APIOrderedArgs.append(Args.begin(), Args.end());
5346
5347 // The first argument's non-CV pointer type is used to deduce the type of
5348 // subsequent arguments, except for:
5349 // - weak flag (always converted to bool)
5350 // - memory order (always converted to int)
5351 // - scope (always converted to int)
5352 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5353 QualType Ty;
5354 if (i < NumVals[Form] + 1) {
5355 switch (i) {
5356 case 0:
5357 // The first argument is always a pointer. It has a fixed type.
5358 // It is always dereferenced, a nullptr is undefined.
5359 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5360 // Nothing else to do: we already know all we want about this pointer.
5361 continue;
5362 case 1:
5363 // The second argument is the non-atomic operand. For arithmetic, this
5364 // is always passed by value, and for a compare_exchange it is always
5365 // passed by address. For the rest, GNU uses by-address and C11 uses
5366 // by-value.
5367 assert(Form != Load);
5368 if (Form == Arithmetic && ValType->isPointerType())
5369 Ty = Context.getPointerDiffType();
5370 else if (Form == Init || Form == Arithmetic)
5371 Ty = ValType;
5372 else if (Form == Copy || Form == Xchg) {
5373 if (IsPassedByAddress) {
5374 // The value pointer is always dereferenced, a nullptr is undefined.
5375 CheckNonNullArgument(*this, APIOrderedArgs[i],
5376 ExprRange.getBegin());
5377 }
5378 Ty = ByValType;
5379 } else {
5380 Expr *ValArg = APIOrderedArgs[i];
5381 // The value pointer is always dereferenced, a nullptr is undefined.
5382 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5384 // Keep address space of non-atomic pointer type.
5385 if (const PointerType *PtrTy =
5386 ValArg->getType()->getAs<PointerType>()) {
5387 AS = PtrTy->getPointeeType().getAddressSpace();
5388 }
5389 Ty = Context.getPointerType(
5390 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5391 }
5392 break;
5393 case 2:
5394 // The third argument to compare_exchange / GNU exchange is the desired
5395 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5396 if (IsPassedByAddress)
5397 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5398 Ty = ByValType;
5399 break;
5400 case 3:
5401 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5402 Ty = Context.BoolTy;
5403 break;
5404 }
5405 } else {
5406 // The order(s) and scope are always converted to int.
5407 Ty = Context.IntTy;
5408 }
5409
5410 InitializedEntity Entity =
5412 ExprResult Arg = APIOrderedArgs[i];
5413 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5414 if (Arg.isInvalid())
5415 return true;
5416 APIOrderedArgs[i] = Arg.get();
5417 }
5418
5419 // Permute the arguments into a 'consistent' order.
5420 SmallVector<Expr*, 5> SubExprs;
5421 SubExprs.push_back(Ptr);
5422 switch (Form) {
5423 case Init:
5424 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5425 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5426 break;
5427 case Load:
5428 case TestAndSetByte:
5429 case ClearByte:
5430 SubExprs.push_back(APIOrderedArgs[1]); // Order
5431 break;
5432 case LoadCopy:
5433 case Copy:
5434 case Arithmetic:
5435 case Xchg:
5436 SubExprs.push_back(APIOrderedArgs[2]); // Order
5437 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5438 break;
5439 case GNUXchg:
5440 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5441 SubExprs.push_back(APIOrderedArgs[3]); // Order
5442 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5443 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5444 break;
5445 case C11CmpXchg:
5446 SubExprs.push_back(APIOrderedArgs[3]); // Order
5447 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5448 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5449 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5450 break;
5451 case GNUCmpXchg:
5452 SubExprs.push_back(APIOrderedArgs[4]); // Order
5453 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5454 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5455 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5456 SubExprs.push_back(APIOrderedArgs[3]); // Weak
5457 break;
5458 }
5459
5460 // If the memory orders are constants, check they are valid.
5461 if (SubExprs.size() >= 2 && Form != Init) {
5462 std::optional<llvm::APSInt> Success =
5463 SubExprs[1]->getIntegerConstantExpr(Context);
5464 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
5465 Diag(SubExprs[1]->getBeginLoc(),
5466 diag::warn_atomic_op_has_invalid_memory_order)
5467 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5468 << SubExprs[1]->getSourceRange();
5469 }
5470 if (SubExprs.size() >= 5) {
5471 if (std::optional<llvm::APSInt> Failure =
5472 SubExprs[3]->getIntegerConstantExpr(Context)) {
5473 if (!llvm::is_contained(
5474 {llvm::AtomicOrderingCABI::relaxed,
5475 llvm::AtomicOrderingCABI::consume,
5476 llvm::AtomicOrderingCABI::acquire,
5477 llvm::AtomicOrderingCABI::seq_cst},
5478 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5479 Diag(SubExprs[3]->getBeginLoc(),
5480 diag::warn_atomic_op_has_invalid_memory_order)
5481 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5482 }
5483 }
5484 }
5485 }
5486
5487 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5488 auto *Scope = Args[Args.size() - 1];
5489 if (std::optional<llvm::APSInt> Result =
5490 Scope->getIntegerConstantExpr(Context)) {
5491 if (!ScopeModel->isValid(Result->getZExtValue()))
5492 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
5493 << Scope->getSourceRange();
5494 }
5495 SubExprs.push_back(Scope);
5496 }
5497
5498 if (IsHIP)
5499 DiagnoseDeprecatedHIPAtomic(*this, ExprRange, Args, Op);
5500
5501 AtomicExpr *AE = new (Context)
5502 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5503
5504 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5505 Op == AtomicExpr::AO__c11_atomic_store ||
5506 Op == AtomicExpr::AO__opencl_atomic_load ||
5507 Op == AtomicExpr::AO__hip_atomic_load ||
5508 Op == AtomicExpr::AO__opencl_atomic_store ||
5509 Op == AtomicExpr::AO__hip_atomic_store) &&
5510 Context.AtomicUsesUnsupportedLibcall(AE))
5511 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5512 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5513 Op == AtomicExpr::AO__opencl_atomic_load ||
5514 Op == AtomicExpr::AO__hip_atomic_load)
5515 ? 0
5516 : 1);
5517
5518 if (ValType->isBitIntType()) {
5519 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5520 return ExprError();
5521 }
5522
5523 return AE;
5524}
5525
5526/// checkBuiltinArgument - Given a call to a builtin function, perform
5527/// normal type-checking on the given argument, updating the call in
5528/// place. This is useful when a builtin function requires custom
5529/// type-checking for some of its arguments but not necessarily all of
5530/// them.
5531///
5532/// Returns true on error.
5533static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5534 FunctionDecl *Fn = E->getDirectCallee();
5535 assert(Fn && "builtin call without direct callee!");
5536
5537 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5538 InitializedEntity Entity =
5540
5541 ExprResult Arg = E->getArg(ArgIndex);
5542 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5543 if (Arg.isInvalid())
5544 return true;
5545
5546 E->setArg(ArgIndex, Arg.get());
5547 return false;
5548}
5549
5550ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5551 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5552 Expr *Callee = TheCall->getCallee();
5553 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5554 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5555
5556 // Ensure that we have at least one argument to do type inference from.
5557 if (TheCall->getNumArgs() < 1) {
5558 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5559 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5560 << Callee->getSourceRange();
5561 return ExprError();
5562 }
5563
5564 // Inspect the first argument of the atomic builtin. This should always be
5565 // a pointer type, whose element is an integral scalar or pointer type.
5566 // Because it is a pointer type, we don't have to worry about any implicit
5567 // casts here.
5568 // FIXME: We don't allow floating point scalars as input.
5569 Expr *FirstArg = TheCall->getArg(0);
5570 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5571 if (FirstArgResult.isInvalid())
5572 return ExprError();
5573 FirstArg = FirstArgResult.get();
5574 TheCall->setArg(0, FirstArg);
5575
5576 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5577 if (!pointerType) {
5578 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5579 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5580 return ExprError();
5581 }
5582
5583 QualType ValType = pointerType->getPointeeType();
5584 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5585 !ValType->isBlockPointerType()) {
5586 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5587 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5588 return ExprError();
5589 }
5590 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5591 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5592 Diag(FirstArg->getBeginLoc(),
5593 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5594 << 1 << ValType << FirstArg->getSourceRange();
5595 return ExprError();
5596 }
5597
5598 if (ValType.isConstQualified()) {
5599 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5600 << FirstArg->getType() << FirstArg->getSourceRange();
5601 return ExprError();
5602 }
5603
5604 switch (ValType.getObjCLifetime()) {
5607 // okay
5608 break;
5609
5613 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5614 << ValType << FirstArg->getSourceRange();
5615 return ExprError();
5616 }
5617
5618 // Strip any qualifiers off ValType.
5619 ValType = ValType.getUnqualifiedType();
5620
5621 // The majority of builtins return a value, but a few have special return
5622 // types, so allow them to override appropriately below.
5623 QualType ResultType = ValType;
5624
5625 // We need to figure out which concrete builtin this maps onto. For example,
5626 // __sync_fetch_and_add with a 2 byte object turns into
5627 // __sync_fetch_and_add_2.
5628#define BUILTIN_ROW(x) \
5629 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5630 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5631
5632 static const unsigned BuiltinIndices[][5] = {
5633 BUILTIN_ROW(__sync_fetch_and_add),
5634 BUILTIN_ROW(__sync_fetch_and_sub),
5635 BUILTIN_ROW(__sync_fetch_and_or),
5636 BUILTIN_ROW(__sync_fetch_and_and),
5637 BUILTIN_ROW(__sync_fetch_and_xor),
5638 BUILTIN_ROW(__sync_fetch_and_nand),
5639
5640 BUILTIN_ROW(__sync_add_and_fetch),
5641 BUILTIN_ROW(__sync_sub_and_fetch),
5642 BUILTIN_ROW(__sync_and_and_fetch),
5643 BUILTIN_ROW(__sync_or_and_fetch),
5644 BUILTIN_ROW(__sync_xor_and_fetch),
5645 BUILTIN_ROW(__sync_nand_and_fetch),
5646
5647 BUILTIN_ROW(__sync_val_compare_and_swap),
5648 BUILTIN_ROW(__sync_bool_compare_and_swap),
5649 BUILTIN_ROW(__sync_lock_test_and_set),
5650 BUILTIN_ROW(__sync_lock_release),
5651 BUILTIN_ROW(__sync_swap)
5652 };
5653#undef BUILTIN_ROW
5654
5655 // Determine the index of the size.
5656 unsigned SizeIndex;
5657 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5658 case 1: SizeIndex = 0; break;
5659 case 2: SizeIndex = 1; break;
5660 case 4: SizeIndex = 2; break;
5661 case 8: SizeIndex = 3; break;
5662 case 16: SizeIndex = 4; break;
5663 default:
5664 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5665 << FirstArg->getType() << FirstArg->getSourceRange();
5666 return ExprError();
5667 }
5668
5669 // Each of these builtins has one pointer argument, followed by some number of
5670 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5671 // that we ignore. Find out which row of BuiltinIndices to read from as well
5672 // as the number of fixed args.
5673 unsigned BuiltinID = FDecl->getBuiltinID();
5674 unsigned BuiltinIndex, NumFixed = 1;
5675 bool WarnAboutSemanticsChange = false;
5676 switch (BuiltinID) {
5677 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5678 case Builtin::BI__sync_fetch_and_add:
5679 case Builtin::BI__sync_fetch_and_add_1:
5680 case Builtin::BI__sync_fetch_and_add_2:
5681 case Builtin::BI__sync_fetch_and_add_4:
5682 case Builtin::BI__sync_fetch_and_add_8:
5683 case Builtin::BI__sync_fetch_and_add_16:
5684 BuiltinIndex = 0;
5685 break;
5686
5687 case Builtin::BI__sync_fetch_and_sub:
5688 case Builtin::BI__sync_fetch_and_sub_1:
5689 case Builtin::BI__sync_fetch_and_sub_2:
5690 case Builtin::BI__sync_fetch_and_sub_4:
5691 case Builtin::BI__sync_fetch_and_sub_8:
5692 case Builtin::BI__sync_fetch_and_sub_16:
5693 BuiltinIndex = 1;
5694 break;
5695
5696 case Builtin::BI__sync_fetch_and_or:
5697 case Builtin::BI__sync_fetch_and_or_1:
5698 case Builtin::BI__sync_fetch_and_or_2:
5699 case Builtin::BI__sync_fetch_and_or_4:
5700 case Builtin::BI__sync_fetch_and_or_8:
5701 case Builtin::BI__sync_fetch_and_or_16:
5702 BuiltinIndex = 2;
5703 break;
5704
5705 case Builtin::BI__sync_fetch_and_and:
5706 case Builtin::BI__sync_fetch_and_and_1:
5707 case Builtin::BI__sync_fetch_and_and_2:
5708 case Builtin::BI__sync_fetch_and_and_4:
5709 case Builtin::BI__sync_fetch_and_and_8:
5710 case Builtin::BI__sync_fetch_and_and_16:
5711 BuiltinIndex = 3;
5712 break;
5713
5714 case Builtin::BI__sync_fetch_and_xor:
5715 case Builtin::BI__sync_fetch_and_xor_1:
5716 case Builtin::BI__sync_fetch_and_xor_2:
5717 case Builtin::BI__sync_fetch_and_xor_4:
5718 case Builtin::BI__sync_fetch_and_xor_8:
5719 case Builtin::BI__sync_fetch_and_xor_16:
5720 BuiltinIndex = 4;
5721 break;
5722
5723 case Builtin::BI__sync_fetch_and_nand:
5724 case Builtin::BI__sync_fetch_and_nand_1:
5725 case Builtin::BI__sync_fetch_and_nand_2:
5726 case Builtin::BI__sync_fetch_and_nand_4:
5727 case Builtin::BI__sync_fetch_and_nand_8:
5728 case Builtin::BI__sync_fetch_and_nand_16:
5729 BuiltinIndex = 5;
5730 WarnAboutSemanticsChange = true;
5731 break;
5732
5733 case Builtin::BI__sync_add_and_fetch:
5734 case Builtin::BI__sync_add_and_fetch_1:
5735 case Builtin::BI__sync_add_and_fetch_2:
5736 case Builtin::BI__sync_add_and_fetch_4:
5737 case Builtin::BI__sync_add_and_fetch_8:
5738 case Builtin::BI__sync_add_and_fetch_16:
5739 BuiltinIndex = 6;
5740 break;
5741
5742 case Builtin::BI__sync_sub_and_fetch:
5743 case Builtin::BI__sync_sub_and_fetch_1:
5744 case Builtin::BI__sync_sub_and_fetch_2:
5745 case Builtin::BI__sync_sub_and_fetch_4:
5746 case Builtin::BI__sync_sub_and_fetch_8:
5747 case Builtin::BI__sync_sub_and_fetch_16:
5748 BuiltinIndex = 7;
5749 break;
5750
5751 case Builtin::BI__sync_and_and_fetch:
5752 case Builtin::BI__sync_and_and_fetch_1:
5753 case Builtin::BI__sync_and_and_fetch_2:
5754 case Builtin::BI__sync_and_and_fetch_4:
5755 case Builtin::BI__sync_and_and_fetch_8:
5756 case Builtin::BI__sync_and_and_fetch_16:
5757 BuiltinIndex = 8;
5758 break;
5759
5760 case Builtin::BI__sync_or_and_fetch:
5761 case Builtin::BI__sync_or_and_fetch_1:
5762 case Builtin::BI__sync_or_and_fetch_2:
5763 case Builtin::BI__sync_or_and_fetch_4:
5764 case Builtin::BI__sync_or_and_fetch_8:
5765 case Builtin::BI__sync_or_and_fetch_16:
5766 BuiltinIndex = 9;
5767 break;
5768
5769 case Builtin::BI__sync_xor_and_fetch:
5770 case Builtin::BI__sync_xor_and_fetch_1:
5771 case Builtin::BI__sync_xor_and_fetch_2:
5772 case Builtin::BI__sync_xor_and_fetch_4:
5773 case Builtin::BI__sync_xor_and_fetch_8:
5774 case Builtin::BI__sync_xor_and_fetch_16:
5775 BuiltinIndex = 10;
5776 break;
5777
5778 case Builtin::BI__sync_nand_and_fetch:
5779 case Builtin::BI__sync_nand_and_fetch_1:
5780 case Builtin::BI__sync_nand_and_fetch_2:
5781 case Builtin::BI__sync_nand_and_fetch_4:
5782 case Builtin::BI__sync_nand_and_fetch_8:
5783 case Builtin::BI__sync_nand_and_fetch_16:
5784 BuiltinIndex = 11;
5785 WarnAboutSemanticsChange = true;
5786 break;
5787
5788 case Builtin::BI__sync_val_compare_and_swap:
5789 case Builtin::BI__sync_val_compare_and_swap_1:
5790 case Builtin::BI__sync_val_compare_and_swap_2:
5791 case Builtin::BI__sync_val_compare_and_swap_4:
5792 case Builtin::BI__sync_val_compare_and_swap_8:
5793 case Builtin::BI__sync_val_compare_and_swap_16:
5794 BuiltinIndex = 12;
5795 NumFixed = 2;
5796 break;
5797
5798 case Builtin::BI__sync_bool_compare_and_swap:
5799 case Builtin::BI__sync_bool_compare_and_swap_1:
5800 case Builtin::BI__sync_bool_compare_and_swap_2:
5801 case Builtin::BI__sync_bool_compare_and_swap_4:
5802 case Builtin::BI__sync_bool_compare_and_swap_8:
5803 case Builtin::BI__sync_bool_compare_and_swap_16:
5804 BuiltinIndex = 13;
5805 NumFixed = 2;
5806 ResultType = Context.BoolTy;
5807 break;
5808
5809 case Builtin::BI__sync_lock_test_and_set:
5810 case Builtin::BI__sync_lock_test_and_set_1:
5811 case Builtin::BI__sync_lock_test_and_set_2:
5812 case Builtin::BI__sync_lock_test_and_set_4:
5813 case Builtin::BI__sync_lock_test_and_set_8:
5814 case Builtin::BI__sync_lock_test_and_set_16:
5815 BuiltinIndex = 14;
5816 break;
5817
5818 case Builtin::BI__sync_lock_release:
5819 case Builtin::BI__sync_lock_release_1:
5820 case Builtin::BI__sync_lock_release_2:
5821 case Builtin::BI__sync_lock_release_4:
5822 case Builtin::BI__sync_lock_release_8:
5823 case Builtin::BI__sync_lock_release_16:
5824 BuiltinIndex = 15;
5825 NumFixed = 0;
5826 ResultType = Context.VoidTy;
5827 break;
5828
5829 case Builtin::BI__sync_swap:
5830 case Builtin::BI__sync_swap_1:
5831 case Builtin::BI__sync_swap_2:
5832 case Builtin::BI__sync_swap_4:
5833 case Builtin::BI__sync_swap_8:
5834 case Builtin::BI__sync_swap_16:
5835 BuiltinIndex = 16;
5836 break;
5837 }
5838
5839 // Now that we know how many fixed arguments we expect, first check that we
5840 // have at least that many.
5841 if (TheCall->getNumArgs() < 1+NumFixed) {
5842 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5843 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5844 << Callee->getSourceRange();
5845 return ExprError();
5846 }
5847
5848 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5849 << Callee->getSourceRange();
5850
5851 if (WarnAboutSemanticsChange) {
5852 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5853 << Callee->getSourceRange();
5854 }
5855
5856 // Get the decl for the concrete builtin from this, we can tell what the
5857 // concrete integer type we should convert to is.
5858 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5859 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5860 FunctionDecl *NewBuiltinDecl;
5861 if (NewBuiltinID == BuiltinID)
5862 NewBuiltinDecl = FDecl;
5863 else {
5864 // Perform builtin lookup to avoid redeclaring it.
5865 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5866 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5867 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5868 assert(Res.getFoundDecl());
5869 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5870 if (!NewBuiltinDecl)
5871 return ExprError();
5872 }
5873
5874 // The first argument --- the pointer --- has a fixed type; we
5875 // deduce the types of the rest of the arguments accordingly. Walk
5876 // the remaining arguments, converting them to the deduced value type.
5877 for (unsigned i = 0; i != NumFixed; ++i) {
5878 ExprResult Arg = TheCall->getArg(i+1);
5879
5880 // GCC does an implicit conversion to the pointer or integer ValType. This
5881 // can fail in some cases (1i -> int**), check for this error case now.
5882 // Initialize the argument.
5883 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5884 ValType, /*consume*/ false);
5885 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5886 if (Arg.isInvalid())
5887 return ExprError();
5888
5889 // Okay, we have something that *can* be converted to the right type. Check
5890 // to see if there is a potentially weird extension going on here. This can
5891 // happen when you do an atomic operation on something like an char* and
5892 // pass in 42. The 42 gets converted to char. This is even more strange
5893 // for things like 45.123 -> char, etc.
5894 // FIXME: Do this check.
5895 TheCall->setArg(i+1, Arg.get());
5896 }
5897
5898 // Create a new DeclRefExpr to refer to the new decl.
5899 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5900 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5901 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5902 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5903
5904 // Set the callee in the CallExpr.
5905 // FIXME: This loses syntactic information.
5906 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5907 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5908 CK_BuiltinFnToFnPtr);
5909 TheCall->setCallee(PromotedCall.get());
5910
5911 // Change the result type of the call to match the original value type. This
5912 // is arbitrary, but the codegen for these builtins ins design to handle it
5913 // gracefully.
5914 TheCall->setType(ResultType);
5915
5916 // Prohibit problematic uses of bit-precise integer types with atomic
5917 // builtins. The arguments would have already been converted to the first
5918 // argument's type, so only need to check the first argument.
5919 const auto *BitIntValType = ValType->getAs<BitIntType>();
5920 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
5921 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5922 return ExprError();
5923 }
5924
5925 return TheCallResult;
5926}
5927
5928ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5929 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5930 DeclRefExpr *DRE =
5932 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5933 unsigned BuiltinID = FDecl->getBuiltinID();
5934 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5935 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5936 "Unexpected nontemporal load/store builtin!");
5937 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5938 unsigned numArgs = isStore ? 2 : 1;
5939
5940 // Ensure that we have the proper number of arguments.
5941 if (checkArgCount(TheCall, numArgs))
5942 return ExprError();
5943
5944 // Inspect the last argument of the nontemporal builtin. This should always
5945 // be a pointer type, from which we imply the type of the memory access.
5946 // Because it is a pointer type, we don't have to worry about any implicit
5947 // casts here.
5948 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5949 ExprResult PointerArgResult =
5951
5952 if (PointerArgResult.isInvalid())
5953 return ExprError();
5954 PointerArg = PointerArgResult.get();
5955 TheCall->setArg(numArgs - 1, PointerArg);
5956
5957 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5958 if (!pointerType) {
5959 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5960 << PointerArg->getType() << PointerArg->getSourceRange();
5961 return ExprError();
5962 }
5963
5964 QualType ValType = pointerType->getPointeeType();
5965
5966 // Strip any qualifiers off ValType.
5967 ValType = ValType.getUnqualifiedType();
5968 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5969 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5970 !ValType->isVectorType()) {
5971 Diag(DRE->getBeginLoc(),
5972 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5973 << PointerArg->getType() << PointerArg->getSourceRange();
5974 return ExprError();
5975 }
5976
5977 if (!isStore) {
5978 TheCall->setType(ValType);
5979 return TheCallResult;
5980 }
5981
5982 ExprResult ValArg = TheCall->getArg(0);
5983 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5984 Context, ValType, /*consume*/ false);
5985 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5986 if (ValArg.isInvalid())
5987 return ExprError();
5988
5989 TheCall->setArg(0, ValArg.get());
5990 TheCall->setType(Context.VoidTy);
5991 return TheCallResult;
5992}
5993
5994/// CheckObjCString - Checks that the format string argument to the os_log()
5995/// and os_trace() functions is correct, and converts it to const char *.
5996ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5997 Arg = Arg->IgnoreParenCasts();
5998 auto *Literal = dyn_cast<StringLiteral>(Arg);
5999 if (!Literal) {
6000 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6001 Literal = ObjcLiteral->getString();
6002 }
6003 }
6004
6005 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
6006 return ExprError(
6007 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6008 << Arg->getSourceRange());
6009 }
6010
6011 ExprResult Result(Literal);
6012 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6013 InitializedEntity Entity =
6015 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6016 return Result;
6017}
6018
6019/// Check that the user is calling the appropriate va_start builtin for the
6020/// target and calling convention.
6021static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6022 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6023 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6024 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6025 TT.getArch() == llvm::Triple::aarch64_32);
6026 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
6027 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6028 if (IsX64 || IsAArch64) {
6029 CallingConv CC = CC_C;
6030 if (const FunctionDecl *FD = S.getCurFunctionDecl())
6031 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6032 if (IsMSVAStart) {
6033 // Don't allow this in System V ABI functions.
6034 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
6035 return S.Diag(Fn->getBeginLoc(),
6036 diag::err_ms_va_start_used_in_sysv_function);
6037 } else {
6038 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6039 // On x64 Windows, don't allow this in System V ABI functions.
6040 // (Yes, that means there's no corresponding way to support variadic
6041 // System V ABI functions on Windows.)
6042 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
6043 (!IsWindowsOrUEFI && CC == CC_Win64))
6044 return S.Diag(Fn->getBeginLoc(),
6045 diag::err_va_start_used_in_wrong_abi_function)
6046 << !IsWindowsOrUEFI;
6047 }
6048 return false;
6049 }
6050
6051 if (IsMSVAStart)
6052 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6053 return false;
6054}
6055
6057 ParmVarDecl **LastParam = nullptr) {
6058 // Determine whether the current function, block, or obj-c method is variadic
6059 // and get its parameter list.
6060 bool IsVariadic = false;
6062 DeclContext *Caller = S.CurContext;
6063 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6064 IsVariadic = Block->isVariadic();
6065 Params = Block->parameters();
6066 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6067 IsVariadic = FD->isVariadic();
6068 Params = FD->parameters();
6069 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6070 IsVariadic = MD->isVariadic();
6071 // FIXME: This isn't correct for methods (results in bogus warning).
6072 Params = MD->parameters();
6073 } else if (isa<CapturedDecl>(Caller)) {
6074 // We don't support va_start in a CapturedDecl.
6075 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6076 return true;
6077 } else {
6078 // This must be some other declcontext that parses exprs.
6079 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6080 return true;
6081 }
6082
6083 if (!IsVariadic) {
6084 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6085 return true;
6086 }
6087
6088 if (LastParam)
6089 *LastParam = Params.empty() ? nullptr : Params.back();
6090
6091 return false;
6092}
6093
6094bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6095 Expr *Fn = TheCall->getCallee();
6096 if (checkVAStartABI(*this, BuiltinID, Fn))
6097 return true;
6098
6099 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
6100 // This builtin requires one argument (the va_list), allows two arguments,
6101 // but diagnoses more than two arguments. e.g.,
6102 // __builtin_c23_va_start(); // error
6103 // __builtin_c23_va_start(list); // ok
6104 // __builtin_c23_va_start(list, param); // ok
6105 // __builtin_c23_va_start(list, anything, anything); // error
6106 // This differs from the GCC behavior in that they accept the last case
6107 // with a warning, but it doesn't seem like a useful behavior to allow.
6108 if (checkArgCountRange(TheCall, 1, 2))
6109 return true;
6110 } else {
6111 // In C23 mode, va_start only needs one argument. However, the builtin still
6112 // requires two arguments (which matches the behavior of the GCC builtin),
6113 // <stdarg.h> passes `0` as the second argument in C23 mode.
6114 if (checkArgCount(TheCall, 2))
6115 return true;
6116 }
6117
6118 // Type-check the first argument normally.
6119 if (checkBuiltinArgument(*this, TheCall, 0))
6120 return true;
6121
6122 // Check that the current function is variadic, and get its last parameter.
6123 ParmVarDecl *LastParam;
6124 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6125 return true;
6126
6127 // Verify that the second argument to the builtin is the last non-variadic
6128 // argument of the current function or method. In C23 mode, if the call is
6129 // not to __builtin_c23_va_start, and the second argument is an integer
6130 // constant expression with value 0, then we don't bother with this check.
6131 // For __builtin_c23_va_start, we only perform the check for the second
6132 // argument being the last argument to the current function if there is a
6133 // second argument present.
6134 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
6135 TheCall->getNumArgs() < 2) {
6136 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6137 return false;
6138 }
6139
6140 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6141 if (std::optional<llvm::APSInt> Val =
6143 Val && LangOpts.C23 && *Val == 0 &&
6144 BuiltinID != Builtin::BI__builtin_c23_va_start) {
6145 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6146 return false;
6147 }
6148
6149 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
6150 // next block.
6151 QualType Type;
6152 SourceLocation ParamLoc;
6153 bool IsCRegister = false;
6154 bool SecondArgIsLastNonVariadicArgument = false;
6155 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6156 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6157 SecondArgIsLastNonVariadicArgument = PV == LastParam;
6158
6159 Type = PV->getType();
6160 ParamLoc = PV->getLocation();
6161 IsCRegister =
6162 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6163 }
6164 }
6165
6166 if (!SecondArgIsLastNonVariadicArgument)
6167 Diag(TheCall->getArg(1)->getBeginLoc(),
6168 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
6169 else if (IsCRegister || Type->isReferenceType() ||
6170 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6171 // Promotable integers are UB, but enumerations need a bit of
6172 // extra checking to see what their promotable type actually is.
6173 if (!Context.isPromotableIntegerType(Type))
6174 return false;
6175 const auto *ED = Type->getAsEnumDecl();
6176 if (!ED)
6177 return true;
6178 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
6179 }()) {
6180 unsigned Reason = 0;
6181 if (Type->isReferenceType()) Reason = 1;
6182 else if (IsCRegister) Reason = 2;
6183 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6184 Diag(ParamLoc, diag::note_parameter_type) << Type;
6185 }
6186
6187 return false;
6188}
6189
6190bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
6191 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6192 const LangOptions &LO = getLangOpts();
6193
6194 if (LO.CPlusPlus)
6195 return Arg->getType()
6197 .getTypePtr()
6198 ->getPointeeType()
6200
6201 // In C, allow aliasing through `char *`, this is required for AArch64 at
6202 // least.
6203 return true;
6204 };
6205
6206 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6207 // const char *named_addr);
6208
6209 Expr *Func = Call->getCallee();
6210
6211 if (Call->getNumArgs() < 3)
6212 return Diag(Call->getEndLoc(),
6213 diag::err_typecheck_call_too_few_args_at_least)
6214 << 0 /*function call*/ << 3 << Call->getNumArgs()
6215 << /*is non object*/ 0;
6216
6217 // Type-check the first argument normally.
6218 if (checkBuiltinArgument(*this, Call, 0))
6219 return true;
6220
6221 // Check that the current function is variadic.
6223 return true;
6224
6225 // __va_start on Windows does not validate the parameter qualifiers
6226
6227 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6228 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6229
6230 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6231 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6232
6233 const QualType &ConstCharPtrTy =
6234 Context.getPointerType(Context.CharTy.withConst());
6235 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6236 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6237 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6238 << 0 /* qualifier difference */
6239 << 3 /* parameter mismatch */
6240 << 2 << Arg1->getType() << ConstCharPtrTy;
6241
6242 const QualType SizeTy = Context.getSizeType();
6243 if (!Context.hasSameType(
6245 SizeTy))
6246 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6247 << Arg2->getType() << SizeTy << 1 /* different class */
6248 << 0 /* qualifier difference */
6249 << 3 /* parameter mismatch */
6250 << 3 << Arg2->getType() << SizeTy;
6251
6252 return false;
6253}
6254
6255bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
6256 if (checkArgCount(TheCall, 2))
6257 return true;
6258
6259 if (BuiltinID == Builtin::BI__builtin_isunordered &&
6260 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
6261 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6262 << 1 << 0 << TheCall->getSourceRange();
6263
6264 ExprResult OrigArg0 = TheCall->getArg(0);
6265 ExprResult OrigArg1 = TheCall->getArg(1);
6266
6267 // Do standard promotions between the two arguments, returning their common
6268 // type.
6269 QualType Res = UsualArithmeticConversions(
6270 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
6271 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6272 return true;
6273
6274 // Make sure any conversions are pushed back into the call; this is
6275 // type safe since unordered compare builtins are declared as "_Bool
6276 // foo(...)".
6277 TheCall->setArg(0, OrigArg0.get());
6278 TheCall->setArg(1, OrigArg1.get());
6279
6280 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6281 return false;
6282
6283 // If the common type isn't a real floating type, then the arguments were
6284 // invalid for this operation.
6285 if (Res.isNull() || !Res->isRealFloatingType())
6286 return Diag(OrigArg0.get()->getBeginLoc(),
6287 diag::err_typecheck_call_invalid_ordered_compare)
6288 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6289 << SourceRange(OrigArg0.get()->getBeginLoc(),
6290 OrigArg1.get()->getEndLoc());
6291
6292 return false;
6293}
6294
6295bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
6296 unsigned BuiltinID) {
6297 if (checkArgCount(TheCall, NumArgs))
6298 return true;
6299
6300 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
6301 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
6302 BuiltinID == Builtin::BI__builtin_isinf ||
6303 BuiltinID == Builtin::BI__builtin_isinf_sign))
6304 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6305 << 0 << 0 << TheCall->getSourceRange();
6306
6307 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
6308 BuiltinID == Builtin::BI__builtin_isunordered))
6309 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6310 << 1 << 0 << TheCall->getSourceRange();
6311
6312 bool IsFPClass = NumArgs == 2;
6313
6314 // Find out position of floating-point argument.
6315 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
6316
6317 // We can count on all parameters preceding the floating-point just being int.
6318 // Try all of those.
6319 for (unsigned i = 0; i < FPArgNo; ++i) {
6320 Expr *Arg = TheCall->getArg(i);
6321
6322 if (Arg->isTypeDependent())
6323 return false;
6324
6327
6328 if (Res.isInvalid())
6329 return true;
6330 TheCall->setArg(i, Res.get());
6331 }
6332
6333 Expr *OrigArg = TheCall->getArg(FPArgNo);
6334
6335 if (OrigArg->isTypeDependent())
6336 return false;
6337
6338 // We want to leave the type how it is, but do normal L->Rvalue conversions.
6340 if (!Res.isUsable())
6341 return true;
6342 OrigArg = Res.get();
6343
6344 TheCall->setArg(FPArgNo, OrigArg);
6345
6346 QualType VectorResultTy;
6347 QualType ElementTy = OrigArg->getType();
6348 // TODO: When all classification function are implemented with is_fpclass,
6349 // vector argument can be supported in all of them.
6350 if (ElementTy->isVectorType() && IsFPClass) {
6351 VectorResultTy = GetSignedVectorType(ElementTy);
6352 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6353 }
6354
6355 // This operation requires a non-_Complex floating-point number.
6356 if (!ElementTy->isRealFloatingType())
6357 return Diag(OrigArg->getBeginLoc(),
6358 diag::err_typecheck_call_invalid_unary_fp)
6359 << OrigArg->getType() << OrigArg->getSourceRange();
6360
6361 // __builtin_isfpclass has integer parameter that specify test mask. It is
6362 // passed in (...), so it should be analyzed completely here.
6363 if (IsFPClass)
6364 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
6365 return true;
6366
6367 // TODO: enable this code to all classification functions.
6368 if (IsFPClass) {
6369 QualType ResultTy;
6370 if (!VectorResultTy.isNull())
6371 ResultTy = VectorResultTy;
6372 else
6373 ResultTy = Context.IntTy;
6374 TheCall->setType(ResultTy);
6375 }
6376
6377 return false;
6378}
6379
6380bool Sema::BuiltinComplex(CallExpr *TheCall) {
6381 if (checkArgCount(TheCall, 2))
6382 return true;
6383
6384 bool Dependent = false;
6385 for (unsigned I = 0; I != 2; ++I) {
6386 Expr *Arg = TheCall->getArg(I);
6387 QualType T = Arg->getType();
6388 if (T->isDependentType()) {
6389 Dependent = true;
6390 continue;
6391 }
6392
6393 // Despite supporting _Complex int, GCC requires a real floating point type
6394 // for the operands of __builtin_complex.
6395 if (!T->isRealFloatingType()) {
6396 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6397 << Arg->getType() << Arg->getSourceRange();
6398 }
6399
6400 ExprResult Converted = DefaultLvalueConversion(Arg);
6401 if (Converted.isInvalid())
6402 return true;
6403 TheCall->setArg(I, Converted.get());
6404 }
6405
6406 if (Dependent) {
6407 TheCall->setType(Context.DependentTy);
6408 return false;
6409 }
6410
6411 Expr *Real = TheCall->getArg(0);
6412 Expr *Imag = TheCall->getArg(1);
6413 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6414 return Diag(Real->getBeginLoc(),
6415 diag::err_typecheck_call_different_arg_types)
6416 << Real->getType() << Imag->getType()
6417 << Real->getSourceRange() << Imag->getSourceRange();
6418 }
6419
6420 TheCall->setType(Context.getComplexType(Real->getType()));
6421 return false;
6422}
6423
6424/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6425// This is declared to take (...), so we have to check everything.
6427 unsigned NumArgs = TheCall->getNumArgs();
6428 if (NumArgs < 2)
6429 return ExprError(Diag(TheCall->getEndLoc(),
6430 diag::err_typecheck_call_too_few_args_at_least)
6431 << 0 /*function call*/ << 2 << NumArgs
6432 << /*is non object*/ 0 << TheCall->getSourceRange());
6433
6434 // Determine which of the following types of shufflevector we're checking:
6435 // 1) unary, vector mask: (lhs, mask)
6436 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6437 QualType ResType = TheCall->getArg(0)->getType();
6438 unsigned NumElements = 0;
6439
6440 if (!TheCall->getArg(0)->isTypeDependent() &&
6441 !TheCall->getArg(1)->isTypeDependent()) {
6442 QualType LHSType = TheCall->getArg(0)->getType();
6443 QualType RHSType = TheCall->getArg(1)->getType();
6444
6445 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6446 return ExprError(
6447 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6448 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6449 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6450 TheCall->getArg(1)->getEndLoc()));
6451
6452 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6453 unsigned NumResElements = NumArgs - 2;
6454
6455 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6456 // with mask. If so, verify that RHS is an integer vector type with the
6457 // same number of elts as lhs.
6458 if (NumArgs == 2) {
6459 if (!RHSType->hasIntegerRepresentation() ||
6460 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
6461 return ExprError(Diag(TheCall->getBeginLoc(),
6462 diag::err_vec_builtin_incompatible_vector)
6463 << TheCall->getDirectCallee()
6464 << /*isMoreThanTwoArgs*/ false
6465 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6466 TheCall->getArg(1)->getEndLoc()));
6467 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6468 return ExprError(Diag(TheCall->getBeginLoc(),
6469 diag::err_vec_builtin_incompatible_vector)
6470 << TheCall->getDirectCallee()
6471 << /*isMoreThanTwoArgs*/ false
6472 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6473 TheCall->getArg(1)->getEndLoc()));
6474 } else if (NumElements != NumResElements) {
6475 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6476 ResType = ResType->isExtVectorType()
6477 ? Context.getExtVectorType(EltType, NumResElements)
6478 : Context.getVectorType(EltType, NumResElements,
6480 }
6481 }
6482
6483 for (unsigned I = 2; I != NumArgs; ++I) {
6484 Expr *Arg = TheCall->getArg(I);
6485 if (Arg->isTypeDependent() || Arg->isValueDependent())
6486 continue;
6487
6488 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
6489 if (!Result)
6490 return ExprError(Diag(TheCall->getBeginLoc(),
6491 diag::err_shufflevector_nonconstant_argument)
6492 << Arg->getSourceRange());
6493
6494 // Allow -1 which will be translated to undef in the IR.
6495 if (Result->isSigned() && Result->isAllOnes())
6496 ;
6497 else if (Result->getActiveBits() > 64 ||
6498 Result->getZExtValue() >= NumElements * 2)
6499 return ExprError(Diag(TheCall->getBeginLoc(),
6500 diag::err_shufflevector_argument_too_large)
6501 << Arg->getSourceRange());
6502
6503 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
6504 }
6505
6506 auto *Result = new (Context) ShuffleVectorExpr(
6507 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6508 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6509
6510 // All moved to Result.
6511 TheCall->shrinkNumArgs(0);
6512 return Result;
6513}
6514
6516 SourceLocation BuiltinLoc,
6517 SourceLocation RParenLoc) {
6520 QualType DstTy = TInfo->getType();
6521 QualType SrcTy = E->getType();
6522
6523 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6524 return ExprError(Diag(BuiltinLoc,
6525 diag::err_convertvector_non_vector)
6526 << E->getSourceRange());
6527 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6528 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
6529 << "second"
6530 << "__builtin_convertvector");
6531
6532 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6533 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6534 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6535 if (SrcElts != DstElts)
6536 return ExprError(Diag(BuiltinLoc,
6537 diag::err_convertvector_incompatible_vector)
6538 << E->getSourceRange());
6539 }
6540
6541 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
6542 RParenLoc, CurFPFeatureOverrides());
6543}
6544
6545bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6546 unsigned NumArgs = TheCall->getNumArgs();
6547
6548 if (NumArgs > 3)
6549 return Diag(TheCall->getEndLoc(),
6550 diag::err_typecheck_call_too_many_args_at_most)
6551 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6552 << TheCall->getSourceRange();
6553
6554 // Argument 0 is checked for us and the remaining arguments must be
6555 // constant integers.
6556 for (unsigned i = 1; i != NumArgs; ++i)
6557 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6558 return true;
6559
6560 return false;
6561}
6562
6563bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6564 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6565 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6566 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6567 if (checkArgCount(TheCall, 1))
6568 return true;
6569 Expr *Arg = TheCall->getArg(0);
6570 if (Arg->isInstantiationDependent())
6571 return false;
6572
6573 QualType ArgTy = Arg->getType();
6574 if (!ArgTy->hasFloatingRepresentation())
6575 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6576 << ArgTy;
6577 if (Arg->isLValue()) {
6578 ExprResult FirstArg = DefaultLvalueConversion(Arg);
6579 TheCall->setArg(0, FirstArg.get());
6580 }
6581 TheCall->setType(TheCall->getArg(0)->getType());
6582 return false;
6583}
6584
6585bool Sema::BuiltinAssume(CallExpr *TheCall) {
6586 Expr *Arg = TheCall->getArg(0);
6587 if (Arg->isInstantiationDependent()) return false;
6588
6589 if (Arg->HasSideEffects(Context))
6590 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6591 << Arg->getSourceRange()
6592 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6593
6594 return false;
6595}
6596
6597bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6598 // The alignment must be a constant integer.
6599 Expr *Arg = TheCall->getArg(1);
6600
6601 // We can't check the value of a dependent argument.
6602 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6603 if (const auto *UE =
6604 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6605 if (UE->getKind() == UETT_AlignOf ||
6606 UE->getKind() == UETT_PreferredAlignOf)
6607 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6608 << Arg->getSourceRange();
6609
6610 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6611
6612 if (!Result.isPowerOf2())
6613 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6614 << Arg->getSourceRange();
6615
6616 if (Result < Context.getCharWidth())
6617 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6618 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6619
6620 if (Result > std::numeric_limits<int32_t>::max())
6621 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6622 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6623 }
6624
6625 return false;
6626}
6627
6628bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6629 if (checkArgCountRange(TheCall, 2, 3))
6630 return true;
6631
6632 unsigned NumArgs = TheCall->getNumArgs();
6633 Expr *FirstArg = TheCall->getArg(0);
6634
6635 {
6636 ExprResult FirstArgResult =
6638 if (!FirstArgResult.get()->getType()->isPointerType()) {
6639 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
6640 << TheCall->getSourceRange();
6641 return true;
6642 }
6643 TheCall->setArg(0, FirstArgResult.get());
6644 }
6645
6646 // The alignment must be a constant integer.
6647 Expr *SecondArg = TheCall->getArg(1);
6648
6649 // We can't check the value of a dependent argument.
6650 if (!SecondArg->isValueDependent()) {
6651 llvm::APSInt Result;
6652 if (BuiltinConstantArg(TheCall, 1, Result))
6653 return true;
6654
6655 if (!Result.isPowerOf2())
6656 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6657 << SecondArg->getSourceRange();
6658
6660 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6661 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6662
6663 TheCall->setArg(1,
6665 }
6666
6667 if (NumArgs > 2) {
6668 Expr *ThirdArg = TheCall->getArg(2);
6669 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
6670 return true;
6671 TheCall->setArg(2, ThirdArg);
6672 }
6673
6674 return false;
6675}
6676
6677bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6678 unsigned BuiltinID =
6679 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6680 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6681
6682 unsigned NumArgs = TheCall->getNumArgs();
6683 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6684 if (NumArgs < NumRequiredArgs) {
6685 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6686 << 0 /* function call */ << NumRequiredArgs << NumArgs
6687 << /*is non object*/ 0 << TheCall->getSourceRange();
6688 }
6689 if (NumArgs >= NumRequiredArgs + 0x100) {
6690 return Diag(TheCall->getEndLoc(),
6691 diag::err_typecheck_call_too_many_args_at_most)
6692 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6693 << /*is non object*/ 0 << TheCall->getSourceRange();
6694 }
6695 unsigned i = 0;
6696
6697 // For formatting call, check buffer arg.
6698 if (!IsSizeCall) {
6699 ExprResult Arg(TheCall->getArg(i));
6700 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6701 Context, Context.VoidPtrTy, false);
6702 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6703 if (Arg.isInvalid())
6704 return true;
6705 TheCall->setArg(i, Arg.get());
6706 i++;
6707 }
6708
6709 // Check string literal arg.
6710 unsigned FormatIdx = i;
6711 {
6712 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6713 if (Arg.isInvalid())
6714 return true;
6715 TheCall->setArg(i, Arg.get());
6716 i++;
6717 }
6718
6719 // Make sure variadic args are scalar.
6720 unsigned FirstDataArg = i;
6721 while (i < NumArgs) {
6723 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6724 if (Arg.isInvalid())
6725 return true;
6726 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6727 if (ArgSize.getQuantity() >= 0x100) {
6728 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6729 << i << (int)ArgSize.getQuantity() << 0xff
6730 << TheCall->getSourceRange();
6731 }
6732 TheCall->setArg(i, Arg.get());
6733 i++;
6734 }
6735
6736 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6737 // call to avoid duplicate diagnostics.
6738 if (!IsSizeCall) {
6739 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6740 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6741 bool Success = CheckFormatArguments(
6742 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
6744 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
6745 if (!Success)
6746 return true;
6747 }
6748
6749 if (IsSizeCall) {
6750 TheCall->setType(Context.getSizeType());
6751 } else {
6752 TheCall->setType(Context.VoidPtrTy);
6753 }
6754 return false;
6755}
6756
6757bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6758 llvm::APSInt &Result) {
6759 Expr *Arg = TheCall->getArg(ArgNum);
6760
6761 if (Arg->isTypeDependent() || Arg->isValueDependent())
6762 return false;
6763
6764 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
6765 if (!R) {
6766 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6767 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6768 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6769 << FDecl->getDeclName() << Arg->getSourceRange();
6770 }
6771 Result = *R;
6772
6773 return false;
6774}
6775
6776bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6777 int High, bool RangeIsError) {
6779 return false;
6780 llvm::APSInt Result;
6781
6782 // We can't check the value of a dependent argument.
6783 Expr *Arg = TheCall->getArg(ArgNum);
6784 if (Arg->isTypeDependent() || Arg->isValueDependent())
6785 return false;
6786
6787 // Check constant-ness first.
6788 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6789 return true;
6790
6791 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6792 if (RangeIsError)
6793 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6794 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6795 else
6796 // Defer the warning until we know if the code will be emitted so that
6797 // dead code can ignore this.
6798 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6799 PDiag(diag::warn_argument_invalid_range)
6800 << toString(Result, 10) << Low << High
6801 << Arg->getSourceRange());
6802 }
6803
6804 return false;
6805}
6806
6807bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6808 unsigned Num) {
6809 llvm::APSInt Result;
6810
6811 // We can't check the value of a dependent argument.
6812 Expr *Arg = TheCall->getArg(ArgNum);
6813 if (Arg->isTypeDependent() || Arg->isValueDependent())
6814 return false;
6815
6816 // Check constant-ness first.
6817 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6818 return true;
6819
6820 if (Result.getSExtValue() % Num != 0)
6821 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6822 << Num << Arg->getSourceRange();
6823
6824 return false;
6825}
6826
6827bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6828 llvm::APSInt Result;
6829
6830 // We can't check the value of a dependent argument.
6831 Expr *Arg = TheCall->getArg(ArgNum);
6832 if (Arg->isTypeDependent() || Arg->isValueDependent())
6833 return false;
6834
6835 // Check constant-ness first.
6836 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6837 return true;
6838
6839 if (Result.isPowerOf2())
6840 return false;
6841
6842 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6843 << Arg->getSourceRange();
6844}
6845
6846static bool IsShiftedByte(llvm::APSInt Value) {
6847 if (Value.isNegative())
6848 return false;
6849
6850 // Check if it's a shifted byte, by shifting it down
6851 while (true) {
6852 // If the value fits in the bottom byte, the check passes.
6853 if (Value < 0x100)
6854 return true;
6855
6856 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6857 // fails.
6858 if ((Value & 0xFF) != 0)
6859 return false;
6860
6861 // If the bottom 8 bits are all 0, but something above that is nonzero,
6862 // then shifting the value right by 8 bits won't affect whether it's a
6863 // shifted byte or not. So do that, and go round again.
6864 Value >>= 8;
6865 }
6866}
6867
6868bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6869 unsigned ArgBits) {
6870 llvm::APSInt Result;
6871
6872 // We can't check the value of a dependent argument.
6873 Expr *Arg = TheCall->getArg(ArgNum);
6874 if (Arg->isTypeDependent() || Arg->isValueDependent())
6875 return false;
6876
6877 // Check constant-ness first.
6878 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6879 return true;
6880
6881 // Truncate to the given size.
6882 Result = Result.getLoBits(ArgBits);
6883 Result.setIsUnsigned(true);
6884
6885 if (IsShiftedByte(Result))
6886 return false;
6887
6888 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6889 << Arg->getSourceRange();
6890}
6891
6893 unsigned ArgNum,
6894 unsigned ArgBits) {
6895 llvm::APSInt Result;
6896
6897 // We can't check the value of a dependent argument.
6898 Expr *Arg = TheCall->getArg(ArgNum);
6899 if (Arg->isTypeDependent() || Arg->isValueDependent())
6900 return false;
6901
6902 // Check constant-ness first.
6903 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6904 return true;
6905
6906 // Truncate to the given size.
6907 Result = Result.getLoBits(ArgBits);
6908 Result.setIsUnsigned(true);
6909
6910 // Check to see if it's in either of the required forms.
6911 if (IsShiftedByte(Result) ||
6912 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6913 return false;
6914
6915 return Diag(TheCall->getBeginLoc(),
6916 diag::err_argument_not_shifted_byte_or_xxff)
6917 << Arg->getSourceRange();
6918}
6919
6920bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6921 if (!Context.getTargetInfo().hasSjLjLowering())
6922 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6923 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6924
6925 Expr *Arg = TheCall->getArg(1);
6926 llvm::APSInt Result;
6927
6928 // TODO: This is less than ideal. Overload this to take a value.
6929 if (BuiltinConstantArg(TheCall, 1, Result))
6930 return true;
6931
6932 if (Result != 1)
6933 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6934 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6935
6936 return false;
6937}
6938
6939bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6940 if (!Context.getTargetInfo().hasSjLjLowering())
6941 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6942 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6943 return false;
6944}
6945
6946bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6947 if (checkArgCount(TheCall, 1))
6948 return true;
6949
6950 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
6951 if (ArgRes.isInvalid())
6952 return true;
6953
6954 // For simplicity, we support only limited expressions for the argument.
6955 // Specifically a flexible array member or a pointer with counted_by:
6956 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
6957 // complex casting, which really shouldn't be a huge problem.
6958 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6959 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
6960 return Diag(Arg->getBeginLoc(),
6961 diag::err_builtin_counted_by_ref_invalid_arg)
6962 << Arg->getSourceRange();
6963
6964 if (Arg->HasSideEffects(Context))
6965 return Diag(Arg->getBeginLoc(),
6966 diag::err_builtin_counted_by_ref_has_side_effects)
6967 << Arg->getSourceRange();
6968
6969 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
6970 const auto *CATy =
6971 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6972
6973 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6974 // Member has counted_by attribute - return pointer to count field
6975 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
6976 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
6977 TheCall->setType(Context.getPointerType(CountFD->getType()));
6978 return false;
6979 }
6980 }
6981
6982 // FAMs and pointers without counted_by return void*
6983 QualType MemberTy = ME->getMemberDecl()->getType();
6984 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
6985 return Diag(Arg->getBeginLoc(),
6986 diag::err_builtin_counted_by_ref_invalid_arg)
6987 << Arg->getSourceRange();
6988 } else {
6989 return Diag(Arg->getBeginLoc(),
6990 diag::err_builtin_counted_by_ref_invalid_arg)
6991 << Arg->getSourceRange();
6992 }
6993
6994 TheCall->setType(Context.getPointerType(Context.VoidTy));
6995 return false;
6996}
6997
6998/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6999/// It allows leaking and modification of bounds safety information.
7000bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
7002 const CallExpr *CE =
7003 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
7004 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
7005 return false;
7006
7007 switch (K) {
7010 Diag(E->getExprLoc(),
7011 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7012 << 0 << E->getSourceRange();
7013 break;
7015 Diag(E->getExprLoc(),
7016 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7017 << 1 << E->getSourceRange();
7018 break;
7020 Diag(E->getExprLoc(),
7021 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7022 << 2 << E->getSourceRange();
7023 break;
7025 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
7026 << 0 << E->getSourceRange();
7027 break;
7029 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
7030 << 1 << E->getSourceRange();
7031 break;
7032 }
7033
7034 return true;
7035}
7036
7037namespace {
7038
7039class UncoveredArgHandler {
7040 enum { Unknown = -1, AllCovered = -2 };
7041
7042 signed FirstUncoveredArg = Unknown;
7043 SmallVector<const Expr *, 4> DiagnosticExprs;
7044
7045public:
7046 UncoveredArgHandler() = default;
7047
7048 bool hasUncoveredArg() const {
7049 return (FirstUncoveredArg >= 0);
7050 }
7051
7052 unsigned getUncoveredArg() const {
7053 assert(hasUncoveredArg() && "no uncovered argument");
7054 return FirstUncoveredArg;
7055 }
7056
7057 void setAllCovered() {
7058 // A string has been found with all arguments covered, so clear out
7059 // the diagnostics.
7060 DiagnosticExprs.clear();
7061 FirstUncoveredArg = AllCovered;
7062 }
7063
7064 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7065 assert(NewFirstUncoveredArg >= 0 && "Outside range");
7066
7067 // Don't update if a previous string covers all arguments.
7068 if (FirstUncoveredArg == AllCovered)
7069 return;
7070
7071 // UncoveredArgHandler tracks the highest uncovered argument index
7072 // and with it all the strings that match this index.
7073 if (NewFirstUncoveredArg == FirstUncoveredArg)
7074 DiagnosticExprs.push_back(StrExpr);
7075 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7076 DiagnosticExprs.clear();
7077 DiagnosticExprs.push_back(StrExpr);
7078 FirstUncoveredArg = NewFirstUncoveredArg;
7079 }
7080 }
7081
7082 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7083};
7084
7085enum StringLiteralCheckType {
7086 SLCT_NotALiteral,
7087 SLCT_UncheckedLiteral,
7088 SLCT_CheckedLiteral
7089};
7090
7091} // namespace
7092
7093static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7094 BinaryOperatorKind BinOpKind,
7095 bool AddendIsRight) {
7096 unsigned BitWidth = Offset.getBitWidth();
7097 unsigned AddendBitWidth = Addend.getBitWidth();
7098 // There might be negative interim results.
7099 if (Addend.isUnsigned()) {
7100 Addend = Addend.zext(++AddendBitWidth);
7101 Addend.setIsSigned(true);
7102 }
7103 // Adjust the bit width of the APSInts.
7104 if (AddendBitWidth > BitWidth) {
7105 Offset = Offset.sext(AddendBitWidth);
7106 BitWidth = AddendBitWidth;
7107 } else if (BitWidth > AddendBitWidth) {
7108 Addend = Addend.sext(BitWidth);
7109 }
7110
7111 bool Ov = false;
7112 llvm::APSInt ResOffset = Offset;
7113 if (BinOpKind == BO_Add)
7114 ResOffset = Offset.sadd_ov(Addend, Ov);
7115 else {
7116 assert(AddendIsRight && BinOpKind == BO_Sub &&
7117 "operator must be add or sub with addend on the right");
7118 ResOffset = Offset.ssub_ov(Addend, Ov);
7119 }
7120
7121 // We add an offset to a pointer here so we should support an offset as big as
7122 // possible.
7123 if (Ov) {
7124 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7125 "index (intermediate) result too big");
7126 Offset = Offset.sext(2 * BitWidth);
7127 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7128 return;
7129 }
7130
7131 Offset = std::move(ResOffset);
7132}
7133
7134namespace {
7135
7136// This is a wrapper class around StringLiteral to support offsetted string
7137// literals as format strings. It takes the offset into account when returning
7138// the string and its length or the source locations to display notes correctly.
7139class FormatStringLiteral {
7140 const StringLiteral *FExpr;
7141 int64_t Offset;
7142
7143public:
7144 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7145 : FExpr(fexpr), Offset(Offset) {}
7146
7147 const StringLiteral *getFormatString() const { return FExpr; }
7148
7149 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
7150
7151 unsigned getByteLength() const {
7152 return FExpr->getByteLength() - getCharByteWidth() * Offset;
7153 }
7154
7155 unsigned getLength() const { return FExpr->getLength() - Offset; }
7156 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7157
7158 StringLiteralKind getKind() const { return FExpr->getKind(); }
7159
7160 QualType getType() const { return FExpr->getType(); }
7161
7162 bool isAscii() const { return FExpr->isOrdinary(); }
7163 bool isWide() const { return FExpr->isWide(); }
7164 bool isUTF8() const { return FExpr->isUTF8(); }
7165 bool isUTF16() const { return FExpr->isUTF16(); }
7166 bool isUTF32() const { return FExpr->isUTF32(); }
7167 bool isPascal() const { return FExpr->isPascal(); }
7168
7169 SourceLocation getLocationOfByte(
7170 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7171 const TargetInfo &Target, unsigned *StartToken = nullptr,
7172 unsigned *StartTokenByteOffset = nullptr) const {
7173 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7174 StartToken, StartTokenByteOffset);
7175 }
7176
7177 SourceLocation getBeginLoc() const LLVM_READONLY {
7178 return FExpr->getBeginLoc().getLocWithOffset(Offset);
7179 }
7180
7181 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7182};
7183
7184} // namespace
7185
7186static void CheckFormatString(
7187 Sema &S, const FormatStringLiteral *FExpr,
7188 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
7190 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
7191 bool inFunctionCall, VariadicCallType CallType,
7192 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7193 bool IgnoreStringsWithoutSpecifiers);
7194
7195static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7196 const Expr *E);
7197
7198// Determine if an expression is a string literal or constant string.
7199// If this function returns false on the arguments to a function expecting a
7200// format string, we will usually need to emit a warning.
7201// True string literals are then checked by CheckFormatString.
7202static StringLiteralCheckType
7203checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
7204 const Expr *E, ArrayRef<const Expr *> Args,
7205 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
7206 unsigned firstDataArg, FormatStringType Type,
7207 VariadicCallType CallType, bool InFunctionCall,
7208 llvm::SmallBitVector &CheckedVarArgs,
7209 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
7210 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
7211 bool IgnoreStringsWithoutSpecifiers = false) {
7213 return SLCT_NotALiteral;
7214tryAgain:
7215 assert(Offset.isSigned() && "invalid offset");
7216
7217 if (E->isTypeDependent() || E->isValueDependent())
7218 return SLCT_NotALiteral;
7219
7220 E = E->IgnoreParenCasts();
7221
7223 // Technically -Wformat-nonliteral does not warn about this case.
7224 // The behavior of printf and friends in this case is implementation
7225 // dependent. Ideally if the format string cannot be null then
7226 // it should have a 'nonnull' attribute in the function prototype.
7227 return SLCT_UncheckedLiteral;
7228
7229 switch (E->getStmtClass()) {
7230 case Stmt::InitListExprClass:
7231 // Handle expressions like {"foobar"}.
7232 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
7233 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7234 format_idx, firstDataArg, Type, CallType,
7235 /*InFunctionCall*/ false, CheckedVarArgs,
7236 UncoveredArg, Offset, CallerFormatParamIdx,
7237 IgnoreStringsWithoutSpecifiers);
7238 }
7239 return SLCT_NotALiteral;
7240 case Stmt::BinaryConditionalOperatorClass:
7241 case Stmt::ConditionalOperatorClass: {
7242 // The expression is a literal if both sub-expressions were, and it was
7243 // completely checked only if both sub-expressions were checked.
7246
7247 // Determine whether it is necessary to check both sub-expressions, for
7248 // example, because the condition expression is a constant that can be
7249 // evaluated at compile time.
7250 bool CheckLeft = true, CheckRight = true;
7251
7252 bool Cond;
7253 if (C->getCond()->EvaluateAsBooleanCondition(
7255 if (Cond)
7256 CheckRight = false;
7257 else
7258 CheckLeft = false;
7259 }
7260
7261 // We need to maintain the offsets for the right and the left hand side
7262 // separately to check if every possible indexed expression is a valid
7263 // string literal. They might have different offsets for different string
7264 // literals in the end.
7265 StringLiteralCheckType Left;
7266 if (!CheckLeft)
7267 Left = SLCT_UncheckedLiteral;
7268 else {
7269 Left = checkFormatStringExpr(S, ReferenceFormatString, C->getTrueExpr(),
7270 Args, APK, format_idx, firstDataArg, Type,
7271 CallType, InFunctionCall, CheckedVarArgs,
7272 UncoveredArg, Offset, CallerFormatParamIdx,
7273 IgnoreStringsWithoutSpecifiers);
7274 if (Left == SLCT_NotALiteral || !CheckRight) {
7275 return Left;
7276 }
7277 }
7278
7279 StringLiteralCheckType Right = checkFormatStringExpr(
7280 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
7281 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7282 UncoveredArg, Offset, CallerFormatParamIdx,
7283 IgnoreStringsWithoutSpecifiers);
7284
7285 return (CheckLeft && Left < Right) ? Left : Right;
7286 }
7287
7288 case Stmt::ImplicitCastExprClass:
7289 E = cast<ImplicitCastExpr>(E)->getSubExpr();
7290 goto tryAgain;
7291
7292 case Stmt::OpaqueValueExprClass:
7293 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7294 E = src;
7295 goto tryAgain;
7296 }
7297 return SLCT_NotALiteral;
7298
7299 case Stmt::PredefinedExprClass:
7300 // While __func__, etc., are technically not string literals, they
7301 // cannot contain format specifiers and thus are not a security
7302 // liability.
7303 return SLCT_UncheckedLiteral;
7304
7305 case Stmt::DeclRefExprClass: {
7306 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7307
7308 // As an exception, do not flag errors for variables binding to
7309 // const string literals.
7310 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7311 bool isConstant = false;
7312 QualType T = DR->getType();
7313
7314 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7315 isConstant = AT->getElementType().isConstant(S.Context);
7316 } else if (const PointerType *PT = T->getAs<PointerType>()) {
7317 isConstant = T.isConstant(S.Context) &&
7318 PT->getPointeeType().isConstant(S.Context);
7319 } else if (T->isObjCObjectPointerType()) {
7320 // In ObjC, there is usually no "const ObjectPointer" type,
7321 // so don't check if the pointee type is constant.
7322 isConstant = T.isConstant(S.Context);
7323 }
7324
7325 if (isConstant) {
7326 if (const Expr *Init = VD->getAnyInitializer()) {
7327 // Look through initializers like const char c[] = { "foo" }
7328 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7329 if (InitList->isStringLiteralInit())
7330 Init = InitList->getInit(0)->IgnoreParenImpCasts();
7331 }
7332 return checkFormatStringExpr(
7333 S, ReferenceFormatString, Init, Args, APK, format_idx,
7334 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7335 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7336 }
7337 }
7338
7339 // When the format argument is an argument of this function, and this
7340 // function also has the format attribute, there are several interactions
7341 // for which there shouldn't be a warning. For instance, when calling
7342 // v*printf from a function that has the printf format attribute, we
7343 // should not emit a warning about using `fmt`, even though it's not
7344 // constant, because the arguments have already been checked for the
7345 // caller of `logmessage`:
7346 //
7347 // __attribute__((format(printf, 1, 2)))
7348 // void logmessage(char const *fmt, ...) {
7349 // va_list ap;
7350 // va_start(ap, fmt);
7351 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7352 // ...
7353 // }
7354 //
7355 // Another interaction that we need to support is using a format string
7356 // specified by the format_matches attribute:
7357 //
7358 // __attribute__((format_matches(printf, 1, "%s %d")))
7359 // void logmessage(char const *fmt, const char *a, int b) {
7360 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7361 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7362 // ...
7363 // }
7364 //
7365 // Yet another interaction that we need to support is calling a variadic
7366 // format function from a format function that has fixed arguments. For
7367 // instance:
7368 //
7369 // __attribute__((format(printf, 1, 2)))
7370 // void logstring(char const *fmt, char const *str) {
7371 // printf(fmt, str); /* do not emit a warning about "fmt" */
7372 // }
7373 //
7374 // Same (and perhaps more relatably) for the variadic template case:
7375 //
7376 // template<typename... Args>
7377 // __attribute__((format(printf, 1, 2)))
7378 // void log(const char *fmt, Args&&... args) {
7379 // printf(fmt, forward<Args>(args)...);
7380 // /* do not emit a warning about "fmt" */
7381 // }
7382 //
7383 // Due to implementation difficulty, we only check the format, not the
7384 // format arguments, in all cases.
7385 //
7386 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
7387 if (CallerFormatParamIdx)
7388 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7389 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
7390 for (const auto *PVFormatMatches :
7391 D->specific_attrs<FormatMatchesAttr>()) {
7392 Sema::FormatStringInfo CalleeFSI;
7393 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
7394 0, &CalleeFSI))
7395 continue;
7396 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7397 // If using the wrong type of format string, emit a diagnostic
7398 // here and stop checking to avoid irrelevant diagnostics.
7399 if (Type != S.GetFormatStringType(PVFormatMatches)) {
7400 S.Diag(Args[format_idx]->getBeginLoc(),
7401 diag::warn_format_string_type_incompatible)
7402 << PVFormatMatches->getType()->getName()
7404 if (!InFunctionCall) {
7405 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
7406 diag::note_format_string_defined);
7407 }
7408 return SLCT_UncheckedLiteral;
7409 }
7410 return checkFormatStringExpr(
7411 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
7412 Args, APK, format_idx, firstDataArg, Type, CallType,
7413 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7414 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7415 }
7416 }
7417
7418 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7419 Sema::FormatStringInfo CallerFSI;
7420 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
7421 PVFormat->getFirstArg(), &CallerFSI))
7422 continue;
7423 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7424 // We also check if the formats are compatible.
7425 // We can't pass a 'scanf' string to a 'printf' function.
7426 if (Type != S.GetFormatStringType(PVFormat)) {
7427 S.Diag(Args[format_idx]->getBeginLoc(),
7428 diag::warn_format_string_type_incompatible)
7429 << PVFormat->getType()->getName()
7431 if (!InFunctionCall) {
7432 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
7433 }
7434 return SLCT_UncheckedLiteral;
7435 }
7436 // Lastly, check that argument passing kinds transition in a
7437 // way that makes sense:
7438 // from a caller with FAPK_VAList, allow FAPK_VAList
7439 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7440 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7441 // from a caller with FAPK_Variadic, allow FAPK_VAList
7442 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
7447 return SLCT_UncheckedLiteral;
7448 }
7449 }
7450 }
7451 }
7452 }
7453 }
7454
7455 return SLCT_NotALiteral;
7456 }
7457
7458 case Stmt::CallExprClass:
7459 case Stmt::CXXMemberCallExprClass: {
7460 const CallExpr *CE = cast<CallExpr>(E);
7461 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7462 bool IsFirst = true;
7463 StringLiteralCheckType CommonResult;
7464 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7465 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7466 StringLiteralCheckType Result = checkFormatStringExpr(
7467 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7468 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7469 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7470 if (IsFirst) {
7471 CommonResult = Result;
7472 IsFirst = false;
7473 }
7474 }
7475 if (!IsFirst)
7476 return CommonResult;
7477
7478 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7479 unsigned BuiltinID = FD->getBuiltinID();
7480 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7481 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7482 const Expr *Arg = CE->getArg(0);
7483 return checkFormatStringExpr(
7484 S, ReferenceFormatString, Arg, Args, APK, format_idx,
7485 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7486 UncoveredArg, Offset, CallerFormatParamIdx,
7487 IgnoreStringsWithoutSpecifiers);
7488 }
7489 }
7490 }
7491 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
7492 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7493 format_idx, firstDataArg, Type, CallType,
7494 /*InFunctionCall*/ false, CheckedVarArgs,
7495 UncoveredArg, Offset, CallerFormatParamIdx,
7496 IgnoreStringsWithoutSpecifiers);
7497 return SLCT_NotALiteral;
7498 }
7499 case Stmt::ObjCMessageExprClass: {
7500 const auto *ME = cast<ObjCMessageExpr>(E);
7501 if (const auto *MD = ME->getMethodDecl()) {
7502 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7503 // As a special case heuristic, if we're using the method -[NSBundle
7504 // localizedStringForKey:value:table:], ignore any key strings that lack
7505 // format specifiers. The idea is that if the key doesn't have any
7506 // format specifiers then its probably just a key to map to the
7507 // localized strings. If it does have format specifiers though, then its
7508 // likely that the text of the key is the format string in the
7509 // programmer's language, and should be checked.
7510 const ObjCInterfaceDecl *IFace;
7511 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7512 IFace->getIdentifier()->isStr("NSBundle") &&
7513 MD->getSelector().isKeywordSelector(
7514 {"localizedStringForKey", "value", "table"})) {
7515 IgnoreStringsWithoutSpecifiers = true;
7516 }
7517
7518 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7519 return checkFormatStringExpr(
7520 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7521 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7522 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7523 }
7524 }
7525
7526 return SLCT_NotALiteral;
7527 }
7528 case Stmt::ObjCStringLiteralClass:
7529 case Stmt::StringLiteralClass: {
7530 const StringLiteral *StrE = nullptr;
7531
7532 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7533 StrE = ObjCFExpr->getString();
7534 else
7535 StrE = cast<StringLiteral>(E);
7536
7537 if (StrE) {
7538 if (Offset.isNegative() || Offset > StrE->getLength()) {
7539 // TODO: It would be better to have an explicit warning for out of
7540 // bounds literals.
7541 return SLCT_NotALiteral;
7542 }
7543 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7544 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
7545 format_idx, firstDataArg, Type, InFunctionCall,
7546 CallType, CheckedVarArgs, UncoveredArg,
7547 IgnoreStringsWithoutSpecifiers);
7548 return SLCT_CheckedLiteral;
7549 }
7550
7551 return SLCT_NotALiteral;
7552 }
7553 case Stmt::BinaryOperatorClass: {
7554 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7555
7556 // A string literal + an int offset is still a string literal.
7557 if (BinOp->isAdditiveOp()) {
7558 Expr::EvalResult LResult, RResult;
7559
7560 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7561 LResult, S.Context, Expr::SE_NoSideEffects,
7563 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7564 RResult, S.Context, Expr::SE_NoSideEffects,
7566
7567 if (LIsInt != RIsInt) {
7568 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7569
7570 if (LIsInt) {
7571 if (BinOpKind == BO_Add) {
7572 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7573 E = BinOp->getRHS();
7574 goto tryAgain;
7575 }
7576 } else {
7577 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7578 E = BinOp->getLHS();
7579 goto tryAgain;
7580 }
7581 }
7582 }
7583
7584 return SLCT_NotALiteral;
7585 }
7586 case Stmt::UnaryOperatorClass: {
7587 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7588 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7589 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7590 Expr::EvalResult IndexResult;
7591 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7594 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7595 /*RHS is int*/ true);
7596 E = ASE->getBase();
7597 goto tryAgain;
7598 }
7599 }
7600
7601 return SLCT_NotALiteral;
7602 }
7603
7604 default:
7605 return SLCT_NotALiteral;
7606 }
7607}
7608
7609// If this expression can be evaluated at compile-time,
7610// check if the result is a StringLiteral and return it
7611// otherwise return nullptr
7613 const Expr *E) {
7615 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
7616 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7617 if (isa_and_nonnull<StringLiteral>(LVE))
7618 return LVE;
7619 }
7620 return nullptr;
7621}
7622
7624 switch (FST) {
7626 return "scanf";
7628 return "printf";
7630 return "NSString";
7632 return "strftime";
7634 return "strfmon";
7636 return "kprintf";
7638 return "freebsd_kprintf";
7640 return "os_log";
7641 default:
7642 return "<unknown>";
7643 }
7644}
7645
7647 return llvm::StringSwitch<FormatStringType>(Flavor)
7648 .Cases({"gnu_scanf", "scanf"}, FormatStringType::Scanf)
7649 .Cases({"gnu_printf", "printf", "printf0", "syslog"},
7651 .Cases({"NSString", "CFString"}, FormatStringType::NSString)
7652 .Cases({"gnu_strftime", "strftime"}, FormatStringType::Strftime)
7653 .Cases({"gnu_strfmon", "strfmon"}, FormatStringType::Strfmon)
7654 .Cases({"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7656 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
7657 .Case("os_trace", FormatStringType::OSLog)
7658 .Case("os_log", FormatStringType::OSLog)
7659 .Default(FormatStringType::Unknown);
7660}
7661
7663 return GetFormatStringType(Format->getType()->getName());
7664}
7665
7666FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7667 return GetFormatStringType(Format->getType()->getName());
7668}
7669
7670bool Sema::CheckFormatArguments(const FormatAttr *Format,
7671 ArrayRef<const Expr *> Args, bool IsCXXMember,
7672 VariadicCallType CallType, SourceLocation Loc,
7673 SourceRange Range,
7674 llvm::SmallBitVector &CheckedVarArgs) {
7675 FormatStringInfo FSI;
7676 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
7677 IsCXXMember,
7678 CallType != VariadicCallType::DoesNotApply, &FSI))
7679 return CheckFormatArguments(
7680 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
7681 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
7682 return false;
7683}
7684
7685bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7686 ArrayRef<const Expr *> Args, bool IsCXXMember,
7687 VariadicCallType CallType, SourceLocation Loc,
7688 SourceRange Range,
7689 llvm::SmallBitVector &CheckedVarArgs) {
7690 FormatStringInfo FSI;
7691 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
7692 &FSI)) {
7693 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7694 return CheckFormatArguments(Args, FSI.ArgPassingKind,
7695 Format->getFormatString(), FSI.FormatIdx,
7696 FSI.FirstDataArg, GetFormatStringType(Format),
7697 CallType, Loc, Range, CheckedVarArgs);
7698 }
7699 return false;
7700}
7701
7704 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7705 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7706 SourceLocation Loc) {
7707 if (S->getDiagnostics().isIgnored(diag::warn_missing_format_attribute, Loc))
7708 return false;
7709
7710 DeclContext *DC = S->CurContext;
7711 if (!isa<ObjCMethodDecl>(DC) && !isa<FunctionDecl>(DC) && !isa<BlockDecl>(DC))
7712 return false;
7713 Decl *Caller = cast<Decl>(DC)->getCanonicalDecl();
7714
7715 unsigned NumCallerParams = getFunctionOrMethodNumParams(Caller);
7716
7717 // Find the offset to convert between attribute and parameter indexes.
7718 unsigned CallerArgumentIndexOffset =
7719 hasImplicitObjectParameter(Caller) ? 2 : 1;
7720
7721 unsigned FirstArgumentIndex = -1;
7722 switch (APK) {
7725 // As an extension, clang allows the format attribute on non-variadic
7726 // functions.
7727 // Caller must have fixed arguments to pass them to a fixed or variadic
7728 // function. Try to match caller and callee arguments. If successful, then
7729 // emit a diag with the caller idx, otherwise we can't determine the callee
7730 // arguments.
7731 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7732 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7733 // There aren't enough arguments in the caller to pass to callee.
7734 return false;
7735 }
7736 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7737 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7738 const auto *Arg =
7739 dyn_cast<DeclRefExpr>(Args[CalleeIdx]->IgnoreParenCasts());
7740 if (!Arg)
7741 return false;
7742 const auto *Param = dyn_cast<ParmVarDecl>(Arg->getDecl());
7743 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7744 return false;
7745 }
7746 FirstArgumentIndex =
7747 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7748 break;
7749 }
7751 // Caller arguments are either variadic or a va_list.
7752 FirstArgumentIndex = isFunctionOrMethodVariadic(Caller)
7753 ? (NumCallerParams + CallerArgumentIndexOffset)
7754 : 0;
7755 break;
7757 // The callee has a format_matches attribute. We will emit that instead.
7758 if (!ReferenceFormatString)
7759 return false;
7760 break;
7761 }
7762
7763 // Emit the diagnostic and fixit.
7764 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7765 StringRef FormatTypeName = S->GetFormatStringTypeName(FormatType);
7766 NamedDecl *ND = dyn_cast<NamedDecl>(Caller);
7767 do {
7768 std::string Attr, Fixit;
7769 llvm::raw_string_ostream AttrOS(Attr);
7771 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7772 << FirstArgumentIndex << ")";
7773 } else {
7774 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7775 << ", \"";
7776 AttrOS.write_escaped(ReferenceFormatString->getString());
7777 AttrOS << "\")";
7778 }
7779 AttrOS.flush();
7780 auto DB = S->Diag(Loc, diag::warn_missing_format_attribute) << Attr;
7781 if (ND)
7782 DB << ND;
7783 else
7784 DB << "block";
7785
7786 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7787 if (isa<BlockDecl>(Caller))
7788 break;
7789
7790 SourceLocation SL;
7791 llvm::raw_string_ostream IS(Fixit);
7792 // The attribute goes at the start of the declaration in C/C++ functions
7793 // and methods, but after the declaration for Objective-C methods.
7794 if (isa<ObjCMethodDecl>(Caller)) {
7795 IS << ' ';
7796 SL = Caller->getEndLoc();
7797 }
7798 const LangOptions &LO = S->getLangOpts();
7799 if (LO.C23 || LO.CPlusPlus11)
7800 IS << "[[gnu::" << Attr << "]]";
7801 else if (LO.ObjC || LO.GNUMode)
7802 IS << "__attribute__((" << Attr << "))";
7803 else
7804 break;
7805 if (!isa<ObjCMethodDecl>(Caller)) {
7806 IS << ' ';
7807 SL = Caller->getBeginLoc();
7808 }
7809 IS.flush();
7810
7811 DB << FixItHint::CreateInsertion(SL, Fixit);
7812 } while (false);
7813
7814 // Add implicit format or format_matches attribute.
7816 Caller->addAttr(FormatAttr::CreateImplicit(
7817 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7818 FormatStringIndex, FirstArgumentIndex));
7819 } else {
7820 Caller->addAttr(FormatMatchesAttr::CreateImplicit(
7821 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7822 FormatStringIndex, ReferenceFormatString));
7823 }
7824
7825 {
7826 auto DB = S->Diag(Caller->getLocation(), diag::note_entity_declared_at);
7827 if (ND)
7828 DB << ND;
7829 else
7830 DB << "block";
7831 }
7832 return true;
7833}
7834
7835bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7837 StringLiteral *ReferenceFormatString,
7838 unsigned format_idx, unsigned firstDataArg,
7840 VariadicCallType CallType, SourceLocation Loc,
7841 SourceRange Range,
7842 llvm::SmallBitVector &CheckedVarArgs) {
7843 // CHECK: printf/scanf-like function is called with no format string.
7844 if (format_idx >= Args.size()) {
7845 Diag(Loc, diag::warn_missing_format_string) << Range;
7846 return false;
7847 }
7848
7849 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7850
7851 // CHECK: format string is not a string literal.
7852 //
7853 // Dynamically generated format strings are difficult to
7854 // automatically vet at compile time. Requiring that format strings
7855 // are string literals: (1) permits the checking of format strings by
7856 // the compiler and thereby (2) can practically remove the source of
7857 // many format string exploits.
7858
7859 // Format string can be either ObjC string (e.g. @"%d") or
7860 // C string (e.g. "%d")
7861 // ObjC string uses the same format specifiers as C string, so we can use
7862 // the same format string checking logic for both ObjC and C strings.
7863 UncoveredArgHandler UncoveredArg;
7864 std::optional<unsigned> CallerParamIdx;
7865 StringLiteralCheckType CT = checkFormatStringExpr(
7866 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
7867 firstDataArg, Type, CallType,
7868 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
7869 /*no string offset*/ llvm::APSInt(64, false) = 0, &CallerParamIdx);
7870
7871 // Generate a diagnostic where an uncovered argument is detected.
7872 if (UncoveredArg.hasUncoveredArg()) {
7873 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7874 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7875 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7876 }
7877
7878 if (CT != SLCT_NotALiteral)
7879 // Literal format string found, check done!
7880 return CT == SLCT_CheckedLiteral;
7881
7882 // Do not emit diag when the string param is a macro expansion and the
7883 // format is either NSString or CFString. This is a hack to prevent
7884 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7885 // which are usually used in place of NS and CF string literals.
7886 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7888 SourceMgr.isInSystemMacro(FormatLoc))
7889 return false;
7890
7891 if (CallerParamIdx && CheckMissingFormatAttribute(
7892 this, Args, APK, ReferenceFormatString, format_idx,
7893 firstDataArg, Type, *CallerParamIdx, Loc))
7894 return false;
7895
7896 // Strftime is particular as it always uses a single 'time' argument,
7897 // so it is safe to pass a non-literal string.
7899 return false;
7900
7901 // If there are no arguments specified, warn with -Wformat-security, otherwise
7902 // warn only with -Wformat-nonliteral.
7903 if (Args.size() == firstDataArg) {
7904 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7905 << OrigFormatExpr->getSourceRange();
7906 switch (Type) {
7907 default:
7908 break;
7912 Diag(FormatLoc, diag::note_format_security_fixit)
7913 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7914 break;
7916 Diag(FormatLoc, diag::note_format_security_fixit)
7917 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7918 break;
7919 }
7920 } else {
7921 Diag(FormatLoc, diag::warn_format_nonliteral)
7922 << OrigFormatExpr->getSourceRange();
7923 }
7924 return false;
7925}
7926
7927namespace {
7928
7929class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7930protected:
7931 Sema &S;
7932 const FormatStringLiteral *FExpr;
7933 const Expr *OrigFormatExpr;
7934 const FormatStringType FSType;
7935 const unsigned FirstDataArg;
7936 const unsigned NumDataArgs;
7937 const char *Beg; // Start of format string.
7938 const Sema::FormatArgumentPassingKind ArgPassingKind;
7939 ArrayRef<const Expr *> Args;
7940 unsigned FormatIdx;
7941 llvm::SmallBitVector CoveredArgs;
7942 bool usesPositionalArgs = false;
7943 bool atFirstArg = true;
7944 bool inFunctionCall;
7945 VariadicCallType CallType;
7946 llvm::SmallBitVector &CheckedVarArgs;
7947 UncoveredArgHandler &UncoveredArg;
7948
7949public:
7950 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7951 const Expr *origFormatExpr, const FormatStringType type,
7952 unsigned firstDataArg, unsigned numDataArgs,
7953 const char *beg, Sema::FormatArgumentPassingKind APK,
7954 ArrayRef<const Expr *> Args, unsigned formatIdx,
7955 bool inFunctionCall, VariadicCallType callType,
7956 llvm::SmallBitVector &CheckedVarArgs,
7957 UncoveredArgHandler &UncoveredArg)
7958 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7959 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7960 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7961 inFunctionCall(inFunctionCall), CallType(callType),
7962 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7963 CoveredArgs.resize(numDataArgs);
7964 CoveredArgs.reset();
7965 }
7966
7967 bool HasFormatArguments() const {
7968 return ArgPassingKind == Sema::FAPK_Fixed ||
7969 ArgPassingKind == Sema::FAPK_Variadic;
7970 }
7971
7972 void DoneProcessing();
7973
7974 void HandleIncompleteSpecifier(const char *startSpecifier,
7975 unsigned specifierLen) override;
7976
7977 void HandleInvalidLengthModifier(
7978 const analyze_format_string::FormatSpecifier &FS,
7979 const analyze_format_string::ConversionSpecifier &CS,
7980 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
7981
7982 void HandleNonStandardLengthModifier(
7983 const analyze_format_string::FormatSpecifier &FS,
7984 const char *startSpecifier, unsigned specifierLen);
7985
7986 void HandleNonStandardConversionSpecifier(
7987 const analyze_format_string::ConversionSpecifier &CS,
7988 const char *startSpecifier, unsigned specifierLen);
7989
7990 void HandlePosition(const char *startPos, unsigned posLen) override;
7991
7992 void HandleInvalidPosition(const char *startSpecifier, unsigned specifierLen,
7994
7995 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7996
7997 void HandleNullChar(const char *nullCharacter) override;
7998
7999 template <typename Range>
8000 static void
8001 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8002 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8003 bool IsStringLocation, Range StringRange,
8004 ArrayRef<FixItHint> Fixit = {});
8005
8006protected:
8007 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8008 const char *startSpec,
8009 unsigned specifierLen,
8010 const char *csStart, unsigned csLen);
8011
8012 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8013 const char *startSpec,
8014 unsigned specifierLen);
8015
8016 SourceRange getFormatStringRange();
8017 CharSourceRange getSpecifierRange(const char *startSpecifier,
8018 unsigned specifierLen);
8019 SourceLocation getLocationOfByte(const char *x);
8020
8021 const Expr *getDataArg(unsigned i) const;
8022
8023 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8024 const analyze_format_string::ConversionSpecifier &CS,
8025 const char *startSpecifier, unsigned specifierLen,
8026 unsigned argIndex);
8027
8028 bool CheckUnsupportedType(const analyze_format_string::ArgType &AT,
8029 const Expr *E, const char *startSpecifier,
8030 unsigned specifierLen);
8031
8032 template <typename Range>
8033 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8034 bool IsStringLocation, Range StringRange,
8035 ArrayRef<FixItHint> Fixit = {});
8036};
8037
8038} // namespace
8039
8040SourceRange CheckFormatHandler::getFormatStringRange() {
8041 return OrigFormatExpr->getSourceRange();
8042}
8043
8045CheckFormatHandler::getSpecifierRange(const char *startSpecifier,
8046 unsigned specifierLen) {
8047 SourceLocation Start = getLocationOfByte(startSpecifier);
8048 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
8049
8050 // Advance the end SourceLocation by one due to half-open ranges.
8051 End = End.getLocWithOffset(1);
8052
8053 return CharSourceRange::getCharRange(Start, End);
8054}
8055
8056SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8057 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8059}
8060
8061void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8062 unsigned specifierLen) {
8063 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8064 getLocationOfByte(startSpecifier),
8065 /*IsStringLocation*/ true,
8066 getSpecifierRange(startSpecifier, specifierLen));
8067}
8068
8069bool CheckFormatHandler::CheckUnsupportedType(
8070 const analyze_format_string::ArgType &AT, const Expr *E,
8071 const char *StartSpecifier, unsigned SpecifierLen) {
8072 if (!AT.isUnsupported())
8073 return false;
8074
8075 EmitFormatDiagnostic(S.PDiag(diag::warn_format_unsupported_type)
8077 E->getExprLoc(), /*IsStringLocation=*/false,
8078 getSpecifierRange(StartSpecifier, SpecifierLen));
8079 return true;
8080}
8081
8082void CheckFormatHandler::HandleInvalidLengthModifier(
8085 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8086 using namespace analyze_format_string;
8087
8088 const LengthModifier &LM = FS.getLengthModifier();
8089 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8090
8091 // See if we know how to fix this length modifier.
8092 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8093 if (FixedLM) {
8094 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8095 getLocationOfByte(LM.getStart()),
8096 /*IsStringLocation*/ true,
8097 getSpecifierRange(startSpecifier, specifierLen));
8098
8099 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8100 << FixedLM->toString()
8101 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8102
8103 } else {
8104 FixItHint Hint;
8105 if (DiagID == diag::warn_format_nonsensical_length)
8106 Hint = FixItHint::CreateRemoval(LMRange);
8107
8108 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8109 getLocationOfByte(LM.getStart()),
8110 /*IsStringLocation*/ true,
8111 getSpecifierRange(startSpecifier, specifierLen), Hint);
8112 }
8113}
8114
8115void CheckFormatHandler::HandleNonStandardLengthModifier(
8117 const char *startSpecifier, unsigned specifierLen) {
8118 using namespace analyze_format_string;
8119
8120 const LengthModifier &LM = FS.getLengthModifier();
8121 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8122
8123 // See if we know how to fix this length modifier.
8124 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8125 if (FixedLM) {
8126 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8127 << LM.toString() << 0,
8128 getLocationOfByte(LM.getStart()),
8129 /*IsStringLocation*/ true,
8130 getSpecifierRange(startSpecifier, specifierLen));
8131
8132 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8133 << FixedLM->toString()
8134 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8135
8136 } else {
8137 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8138 << LM.toString() << 0,
8139 getLocationOfByte(LM.getStart()),
8140 /*IsStringLocation*/ true,
8141 getSpecifierRange(startSpecifier, specifierLen));
8142 }
8143}
8144
8145void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8147 const char *startSpecifier, unsigned specifierLen) {
8148 using namespace analyze_format_string;
8149
8150 // See if we know how to fix this conversion specifier.
8151 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8152 if (FixedCS) {
8153 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8154 << CS.toString() << /*conversion specifier*/ 1,
8155 getLocationOfByte(CS.getStart()),
8156 /*IsStringLocation*/ true,
8157 getSpecifierRange(startSpecifier, specifierLen));
8158
8159 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8160 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8161 << FixedCS->toString()
8162 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8163 } else {
8164 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8165 << CS.toString() << /*conversion specifier*/ 1,
8166 getLocationOfByte(CS.getStart()),
8167 /*IsStringLocation*/ true,
8168 getSpecifierRange(startSpecifier, specifierLen));
8169 }
8170}
8171
8172void CheckFormatHandler::HandlePosition(const char *startPos, unsigned posLen) {
8173 if (!S.getDiagnostics().isIgnored(
8174 diag::warn_format_non_standard_positional_arg, SourceLocation()))
8175 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8176 getLocationOfByte(startPos),
8177 /*IsStringLocation*/ true,
8178 getSpecifierRange(startPos, posLen));
8179}
8180
8181void CheckFormatHandler::HandleInvalidPosition(
8182 const char *startSpecifier, unsigned specifierLen,
8184 if (!S.getDiagnostics().isIgnored(
8185 diag::warn_format_invalid_positional_specifier, SourceLocation()))
8186 EmitFormatDiagnostic(
8187 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
8188 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
8189 getSpecifierRange(startSpecifier, specifierLen));
8190}
8191
8192void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8193 unsigned posLen) {
8194 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
8195 SourceLocation()))
8196 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8197 getLocationOfByte(startPos),
8198 /*IsStringLocation*/ true,
8199 getSpecifierRange(startPos, posLen));
8200}
8201
8202void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8203 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8204 // The presence of a null character is likely an error.
8205 EmitFormatDiagnostic(
8206 S.PDiag(diag::warn_printf_format_string_contains_null_char),
8207 getLocationOfByte(nullCharacter), /*IsStringLocation*/ true,
8208 getFormatStringRange());
8209 }
8210}
8211
8212// Note that this may return NULL if there was an error parsing or building
8213// one of the argument expressions.
8214const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8215 return Args[FirstDataArg + i];
8216}
8217
8218void CheckFormatHandler::DoneProcessing() {
8219 // Does the number of data arguments exceed the number of
8220 // format conversions in the format string?
8221 if (HasFormatArguments()) {
8222 // Find any arguments that weren't covered.
8223 CoveredArgs.flip();
8224 signed notCoveredArg = CoveredArgs.find_first();
8225 if (notCoveredArg >= 0) {
8226 assert((unsigned)notCoveredArg < NumDataArgs);
8227 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8228 } else {
8229 UncoveredArg.setAllCovered();
8230 }
8231 }
8232}
8233
8234void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8235 const Expr *ArgExpr) {
8236 assert(hasUncoveredArg() && !DiagnosticExprs.empty() && "Invalid state");
8237
8238 if (!ArgExpr)
8239 return;
8240
8241 SourceLocation Loc = ArgExpr->getBeginLoc();
8242
8243 if (S.getSourceManager().isInSystemMacro(Loc))
8244 return;
8245
8246 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8247 for (auto E : DiagnosticExprs)
8248 PDiag << E->getSourceRange();
8249
8250 CheckFormatHandler::EmitFormatDiagnostic(
8251 S, IsFunctionCall, DiagnosticExprs[0], PDiag, Loc,
8252 /*IsStringLocation*/ false, DiagnosticExprs[0]->getSourceRange());
8253}
8254
8255bool CheckFormatHandler::HandleInvalidConversionSpecifier(
8256 unsigned argIndex, SourceLocation Loc, const char *startSpec,
8257 unsigned specifierLen, const char *csStart, unsigned csLen) {
8258 bool keepGoing = true;
8259 if (argIndex < NumDataArgs) {
8260 // Consider the argument coverered, even though the specifier doesn't
8261 // make sense.
8262 CoveredArgs.set(argIndex);
8263 } else {
8264 // If argIndex exceeds the number of data arguments we
8265 // don't issue a warning because that is just a cascade of warnings (and
8266 // they may have intended '%%' anyway). We don't want to continue processing
8267 // the format string after this point, however, as we will like just get
8268 // gibberish when trying to match arguments.
8269 keepGoing = false;
8270 }
8271
8272 StringRef Specifier(csStart, csLen);
8273
8274 // If the specifier in non-printable, it could be the first byte of a UTF-8
8275 // sequence. In that case, print the UTF-8 code point. If not, print the byte
8276 // hex value.
8277 std::string CodePointStr;
8278 if (!llvm::sys::locale::isPrint(*csStart)) {
8279 llvm::UTF32 CodePoint;
8280 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8281 const llvm::UTF8 *E = reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8282 llvm::ConversionResult Result =
8283 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8284
8285 if (Result != llvm::conversionOK) {
8286 unsigned char FirstChar = *csStart;
8287 CodePoint = (llvm::UTF32)FirstChar;
8288 }
8289
8290 llvm::raw_string_ostream OS(CodePointStr);
8291 if (CodePoint < 256)
8292 OS << "\\x" << llvm::format("%02x", CodePoint);
8293 else if (CodePoint <= 0xFFFF)
8294 OS << "\\u" << llvm::format("%04x", CodePoint);
8295 else
8296 OS << "\\U" << llvm::format("%08x", CodePoint);
8297 Specifier = CodePointStr;
8298 }
8299
8300 EmitFormatDiagnostic(
8301 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8302 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8303
8304 return keepGoing;
8305}
8306
8307void CheckFormatHandler::HandlePositionalNonpositionalArgs(
8308 SourceLocation Loc, const char *startSpec, unsigned specifierLen) {
8309 EmitFormatDiagnostic(
8310 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), Loc,
8311 /*isStringLoc*/ true, getSpecifierRange(startSpec, specifierLen));
8312}
8313
8314bool CheckFormatHandler::CheckNumArgs(
8317 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8318
8319 if (HasFormatArguments() && argIndex >= NumDataArgs) {
8320 PartialDiagnostic PDiag =
8322 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8323 << (argIndex + 1) << NumDataArgs)
8324 : S.PDiag(diag::warn_printf_insufficient_data_args);
8325 EmitFormatDiagnostic(PDiag, getLocationOfByte(CS.getStart()),
8326 /*IsStringLocation*/ true,
8327 getSpecifierRange(startSpecifier, specifierLen));
8328
8329 // Since more arguments than conversion tokens are given, by extension
8330 // all arguments are covered, so mark this as so.
8331 UncoveredArg.setAllCovered();
8332 return false;
8333 }
8334 return true;
8335}
8336
8337template <typename Range>
8338void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8339 SourceLocation Loc,
8340 bool IsStringLocation,
8341 Range StringRange,
8342 ArrayRef<FixItHint> FixIt) {
8343 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, Loc,
8344 IsStringLocation, StringRange, FixIt);
8345}
8346
8347/// If the format string is not within the function call, emit a note
8348/// so that the function call and string are in diagnostic messages.
8349///
8350/// \param InFunctionCall if true, the format string is within the function
8351/// call and only one diagnostic message will be produced. Otherwise, an
8352/// extra note will be emitted pointing to location of the format string.
8353///
8354/// \param ArgumentExpr the expression that is passed as the format string
8355/// argument in the function call. Used for getting locations when two
8356/// diagnostics are emitted.
8357///
8358/// \param PDiag the callee should already have provided any strings for the
8359/// diagnostic message. This function only adds locations and fixits
8360/// to diagnostics.
8361///
8362/// \param Loc primary location for diagnostic. If two diagnostics are
8363/// required, one will be at Loc and a new SourceLocation will be created for
8364/// the other one.
8365///
8366/// \param IsStringLocation if true, Loc points to the format string should be
8367/// used for the note. Otherwise, Loc points to the argument list and will
8368/// be used with PDiag.
8369///
8370/// \param StringRange some or all of the string to highlight. This is
8371/// templated so it can accept either a CharSourceRange or a SourceRange.
8372///
8373/// \param FixIt optional fix it hint for the format string.
8374template <typename Range>
8375void CheckFormatHandler::EmitFormatDiagnostic(
8376 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8377 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8378 Range StringRange, ArrayRef<FixItHint> FixIt) {
8379 if (InFunctionCall) {
8380 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8381 D << StringRange;
8382 D << FixIt;
8383 } else {
8384 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8385 << ArgumentExpr->getSourceRange();
8386
8388 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8389 diag::note_format_string_defined);
8390
8391 Note << StringRange;
8392 Note << FixIt;
8393 }
8394}
8395
8396//===--- CHECK: Printf format string checking -----------------------------===//
8397
8398namespace {
8399
8400class CheckPrintfHandler : public CheckFormatHandler {
8401public:
8402 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8403 const Expr *origFormatExpr, const FormatStringType type,
8404 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8405 const char *beg, Sema::FormatArgumentPassingKind APK,
8406 ArrayRef<const Expr *> Args, unsigned formatIdx,
8407 bool inFunctionCall, VariadicCallType CallType,
8408 llvm::SmallBitVector &CheckedVarArgs,
8409 UncoveredArgHandler &UncoveredArg)
8410 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8411 numDataArgs, beg, APK, Args, formatIdx,
8412 inFunctionCall, CallType, CheckedVarArgs,
8413 UncoveredArg) {}
8414
8415 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8416
8417 /// Returns true if '%@' specifiers are allowed in the format string.
8418 bool allowsObjCArg() const {
8419 return FSType == FormatStringType::NSString ||
8420 FSType == FormatStringType::OSLog ||
8421 FSType == FormatStringType::OSTrace;
8422 }
8423
8424 bool HandleInvalidPrintfConversionSpecifier(
8425 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8426 unsigned specifierLen) override;
8427
8428 void handleInvalidMaskType(StringRef MaskType) override;
8429
8430 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8431 const char *startSpecifier, unsigned specifierLen,
8432 const TargetInfo &Target) override;
8433 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8434 const char *StartSpecifier, unsigned SpecifierLen,
8435 const Expr *E);
8436
8437 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt,
8438 unsigned k, const char *startSpecifier,
8439 unsigned specifierLen);
8440 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8441 const analyze_printf::OptionalAmount &Amt,
8442 unsigned type, const char *startSpecifier,
8443 unsigned specifierLen);
8444 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8445 const analyze_printf::OptionalFlag &flag,
8446 const char *startSpecifier, unsigned specifierLen);
8447 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8448 const analyze_printf::OptionalFlag &ignoredFlag,
8449 const analyze_printf::OptionalFlag &flag,
8450 const char *startSpecifier, unsigned specifierLen);
8451 bool checkForCStrMembers(const analyze_printf::ArgType &AT, const Expr *E);
8452
8453 void HandleEmptyObjCModifierFlag(const char *startFlag,
8454 unsigned flagLen) override;
8455
8456 void HandleInvalidObjCModifierFlag(const char *startFlag,
8457 unsigned flagLen) override;
8458
8459 void
8460 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8461 const char *flagsEnd,
8462 const char *conversionPosition) override;
8463};
8464
8465/// Keeps around the information needed to verify that two specifiers are
8466/// compatible.
8467class EquatableFormatArgument {
8468public:
8469 enum SpecifierSensitivity : unsigned {
8470 SS_None,
8471 SS_Private,
8472 SS_Public,
8473 SS_Sensitive
8474 };
8475
8476 enum FormatArgumentRole : unsigned {
8477 FAR_Data,
8478 FAR_FieldWidth,
8479 FAR_Precision,
8480 FAR_Auxiliary, // FreeBSD kernel %b and %D
8481 };
8482
8483private:
8484 analyze_format_string::ArgType ArgType;
8485 analyze_format_string::LengthModifier LengthMod;
8486 StringRef SpecifierLetter;
8487 CharSourceRange Range;
8488 SourceLocation ElementLoc;
8489 FormatArgumentRole Role : 2;
8490 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8491 unsigned Position : 14;
8492 unsigned ModifierFor : 14; // not set for FAR_Data
8493
8494 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8495 bool InFunctionCall) const;
8496
8497public:
8498 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8499 analyze_format_string::LengthModifier LengthMod,
8500 StringRef SpecifierLetter,
8501 analyze_format_string::ArgType ArgType,
8502 FormatArgumentRole Role,
8503 SpecifierSensitivity Sensitivity, unsigned Position,
8504 unsigned ModifierFor)
8505 : ArgType(ArgType), LengthMod(LengthMod),
8506 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8507 Role(Role), Sensitivity(Sensitivity), Position(Position),
8508 ModifierFor(ModifierFor) {}
8509
8510 unsigned getPosition() const { return Position; }
8511 SourceLocation getSourceLocation() const { return ElementLoc; }
8512 CharSourceRange getSourceRange() const { return Range; }
8513 analyze_format_string::LengthModifier getLengthModifier() const {
8514 return LengthMod;
8515 }
8516 void setModifierFor(unsigned V) { ModifierFor = V; }
8517
8518 std::string buildFormatSpecifier() const {
8519 std::string result;
8520 llvm::raw_string_ostream(result)
8521 << getLengthModifier().toString() << SpecifierLetter;
8522 return result;
8523 }
8524
8525 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8526 const Expr *FmtExpr, bool InFunctionCall) const;
8527};
8528
8529/// Turns format strings into lists of EquatableSpecifier objects.
8530class DecomposePrintfHandler : public CheckPrintfHandler {
8531 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8532 bool HadError;
8533
8534 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8535 const Expr *origFormatExpr,
8536 const FormatStringType type, unsigned firstDataArg,
8537 unsigned numDataArgs, bool isObjC, const char *beg,
8539 ArrayRef<const Expr *> Args, unsigned formatIdx,
8540 bool inFunctionCall, VariadicCallType CallType,
8541 llvm::SmallBitVector &CheckedVarArgs,
8542 UncoveredArgHandler &UncoveredArg,
8543 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8544 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8545 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8546 inFunctionCall, CallType, CheckedVarArgs,
8547 UncoveredArg),
8548 Specs(Specs), HadError(false) {}
8549
8550public:
8551 static bool
8552 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8553 FormatStringType type, bool IsObjC, bool InFunctionCall,
8554 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8555
8556 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8557 const char *startSpecifier,
8558 unsigned specifierLen,
8559 const TargetInfo &Target) override;
8560};
8561
8562} // namespace
8563
8564bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8565 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8566 unsigned specifierLen) {
8569
8570 return HandleInvalidConversionSpecifier(
8571 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
8572 specifierLen, CS.getStart(), CS.getLength());
8573}
8574
8575void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8576 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8577}
8578
8579// Error out if struct or complex type argments are passed to os_log.
8581 QualType T) {
8582 if (FSType != FormatStringType::OSLog)
8583 return false;
8584 return T->isRecordType() || T->isComplexType();
8585}
8586
8587bool CheckPrintfHandler::HandleAmount(
8588 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8589 const char *startSpecifier, unsigned specifierLen) {
8590 if (Amt.hasDataArgument()) {
8591 if (HasFormatArguments()) {
8592 unsigned argIndex = Amt.getArgIndex();
8593 if (argIndex >= NumDataArgs) {
8594 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8595 << k,
8596 getLocationOfByte(Amt.getStart()),
8597 /*IsStringLocation*/ true,
8598 getSpecifierRange(startSpecifier, specifierLen));
8599 // Don't do any more checking. We will just emit
8600 // spurious errors.
8601 return false;
8602 }
8603
8604 // Type check the data argument. It should be an 'int'.
8605 // Although not in conformance with C99, we also allow the argument to be
8606 // an 'unsigned int' as that is a reasonably safe case. GCC also
8607 // doesn't emit a warning for that case.
8608 CoveredArgs.set(argIndex);
8609 const Expr *Arg = getDataArg(argIndex);
8610 if (!Arg)
8611 return false;
8612
8613 QualType T = Arg->getType();
8614
8615 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8616 assert(AT.isValid());
8617
8618 if (!AT.matchesType(S.Context, T)) {
8619 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8620 ? diag::err_printf_asterisk_wrong_type
8621 : diag::warn_printf_asterisk_wrong_type;
8622 EmitFormatDiagnostic(S.PDiag(DiagID)
8624 << T << Arg->getSourceRange(),
8625 getLocationOfByte(Amt.getStart()),
8626 /*IsStringLocation*/ true,
8627 getSpecifierRange(startSpecifier, specifierLen));
8628 // Don't do any more checking. We will just emit
8629 // spurious errors.
8630 return false;
8631 }
8632 }
8633 }
8634 return true;
8635}
8636
8637void CheckPrintfHandler::HandleInvalidAmount(
8639 const analyze_printf::OptionalAmount &Amt, unsigned type,
8640 const char *startSpecifier, unsigned specifierLen) {
8643
8644 FixItHint fixit =
8647 getSpecifierRange(Amt.getStart(), Amt.getConstantLength()))
8648 : FixItHint();
8649
8650 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8651 << type << CS.toString(),
8652 getLocationOfByte(Amt.getStart()),
8653 /*IsStringLocation*/ true,
8654 getSpecifierRange(startSpecifier, specifierLen), fixit);
8655}
8656
8657void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8658 const analyze_printf::OptionalFlag &flag,
8659 const char *startSpecifier,
8660 unsigned specifierLen) {
8661 // Warn about pointless flag with a fixit removal.
8664 EmitFormatDiagnostic(
8665 S.PDiag(diag::warn_printf_nonsensical_flag)
8666 << flag.toString() << CS.toString(),
8667 getLocationOfByte(flag.getPosition()),
8668 /*IsStringLocation*/ true,
8669 getSpecifierRange(startSpecifier, specifierLen),
8670 FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1)));
8671}
8672
8673void CheckPrintfHandler::HandleIgnoredFlag(
8675 const analyze_printf::OptionalFlag &ignoredFlag,
8676 const analyze_printf::OptionalFlag &flag, const char *startSpecifier,
8677 unsigned specifierLen) {
8678 // Warn about ignored flag with a fixit removal.
8679 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8680 << ignoredFlag.toString() << flag.toString(),
8681 getLocationOfByte(ignoredFlag.getPosition()),
8682 /*IsStringLocation*/ true,
8683 getSpecifierRange(startSpecifier, specifierLen),
8685 getSpecifierRange(ignoredFlag.getPosition(), 1)));
8686}
8687
8688void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8689 unsigned flagLen) {
8690 // Warn about an empty flag.
8691 EmitFormatDiagnostic(
8692 S.PDiag(diag::warn_printf_empty_objc_flag), getLocationOfByte(startFlag),
8693 /*IsStringLocation*/ true, getSpecifierRange(startFlag, flagLen));
8694}
8695
8696void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8697 unsigned flagLen) {
8698 // Warn about an invalid flag.
8699 auto Range = getSpecifierRange(startFlag, flagLen);
8700 StringRef flag(startFlag, flagLen);
8701 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8702 getLocationOfByte(startFlag),
8703 /*IsStringLocation*/ true, Range,
8705}
8706
8707void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8708 const char *flagsStart, const char *flagsEnd,
8709 const char *conversionPosition) {
8710 // Warn about using '[...]' without a '@' conversion.
8711 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8712 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8713 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8714 getLocationOfByte(conversionPosition),
8715 /*IsStringLocation*/ true, Range,
8717}
8718
8719void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8720 const Expr *FmtExpr,
8721 bool InFunctionCall) const {
8722 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
8723 ElementLoc, true, Range);
8724}
8725
8726bool EquatableFormatArgument::VerifyCompatible(
8727 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8728 bool InFunctionCall) const {
8730 if (Role != Other.Role) {
8731 // diagnose and stop
8732 EmitDiagnostic(
8733 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8734 FmtExpr, InFunctionCall);
8735 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8736 return false;
8737 }
8738
8739 if (Role != FAR_Data) {
8740 if (ModifierFor != Other.ModifierFor) {
8741 // diagnose and stop
8742 EmitDiagnostic(S,
8743 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
8744 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8745 FmtExpr, InFunctionCall);
8746 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8747 return false;
8748 }
8749 return true;
8750 }
8751
8752 bool HadError = false;
8753 if (Sensitivity != Other.Sensitivity) {
8754 // diagnose and continue
8755 EmitDiagnostic(S,
8756 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
8757 << Sensitivity << Other.Sensitivity,
8758 FmtExpr, InFunctionCall);
8759 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8760 << 0 << Other.Range;
8761 }
8762
8763 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
8764 case MK::Match:
8765 break;
8766
8767 case MK::MatchPromotion:
8768 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8769 // MatchPromotion is treated as a failure by format_matches.
8770 case MK::NoMatch:
8771 case MK::NoMatchTypeConfusion:
8772 case MK::NoMatchPromotionTypeConfusion:
8773 EmitDiagnostic(S,
8774 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
8775 << buildFormatSpecifier()
8776 << Other.buildFormatSpecifier(),
8777 FmtExpr, InFunctionCall);
8778 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8779 << 0 << Other.Range;
8780 break;
8781
8782 case MK::NoMatchPedantic:
8783 EmitDiagnostic(S,
8784 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
8785 << buildFormatSpecifier()
8786 << Other.buildFormatSpecifier(),
8787 FmtExpr, InFunctionCall);
8788 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8789 << 0 << Other.Range;
8790 break;
8791
8792 case MK::NoMatchSignedness:
8793 EmitDiagnostic(S,
8794 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
8795 << buildFormatSpecifier()
8796 << Other.buildFormatSpecifier(),
8797 FmtExpr, InFunctionCall);
8798 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8799 << 0 << Other.Range;
8800 break;
8801 }
8802 return !HadError;
8803}
8804
8805bool DecomposePrintfHandler::GetSpecifiers(
8806 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8807 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8809 StringRef Data = FSL->getString();
8810 const char *Str = Data.data();
8811 llvm::SmallBitVector BV;
8812 UncoveredArgHandler UA;
8813 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8814 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8815 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8816 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8817 UA, Args);
8818
8820 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
8822 H.DoneProcessing();
8823 if (H.HadError)
8824 return false;
8825
8826 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
8827 const EquatableFormatArgument &B) {
8828 return A.getPosition() < B.getPosition();
8829 });
8830 return true;
8831}
8832
8833bool DecomposePrintfHandler::HandlePrintfSpecifier(
8834 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8835 unsigned specifierLen, const TargetInfo &Target) {
8836 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8837 specifierLen, Target)) {
8838 HadError = true;
8839 return false;
8840 }
8841
8842 // Do not add any specifiers to the list for %%. This is possibly incorrect
8843 // if using a precision/width with a data argument, but that combination is
8844 // meaningless and we wouldn't know which format to attach the
8845 // precision/width to.
8846 const auto &CS = FS.getConversionSpecifier();
8848 return true;
8849
8850 // have to patch these to have the right ModifierFor if they are used
8851 const unsigned Unset = ~0;
8852 unsigned FieldWidthIndex = Unset;
8853 unsigned PrecisionIndex = Unset;
8854
8855 // field width?
8856 const auto &FieldWidth = FS.getFieldWidth();
8857 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8858 FieldWidthIndex = Specs.size();
8859 Specs.emplace_back(
8860 getSpecifierRange(startSpecifier, specifierLen),
8861 getLocationOfByte(FieldWidth.getStart()),
8862 analyze_format_string::LengthModifier(), FieldWidth.getCharacters(),
8863 FieldWidth.getArgType(S.Context),
8864 EquatableFormatArgument::FAR_FieldWidth,
8865 EquatableFormatArgument::SS_None,
8866 FieldWidth.usesPositionalArg() ? FieldWidth.getPositionalArgIndex() - 1
8867 : FieldWidthIndex,
8868 0);
8869 }
8870 // precision?
8871 const auto &Precision = FS.getPrecision();
8872 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8873 PrecisionIndex = Specs.size();
8874 Specs.emplace_back(
8875 getSpecifierRange(startSpecifier, specifierLen),
8876 getLocationOfByte(Precision.getStart()),
8877 analyze_format_string::LengthModifier(), Precision.getCharacters(),
8878 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
8879 EquatableFormatArgument::SS_None,
8880 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8881 : PrecisionIndex,
8882 0);
8883 }
8884
8885 // this specifier
8886 unsigned SpecIndex =
8887 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8888 if (FieldWidthIndex != Unset)
8889 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8890 if (PrecisionIndex != Unset)
8891 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8892
8893 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8894 if (FS.isPrivate())
8895 Sensitivity = EquatableFormatArgument::SS_Private;
8896 else if (FS.isPublic())
8897 Sensitivity = EquatableFormatArgument::SS_Public;
8898 else if (FS.isSensitive())
8899 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8900 else
8901 Sensitivity = EquatableFormatArgument::SS_None;
8902
8903 Specs.emplace_back(
8904 getSpecifierRange(startSpecifier, specifierLen),
8905 getLocationOfByte(CS.getStart()), FS.getLengthModifier(),
8906 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
8907 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
8908
8909 // auxiliary argument?
8912 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8913 getLocationOfByte(CS.getStart()),
8915 CS.getCharacters(),
8917 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
8918 SpecIndex + 1, SpecIndex);
8919 }
8920 return true;
8921}
8922
8923// Determines if the specified is a C++ class or struct containing
8924// a member with the specified name and kind (e.g. a CXXMethodDecl named
8925// "c_str()").
8926template<typename MemberKind>
8928CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8929 auto *RD = Ty->getAsCXXRecordDecl();
8931
8932 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8933 return Results;
8934
8935 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8937 R.suppressDiagnostics();
8938
8939 // We just need to include all members of the right kind turned up by the
8940 // filter, at this point.
8941 if (S.LookupQualifiedName(R, RD))
8942 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8943 NamedDecl *decl = (*I)->getUnderlyingDecl();
8944 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8945 Results.insert(FK);
8946 }
8947 return Results;
8948}
8949
8950/// Check if we could call '.c_str()' on an object.
8951///
8952/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8953/// allow the call, or if it would be ambiguous).
8955 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8956
8957 MethodSet Results =
8958 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8959 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8960 MI != ME; ++MI)
8961 if ((*MI)->getMinRequiredArguments() == 0)
8962 return true;
8963 return false;
8964}
8965
8966// Check if a (w)string was passed when a (w)char* was needed, and offer a
8967// better diagnostic if so. AT is assumed to be valid.
8968// Returns true when a c_str() conversion method is found.
8969bool CheckPrintfHandler::checkForCStrMembers(
8970 const analyze_printf::ArgType &AT, const Expr *E) {
8971 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8972
8973 MethodSet Results =
8975
8976 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8977 MI != ME; ++MI) {
8978 const CXXMethodDecl *Method = *MI;
8979 if (Method->getMinRequiredArguments() == 0 &&
8980 AT.matchesType(S.Context, Method->getReturnType())) {
8981 // FIXME: Suggest parens if the expression needs them.
8983 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8984 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8985 return true;
8986 }
8987 }
8988
8989 return false;
8990}
8991
8992bool CheckPrintfHandler::HandlePrintfSpecifier(
8993 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8994 unsigned specifierLen, const TargetInfo &Target) {
8995 using namespace analyze_format_string;
8996 using namespace analyze_printf;
8997
8998 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8999
9000 if (FS.consumesDataArgument()) {
9001 if (atFirstArg) {
9002 atFirstArg = false;
9003 usesPositionalArgs = FS.usesPositionalArg();
9004 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9005 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9006 startSpecifier, specifierLen);
9007 return false;
9008 }
9009 }
9010
9011 // First check if the field width, precision, and conversion specifier
9012 // have matching data arguments.
9013 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, startSpecifier,
9014 specifierLen)) {
9015 return false;
9016 }
9017
9018 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, startSpecifier,
9019 specifierLen)) {
9020 return false;
9021 }
9022
9023 if (!CS.consumesDataArgument()) {
9024 // FIXME: Technically specifying a precision or field width here
9025 // makes no sense. Worth issuing a warning at some point.
9026 return true;
9027 }
9028
9029 // Consume the argument.
9030 unsigned argIndex = FS.getArgIndex();
9031 if (argIndex < NumDataArgs) {
9032 // The check to see if the argIndex is valid will come later.
9033 // We set the bit here because we may exit early from this
9034 // function if we encounter some other error.
9035 CoveredArgs.set(argIndex);
9036 }
9037
9038 // FreeBSD kernel extensions.
9039 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9040 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9041 // We need at least two arguments.
9042 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9043 return false;
9044
9045 if (HasFormatArguments()) {
9046 // Claim the second argument.
9047 CoveredArgs.set(argIndex + 1);
9048
9049 // Type check the first argument (int for %b, pointer for %D)
9050 const Expr *Ex = getDataArg(argIndex);
9051 const analyze_printf::ArgType &AT =
9052 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
9053 ? ArgType(S.Context.IntTy)
9054 : ArgType::CPointerTy;
9055 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9056 EmitFormatDiagnostic(
9057 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9058 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9059 << false << Ex->getSourceRange(),
9060 Ex->getBeginLoc(), /*IsStringLocation*/ false,
9061 getSpecifierRange(startSpecifier, specifierLen));
9062
9063 // Type check the second argument (char * for both %b and %D)
9064 Ex = getDataArg(argIndex + 1);
9066 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9067 EmitFormatDiagnostic(
9068 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9069 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9070 << false << Ex->getSourceRange(),
9071 Ex->getBeginLoc(), /*IsStringLocation*/ false,
9072 getSpecifierRange(startSpecifier, specifierLen));
9073 }
9074 return true;
9075 }
9076
9077 // Check for using an Objective-C specific conversion specifier
9078 // in a non-ObjC literal.
9079 if (!allowsObjCArg() && CS.isObjCArg()) {
9080 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9081 specifierLen);
9082 }
9083
9084 // %P can only be used with os_log.
9085 if (FSType != FormatStringType::OSLog &&
9086 CS.getKind() == ConversionSpecifier::PArg) {
9087 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9088 specifierLen);
9089 }
9090
9091 // %n is not allowed with os_log.
9092 if (FSType == FormatStringType::OSLog &&
9093 CS.getKind() == ConversionSpecifier::nArg) {
9094 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9095 getLocationOfByte(CS.getStart()),
9096 /*IsStringLocation*/ false,
9097 getSpecifierRange(startSpecifier, specifierLen));
9098
9099 return true;
9100 }
9101
9102 // Only scalars are allowed for os_trace.
9103 if (FSType == FormatStringType::OSTrace &&
9104 (CS.getKind() == ConversionSpecifier::PArg ||
9105 CS.getKind() == ConversionSpecifier::sArg ||
9106 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9107 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9108 specifierLen);
9109 }
9110
9111 // Check for use of public/private annotation outside of os_log().
9112 if (FSType != FormatStringType::OSLog) {
9113 if (FS.isPublic().isSet()) {
9114 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9115 << "public",
9116 getLocationOfByte(FS.isPublic().getPosition()),
9117 /*IsStringLocation*/ false,
9118 getSpecifierRange(startSpecifier, specifierLen));
9119 }
9120 if (FS.isPrivate().isSet()) {
9121 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9122 << "private",
9123 getLocationOfByte(FS.isPrivate().getPosition()),
9124 /*IsStringLocation*/ false,
9125 getSpecifierRange(startSpecifier, specifierLen));
9126 }
9127 }
9128
9129 const llvm::Triple &Triple = Target.getTriple();
9130 if (CS.getKind() == ConversionSpecifier::nArg &&
9131 (Triple.isAndroid() || Triple.isOSFuchsia())) {
9132 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9133 getLocationOfByte(CS.getStart()),
9134 /*IsStringLocation*/ false,
9135 getSpecifierRange(startSpecifier, specifierLen));
9136 }
9137
9138 // Check for invalid use of field width
9139 if (!FS.hasValidFieldWidth()) {
9140 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9141 startSpecifier, specifierLen);
9142 }
9143
9144 // Check for invalid use of precision
9145 if (!FS.hasValidPrecision()) {
9146 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9147 startSpecifier, specifierLen);
9148 }
9149
9150 // Precision is mandatory for %P specifier.
9151 if (CS.getKind() == ConversionSpecifier::PArg &&
9153 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9154 getLocationOfByte(startSpecifier),
9155 /*IsStringLocation*/ false,
9156 getSpecifierRange(startSpecifier, specifierLen));
9157 }
9158
9159 // Check each flag does not conflict with any other component.
9161 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9162 if (!FS.hasValidLeadingZeros())
9163 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9164 if (!FS.hasValidPlusPrefix())
9165 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9166 if (!FS.hasValidSpacePrefix())
9167 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9168 if (!FS.hasValidAlternativeForm())
9169 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9170 if (!FS.hasValidLeftJustified())
9171 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9172
9173 // Check that flags are not ignored by another flag
9174 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9175 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9176 startSpecifier, specifierLen);
9177 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9178 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9179 startSpecifier, specifierLen);
9180
9181 // Check the length modifier is valid with the given conversion specifier.
9183 S.getLangOpts()))
9184 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9185 diag::warn_format_nonsensical_length);
9186 else if (!FS.hasStandardLengthModifier())
9187 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9189 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9190 diag::warn_format_non_standard_conversion_spec);
9191
9193 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9194
9195 // The remaining checks depend on the data arguments.
9196 if (!HasFormatArguments())
9197 return true;
9198
9199 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9200 return false;
9201
9202 const Expr *Arg = getDataArg(argIndex);
9203 if (!Arg)
9204 return true;
9205
9206 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9207}
9208
9209static bool requiresParensToAddCast(const Expr *E) {
9210 // FIXME: We should have a general way to reason about operator
9211 // precedence and whether parens are actually needed here.
9212 // Take care of a few common cases where they aren't.
9213 const Expr *Inside = E->IgnoreImpCasts();
9214 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9215 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9216
9217 switch (Inside->getStmtClass()) {
9218 case Stmt::ArraySubscriptExprClass:
9219 case Stmt::CallExprClass:
9220 case Stmt::CharacterLiteralClass:
9221 case Stmt::CXXBoolLiteralExprClass:
9222 case Stmt::DeclRefExprClass:
9223 case Stmt::FloatingLiteralClass:
9224 case Stmt::IntegerLiteralClass:
9225 case Stmt::MemberExprClass:
9226 case Stmt::ObjCArrayLiteralClass:
9227 case Stmt::ObjCBoolLiteralExprClass:
9228 case Stmt::ObjCBoxedExprClass:
9229 case Stmt::ObjCDictionaryLiteralClass:
9230 case Stmt::ObjCEncodeExprClass:
9231 case Stmt::ObjCIvarRefExprClass:
9232 case Stmt::ObjCMessageExprClass:
9233 case Stmt::ObjCPropertyRefExprClass:
9234 case Stmt::ObjCStringLiteralClass:
9235 case Stmt::ObjCSubscriptRefExprClass:
9236 case Stmt::ParenExprClass:
9237 case Stmt::StringLiteralClass:
9238 case Stmt::UnaryOperatorClass:
9239 return false;
9240 default:
9241 return true;
9242 }
9243}
9244
9245static std::pair<QualType, StringRef>
9246shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy,
9247 const Expr *E) {
9248 // Use a 'while' to peel off layers of typedefs.
9249 QualType TyTy = IntendedTy;
9250 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9251 StringRef Name = UserTy->getDecl()->getName();
9252 QualType CastTy = llvm::StringSwitch<QualType>(Name)
9253 .Case("CFIndex", Context.getNSIntegerType())
9254 .Case("NSInteger", Context.getNSIntegerType())
9255 .Case("NSUInteger", Context.getNSUIntegerType())
9256 .Case("SInt32", Context.IntTy)
9257 .Case("UInt32", Context.UnsignedIntTy)
9258 .Default(QualType());
9259
9260 if (!CastTy.isNull())
9261 return std::make_pair(CastTy, Name);
9262
9263 TyTy = UserTy->desugar();
9264 }
9265
9266 // Strip parens if necessary.
9267 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9268 return shouldNotPrintDirectly(Context, PE->getSubExpr()->getType(),
9269 PE->getSubExpr());
9270
9271 // If this is a conditional expression, then its result type is constructed
9272 // via usual arithmetic conversions and thus there might be no necessary
9273 // typedef sugar there. Recurse to operands to check for NSInteger &
9274 // Co. usage condition.
9275 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9276 QualType TrueTy, FalseTy;
9277 StringRef TrueName, FalseName;
9278
9279 std::tie(TrueTy, TrueName) = shouldNotPrintDirectly(
9280 Context, CO->getTrueExpr()->getType(), CO->getTrueExpr());
9281 std::tie(FalseTy, FalseName) = shouldNotPrintDirectly(
9282 Context, CO->getFalseExpr()->getType(), CO->getFalseExpr());
9283
9284 if (TrueTy == FalseTy)
9285 return std::make_pair(TrueTy, TrueName);
9286 else if (TrueTy.isNull())
9287 return std::make_pair(FalseTy, FalseName);
9288 else if (FalseTy.isNull())
9289 return std::make_pair(TrueTy, TrueName);
9290 }
9291
9292 return std::make_pair(QualType(), StringRef());
9293}
9294
9295/// Return true if \p ICE is an implicit argument promotion of an arithmetic
9296/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9297/// type do not count.
9299 const ImplicitCastExpr *ICE) {
9300 QualType From = ICE->getSubExpr()->getType();
9301 QualType To = ICE->getType();
9302 // It's an integer promotion if the destination type is the promoted
9303 // source type.
9304 if (ICE->getCastKind() == CK_IntegralCast &&
9306 S.Context.getPromotedIntegerType(From) == To)
9307 return true;
9308 // Look through vector types, since we do default argument promotion for
9309 // those in OpenCL.
9310 if (const auto *VecTy = From->getAs<ExtVectorType>())
9311 From = VecTy->getElementType();
9312 if (const auto *VecTy = To->getAs<ExtVectorType>())
9313 To = VecTy->getElementType();
9314 // It's a floating promotion if the source type is a lower rank.
9315 return ICE->getCastKind() == CK_FloatingCast &&
9316 S.Context.getFloatingTypeOrder(From, To) < 0;
9317}
9318
9321 DiagnosticsEngine &Diags, SourceLocation Loc) {
9323 if (Diags.isIgnored(
9324 diag::warn_format_conversion_argument_type_mismatch_signedness,
9325 Loc) ||
9326 Diags.isIgnored(
9327 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9328 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9330 }
9331 }
9332 return Match;
9333}
9334
9335bool CheckPrintfHandler::checkFormatExpr(
9336 const analyze_printf::PrintfSpecifier &FS, const char *StartSpecifier,
9337 unsigned SpecifierLen, const Expr *E) {
9338 using namespace analyze_format_string;
9339 using namespace analyze_printf;
9340
9341 // Now type check the data expression that matches the
9342 // format specifier.
9343 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9344 if (!AT.isValid())
9345 return true;
9346
9347 QualType ExprTy = E->getType();
9348 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9349 ExprTy = TET->getUnderlyingExpr()->getType();
9350 }
9351
9352 if (const OverflowBehaviorType *OBT =
9353 dyn_cast<OverflowBehaviorType>(ExprTy.getCanonicalType()))
9354 ExprTy = OBT->getUnderlyingType();
9355
9356 // When using the format attribute in C++, you can receive a function or an
9357 // array that will necessarily decay to a pointer when passed to the final
9358 // format consumer. Apply decay before type comparison.
9359 if (ExprTy->canDecayToPointerType())
9360 ExprTy = S.Context.getDecayedType(ExprTy);
9361
9362 // Diagnose attempts to print a boolean value as a character. Unlike other
9363 // -Wformat diagnostics, this is fine from a type perspective, but it still
9364 // doesn't make sense.
9367 const CharSourceRange &CSR =
9368 getSpecifierRange(StartSpecifier, SpecifierLen);
9369 SmallString<4> FSString;
9370 llvm::raw_svector_ostream os(FSString);
9371 FS.toString(os);
9372 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9373 << FSString,
9374 E->getExprLoc(), false, CSR);
9375 return true;
9376 }
9377
9378 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9379 // dumping raw class data (like is-a pointer), not actual data.
9381 ExprTy->isObjCObjectPointerType()) {
9382 const CharSourceRange &CSR =
9383 getSpecifierRange(StartSpecifier, SpecifierLen);
9384 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
9385 E->getExprLoc(), false, CSR);
9386 return true;
9387 }
9388
9389 if (CheckUnsupportedType(AT, E, StartSpecifier, SpecifierLen))
9390 return true;
9391
9392 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9394 ArgType::MatchKind OrigMatch = Match;
9395
9397 if (Match == ArgType::Match)
9398 return true;
9399
9400 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9401 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9402
9403 // Look through argument promotions for our error message's reported type.
9404 // This includes the integral and floating promotions, but excludes array
9405 // and function pointer decay (seeing that an argument intended to be a
9406 // string has type 'char [6]' is probably more confusing than 'char *') and
9407 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9408 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9409 if (isArithmeticArgumentPromotion(S, ICE)) {
9410 E = ICE->getSubExpr();
9411 ExprTy = E->getType();
9412
9413 // Check if we didn't match because of an implicit cast from a 'char'
9414 // or 'short' to an 'int'. This is done because printf is a varargs
9415 // function.
9416 if (ICE->getType() == S.Context.IntTy ||
9417 ICE->getType() == S.Context.UnsignedIntTy) {
9418 // All further checking is done on the subexpression
9419 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
9420 if (OrigMatch == ArgType::NoMatchSignedness &&
9421 ImplicitMatch != ArgType::NoMatchSignedness)
9422 // If the original match was a signedness match this match on the
9423 // implicit cast type also need to be signedness match otherwise we
9424 // might introduce new unexpected warnings from -Wformat-signedness.
9425 return true;
9426 ImplicitMatch = handleFormatSignedness(
9427 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
9428 if (ImplicitMatch == ArgType::Match)
9429 return true;
9430 }
9431 }
9432 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9433 // Special case for 'a', which has type 'int' in C.
9434 // Note, however, that we do /not/ want to treat multibyte constants like
9435 // 'MooV' as characters! This form is deprecated but still exists. In
9436 // addition, don't treat expressions as of type 'char' if one byte length
9437 // modifier is provided.
9438 if (ExprTy == S.Context.IntTy &&
9440 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
9441 ExprTy = S.Context.CharTy;
9442 // To improve check results, we consider a character literal in C
9443 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9444 // more likely a type confusion situation, so we will suggest to
9445 // use '%hhd' instead by discarding the MatchPromotion.
9446 if (Match == ArgType::MatchPromotion)
9448 }
9449 }
9450 if (Match == ArgType::MatchPromotion) {
9451 // WG14 N2562 only clarified promotions in *printf
9452 // For NSLog in ObjC, just preserve -Wformat behavior
9453 if (!S.getLangOpts().ObjC &&
9454 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9455 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9456 return true;
9458 }
9459 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9460 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9461 Match = ImplicitMatch;
9462 assert(Match != ArgType::MatchPromotion);
9463
9464 // Look through unscoped enums to their underlying type.
9465 bool IsEnum = false;
9466 bool IsScopedEnum = false;
9467 QualType IntendedTy = ExprTy;
9468 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9469 IntendedTy = ED->getIntegerType();
9470 if (!ED->isScoped()) {
9471 ExprTy = IntendedTy;
9472 // This controls whether we're talking about the underlying type or not,
9473 // which we only want to do when it's an unscoped enum.
9474 IsEnum = true;
9475 } else {
9476 IsScopedEnum = true;
9477 }
9478 }
9479
9480 // %C in an Objective-C context prints a unichar, not a wchar_t.
9481 // If the argument is an integer of some kind, believe the %C and suggest
9482 // a cast instead of changing the conversion specifier.
9483 if (isObjCContext() &&
9486 !ExprTy->isCharType()) {
9487 // 'unichar' is defined as a typedef of unsigned short, but we should
9488 // prefer using the typedef if it is visible.
9489 IntendedTy = S.Context.UnsignedShortTy;
9490
9491 // While we are here, check if the value is an IntegerLiteral that happens
9492 // to be within the valid range.
9493 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9494 const llvm::APInt &V = IL->getValue();
9495 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9496 return true;
9497 }
9498
9499 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9501 if (S.LookupName(Result, S.getCurScope())) {
9502 NamedDecl *ND = Result.getFoundDecl();
9503 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9504 if (TD->getUnderlyingType() == IntendedTy)
9505 IntendedTy =
9507 /*Qualifier=*/std::nullopt, TD);
9508 }
9509 }
9510 }
9511
9512 // Special-case some of Darwin's platform-independence types by suggesting
9513 // casts to primitive types that are known to be large enough.
9514 bool ShouldNotPrintDirectly = false;
9515 StringRef CastTyName;
9516 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9517 QualType CastTy;
9518 std::tie(CastTy, CastTyName) =
9519 shouldNotPrintDirectly(S.Context, IntendedTy, E);
9520 if (!CastTy.isNull()) {
9521 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9522 // (long in ASTContext). Only complain to pedants or when they're the
9523 // underlying type of a scoped enum (which always needs a cast).
9524 if (!IsScopedEnum &&
9525 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9526 (AT.isSizeT() || AT.isPtrdiffT()) &&
9527 AT.matchesType(S.Context, CastTy))
9529 IntendedTy = CastTy;
9530 ShouldNotPrintDirectly = true;
9531 }
9532 }
9533
9534 // We may be able to offer a FixItHint if it is a supported type.
9535 PrintfSpecifier fixedFS = FS;
9536 bool Success =
9537 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9538
9539 if (Success) {
9540 // Get the fix string from the fixed format specifier
9541 SmallString<16> buf;
9542 llvm::raw_svector_ostream os(buf);
9543 fixedFS.toString(os);
9544
9545 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9546
9547 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9548 unsigned Diag;
9549 switch (Match) {
9550 case ArgType::Match:
9553 llvm_unreachable("expected non-matching");
9555 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9556 break;
9558 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9559 break;
9561 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9562 break;
9563 case ArgType::NoMatch:
9564 Diag = diag::warn_format_conversion_argument_type_mismatch;
9565 break;
9566 }
9567
9568 // In this case, the specifier is wrong and should be changed to match
9569 // the argument.
9570 EmitFormatDiagnostic(S.PDiag(Diag)
9572 << IntendedTy << IsEnum << E->getSourceRange(),
9573 E->getBeginLoc(),
9574 /*IsStringLocation*/ false, SpecRange,
9575 FixItHint::CreateReplacement(SpecRange, os.str()));
9576 } else {
9577 // The canonical type for formatting this value is different from the
9578 // actual type of the expression. (This occurs, for example, with Darwin's
9579 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9580 // should be printed as 'long' for 64-bit compatibility.)
9581 // Rather than emitting a normal format/argument mismatch, we want to
9582 // add a cast to the recommended type (and correct the format string
9583 // if necessary). We should also do so for scoped enumerations.
9584 SmallString<16> CastBuf;
9585 llvm::raw_svector_ostream CastFix(CastBuf);
9586 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9587 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9588 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9589
9591 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
9592 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
9593 E->getExprLoc());
9594 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9595 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9596
9597 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9598 // If there's already a cast present, just replace it.
9599 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9600 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9601
9602 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9603 // If the expression has high enough precedence,
9604 // just write the C-style cast.
9605 Hints.push_back(
9606 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9607 } else {
9608 // Otherwise, add parens around the expression as well as the cast.
9609 CastFix << "(";
9610 Hints.push_back(
9611 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9612
9613 // We don't use getLocForEndOfToken because it returns invalid source
9614 // locations for macro expansions (by design).
9618 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9619 }
9620
9621 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9622 // The expression has a type that should not be printed directly.
9623 // We extract the name from the typedef because we don't want to show
9624 // the underlying type in the diagnostic.
9625 StringRef Name;
9626 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9627 Name = TypedefTy->getDecl()->getName();
9628 else
9629 Name = CastTyName;
9630 unsigned Diag = Match == ArgType::NoMatchPedantic
9631 ? diag::warn_format_argument_needs_cast_pedantic
9632 : diag::warn_format_argument_needs_cast;
9633 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9634 << E->getSourceRange(),
9635 E->getBeginLoc(), /*IsStringLocation=*/false,
9636 SpecRange, Hints);
9637 } else {
9638 // In this case, the expression could be printed using a different
9639 // specifier, but we've decided that the specifier is probably correct
9640 // and we should cast instead. Just use the normal warning message.
9641
9642 unsigned Diag =
9643 IsScopedEnum
9644 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9645 : diag::warn_format_conversion_argument_type_mismatch;
9646
9647 EmitFormatDiagnostic(
9648 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9649 << IsEnum << E->getSourceRange(),
9650 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9651 }
9652 }
9653 } else {
9654 const CharSourceRange &CSR =
9655 getSpecifierRange(StartSpecifier, SpecifierLen);
9656 // Since the warning for passing non-POD types to variadic functions
9657 // was deferred until now, we emit a warning for non-POD
9658 // arguments here.
9659 bool EmitTypeMismatch = false;
9660 // Record and complex type arguments cannot be code generated for os_log
9661 // and would crash CodeGen, so they are rejected with a hard error emitted
9662 // after the switch below.
9663 bool EmitOSLogError = false;
9664 switch (S.isValidVarArgType(ExprTy)) {
9665 case VarArgKind::Valid:
9667 unsigned Diag;
9668 switch (Match) {
9669 case ArgType::Match:
9672 llvm_unreachable("expected non-matching");
9674 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9675 break;
9677 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9678 break;
9680 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9681 break;
9682 case ArgType::NoMatch:
9683 EmitOSLogError = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy);
9684 Diag = diag::warn_format_conversion_argument_type_mismatch;
9685 break;
9686 }
9687
9688 if (!EmitOSLogError)
9689 EmitFormatDiagnostic(
9690 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9691 << IsEnum << CSR << E->getSourceRange(),
9692 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9693 break;
9694 }
9697 if (CallType == VariadicCallType::DoesNotApply) {
9698 EmitTypeMismatch = true;
9699 } else if (isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)) {
9700 // Emit a hard error rather than the -Wnon-pod-varargs warning, which
9701 // does not stop compilation.
9702 EmitOSLogError = true;
9703 } else {
9704 EmitFormatDiagnostic(
9705 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9706 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9707 << AT.getRepresentativeTypeName(S.Context) << CSR
9708 << E->getSourceRange(),
9709 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9710 checkForCStrMembers(AT, E);
9711 }
9712 break;
9713
9715 if (CallType == VariadicCallType::DoesNotApply)
9716 EmitTypeMismatch = true;
9717 else if (ExprTy->isObjCObjectType())
9718 EmitFormatDiagnostic(
9719 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9720 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9721 << AT.getRepresentativeTypeName(S.Context) << CSR
9722 << E->getSourceRange(),
9723 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9724 else
9725 // FIXME: If this is an initializer list, suggest removing the braces
9726 // or inserting a cast to the target type.
9727 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9728 << isa<InitListExpr>(E) << ExprTy << CallType
9730 break;
9731 }
9732
9733 if (EmitOSLogError)
9734 EmitFormatDiagnostic(
9735 S.PDiag(diag::err_format_conversion_argument_type_mismatch)
9736 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9737 << CSR << E->getSourceRange(),
9738 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9739
9740 if (EmitTypeMismatch) {
9741 // The function is not variadic, so we do not generate warnings about
9742 // being allowed to pass that object as a variadic argument. Instead,
9743 // since there are inherently no printf specifiers for types which cannot
9744 // be passed as variadic arguments, emit a plain old specifier mismatch
9745 // argument.
9746 EmitFormatDiagnostic(
9747 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9748 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
9749 << E->getSourceRange(),
9750 E->getBeginLoc(), false, CSR);
9751 }
9752
9753 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9754 "format string specifier index out of range");
9755 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9756 }
9757
9758 return true;
9759}
9760
9761//===--- CHECK: Scanf format string checking ------------------------------===//
9762
9763namespace {
9764
9765class CheckScanfHandler : public CheckFormatHandler {
9766public:
9767 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9768 const Expr *origFormatExpr, FormatStringType type,
9769 unsigned firstDataArg, unsigned numDataArgs,
9770 const char *beg, Sema::FormatArgumentPassingKind APK,
9771 ArrayRef<const Expr *> Args, unsigned formatIdx,
9772 bool inFunctionCall, VariadicCallType CallType,
9773 llvm::SmallBitVector &CheckedVarArgs,
9774 UncoveredArgHandler &UncoveredArg)
9775 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9776 numDataArgs, beg, APK, Args, formatIdx,
9777 inFunctionCall, CallType, CheckedVarArgs,
9778 UncoveredArg) {}
9779
9780 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9781 const char *startSpecifier,
9782 unsigned specifierLen) override;
9783
9784 bool
9785 HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9786 const char *startSpecifier,
9787 unsigned specifierLen) override;
9788
9789 void HandleIncompleteScanList(const char *start, const char *end) override;
9790};
9791
9792} // namespace
9793
9794void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9795 const char *end) {
9796 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9797 getLocationOfByte(end), /*IsStringLocation*/ true,
9798 getSpecifierRange(start, end - start));
9799}
9800
9801bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9802 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9803 unsigned specifierLen) {
9806
9807 return HandleInvalidConversionSpecifier(
9808 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
9809 specifierLen, CS.getStart(), CS.getLength());
9810}
9811
9812bool CheckScanfHandler::HandleScanfSpecifier(
9813 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9814 unsigned specifierLen) {
9815 using namespace analyze_scanf;
9816 using namespace analyze_format_string;
9817
9818 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9819
9820 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9821 // be used to decide if we are using positional arguments consistently.
9822 if (FS.consumesDataArgument()) {
9823 if (atFirstArg) {
9824 atFirstArg = false;
9825 usesPositionalArgs = FS.usesPositionalArg();
9826 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9827 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9828 startSpecifier, specifierLen);
9829 return false;
9830 }
9831 }
9832
9833 // Check if the field with is non-zero.
9834 const OptionalAmount &Amt = FS.getFieldWidth();
9836 if (Amt.getConstantAmount() == 0) {
9837 const CharSourceRange &R =
9838 getSpecifierRange(Amt.getStart(), Amt.getConstantLength());
9839 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9840 getLocationOfByte(Amt.getStart()),
9841 /*IsStringLocation*/ true, R,
9843 }
9844 }
9845
9846 if (!FS.consumesDataArgument()) {
9847 // FIXME: Technically specifying a precision or field width here
9848 // makes no sense. Worth issuing a warning at some point.
9849 return true;
9850 }
9851
9852 // Consume the argument.
9853 unsigned argIndex = FS.getArgIndex();
9854 if (argIndex < NumDataArgs) {
9855 // The check to see if the argIndex is valid will come later.
9856 // We set the bit here because we may exit early from this
9857 // function if we encounter some other error.
9858 CoveredArgs.set(argIndex);
9859 }
9860
9861 // Check the length modifier is valid with the given conversion specifier.
9863 S.getLangOpts()))
9864 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9865 diag::warn_format_nonsensical_length);
9866 else if (!FS.hasStandardLengthModifier())
9867 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9869 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9870 diag::warn_format_non_standard_conversion_spec);
9871
9873 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9874
9875 // The remaining checks depend on the data arguments.
9876 if (!HasFormatArguments())
9877 return true;
9878
9879 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9880 return false;
9881
9882 // Check that the argument type matches the format specifier.
9883 const Expr *Ex = getDataArg(argIndex);
9884 if (!Ex)
9885 return true;
9886
9888
9889 if (!AT.isValid()) {
9890 return true;
9891 }
9892
9893 if (CheckUnsupportedType(AT, Ex, startSpecifier, specifierLen))
9894 return true;
9895
9897 AT.matchesType(S.Context, Ex->getType());
9900 return true;
9903
9904 ScanfSpecifier fixedFS = FS;
9905 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9906 S.getLangOpts(), S.Context);
9907
9908 unsigned Diag =
9909 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9910 : Signedness
9911 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9912 : diag::warn_format_conversion_argument_type_mismatch;
9913
9914 if (Success) {
9915 // Get the fix string from the fixed format specifier.
9916 SmallString<128> buf;
9917 llvm::raw_svector_ostream os(buf);
9918 fixedFS.toString(os);
9919
9920 EmitFormatDiagnostic(
9922 << Ex->getType() << false << Ex->getSourceRange(),
9923 Ex->getBeginLoc(),
9924 /*IsStringLocation*/ false,
9925 getSpecifierRange(startSpecifier, specifierLen),
9927 getSpecifierRange(startSpecifier, specifierLen), os.str()));
9928 } else {
9929 EmitFormatDiagnostic(S.PDiag(Diag)
9931 << Ex->getType() << false << Ex->getSourceRange(),
9932 Ex->getBeginLoc(),
9933 /*IsStringLocation*/ false,
9934 getSpecifierRange(startSpecifier, specifierLen));
9935 }
9936
9937 return true;
9938}
9939
9940static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9942 const StringLiteral *Fmt,
9944 const Expr *FmtExpr, bool InFunctionCall) {
9945 bool HadError = false;
9946 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9947 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9948 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9949 // In positional-style format strings, the same specifier can appear
9950 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9951 // are sorted by getPosition(), and we process each range of equal
9952 // getPosition() values as one group.
9953 // RefArgs are taken from a string literal that was given to
9954 // attribute(format_matches), and if we got this far, we have already
9955 // verified that if it has positional specifiers that appear in multiple
9956 // locations, then they are all mutually compatible. What's left for us to
9957 // do is verify that all specifiers with the same position in FmtArgs are
9958 // compatible with the RefArgs specifiers. We check each specifier from
9959 // FmtArgs against the first member of the RefArgs group.
9960 for (; FmtIter < FmtEnd; ++FmtIter) {
9961 // Clang does not diagnose missing format specifiers in positional-style
9962 // strings (TODO: which it probably should do, as it is UB to skip over a
9963 // format argument). Skip specifiers if needed.
9964 if (FmtIter->getPosition() < RefIter->getPosition())
9965 continue;
9966
9967 // Delimits a new getPosition() value.
9968 if (FmtIter->getPosition() > RefIter->getPosition())
9969 break;
9970
9971 HadError |=
9972 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
9973 }
9974
9975 // Jump RefIter to the start of the next group.
9976 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
9977 return Arg.getPosition() != RefIter->getPosition();
9978 });
9979 }
9980
9981 if (FmtIter < FmtEnd) {
9982 CheckFormatHandler::EmitFormatDiagnostic(
9983 S, InFunctionCall, FmtExpr,
9984 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
9985 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
9986 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
9987 } else if (RefIter < RefEnd) {
9988 CheckFormatHandler::EmitFormatDiagnostic(
9989 S, InFunctionCall, FmtExpr,
9990 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
9991 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
9992 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
9993 << 1 << RefIter->getSourceRange();
9994 }
9995 return !HadError;
9996}
9997
9999 Sema &S, const FormatStringLiteral *FExpr,
10000 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
10002 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
10003 bool inFunctionCall, VariadicCallType CallType,
10004 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
10005 bool IgnoreStringsWithoutSpecifiers) {
10006 // CHECK: is the format string a wide literal?
10007 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10008 CheckFormatHandler::EmitFormatDiagnostic(
10009 S, inFunctionCall, Args[format_idx],
10010 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
10011 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10012 return;
10013 }
10014
10015 // Str - The format string. NOTE: this is NOT null-terminated!
10016 StringRef StrRef = FExpr->getString();
10017 const char *Str = StrRef.data();
10018 // Account for cases where the string literal is truncated in a declaration.
10019 const ConstantArrayType *T =
10020 S.Context.getAsConstantArrayType(FExpr->getType());
10021 assert(T && "String literal not of constant array type!");
10022 size_t TypeSize = T->getZExtSize();
10023 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10024 const unsigned numDataArgs = Args.size() - firstDataArg;
10025
10026 if (IgnoreStringsWithoutSpecifiers &&
10028 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10029 return;
10030
10031 // Emit a warning if the string literal is truncated and does not contain an
10032 // embedded null character.
10033 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
10034 CheckFormatHandler::EmitFormatDiagnostic(
10035 S, inFunctionCall, Args[format_idx],
10036 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
10037 FExpr->getBeginLoc(),
10038 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
10039 return;
10040 }
10041
10042 // CHECK: empty format string?
10043 if (StrLen == 0 && numDataArgs > 0) {
10044 CheckFormatHandler::EmitFormatDiagnostic(
10045 S, inFunctionCall, Args[format_idx],
10046 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10047 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10048 return;
10049 }
10050
10055 bool IsObjC =
10057 if (ReferenceFormatString == nullptr) {
10058 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10059 numDataArgs, IsObjC, Str, APK, Args, format_idx,
10060 inFunctionCall, CallType, CheckedVarArgs,
10061 UncoveredArg);
10062
10064 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
10067 H.DoneProcessing();
10068 } else {
10070 Type, ReferenceFormatString, FExpr->getFormatString(),
10071 inFunctionCall ? nullptr : Args[format_idx]);
10072 }
10073 } else if (Type == FormatStringType::Scanf) {
10074 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10075 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
10076 CallType, CheckedVarArgs, UncoveredArg);
10077
10079 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10080 H.DoneProcessing();
10081 } // TODO: handle other formats
10082}
10083
10085 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
10086 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
10091 return true;
10092
10093 bool IsObjC =
10096 FormatStringLiteral RefLit = AuthoritativeFormatString;
10097 FormatStringLiteral TestLit = TestedFormatString;
10098 const Expr *Arg;
10099 bool DiagAtStringLiteral;
10100 if (FunctionCallArg) {
10101 Arg = FunctionCallArg;
10102 DiagAtStringLiteral = false;
10103 } else {
10104 Arg = TestedFormatString;
10105 DiagAtStringLiteral = true;
10106 }
10107 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
10108 AuthoritativeFormatString, Type,
10109 IsObjC, true, RefArgs) &&
10110 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
10111 DiagAtStringLiteral, FmtArgs)) {
10112 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
10113 TestedFormatString, FmtArgs, Arg,
10114 DiagAtStringLiteral);
10115 }
10116 return false;
10117}
10118
10120 const StringLiteral *Str) {
10125 return true;
10126
10127 FormatStringLiteral RefLit = Str;
10129 bool IsObjC =
10131 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
10132 true, Args))
10133 return false;
10134
10135 // Group arguments by getPosition() value, and check that each member of the
10136 // group is compatible with the first member. This verifies that when
10137 // positional arguments are used multiple times (such as %2$i %2$d), all uses
10138 // are mutually compatible. As an optimization, don't test the first member
10139 // against itself.
10140 bool HadError = false;
10141 auto Iter = Args.begin();
10142 auto End = Args.end();
10143 while (Iter != End) {
10144 const auto &FirstInGroup = *Iter;
10145 for (++Iter;
10146 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
10147 ++Iter) {
10148 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
10149 }
10150 }
10151 return !HadError;
10152}
10153
10155 // Str - The format string. NOTE: this is NOT null-terminated!
10156 StringRef StrRef = FExpr->getString();
10157 const char *Str = StrRef.data();
10158 // Account for cases where the string literal is truncated in a declaration.
10159 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10160 assert(T && "String literal not of constant array type!");
10161 size_t TypeSize = T->getZExtSize();
10162 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10164 Str, Str + StrLen, getLangOpts(), Context.getTargetInfo());
10165}
10166
10167//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10168
10169// Returns the related absolute value function that is larger, of 0 if one
10170// does not exist.
10171static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10172 switch (AbsFunction) {
10173 default:
10174 return 0;
10175
10176 case Builtin::BI__builtin_abs:
10177 return Builtin::BI__builtin_labs;
10178 case Builtin::BI__builtin_labs:
10179 return Builtin::BI__builtin_llabs;
10180 case Builtin::BI__builtin_llabs:
10181 return 0;
10182
10183 case Builtin::BI__builtin_fabsf:
10184 return Builtin::BI__builtin_fabs;
10185 case Builtin::BI__builtin_fabs:
10186 return Builtin::BI__builtin_fabsl;
10187 case Builtin::BI__builtin_fabsl:
10188 return 0;
10189
10190 case Builtin::BI__builtin_cabsf:
10191 return Builtin::BI__builtin_cabs;
10192 case Builtin::BI__builtin_cabs:
10193 return Builtin::BI__builtin_cabsl;
10194 case Builtin::BI__builtin_cabsl:
10195 return 0;
10196
10197 case Builtin::BIabs:
10198 return Builtin::BIlabs;
10199 case Builtin::BIlabs:
10200 return Builtin::BIllabs;
10201 case Builtin::BIllabs:
10202 return 0;
10203
10204 case Builtin::BIfabsf:
10205 return Builtin::BIfabs;
10206 case Builtin::BIfabs:
10207 return Builtin::BIfabsl;
10208 case Builtin::BIfabsl:
10209 return 0;
10210
10211 case Builtin::BIcabsf:
10212 return Builtin::BIcabs;
10213 case Builtin::BIcabs:
10214 return Builtin::BIcabsl;
10215 case Builtin::BIcabsl:
10216 return 0;
10217 }
10218}
10219
10220// Returns the argument type of the absolute value function.
10222 unsigned AbsType) {
10223 if (AbsType == 0)
10224 return QualType();
10225
10227 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10229 return QualType();
10230
10232 if (!FT)
10233 return QualType();
10234
10235 if (FT->getNumParams() != 1)
10236 return QualType();
10237
10238 return FT->getParamType(0);
10239}
10240
10241// Returns the best absolute value function, or zero, based on type and
10242// current absolute value function.
10243static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10244 unsigned AbsFunctionKind) {
10245 unsigned BestKind = 0;
10246 uint64_t ArgSize = Context.getTypeSize(ArgType);
10247 for (unsigned Kind = AbsFunctionKind; Kind != 0;
10248 Kind = getLargerAbsoluteValueFunction(Kind)) {
10249 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10250 if (Context.getTypeSize(ParamType) >= ArgSize) {
10251 if (BestKind == 0)
10252 BestKind = Kind;
10253 else if (Context.hasSameType(ParamType, ArgType)) {
10254 BestKind = Kind;
10255 break;
10256 }
10257 }
10258 }
10259 return BestKind;
10260}
10261
10267
10269 if (T->isIntegralOrEnumerationType())
10270 return AVK_Integer;
10271 if (T->isRealFloatingType())
10272 return AVK_Floating;
10273 if (T->isAnyComplexType())
10274 return AVK_Complex;
10275
10276 llvm_unreachable("Type not integer, floating, or complex");
10277}
10278
10279// Changes the absolute value function to a different type. Preserves whether
10280// the function is a builtin.
10281static unsigned changeAbsFunction(unsigned AbsKind,
10282 AbsoluteValueKind ValueKind) {
10283 switch (ValueKind) {
10284 case AVK_Integer:
10285 switch (AbsKind) {
10286 default:
10287 return 0;
10288 case Builtin::BI__builtin_fabsf:
10289 case Builtin::BI__builtin_fabs:
10290 case Builtin::BI__builtin_fabsl:
10291 case Builtin::BI__builtin_cabsf:
10292 case Builtin::BI__builtin_cabs:
10293 case Builtin::BI__builtin_cabsl:
10294 return Builtin::BI__builtin_abs;
10295 case Builtin::BIfabsf:
10296 case Builtin::BIfabs:
10297 case Builtin::BIfabsl:
10298 case Builtin::BIcabsf:
10299 case Builtin::BIcabs:
10300 case Builtin::BIcabsl:
10301 return Builtin::BIabs;
10302 }
10303 case AVK_Floating:
10304 switch (AbsKind) {
10305 default:
10306 return 0;
10307 case Builtin::BI__builtin_abs:
10308 case Builtin::BI__builtin_labs:
10309 case Builtin::BI__builtin_llabs:
10310 case Builtin::BI__builtin_cabsf:
10311 case Builtin::BI__builtin_cabs:
10312 case Builtin::BI__builtin_cabsl:
10313 return Builtin::BI__builtin_fabsf;
10314 case Builtin::BIabs:
10315 case Builtin::BIlabs:
10316 case Builtin::BIllabs:
10317 case Builtin::BIcabsf:
10318 case Builtin::BIcabs:
10319 case Builtin::BIcabsl:
10320 return Builtin::BIfabsf;
10321 }
10322 case AVK_Complex:
10323 switch (AbsKind) {
10324 default:
10325 return 0;
10326 case Builtin::BI__builtin_abs:
10327 case Builtin::BI__builtin_labs:
10328 case Builtin::BI__builtin_llabs:
10329 case Builtin::BI__builtin_fabsf:
10330 case Builtin::BI__builtin_fabs:
10331 case Builtin::BI__builtin_fabsl:
10332 return Builtin::BI__builtin_cabsf;
10333 case Builtin::BIabs:
10334 case Builtin::BIlabs:
10335 case Builtin::BIllabs:
10336 case Builtin::BIfabsf:
10337 case Builtin::BIfabs:
10338 case Builtin::BIfabsl:
10339 return Builtin::BIcabsf;
10340 }
10341 }
10342 llvm_unreachable("Unable to convert function");
10343}
10344
10345static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10346 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10347 if (!FnInfo)
10348 return 0;
10349
10350 switch (FDecl->getBuiltinID()) {
10351 default:
10352 return 0;
10353 case Builtin::BI__builtin_abs:
10354 case Builtin::BI__builtin_fabs:
10355 case Builtin::BI__builtin_fabsf:
10356 case Builtin::BI__builtin_fabsl:
10357 case Builtin::BI__builtin_labs:
10358 case Builtin::BI__builtin_llabs:
10359 case Builtin::BI__builtin_cabs:
10360 case Builtin::BI__builtin_cabsf:
10361 case Builtin::BI__builtin_cabsl:
10362 case Builtin::BIabs:
10363 case Builtin::BIlabs:
10364 case Builtin::BIllabs:
10365 case Builtin::BIfabs:
10366 case Builtin::BIfabsf:
10367 case Builtin::BIfabsl:
10368 case Builtin::BIcabs:
10369 case Builtin::BIcabsf:
10370 case Builtin::BIcabsl:
10371 return FDecl->getBuiltinID();
10372 }
10373 llvm_unreachable("Unknown Builtin type");
10374}
10375
10376// If the replacement is valid, emit a note with replacement function.
10377// Additionally, suggest including the proper header if not already included.
10379 unsigned AbsKind, QualType ArgType) {
10380 bool EmitHeaderHint = true;
10381 const char *HeaderName = nullptr;
10382 std::string FunctionName;
10383 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10384 FunctionName = "std::abs";
10385 if (ArgType->isIntegralOrEnumerationType()) {
10386 HeaderName = "cstdlib";
10387 } else if (ArgType->isRealFloatingType()) {
10388 HeaderName = "cmath";
10389 } else {
10390 llvm_unreachable("Invalid Type");
10391 }
10392
10393 // Lookup all std::abs
10394 if (NamespaceDecl *Std = S.getStdNamespace()) {
10395 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10396 R.suppressDiagnostics();
10397 S.LookupQualifiedName(R, Std);
10398
10399 for (const auto *I : R) {
10400 const FunctionDecl *FDecl = nullptr;
10401 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10402 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10403 } else {
10404 FDecl = dyn_cast<FunctionDecl>(I);
10405 }
10406 if (!FDecl)
10407 continue;
10408
10409 // Found std::abs(), check that they are the right ones.
10410 if (FDecl->getNumParams() != 1)
10411 continue;
10412
10413 // Check that the parameter type can handle the argument.
10414 QualType ParamType = FDecl->getParamDecl(0)->getType();
10415 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10416 S.Context.getTypeSize(ArgType) <=
10417 S.Context.getTypeSize(ParamType)) {
10418 // Found a function, don't need the header hint.
10419 EmitHeaderHint = false;
10420 break;
10421 }
10422 }
10423 }
10424 } else {
10425 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10426 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10427
10428 if (HeaderName) {
10429 DeclarationName DN(&S.Context.Idents.get(FunctionName));
10430 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10431 R.suppressDiagnostics();
10432 S.LookupName(R, S.getCurScope());
10433
10434 if (R.isSingleResult()) {
10435 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10436 if (FD && FD->getBuiltinID() == AbsKind) {
10437 EmitHeaderHint = false;
10438 } else {
10439 return;
10440 }
10441 } else if (!R.empty()) {
10442 return;
10443 }
10444 }
10445 }
10446
10447 S.Diag(Loc, diag::note_replace_abs_function)
10448 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10449
10450 if (!HeaderName)
10451 return;
10452
10453 if (!EmitHeaderHint)
10454 return;
10455
10456 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10457 << FunctionName;
10458}
10459
10460template <std::size_t StrLen>
10461static bool IsStdFunction(const FunctionDecl *FDecl,
10462 const char (&Str)[StrLen]) {
10463 if (!FDecl)
10464 return false;
10465 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10466 return false;
10467 if (!FDecl->isInStdNamespace())
10468 return false;
10469
10470 return true;
10471}
10472
10473enum class MathCheck { NaN, Inf };
10474static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10475 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10476 return llvm::is_contained(names, calleeName);
10477 };
10478
10479 switch (Check) {
10480 case MathCheck::NaN:
10481 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10482 "__builtin_nanf16", "__builtin_nanf128"});
10483 case MathCheck::Inf:
10484 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10485 "__builtin_inff16", "__builtin_inff128"});
10486 }
10487 llvm_unreachable("unknown MathCheck");
10488}
10489
10490static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10491 if (FDecl->getName() != "infinity")
10492 return false;
10493
10494 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
10495 const CXXRecordDecl *RDecl = MDecl->getParent();
10496 if (RDecl->getName() != "numeric_limits")
10497 return false;
10498
10499 if (const NamespaceDecl *NSDecl =
10500 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
10501 return NSDecl->isStdNamespace();
10502 }
10503
10504 return false;
10505}
10506
10507void Sema::CheckInfNaNFunction(const CallExpr *Call,
10508 const FunctionDecl *FDecl) {
10509 if (!FDecl->getIdentifier())
10510 return;
10511
10512 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
10513 if (FPO.getNoHonorNaNs() &&
10514 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
10516 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10517 << 1 << 0 << Call->getSourceRange();
10518 return;
10519 }
10520
10521 if (FPO.getNoHonorInfs() &&
10522 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
10523 IsInfinityFunction(FDecl) ||
10525 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10526 << 0 << 0 << Call->getSourceRange();
10527 }
10528}
10529
10530void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10531 const FunctionDecl *FDecl) {
10532 if (Call->getNumArgs() != 1)
10533 return;
10534
10535 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10536 bool IsStdAbs = IsStdFunction(FDecl, "abs");
10537 if (AbsKind == 0 && !IsStdAbs)
10538 return;
10539
10540 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10541 QualType ParamType = Call->getArg(0)->getType();
10542
10543 // Unsigned types cannot be negative. Suggest removing the absolute value
10544 // function call.
10545 if (ArgType->isUnsignedIntegerType()) {
10546 std::string FunctionName =
10547 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10548 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10549 Diag(Call->getExprLoc(), diag::note_remove_abs)
10550 << FunctionName
10551 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10552 return;
10553 }
10554
10555 // Taking the absolute value of a pointer is very suspicious, they probably
10556 // wanted to index into an array, dereference a pointer, call a function, etc.
10557 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10558 unsigned DiagType = 0;
10559 if (ArgType->isFunctionType())
10560 DiagType = 1;
10561 else if (ArgType->isArrayType())
10562 DiagType = 2;
10563
10564 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10565 return;
10566 }
10567
10568 // std::abs has overloads which prevent most of the absolute value problems
10569 // from occurring.
10570 if (IsStdAbs)
10571 return;
10572
10573 // Prevent reaching unreachable code in getAbsoluteValueKind for unsupported
10574 // types.
10575 if (!ArgType->isIntegralOrEnumerationType() &&
10576 !ArgType->isRealFloatingType() && !ArgType->isAnyComplexType())
10577 return;
10578
10579 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10580 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10581
10582 // The argument and parameter are the same kind. Check if they are the right
10583 // size.
10584 if (ArgValueKind == ParamValueKind) {
10585 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10586 return;
10587
10588 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10589 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10590 << FDecl << ArgType << ParamType;
10591
10592 if (NewAbsKind == 0)
10593 return;
10594
10595 emitReplacement(*this, Call->getExprLoc(),
10596 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10597 return;
10598 }
10599
10600 // ArgValueKind != ParamValueKind
10601 // The wrong type of absolute value function was used. Attempt to find the
10602 // proper one.
10603 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10604 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10605 if (NewAbsKind == 0)
10606 return;
10607
10608 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10609 << FDecl << ParamValueKind << ArgValueKind;
10610
10611 emitReplacement(*this, Call->getExprLoc(),
10612 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10613}
10614
10615//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10616void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10617 const FunctionDecl *FDecl) {
10618 if (!Call || !FDecl) return;
10619
10620 // Ignore template specializations and macros.
10621 if (inTemplateInstantiation()) return;
10622 if (Call->getExprLoc().isMacroID()) return;
10623
10624 // Only care about the one template argument, two function parameter std::max
10625 if (Call->getNumArgs() != 2) return;
10626 if (!IsStdFunction(FDecl, "max")) return;
10627 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10628 if (!ArgList) return;
10629 if (ArgList->size() != 1) return;
10630
10631 // Check that template type argument is unsigned integer.
10632 const auto& TA = ArgList->get(0);
10633 if (TA.getKind() != TemplateArgument::Type) return;
10634 QualType ArgType = TA.getAsType();
10635 if (!ArgType->isUnsignedIntegerType()) return;
10636
10637 // See if either argument is a literal zero.
10638 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10639 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10640 if (!MTE) return false;
10641 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10642 if (!Num) return false;
10643 if (Num->getValue() != 0) return false;
10644 return true;
10645 };
10646
10647 const Expr *FirstArg = Call->getArg(0);
10648 const Expr *SecondArg = Call->getArg(1);
10649 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10650 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10651
10652 // Only warn when exactly one argument is zero.
10653 if (IsFirstArgZero == IsSecondArgZero) return;
10654
10655 SourceRange FirstRange = FirstArg->getSourceRange();
10656 SourceRange SecondRange = SecondArg->getSourceRange();
10657
10658 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10659
10660 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10661 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10662
10663 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10664 SourceRange RemovalRange;
10665 if (IsFirstArgZero) {
10666 RemovalRange = SourceRange(FirstRange.getBegin(),
10667 SecondRange.getBegin().getLocWithOffset(-1));
10668 } else {
10669 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10670 SecondRange.getEnd());
10671 }
10672
10673 Diag(Call->getExprLoc(), diag::note_remove_max_call)
10674 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10675 << FixItHint::CreateRemoval(RemovalRange);
10676}
10677
10678//===--- CHECK: Standard memory functions ---------------------------------===//
10679
10680/// Takes the expression passed to the size_t parameter of functions
10681/// such as memcmp, strncat, etc and warns if it's a comparison.
10682///
10683/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10685 const IdentifierInfo *FnName,
10686 SourceLocation FnLoc,
10687 SourceLocation RParenLoc) {
10688 const auto *Size = dyn_cast<BinaryOperator>(E);
10689 if (!Size)
10690 return false;
10691
10692 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10693 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10694 return false;
10695
10696 SourceRange SizeRange = Size->getSourceRange();
10697 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10698 << SizeRange << FnName;
10699 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10700 << FnName
10702 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10703 << FixItHint::CreateRemoval(RParenLoc);
10704 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10705 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10707 ")");
10708
10709 return true;
10710}
10711
10712/// Determine whether the given type is or contains a dynamic class type
10713/// (e.g., whether it has a vtable).
10715 bool &IsContained) {
10716 // Look through array types while ignoring qualifiers.
10717 const Type *Ty = T->getBaseElementTypeUnsafe();
10718 IsContained = false;
10719
10720 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10721 RD = RD ? RD->getDefinition() : nullptr;
10722 if (!RD || RD->isInvalidDecl())
10723 return nullptr;
10724
10725 if (RD->isDynamicClass())
10726 return RD;
10727
10728 // Check all the fields. If any bases were dynamic, the class is dynamic.
10729 // It's impossible for a class to transitively contain itself by value, so
10730 // infinite recursion is impossible.
10731 for (auto *FD : RD->fields()) {
10732 bool SubContained;
10733 if (const CXXRecordDecl *ContainedRD =
10734 getContainedDynamicClass(FD->getType(), SubContained)) {
10735 IsContained = true;
10736 return ContainedRD;
10737 }
10738 }
10739
10740 return nullptr;
10741}
10742
10744 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10745 if (Unary->getKind() == UETT_SizeOf)
10746 return Unary;
10747 return nullptr;
10748}
10749
10750/// If E is a sizeof expression, returns its argument expression,
10751/// otherwise returns NULL.
10752static const Expr *getSizeOfExprArg(const Expr *E) {
10754 if (!SizeOf->isArgumentType())
10755 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10756 return nullptr;
10757}
10758
10759/// If E is a sizeof expression, returns its argument type.
10762 return SizeOf->getTypeOfArgument();
10763 return QualType();
10764}
10765
10766namespace {
10767
10768struct SearchNonTrivialToInitializeField
10769 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10770 using Super =
10771 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10772
10773 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10774
10775 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10776 SourceLocation SL) {
10777 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10778 asDerived().visitArray(PDIK, AT, SL);
10779 return;
10780 }
10781
10782 Super::visitWithKind(PDIK, FT, SL);
10783 }
10784
10785 void visitARCStrong(QualType FT, SourceLocation SL) {
10786 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10787 }
10788 void visitARCWeak(QualType FT, SourceLocation SL) {
10789 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10790 }
10791 void visitStruct(QualType FT, SourceLocation SL) {
10792 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10793 visit(FD->getType(), FD->getLocation());
10794 }
10795 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10796 const ArrayType *AT, SourceLocation SL) {
10797 visit(getContext().getBaseElementType(AT), SL);
10798 }
10799 void visitTrivial(QualType FT, SourceLocation SL) {}
10800
10801 static void diag(QualType RT, const Expr *E, Sema &S) {
10802 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10803 }
10804
10805 ASTContext &getContext() { return S.getASTContext(); }
10806
10807 const Expr *E;
10808 Sema &S;
10809};
10810
10811struct SearchNonTrivialToCopyField
10812 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10813 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10814
10815 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10816
10817 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10818 SourceLocation SL) {
10819 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10820 asDerived().visitArray(PCK, AT, SL);
10821 return;
10822 }
10823
10824 Super::visitWithKind(PCK, FT, SL);
10825 }
10826
10827 void visitARCStrong(QualType FT, SourceLocation SL) {
10828 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10829 }
10830 void visitARCWeak(QualType FT, SourceLocation SL) {
10831 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10832 }
10833 void visitPtrAuth(QualType FT, SourceLocation SL) {
10834 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10835 }
10836 void visitStruct(QualType FT, SourceLocation SL) {
10837 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10838 visit(FD->getType(), FD->getLocation());
10839 }
10840 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10841 SourceLocation SL) {
10842 visit(getContext().getBaseElementType(AT), SL);
10843 }
10844 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10845 SourceLocation SL) {}
10846 void visitTrivial(QualType FT, SourceLocation SL) {}
10847 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10848
10849 static void diag(QualType RT, const Expr *E, Sema &S) {
10850 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10851 }
10852
10853 ASTContext &getContext() { return S.getASTContext(); }
10854
10855 const Expr *E;
10856 Sema &S;
10857};
10858
10859}
10860
10861/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10862static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10863 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10864
10865 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10866 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10867 return false;
10868
10869 return doesExprLikelyComputeSize(BO->getLHS()) ||
10870 doesExprLikelyComputeSize(BO->getRHS());
10871 }
10872
10873 return getAsSizeOfExpr(SizeofExpr) != nullptr;
10874}
10875
10876/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10877///
10878/// \code
10879/// #define MACRO 0
10880/// foo(MACRO);
10881/// foo(0);
10882/// \endcode
10883///
10884/// This should return true for the first call to foo, but not for the second
10885/// (regardless of whether foo is a macro or function).
10887 SourceLocation CallLoc,
10888 SourceLocation ArgLoc) {
10889 if (!CallLoc.isMacroID())
10890 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10891
10892 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10893 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10894}
10895
10896/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10897/// last two arguments transposed.
10898static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10899 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10900 return;
10901
10902 const Expr *SizeArg =
10903 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10904
10905 auto isLiteralZero = [](const Expr *E) {
10906 return (isa<IntegerLiteral>(E) &&
10907 cast<IntegerLiteral>(E)->getValue() == 0) ||
10909 cast<CharacterLiteral>(E)->getValue() == 0);
10910 };
10911
10912 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10913 SourceLocation CallLoc = Call->getRParenLoc();
10915 if (isLiteralZero(SizeArg) &&
10916 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10917
10918 SourceLocation DiagLoc = SizeArg->getExprLoc();
10919
10920 // Some platforms #define bzero to __builtin_memset. See if this is the
10921 // case, and if so, emit a better diagnostic.
10922 if (BId == Builtin::BIbzero ||
10924 CallLoc, SM, S.getLangOpts()) == "bzero")) {
10925 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10926 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10927 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10928 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10929 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10930 }
10931 return;
10932 }
10933
10934 // If the second argument to a memset is a sizeof expression and the third
10935 // isn't, this is also likely an error. This should catch
10936 // 'memset(buf, sizeof(buf), 0xff)'.
10937 if (BId == Builtin::BImemset &&
10938 doesExprLikelyComputeSize(Call->getArg(1)) &&
10939 !doesExprLikelyComputeSize(Call->getArg(2))) {
10940 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10941 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10942 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10943 return;
10944 }
10945}
10946
10947void Sema::CheckMemaccessArguments(const CallExpr *Call,
10948 unsigned BId,
10949 IdentifierInfo *FnName) {
10950 assert(BId != 0);
10951
10952 // It is possible to have a non-standard definition of memset. Validate
10953 // we have enough arguments, and if not, abort further checking.
10954 unsigned ExpectedNumArgs =
10955 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10956 if (Call->getNumArgs() < ExpectedNumArgs)
10957 return;
10958
10959 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10960 BId == Builtin::BIstrndup ? 1 : 2);
10961 unsigned LenArg =
10962 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10963 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10964
10965 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10966 Call->getBeginLoc(), Call->getRParenLoc()))
10967 return;
10968
10969 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10970 CheckMemaccessSize(*this, BId, Call);
10971
10972 // We have special checking when the length is a sizeof expression.
10973 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10974
10975 // Although widely used, 'bzero' is not a standard function. Be more strict
10976 // with the argument types before allowing diagnostics and only allow the
10977 // form bzero(ptr, sizeof(...)).
10978 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10979 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10980 return;
10981
10982 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10983 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10984 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10985
10986 QualType DestTy = Dest->getType();
10987 QualType PointeeTy;
10988 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10989 PointeeTy = DestPtrTy->getPointeeType();
10990
10991 // Never warn about void type pointers. This can be used to suppress
10992 // false positives.
10993 if (PointeeTy->isVoidType())
10994 continue;
10995
10996 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10997 // actually comparing the expressions for equality. Because computing the
10998 // expression IDs can be expensive, we only do this if the diagnostic is
10999 // enabled.
11000 if (CheckSizeofMemaccessArgument(LenExpr, Dest, FnName))
11001 break;
11002
11003 // Also check for cases where the sizeof argument is the exact same
11004 // type as the memory argument, and where it points to a user-defined
11005 // record type.
11006 if (SizeOfArgTy != QualType()) {
11007 if (PointeeTy->isRecordType() &&
11008 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
11009 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
11010 PDiag(diag::warn_sizeof_pointer_type_memaccess)
11011 << FnName << SizeOfArgTy << ArgIdx
11012 << PointeeTy << Dest->getSourceRange()
11013 << LenExpr->getSourceRange());
11014 break;
11015 }
11016 }
11017 } else if (DestTy->isArrayType()) {
11018 PointeeTy = DestTy;
11019 }
11020
11021 if (PointeeTy == QualType())
11022 continue;
11023
11024 // Always complain about dynamic classes.
11025 bool IsContained;
11026 if (const CXXRecordDecl *ContainedRD =
11027 getContainedDynamicClass(PointeeTy, IsContained)) {
11028
11029 unsigned OperationType = 0;
11030 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11031 // "overwritten" if we're warning about the destination for any call
11032 // but memcmp; otherwise a verb appropriate to the call.
11033 if (ArgIdx != 0 || IsCmp) {
11034 if (BId == Builtin::BImemcpy)
11035 OperationType = 1;
11036 else if(BId == Builtin::BImemmove)
11037 OperationType = 2;
11038 else if (IsCmp)
11039 OperationType = 3;
11040 }
11041
11042 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11043 PDiag(diag::warn_dyn_class_memaccess)
11044 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11045 << IsContained << ContainedRD << OperationType
11046 << Call->getCallee()->getSourceRange());
11047 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11048 BId != Builtin::BImemset)
11050 Dest->getExprLoc(), Dest,
11051 PDiag(diag::warn_arc_object_memaccess)
11052 << ArgIdx << FnName << PointeeTy
11053 << Call->getCallee()->getSourceRange());
11054 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
11055
11056 // FIXME: Do not consider incomplete types even though they may be
11057 // completed later. GCC does not diagnose such code, but we may want to
11058 // consider diagnosing it in the future, perhaps under a different, but
11059 // related, diagnostic group.
11060 bool NonTriviallyCopyableCXXRecord =
11061 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
11062 !PointeeTy.isTriviallyCopyableType(Context);
11063
11064 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11066 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11067 PDiag(diag::warn_cstruct_memaccess)
11068 << ArgIdx << FnName << PointeeTy << 0);
11069 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
11070 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11071 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11072 // FIXME: Limiting this warning to dest argument until we decide
11073 // whether it's valid for source argument too.
11074 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11075 PDiag(diag::warn_cxxstruct_memaccess)
11076 << FnName << PointeeTy);
11077 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11079 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11080 PDiag(diag::warn_cstruct_memaccess)
11081 << ArgIdx << FnName << PointeeTy << 1);
11082 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
11083 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11084 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11085 // FIXME: Limiting this warning to dest argument until we decide
11086 // whether it's valid for source argument too.
11087 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11088 PDiag(diag::warn_cxxstruct_memaccess)
11089 << FnName << PointeeTy);
11090 } else {
11091 continue;
11092 }
11093 } else
11094 continue;
11095
11097 Dest->getExprLoc(), Dest,
11098 PDiag(diag::note_bad_memaccess_silence)
11099 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
11100 break;
11101 }
11102}
11103
11104bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
11105 IdentifierInfo *FnName) {
11106 llvm::FoldingSetNodeID SizeOfArgID;
11107 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
11108 if (!SizeOfArg)
11109 return false;
11110 // Computing this warning is expensive, so we only do so if the warning is
11111 // enabled.
11112 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
11113 SizeOfArg->getExprLoc()))
11114 return false;
11115 QualType DestTy = Dest->getType();
11116 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
11117 if (!DestPtrTy)
11118 return false;
11119
11120 QualType PointeeTy = DestPtrTy->getPointeeType();
11121
11122 if (SizeOfArgID == llvm::FoldingSetNodeID())
11123 SizeOfArg->Profile(SizeOfArgID, Context, true);
11124
11125 llvm::FoldingSetNodeID DestID;
11126 Dest->Profile(DestID, Context, true);
11127 if (DestID == SizeOfArgID) {
11128 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11129 // over sizeof(src) as well.
11130 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11131 StringRef ReadableName = FnName->getName();
11132
11133 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest);
11134 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
11135 ActionIdx = 1; // If its an address-of operator, just remove it.
11136 if (!PointeeTy->isIncompleteType() &&
11137 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
11138 ActionIdx = 2; // If the pointee's size is sizeof(char),
11139 // suggest an explicit length.
11140
11141 // If the function is defined as a builtin macro, do not show macro
11142 // expansion.
11143 SourceLocation SL = SizeOfArg->getExprLoc();
11144 SourceRange DSR = Dest->getSourceRange();
11145 SourceRange SSR = SizeOfArg->getSourceRange();
11146 SourceManager &SM = getSourceManager();
11147
11148 if (SM.isMacroArgExpansion(SL)) {
11149 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
11150 SL = SM.getSpellingLoc(SL);
11151 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
11152 SM.getSpellingLoc(DSR.getEnd()));
11153 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
11154 SM.getSpellingLoc(SSR.getEnd()));
11155 }
11156
11157 DiagRuntimeBehavior(SL, SizeOfArg,
11158 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
11159 << ReadableName << PointeeTy << DestTy << DSR
11160 << SSR);
11161 DiagRuntimeBehavior(SL, SizeOfArg,
11162 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
11163 << ActionIdx << SSR);
11164 return true;
11165 }
11166 return false;
11167}
11168
11169// A little helper routine: ignore addition and subtraction of integer literals.
11170// This intentionally does not ignore all integer constant expressions because
11171// we don't want to remove sizeof().
11172static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11173 Ex = Ex->IgnoreParenCasts();
11174
11175 while (true) {
11176 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11177 if (!BO || !BO->isAdditiveOp())
11178 break;
11179
11180 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11181 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11182
11183 if (isa<IntegerLiteral>(RHS))
11184 Ex = LHS;
11185 else if (isa<IntegerLiteral>(LHS))
11186 Ex = RHS;
11187 else
11188 break;
11189 }
11190
11191 return Ex;
11192}
11193
11195 ASTContext &Context) {
11196 // Only handle constant-sized or VLAs, but not flexible members.
11197 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11198 // Only issue the FIXIT for arrays of size > 1.
11199 if (CAT->getZExtSize() <= 1)
11200 return false;
11201 } else if (!Ty->isVariableArrayType()) {
11202 return false;
11203 }
11204 return true;
11205}
11206
11207void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11208 IdentifierInfo *FnName) {
11209
11210 // Don't crash if the user has the wrong number of arguments
11211 unsigned NumArgs = Call->getNumArgs();
11212 if ((NumArgs != 3) && (NumArgs != 4))
11213 return;
11214
11215 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11216 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11217 const Expr *CompareWithSrc = nullptr;
11218
11219 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11220 Call->getBeginLoc(), Call->getRParenLoc()))
11221 return;
11222
11223 // Look for 'strlcpy(dst, x, sizeof(x))'
11224 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11225 CompareWithSrc = Ex;
11226 else {
11227 // Look for 'strlcpy(dst, x, strlen(x))'
11228 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11229 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11230 SizeCall->getNumArgs() == 1)
11231 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11232 }
11233 }
11234
11235 if (!CompareWithSrc)
11236 return;
11237
11238 // Determine if the argument to sizeof/strlen is equal to the source
11239 // argument. In principle there's all kinds of things you could do
11240 // here, for instance creating an == expression and evaluating it with
11241 // EvaluateAsBooleanCondition, but this uses a more direct technique:
11242 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11243 if (!SrcArgDRE)
11244 return;
11245
11246 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11247 if (!CompareWithSrcDRE ||
11248 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11249 return;
11250
11251 const Expr *OriginalSizeArg = Call->getArg(2);
11252 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11253 << OriginalSizeArg->getSourceRange() << FnName;
11254
11255 // Output a FIXIT hint if the destination is an array (rather than a
11256 // pointer to an array). This could be enhanced to handle some
11257 // pointers if we know the actual size, like if DstArg is 'array+2'
11258 // we could say 'sizeof(array)-2'.
11259 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11261 return;
11262
11263 SmallString<128> sizeString;
11264 llvm::raw_svector_ostream OS(sizeString);
11265 OS << "sizeof(";
11266 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11267 OS << ")";
11268
11269 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11270 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11271 OS.str());
11272}
11273
11274/// Check if two expressions refer to the same declaration.
11275static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11276 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11277 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11278 return D1->getDecl() == D2->getDecl();
11279 return false;
11280}
11281
11282static const Expr *getStrlenExprArg(const Expr *E) {
11283 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11284 const FunctionDecl *FD = CE->getDirectCallee();
11285 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11286 return nullptr;
11287 return CE->getArg(0)->IgnoreParenCasts();
11288 }
11289 return nullptr;
11290}
11291
11292void Sema::CheckStrncatArguments(const CallExpr *CE,
11293 const IdentifierInfo *FnName) {
11294 // Don't crash if the user has the wrong number of arguments.
11295 if (CE->getNumArgs() < 3)
11296 return;
11297 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11298 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11299 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11300
11301 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11302 CE->getRParenLoc()))
11303 return;
11304
11305 // Identify common expressions, which are wrongly used as the size argument
11306 // to strncat and may lead to buffer overflows.
11307 unsigned PatternType = 0;
11308 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11309 // - sizeof(dst)
11310 if (referToTheSameDecl(SizeOfArg, DstArg))
11311 PatternType = 1;
11312 // - sizeof(src)
11313 else if (referToTheSameDecl(SizeOfArg, SrcArg))
11314 PatternType = 2;
11315 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11316 if (BE->getOpcode() == BO_Sub) {
11317 const Expr *L = BE->getLHS()->IgnoreParenCasts();
11318 const Expr *R = BE->getRHS()->IgnoreParenCasts();
11319 // - sizeof(dst) - strlen(dst)
11320 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11322 PatternType = 1;
11323 // - sizeof(src) - (anything)
11324 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11325 PatternType = 2;
11326 }
11327 }
11328
11329 if (PatternType == 0)
11330 return;
11331
11332 // Generate the diagnostic.
11333 SourceLocation SL = LenArg->getBeginLoc();
11334 SourceRange SR = LenArg->getSourceRange();
11335 SourceManager &SM = getSourceManager();
11336
11337 // If the function is defined as a builtin macro, do not show macro expansion.
11338 if (SM.isMacroArgExpansion(SL)) {
11339 SL = SM.getSpellingLoc(SL);
11340 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11341 SM.getSpellingLoc(SR.getEnd()));
11342 }
11343
11344 // Check if the destination is an array (rather than a pointer to an array).
11345 QualType DstTy = DstArg->getType();
11346 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11347 Context);
11348 if (!isKnownSizeArray) {
11349 if (PatternType == 1)
11350 Diag(SL, diag::warn_strncat_wrong_size) << SR;
11351 else
11352 Diag(SL, diag::warn_strncat_src_size) << SR;
11353 return;
11354 }
11355
11356 if (PatternType == 1)
11357 Diag(SL, diag::warn_strncat_large_size) << SR;
11358 else
11359 Diag(SL, diag::warn_strncat_src_size) << SR;
11360
11361 SmallString<128> sizeString;
11362 llvm::raw_svector_ostream OS(sizeString);
11363 OS << "sizeof(";
11364 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11365 OS << ") - ";
11366 OS << "strlen(";
11367 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11368 OS << ") - 1";
11369
11370 Diag(SL, diag::note_strncat_wrong_size)
11371 << FixItHint::CreateReplacement(SR, OS.str());
11372}
11373
11374namespace {
11375void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11376 const UnaryOperator *UnaryExpr, const Decl *D) {
11378 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11379 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11380 return;
11381 }
11382}
11383
11384void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11385 const UnaryOperator *UnaryExpr) {
11386 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11387 const Decl *D = Lvalue->getDecl();
11388 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11389 if (!DD->getType()->isReferenceType())
11390 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11391 }
11392 }
11393
11394 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11395 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11396 Lvalue->getMemberDecl());
11397}
11398
11399void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11400 const UnaryOperator *UnaryExpr) {
11401 const auto *Lambda = dyn_cast<LambdaExpr>(
11403 if (!Lambda)
11404 return;
11405
11406 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11407 << CalleeName << 2 /*object: lambda expression*/;
11408}
11409
11410void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11411 const DeclRefExpr *Lvalue) {
11412 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11413 if (Var == nullptr)
11414 return;
11415
11416 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11417 << CalleeName << 0 /*object: */ << Var;
11418}
11419
11420void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11421 const CastExpr *Cast) {
11422 SmallString<128> SizeString;
11423 llvm::raw_svector_ostream OS(SizeString);
11424
11425 clang::CastKind Kind = Cast->getCastKind();
11426 if (Kind == clang::CK_BitCast &&
11427 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11428 return;
11429 if (Kind == clang::CK_IntegralToPointer &&
11431 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11432 return;
11433
11434 switch (Cast->getCastKind()) {
11435 case clang::CK_BitCast:
11436 case clang::CK_IntegralToPointer:
11437 case clang::CK_FunctionToPointerDecay:
11438 OS << '\'';
11439 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11440 OS << '\'';
11441 break;
11442 default:
11443 return;
11444 }
11445
11446 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11447 << CalleeName << 0 /*object: */ << OS.str();
11448}
11449} // namespace
11450
11451void Sema::CheckFreeArguments(const CallExpr *E) {
11452 const std::string CalleeName =
11453 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11454
11455 { // Prefer something that doesn't involve a cast to make things simpler.
11456 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11457 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11458 switch (UnaryExpr->getOpcode()) {
11459 case UnaryOperator::Opcode::UO_AddrOf:
11460 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11461 case UnaryOperator::Opcode::UO_Plus:
11462 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11463 default:
11464 break;
11465 }
11466
11467 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11468 if (Lvalue->getType()->isArrayType())
11469 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11470
11471 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11472 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11473 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11474 return;
11475 }
11476
11477 if (isa<BlockExpr>(Arg)) {
11478 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11479 << CalleeName << 1 /*object: block*/;
11480 return;
11481 }
11482 }
11483 // Maybe the cast was important, check after the other cases.
11484 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11485 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11486}
11487
11488void
11489Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11490 SourceLocation ReturnLoc,
11491 bool isObjCMethod,
11492 const AttrVec *Attrs,
11493 const FunctionDecl *FD) {
11494 // Check if the return value is null but should not be.
11495 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11496 (!isObjCMethod && isNonNullType(lhsType))) &&
11497 CheckNonNullExpr(*this, RetValExp))
11498 Diag(ReturnLoc, diag::warn_null_ret)
11499 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11500
11501 // C++11 [basic.stc.dynamic.allocation]p4:
11502 // If an allocation function declared with a non-throwing
11503 // exception-specification fails to allocate storage, it shall return
11504 // a null pointer. Any other allocation function that fails to allocate
11505 // storage shall indicate failure only by throwing an exception [...]
11506 if (FD) {
11508 if (Op == OO_New || Op == OO_Array_New) {
11509 const FunctionProtoType *Proto
11510 = FD->getType()->castAs<FunctionProtoType>();
11511 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11512 CheckNonNullExpr(*this, RetValExp))
11513 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11514 << FD << getLangOpts().CPlusPlus11;
11515 }
11516 }
11517
11518 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11519 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
11520 }
11521
11522 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11523 // here prevent the user from using a PPC MMA type as trailing return type.
11524 if (Context.getTargetInfo().getTriple().isPPC64())
11525 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11526}
11527
11529 const Expr *RHS, BinaryOperatorKind Opcode) {
11530 if (!BinaryOperator::isEqualityOp(Opcode))
11531 return;
11532
11533 // Match and capture subexpressions such as "(float) X == 0.1".
11534 const FloatingLiteral *FPLiteral;
11535 const CastExpr *FPCast;
11536 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11537 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11538 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11539 return FPLiteral && FPCast;
11540 };
11541
11542 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11543 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11544 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11545 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11546 TargetTy->isFloatingPoint()) {
11547 bool Lossy;
11548 llvm::APFloat TargetC = FPLiteral->getValue();
11549 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11550 llvm::APFloat::rmNearestTiesToEven, &Lossy);
11551 if (Lossy) {
11552 // If the literal cannot be represented in the source type, then a
11553 // check for == is always false and check for != is always true.
11554 Diag(Loc, diag::warn_float_compare_literal)
11555 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11556 << LHS->getSourceRange() << RHS->getSourceRange();
11557 return;
11558 }
11559 }
11560 }
11561
11562 // Match a more general floating-point equality comparison (-Wfloat-equal).
11563 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11564 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11565
11566 // Special case: check for x == x (which is OK).
11567 // Do not emit warnings for such cases.
11568 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11569 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11570 if (DRL->getDecl() == DRR->getDecl())
11571 return;
11572
11573 // Special case: check for comparisons against literals that can be exactly
11574 // represented by APFloat. In such cases, do not emit a warning. This
11575 // is a heuristic: often comparison against such literals are used to
11576 // detect if a value in a variable has not changed. This clearly can
11577 // lead to false negatives.
11578 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11579 if (FLL->isExact())
11580 return;
11581 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11582 if (FLR->isExact())
11583 return;
11584
11585 // Check for comparisons with builtin types.
11586 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
11587 CL && CL->getBuiltinCallee())
11588 return;
11589
11590 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
11591 CR && CR->getBuiltinCallee())
11592 return;
11593
11594 // Emit the diagnostic.
11595 Diag(Loc, diag::warn_floatingpoint_eq)
11596 << LHS->getSourceRange() << RHS->getSourceRange();
11597}
11598
11599//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11600//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11601
11602namespace {
11603
11604/// Structure recording the 'active' range of an integer-valued
11605/// expression.
11606struct IntRange {
11607 /// The number of bits active in the int. Note that this includes exactly one
11608 /// sign bit if !NonNegative.
11609 unsigned Width;
11610
11611 /// True if the int is known not to have negative values. If so, all leading
11612 /// bits before Width are known zero, otherwise they are known to be the
11613 /// same as the MSB within Width.
11614 bool NonNegative;
11615
11616 IntRange(unsigned Width, bool NonNegative)
11617 : Width(Width), NonNegative(NonNegative) {}
11618
11619 /// Number of bits excluding the sign bit.
11620 unsigned valueBits() const {
11621 return NonNegative ? Width : Width - 1;
11622 }
11623
11624 /// Returns the range of the bool type.
11625 static IntRange forBoolType() {
11626 return IntRange(1, true);
11627 }
11628
11629 /// Returns the range of an opaque value of the given integral type.
11630 static IntRange forValueOfType(ASTContext &C, QualType T) {
11631 return forValueOfCanonicalType(C,
11633 }
11634
11635 /// Returns the range of an opaque value of a canonical integral type.
11636 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11637 assert(T->isCanonicalUnqualified());
11638
11639 if (const auto *VT = dyn_cast<VectorType>(T))
11640 T = VT->getElementType().getTypePtr();
11641 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11642 T = MT->getElementType().getTypePtr();
11643 if (const auto *CT = dyn_cast<ComplexType>(T))
11644 T = CT->getElementType().getTypePtr();
11645 if (const auto *AT = dyn_cast<AtomicType>(T))
11646 T = AT->getValueType().getTypePtr();
11647 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11648 T = OBT->getUnderlyingType().getTypePtr();
11649
11650 if (!C.getLangOpts().CPlusPlus) {
11651 // For enum types in C code, use the underlying datatype.
11652 if (const auto *ED = T->getAsEnumDecl())
11653 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
11654 } else if (auto *Enum = T->getAsEnumDecl()) {
11655 // For enum types in C++, use the known bit width of the enumerators.
11656 // In C++11, enums can have a fixed underlying type. Use this type to
11657 // compute the range.
11658 if (Enum->isFixed()) {
11659 return IntRange(C.getIntWidth(QualType(T, 0)),
11660 !Enum->getIntegerType()->isSignedIntegerType());
11661 }
11662
11663 unsigned NumPositive = Enum->getNumPositiveBits();
11664 unsigned NumNegative = Enum->getNumNegativeBits();
11665
11666 if (NumNegative == 0)
11667 return IntRange(NumPositive, true/*NonNegative*/);
11668 else
11669 return IntRange(std::max(NumPositive + 1, NumNegative),
11670 false/*NonNegative*/);
11671 }
11672
11673 if (const auto *EIT = dyn_cast<BitIntType>(T))
11674 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11675
11676 const BuiltinType *BT = cast<BuiltinType>(T);
11677 assert(BT->isInteger());
11678
11679 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11680 }
11681
11682 /// Returns the "target" range of a canonical integral type, i.e.
11683 /// the range of values expressible in the type.
11684 ///
11685 /// This matches forValueOfCanonicalType except that enums have the
11686 /// full range of their type, not the range of their enumerators.
11687 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11688 assert(T->isCanonicalUnqualified());
11689
11690 if (const VectorType *VT = dyn_cast<VectorType>(T))
11691 T = VT->getElementType().getTypePtr();
11692 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11693 T = MT->getElementType().getTypePtr();
11694 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11695 T = CT->getElementType().getTypePtr();
11696 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11697 T = AT->getValueType().getTypePtr();
11698 if (const auto *ED = T->getAsEnumDecl())
11699 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
11700 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11701 T = OBT->getUnderlyingType().getTypePtr();
11702
11703 if (const auto *EIT = dyn_cast<BitIntType>(T))
11704 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11705
11706 const BuiltinType *BT = cast<BuiltinType>(T);
11707 assert(BT->isInteger());
11708
11709 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11710 }
11711
11712 /// Returns the supremum of two ranges: i.e. their conservative merge.
11713 static IntRange join(IntRange L, IntRange R) {
11714 bool Unsigned = L.NonNegative && R.NonNegative;
11715 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11716 L.NonNegative && R.NonNegative);
11717 }
11718
11719 /// Return the range of a bitwise-AND of the two ranges.
11720 static IntRange bit_and(IntRange L, IntRange R) {
11721 unsigned Bits = std::max(L.Width, R.Width);
11722 bool NonNegative = false;
11723 if (L.NonNegative) {
11724 Bits = std::min(Bits, L.Width);
11725 NonNegative = true;
11726 }
11727 if (R.NonNegative) {
11728 Bits = std::min(Bits, R.Width);
11729 NonNegative = true;
11730 }
11731 return IntRange(Bits, NonNegative);
11732 }
11733
11734 /// Return the range of a sum of the two ranges.
11735 static IntRange sum(IntRange L, IntRange R) {
11736 bool Unsigned = L.NonNegative && R.NonNegative;
11737 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11738 Unsigned);
11739 }
11740
11741 /// Return the range of a difference of the two ranges.
11742 static IntRange difference(IntRange L, IntRange R) {
11743 // We need a 1-bit-wider range if:
11744 // 1) LHS can be negative: least value can be reduced.
11745 // 2) RHS can be negative: greatest value can be increased.
11746 bool CanWiden = !L.NonNegative || !R.NonNegative;
11747 bool Unsigned = L.NonNegative && R.Width == 0;
11748 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11749 !Unsigned,
11750 Unsigned);
11751 }
11752
11753 /// Return the range of a product of the two ranges.
11754 static IntRange product(IntRange L, IntRange R) {
11755 // If both LHS and RHS can be negative, we can form
11756 // -2^L * -2^R = 2^(L + R)
11757 // which requires L + R + 1 value bits to represent.
11758 bool CanWiden = !L.NonNegative && !R.NonNegative;
11759 bool Unsigned = L.NonNegative && R.NonNegative;
11760 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11761 Unsigned);
11762 }
11763
11764 /// Return the range of a remainder operation between the two ranges.
11765 static IntRange rem(IntRange L, IntRange R) {
11766 // The result of a remainder can't be larger than the result of
11767 // either side. The sign of the result is the sign of the LHS.
11768 bool Unsigned = L.NonNegative;
11769 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11770 Unsigned);
11771 }
11772};
11773
11774} // namespace
11775
11776static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11777 if (value.isSigned() && value.isNegative())
11778 return IntRange(value.getSignificantBits(), false);
11779
11780 if (value.getBitWidth() > MaxWidth)
11781 value = value.trunc(MaxWidth);
11782
11783 // isNonNegative() just checks the sign bit without considering
11784 // signedness.
11785 return IntRange(value.getActiveBits(), true);
11786}
11787
11788static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11789 if (result.isInt())
11790 return GetValueRange(result.getInt(), MaxWidth);
11791
11792 if (result.isVector()) {
11793 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
11794 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11795 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
11796 R = IntRange::join(R, El);
11797 }
11798 return R;
11799 }
11800
11801 if (result.isComplexInt()) {
11802 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
11803 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
11804 return IntRange::join(R, I);
11805 }
11806
11807 // This can happen with lossless casts to intptr_t of "based" lvalues.
11808 // Assume it might use arbitrary bits.
11809 // FIXME: The only reason we need to pass the type in here is to get
11810 // the sign right on this one case. It would be nice if APValue
11811 // preserved this.
11812 assert(result.isLValue() || result.isAddrLabelDiff());
11813 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11814}
11815
11816static QualType GetExprType(const Expr *E) {
11817 QualType Ty = E->getType();
11818 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11819 Ty = AtomicRHS->getValueType();
11820 return Ty;
11821}
11822
11823/// Attempts to estimate an approximate range for the given integer expression.
11824/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11825/// reliable estimation cannot be determined.
11826///
11827/// \param MaxWidth The width to which the value will be truncated.
11828/// \param InConstantContext If \c true, interpret the expression within a
11829/// constant context.
11830/// \param Approximate If \c true, provide a likely range of values by assuming
11831/// that arithmetic on narrower types remains within those types.
11832/// If \c false, return a range that includes all possible values
11833/// resulting from the expression.
11834/// \returns A range of values that the expression might take, or
11835/// std::nullopt if a reliable estimation cannot be determined.
11836static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11837 unsigned MaxWidth,
11838 bool InConstantContext,
11839 bool Approximate) {
11840 E = E->IgnoreParens();
11841
11842 // Try a full evaluation first.
11843 Expr::EvalResult result;
11844 if (E->EvaluateAsRValue(result, C, InConstantContext))
11845 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
11846
11847 // I think we only want to look through implicit casts here; if the
11848 // user has an explicit widening cast, we should treat the value as
11849 // being of the new, wider type.
11850 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11851 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11852 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11853 Approximate);
11854
11855 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11856
11857 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11858 CE->getCastKind() == CK_BooleanToSignedIntegral;
11859
11860 // Assume that non-integer casts can span the full range of the type.
11861 if (!isIntegerCast)
11862 return OutputTypeRange;
11863
11864 std::optional<IntRange> SubRange = TryGetExprRange(
11865 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
11866 InConstantContext, Approximate);
11867 if (!SubRange)
11868 return std::nullopt;
11869
11870 // Bail out if the subexpr's range is as wide as the cast type.
11871 if (SubRange->Width >= OutputTypeRange.Width)
11872 return OutputTypeRange;
11873
11874 // Otherwise, we take the smaller width, and we're non-negative if
11875 // either the output type or the subexpr is.
11876 return IntRange(SubRange->Width,
11877 SubRange->NonNegative || OutputTypeRange.NonNegative);
11878 }
11879
11880 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11881 // If we can fold the condition, just take that operand.
11882 bool CondResult;
11883 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11884 return TryGetExprRange(
11885 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
11886 InConstantContext, Approximate);
11887
11888 // Otherwise, conservatively merge.
11889 // TryGetExprRange requires an integer expression, but a throw expression
11890 // results in a void type.
11891 Expr *TrueExpr = CO->getTrueExpr();
11892 if (TrueExpr->getType()->isVoidType())
11893 return std::nullopt;
11894
11895 std::optional<IntRange> L =
11896 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
11897 if (!L)
11898 return std::nullopt;
11899
11900 Expr *FalseExpr = CO->getFalseExpr();
11901 if (FalseExpr->getType()->isVoidType())
11902 return std::nullopt;
11903
11904 std::optional<IntRange> R =
11905 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
11906 if (!R)
11907 return std::nullopt;
11908
11909 return IntRange::join(*L, *R);
11910 }
11911
11912 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11913 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11914
11915 switch (BO->getOpcode()) {
11916 case BO_Cmp:
11917 llvm_unreachable("builtin <=> should have class type");
11918
11919 // Boolean-valued operations are single-bit and positive.
11920 case BO_LAnd:
11921 case BO_LOr:
11922 case BO_LT:
11923 case BO_GT:
11924 case BO_LE:
11925 case BO_GE:
11926 case BO_EQ:
11927 case BO_NE:
11928 return IntRange::forBoolType();
11929
11930 // The type of the assignments is the type of the LHS, so the RHS
11931 // is not necessarily the same type.
11932 case BO_MulAssign:
11933 case BO_DivAssign:
11934 case BO_RemAssign:
11935 case BO_AddAssign:
11936 case BO_SubAssign:
11937 case BO_XorAssign:
11938 case BO_OrAssign:
11939 // TODO: bitfields?
11940 return IntRange::forValueOfType(C, GetExprType(E));
11941
11942 // Simple assignments just pass through the RHS, which will have
11943 // been coerced to the LHS type.
11944 case BO_Assign:
11945 // TODO: bitfields?
11946 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11947 Approximate);
11948
11949 // Operations with opaque sources are black-listed.
11950 case BO_PtrMemD:
11951 case BO_PtrMemI:
11952 return IntRange::forValueOfType(C, GetExprType(E));
11953
11954 // Bitwise-and uses the *infinum* of the two source ranges.
11955 case BO_And:
11956 case BO_AndAssign:
11957 Combine = IntRange::bit_and;
11958 break;
11959
11960 // Left shift gets black-listed based on a judgement call.
11961 case BO_Shl:
11962 // ...except that we want to treat '1 << (blah)' as logically
11963 // positive. It's an important idiom.
11964 if (IntegerLiteral *I
11965 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11966 if (I->getValue() == 1) {
11967 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11968 return IntRange(R.Width, /*NonNegative*/ true);
11969 }
11970 }
11971 [[fallthrough]];
11972
11973 case BO_ShlAssign:
11974 return IntRange::forValueOfType(C, GetExprType(E));
11975
11976 // Right shift by a constant can narrow its left argument.
11977 case BO_Shr:
11978 case BO_ShrAssign: {
11979 std::optional<IntRange> L = TryGetExprRange(
11980 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11981 if (!L)
11982 return std::nullopt;
11983
11984 // If the shift amount is a positive constant, drop the width by
11985 // that much.
11986 if (std::optional<llvm::APSInt> shift =
11987 BO->getRHS()->getIntegerConstantExpr(C)) {
11988 if (shift->isNonNegative()) {
11989 if (shift->uge(L->Width))
11990 L->Width = (L->NonNegative ? 0 : 1);
11991 else
11992 L->Width -= shift->getZExtValue();
11993 }
11994 }
11995
11996 return L;
11997 }
11998
11999 // Comma acts as its right operand.
12000 case BO_Comma:
12001 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
12002 Approximate);
12003
12004 case BO_Add:
12005 if (!Approximate)
12006 Combine = IntRange::sum;
12007 break;
12008
12009 case BO_Sub:
12010 if (BO->getLHS()->getType()->isPointerType())
12011 return IntRange::forValueOfType(C, GetExprType(E));
12012 if (!Approximate)
12013 Combine = IntRange::difference;
12014 break;
12015
12016 case BO_Mul:
12017 if (!Approximate)
12018 Combine = IntRange::product;
12019 break;
12020
12021 // The width of a division result is mostly determined by the size
12022 // of the LHS.
12023 case BO_Div: {
12024 // Don't 'pre-truncate' the operands.
12025 unsigned opWidth = C.getIntWidth(GetExprType(E));
12026 std::optional<IntRange> L = TryGetExprRange(
12027 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
12028 if (!L)
12029 return std::nullopt;
12030
12031 // If the divisor is constant, use that.
12032 if (std::optional<llvm::APSInt> divisor =
12033 BO->getRHS()->getIntegerConstantExpr(C)) {
12034 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
12035 if (log2 >= L->Width)
12036 L->Width = (L->NonNegative ? 0 : 1);
12037 else
12038 L->Width = std::min(L->Width - log2, MaxWidth);
12039 return L;
12040 }
12041
12042 // Otherwise, just use the LHS's width.
12043 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
12044 // could be -1.
12045 std::optional<IntRange> R = TryGetExprRange(
12046 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
12047 if (!R)
12048 return std::nullopt;
12049
12050 return IntRange(L->Width, L->NonNegative && R->NonNegative);
12051 }
12052
12053 case BO_Rem:
12054 Combine = IntRange::rem;
12055 break;
12056
12057 // The default behavior is okay for these.
12058 case BO_Xor:
12059 case BO_Or:
12060 break;
12061 }
12062
12063 // Combine the two ranges, but limit the result to the type in which we
12064 // performed the computation.
12065 QualType T = GetExprType(E);
12066 unsigned opWidth = C.getIntWidth(T);
12067 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
12068 InConstantContext, Approximate);
12069 if (!L)
12070 return std::nullopt;
12071
12072 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
12073 InConstantContext, Approximate);
12074 if (!R)
12075 return std::nullopt;
12076
12077 IntRange C = Combine(*L, *R);
12078 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
12079 C.Width = std::min(C.Width, MaxWidth);
12080 return C;
12081 }
12082
12083 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12084 switch (UO->getOpcode()) {
12085 // Boolean-valued operations are white-listed.
12086 case UO_LNot:
12087 return IntRange::forBoolType();
12088
12089 // Operations with opaque sources are black-listed.
12090 case UO_Deref:
12091 case UO_AddrOf: // should be impossible
12092 return IntRange::forValueOfType(C, GetExprType(E));
12093
12094 case UO_Minus: {
12095 if (E->getType()->isUnsignedIntegerType()) {
12096 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12097 Approximate);
12098 }
12099
12100 std::optional<IntRange> SubRange = TryGetExprRange(
12101 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12102
12103 if (!SubRange)
12104 return std::nullopt;
12105
12106 // If the range was previously non-negative, we need an extra bit for the
12107 // sign bit. Otherwise, we need an extra bit because the negation of the
12108 // most-negative value is one bit wider than that value.
12109 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
12110 }
12111
12112 case UO_Not: {
12113 if (E->getType()->isUnsignedIntegerType()) {
12114 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12115 Approximate);
12116 }
12117
12118 std::optional<IntRange> SubRange = TryGetExprRange(
12119 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12120
12121 if (!SubRange)
12122 return std::nullopt;
12123
12124 // The width increments by 1 if the sub-expression cannot be negative
12125 // since it now can be.
12126 return IntRange(
12127 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
12128 false);
12129 }
12130
12131 default:
12132 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12133 Approximate);
12134 }
12135 }
12136
12137 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12138 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
12139 Approximate);
12140
12141 if (const auto *BitField = E->getSourceBitField())
12142 return IntRange(BitField->getBitWidthValue(),
12143 BitField->getType()->isUnsignedIntegerOrEnumerationType());
12144
12145 if (GetExprType(E)->isVoidType())
12146 return std::nullopt;
12147
12148 return IntRange::forValueOfType(C, GetExprType(E));
12149}
12150
12151static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12152 bool InConstantContext,
12153 bool Approximate) {
12154 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
12155 Approximate);
12156}
12157
12158/// Checks whether the given value, which currently has the given
12159/// source semantics, has the same value when coerced through the
12160/// target semantics.
12161static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12162 const llvm::fltSemantics &Src,
12163 const llvm::fltSemantics &Tgt) {
12164 llvm::APFloat truncated = value;
12165
12166 bool ignored;
12167 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
12168 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
12169
12170 return truncated.bitwiseIsEqual(value);
12171}
12172
12173/// Checks whether the given value, which currently has the given
12174/// source semantics, has the same value when coerced through the
12175/// target semantics.
12176///
12177/// The value might be a vector of floats (or a complex number).
12178static bool IsSameFloatAfterCast(const APValue &value,
12179 const llvm::fltSemantics &Src,
12180 const llvm::fltSemantics &Tgt) {
12181 if (value.isFloat())
12182 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
12183
12184 if (value.isVector()) {
12185 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12186 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
12187 return false;
12188 return true;
12189 }
12190
12191 if (value.isMatrix()) {
12192 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
12193 if (!IsSameFloatAfterCast(value.getMatrixElt(i), Src, Tgt))
12194 return false;
12195 return true;
12196 }
12197
12198 assert(value.isComplexFloat());
12199 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
12200 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
12201}
12202
12203static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12204 bool IsListInit = false);
12205
12206static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
12207 // Suppress cases where we are comparing against an enum constant.
12208 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
12209 if (isa<EnumConstantDecl>(DR->getDecl()))
12210 return true;
12211
12212 // Suppress cases where the value is expanded from a macro, unless that macro
12213 // is how a language represents a boolean literal. This is the case in both C
12214 // and Objective-C.
12215 SourceLocation BeginLoc = E->getBeginLoc();
12216 if (BeginLoc.isMacroID()) {
12217 StringRef MacroName = Lexer::getImmediateMacroName(
12218 BeginLoc, S.getSourceManager(), S.getLangOpts());
12219 return MacroName != "YES" && MacroName != "NO" &&
12220 MacroName != "true" && MacroName != "false";
12221 }
12222
12223 return false;
12224}
12225
12226static bool isKnownToHaveUnsignedValue(const Expr *E) {
12227 return E->getType()->isIntegerType() &&
12228 (!E->getType()->isSignedIntegerType() ||
12230}
12231
12232namespace {
12233/// The promoted range of values of a type. In general this has the
12234/// following structure:
12235///
12236/// |-----------| . . . |-----------|
12237/// ^ ^ ^ ^
12238/// Min HoleMin HoleMax Max
12239///
12240/// ... where there is only a hole if a signed type is promoted to unsigned
12241/// (in which case Min and Max are the smallest and largest representable
12242/// values).
12243struct PromotedRange {
12244 // Min, or HoleMax if there is a hole.
12245 llvm::APSInt PromotedMin;
12246 // Max, or HoleMin if there is a hole.
12247 llvm::APSInt PromotedMax;
12248
12249 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12250 if (R.Width == 0)
12251 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12252 else if (R.Width >= BitWidth && !Unsigned) {
12253 // Promotion made the type *narrower*. This happens when promoting
12254 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12255 // Treat all values of 'signed int' as being in range for now.
12256 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12257 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12258 } else {
12259 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12260 .extOrTrunc(BitWidth);
12261 PromotedMin.setIsUnsigned(Unsigned);
12262
12263 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12264 .extOrTrunc(BitWidth);
12265 PromotedMax.setIsUnsigned(Unsigned);
12266 }
12267 }
12268
12269 // Determine whether this range is contiguous (has no hole).
12270 bool isContiguous() const { return PromotedMin <= PromotedMax; }
12271
12272 // Where a constant value is within the range.
12273 enum ComparisonResult {
12274 LT = 0x1,
12275 LE = 0x2,
12276 GT = 0x4,
12277 GE = 0x8,
12278 EQ = 0x10,
12279 NE = 0x20,
12280 InRangeFlag = 0x40,
12281
12282 Less = LE | LT | NE,
12283 Min = LE | InRangeFlag,
12284 InRange = InRangeFlag,
12285 Max = GE | InRangeFlag,
12286 Greater = GE | GT | NE,
12287
12288 OnlyValue = LE | GE | EQ | InRangeFlag,
12289 InHole = NE
12290 };
12291
12292 ComparisonResult compare(const llvm::APSInt &Value) const {
12293 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12294 Value.isUnsigned() == PromotedMin.isUnsigned());
12295 if (!isContiguous()) {
12296 assert(Value.isUnsigned() && "discontiguous range for signed compare");
12297 if (Value.isMinValue()) return Min;
12298 if (Value.isMaxValue()) return Max;
12299 if (Value >= PromotedMin) return InRange;
12300 if (Value <= PromotedMax) return InRange;
12301 return InHole;
12302 }
12303
12304 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12305 case -1: return Less;
12306 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12307 case 1:
12308 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12309 case -1: return InRange;
12310 case 0: return Max;
12311 case 1: return Greater;
12312 }
12313 }
12314
12315 llvm_unreachable("impossible compare result");
12316 }
12317
12318 static std::optional<StringRef>
12319 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12320 if (Op == BO_Cmp) {
12321 ComparisonResult LTFlag = LT, GTFlag = GT;
12322 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12323
12324 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12325 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12326 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12327 return std::nullopt;
12328 }
12329
12330 ComparisonResult TrueFlag, FalseFlag;
12331 if (Op == BO_EQ) {
12332 TrueFlag = EQ;
12333 FalseFlag = NE;
12334 } else if (Op == BO_NE) {
12335 TrueFlag = NE;
12336 FalseFlag = EQ;
12337 } else {
12338 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12339 TrueFlag = LT;
12340 FalseFlag = GE;
12341 } else {
12342 TrueFlag = GT;
12343 FalseFlag = LE;
12344 }
12345 if (Op == BO_GE || Op == BO_LE)
12346 std::swap(TrueFlag, FalseFlag);
12347 }
12348 if (R & TrueFlag)
12349 return StringRef("true");
12350 if (R & FalseFlag)
12351 return StringRef("false");
12352 return std::nullopt;
12353 }
12354};
12355}
12356
12357static bool HasEnumType(const Expr *E) {
12358 // Strip off implicit integral promotions.
12359 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12360 if (ICE->getCastKind() != CK_IntegralCast &&
12361 ICE->getCastKind() != CK_NoOp)
12362 break;
12363 E = ICE->getSubExpr();
12364 }
12365
12366 return E->getType()->isEnumeralType();
12367}
12368
12370 // The values of this enumeration are used in the diagnostics
12371 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12372 enum ConstantValueKind {
12373 Miscellaneous = 0,
12374 LiteralTrue,
12375 LiteralFalse
12376 };
12377 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12378 return BL->getValue() ? ConstantValueKind::LiteralTrue
12379 : ConstantValueKind::LiteralFalse;
12380 return ConstantValueKind::Miscellaneous;
12381}
12382
12385 const llvm::APSInt &Value,
12386 bool RhsConstant) {
12388 return false;
12389
12390 Expr *OriginalOther = Other;
12391
12392 Constant = Constant->IgnoreParenImpCasts();
12393 Other = Other->IgnoreParenImpCasts();
12394
12395 // Suppress warnings on tautological comparisons between values of the same
12396 // enumeration type. There are only two ways we could warn on this:
12397 // - If the constant is outside the range of representable values of
12398 // the enumeration. In such a case, we should warn about the cast
12399 // to enumeration type, not about the comparison.
12400 // - If the constant is the maximum / minimum in-range value. For an
12401 // enumeratin type, such comparisons can be meaningful and useful.
12402 if (Constant->getType()->isEnumeralType() &&
12403 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12404 return false;
12405
12406 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12407 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
12408 if (!OtherValueRange)
12409 return false;
12410
12411 QualType OtherT = Other->getType();
12412 if (const auto *AT = OtherT->getAs<AtomicType>())
12413 OtherT = AT->getValueType();
12414 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12415
12416 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12417 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12418 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12419 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
12420 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12421
12422 // Whether we're treating Other as being a bool because of the form of
12423 // expression despite it having another type (typically 'int' in C).
12424 bool OtherIsBooleanDespiteType =
12425 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12426 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12427 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12428
12429 // Check if all values in the range of possible values of this expression
12430 // lead to the same comparison outcome.
12431 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12432 Value.isUnsigned());
12433 auto Cmp = OtherPromotedValueRange.compare(Value);
12434 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12435 if (!Result)
12436 return false;
12437
12438 // Also consider the range determined by the type alone. This allows us to
12439 // classify the warning under the proper diagnostic group.
12440 bool TautologicalTypeCompare = false;
12441 {
12442 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12443 Value.isUnsigned());
12444 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12445 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12446 RhsConstant)) {
12447 TautologicalTypeCompare = true;
12448 Cmp = TypeCmp;
12450 }
12451 }
12452
12453 // Don't warn if the non-constant operand actually always evaluates to the
12454 // same value.
12455 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12456 return false;
12457
12458 // Suppress the diagnostic for an in-range comparison if the constant comes
12459 // from a macro or enumerator. We don't want to diagnose
12460 //
12461 // some_long_value <= INT_MAX
12462 //
12463 // when sizeof(int) == sizeof(long).
12464 bool InRange = Cmp & PromotedRange::InRangeFlag;
12465 if (InRange && IsEnumConstOrFromMacro(S, Constant))
12466 return false;
12467
12468 // A comparison of an unsigned bit-field against 0 is really a type problem,
12469 // even though at the type level the bit-field might promote to 'signed int'.
12470 if (Other->refersToBitField() && InRange && Value == 0 &&
12471 Other->getType()->isUnsignedIntegerOrEnumerationType())
12472 TautologicalTypeCompare = true;
12473
12474 // If this is a comparison to an enum constant, include that
12475 // constant in the diagnostic.
12476 const EnumConstantDecl *ED = nullptr;
12477 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
12478 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12479
12480 // Should be enough for uint128 (39 decimal digits)
12481 SmallString<64> PrettySourceValue;
12482 llvm::raw_svector_ostream OS(PrettySourceValue);
12483 if (ED) {
12484 OS << '\'' << *ED << "' (" << Value << ")";
12485 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12486 Constant->IgnoreParenImpCasts())) {
12487 OS << (BL->getValue() ? "YES" : "NO");
12488 } else {
12489 OS << Value;
12490 }
12491
12492 if (!TautologicalTypeCompare) {
12493 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12494 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12495 << E->getOpcodeStr() << OS.str() << *Result
12496 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12497 return true;
12498 }
12499
12500 if (IsObjCSignedCharBool) {
12502 S.PDiag(diag::warn_tautological_compare_objc_bool)
12503 << OS.str() << *Result);
12504 return true;
12505 }
12506
12507 // FIXME: We use a somewhat different formatting for the in-range cases and
12508 // cases involving boolean values for historical reasons. We should pick a
12509 // consistent way of presenting these diagnostics.
12510 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12511
12513 E->getOperatorLoc(), E,
12514 S.PDiag(!InRange ? diag::warn_out_of_range_compare
12515 : diag::warn_tautological_bool_compare)
12516 << OS.str() << classifyConstantValue(Constant) << OtherT
12517 << OtherIsBooleanDespiteType << *Result
12518 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12519 } else {
12520 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12521 unsigned Diag =
12522 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12523 ? (HasEnumType(OriginalOther)
12524 ? diag::warn_unsigned_enum_always_true_comparison
12525 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12526 : diag::warn_unsigned_always_true_comparison)
12527 : diag::warn_tautological_constant_compare;
12528
12529 S.Diag(E->getOperatorLoc(), Diag)
12530 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12531 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12532 }
12533
12534 return true;
12535}
12536
12537/// Analyze the operands of the given comparison. Implements the
12538/// fallback case from AnalyzeComparison.
12543
12544/// Implements -Wsign-compare.
12545///
12546/// \param E the binary operator to check for warnings
12548 // The type the comparison is being performed in.
12549 QualType T = E->getLHS()->getType();
12550
12551 // Only analyze comparison operators where both sides have been converted to
12552 // the same type.
12553 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12554 return AnalyzeImpConvsInComparison(S, E);
12555
12556 // Don't analyze value-dependent comparisons directly.
12557 if (E->isValueDependent())
12558 return AnalyzeImpConvsInComparison(S, E);
12559
12560 Expr *LHS = E->getLHS();
12561 Expr *RHS = E->getRHS();
12562
12563 if (T->isIntegralType(S.Context)) {
12564 std::optional<llvm::APSInt> RHSValue =
12566 std::optional<llvm::APSInt> LHSValue =
12568
12569 // We don't care about expressions whose result is a constant.
12570 if (RHSValue && LHSValue)
12571 return AnalyzeImpConvsInComparison(S, E);
12572
12573 // We only care about expressions where just one side is literal
12574 if ((bool)RHSValue ^ (bool)LHSValue) {
12575 // Is the constant on the RHS or LHS?
12576 const bool RhsConstant = (bool)RHSValue;
12577 Expr *Const = RhsConstant ? RHS : LHS;
12578 Expr *Other = RhsConstant ? LHS : RHS;
12579 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12580
12581 // Check whether an integer constant comparison results in a value
12582 // of 'true' or 'false'.
12583 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12584 return AnalyzeImpConvsInComparison(S, E);
12585 }
12586 }
12587
12588 if (!T->hasUnsignedIntegerRepresentation()) {
12589 // We don't do anything special if this isn't an unsigned integral
12590 // comparison: we're only interested in integral comparisons, and
12591 // signed comparisons only happen in cases we don't care to warn about.
12592 return AnalyzeImpConvsInComparison(S, E);
12593 }
12594
12595 LHS = LHS->IgnoreParenImpCasts();
12596 RHS = RHS->IgnoreParenImpCasts();
12597
12598 if (!S.getLangOpts().CPlusPlus) {
12599 // Avoid warning about comparison of integers with different signs when
12600 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12601 // the type of `E`.
12602 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12603 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12604 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12605 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12606 }
12607
12608 // Check to see if one of the (unmodified) operands is of different
12609 // signedness.
12610 Expr *signedOperand, *unsignedOperand;
12612 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12613 "unsigned comparison between two signed integer expressions?");
12614 signedOperand = LHS;
12615 unsignedOperand = RHS;
12616 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12617 signedOperand = RHS;
12618 unsignedOperand = LHS;
12619 } else {
12620 return AnalyzeImpConvsInComparison(S, E);
12621 }
12622
12623 // Otherwise, calculate the effective range of the signed operand.
12624 std::optional<IntRange> signedRange =
12626 /*Approximate=*/true);
12627 if (!signedRange)
12628 return;
12629
12630 // Go ahead and analyze implicit conversions in the operands. Note
12631 // that we skip the implicit conversions on both sides.
12634
12635 // If the signed range is non-negative, -Wsign-compare won't fire.
12636 if (signedRange->NonNegative)
12637 return;
12638
12639 // For (in)equality comparisons, if the unsigned operand is a
12640 // constant which cannot collide with a overflowed signed operand,
12641 // then reinterpreting the signed operand as unsigned will not
12642 // change the result of the comparison.
12643 if (E->isEqualityOp()) {
12644 unsigned comparisonWidth = S.Context.getIntWidth(T);
12645 std::optional<IntRange> unsignedRange = TryGetExprRange(
12646 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
12647 /*Approximate=*/true);
12648 if (!unsignedRange)
12649 return;
12650
12651 // We should never be unable to prove that the unsigned operand is
12652 // non-negative.
12653 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12654
12655 if (unsignedRange->Width < comparisonWidth)
12656 return;
12657 }
12658
12660 S.PDiag(diag::warn_mixed_sign_comparison)
12661 << LHS->getType() << RHS->getType()
12662 << LHS->getSourceRange() << RHS->getSourceRange());
12663}
12664
12665/// Analyzes an attempt to assign the given value to a bitfield.
12666///
12667/// Returns true if there was something fishy about the attempt.
12669 SourceLocation InitLoc) {
12670 assert(Bitfield->isBitField());
12671 if (Bitfield->isInvalidDecl())
12672 return false;
12673
12674 // White-list bool bitfields.
12675 QualType BitfieldType = Bitfield->getType();
12676 if (BitfieldType->isBooleanType())
12677 return false;
12678
12679 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12680 // If the underlying enum type was not explicitly specified as an unsigned
12681 // type and the enum contain only positive values, MSVC++ will cause an
12682 // inconsistency by storing this as a signed type.
12683 if (S.getLangOpts().CPlusPlus11 &&
12684 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12685 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12686 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12687 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12688 << BitfieldEnumDecl;
12689 }
12690 }
12691
12692 // Ignore value- or type-dependent expressions.
12693 if (Bitfield->getBitWidth()->isValueDependent() ||
12694 Bitfield->getBitWidth()->isTypeDependent() ||
12695 Init->isValueDependent() ||
12696 Init->isTypeDependent())
12697 return false;
12698
12699 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12700 unsigned FieldWidth = Bitfield->getBitWidthValue();
12701
12703 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12705 // The RHS is not constant. If the RHS has an enum type, make sure the
12706 // bitfield is wide enough to hold all the values of the enum without
12707 // truncation.
12708 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12709 const PreferredTypeAttr *PTAttr = nullptr;
12710 if (!ED) {
12711 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12712 if (PTAttr)
12713 ED = PTAttr->getType()->getAsEnumDecl();
12714 }
12715 if (ED) {
12716 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12717
12718 // Enum types are implicitly signed on Windows, so check if there are any
12719 // negative enumerators to see if the enum was intended to be signed or
12720 // not.
12721 bool SignedEnum = ED->getNumNegativeBits() > 0;
12722
12723 // Check for surprising sign changes when assigning enum values to a
12724 // bitfield of different signedness. If the bitfield is signed and we
12725 // have exactly the right number of bits to store this unsigned enum,
12726 // suggest changing the enum to an unsigned type. This typically happens
12727 // on Windows where unfixed enums always use an underlying type of 'int'.
12728 unsigned DiagID = 0;
12729 if (SignedEnum && !SignedBitfield) {
12730 DiagID =
12731 PTAttr == nullptr
12732 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12733 : diag::
12734 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12735 } else if (SignedBitfield && !SignedEnum &&
12736 ED->getNumPositiveBits() == FieldWidth) {
12737 DiagID =
12738 PTAttr == nullptr
12739 ? diag::warn_signed_bitfield_enum_conversion
12740 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12741 }
12742 if (DiagID) {
12743 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12744 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12745 SourceRange TypeRange =
12746 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12747 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12748 << SignedEnum << TypeRange;
12749 if (PTAttr)
12750 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12751 << ED;
12752 }
12753
12754 // Compute the required bitwidth. If the enum has negative values, we need
12755 // one more bit than the normal number of positive bits to represent the
12756 // sign bit.
12757 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12758 ED->getNumNegativeBits())
12759 : ED->getNumPositiveBits();
12760
12761 // Check the bitwidth.
12762 if (BitsNeeded > FieldWidth) {
12763 Expr *WidthExpr = Bitfield->getBitWidth();
12764 auto DiagID =
12765 PTAttr == nullptr
12766 ? diag::warn_bitfield_too_small_for_enum
12767 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12768 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12769 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12770 << BitsNeeded << ED << WidthExpr->getSourceRange();
12771 if (PTAttr)
12772 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12773 << ED;
12774 }
12775 }
12776
12777 return false;
12778 }
12779
12780 llvm::APSInt Value = Result.Val.getInt();
12781
12782 unsigned OriginalWidth = Value.getBitWidth();
12783
12784 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12785 // false positives where the user is demonstrating they intend to use the
12786 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12787 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12788 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12789 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12790 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12791 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
12792 S.findMacroSpelling(MaybeMacroLoc, "true"))
12793 return false;
12794 }
12795
12796 if (!Value.isSigned() || Value.isNegative())
12797 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12798 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12799 OriginalWidth = Value.getSignificantBits();
12800
12801 if (OriginalWidth <= FieldWidth)
12802 return false;
12803
12804 // Compute the value which the bitfield will contain.
12805 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12806 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12807
12808 // Check whether the stored value is equal to the original value.
12809 TruncatedValue = TruncatedValue.extend(OriginalWidth);
12810 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12811 return false;
12812
12813 std::string PrettyValue = toString(Value, 10);
12814 std::string PrettyTrunc = toString(TruncatedValue, 10);
12815
12816 S.Diag(InitLoc, OneAssignedToOneBitBitfield
12817 ? diag::warn_impcast_single_bit_bitield_precision_constant
12818 : diag::warn_impcast_bitfield_precision_constant)
12819 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12820 << Init->getSourceRange();
12821
12822 return true;
12823}
12824
12825/// Analyze the given simple or compound assignment for warning-worthy
12826/// operations.
12828 // Just recurse on the LHS.
12830
12831 // We want to recurse on the RHS as normal unless we're assigning to
12832 // a bitfield.
12833 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12834 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12835 E->getOperatorLoc())) {
12836 // Recurse, ignoring any implicit conversions on the RHS.
12838 E->getOperatorLoc());
12839 }
12840 }
12841
12842 // Set context flag for overflow behavior type assignment analysis, use RAII
12843 // pattern to handle nested assignments.
12844 llvm::SaveAndRestore OBTAssignmentContext(
12846
12848
12849 // Diagnose implicitly sequentially-consistent atomic assignment.
12850 if (E->getLHS()->getType()->isAtomicType())
12851 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12852}
12853
12854/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12855static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12856 QualType T, SourceLocation CContext, unsigned diag,
12857 bool PruneControlFlow = false) {
12858 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12859 // address space annotations isn't really useful. The warnings aren't because
12860 // you're converting a `private int` to `unsigned int`, it is because you're
12861 // conerting `int` to `unsigned int`.
12862 if (SourceType.hasAddressSpace())
12863 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
12864 if (T.hasAddressSpace())
12866 if (PruneControlFlow) {
12868 S.PDiag(diag)
12869 << SourceType << T << E->getSourceRange()
12870 << SourceRange(CContext));
12871 return;
12872 }
12873 S.Diag(E->getExprLoc(), diag)
12874 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12875}
12876
12877/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12878static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
12879 SourceLocation CContext, unsigned diag,
12880 bool PruneControlFlow = false) {
12881 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
12882}
12883
12884/// Diagnose an implicit cast from a floating point value to an integer value.
12885static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
12886 SourceLocation CContext) {
12887 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12888 bool PruneWarnings = S.inTemplateInstantiation();
12889
12890 const Expr *InnerE = E->IgnoreParenImpCasts();
12891 // We also want to warn on, e.g., "int i = -1.234"
12892 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
12893 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12894 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12895
12896 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12897
12898 llvm::APFloat Value(0.0);
12899 bool IsConstant =
12901 if (!IsConstant) {
12902 if (S.ObjC().isSignedCharBool(T)) {
12904 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12905 << E->getType());
12906 }
12907
12908 return DiagnoseImpCast(S, E, T, CContext,
12909 diag::warn_impcast_float_integer, PruneWarnings);
12910 }
12911
12912 bool isExact = false;
12913
12914 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12915 T->hasUnsignedIntegerRepresentation());
12916 llvm::APFloat::opStatus Result = Value.convertToInteger(
12917 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12918
12919 // FIXME: Force the precision of the source value down so we don't print
12920 // digits which are usually useless (we don't really care here if we
12921 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12922 // would automatically print the shortest representation, but it's a bit
12923 // tricky to implement.
12924 SmallString<16> PrettySourceValue;
12925 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12926 precision = (precision * 59 + 195) / 196;
12927 Value.toString(PrettySourceValue, precision);
12928
12929 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
12931 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12932 << PrettySourceValue);
12933 }
12934
12935 if (Result == llvm::APFloat::opOK && isExact) {
12936 if (IsLiteral) return;
12937 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12938 PruneWarnings);
12939 }
12940
12941 // Conversion of a floating-point value to a non-bool integer where the
12942 // integral part cannot be represented by the integer type is undefined.
12943 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12944 return DiagnoseImpCast(
12945 S, E, T, CContext,
12946 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12947 : diag::warn_impcast_float_to_integer_out_of_range,
12948 PruneWarnings);
12949
12950 unsigned DiagID = 0;
12951 if (IsLiteral) {
12952 // Warn on floating point literal to integer.
12953 DiagID = diag::warn_impcast_literal_float_to_integer;
12954 } else if (IntegerValue == 0) {
12955 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
12956 return DiagnoseImpCast(S, E, T, CContext,
12957 diag::warn_impcast_float_integer, PruneWarnings);
12958 }
12959 // Warn on non-zero to zero conversion.
12960 DiagID = diag::warn_impcast_float_to_integer_zero;
12961 } else {
12962 if (IntegerValue.isUnsigned()) {
12963 if (!IntegerValue.isMaxValue()) {
12964 return DiagnoseImpCast(S, E, T, CContext,
12965 diag::warn_impcast_float_integer, PruneWarnings);
12966 }
12967 } else { // IntegerValue.isSigned()
12968 if (!IntegerValue.isMaxSignedValue() &&
12969 !IntegerValue.isMinSignedValue()) {
12970 return DiagnoseImpCast(S, E, T, CContext,
12971 diag::warn_impcast_float_integer, PruneWarnings);
12972 }
12973 }
12974 // Warn on evaluatable floating point expression to integer conversion.
12975 DiagID = diag::warn_impcast_float_to_integer;
12976 }
12977
12978 SmallString<16> PrettyTargetValue;
12979 if (IsBool)
12980 PrettyTargetValue = Value.isZero() ? "false" : "true";
12981 else
12982 IntegerValue.toString(PrettyTargetValue);
12983
12984 if (PruneWarnings) {
12986 S.PDiag(DiagID)
12987 << E->getType() << T.getUnqualifiedType()
12988 << PrettySourceValue << PrettyTargetValue
12989 << E->getSourceRange() << SourceRange(CContext));
12990 } else {
12991 S.Diag(E->getExprLoc(), DiagID)
12992 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12993 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12994 }
12995}
12996
12997/// Analyze the given compound assignment for the possible losing of
12998/// floating-point precision.
13000 assert(isa<CompoundAssignOperator>(E) &&
13001 "Must be compound assignment operation");
13002 // Recurse on the LHS and RHS in here
13005
13006 if (E->getLHS()->getType()->isAtomicType())
13007 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
13008
13009 // Now check the outermost expression
13010 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
13011 const auto *RBT = cast<CompoundAssignOperator>(E)
13012 ->getComputationResultType()
13013 ->getAs<BuiltinType>();
13014
13015 // The below checks assume source is floating point.
13016 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
13017
13018 // If source is floating point but target is an integer.
13019 if (ResultBT->isInteger())
13020 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
13021 E->getExprLoc(), diag::warn_impcast_float_integer);
13022
13023 if (!ResultBT->isFloatingPoint())
13024 return;
13025
13026 // If both source and target are floating points, warn about losing precision.
13028 QualType(ResultBT, 0), QualType(RBT, 0));
13029 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
13030 // warn about dropping FP rank.
13031 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
13032 diag::warn_impcast_float_result_precision);
13033}
13034
13035static std::string PrettyPrintInRange(const llvm::APSInt &Value,
13036 IntRange Range) {
13037 if (!Range.Width) return "0";
13038
13039 llvm::APSInt ValueInRange = Value;
13040 ValueInRange.setIsSigned(!Range.NonNegative);
13041 ValueInRange = ValueInRange.trunc(Range.Width);
13042 return toString(ValueInRange, 10);
13043}
13044
13045static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
13046 bool ToBool) {
13047 if (!isa<ImplicitCastExpr>(Ex))
13048 return false;
13049
13050 const Expr *InnerE = Ex->IgnoreParenImpCasts();
13052 const Type *Source =
13054 if (Target->isDependentType())
13055 return false;
13056
13057 const auto *FloatCandidateBT =
13058 dyn_cast<BuiltinType>(ToBool ? Source : Target);
13059 const Type *BoolCandidateType = ToBool ? Target : Source;
13060
13061 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
13062 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
13063}
13064
13065static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
13066 SourceLocation CC) {
13067 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
13068 const Expr *CurrA = TheCall->getArg(I);
13069 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
13070 continue;
13071
13072 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
13073 S, TheCall->getArg(I - 1), false));
13074 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
13075 S, TheCall->getArg(I + 1), false));
13076 if (IsSwapped) {
13077 // Warn on this floating-point to bool conversion.
13079 CurrA->getType(), CC,
13080 diag::warn_impcast_floating_point_to_bool);
13081 }
13082 }
13083}
13084
13086 SourceLocation CC) {
13087 // Don't warn on functions which have return type nullptr_t.
13088 if (isa<CallExpr>(E))
13089 return;
13090
13091 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
13092 const Expr *NewE = E->IgnoreParenImpCasts();
13093 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
13094 bool HasNullPtrType = NewE->getType()->isNullPtrType();
13095 if (!IsGNUNullExpr && !HasNullPtrType)
13096 return;
13097
13098 // Return if target type is a safe conversion.
13099 if (T->isAnyPointerType() || T->isBlockPointerType() ||
13100 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
13101 return;
13102
13103 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
13104 E->getExprLoc()))
13105 return;
13106
13108
13109 // Venture through the macro stacks to get to the source of macro arguments.
13110 // The new location is a better location than the complete location that was
13111 // passed in.
13112 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
13114
13115 // __null is usually wrapped in a macro. Go up a macro if that is the case.
13116 if (IsGNUNullExpr && Loc.isMacroID()) {
13117 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13118 Loc, S.SourceMgr, S.getLangOpts());
13119 if (MacroName == "NULL")
13121 }
13122
13123 // Only warn if the null and context location are in the same macro expansion.
13124 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
13125 return;
13126
13127 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
13128 << HasNullPtrType << T << SourceRange(CC)
13130 S.getFixItZeroLiteralForType(T, Loc));
13131}
13132
13133// Helper function to filter out cases for constant width constant conversion.
13134// Don't warn on char array initialization or for non-decimal values.
13136 SourceLocation CC) {
13137 // If initializing from a constant, and the constant starts with '0',
13138 // then it is a binary, octal, or hexadecimal. Allow these constants
13139 // to fill all the bits, even if there is a sign change.
13140 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
13141 const char FirstLiteralCharacter =
13142 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
13143 if (FirstLiteralCharacter == '0')
13144 return false;
13145 }
13146
13147 // If the CC location points to a '{', and the type is char, then assume
13148 // assume it is an array initialization.
13149 if (CC.isValid() && T->isCharType()) {
13150 const char FirstContextCharacter =
13152 if (FirstContextCharacter == '{')
13153 return false;
13154 }
13155
13156 return true;
13157}
13158
13160 const auto *IL = dyn_cast<IntegerLiteral>(E);
13161 if (!IL) {
13162 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
13163 if (UO->getOpcode() == UO_Minus)
13164 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13165 }
13166 }
13167
13168 return IL;
13169}
13170
13172 E = E->IgnoreParenImpCasts();
13173 SourceLocation ExprLoc = E->getExprLoc();
13174
13175 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13176 BinaryOperator::Opcode Opc = BO->getOpcode();
13178 // Do not diagnose unsigned shifts.
13179 if (Opc == BO_Shl) {
13180 const auto *LHS = getIntegerLiteral(BO->getLHS());
13181 const auto *RHS = getIntegerLiteral(BO->getRHS());
13182 if (LHS && LHS->getValue() == 0)
13183 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13184 else if (!E->isValueDependent() && LHS && RHS &&
13185 RHS->getValue().isNonNegative() &&
13187 S.Diag(ExprLoc, diag::warn_left_shift_always)
13188 << (Result.Val.getInt() != 0);
13189 else if (E->getType()->isSignedIntegerType())
13190 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
13193 ") != 0");
13194 }
13195 }
13196
13197 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13198 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13199 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13200 if (!LHS || !RHS)
13201 return;
13202 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13203 (RHS->getValue() == 0 || RHS->getValue() == 1))
13204 // Do not diagnose common idioms.
13205 return;
13206 if (LHS->getValue() != 0 && RHS->getValue() != 0)
13207 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13208 }
13209}
13210
13212 const Type *Target, Expr *E,
13213 QualType T,
13214 SourceLocation CC) {
13215 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
13216 Source != Target);
13217
13218 // Lone surrogates have a distinct representation in UTF-32.
13219 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
13220 // so don't warn on such conversion.
13221 if (Source->isChar16Type() && Target->isChar32Type())
13222 return;
13223
13227 llvm::APSInt Value(32);
13228 Value = Result.Val.getInt();
13229 bool IsASCII = Value <= 0x7F;
13230 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
13231 bool ConversionPreservesSemantics =
13232 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
13233
13234 if (!ConversionPreservesSemantics) {
13235 auto IsSingleCodeUnitCP = [](const QualType &T,
13236 const llvm::APSInt &Value) {
13237 if (T->isChar8Type())
13238 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
13239 if (T->isChar16Type())
13240 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
13241 assert(T->isChar32Type());
13242 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
13243 };
13244
13245 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
13246 << E->getType() << T
13247 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
13248 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
13249 }
13250 } else {
13251 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
13253 DiagnoseImpCast(S, E, T, CC,
13254 LosesPrecision ? diag::warn_impcast_unicode_precision
13255 : diag::warn_impcast_unicode_char_type);
13256 }
13257}
13258
13260 From = Context.getCanonicalType(From);
13261 To = Context.getCanonicalType(To);
13262 QualType MaybePointee = From->getPointeeType();
13263 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13264 From = MaybePointee;
13265 MaybePointee = To->getPointeeType();
13266 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13267 To = MaybePointee;
13268
13269 if (const auto *FromFn = From->getAs<FunctionType>()) {
13270 if (const auto *ToFn = To->getAs<FunctionType>()) {
13271 if (FromFn->getCFIUncheckedCalleeAttr() &&
13272 !ToFn->getCFIUncheckedCalleeAttr())
13273 return true;
13274 }
13275 }
13276 return false;
13277}
13278
13280 bool *ICContext, bool IsListInit) {
13281 if (E->isTypeDependent() || E->isValueDependent()) return;
13282
13283 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
13284 const Type *Target = Context.getCanonicalType(T).getTypePtr();
13285 if (Source == Target) return;
13286 if (Target->isDependentType()) return;
13287
13288 // If the conversion context location is invalid don't complain. We also
13289 // don't want to emit a warning if the issue occurs from the expansion of
13290 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13291 // delay this check as long as possible. Once we detect we are in that
13292 // scenario, we just return.
13293 if (CC.isInvalid())
13294 return;
13295
13296 if (Source->isAtomicType())
13297 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13298
13299 // Diagnose implicit casts to bool.
13300 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13301 if (isa<StringLiteral>(E))
13302 // Warn on string literal to bool. Checks for string literals in logical
13303 // and expressions, for instance, assert(0 && "error here"), are
13304 // prevented by a check in AnalyzeImplicitConversions().
13305 return DiagnoseImpCast(*this, E, T, CC,
13306 diag::warn_impcast_string_literal_to_bool);
13309 // This covers the literal expressions that evaluate to Objective-C
13310 // objects.
13311 return DiagnoseImpCast(*this, E, T, CC,
13312 diag::warn_impcast_objective_c_literal_to_bool);
13313 }
13314 if (Source->isPointerType() || Source->canDecayToPointerType()) {
13315 // Warn on pointer to bool conversion that is always true.
13317 SourceRange(CC));
13318 }
13319 }
13320
13322
13323 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13324 // is a typedef for signed char (macOS), then that constant value has to be 1
13325 // or 0.
13326 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
13329 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13331 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13332 << toString(Result.Val.getInt(), 10));
13333 }
13334 return;
13335 }
13336 }
13337
13338 // Check implicit casts from Objective-C collection literals to specialized
13339 // collection types, e.g., NSArray<NSString *> *.
13340 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13341 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
13342 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13343 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
13344
13345 // Strip complex types.
13346 if (isa<ComplexType>(Source)) {
13347 if (!isa<ComplexType>(Target)) {
13348 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13349 return;
13350
13351 if (!getLangOpts().CPlusPlus && Target->isVectorType()) {
13352 return DiagnoseImpCast(*this, E, T, CC,
13353 diag::err_impcast_incompatible_type);
13354 }
13355
13356 return DiagnoseImpCast(*this, E, T, CC,
13358 ? diag::err_impcast_complex_scalar
13359 : diag::warn_impcast_complex_scalar);
13360 }
13361
13362 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13363 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13364 }
13365
13366 // Strip vector types.
13367 if (isa<VectorType>(Source)) {
13368 if (Target->isSveVLSBuiltinType() &&
13369 (ARM().areCompatibleSveTypes(QualType(Target, 0),
13370 QualType(Source, 0)) ||
13371 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
13372 QualType(Source, 0))))
13373 return;
13374
13375 if (Target->isRVVVLSBuiltinType() &&
13376 (Context.areCompatibleRVVTypes(QualType(Target, 0),
13377 QualType(Source, 0)) ||
13378 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
13379 QualType(Source, 0))))
13380 return;
13381
13382 if (!isa<VectorType>(Target)) {
13383 if (SourceMgr.isInSystemMacro(CC))
13384 return;
13385 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
13386 }
13387 if (getLangOpts().HLSL &&
13388 Target->castAs<VectorType>()->getNumElements() <
13389 Source->castAs<VectorType>()->getNumElements()) {
13390 // Diagnose vector truncation but don't return. We may also want to
13391 // diagnose an element conversion.
13392 DiagnoseImpCast(*this, E, T, CC,
13393 diag::warn_hlsl_impcast_vector_truncation);
13394 }
13395
13396 // If the vector cast is cast between two vectors of the same size, it is
13397 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13398 if (!getLangOpts().HLSL &&
13399 Context.getTypeSize(Source) == Context.getTypeSize(Target))
13400 return;
13401
13402 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13403 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13404 }
13405 if (const auto *VecTy = dyn_cast<VectorType>(Target))
13406 Target = VecTy->getElementType().getTypePtr();
13407
13408 // Strip matrix types.
13409 if (isa<ConstantMatrixType>(Source)) {
13410 if (Target->isScalarType())
13411 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_matrix_scalar);
13412
13415 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13416 // Diagnose Matrix truncation but don't return. We may also want to
13417 // diagnose an element conversion.
13418 DiagnoseImpCast(*this, E, T, CC,
13419 diag::warn_hlsl_impcast_matrix_truncation);
13420 }
13421
13422 Source = cast<ConstantMatrixType>(Source)->getElementType().getTypePtr();
13423 Target = cast<ConstantMatrixType>(Target)->getElementType().getTypePtr();
13424 }
13425 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Target))
13426 Target = MatTy->getElementType().getTypePtr();
13427
13428 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13429 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13430
13431 // Strip SVE vector types
13432 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13433 // Need the original target type for vector type checks
13434 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13435 // Handle conversion from scalable to fixed when msve-vector-bits is
13436 // specified
13437 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
13438 QualType(Source, 0)) ||
13439 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
13440 QualType(Source, 0)))
13441 return;
13442
13443 // If the vector cast is cast between two vectors of the same size, it is
13444 // a bitcast, not a conversion.
13445 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
13446 return;
13447
13448 Source = SourceBT->getSveEltType(Context).getTypePtr();
13449 }
13450
13451 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13452 Target = TargetBT->getSveEltType(Context).getTypePtr();
13453
13454 // If the source is floating point...
13455 if (SourceBT && SourceBT->isFloatingPoint()) {
13456 // ...and the target is floating point...
13457 if (TargetBT && TargetBT->isFloatingPoint()) {
13458 // ...then warn if we're dropping FP rank.
13459
13461 QualType(SourceBT, 0), QualType(TargetBT, 0));
13462 if (Order > 0) {
13463 // Don't warn about float constants that are precisely
13464 // representable in the target type.
13465 Expr::EvalResult result;
13466 if (E->EvaluateAsRValue(result, Context)) {
13467 // Value might be a float, a float vector, or a float complex.
13469 result.Val,
13470 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13471 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13472 return;
13473 }
13474
13475 if (SourceMgr.isInSystemMacro(CC))
13476 return;
13477
13478 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
13479 }
13480 // ... or possibly if we're increasing rank, too
13481 else if (Order < 0) {
13482 if (SourceMgr.isInSystemMacro(CC))
13483 return;
13484
13485 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
13486 }
13487 return;
13488 }
13489
13490 // If the target is integral, always warn.
13491 if (TargetBT && TargetBT->isInteger()) {
13492 if (SourceMgr.isInSystemMacro(CC))
13493 return;
13494
13495 DiagnoseFloatingImpCast(*this, E, T, CC);
13496 }
13497
13498 // Detect the case where a call result is converted from floating-point to
13499 // to bool, and the final argument to the call is converted from bool, to
13500 // discover this typo:
13501 //
13502 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13503 //
13504 // FIXME: This is an incredibly special case; is there some more general
13505 // way to detect this class of misplaced-parentheses bug?
13506 if (Target->isBooleanType() && isa<CallExpr>(E)) {
13507 // Check last argument of function call to see if it is an
13508 // implicit cast from a type matching the type the result
13509 // is being cast to.
13510 CallExpr *CEx = cast<CallExpr>(E);
13511 if (unsigned NumArgs = CEx->getNumArgs()) {
13512 Expr *LastA = CEx->getArg(NumArgs - 1);
13513 Expr *InnerE = LastA->IgnoreParenImpCasts();
13514 if (isa<ImplicitCastExpr>(LastA) &&
13515 InnerE->getType()->isBooleanType()) {
13516 // Warn on this floating-point to bool conversion
13517 DiagnoseImpCast(*this, E, T, CC,
13518 diag::warn_impcast_floating_point_to_bool);
13519 }
13520 }
13521 }
13522 return;
13523 }
13524
13525 // Valid casts involving fixed point types should be accounted for here.
13526 if (Source->isFixedPointType()) {
13527 if (Target->isUnsaturatedFixedPointType()) {
13531 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13532 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
13533 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
13534 if (Value > MaxVal || Value < MinVal) {
13536 PDiag(diag::warn_impcast_fixed_point_range)
13537 << Value.toString() << T
13538 << E->getSourceRange()
13539 << clang::SourceRange(CC));
13540 return;
13541 }
13542 }
13543 } else if (Target->isIntegerType()) {
13547 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13548
13549 bool Overflowed;
13550 llvm::APSInt IntResult = FXResult.convertToInt(
13551 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
13552 &Overflowed);
13553
13554 if (Overflowed) {
13556 PDiag(diag::warn_impcast_fixed_point_range)
13557 << FXResult.toString() << T
13558 << E->getSourceRange()
13559 << clang::SourceRange(CC));
13560 return;
13561 }
13562 }
13563 }
13564 } else if (Target->isUnsaturatedFixedPointType()) {
13565 if (Source->isIntegerType()) {
13569 llvm::APSInt Value = Result.Val.getInt();
13570
13571 bool Overflowed;
13572 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13573 Value, Context.getFixedPointSemantics(T), &Overflowed);
13574
13575 if (Overflowed) {
13577 PDiag(diag::warn_impcast_fixed_point_range)
13578 << toString(Value, /*Radix=*/10) << T
13579 << E->getSourceRange()
13580 << clang::SourceRange(CC));
13581 return;
13582 }
13583 }
13584 }
13585 }
13586
13587 // If we are casting an integer type to a floating point type without
13588 // initialization-list syntax, we might lose accuracy if the floating
13589 // point type has a narrower significand than the integer type.
13590 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13591 TargetBT->isFloatingType() && !IsListInit) {
13592 // Determine the number of precision bits in the source integer type.
13593 std::optional<IntRange> SourceRange =
13595 /*Approximate=*/true);
13596 if (!SourceRange)
13597 return;
13598 unsigned int SourcePrecision = SourceRange->Width;
13599
13600 // Determine the number of precision bits in the
13601 // target floating point type.
13602 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13603 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13604
13605 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13606 SourcePrecision > TargetPrecision) {
13607
13608 if (std::optional<llvm::APSInt> SourceInt =
13610 // If the source integer is a constant, convert it to the target
13611 // floating point type. Issue a warning if the value changes
13612 // during the whole conversion.
13613 llvm::APFloat TargetFloatValue(
13614 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13615 llvm::APFloat::opStatus ConversionStatus =
13616 TargetFloatValue.convertFromAPInt(
13617 *SourceInt, SourceBT->isSignedInteger(),
13618 llvm::APFloat::rmNearestTiesToEven);
13619
13620 if (ConversionStatus != llvm::APFloat::opOK) {
13621 SmallString<32> PrettySourceValue;
13622 SourceInt->toString(PrettySourceValue, 10);
13623 SmallString<32> PrettyTargetValue;
13624 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13625
13627 E->getExprLoc(), E,
13628 PDiag(diag::warn_impcast_integer_float_precision_constant)
13629 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13630 << E->getSourceRange() << clang::SourceRange(CC));
13631 }
13632 } else {
13633 // Otherwise, the implicit conversion may lose precision.
13634 DiagnoseImpCast(*this, E, T, CC,
13635 diag::warn_impcast_integer_float_precision);
13636 }
13637 }
13638 }
13639
13640 DiagnoseNullConversion(*this, E, T, CC);
13641
13643
13644 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13645 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
13646 return;
13647 }
13648
13649 if (Target->isBooleanType())
13650 DiagnoseIntInBoolContext(*this, E);
13651
13653 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
13654 << QualType(Source, 0) << QualType(Target, 0);
13655 }
13656
13657 if (!Source->isIntegerType() || !Target->isIntegerType())
13658 return;
13659
13660 // TODO: remove this early return once the false positives for constant->bool
13661 // in templates, macros, etc, are reduced or removed.
13662 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13663 return;
13664
13665 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
13666 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13668 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13669 << E->getType());
13670 }
13671 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13672 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
13673 if (!LikelySourceRange)
13674 return;
13675
13676 IntRange SourceTypeRange =
13677 IntRange::forTargetOfCanonicalType(Context, Source);
13678 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
13679
13680 if (LikelySourceRange->Width > TargetRange.Width) {
13681 // Check if target is a wrapping OBT - if so, don't warn about constant
13682 // conversion as this type may be used intentionally with implicit
13683 // truncation, especially during assignments.
13684 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13685 if (TargetOBT->isWrapKind()) {
13686 return;
13687 }
13688 }
13689
13690 // Check if source expression has an explicit __ob_wrap cast because if so,
13691 // wrapping was explicitly requested and we shouldn't warn
13692 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
13693 if (SourceOBT->isWrapKind()) {
13694 return;
13695 }
13696 }
13697
13698 // If the source is a constant, use a default-on diagnostic.
13699 // TODO: this should happen for bitfield stores, too.
13703 llvm::APSInt Value(32);
13704 Value = Result.Val.getInt();
13705
13706 if (SourceMgr.isInSystemMacro(CC))
13707 return;
13708
13709 std::string PrettySourceValue = toString(Value, 10);
13710 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13711
13713 PDiag(diag::warn_impcast_integer_precision_constant)
13714 << PrettySourceValue << PrettyTargetValue
13715 << E->getType() << T << E->getSourceRange()
13716 << SourceRange(CC));
13717 return;
13718 }
13719
13720 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13721 if (SourceMgr.isInSystemMacro(CC))
13722 return;
13723
13724 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
13725 if (UO->getOpcode() == UO_Minus)
13726 return DiagnoseImpCast(
13727 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
13728 }
13729
13730 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
13731 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
13732 /* pruneControlFlow */ true);
13733 return DiagnoseImpCast(*this, E, T, CC,
13734 diag::warn_impcast_integer_precision);
13735 }
13736
13737 if (TargetRange.Width > SourceTypeRange.Width) {
13738 if (auto *UO = dyn_cast<UnaryOperator>(E))
13739 if (UO->getOpcode() == UO_Minus)
13740 if (Source->isUnsignedIntegerType()) {
13741 if (Target->isUnsignedIntegerType())
13742 return DiagnoseImpCast(*this, E, T, CC,
13743 diag::warn_impcast_high_order_zero_bits);
13744 if (Target->isSignedIntegerType())
13745 return DiagnoseImpCast(*this, E, T, CC,
13746 diag::warn_impcast_nonnegative_result);
13747 }
13748 }
13749
13750 if (TargetRange.Width == LikelySourceRange->Width &&
13751 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13752 Source->isSignedIntegerType()) {
13753 // Warn when doing a signed to signed conversion, warn if the positive
13754 // source value is exactly the width of the target type, which will
13755 // cause a negative value to be stored.
13756
13759 !SourceMgr.isInSystemMacro(CC)) {
13760 llvm::APSInt Value = Result.Val.getInt();
13761 if (isSameWidthConstantConversion(*this, E, T, CC)) {
13762 std::string PrettySourceValue = toString(Value, 10);
13763 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13764
13765 Diag(E->getExprLoc(),
13766 PDiag(diag::warn_impcast_integer_precision_constant)
13767 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13768 << E->getSourceRange() << SourceRange(CC));
13769 return;
13770 }
13771 }
13772
13773 // Fall through for non-constants to give a sign conversion warning.
13774 }
13775
13776 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
13777 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13778 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13779 LikelySourceRange->Width == TargetRange.Width))) {
13780 if (SourceMgr.isInSystemMacro(CC))
13781 return;
13782
13783 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13784 TargetBT->isInteger() &&
13785 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13786 return;
13787 }
13788
13789 unsigned DiagID = diag::warn_impcast_integer_sign;
13790
13791 // Traditionally, gcc has warned about this under -Wsign-compare.
13792 // We also want to warn about it in -Wconversion.
13793 // So if -Wconversion is off, use a completely identical diagnostic
13794 // in the sign-compare group.
13795 // The conditional-checking code will
13796 if (ICContext) {
13797 DiagID = diag::warn_impcast_integer_sign_conditional;
13798 *ICContext = true;
13799 }
13800
13801 DiagnoseImpCast(*this, E, T, CC, DiagID);
13802 }
13803
13804 // If we're implicitly converting from an integer into an enumeration, that
13805 // is valid in C but invalid in C++.
13806 QualType SourceType = E->getEnumCoercedType(Context);
13807 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13808 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
13809 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
13810
13811 // Diagnose conversions between different enumeration types.
13812 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13813 // type, to give us better diagnostics.
13814 Source = Context.getCanonicalType(SourceType).getTypePtr();
13815
13816 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13817 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13818 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13819 TargetEnum->getDecl()->hasNameForLinkage() &&
13820 SourceEnum != TargetEnum) {
13821 if (SourceMgr.isInSystemMacro(CC))
13822 return;
13823
13824 return DiagnoseImpCast(*this, E, SourceType, T, CC,
13825 diag::warn_impcast_different_enum_types);
13826 }
13827}
13828
13830 SourceLocation CC, QualType T);
13831
13833 SourceLocation CC, bool &ICContext) {
13834 E = E->IgnoreParenImpCasts();
13835 // Diagnose incomplete type for second or third operand in C.
13836 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13837 S.RequireCompleteExprType(E, diag::err_incomplete_type);
13838
13839 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13840 return CheckConditionalOperator(S, CO, CC, T);
13841
13843 if (E->getType() != T)
13844 return S.CheckImplicitConversion(E, T, CC, &ICContext);
13845}
13846
13848 SourceLocation CC, QualType T) {
13850
13851 Expr *TrueExpr = E->getTrueExpr();
13852 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13853 TrueExpr = BCO->getCommon();
13854
13855 bool Suspicious = false;
13856 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13857 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13858
13859 if (T->isBooleanType())
13861
13862 // If -Wconversion would have warned about either of the candidates
13863 // for a signedness conversion to the context type...
13864 if (!Suspicious) return;
13865
13866 // ...but it's currently ignored...
13867 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13868 return;
13869
13870 // ...then check whether it would have warned about either of the
13871 // candidates for a signedness conversion to the condition type.
13872 if (E->getType() == T) return;
13873
13874 Suspicious = false;
13875 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
13876 &Suspicious);
13877 if (!Suspicious)
13879 E->getType(), CC, &Suspicious);
13880}
13881
13882/// Check conversion of given expression to boolean.
13883/// Input argument E is a logical expression.
13885 // Run the bool-like conversion checks only for C since there bools are
13886 // still not used as the return type from "boolean" operators or as the input
13887 // type for conditional operators.
13888 if (S.getLangOpts().CPlusPlus)
13889 return;
13891 return;
13893}
13894
13895namespace {
13896struct AnalyzeImplicitConversionsWorkItem {
13897 Expr *E;
13898 SourceLocation CC;
13899 bool IsListInit;
13900};
13901}
13902
13904 Sema &S, Expr *E, QualType T, SourceLocation CC,
13905 bool ExtraCheckForImplicitConversion,
13907 E = E->IgnoreParenImpCasts();
13908 WorkList.push_back({E, CC, false});
13909
13910 if (ExtraCheckForImplicitConversion && E->getType() != T)
13911 S.CheckImplicitConversion(E, T, CC);
13912}
13913
13914/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13915/// that should be visited are added to WorkList.
13917 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13919 Expr *OrigE = Item.E;
13920 SourceLocation CC = Item.CC;
13921
13922 QualType T = OrigE->getType();
13923 Expr *E = OrigE->IgnoreParenImpCasts();
13924
13925 // Propagate whether we are in a C++ list initialization expression.
13926 // If so, we do not issue warnings for implicit int-float conversion
13927 // precision loss, because C++11 narrowing already handles it.
13928 //
13929 // HLSL's initialization lists are special, so they shouldn't observe the C++
13930 // behavior here.
13931 bool IsListInit =
13932 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
13933 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
13934
13935 if (E->isTypeDependent() || E->isValueDependent())
13936 return;
13937
13938 Expr *SourceExpr = E;
13939 // Examine, but don't traverse into the source expression of an
13940 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13941 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13942 // evaluate it in the context of checking the specific conversion to T though.
13943 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13944 if (auto *Src = OVE->getSourceExpr())
13945 SourceExpr = Src;
13946
13947 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13948 if (UO->getOpcode() == UO_Not &&
13949 UO->getSubExpr()->isKnownToHaveBooleanValue())
13950 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13951 << OrigE->getSourceRange() << T->isBooleanType()
13952 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13953
13954 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
13955 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13956 BO->getLHS()->isKnownToHaveBooleanValue() &&
13957 BO->getRHS()->isKnownToHaveBooleanValue() &&
13958 BO->getLHS()->HasSideEffects(S.Context) &&
13959 BO->getRHS()->HasSideEffects(S.Context)) {
13961 const LangOptions &LO = S.getLangOpts();
13962 SourceLocation BLoc = BO->getOperatorLoc();
13963 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
13964 StringRef SR = clang::Lexer::getSourceText(
13965 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
13966 // To reduce false positives, only issue the diagnostic if the operator
13967 // is explicitly spelled as a punctuator. This suppresses the diagnostic
13968 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
13969 // in C, along with other macro spellings the user might invent.
13970 if (SR.str() == "&" || SR.str() == "|") {
13971
13972 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13973 << (BO->getOpcode() == BO_And ? "&" : "|")
13974 << OrigE->getSourceRange()
13976 BO->getOperatorLoc(),
13977 (BO->getOpcode() == BO_And ? "&&" : "||"));
13978 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13979 }
13980 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
13981 /// Analyze the given comma operator. The basic idea behind the analysis
13982 /// is to analyze the left and right operands slightly differently. The
13983 /// left operand needs to check whether the operand itself has an implicit
13984 /// conversion, but not whether the left operand induces an implicit
13985 /// conversion for the entire comma expression itself. This is similar to
13986 /// how CheckConditionalOperand behaves; it's as-if the correct operand
13987 /// were directly used for the implicit conversion check.
13988 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
13989 /*ExtraCheckForImplicitConversion=*/false, WorkList);
13990 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
13991 /*ExtraCheckForImplicitConversion=*/true, WorkList);
13992 return;
13993 }
13994 }
13995
13996 // For conditional operators, we analyze the arguments as if they
13997 // were being fed directly into the output.
13998 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13999 CheckConditionalOperator(S, CO, CC, T);
14000 return;
14001 }
14002
14003 // Check implicit argument conversions for function calls.
14004 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
14006
14007 // Go ahead and check any implicit conversions we might have skipped.
14008 // The non-canonical typecheck is just an optimization;
14009 // CheckImplicitConversion will filter out dead implicit conversions.
14010 if (SourceExpr->getType() != T)
14011 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
14012
14013 // Now continue drilling into this expression.
14014
14015 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
14016 // The bound subexpressions in a PseudoObjectExpr are not reachable
14017 // as transitive children.
14018 // FIXME: Use a more uniform representation for this.
14019 for (auto *SE : POE->semantics())
14020 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
14021 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
14022 }
14023
14024 // Skip past explicit casts.
14025 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
14026 E = CE->getSubExpr();
14027 // In the special case of a C++ function-style cast with braces,
14028 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
14029 // initializer. This InitListExpr basically belongs to the cast itself, so
14030 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
14032 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
14033 if (InitListE->getNumInits() == 1) {
14034 E = InitListE->getInit(0);
14035 }
14036 }
14037 }
14038 E = E->IgnoreParenImpCasts();
14039 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
14040 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
14041 WorkList.push_back({E, CC, IsListInit});
14042 return;
14043 }
14044
14045 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
14046 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
14047 // The base expression is only used to initialize the parameter for
14048 // arguments to `inout` parameters, so we only traverse down the base
14049 // expression for `inout` cases.
14050 if (OutArgE->isInOut())
14051 WorkList.push_back(
14052 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
14053 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
14054 return;
14055 }
14056
14057 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14058 // Do a somewhat different check with comparison operators.
14059 if (BO->isComparisonOp())
14060 return AnalyzeComparison(S, BO);
14061
14062 // And with simple assignments.
14063 if (BO->getOpcode() == BO_Assign)
14064 return AnalyzeAssignment(S, BO);
14065 // And with compound assignments.
14066 if (BO->isAssignmentOp())
14067 return AnalyzeCompoundAssignment(S, BO);
14068 }
14069
14070 // These break the otherwise-useful invariant below. Fortunately,
14071 // we don't really need to recurse into them, because any internal
14072 // expressions should have been analyzed already when they were
14073 // built into statements.
14074 if (isa<StmtExpr>(E)) return;
14075
14076 // Don't descend into unevaluated contexts.
14077 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
14078
14079 // Now just recurse over the expression's children.
14080 CC = E->getExprLoc();
14081 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
14082 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
14083 for (Stmt *SubStmt : E->children()) {
14084 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
14085 if (!ChildExpr)
14086 continue;
14087
14088 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
14089 if (ChildExpr == CSE->getOperand())
14090 // Do not recurse over a CoroutineSuspendExpr's operand.
14091 // The operand is also a subexpression of getCommonExpr(), and
14092 // recursing into it directly would produce duplicate diagnostics.
14093 continue;
14094
14095 if (IsLogicalAndOperator &&
14097 // Ignore checking string literals that are in logical and operators.
14098 // This is a common pattern for asserts.
14099 continue;
14100 WorkList.push_back({ChildExpr, CC, IsListInit});
14101 }
14102
14103 if (BO && BO->isLogicalOp()) {
14104 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
14105 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14106 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14107
14108 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
14109 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14110 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14111 }
14112
14113 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
14114 if (U->getOpcode() == UO_LNot) {
14115 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
14116 } else if (U->getOpcode() != UO_AddrOf) {
14117 if (U->getSubExpr()->getType()->isAtomicType())
14118 S.Diag(U->getSubExpr()->getBeginLoc(),
14119 diag::warn_atomic_implicit_seq_cst);
14120 }
14121 }
14122}
14123
14124/// AnalyzeImplicitConversions - Find and report any interesting
14125/// implicit conversions in the given expression. There are a couple
14126/// of competing diagnostics here, -Wconversion and -Wsign-compare.
14128 bool IsListInit/*= false*/) {
14130 WorkList.push_back({OrigE, CC, IsListInit});
14131 while (!WorkList.empty())
14132 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
14133}
14134
14135// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
14136// Returns true when emitting a warning about taking the address of a reference.
14137static bool CheckForReference(Sema &SemaRef, const Expr *E,
14138 const PartialDiagnostic &PD) {
14139 E = E->IgnoreParenImpCasts();
14140
14141 const FunctionDecl *FD = nullptr;
14142
14143 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14144 if (!DRE->getDecl()->getType()->isReferenceType())
14145 return false;
14146 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14147 if (!M->getMemberDecl()->getType()->isReferenceType())
14148 return false;
14149 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
14150 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
14151 return false;
14152 FD = Call->getDirectCallee();
14153 } else {
14154 return false;
14155 }
14156
14157 SemaRef.Diag(E->getExprLoc(), PD);
14158
14159 // If possible, point to location of function.
14160 if (FD) {
14161 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
14162 }
14163
14164 return true;
14165}
14166
14167// Returns true if the SourceLocation is expanded from any macro body.
14168// Returns false if the SourceLocation is invalid, is from not in a macro
14169// expansion, or is from expanded from a top-level macro argument.
14171 if (Loc.isInvalid())
14172 return false;
14173
14174 while (Loc.isMacroID()) {
14175 if (SM.isMacroBodyExpansion(Loc))
14176 return true;
14177 Loc = SM.getImmediateMacroCallerLoc(Loc);
14178 }
14179
14180 return false;
14181}
14182
14185 bool IsEqual, SourceRange Range) {
14186 if (!E)
14187 return;
14188
14189 // Don't warn inside macros.
14190 if (E->getExprLoc().isMacroID()) {
14192 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
14193 IsInAnyMacroBody(SM, Range.getBegin()))
14194 return;
14195 }
14196 E = E->IgnoreImpCasts();
14197
14198 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14199
14200 if (isa<CXXThisExpr>(E)) {
14201 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14202 : diag::warn_this_bool_conversion;
14203 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14204 return;
14205 }
14206
14207 bool IsAddressOf = false;
14208
14209 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
14210 if (UO->getOpcode() != UO_AddrOf)
14211 return;
14212 IsAddressOf = true;
14213 E = UO->getSubExpr();
14214 }
14215
14216 if (IsAddressOf) {
14217 unsigned DiagID = IsCompare
14218 ? diag::warn_address_of_reference_null_compare
14219 : diag::warn_address_of_reference_bool_conversion;
14220 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14221 << IsEqual;
14222 if (CheckForReference(*this, E, PD)) {
14223 return;
14224 }
14225 }
14226
14227 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14228 bool IsParam = isa<NonNullAttr>(NonnullAttr);
14229 std::string Str;
14230 llvm::raw_string_ostream S(Str);
14231 E->printPretty(S, nullptr, getPrintingPolicy());
14232 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14233 : diag::warn_cast_nonnull_to_bool;
14234 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
14235 << E->getSourceRange() << Range << IsEqual;
14236 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
14237 };
14238
14239 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14240 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
14241 if (auto *Callee = Call->getDirectCallee()) {
14242 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14243 ComplainAboutNonnullParamOrCall(A);
14244 return;
14245 }
14246 }
14247 }
14248
14249 // Complain if we are converting a lambda expression to a boolean value
14250 // outside of instantiation.
14251 if (!inTemplateInstantiation()) {
14252 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
14253 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
14254 MRecordDecl && MRecordDecl->isLambda()) {
14255 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
14256 << /*LambdaPointerConversionOperatorType=*/3
14257 << MRecordDecl->getSourceRange() << Range << IsEqual;
14258 return;
14259 }
14260 }
14261 }
14262
14263 // Expect to find a single Decl. Skip anything more complicated.
14264 ValueDecl *D = nullptr;
14265 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
14266 D = R->getDecl();
14267 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14268 D = M->getMemberDecl();
14269 }
14270
14271 // Weak Decls can be null.
14272 if (!D || D->isWeak())
14273 return;
14274
14275 // Check for parameter decl with nonnull attribute
14276 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
14277 if (getCurFunction() &&
14278 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
14279 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14280 ComplainAboutNonnullParamOrCall(A);
14281 return;
14282 }
14283
14284 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
14285 // Skip function template not specialized yet.
14287 return;
14288 auto ParamIter = llvm::find(FD->parameters(), PV);
14289 assert(ParamIter != FD->param_end());
14290 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
14291
14292 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14293 if (!NonNull->args_size()) {
14294 ComplainAboutNonnullParamOrCall(NonNull);
14295 return;
14296 }
14297
14298 for (const ParamIdx &ArgNo : NonNull->args()) {
14299 if (ArgNo.getASTIndex() == ParamNo) {
14300 ComplainAboutNonnullParamOrCall(NonNull);
14301 return;
14302 }
14303 }
14304 }
14305 }
14306 }
14307 }
14308
14309 QualType T = D->getType();
14310 // A reference to a function is never null either; look through it.
14311 const bool IsFunctionReference =
14312 T->isReferenceType() && T->getPointeeType()->isFunctionType();
14313 if (IsFunctionReference)
14314 T = T->getPointeeType();
14315 const bool IsArray = T->isArrayType();
14316 const bool IsFunction = T->isFunctionType();
14317
14318 // Address of function is used to silence the function warning.
14319 if (IsAddressOf && IsFunction) {
14320 return;
14321 }
14322
14323 // Found nothing.
14324 if (!IsAddressOf && !IsFunction && !IsArray)
14325 return;
14326
14327 // Pretty print the expression for the diagnostic.
14328 std::string Str;
14329 llvm::raw_string_ostream S(Str);
14330 E->printPretty(S, nullptr, getPrintingPolicy());
14331
14332 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14333 : diag::warn_impcast_pointer_to_bool;
14334 enum {
14335 AddressOf,
14336 FunctionPointer,
14337 ArrayPointer
14338 } DiagType;
14339 if (IsAddressOf)
14340 DiagType = AddressOf;
14341 else if (IsFunction)
14342 DiagType = FunctionPointer;
14343 else if (IsArray)
14344 DiagType = ArrayPointer;
14345 else
14346 llvm_unreachable("Could not determine diagnostic.");
14347 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14348 << Range << IsEqual;
14349
14350 // The fix-it notes below only apply to a bare function name, not a reference.
14351 if (!IsFunction || IsFunctionReference)
14352 return;
14353
14354 // Suggest '&' to silence the function warning.
14355 Diag(E->getExprLoc(), diag::note_function_warning_silence)
14357
14358 // Check to see if '()' fixit should be emitted.
14359 QualType ReturnType;
14360 UnresolvedSet<4> NonTemplateOverloads;
14361 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14362 if (ReturnType.isNull())
14363 return;
14364
14365 if (IsCompare) {
14366 // There are two cases here. If there is null constant, the only suggest
14367 // for a pointer return type. If the null is 0, then suggest if the return
14368 // type is a pointer or an integer type.
14369 if (!ReturnType->isPointerType()) {
14370 if (NullKind == Expr::NPCK_ZeroExpression ||
14371 NullKind == Expr::NPCK_ZeroLiteral) {
14372 if (!ReturnType->isIntegerType())
14373 return;
14374 } else {
14375 return;
14376 }
14377 }
14378 } else { // !IsCompare
14379 // For function to bool, only suggest if the function pointer has bool
14380 // return type.
14381 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14382 return;
14383 }
14384 Diag(E->getExprLoc(), diag::note_function_to_function_call)
14386}
14387
14389 SourceLocation CC) {
14390 QualType Source = E->getType();
14391 QualType Target = T;
14392
14393 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14394 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14395 // Overflow behavior type is being stripped - issue warning
14396 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14397 Target->isUnsignedIntegerType()) {
14398 // For unsigned wrap to unsigned conversions, use pedantic version
14399 unsigned DiagId =
14401 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14402 : diag::warn_impcast_overflow_behavior_pedantic;
14403 DiagnoseImpCast(*this, E, T, CC, DiagId);
14404 } else {
14405 unsigned DiagId = InOverflowBehaviorAssignmentContext
14406 ? diag::warn_impcast_overflow_behavior_assignment
14407 : diag::warn_impcast_overflow_behavior;
14408 DiagnoseImpCast(*this, E, T, CC, DiagId);
14409 }
14410 }
14411 }
14412
14413 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14414 if (TargetOBT->isWrapKind()) {
14415 return true;
14416 }
14417 }
14418
14419 return false;
14420}
14421
14422void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14423 // Don't diagnose in unevaluated contexts.
14425 return;
14426
14427 // Don't diagnose for value- or type-dependent expressions.
14428 if (E->isTypeDependent() || E->isValueDependent())
14429 return;
14430
14431 // Check for array bounds violations in cases where the check isn't triggered
14432 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14433 // ArraySubscriptExpr is on the RHS of a variable initialization.
14434 CheckArrayAccess(E);
14435
14436 // This is not the right CC for (e.g.) a variable initialization.
14437 AnalyzeImplicitConversions(*this, E, CC);
14438}
14439
14440void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14441 ::CheckBoolLikeConversion(*this, E, CC);
14442}
14443
14444void Sema::CheckForIntOverflow (const Expr *E) {
14445 // Use a work list to deal with nested struct initializers.
14446 SmallVector<const Expr *, 2> Exprs(1, E);
14447
14448 do {
14449 const Expr *OriginalE = Exprs.pop_back_val();
14450 const Expr *E = OriginalE->IgnoreParenCasts();
14451
14452 if (isa<BinaryOperator>(E) ||
14453 (isa<UnaryOperator>(E) && cast<UnaryOperator>(E)->canOverflow())) {
14455 continue;
14456 }
14457
14458 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
14459 Exprs.append(InitList->inits().begin(), InitList->inits().end());
14460 else if (isa<ObjCBoxedExpr>(OriginalE))
14462 else if (const auto *Call = dyn_cast<CallExpr>(E))
14463 Exprs.append(Call->arg_begin(), Call->arg_end());
14464 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
14465 Exprs.append(Message->arg_begin(), Message->arg_end());
14466 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
14467 Exprs.append(Construct->arg_begin(), Construct->arg_end());
14468 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
14469 Exprs.push_back(Temporary->getSubExpr());
14470 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
14471 Exprs.push_back(Array->getIdx());
14472 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
14473 Exprs.push_back(Compound->getInitializer());
14474 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
14475 New && New->isArray()) {
14476 if (auto ArraySize = New->getArraySize())
14477 Exprs.push_back(*ArraySize);
14478 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
14479 Exprs.push_back(MTE->getSubExpr());
14480 } while (!Exprs.empty());
14481}
14482
14483namespace {
14484
14485/// Visitor for expressions which looks for unsequenced operations on the
14486/// same object.
14487class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14488 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14489
14490 /// A tree of sequenced regions within an expression. Two regions are
14491 /// unsequenced if one is an ancestor or a descendent of the other. When we
14492 /// finish processing an expression with sequencing, such as a comma
14493 /// expression, we fold its tree nodes into its parent, since they are
14494 /// unsequenced with respect to nodes we will visit later.
14495 class SequenceTree {
14496 struct Value {
14497 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14498 unsigned Parent : 31;
14499 LLVM_PREFERRED_TYPE(bool)
14500 unsigned Merged : 1;
14501 };
14502 SmallVector<Value, 8> Values;
14503
14504 public:
14505 /// A region within an expression which may be sequenced with respect
14506 /// to some other region.
14507 class Seq {
14508 friend class SequenceTree;
14509
14510 unsigned Index;
14511
14512 explicit Seq(unsigned N) : Index(N) {}
14513
14514 public:
14515 Seq() : Index(0) {}
14516 };
14517
14518 SequenceTree() { Values.push_back(Value(0)); }
14519 Seq root() const { return Seq(0); }
14520
14521 /// Create a new sequence of operations, which is an unsequenced
14522 /// subset of \p Parent. This sequence of operations is sequenced with
14523 /// respect to other children of \p Parent.
14524 Seq allocate(Seq Parent) {
14525 Values.push_back(Value(Parent.Index));
14526 return Seq(Values.size() - 1);
14527 }
14528
14529 /// Merge a sequence of operations into its parent.
14530 void merge(Seq S) {
14531 Values[S.Index].Merged = true;
14532 }
14533
14534 /// Determine whether two operations are unsequenced. This operation
14535 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14536 /// should have been merged into its parent as appropriate.
14537 bool isUnsequenced(Seq Cur, Seq Old) {
14538 unsigned C = representative(Cur.Index);
14539 unsigned Target = representative(Old.Index);
14540 while (C >= Target) {
14541 if (C == Target)
14542 return true;
14543 C = Values[C].Parent;
14544 }
14545 return false;
14546 }
14547
14548 private:
14549 /// Pick a representative for a sequence.
14550 unsigned representative(unsigned K) {
14551 if (Values[K].Merged)
14552 // Perform path compression as we go.
14553 return Values[K].Parent = representative(Values[K].Parent);
14554 return K;
14555 }
14556 };
14557
14558 /// An object for which we can track unsequenced uses.
14559 using Object = const NamedDecl *;
14560
14561 /// Different flavors of object usage which we track. We only track the
14562 /// least-sequenced usage of each kind.
14563 enum UsageKind {
14564 /// A read of an object. Multiple unsequenced reads are OK.
14565 UK_Use,
14566
14567 /// A modification of an object which is sequenced before the value
14568 /// computation of the expression, such as ++n in C++.
14569 UK_ModAsValue,
14570
14571 /// A modification of an object which is not sequenced before the value
14572 /// computation of the expression, such as n++.
14573 UK_ModAsSideEffect,
14574
14575 UK_Count = UK_ModAsSideEffect + 1
14576 };
14577
14578 /// Bundle together a sequencing region and the expression corresponding
14579 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14580 struct Usage {
14581 const Expr *UsageExpr = nullptr;
14582 SequenceTree::Seq Seq;
14583
14584 Usage() = default;
14585 };
14586
14587 struct UsageInfo {
14588 Usage Uses[UK_Count];
14589
14590 /// Have we issued a diagnostic for this object already?
14591 bool Diagnosed = false;
14592
14593 UsageInfo();
14594 };
14595 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14596
14597 Sema &SemaRef;
14598
14599 /// Sequenced regions within the expression.
14600 SequenceTree Tree;
14601
14602 /// Declaration modifications and references which we have seen.
14603 UsageInfoMap UsageMap;
14604
14605 /// The region we are currently within.
14606 SequenceTree::Seq Region;
14607
14608 /// Filled in with declarations which were modified as a side-effect
14609 /// (that is, post-increment operations).
14610 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14611
14612 /// Expressions to check later. We defer checking these to reduce
14613 /// stack usage.
14614 SmallVectorImpl<const Expr *> &WorkList;
14615
14616 /// RAII object wrapping the visitation of a sequenced subexpression of an
14617 /// expression. At the end of this process, the side-effects of the evaluation
14618 /// become sequenced with respect to the value computation of the result, so
14619 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14620 /// UK_ModAsValue.
14621 struct SequencedSubexpression {
14622 SequencedSubexpression(SequenceChecker &Self)
14623 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14624 Self.ModAsSideEffect = &ModAsSideEffect;
14625 }
14626
14627 ~SequencedSubexpression() {
14628 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14629 // Add a new usage with usage kind UK_ModAsValue, and then restore
14630 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14631 // the previous one was empty).
14632 UsageInfo &UI = Self.UsageMap[M.first];
14633 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14634 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14635 SideEffectUsage = M.second;
14636 }
14637 Self.ModAsSideEffect = OldModAsSideEffect;
14638 }
14639
14640 SequenceChecker &Self;
14641 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14642 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14643 };
14644
14645 /// RAII object wrapping the visitation of a subexpression which we might
14646 /// choose to evaluate as a constant. If any subexpression is evaluated and
14647 /// found to be non-constant, this allows us to suppress the evaluation of
14648 /// the outer expression.
14649 class EvaluationTracker {
14650 public:
14651 EvaluationTracker(SequenceChecker &Self)
14652 : Self(Self), Prev(Self.EvalTracker) {
14653 Self.EvalTracker = this;
14654 }
14655
14656 ~EvaluationTracker() {
14657 Self.EvalTracker = Prev;
14658 if (Prev)
14659 Prev->EvalOK &= EvalOK;
14660 }
14661
14662 bool evaluate(const Expr *E, bool &Result) {
14663 if (!EvalOK || E->isValueDependent())
14664 return false;
14665 EvalOK = E->EvaluateAsBooleanCondition(
14666 Result, Self.SemaRef.Context,
14667 Self.SemaRef.isConstantEvaluatedContext());
14668 return EvalOK;
14669 }
14670
14671 private:
14672 SequenceChecker &Self;
14673 EvaluationTracker *Prev;
14674 bool EvalOK = true;
14675 } *EvalTracker = nullptr;
14676
14677 /// Find the object which is produced by the specified expression,
14678 /// if any.
14679 Object getObject(const Expr *E, bool Mod) const {
14680 E = E->IgnoreParenCasts();
14681 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14682 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14683 return getObject(UO->getSubExpr(), Mod);
14684 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14685 if (BO->getOpcode() == BO_Comma)
14686 return getObject(BO->getRHS(), Mod);
14687 if (Mod && BO->isAssignmentOp())
14688 return getObject(BO->getLHS(), Mod);
14689 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14690 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14691 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14692 return ME->getMemberDecl();
14693 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14694 // FIXME: If this is a reference, map through to its value.
14695 return DRE->getDecl();
14696 return nullptr;
14697 }
14698
14699 /// Note that an object \p O was modified or used by an expression
14700 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14701 /// the object \p O as obtained via the \p UsageMap.
14702 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14703 // Get the old usage for the given object and usage kind.
14704 Usage &U = UI.Uses[UK];
14705 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14706 // If we have a modification as side effect and are in a sequenced
14707 // subexpression, save the old Usage so that we can restore it later
14708 // in SequencedSubexpression::~SequencedSubexpression.
14709 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14710 ModAsSideEffect->push_back(std::make_pair(O, U));
14711 // Then record the new usage with the current sequencing region.
14712 U.UsageExpr = UsageExpr;
14713 U.Seq = Region;
14714 }
14715 }
14716
14717 /// Check whether a modification or use of an object \p O in an expression
14718 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14719 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14720 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14721 /// usage and false we are checking for a mod-use unsequenced usage.
14722 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14723 UsageKind OtherKind, bool IsModMod) {
14724 if (UI.Diagnosed)
14725 return;
14726
14727 const Usage &U = UI.Uses[OtherKind];
14728 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14729 return;
14730
14731 const Expr *Mod = U.UsageExpr;
14732 const Expr *ModOrUse = UsageExpr;
14733 if (OtherKind == UK_Use)
14734 std::swap(Mod, ModOrUse);
14735
14736 SemaRef.DiagRuntimeBehavior(
14737 Mod->getExprLoc(), {Mod, ModOrUse},
14738 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14739 : diag::warn_unsequenced_mod_use)
14740 << O << SourceRange(ModOrUse->getExprLoc()));
14741 UI.Diagnosed = true;
14742 }
14743
14744 // A note on note{Pre, Post}{Use, Mod}:
14745 //
14746 // (It helps to follow the algorithm with an expression such as
14747 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14748 // operations before C++17 and both are well-defined in C++17).
14749 //
14750 // When visiting a node which uses/modify an object we first call notePreUse
14751 // or notePreMod before visiting its sub-expression(s). At this point the
14752 // children of the current node have not yet been visited and so the eventual
14753 // uses/modifications resulting from the children of the current node have not
14754 // been recorded yet.
14755 //
14756 // We then visit the children of the current node. After that notePostUse or
14757 // notePostMod is called. These will 1) detect an unsequenced modification
14758 // as side effect (as in "k++ + k") and 2) add a new usage with the
14759 // appropriate usage kind.
14760 //
14761 // We also have to be careful that some operation sequences modification as
14762 // side effect as well (for example: || or ,). To account for this we wrap
14763 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14764 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14765 // which record usages which are modifications as side effect, and then
14766 // downgrade them (or more accurately restore the previous usage which was a
14767 // modification as side effect) when exiting the scope of the sequenced
14768 // subexpression.
14769
14770 void notePreUse(Object O, const Expr *UseExpr) {
14771 UsageInfo &UI = UsageMap[O];
14772 // Uses conflict with other modifications.
14773 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14774 }
14775
14776 void notePostUse(Object O, const Expr *UseExpr) {
14777 UsageInfo &UI = UsageMap[O];
14778 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14779 /*IsModMod=*/false);
14780 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14781 }
14782
14783 void notePreMod(Object O, const Expr *ModExpr) {
14784 UsageInfo &UI = UsageMap[O];
14785 // Modifications conflict with other modifications and with uses.
14786 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14787 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14788 }
14789
14790 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14791 UsageInfo &UI = UsageMap[O];
14792 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14793 /*IsModMod=*/true);
14794 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14795 }
14796
14797public:
14798 SequenceChecker(Sema &S, const Expr *E,
14799 SmallVectorImpl<const Expr *> &WorkList)
14800 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14801 Visit(E);
14802 // Silence a -Wunused-private-field since WorkList is now unused.
14803 // TODO: Evaluate if it can be used, and if not remove it.
14804 (void)this->WorkList;
14805 }
14806
14807 void VisitStmt(const Stmt *S) {
14808 // Skip all statements which aren't expressions for now.
14809 }
14810
14811 void VisitExpr(const Expr *E) {
14812 // By default, just recurse to evaluated subexpressions.
14813 Base::VisitStmt(E);
14814 }
14815
14816 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14817 for (auto *Sub : CSE->children()) {
14818 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
14819 if (!ChildExpr)
14820 continue;
14821
14822 if (ChildExpr == CSE->getOperand())
14823 // Do not recurse over a CoroutineSuspendExpr's operand.
14824 // The operand is also a subexpression of getCommonExpr(), and
14825 // recursing into it directly could confuse object management
14826 // for the sake of sequence tracking.
14827 continue;
14828
14829 Visit(Sub);
14830 }
14831 }
14832
14833 void VisitCastExpr(const CastExpr *E) {
14834 Object O = Object();
14835 if (E->getCastKind() == CK_LValueToRValue)
14836 O = getObject(E->getSubExpr(), false);
14837
14838 if (O)
14839 notePreUse(O, E);
14840 VisitExpr(E);
14841 if (O)
14842 notePostUse(O, E);
14843 }
14844
14845 void VisitSequencedExpressions(const Expr *SequencedBefore,
14846 const Expr *SequencedAfter) {
14847 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14848 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14849 SequenceTree::Seq OldRegion = Region;
14850
14851 {
14852 SequencedSubexpression SeqBefore(*this);
14853 Region = BeforeRegion;
14854 Visit(SequencedBefore);
14855 }
14856
14857 Region = AfterRegion;
14858 Visit(SequencedAfter);
14859
14860 Region = OldRegion;
14861
14862 Tree.merge(BeforeRegion);
14863 Tree.merge(AfterRegion);
14864 }
14865
14866 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14867 // C++17 [expr.sub]p1:
14868 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14869 // expression E1 is sequenced before the expression E2.
14870 if (SemaRef.getLangOpts().CPlusPlus17)
14871 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14872 else {
14873 Visit(ASE->getLHS());
14874 Visit(ASE->getRHS());
14875 }
14876 }
14877
14878 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14879 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14880 void VisitBinPtrMem(const BinaryOperator *BO) {
14881 // C++17 [expr.mptr.oper]p4:
14882 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14883 // the expression E1 is sequenced before the expression E2.
14884 if (SemaRef.getLangOpts().CPlusPlus17)
14885 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14886 else {
14887 Visit(BO->getLHS());
14888 Visit(BO->getRHS());
14889 }
14890 }
14891
14892 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14893 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14894 void VisitBinShlShr(const BinaryOperator *BO) {
14895 // C++17 [expr.shift]p4:
14896 // The expression E1 is sequenced before the expression E2.
14897 if (SemaRef.getLangOpts().CPlusPlus17)
14898 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14899 else {
14900 Visit(BO->getLHS());
14901 Visit(BO->getRHS());
14902 }
14903 }
14904
14905 void VisitBinComma(const BinaryOperator *BO) {
14906 // C++11 [expr.comma]p1:
14907 // Every value computation and side effect associated with the left
14908 // expression is sequenced before every value computation and side
14909 // effect associated with the right expression.
14910 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14911 }
14912
14913 void VisitBinAssign(const BinaryOperator *BO) {
14914 SequenceTree::Seq RHSRegion;
14915 SequenceTree::Seq LHSRegion;
14916 if (SemaRef.getLangOpts().CPlusPlus17) {
14917 RHSRegion = Tree.allocate(Region);
14918 LHSRegion = Tree.allocate(Region);
14919 } else {
14920 RHSRegion = Region;
14921 LHSRegion = Region;
14922 }
14923 SequenceTree::Seq OldRegion = Region;
14924
14925 // C++11 [expr.ass]p1:
14926 // [...] the assignment is sequenced after the value computation
14927 // of the right and left operands, [...]
14928 //
14929 // so check it before inspecting the operands and update the
14930 // map afterwards.
14931 Object O = getObject(BO->getLHS(), /*Mod=*/true);
14932 if (O)
14933 notePreMod(O, BO);
14934
14935 if (SemaRef.getLangOpts().CPlusPlus17) {
14936 // C++17 [expr.ass]p1:
14937 // [...] The right operand is sequenced before the left operand. [...]
14938 {
14939 SequencedSubexpression SeqBefore(*this);
14940 Region = RHSRegion;
14941 Visit(BO->getRHS());
14942 }
14943
14944 Region = LHSRegion;
14945 Visit(BO->getLHS());
14946
14947 if (O && isa<CompoundAssignOperator>(BO))
14948 notePostUse(O, BO);
14949
14950 } else {
14951 // C++11 does not specify any sequencing between the LHS and RHS.
14952 Region = LHSRegion;
14953 Visit(BO->getLHS());
14954
14955 if (O && isa<CompoundAssignOperator>(BO))
14956 notePostUse(O, BO);
14957
14958 Region = RHSRegion;
14959 Visit(BO->getRHS());
14960 }
14961
14962 // C++11 [expr.ass]p1:
14963 // the assignment is sequenced [...] before the value computation of the
14964 // assignment expression.
14965 // C11 6.5.16/3 has no such rule.
14966 Region = OldRegion;
14967 if (O)
14968 notePostMod(O, BO,
14969 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14970 : UK_ModAsSideEffect);
14971 if (SemaRef.getLangOpts().CPlusPlus17) {
14972 Tree.merge(RHSRegion);
14973 Tree.merge(LHSRegion);
14974 }
14975 }
14976
14977 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14978 VisitBinAssign(CAO);
14979 }
14980
14981 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14982 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14983 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14984 Object O = getObject(UO->getSubExpr(), true);
14985 if (!O)
14986 return VisitExpr(UO);
14987
14988 notePreMod(O, UO);
14989 Visit(UO->getSubExpr());
14990 // C++11 [expr.pre.incr]p1:
14991 // the expression ++x is equivalent to x+=1
14992 notePostMod(O, UO,
14993 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14994 : UK_ModAsSideEffect);
14995 }
14996
14997 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14998 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14999 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
15000 Object O = getObject(UO->getSubExpr(), true);
15001 if (!O)
15002 return VisitExpr(UO);
15003
15004 notePreMod(O, UO);
15005 Visit(UO->getSubExpr());
15006 notePostMod(O, UO, UK_ModAsSideEffect);
15007 }
15008
15009 void VisitBinLOr(const BinaryOperator *BO) {
15010 // C++11 [expr.log.or]p2:
15011 // If the second expression is evaluated, every value computation and
15012 // side effect associated with the first expression is sequenced before
15013 // every value computation and side effect associated with the
15014 // second expression.
15015 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15016 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15017 SequenceTree::Seq OldRegion = Region;
15018
15019 EvaluationTracker Eval(*this);
15020 {
15021 SequencedSubexpression Sequenced(*this);
15022 Region = LHSRegion;
15023 Visit(BO->getLHS());
15024 }
15025
15026 // C++11 [expr.log.or]p1:
15027 // [...] the second operand is not evaluated if the first operand
15028 // evaluates to true.
15029 bool EvalResult = false;
15030 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15031 bool ShouldVisitRHS = !EvalOK || !EvalResult;
15032 if (ShouldVisitRHS) {
15033 Region = RHSRegion;
15034 Visit(BO->getRHS());
15035 }
15036
15037 Region = OldRegion;
15038 Tree.merge(LHSRegion);
15039 Tree.merge(RHSRegion);
15040 }
15041
15042 void VisitBinLAnd(const BinaryOperator *BO) {
15043 // C++11 [expr.log.and]p2:
15044 // If the second expression is evaluated, every value computation and
15045 // side effect associated with the first expression is sequenced before
15046 // every value computation and side effect associated with the
15047 // second expression.
15048 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15049 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15050 SequenceTree::Seq OldRegion = Region;
15051
15052 EvaluationTracker Eval(*this);
15053 {
15054 SequencedSubexpression Sequenced(*this);
15055 Region = LHSRegion;
15056 Visit(BO->getLHS());
15057 }
15058
15059 // C++11 [expr.log.and]p1:
15060 // [...] the second operand is not evaluated if the first operand is false.
15061 bool EvalResult = false;
15062 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15063 bool ShouldVisitRHS = !EvalOK || EvalResult;
15064 if (ShouldVisitRHS) {
15065 Region = RHSRegion;
15066 Visit(BO->getRHS());
15067 }
15068
15069 Region = OldRegion;
15070 Tree.merge(LHSRegion);
15071 Tree.merge(RHSRegion);
15072 }
15073
15074 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
15075 // C++11 [expr.cond]p1:
15076 // [...] Every value computation and side effect associated with the first
15077 // expression is sequenced before every value computation and side effect
15078 // associated with the second or third expression.
15079 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
15080
15081 // No sequencing is specified between the true and false expression.
15082 // However since exactly one of both is going to be evaluated we can
15083 // consider them to be sequenced. This is needed to avoid warning on
15084 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
15085 // both the true and false expressions because we can't evaluate x.
15086 // This will still allow us to detect an expression like (pre C++17)
15087 // "(x ? y += 1 : y += 2) = y".
15088 //
15089 // We don't wrap the visitation of the true and false expression with
15090 // SequencedSubexpression because we don't want to downgrade modifications
15091 // as side effect in the true and false expressions after the visition
15092 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
15093 // not warn between the two "y++", but we should warn between the "y++"
15094 // and the "y".
15095 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
15096 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
15097 SequenceTree::Seq OldRegion = Region;
15098
15099 EvaluationTracker Eval(*this);
15100 {
15101 SequencedSubexpression Sequenced(*this);
15102 Region = ConditionRegion;
15103 Visit(CO->getCond());
15104 }
15105
15106 // C++11 [expr.cond]p1:
15107 // [...] The first expression is contextually converted to bool (Clause 4).
15108 // It is evaluated and if it is true, the result of the conditional
15109 // expression is the value of the second expression, otherwise that of the
15110 // third expression. Only one of the second and third expressions is
15111 // evaluated. [...]
15112 bool EvalResult = false;
15113 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
15114 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
15115 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
15116 if (ShouldVisitTrueExpr) {
15117 Region = TrueRegion;
15118 Visit(CO->getTrueExpr());
15119 }
15120 if (ShouldVisitFalseExpr) {
15121 Region = FalseRegion;
15122 Visit(CO->getFalseExpr());
15123 }
15124
15125 Region = OldRegion;
15126 Tree.merge(ConditionRegion);
15127 Tree.merge(TrueRegion);
15128 Tree.merge(FalseRegion);
15129 }
15130
15131 void VisitCallExpr(const CallExpr *CE) {
15132 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
15133
15134 if (CE->isUnevaluatedBuiltinCall(Context))
15135 return;
15136
15137 // C++11 [intro.execution]p15:
15138 // When calling a function [...], every value computation and side effect
15139 // associated with any argument expression, or with the postfix expression
15140 // designating the called function, is sequenced before execution of every
15141 // expression or statement in the body of the function [and thus before
15142 // the value computation of its result].
15143 SequencedSubexpression Sequenced(*this);
15144 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
15145 // C++17 [expr.call]p5
15146 // The postfix-expression is sequenced before each expression in the
15147 // expression-list and any default argument. [...]
15148 SequenceTree::Seq CalleeRegion;
15149 SequenceTree::Seq OtherRegion;
15150 if (SemaRef.getLangOpts().CPlusPlus17) {
15151 CalleeRegion = Tree.allocate(Region);
15152 OtherRegion = Tree.allocate(Region);
15153 } else {
15154 CalleeRegion = Region;
15155 OtherRegion = Region;
15156 }
15157 SequenceTree::Seq OldRegion = Region;
15158
15159 // Visit the callee expression first.
15160 Region = CalleeRegion;
15161 if (SemaRef.getLangOpts().CPlusPlus17) {
15162 SequencedSubexpression Sequenced(*this);
15163 Visit(CE->getCallee());
15164 } else {
15165 Visit(CE->getCallee());
15166 }
15167
15168 // Then visit the argument expressions.
15169 Region = OtherRegion;
15170 for (const Expr *Argument : CE->arguments())
15171 Visit(Argument);
15172
15173 Region = OldRegion;
15174 if (SemaRef.getLangOpts().CPlusPlus17) {
15175 Tree.merge(CalleeRegion);
15176 Tree.merge(OtherRegion);
15177 }
15178 });
15179 }
15180
15181 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
15182 // C++17 [over.match.oper]p2:
15183 // [...] the operator notation is first transformed to the equivalent
15184 // function-call notation as summarized in Table 12 (where @ denotes one
15185 // of the operators covered in the specified subclause). However, the
15186 // operands are sequenced in the order prescribed for the built-in
15187 // operator (Clause 8).
15188 //
15189 // From the above only overloaded binary operators and overloaded call
15190 // operators have sequencing rules in C++17 that we need to handle
15191 // separately.
15192 if (!SemaRef.getLangOpts().CPlusPlus17 ||
15193 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15194 return VisitCallExpr(CXXOCE);
15195
15196 enum {
15197 NoSequencing,
15198 LHSBeforeRHS,
15199 RHSBeforeLHS,
15200 LHSBeforeRest
15201 } SequencingKind;
15202 switch (CXXOCE->getOperator()) {
15203 case OO_Equal:
15204 case OO_PlusEqual:
15205 case OO_MinusEqual:
15206 case OO_StarEqual:
15207 case OO_SlashEqual:
15208 case OO_PercentEqual:
15209 case OO_CaretEqual:
15210 case OO_AmpEqual:
15211 case OO_PipeEqual:
15212 case OO_LessLessEqual:
15213 case OO_GreaterGreaterEqual:
15214 SequencingKind = RHSBeforeLHS;
15215 break;
15216
15217 case OO_LessLess:
15218 case OO_GreaterGreater:
15219 case OO_AmpAmp:
15220 case OO_PipePipe:
15221 case OO_Comma:
15222 case OO_ArrowStar:
15223 case OO_Subscript:
15224 SequencingKind = LHSBeforeRHS;
15225 break;
15226
15227 case OO_Call:
15228 SequencingKind = LHSBeforeRest;
15229 break;
15230
15231 default:
15232 SequencingKind = NoSequencing;
15233 break;
15234 }
15235
15236 if (SequencingKind == NoSequencing)
15237 return VisitCallExpr(CXXOCE);
15238
15239 // This is a call, so all subexpressions are sequenced before the result.
15240 SequencedSubexpression Sequenced(*this);
15241
15242 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
15243 assert(SemaRef.getLangOpts().CPlusPlus17 &&
15244 "Should only get there with C++17 and above!");
15245 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15246 "Should only get there with an overloaded binary operator"
15247 " or an overloaded call operator!");
15248
15249 if (SequencingKind == LHSBeforeRest) {
15250 assert(CXXOCE->getOperator() == OO_Call &&
15251 "We should only have an overloaded call operator here!");
15252
15253 // This is very similar to VisitCallExpr, except that we only have the
15254 // C++17 case. The postfix-expression is the first argument of the
15255 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15256 // are in the following arguments.
15257 //
15258 // Note that we intentionally do not visit the callee expression since
15259 // it is just a decayed reference to a function.
15260 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
15261 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
15262 SequenceTree::Seq OldRegion = Region;
15263
15264 assert(CXXOCE->getNumArgs() >= 1 &&
15265 "An overloaded call operator must have at least one argument"
15266 " for the postfix-expression!");
15267 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15268 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15269 CXXOCE->getNumArgs() - 1);
15270
15271 // Visit the postfix-expression first.
15272 {
15273 Region = PostfixExprRegion;
15274 SequencedSubexpression Sequenced(*this);
15275 Visit(PostfixExpr);
15276 }
15277
15278 // Then visit the argument expressions.
15279 Region = ArgsRegion;
15280 for (const Expr *Arg : Args)
15281 Visit(Arg);
15282
15283 Region = OldRegion;
15284 Tree.merge(PostfixExprRegion);
15285 Tree.merge(ArgsRegion);
15286 } else {
15287 assert(CXXOCE->getNumArgs() == 2 &&
15288 "Should only have two arguments here!");
15289 assert((SequencingKind == LHSBeforeRHS ||
15290 SequencingKind == RHSBeforeLHS) &&
15291 "Unexpected sequencing kind!");
15292
15293 // We do not visit the callee expression since it is just a decayed
15294 // reference to a function.
15295 const Expr *E1 = CXXOCE->getArg(0);
15296 const Expr *E2 = CXXOCE->getArg(1);
15297 if (SequencingKind == RHSBeforeLHS)
15298 std::swap(E1, E2);
15299
15300 return VisitSequencedExpressions(E1, E2);
15301 }
15302 });
15303 }
15304
15305 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15306 // This is a call, so all subexpressions are sequenced before the result.
15307 SequencedSubexpression Sequenced(*this);
15308
15309 if (!CCE->isListInitialization())
15310 return VisitExpr(CCE);
15311
15312 // In C++11, list initializations are sequenced.
15313 SequenceExpressionsInOrder(
15314 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
15315 }
15316
15317 void VisitInitListExpr(const InitListExpr *ILE) {
15318 if (!SemaRef.getLangOpts().CPlusPlus11)
15319 return VisitExpr(ILE);
15320
15321 // In C++11, list initializations are sequenced.
15322 SequenceExpressionsInOrder(ILE->inits());
15323 }
15324
15325 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
15326 // C++20 parenthesized list initializations are sequenced. See C++20
15327 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
15328 SequenceExpressionsInOrder(PLIE->getInitExprs());
15329 }
15330
15331private:
15332 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
15334 SequenceTree::Seq Parent = Region;
15335 for (const Expr *E : ExpressionList) {
15336 if (!E)
15337 continue;
15338 Region = Tree.allocate(Parent);
15339 Elts.push_back(Region);
15340 Visit(E);
15341 }
15342
15343 // Forget that the initializers are sequenced.
15344 Region = Parent;
15345 for (unsigned I = 0; I < Elts.size(); ++I)
15346 Tree.merge(Elts[I]);
15347 }
15348};
15349
15350SequenceChecker::UsageInfo::UsageInfo() = default;
15351
15352} // namespace
15353
15354void Sema::CheckUnsequencedOperations(const Expr *E) {
15355 SmallVector<const Expr *, 8> WorkList;
15356 WorkList.push_back(E);
15357 while (!WorkList.empty()) {
15358 const Expr *Item = WorkList.pop_back_val();
15359 SequenceChecker(*this, Item, WorkList);
15360 }
15361}
15362
15363void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15364 bool IsConstexpr) {
15365 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15366 IsConstexpr || isa<ConstantExpr>(E));
15367 CheckImplicitConversions(E, CheckLoc);
15368 if (!E->isInstantiationDependent())
15369 CheckUnsequencedOperations(E);
15370 if (!IsConstexpr && !E->isValueDependent())
15371 CheckForIntOverflow(E);
15372}
15373
15374void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15375 FieldDecl *BitField,
15376 Expr *Init) {
15377 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
15378}
15379
15381 SourceLocation Loc) {
15382 if (!PType->isVariablyModifiedType())
15383 return;
15384 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
15385 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
15386 return;
15387 }
15388 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
15389 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
15390 return;
15391 }
15392 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
15393 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
15394 return;
15395 }
15396
15397 const ArrayType *AT = S.Context.getAsArrayType(PType);
15398 if (!AT)
15399 return;
15400
15403 return;
15404 }
15405
15406 S.Diag(Loc, diag::err_array_star_in_function_definition);
15407}
15408
15410 bool CheckParameterNames) {
15411 bool HasInvalidParm = false;
15412 for (ParmVarDecl *Param : Parameters) {
15413 assert(Param && "null in a parameter list");
15414 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15415 // function declarator that is part of a function definition of
15416 // that function shall not have incomplete type.
15417 //
15418 // C++23 [dcl.fct.def.general]/p2
15419 // The type of a parameter [...] for a function definition
15420 // shall not be a (possibly cv-qualified) class type that is incomplete
15421 // or abstract within the function body unless the function is deleted.
15422 if (!Param->isInvalidDecl() &&
15423 (RequireCompleteType(Param->getLocation(), Param->getType(),
15424 diag::err_typecheck_decl_incomplete_type) ||
15425 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
15426 diag::err_abstract_type_in_decl,
15428 Param->setInvalidDecl();
15429 HasInvalidParm = true;
15430 }
15431
15432 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15433 // declaration of each parameter shall include an identifier.
15434 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15435 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15436 // Diagnose this as an extension in C17 and earlier.
15437 if (!getLangOpts().C23)
15438 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
15439 }
15440
15441 // C99 6.7.5.3p12:
15442 // If the function declarator is not part of a definition of that
15443 // function, parameters may have incomplete type and may use the [*]
15444 // notation in their sequences of declarator specifiers to specify
15445 // variable length array types.
15446 QualType PType = Param->getOriginalType();
15447 // FIXME: This diagnostic should point the '[*]' if source-location
15448 // information is added for it.
15449 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15450
15451 // If the parameter is a c++ class type and it has to be destructed in the
15452 // callee function, declare the destructor so that it can be called by the
15453 // callee function. Do not perform any direct access check on the dtor here.
15454 if (!Param->isInvalidDecl()) {
15455 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15456 if (!ClassDecl->isInvalidDecl() &&
15457 !ClassDecl->hasIrrelevantDestructor() &&
15458 !ClassDecl->isDependentContext() &&
15459 ClassDecl->isParamDestroyedInCallee()) {
15461 MarkFunctionReferenced(Param->getLocation(), Destructor);
15462 DiagnoseUseOfDecl(Destructor, Param->getLocation());
15463 }
15464 }
15465 }
15466
15467 // Parameters with the pass_object_size attribute only need to be marked
15468 // constant at function definitions. Because we lack information about
15469 // whether we're on a declaration or definition when we're instantiating the
15470 // attribute, we need to check for constness here.
15471 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15472 if (!Param->getType().isConstQualified())
15473 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15474 << Attr->getSpelling() << 1;
15475
15476 // Check for parameter names shadowing fields from the class.
15477 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15478 // The owning context for the parameter should be the function, but we
15479 // want to see if this function's declaration context is a record.
15480 DeclContext *DC = Param->getDeclContext();
15481 if (DC && DC->isFunctionOrMethod()) {
15482 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15483 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15484 RD, /*DeclIsField*/ false);
15485 }
15486 }
15487
15488 if (!Param->isInvalidDecl() &&
15489 Param->getOriginalType()->isWebAssemblyTableType()) {
15490 Param->setInvalidDecl();
15491 HasInvalidParm = true;
15492 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
15493 }
15494 }
15495
15496 return HasInvalidParm;
15497}
15498
15499std::optional<std::pair<
15501 *E,
15503 &Ctx);
15504
15505/// Compute the alignment and offset of the base class object given the
15506/// derived-to-base cast expression and the alignment and offset of the derived
15507/// class object.
15508static std::pair<CharUnits, CharUnits>
15510 CharUnits BaseAlignment, CharUnits Offset,
15511 ASTContext &Ctx) {
15512 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15513 ++PathI) {
15514 const CXXBaseSpecifier *Base = *PathI;
15515 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15516 if (Base->isVirtual()) {
15517 // The complete object may have a lower alignment than the non-virtual
15518 // alignment of the base, in which case the base may be misaligned. Choose
15519 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15520 // conservative lower bound of the complete object alignment.
15521 CharUnits NonVirtualAlignment =
15523 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15524 Offset = CharUnits::Zero();
15525 } else {
15526 const ASTRecordLayout &RL =
15527 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15528 Offset += RL.getBaseClassOffset(BaseDecl);
15529 }
15530 DerivedType = Base->getType();
15531 }
15532
15533 return std::make_pair(BaseAlignment, Offset);
15534}
15535
15536/// Compute the alignment and offset of a binary additive operator.
15537static std::optional<std::pair<CharUnits, CharUnits>>
15539 bool IsSub, ASTContext &Ctx) {
15540 QualType PointeeType = PtrE->getType()->getPointeeType();
15541
15542 if (!PointeeType->isConstantSizeType())
15543 return std::nullopt;
15544
15545 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15546
15547 if (!P)
15548 return std::nullopt;
15549
15550 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15551 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15552 CharUnits Offset = EltSize * IdxRes->getExtValue();
15553 if (IsSub)
15554 Offset = -Offset;
15555 return std::make_pair(P->first, P->second + Offset);
15556 }
15557
15558 // If the integer expression isn't a constant expression, compute the lower
15559 // bound of the alignment using the alignment and offset of the pointer
15560 // expression and the element size.
15561 return std::make_pair(
15562 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15563 CharUnits::Zero());
15564}
15565
15566/// This helper function takes an lvalue expression and returns the alignment of
15567/// a VarDecl and a constant offset from the VarDecl.
15568std::optional<std::pair<
15569 CharUnits,
15571 ASTContext &Ctx) {
15572 E = E->IgnoreParens();
15573 switch (E->getStmtClass()) {
15574 default:
15575 break;
15576 case Stmt::CStyleCastExprClass:
15577 case Stmt::CXXStaticCastExprClass:
15578 case Stmt::ImplicitCastExprClass: {
15579 auto *CE = cast<CastExpr>(E);
15580 const Expr *From = CE->getSubExpr();
15581 switch (CE->getCastKind()) {
15582 default:
15583 break;
15584 case CK_NoOp:
15585 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15586 case CK_UncheckedDerivedToBase:
15587 case CK_DerivedToBase: {
15588 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15589 if (!P)
15590 break;
15591 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15592 P->second, Ctx);
15593 }
15594 }
15595 break;
15596 }
15597 case Stmt::ArraySubscriptExprClass: {
15598 auto *ASE = cast<ArraySubscriptExpr>(E);
15600 false, Ctx);
15601 }
15602 case Stmt::DeclRefExprClass: {
15603 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15604 // FIXME: If VD is captured by copy or is an escaping __block variable,
15605 // use the alignment of VD's type.
15606 if (!VD->getType()->isReferenceType()) {
15607 // Dependent alignment cannot be resolved -> bail out.
15608 if (VD->hasDependentAlignment())
15609 break;
15610 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15611 }
15612 if (VD->hasInit())
15613 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15614 }
15615 break;
15616 }
15617 case Stmt::MemberExprClass: {
15618 auto *ME = cast<MemberExpr>(E);
15619 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15620 if (!FD || FD->getType()->isReferenceType() ||
15621 FD->getParent()->isInvalidDecl())
15622 break;
15623 std::optional<std::pair<CharUnits, CharUnits>> P;
15624 if (ME->isArrow())
15625 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15626 else
15627 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15628 if (!P)
15629 break;
15630 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15631 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15632 return std::make_pair(P->first,
15633 P->second + CharUnits::fromQuantity(Offset));
15634 }
15635 case Stmt::UnaryOperatorClass: {
15636 auto *UO = cast<UnaryOperator>(E);
15637 switch (UO->getOpcode()) {
15638 default:
15639 break;
15640 case UO_Deref:
15642 }
15643 break;
15644 }
15645 case Stmt::BinaryOperatorClass: {
15646 auto *BO = cast<BinaryOperator>(E);
15647 auto Opcode = BO->getOpcode();
15648 switch (Opcode) {
15649 default:
15650 break;
15651 case BO_Comma:
15653 }
15654 break;
15655 }
15656 }
15657 return std::nullopt;
15658}
15659
15660/// This helper function takes a pointer expression and returns the alignment of
15661/// a VarDecl and a constant offset from the VarDecl.
15662std::optional<std::pair<
15664 *E,
15666 &Ctx) {
15667 E = E->IgnoreParens();
15668 switch (E->getStmtClass()) {
15669 default:
15670 break;
15671 case Stmt::CStyleCastExprClass:
15672 case Stmt::CXXStaticCastExprClass:
15673 case Stmt::ImplicitCastExprClass: {
15674 auto *CE = cast<CastExpr>(E);
15675 const Expr *From = CE->getSubExpr();
15676 switch (CE->getCastKind()) {
15677 default:
15678 break;
15679 case CK_NoOp:
15680 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15681 case CK_ArrayToPointerDecay:
15682 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15683 case CK_UncheckedDerivedToBase:
15684 case CK_DerivedToBase: {
15685 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15686 if (!P)
15687 break;
15689 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15690 }
15691 }
15692 break;
15693 }
15694 case Stmt::CXXThisExprClass: {
15695 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15697 return std::make_pair(Alignment, CharUnits::Zero());
15698 }
15699 case Stmt::UnaryOperatorClass: {
15700 auto *UO = cast<UnaryOperator>(E);
15701 if (UO->getOpcode() == UO_AddrOf)
15703 break;
15704 }
15705 case Stmt::BinaryOperatorClass: {
15706 auto *BO = cast<BinaryOperator>(E);
15707 auto Opcode = BO->getOpcode();
15708 switch (Opcode) {
15709 default:
15710 break;
15711 case BO_Add:
15712 case BO_Sub: {
15713 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15714 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15715 std::swap(LHS, RHS);
15716 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15717 Ctx);
15718 }
15719 case BO_Comma:
15720 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15721 }
15722 break;
15723 }
15724 }
15725 return std::nullopt;
15726}
15727
15729 // See if we can compute the alignment of a VarDecl and an offset from it.
15730 std::optional<std::pair<CharUnits, CharUnits>> P =
15732
15733 if (P)
15734 return P->first.alignmentAtOffset(P->second);
15735
15736 // If that failed, return the type's alignment.
15738}
15739
15741 // This is actually a lot of work to potentially be doing on every
15742 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15743 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15744 return;
15745
15746 // Ignore dependent types.
15747 if (T->isDependentType() || Op->getType()->isDependentType())
15748 return;
15749
15750 // Require that the destination be a pointer type.
15751 const PointerType *DestPtr = T->getAs<PointerType>();
15752 if (!DestPtr) return;
15753
15754 // If the destination has alignment 1, we're done.
15755 QualType DestPointee = DestPtr->getPointeeType();
15756 if (DestPointee->isIncompleteType()) return;
15757 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15758 if (DestAlign.isOne()) return;
15759
15760 // Require that the source be a pointer type.
15761 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15762 if (!SrcPtr) return;
15763 QualType SrcPointee = SrcPtr->getPointeeType();
15764
15765 // Explicitly allow casts from cv void*. We already implicitly
15766 // allowed casts to cv void*, since they have alignment 1.
15767 // Also allow casts involving incomplete types, which implicitly
15768 // includes 'void'.
15769 if (SrcPointee->isIncompleteType()) return;
15770
15771 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15772
15773 if (SrcAlign >= DestAlign) return;
15774
15775 Diag(TRange.getBegin(), diag::warn_cast_align)
15776 << Op->getType() << T
15777 << static_cast<unsigned>(SrcAlign.getQuantity())
15778 << static_cast<unsigned>(DestAlign.getQuantity())
15779 << TRange << Op->getSourceRange();
15780}
15781
15782void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15783 const ArraySubscriptExpr *ASE,
15784 bool AllowOnePastEnd, bool IndexNegated) {
15785 // Already diagnosed by the constant evaluator.
15787 return;
15788
15789 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15790 if (IndexExpr->isValueDependent())
15791 return;
15792
15793 const Type *EffectiveType =
15795 BaseExpr = BaseExpr->IgnoreParenCasts();
15796 const ConstantArrayType *ArrayTy =
15797 Context.getAsConstantArrayType(BaseExpr->getType());
15798
15800 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15801
15802 const Type *BaseType =
15803 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15804 bool IsUnboundedArray =
15805 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15806 Context, StrictFlexArraysLevel,
15807 /*IgnoreTemplateOrMacroSubstitution=*/true);
15808 if (EffectiveType->isDependentType() ||
15809 (!IsUnboundedArray && BaseType->isDependentType()))
15810 return;
15811
15813 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15814 return;
15815
15816 llvm::APSInt index = Result.Val.getInt();
15817 if (IndexNegated) {
15818 index.setIsUnsigned(false);
15819 index = -index;
15820 }
15821
15822 if (IsUnboundedArray) {
15823 if (EffectiveType->isFunctionType())
15824 return;
15825 if (index.isUnsigned() || !index.isNegative()) {
15826 const auto &ASTC = getASTContext();
15827 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15828 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15829 if (index.getBitWidth() < AddrBits)
15830 index = index.zext(AddrBits);
15831 std::optional<CharUnits> ElemCharUnits =
15832 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15833 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15834 // pointer) bounds-checking isn't meaningful.
15835 if (!ElemCharUnits || ElemCharUnits->isZero())
15836 return;
15837 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15838 // If index has more active bits than address space, we already know
15839 // we have a bounds violation to warn about. Otherwise, compute
15840 // address of (index + 1)th element, and warn about bounds violation
15841 // only if that address exceeds address space.
15842 if (index.getActiveBits() <= AddrBits) {
15843 bool Overflow;
15844 llvm::APInt Product(index);
15845 Product += 1;
15846 Product = Product.umul_ov(ElemBytes, Overflow);
15847 if (!Overflow && Product.getActiveBits() <= AddrBits)
15848 return;
15849 }
15850
15851 // Need to compute max possible elements in address space, since that
15852 // is included in diag message.
15853 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15854 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15855 MaxElems += 1;
15856 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15857 MaxElems = MaxElems.udiv(ElemBytes);
15858
15859 unsigned DiagID =
15860 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15861 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15862
15863 // Diag message shows element size in bits and in "bytes" (platform-
15864 // dependent CharUnits)
15865 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15866 PDiag(DiagID) << index << AddrBits
15867 << (unsigned)ASTC.toBits(*ElemCharUnits)
15868 << ElemBytes << MaxElems
15869 << MaxElems.getZExtValue()
15870 << IndexExpr->getSourceRange());
15871
15872 const NamedDecl *ND = nullptr;
15873 // Try harder to find a NamedDecl to point at in the note.
15874 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15875 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15876 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15877 ND = DRE->getDecl();
15878 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15879 ND = ME->getMemberDecl();
15880
15881 if (ND)
15882 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15883 PDiag(diag::note_array_declared_here) << ND);
15884 }
15885 return;
15886 }
15887
15888 if (index.isUnsigned() || !index.isNegative()) {
15889 // It is possible that the type of the base expression after
15890 // IgnoreParenCasts is incomplete, even though the type of the base
15891 // expression before IgnoreParenCasts is complete (see PR39746 for an
15892 // example). In this case we have no information about whether the array
15893 // access exceeds the array bounds. However we can still diagnose an array
15894 // access which precedes the array bounds.
15895 if (BaseType->isIncompleteType())
15896 return;
15897
15898 llvm::APInt size = ArrayTy->getSize();
15899
15900 if (BaseType != EffectiveType) {
15901 // Make sure we're comparing apples to apples when comparing index to
15902 // size.
15903 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15904 uint64_t array_typesize = Context.getTypeSize(BaseType);
15905
15906 // Handle ptrarith_typesize being zero, such as when casting to void*.
15907 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
15908 if (!ptrarith_typesize)
15909 ptrarith_typesize = Context.getCharWidth();
15910
15911 if (ptrarith_typesize != array_typesize) {
15912 // There's a cast to a different size type involved.
15913 uint64_t ratio = array_typesize / ptrarith_typesize;
15914
15915 // TODO: Be smarter about handling cases where array_typesize is not a
15916 // multiple of ptrarith_typesize.
15917 if (ptrarith_typesize * ratio == array_typesize)
15918 size *= llvm::APInt(size.getBitWidth(), ratio);
15919 }
15920 }
15921
15922 if (size.getBitWidth() > index.getBitWidth())
15923 index = index.zext(size.getBitWidth());
15924 else if (size.getBitWidth() < index.getBitWidth())
15925 size = size.zext(index.getBitWidth());
15926
15927 // For array subscripting the index must be less than size, but for pointer
15928 // arithmetic also allow the index (offset) to be equal to size since
15929 // computing the next address after the end of the array is legal and
15930 // commonly done e.g. in C++ iterators and range-based for loops.
15931 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15932 return;
15933
15934 // Suppress the warning if the subscript expression (as identified by the
15935 // ']' location) and the index expression are both from macro expansions
15936 // within a system header.
15937 if (ASE) {
15938 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15939 ASE->getRBracketLoc());
15940 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15941 SourceLocation IndexLoc =
15942 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15943 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15944 return;
15945 }
15946 }
15947
15948 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15949 : diag::warn_ptr_arith_exceeds_bounds;
15950 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
15951 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
15952
15953 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15954 PDiag(DiagID)
15955 << index << ArrayTy->desugar() << CastMsg
15956 << CastMsgTy << IndexExpr->getSourceRange());
15957 } else {
15958 unsigned DiagID = diag::warn_array_index_precedes_bounds;
15959 if (!ASE) {
15960 DiagID = diag::warn_ptr_arith_precedes_bounds;
15961 if (index.isNegative()) index = -index;
15962 }
15963
15964 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15965 PDiag(DiagID) << index << IndexExpr->getSourceRange());
15966 }
15967
15968 const NamedDecl *ND = nullptr;
15969 // Try harder to find a NamedDecl to point at in the note.
15970 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15971 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15972 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15973 ND = DRE->getDecl();
15974 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15975 ND = ME->getMemberDecl();
15976
15977 if (ND)
15978 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15979 PDiag(diag::note_array_declared_here) << ND);
15980}
15981
15982void Sema::CheckArrayAccess(const Expr *expr) {
15983 int AllowOnePastEnd = 0;
15984 while (expr) {
15985 expr = expr->IgnoreParenImpCasts();
15986 switch (expr->getStmtClass()) {
15987 case Stmt::ArraySubscriptExprClass: {
15988 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15989 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15990 AllowOnePastEnd > 0);
15991 expr = ASE->getBase();
15992 break;
15993 }
15994 case Stmt::MemberExprClass: {
15995 expr = cast<MemberExpr>(expr)->getBase();
15996 break;
15997 }
15998 case Stmt::CXXMemberCallExprClass: {
15999 expr = cast<CXXMemberCallExpr>(expr)->getImplicitObjectArgument();
16000 break;
16001 }
16002 case Stmt::ArraySectionExprClass: {
16003 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
16004 // FIXME: We should probably be checking all of the elements to the
16005 // 'length' here as well.
16006 if (ASE->getLowerBound())
16007 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
16008 /*ASE=*/nullptr, AllowOnePastEnd > 0);
16009 return;
16010 }
16011 case Stmt::UnaryOperatorClass: {
16012 // Only unwrap the * and & unary operators
16013 const UnaryOperator *UO = cast<UnaryOperator>(expr);
16014 expr = UO->getSubExpr();
16015 switch (UO->getOpcode()) {
16016 case UO_AddrOf:
16017 AllowOnePastEnd++;
16018 break;
16019 case UO_Deref:
16020 AllowOnePastEnd--;
16021 break;
16022 default:
16023 return;
16024 }
16025 break;
16026 }
16027 case Stmt::ConditionalOperatorClass: {
16028 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
16029 if (const Expr *lhs = cond->getLHS())
16030 CheckArrayAccess(lhs);
16031 if (const Expr *rhs = cond->getRHS())
16032 CheckArrayAccess(rhs);
16033 return;
16034 }
16035 case Stmt::CXXOperatorCallExprClass: {
16036 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
16037 for (const auto *Arg : OCE->arguments())
16038 CheckArrayAccess(Arg);
16039 return;
16040 }
16041 default:
16042 return;
16043 }
16044 }
16045}
16046
16048 Expr *RHS, bool isProperty) {
16049 // Check if RHS is an Objective-C object literal, which also can get
16050 // immediately zapped in a weak reference. Note that we explicitly
16051 // allow ObjCStringLiterals, since those are designed to never really die.
16052 RHS = RHS->IgnoreParenImpCasts();
16053
16054 // This enum needs to match with the 'select' in
16055 // warn_objc_arc_literal_assign (off-by-1).
16057 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
16058 return false;
16059
16060 S.Diag(Loc, diag::warn_arc_literal_assign)
16061 << (unsigned) Kind
16062 << (isProperty ? 0 : 1)
16063 << RHS->getSourceRange();
16064
16065 return true;
16066}
16067
16070 Expr *RHS, bool isProperty) {
16071 // Strip off any implicit cast added to get to the one ARC-specific.
16072 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16073 if (cast->getCastKind() == CK_ARCConsumeObject) {
16074 S.Diag(Loc, diag::warn_arc_retained_assign)
16076 << (isProperty ? 0 : 1)
16077 << RHS->getSourceRange();
16078 return true;
16079 }
16080 RHS = cast->getSubExpr();
16081 }
16082
16083 if (LT == Qualifiers::OCL_Weak &&
16084 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16085 return true;
16086
16087 return false;
16088}
16089
16091 QualType LHS, Expr *RHS) {
16093
16095 return false;
16096
16097 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16098 return true;
16099
16100 return false;
16101}
16102
16104 Expr *LHS, Expr *RHS) {
16105 QualType LHSType;
16106 // PropertyRef on LHS type need be directly obtained from
16107 // its declaration as it has a PseudoType.
16109 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16110 if (PRE && !PRE->isImplicitProperty()) {
16111 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16112 if (PD)
16113 LHSType = PD->getType();
16114 }
16115
16116 if (LHSType.isNull())
16117 LHSType = LHS->getType();
16118
16120
16121 if (LT == Qualifiers::OCL_Weak) {
16122 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16124 }
16125
16126 if (checkUnsafeAssigns(Loc, LHSType, RHS))
16127 return;
16128
16129 // FIXME. Check for other life times.
16130 if (LT != Qualifiers::OCL_None)
16131 return;
16132
16133 if (PRE) {
16134 if (PRE->isImplicitProperty())
16135 return;
16136 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16137 if (!PD)
16138 return;
16139
16140 unsigned Attributes = PD->getPropertyAttributes();
16141 if (Attributes & ObjCPropertyAttribute::kind_assign) {
16142 // when 'assign' attribute was not explicitly specified
16143 // by user, ignore it and rely on property type itself
16144 // for lifetime info.
16145 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16146 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16147 LHSType->isObjCRetainableType())
16148 return;
16149
16150 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16151 if (cast->getCastKind() == CK_ARCConsumeObject) {
16152 Diag(Loc, diag::warn_arc_retained_property_assign)
16153 << RHS->getSourceRange();
16154 return;
16155 }
16156 RHS = cast->getSubExpr();
16157 }
16158 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16159 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16160 return;
16161 }
16162 }
16163}
16164
16165//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16166
16167static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16168 SourceLocation StmtLoc,
16169 const NullStmt *Body) {
16170 // Do not warn if the body is a macro that expands to nothing, e.g:
16171 //
16172 // #define CALL(x)
16173 // if (condition)
16174 // CALL(0);
16175 if (Body->hasLeadingEmptyMacro())
16176 return false;
16177
16178 // Get line numbers of statement and body.
16179 bool StmtLineInvalid;
16180 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16181 &StmtLineInvalid);
16182 if (StmtLineInvalid)
16183 return false;
16184
16185 bool BodyLineInvalid;
16186 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16187 &BodyLineInvalid);
16188 if (BodyLineInvalid)
16189 return false;
16190
16191 // Warn if null statement and body are on the same line.
16192 if (StmtLine != BodyLine)
16193 return false;
16194
16195 return true;
16196}
16197
16199 const Stmt *Body,
16200 unsigned DiagID) {
16201 // Since this is a syntactic check, don't emit diagnostic for template
16202 // instantiations, this just adds noise.
16204 return;
16205
16206 // The body should be a null statement.
16207 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16208 if (!NBody)
16209 return;
16210
16211 // Do the usual checks.
16212 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16213 return;
16214
16215 Diag(NBody->getSemiLoc(), DiagID);
16216 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16217}
16218
16220 const Stmt *PossibleBody) {
16221 assert(!CurrentInstantiationScope); // Ensured by caller
16222
16223 SourceLocation StmtLoc;
16224 const Stmt *Body;
16225 unsigned DiagID;
16226 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16227 StmtLoc = FS->getRParenLoc();
16228 Body = FS->getBody();
16229 DiagID = diag::warn_empty_for_body;
16230 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16231 StmtLoc = WS->getRParenLoc();
16232 Body = WS->getBody();
16233 DiagID = diag::warn_empty_while_body;
16234 } else
16235 return; // Neither `for' nor `while'.
16236
16237 // The body should be a null statement.
16238 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16239 if (!NBody)
16240 return;
16241
16242 // Skip expensive checks if diagnostic is disabled.
16243 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16244 return;
16245
16246 // Do the usual checks.
16247 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16248 return;
16249
16250 // `for(...);' and `while(...);' are popular idioms, so in order to keep
16251 // noise level low, emit diagnostics only if for/while is followed by a
16252 // CompoundStmt, e.g.:
16253 // for (int i = 0; i < n; i++);
16254 // {
16255 // a(i);
16256 // }
16257 // or if for/while is followed by a statement with more indentation
16258 // than for/while itself:
16259 // for (int i = 0; i < n; i++);
16260 // a(i);
16261 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16262 if (!ProbableTypo) {
16263 bool BodyColInvalid;
16264 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16265 PossibleBody->getBeginLoc(), &BodyColInvalid);
16266 if (BodyColInvalid)
16267 return;
16268
16269 bool StmtColInvalid;
16270 unsigned StmtCol =
16271 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16272 if (StmtColInvalid)
16273 return;
16274
16275 if (BodyCol > StmtCol)
16276 ProbableTypo = true;
16277 }
16278
16279 if (ProbableTypo) {
16280 Diag(NBody->getSemiLoc(), DiagID);
16281 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16282 }
16283}
16284
16285//===--- CHECK: Warn on self move with std::move. -------------------------===//
16286
16287void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16288 SourceLocation OpLoc) {
16289 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16290 return;
16291
16293 return;
16294
16295 // Strip parens and casts away.
16296 LHSExpr = LHSExpr->IgnoreParenImpCasts();
16297 RHSExpr = RHSExpr->IgnoreParenImpCasts();
16298
16299 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
16300 // which we can treat as an inlined std::move
16301 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
16302 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
16303 RHSExpr = CE->getArg(0);
16304 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
16305 CXXSCE && CXXSCE->isXValue())
16306 RHSExpr = CXXSCE->getSubExpr();
16307 else
16308 return;
16309
16310 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16311 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16312
16313 // Two DeclRefExpr's, check that the decls are the same.
16314 if (LHSDeclRef && RHSDeclRef) {
16315 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16316 return;
16317 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16318 RHSDeclRef->getDecl()->getCanonicalDecl())
16319 return;
16320
16321 auto D = Diag(OpLoc, diag::warn_self_move)
16322 << LHSExpr->getType() << LHSExpr->getSourceRange()
16323 << RHSExpr->getSourceRange();
16324 if (const FieldDecl *F =
16326 D << 1 << F
16327 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
16328 else
16329 D << 0;
16330 return;
16331 }
16332
16333 // Member variables require a different approach to check for self moves.
16334 // MemberExpr's are the same if every nested MemberExpr refers to the same
16335 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16336 // the base Expr's are CXXThisExpr's.
16337 const Expr *LHSBase = LHSExpr;
16338 const Expr *RHSBase = RHSExpr;
16339 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16340 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16341 if (!LHSME || !RHSME)
16342 return;
16343
16344 while (LHSME && RHSME) {
16345 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16346 RHSME->getMemberDecl()->getCanonicalDecl())
16347 return;
16348
16349 LHSBase = LHSME->getBase();
16350 RHSBase = RHSME->getBase();
16351 LHSME = dyn_cast<MemberExpr>(LHSBase);
16352 RHSME = dyn_cast<MemberExpr>(RHSBase);
16353 }
16354
16355 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16356 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16357 if (LHSDeclRef && RHSDeclRef) {
16358 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16359 return;
16360 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16361 RHSDeclRef->getDecl()->getCanonicalDecl())
16362 return;
16363
16364 Diag(OpLoc, diag::warn_self_move)
16365 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16366 << RHSExpr->getSourceRange();
16367 return;
16368 }
16369
16370 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16371 Diag(OpLoc, diag::warn_self_move)
16372 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16373 << RHSExpr->getSourceRange();
16374}
16375
16376//===--- Layout compatibility ----------------------------------------------//
16377
16378static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16379
16380/// Check if two enumeration types are layout-compatible.
16381static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16382 const EnumDecl *ED2) {
16383 // C++11 [dcl.enum] p8:
16384 // Two enumeration types are layout-compatible if they have the same
16385 // underlying type.
16386 return ED1->isComplete() && ED2->isComplete() &&
16387 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16388}
16389
16390/// Check if two fields are layout-compatible.
16391/// Can be used on union members, which are exempt from alignment requirement
16392/// of common initial sequence.
16393static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16394 const FieldDecl *Field2,
16395 bool AreUnionMembers = false) {
16396#ifndef NDEBUG
16397 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16398 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16399 assert(((Field1Parent->isStructureOrClassType() &&
16400 Field2Parent->isStructureOrClassType()) ||
16401 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16402 "Can't evaluate layout compatibility between a struct field and a "
16403 "union field.");
16404 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16405 (AreUnionMembers && Field1Parent->isUnionType())) &&
16406 "AreUnionMembers should be 'true' for union fields (only).");
16407#endif
16408
16409 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16410 return false;
16411
16412 if (Field1->isBitField() != Field2->isBitField())
16413 return false;
16414
16415 if (Field1->isBitField()) {
16416 // Make sure that the bit-fields are the same length.
16417 unsigned Bits1 = Field1->getBitWidthValue();
16418 unsigned Bits2 = Field2->getBitWidthValue();
16419
16420 if (Bits1 != Bits2)
16421 return false;
16422 }
16423
16424 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16425 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16426 return false;
16427
16428 if (!AreUnionMembers &&
16429 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16430 return false;
16431
16432 return true;
16433}
16434
16435/// Check if two standard-layout structs are layout-compatible.
16436/// (C++11 [class.mem] p17)
16437static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16438 const RecordDecl *RD2) {
16439 // Get to the class where the fields are declared
16440 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
16441 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16442
16443 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
16444 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16445
16446 // Check the fields.
16447 return llvm::equal(RD1->fields(), RD2->fields(),
16448 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16449 return isLayoutCompatible(C, F1, F2);
16450 });
16451}
16452
16453/// Check if two standard-layout unions are layout-compatible.
16454/// (C++11 [class.mem] p18)
16455static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16456 const RecordDecl *RD2) {
16457 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16458 RD2->fields());
16459
16460 for (auto *Field1 : RD1->fields()) {
16461 auto I = UnmatchedFields.begin();
16462 auto E = UnmatchedFields.end();
16463
16464 for ( ; I != E; ++I) {
16465 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
16466 bool Result = UnmatchedFields.erase(*I);
16467 (void) Result;
16468 assert(Result);
16469 break;
16470 }
16471 }
16472 if (I == E)
16473 return false;
16474 }
16475
16476 return UnmatchedFields.empty();
16477}
16478
16479static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16480 const RecordDecl *RD2) {
16481 if (RD1->isUnion() != RD2->isUnion())
16482 return false;
16483
16484 if (RD1->isUnion())
16485 return isLayoutCompatibleUnion(C, RD1, RD2);
16486 else
16487 return isLayoutCompatibleStruct(C, RD1, RD2);
16488}
16489
16490/// Check if two types are layout-compatible in C++11 sense.
16491static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16492 if (T1.isNull() || T2.isNull())
16493 return false;
16494
16495 // C++20 [basic.types] p11:
16496 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16497 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16498 // or layout-compatible standard-layout class types (11.4).
16501
16502 if (C.hasSameType(T1, T2))
16503 return true;
16504
16505 const Type::TypeClass TC1 = T1->getTypeClass();
16506 const Type::TypeClass TC2 = T2->getTypeClass();
16507
16508 if (TC1 != TC2)
16509 return false;
16510
16511 if (TC1 == Type::Enum)
16512 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
16513 if (TC1 == Type::Record) {
16514 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16515 return false;
16516
16518 T2->castAsRecordDecl());
16519 }
16520
16521 return false;
16522}
16523
16525 return isLayoutCompatible(getASTContext(), T1, T2);
16526}
16527
16528//===-------------- Pointer interconvertibility ----------------------------//
16529
16531 const TypeSourceInfo *Derived) {
16532 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16533 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16534
16535 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16536 getASTContext().hasSameType(BaseT, DerivedT))
16537 return true;
16538
16539 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
16540 return false;
16541
16542 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16543 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16544 return true;
16545
16546 return false;
16547}
16548
16549//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16550
16551/// Given a type tag expression find the type tag itself.
16552///
16553/// \param TypeExpr Type tag expression, as it appears in user's code.
16554///
16555/// \param VD Declaration of an identifier that appears in a type tag.
16556///
16557/// \param MagicValue Type tag magic value.
16558///
16559/// \param isConstantEvaluated whether the evalaution should be performed in
16560
16561/// constant context.
16562static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16563 const ValueDecl **VD, uint64_t *MagicValue,
16564 bool isConstantEvaluated) {
16565 while(true) {
16566 if (!TypeExpr)
16567 return false;
16568
16569 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16570
16571 switch (TypeExpr->getStmtClass()) {
16572 case Stmt::UnaryOperatorClass: {
16573 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16574 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16575 TypeExpr = UO->getSubExpr();
16576 continue;
16577 }
16578 return false;
16579 }
16580
16581 case Stmt::DeclRefExprClass: {
16582 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16583 *VD = DRE->getDecl();
16584 return true;
16585 }
16586
16587 case Stmt::IntegerLiteralClass: {
16588 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16589 llvm::APInt MagicValueAPInt = IL->getValue();
16590 if (MagicValueAPInt.getActiveBits() <= 64) {
16591 *MagicValue = MagicValueAPInt.getZExtValue();
16592 return true;
16593 } else
16594 return false;
16595 }
16596
16597 case Stmt::BinaryConditionalOperatorClass:
16598 case Stmt::ConditionalOperatorClass: {
16599 const AbstractConditionalOperator *ACO =
16601 bool Result;
16602 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16603 isConstantEvaluated)) {
16604 if (Result)
16605 TypeExpr = ACO->getTrueExpr();
16606 else
16607 TypeExpr = ACO->getFalseExpr();
16608 continue;
16609 }
16610 return false;
16611 }
16612
16613 case Stmt::BinaryOperatorClass: {
16614 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16615 if (BO->getOpcode() == BO_Comma) {
16616 TypeExpr = BO->getRHS();
16617 continue;
16618 }
16619 return false;
16620 }
16621
16622 default:
16623 return false;
16624 }
16625 }
16626}
16627
16628/// Retrieve the C type corresponding to type tag TypeExpr.
16629///
16630/// \param TypeExpr Expression that specifies a type tag.
16631///
16632/// \param MagicValues Registered magic values.
16633///
16634/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16635/// kind.
16636///
16637/// \param TypeInfo Information about the corresponding C type.
16638///
16639/// \param isConstantEvaluated whether the evalaution should be performed in
16640/// constant context.
16641///
16642/// \returns true if the corresponding C type was found.
16644 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16645 const ASTContext &Ctx,
16646 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16647 *MagicValues,
16648 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16649 bool isConstantEvaluated) {
16650 FoundWrongKind = false;
16651
16652 // Variable declaration that has type_tag_for_datatype attribute.
16653 const ValueDecl *VD = nullptr;
16654
16655 uint64_t MagicValue;
16656
16657 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16658 return false;
16659
16660 if (VD) {
16661 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16662 if (I->getArgumentKind() != ArgumentKind) {
16663 FoundWrongKind = true;
16664 return false;
16665 }
16666 TypeInfo.Type = I->getMatchingCType();
16667 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16668 TypeInfo.MustBeNull = I->getMustBeNull();
16669 return true;
16670 }
16671 return false;
16672 }
16673
16674 if (!MagicValues)
16675 return false;
16676
16677 llvm::DenseMap<Sema::TypeTagMagicValue,
16679 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16680 if (I == MagicValues->end())
16681 return false;
16682
16683 TypeInfo = I->second;
16684 return true;
16685}
16686
16688 uint64_t MagicValue, QualType Type,
16689 bool LayoutCompatible,
16690 bool MustBeNull) {
16691 if (!TypeTagForDatatypeMagicValues)
16692 TypeTagForDatatypeMagicValues.reset(
16693 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16694
16695 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16696 (*TypeTagForDatatypeMagicValues)[Magic] =
16697 TypeTagData(Type, LayoutCompatible, MustBeNull);
16698}
16699
16700static bool IsSameCharType(QualType T1, QualType T2) {
16701 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16702 if (!BT1)
16703 return false;
16704
16705 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16706 if (!BT2)
16707 return false;
16708
16709 BuiltinType::Kind T1Kind = BT1->getKind();
16710 BuiltinType::Kind T2Kind = BT2->getKind();
16711
16712 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16713 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16714 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16715 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16716}
16717
16718void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16719 const ArrayRef<const Expr *> ExprArgs,
16720 SourceLocation CallSiteLoc) {
16721 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16722 bool IsPointerAttr = Attr->getIsPointer();
16723
16724 // Retrieve the argument representing the 'type_tag'.
16725 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16726 if (TypeTagIdxAST >= ExprArgs.size()) {
16727 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16728 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16729 return;
16730 }
16731 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16732 bool FoundWrongKind;
16733 TypeTagData TypeInfo;
16734 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16735 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16736 TypeInfo, isConstantEvaluatedContext())) {
16737 if (FoundWrongKind)
16738 Diag(TypeTagExpr->getExprLoc(),
16739 diag::warn_type_tag_for_datatype_wrong_kind)
16740 << TypeTagExpr->getSourceRange();
16741 return;
16742 }
16743
16744 // Retrieve the argument representing the 'arg_idx'.
16745 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16746 if (ArgumentIdxAST >= ExprArgs.size()) {
16747 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16748 << 1 << Attr->getArgumentIdx().getSourceIndex();
16749 return;
16750 }
16751 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16752 if (IsPointerAttr) {
16753 // Skip implicit cast of pointer to `void *' (as a function argument).
16754 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16755 if (ICE->getType()->isVoidPointerType() &&
16756 ICE->getCastKind() == CK_BitCast)
16757 ArgumentExpr = ICE->getSubExpr();
16758 }
16759 QualType ArgumentType = ArgumentExpr->getType();
16760
16761 // Passing a `void*' pointer shouldn't trigger a warning.
16762 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16763 return;
16764
16765 if (TypeInfo.MustBeNull) {
16766 // Type tag with matching void type requires a null pointer.
16767 if (!ArgumentExpr->isNullPointerConstant(Context,
16769 Diag(ArgumentExpr->getExprLoc(),
16770 diag::warn_type_safety_null_pointer_required)
16771 << ArgumentKind->getName()
16772 << ArgumentExpr->getSourceRange()
16773 << TypeTagExpr->getSourceRange();
16774 }
16775 return;
16776 }
16777
16778 QualType RequiredType = TypeInfo.Type;
16779 if (IsPointerAttr)
16780 RequiredType = Context.getPointerType(RequiredType);
16781
16782 bool mismatch = false;
16783 if (!TypeInfo.LayoutCompatible) {
16784 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16785
16786 // C++11 [basic.fundamental] p1:
16787 // Plain char, signed char, and unsigned char are three distinct types.
16788 //
16789 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16790 // char' depending on the current char signedness mode.
16791 if (mismatch)
16792 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16793 RequiredType->getPointeeType())) ||
16794 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16795 mismatch = false;
16796 } else
16797 if (IsPointerAttr)
16798 mismatch = !isLayoutCompatible(Context,
16799 ArgumentType->getPointeeType(),
16800 RequiredType->getPointeeType());
16801 else
16802 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16803
16804 if (mismatch)
16805 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16806 << ArgumentType << ArgumentKind
16807 << TypeInfo.LayoutCompatible << RequiredType
16808 << ArgumentExpr->getSourceRange()
16809 << TypeTagExpr->getSourceRange();
16810}
16811
16812void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16813 CharUnits Alignment) {
16814 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
16815 Alignment);
16816}
16817
16819 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16820 const NamedDecl *ND = m.RD;
16821 if (ND->getName().empty()) {
16822 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16823 ND = TD;
16824 }
16825 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16826 << m.MD << ND << m.E->getSourceRange();
16827 }
16829}
16830
16832 E = E->IgnoreParens();
16833 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16834 return;
16835 if (isa<UnaryOperator>(E) &&
16836 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16837 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16838 if (isa<MemberExpr>(Op)) {
16839 auto &MisalignedMembersForExpr =
16841 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
16842 if (MA != MisalignedMembersForExpr.end() &&
16843 (T->isDependentType() || T->isIntegerType() ||
16844 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16845 Context.getTypeAlignInChars(
16846 T->getPointeeType()) <= MA->Alignment))))
16847 MisalignedMembersForExpr.erase(MA);
16848 }
16849 }
16850}
16851
16853 Expr *E,
16854 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16855 Action) {
16856 const auto *ME = dyn_cast<MemberExpr>(E);
16857 if (!ME)
16858 return;
16859
16860 // No need to check expressions with an __unaligned-qualified type.
16861 if (E->getType().getQualifiers().hasUnaligned())
16862 return;
16863
16864 // For a chain of MemberExpr like "a.b.c.d" this list
16865 // will keep FieldDecl's like [d, c, b].
16866 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16867 const MemberExpr *TopME = nullptr;
16868 bool AnyIsPacked = false;
16869 do {
16870 QualType BaseType = ME->getBase()->getType();
16871 if (BaseType->isDependentType())
16872 return;
16873 if (ME->isArrow())
16874 BaseType = BaseType->getPointeeType();
16875 auto *RD = BaseType->castAsRecordDecl();
16876 if (RD->isInvalidDecl())
16877 return;
16878
16879 ValueDecl *MD = ME->getMemberDecl();
16880 auto *FD = dyn_cast<FieldDecl>(MD);
16881 // We do not care about non-data members.
16882 if (!FD || FD->isInvalidDecl())
16883 return;
16884
16885 AnyIsPacked =
16886 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16887 ReverseMemberChain.push_back(FD);
16888
16889 TopME = ME;
16890 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16891 } while (ME);
16892 assert(TopME && "We did not compute a topmost MemberExpr!");
16893
16894 // Not the scope of this diagnostic.
16895 if (!AnyIsPacked)
16896 return;
16897
16898 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16899 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16900 // TODO: The innermost base of the member expression may be too complicated.
16901 // For now, just disregard these cases. This is left for future
16902 // improvement.
16903 if (!DRE && !isa<CXXThisExpr>(TopBase))
16904 return;
16905
16906 // Alignment expected by the whole expression.
16907 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16908
16909 // No need to do anything else with this case.
16910 if (ExpectedAlignment.isOne())
16911 return;
16912
16913 // Synthesize offset of the whole access.
16914 CharUnits Offset;
16915 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16916 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16917
16918 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16919 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16920 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
16921
16922 // The base expression of the innermost MemberExpr may give
16923 // stronger guarantees than the class containing the member.
16924 if (DRE && !TopME->isArrow()) {
16925 const ValueDecl *VD = DRE->getDecl();
16926 if (!VD->getType()->isReferenceType())
16927 CompleteObjectAlignment =
16928 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16929 }
16930
16931 // Check if the synthesized offset fulfills the alignment.
16932 if (!Offset.isMultipleOf(ExpectedAlignment) ||
16933 // It may fulfill the offset it but the effective alignment may still be
16934 // lower than the expected expression alignment.
16935 CompleteObjectAlignment < ExpectedAlignment) {
16936 // If this happens, we want to determine a sensible culprit of this.
16937 // Intuitively, watching the chain of member expressions from right to
16938 // left, we start with the required alignment (as required by the field
16939 // type) but some packed attribute in that chain has reduced the alignment.
16940 // It may happen that another packed structure increases it again. But if
16941 // we are here such increase has not been enough. So pointing the first
16942 // FieldDecl that either is packed or else its RecordDecl is,
16943 // seems reasonable.
16944 FieldDecl *FD = nullptr;
16945 CharUnits Alignment;
16946 for (FieldDecl *FDI : ReverseMemberChain) {
16947 if (FDI->hasAttr<PackedAttr>() ||
16948 FDI->getParent()->hasAttr<PackedAttr>()) {
16949 FD = FDI;
16950 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
16951 Context.getTypeAlignInChars(
16952 Context.getCanonicalTagType(FD->getParent())));
16953 break;
16954 }
16955 }
16956 assert(FD && "We did not find a packed FieldDecl!");
16957 Action(E, FD->getParent(), FD, Alignment);
16958 }
16959}
16960
16961void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16962 using namespace std::placeholders;
16963
16965 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16966 _2, _3, _4));
16967}
16968
16970 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16971 if (checkArgCount(TheCall, 1))
16972 return true;
16973
16974 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
16975 if (A.isInvalid())
16976 return true;
16977
16978 TheCall->setArg(0, A.get());
16979 QualType TyA = A.get()->getType();
16980
16981 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
16982 ArgTyRestr, 1))
16983 return true;
16984
16985 TheCall->setType(TyA);
16986 return false;
16987}
16988
16989bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
16990 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16991 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
16992 TheCall->setType(*Res);
16993 return false;
16994 }
16995 return true;
16996}
16997
16999 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
17000 if (!Res)
17001 return true;
17002
17003 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
17004 TheCall->setType(VecTy0->getElementType());
17005 else
17006 TheCall->setType(*Res);
17007
17008 return false;
17009}
17010
17012 SourceLocation Loc) {
17014 R = RHS->getEnumCoercedType(S.Context);
17015 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
17017 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
17018 << LHS->getSourceRange() << RHS->getSourceRange()
17019 << /*Arithmetic Between*/ 0 << L << R;
17020 }
17021 return false;
17022}
17023
17024/// Check if all arguments have the same type. If the types don't match, emit an
17025/// error message and return true. Otherwise return false.
17026///
17027/// For scalars we directly compare their unqualified types. But even if we
17028/// compare unqualified vector types, a difference in qualifiers in the element
17029/// types can make the vector types be considered not equal. For example,
17030/// vector of 4 'const float' values vs vector of 4 'float' values.
17031/// So we compare unqualified types of their elements and number of elements.
17033 ArrayRef<Expr *> Args) {
17034 assert(!Args.empty() && "Should have at least one argument.");
17035
17036 Expr *Arg0 = Args.front();
17037 QualType Ty0 = Arg0->getType();
17038
17039 auto EmitError = [&](Expr *ArgI) {
17040 SemaRef.Diag(Arg0->getBeginLoc(),
17041 diag::err_typecheck_call_different_arg_types)
17042 << Arg0->getType() << ArgI->getType();
17043 };
17044
17045 // Compare scalar types.
17046 if (!Ty0->isVectorType()) {
17047 for (Expr *ArgI : Args.drop_front())
17048 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
17049 EmitError(ArgI);
17050 return true;
17051 }
17052
17053 return false;
17054 }
17055
17056 // Compare vector types.
17057 const auto *Vec0 = Ty0->castAs<VectorType>();
17058 for (Expr *ArgI : Args.drop_front()) {
17059 const auto *VecI = ArgI->getType()->getAs<VectorType>();
17060 if (!VecI ||
17061 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
17062 VecI->getElementType()) ||
17063 Vec0->getNumElements() != VecI->getNumElements()) {
17064 EmitError(ArgI);
17065 return true;
17066 }
17067 }
17068
17069 return false;
17070}
17071
17072std::optional<QualType>
17074 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17075 if (checkArgCount(TheCall, 2))
17076 return std::nullopt;
17077
17079 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
17080 return std::nullopt;
17081
17082 Expr *Args[2];
17083 for (int I = 0; I < 2; ++I) {
17084 ExprResult Converted =
17085 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
17086 if (Converted.isInvalid())
17087 return std::nullopt;
17088 Args[I] = Converted.get();
17089 }
17090
17091 SourceLocation LocA = Args[0]->getBeginLoc();
17092 QualType TyA = Args[0]->getType();
17093
17094 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
17095 return std::nullopt;
17096
17097 if (checkBuiltinVectorMathArgTypes(*this, Args))
17098 return std::nullopt;
17099
17100 TheCall->setArg(0, Args[0]);
17101 TheCall->setArg(1, Args[1]);
17102 return TyA;
17103}
17104
17106 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17107 if (checkArgCount(TheCall, 3))
17108 return true;
17109
17110 SourceLocation Loc = TheCall->getExprLoc();
17111 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
17112 TheCall->getArg(1), Loc) ||
17113 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
17114 TheCall->getArg(2), Loc))
17115 return true;
17116
17117 Expr *Args[3];
17118 for (int I = 0; I < 3; ++I) {
17119 ExprResult Converted =
17120 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
17121 if (Converted.isInvalid())
17122 return true;
17123 Args[I] = Converted.get();
17124 }
17125
17126 int ArgOrdinal = 1;
17127 for (Expr *Arg : Args) {
17128 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
17129 ArgTyRestr, ArgOrdinal++))
17130 return true;
17131 }
17132
17133 if (checkBuiltinVectorMathArgTypes(*this, Args))
17134 return true;
17135
17136 for (int I = 0; I < 3; ++I)
17137 TheCall->setArg(I, Args[I]);
17138
17139 TheCall->setType(Args[0]->getType());
17140 return false;
17141}
17142
17143bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17144 if (checkArgCount(TheCall, 1))
17145 return true;
17146
17147 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17148 if (A.isInvalid())
17149 return true;
17150
17151 TheCall->setArg(0, A.get());
17152 return false;
17153}
17154
17155bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
17156 if (checkArgCount(TheCall, 1))
17157 return true;
17158
17159 ExprResult Arg = TheCall->getArg(0);
17160 QualType TyArg = Arg.get()->getType();
17161
17162 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
17163 return Diag(TheCall->getArg(0)->getBeginLoc(),
17164 diag::err_builtin_invalid_arg_type)
17165 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
17166
17167 TheCall->setType(TyArg);
17168 return false;
17169}
17170
17171ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
17172 ExprResult CallResult) {
17173 if (checkArgCount(TheCall, 1))
17174 return ExprError();
17175
17176 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17177 if (MatrixArg.isInvalid())
17178 return MatrixArg;
17179 Expr *Matrix = MatrixArg.get();
17180
17181 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17182 if (!MType) {
17183 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17184 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
17185 << Matrix->getType();
17186 return ExprError();
17187 }
17188
17189 // Create returned matrix type by swapping rows and columns of the argument
17190 // matrix type.
17191 QualType ResultType = Context.getConstantMatrixType(
17192 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17193
17194 // Change the return type to the type of the returned matrix.
17195 TheCall->setType(ResultType);
17196
17197 // Update call argument to use the possibly converted matrix argument.
17198 TheCall->setArg(0, Matrix);
17199 return CallResult;
17200}
17201
17202// Get and verify the matrix dimensions.
17203static std::optional<unsigned>
17205 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
17206 if (!Value) {
17207 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17208 << Name;
17209 return {};
17210 }
17211 uint64_t Dim = Value->getZExtValue();
17212 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
17213 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17214 << Name << S.Context.getLangOpts().MaxMatrixDimension;
17215 return {};
17216 }
17217 return Dim;
17218}
17219
17220ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17221 ExprResult CallResult) {
17222 if (!getLangOpts().MatrixTypes) {
17223 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17224 return ExprError();
17225 }
17226
17227 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17229 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17230 << /*column*/ 1 << /*load*/ 0;
17231 return ExprError();
17232 }
17233
17234 if (checkArgCount(TheCall, 4))
17235 return ExprError();
17236
17237 unsigned PtrArgIdx = 0;
17238 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17239 Expr *RowsExpr = TheCall->getArg(1);
17240 Expr *ColumnsExpr = TheCall->getArg(2);
17241 Expr *StrideExpr = TheCall->getArg(3);
17242
17243 bool ArgError = false;
17244
17245 // Check pointer argument.
17246 {
17248 if (PtrConv.isInvalid())
17249 return PtrConv;
17250 PtrExpr = PtrConv.get();
17251 TheCall->setArg(0, PtrExpr);
17252 if (PtrExpr->isTypeDependent()) {
17253 TheCall->setType(Context.DependentTy);
17254 return TheCall;
17255 }
17256 }
17257
17258 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17259 QualType ElementTy;
17260 if (!PtrTy) {
17261 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17262 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
17263 << PtrExpr->getType();
17264 ArgError = true;
17265 } else {
17266 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17267
17269 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17270 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
17271 << /* no fp */ 0 << PtrExpr->getType();
17272 ArgError = true;
17273 }
17274 }
17275
17276 // Apply default Lvalue conversions and convert the expression to size_t.
17277 auto ApplyArgumentConversions = [this](Expr *E) {
17279 if (Conv.isInvalid())
17280 return Conv;
17281
17282 return tryConvertExprToType(Conv.get(), Context.getSizeType());
17283 };
17284
17285 // Apply conversion to row and column expressions.
17286 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17287 if (!RowsConv.isInvalid()) {
17288 RowsExpr = RowsConv.get();
17289 TheCall->setArg(1, RowsExpr);
17290 } else
17291 RowsExpr = nullptr;
17292
17293 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17294 if (!ColumnsConv.isInvalid()) {
17295 ColumnsExpr = ColumnsConv.get();
17296 TheCall->setArg(2, ColumnsExpr);
17297 } else
17298 ColumnsExpr = nullptr;
17299
17300 // If any part of the result matrix type is still pending, just use
17301 // Context.DependentTy, until all parts are resolved.
17302 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17303 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17304 TheCall->setType(Context.DependentTy);
17305 return CallResult;
17306 }
17307
17308 // Check row and column dimensions.
17309 std::optional<unsigned> MaybeRows;
17310 if (RowsExpr)
17311 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17312
17313 std::optional<unsigned> MaybeColumns;
17314 if (ColumnsExpr)
17315 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17316
17317 // Check stride argument.
17318 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17319 if (StrideConv.isInvalid())
17320 return ExprError();
17321 StrideExpr = StrideConv.get();
17322 TheCall->setArg(3, StrideExpr);
17323
17324 if (MaybeRows) {
17325 if (std::optional<llvm::APSInt> Value =
17326 StrideExpr->getIntegerConstantExpr(Context)) {
17327 uint64_t Stride = Value->getZExtValue();
17328 if (Stride < *MaybeRows) {
17329 Diag(StrideExpr->getBeginLoc(),
17330 diag::err_builtin_matrix_stride_too_small);
17331 ArgError = true;
17332 }
17333 }
17334 }
17335
17336 if (ArgError || !MaybeRows || !MaybeColumns)
17337 return ExprError();
17338
17339 TheCall->setType(
17340 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17341 return CallResult;
17342}
17343
17344ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17345 ExprResult CallResult) {
17346 if (!getLangOpts().MatrixTypes) {
17347 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17348 return ExprError();
17349 }
17350
17351 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17353 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17354 << /*column*/ 1 << /*store*/ 1;
17355 return ExprError();
17356 }
17357
17358 if (checkArgCount(TheCall, 3))
17359 return ExprError();
17360
17361 unsigned PtrArgIdx = 1;
17362 Expr *MatrixExpr = TheCall->getArg(0);
17363 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17364 Expr *StrideExpr = TheCall->getArg(2);
17365
17366 bool ArgError = false;
17367
17368 {
17369 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17370 if (MatrixConv.isInvalid())
17371 return MatrixConv;
17372 MatrixExpr = MatrixConv.get();
17373 TheCall->setArg(0, MatrixExpr);
17374 }
17375 if (MatrixExpr->isTypeDependent()) {
17376 TheCall->setType(Context.DependentTy);
17377 return TheCall;
17378 }
17379
17380 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17381 if (!MatrixTy) {
17382 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17383 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17384 ArgError = true;
17385 }
17386
17387 {
17389 if (PtrConv.isInvalid())
17390 return PtrConv;
17391 PtrExpr = PtrConv.get();
17392 TheCall->setArg(1, PtrExpr);
17393 if (PtrExpr->isTypeDependent()) {
17394 TheCall->setType(Context.DependentTy);
17395 return TheCall;
17396 }
17397 }
17398
17399 // Check pointer argument.
17400 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17401 if (!PtrTy) {
17402 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17403 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17404 << PtrExpr->getType();
17405 ArgError = true;
17406 } else {
17407 QualType ElementTy = PtrTy->getPointeeType();
17408 if (ElementTy.isConstQualified()) {
17409 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17410 ArgError = true;
17411 }
17412 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17413 if (MatrixTy &&
17414 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17415 Diag(PtrExpr->getBeginLoc(),
17416 diag::err_builtin_matrix_pointer_arg_mismatch)
17417 << ElementTy << MatrixTy->getElementType();
17418 ArgError = true;
17419 }
17420 }
17421
17422 // Apply default Lvalue conversions and convert the stride expression to
17423 // size_t.
17424 {
17425 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17426 if (StrideConv.isInvalid())
17427 return StrideConv;
17428
17429 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17430 if (StrideConv.isInvalid())
17431 return StrideConv;
17432 StrideExpr = StrideConv.get();
17433 TheCall->setArg(2, StrideExpr);
17434 }
17435
17436 // Check stride argument.
17437 if (MatrixTy) {
17438 if (std::optional<llvm::APSInt> Value =
17439 StrideExpr->getIntegerConstantExpr(Context)) {
17440 uint64_t Stride = Value->getZExtValue();
17441 if (Stride < MatrixTy->getNumRows()) {
17442 Diag(StrideExpr->getBeginLoc(),
17443 diag::err_builtin_matrix_stride_too_small);
17444 ArgError = true;
17445 }
17446 }
17447 }
17448
17449 if (ArgError)
17450 return ExprError();
17451
17452 return CallResult;
17453}
17454
17456 const NamedDecl *Callee) {
17457 // This warning does not make sense in code that has no runtime behavior.
17459 return;
17460
17461 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17462
17463 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17464 return;
17465
17466 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17467 // all TCBs the callee is a part of.
17468 llvm::StringSet<> CalleeTCBs;
17469 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17470 CalleeTCBs.insert(A->getTCBName());
17471 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17472 CalleeTCBs.insert(A->getTCBName());
17473
17474 // Go through the TCBs the caller is a part of and emit warnings if Caller
17475 // is in a TCB that the Callee is not.
17476 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17477 StringRef CallerTCB = A->getTCBName();
17478 if (CalleeTCBs.count(CallerTCB) == 0) {
17479 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17480 << Callee << CallerTCB;
17481 }
17482 }
17483}
Defines the clang::ASTContext interface.
#define V(N, I)
Provides definitions for the various language-specific address spaces.
Defines the Diagnostic-related interfaces.
static bool getTypeString(SmallStringEnc &Enc, const Decl *D, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC)
The XCore ABI includes a type information section that communicates symbol type information to the li...
Definition XCore.cpp:630
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
std::shared_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token's formatting.
unsigned IsFirst
Indicates that this is the first token of the file.
TokenType getType() const
Returns the token's type, e.g.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Result
Implement __builtin_bit_cast and related operations.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
#define SM(sm)
Defines the clang::OpenCLOptions class.
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
llvm::json::Object Object
llvm::json::Array Array
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis functions specific to BPF.
static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout unions are layout-compatible.
static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, const ValueDecl **VD, uint64_t *MagicValue, bool isConstantEvaluated)
Given a type tag expression find the type tag itself.
static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, SourceLocation CC, QualType T)
static QualType getSizeOfArgType(const Expr *E)
If E is a sizeof expression, returns its argument type.
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, SourceLocation CallSiteLoc)
static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind, bool RequireConstant=false)
static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall)
static const CXXRecordDecl * getContainedDynamicClass(QualType T, bool &IsContained)
Determine whether the given type is or contains a dynamic class type (e.g., whether it has a vtable).
static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call)
static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall)
static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call)
static bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType, QualType T)
static bool IsSameFloatAfterCast(const llvm::APFloat &value, const llvm::fltSemantics &Src, const llvm::fltSemantics &Tgt)
Checks whether the given value, which currently has the given source semantics, has the same value wh...
static void AnalyzeComparison(Sema &S, BinaryOperator *E)
Implements -Wsign-compare.
static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, BinaryOperatorKind BinOpKind, bool AddendIsRight)
static std::pair< QualType, StringRef > shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy, const Expr *E)
static QualType GetExprType(const Expr *E)
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx)
This helper function takes an lvalue expression and returns the alignment of a VarDecl and a constant...
static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, Expr *Other, const llvm::APSInt &Value, bool RhsConstant)
static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex, bool ToBool)
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, const IdentifierInfo *FnName, SourceLocation FnLoc, SourceLocation RParenLoc)
Takes the expression passed to the size_t parameter of functions such as memcmp, strncat,...
static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall)
static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_stdc_rotate_{left,right} was called with two arguments, that the first argument...
static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref, ArrayRef< EquatableFormatArgument > RefArgs, const StringLiteral *Fmt, ArrayRef< EquatableFormatArgument > FmtArgs, const Expr *FmtExpr, bool InFunctionCall)
static bool BuiltinBswapg(Sema &S, CallExpr *TheCall)
Checks that __builtin_bswapg was called with a single argument, which is an unsigned integer,...
static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall)
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op)
static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, Scope::ScopeFlags NeededScopeFlags, unsigned DiagID)
static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E)
Analyze the given compound assignment for the possible losing of floating-point precision.
static bool doesExprLikelyComputeSize(const Expr *SizeofExpr)
Detect if SizeofExpr is likely to calculate the sizeof an object.
static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, bool inFunctionCall, VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, bool IgnoreStringsWithoutSpecifiers)
static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall)
Check the number of arguments and set the result type to the argument type.
static bool CheckForReference(Sema &SemaRef, const Expr *E, const PartialDiagnostic &PD)
static const UnaryExprOrTypeTraitExpr * getAsSizeOfExpr(const Expr *E)
static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID)
Check that the value argument for __builtin_is_aligned(value, alignment) and __builtin_aligned_{up,...
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
static bool isKnownToHaveUnsignedValue(const Expr *E)
static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef, ArrayRef< Expr * > Args)
Check if all arguments have the same type.
static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call)
Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the last two arguments transpose...
static bool checkPointerAuthEnabled(Sema &S, Expr *E)
static std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range)
static ExprResult BuiltinMaskedStore(Sema &S, CallExpr *TheCall)
AbsoluteValueKind
@ AVK_Complex
@ AVK_Floating
@ AVK_Integer
static const Expr * getStrlenExprArg(const Expr *E)
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check)
static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall, const TargetInfo *AuxTI, unsigned BuiltinID)
BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
static bool isValidMathElementType(QualType T)
static void DiagnoseDeprecatedHIPAtomic(Sema &S, SourceRange ExprRange, MultiExprArg Args, AtomicExpr::AtomicOp Op)
Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_* equivalents.
static bool IsSameCharType(QualType T1, QualType T2)
static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E)
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall)
static bool isArgumentExpandedFromMacro(SourceManager &SM, SourceLocation CallLoc, SourceLocation ArgLoc)
Check if the ArgLoc originated from a macro passed to the call at CallLoc.
static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth)
static const IntegerLiteral * getIntegerLiteral(Expr *E)
#define HIP_ATOMIC_FIXABLE(hip, scoped)
static bool CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall, ArrayRef< llvm::Triple::ArchType > SupportedArchs)
static const Expr * maybeConstEvalStringLiteral(ASTContext &Context, const Expr *E)
static bool IsStdFunction(const FunctionDecl *FDecl, const char(&Str)[StrLen])
static void AnalyzeAssignment(Sema &S, BinaryOperator *E)
Analyze the given simple or compound assignment for warning-worthy operations.
static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_function_start is a function.
static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall)
static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, SourceLocation StmtLoc, const NullStmt *Body)
static std::pair< CharUnits, CharUnits > getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, CharUnits BaseAlignment, CharUnits Offset, ASTContext &Ctx)
Compute the alignment and offset of the base class object given the derived-to-base cast expression a...
static std::pair< const ValueDecl *, CharUnits > findConstantBaseAndOffset(Sema &S, Expr *E)
static QualType getVectorElementType(ASTContext &Context, QualType VecTy)
static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E)
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
static std::optional< IntRange > TryGetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, bool InConstantContext, bool Approximate)
Attempts to estimate an approximate range for the given integer expression.
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
static ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall)
static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall, SourceLocation CC)
static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall)
Checks that __builtin_bitreverseg was called with a single argument, which is an integer.
static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool &ICContext)
static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall)
static bool CheckMissingFormatAttribute(Sema *S, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, StringLiteral *ReferenceFormatString, unsigned FormatIdx, unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx, SourceLocation Loc)
static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call)
static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, SourceLocation InitLoc)
Analyzes an attempt to assign the given value to a bitfield.
static void CheckCommaOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool ExtraCheckForImplicitConversion, llvm::SmallVectorImpl< AnalyzeImplicitConversionsWorkItem > &WorkList)
static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T, SourceLocation CContext)
Diagnose an implicit cast from a floating point value to an integer value.
static int classifyConstantValue(Expr *Constant)
static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc)
static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, unsigned AbsKind, QualType ArgType)
static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2)
Check if two types are layout-compatible in C++11 sense.
static bool checkPointerAuthKey(Sema &S, Expr *&Arg)
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, Qualifiers::ObjCLifetime LT, Expr *RHS, bool isProperty)
static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID)
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl)
static llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool IsInfinityFunction(const FunctionDecl *FDecl)
static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType, QualType T, SourceLocation CContext, unsigned diag, bool PruneControlFlow=false)
Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr * > Args, SourceLocation CallSiteLoc)
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction)
static analyze_format_string::ArgType::MatchKind handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match, DiagnosticsEngine &Diags, SourceLocation Loc)
static bool referToTheSameDecl(const Expr *E1, const Expr *E2)
Check if two expressions refer to the same declaration.
static ExprResult BuiltinMaskedScatter(Sema &S, CallExpr *TheCall)
#define BUILTIN_ROW(x)
static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_{clzg,ctzg} was called with a first argument, which is an unsigned integer,...
static ExprResult GetVTablePointer(Sema &S, CallExpr *Call)
static bool requiresParensToAddCast(const Expr *E)
static bool HasEnumType(const Expr *E)
static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call)
static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall)
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
static StringLiteralCheckType checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString, const Expr *E, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset, std::optional< unsigned > *CallerFormatParamIdx=nullptr, bool IgnoreStringsWithoutSpecifiers=false)
static std::optional< unsigned > getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S)
static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty)
static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call)
static bool ProcessFormatStringLiteral(const Expr *FormatExpr, StringRef &FormatStrRef, size_t &StrLen, ASTContext &Context)
static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout structs are layout-compatible.
static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall)
Checks that __builtin_popcountg was called with a single argument, which is an unsigned integer.
static const Expr * getSizeOfExprArg(const Expr *E)
If E is a sizeof expression, returns its argument expression, otherwise returns NULL.
static void DiagnoseIntInBoolContext(Sema &S, Expr *E)
static bool CheckBuiltinTargetNotInUnsupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall, ArrayRef< llvm::Triple::ObjectFormatType > UnsupportedObjectFormatTypes)
static void DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source, const Type *Target, Expr *E, QualType T, SourceLocation CC)
static bool BuiltinAddressof(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_addressof is a glvalue, and set the result type to the correspon...
static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S)
static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg, unsigned Pos, bool AllowConst, bool AllowAS)
static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn)
Check that the user is calling the appropriate va_start builtin for the target and calling convention...
static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call, PointerAuthOpKind OpKind, bool RequireConstant)
static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S)
static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr, int ArgOrdinal)
static bool GetMatchingCType(const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, const ASTContext &Ctx, const llvm::DenseMap< Sema::TypeTagMagicValue, Sema::TypeTagData > *MagicValues, bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, bool isConstantEvaluated)
Retrieve the C type corresponding to type tag TypeExpr.
static QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall)
static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall)
static bool isNonNullType(QualType type)
Determine whether the given type has a non-null nullability annotation.
static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A, Sema::FormatArgumentPassingKind B)
static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall)
Check that the first argument to __builtin_annotation is an integer and the second argument is a non-...
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx)
This helper function takes a pointer expression and returns the alignment of a VarDecl and a constant...
static bool IsShiftedByte(llvm::APSInt Value)
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, unsigned AbsFunctionKind)
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
checkBuiltinArgument - Given a call to a builtin function, perform normal type-checking on the given ...
static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E)
Analyze the operands of the given comparison.
static ExprResult PointerAuthAuthLoadRelativeAndSign(Sema &S, CallExpr *Call)
static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall, QualType ReturnType)
Checks the __builtin_stdc_* builtins that take a single unsigned integer argument and return either i...
static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
static bool isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE)
Return true if ICE is an implicit argument promotion of an arithmetic type.
static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, bool IsListInit=false)
AnalyzeImplicitConversions - Find and report any interesting implicit conversions in the given expres...
static std::optional< std::pair< CharUnits, CharUnits > > getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, bool IsSub, ASTContext &Ctx)
Compute the alignment and offset of a binary additive operator.
static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
This file declares semantic analysis for DirectX constructs.
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis functions specific to Hexagon.
This file declares semantic analysis functions specific to LoongArch.
This file declares semantic analysis functions specific to MIPS.
This file declares semantic analysis functions specific to NVPTX.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis routines for OpenCL.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SPIRV constructs.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to SystemZ.
This file declares semantic analysis functions specific to Wasm.
This file declares semantic analysis functions specific to X86.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Provides definitions for the atomic synchronization scopes.
C Language Family Type Representation.
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
C Language Family Type Representation.
__DEVICE__ int min(int __a, int __b)
@ GE_None
No error.
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatch
The conversion specifier and the argument types are incompatible.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ MatchPromotion
The conversion specifier and the argument type are compatible because of default argument promotions.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
@ NoMatchTypeConfusion
The conversion specifier and the argument type are compatible, but still seems likely to be an error.
@ NoMatchPromotionTypeConfusion
The conversion specifier and the argument type are compatible but still seems likely to be an error.
unsigned getLength() const
const char * getStart() const
StringRef toString() const
const char * getStart() const
HowSpecified getHowSpecified() const
unsigned getConstantAmount() const
unsigned getConstantLength() const
bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx, bool IsObjCLiteral)
Changes the specifier and length according to a QualType, retaining any flags or options.
void toString(raw_ostream &os) const
Sema::SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when the only matching conversion function is explicit.
Sema::SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when the expression has incomplete class type.
Sema::SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for one of the candidate conversions.
Sema::SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when there are multiple possible conversion functions.
Sema::SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
Sema::SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
Sema::SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for the explicit conversion function.
bool match(QualType T) override
Determine whether the specified type is a valid destination type for this conversion.
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
void toString(raw_ostream &os) const
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
APSInt & getInt()
Definition APValue.h:508
bool isVector() const
Definition APValue.h:491
APSInt & getComplexIntImag()
Definition APValue.h:546
bool isComplexInt() const
Definition APValue.h:488
bool isFloat() const
Definition APValue.h:486
bool isComplexFloat() const
Definition APValue.h:489
APValue & getVectorElt(unsigned I)
Definition APValue.h:582
unsigned getVectorLength() const
Definition APValue.h:590
bool isLValue() const
Definition APValue.h:490
bool isInt() const
Definition APValue.h:485
APValue & getMatrixElt(unsigned Idx)
Definition APValue.h:606
APSInt & getComplexIntReal()
Definition APValue.h:538
APFloat & getComplexFloatImag()
Definition APValue.h:562
APFloat & getComplexFloatReal()
Definition APValue.h:554
APFloat & getFloat()
Definition APValue.h:522
bool isMatrix() const
Definition APValue.h:492
unsigned getMatrixNumElements() const
Definition APValue.h:603
bool isAddrLabelDiff() const
Definition APValue.h:497
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:805
Builtin::Context & BuiltinInfo
Definition ASTContext.h:807
const LangOptions & getLangOpts() const
Definition ASTContext.h:962
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType CharTy
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:858
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:924
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
@ GE_None
No error.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getNonVirtualAlignment() const
getNonVirtualAlignment - Get the non-virtual alignment (in chars) of an object, which is the alignmen...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4359
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4537
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4543
SourceLocation getQuestionLoc() const
Definition Expr.h:4386
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4549
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Expr * getBase()
Get base of the array section.
Definition Expr.h:7300
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7304
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2727
SourceLocation getRBracketLoc() const
Definition Expr.h:2775
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2756
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3786
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3800
QualType getElementType() const
Definition TypeBase.h:3798
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6931
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:7080
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:7062
Attr - This represents one attribute.
Definition Attr.h:46
const char * getSpelling() const
Type source information for an attributed type.
Definition TypeLoc.h:1008
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1022
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4177
Expr * getLHS() const
Definition Expr.h:4094
SourceLocation getOperatorLoc() const
Definition Expr.h:4086
SourceLocation getExprLoc() const
Definition Expr.h:4085
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2140
Expr * getRHS() const
Definition Expr.h:4096
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4130
Opcode getOpcode() const
Definition Expr.h:4089
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4141
BinaryOperatorKind Opcode
Definition Expr.h:4049
Pointer to a block type.
Definition TypeBase.h:3606
This class is used for builtin types like 'int'.
Definition TypeBase.h:3228
bool isInteger() const
Definition TypeBase.h:3289
bool isFloatingPoint() const
Definition TypeBase.h:3301
bool isSignedInteger() const
Definition TypeBase.h:3293
bool isUnsignedInteger() const
Definition TypeBase.h:3297
Kind getKind() const
Definition TypeBase.h:3276
std::string getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp: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:383
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:3975
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition ExprCXX.h:1634
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1692
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2968
Represents a C++ destructor within a class.
Definition DeclCXX.h:2898
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:85
SourceLocation getExprLoc() const LLVM_READONLY
Definition ExprCXX.h:158
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:115
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5141
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5181
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1230
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1219
bool isDynamicClass() const
Definition DeclCXX.h:574
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2949
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3153
SourceLocation getBeginLoc() const
Definition Expr.h:3283
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3166
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1598
arg_iterator arg_begin()
Definition Expr.h:3206
arg_iterator arg_end()
Definition Expr.h:3209
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3132
bool isCallToStdMove() const
Definition Expr.cpp:3651
Expr * getCallee()
Definition Expr.h:3096
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3140
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3242
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3143
arg_range arguments()
Definition Expr.h:3201
SourceLocation getEndLoc() const
Definition Expr.h:3302
SourceLocation getRParenLoc() const
Definition Expr.h:3280
Decl * getCalleeDecl()
Definition Expr.h:3126
bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const
Returns true if this is a call to a builtin which does not evaluate side-effects within its arguments...
Definition Expr.cpp:1603
void setCallee(Expr *F)
Definition Expr.h:3098
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition Expr.h:3185
QualType withConst() const
Retrieves a version of this type with const applied.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3682
path_iterator path_begin()
Definition Expr.h:3752
CastKind getCastKind() const
Definition Expr.h:3726
path_iterator path_end()
Definition Expr.h:3753
Expr * getSubExpr()
Definition Expr.h:3732
Represents a byte-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
bool isOne() const
isOne - Test whether the quantity equals one.
Definition CharUnits.h:125
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
ConditionalOperator - The ?
Definition Expr.h:4397
Expr * getLHS() const
Definition Expr.h:4431
Expr * getRHS() const
Definition Expr.h:4432
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3824
QualType desugar() const
Definition TypeBase.h:3925
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3880
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4451
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4473
static ConvertVectorExpr * Create(const ASTContext &C, Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType, ExprValueKind VK, ExprObjectKind OK, SourceLocation BuiltinLoc, SourceLocation RParenLoc, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5691
Expr * getOperand() const
Definition ExprCXX.h:5320
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool isStdNamespace() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2390
bool isFunctionOrMethod() const
Definition DeclBase.h:2178
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:494
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1369
ValueDecl * getDecl()
Definition Expr.h:1344
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1474
SourceLocation getBeginLoc() const
Definition Expr.h:1355
SourceLocation getLocation() const
Definition Expr.h:1352
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:450
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:443
T * getAttr() const
Definition DeclBase.h:581
void addAttr(Attr *A)
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:561
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
bool isInvalidDecl() const
Definition DeclBase.h:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:435
The name of a declaration.
std::string getAsString() const
Retrieve the human-readable string for this name.
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2003
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:234
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:961
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3458
Represents an enum.
Definition Decl.h:4046
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4278
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4219
This represents one expression.
Definition Expr.h:112
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3126
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:681
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition Expr.h:678
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3104
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3099
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3087
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3095
bool isFlexibleArrayMemberLike(const ASTContext &Context, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution=false) const
Check whether this array fits the idiom of a flexible array member, depending on the value of -fstric...
Definition Expr.cpp:212
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4238
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:837
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:841
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreCasts() LLVM_READONLY
Skip past any casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3083
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3091
std::optional< uint64_t > tryEvaluateStrLen(const ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3697
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3079
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:808
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:817
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:820
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:810
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4077
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:272
std::optional< uint64_t > tryEvaluateObjectSize(const ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:464
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:467
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
const ValueDecl * getAsBuiltinConstantDeclRef(const ASTContext &Context) const
If this expression is an unambiguous reference to a single declaration, in the style of __builtin_fun...
Definition Expr.cpp:232
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition Expr.cpp:138
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition TypeBase.h:4331
Represents a member of a struct/union/class.
Definition Decl.h:3195
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3298
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4749
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3431
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3311
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:81
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:142
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:131
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:105
llvm::APFloat getValue() const
Definition Expr.h:1672
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2898
Represents a function declaration or definition.
Definition Decl.h:2027
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4550
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2828
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3739
param_iterator param_end()
Definition Decl.h:2818
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3842
QualType getReturnType() const
Definition Decl.h:2876
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2805
param_iterator param_begin()
Definition Decl.h:2817
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3110
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4306
bool isStatic() const
Definition Decl.h:2960
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4121
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4107
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3803
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5371
unsigned getNumParams() const
Definition TypeBase.h:5649
QualType getParamType(unsigned i) const
Definition TypeBase.h:5651
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5775
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5660
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5770
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5656
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4567
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4876
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4872
QualType getReturnType() const
Definition TypeBase.h:4907
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3859
Describes an C or C++ initializer list.
Definition Expr.h:5305
ArrayRef< Expr * > inits() const
Definition Expr.h:5358
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:981
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition Lexer.cpp:1074
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1110
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition Lexer.cpp:508
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1157
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition Lexer.cpp:881
Represents the results of name lookup.
Definition Lookup.h:147
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4401
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4422
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
Expr * getBase() const
Definition Expr.h:3447
bool isArrow() const
Definition Expr.h:3554
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3717
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1207
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1943
Represent a C++ namespace.
Definition Decl.h:592
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition Stmt.h:1713
bool hasLeadingEmptyMacro() const
Definition Stmt.h:1727
SourceLocation getSemiLoc() const
Definition Stmt.h:1724
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
QualType getType() const
Definition DeclObjC.h:804
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition DeclObjC.h:827
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:815
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition ExprObjC.h:648
ObjCPropertyDecl * getExplicitProperty() const
Definition ExprObjC.h:737
bool isImplicitProperty() const
Definition ExprObjC.h:734
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:84
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2188
Represents a parameter to a function.
Definition Decl.h:1817
Pointer-authentication qualifiers.
Definition TypeBase.h:152
@ MaxDiscriminator
The maximum supported pointer-authentication discriminator.
Definition TypeBase.h:232
bool isAddressDiscriminated() const
Definition TypeBase.h:265
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
QualType getPointeeType() const
Definition TypeBase.h:3402
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6807
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5198
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8531
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2970
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1468
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1229
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8447
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8573
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8487
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1453
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition TypeBase.h:8499
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
void removeLocalVolatile()
Definition TypeBase.h:8563
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1194
void removeLocalConst()
Definition TypeBase.h:8555
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8520
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8568
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1719
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8493
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1347
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1457
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
bool hasUnaligned() const
Definition TypeBase.h:511
Represents a struct/union/class.
Definition Decl.h:4360
bool hasFlexibleArrayMember() const
Definition Decl.h:4393
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4446
field_range fields() const
Definition Decl.h:4563
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4438
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
bool isSEHExceptScope() const
Determine whether this scope is a SEH '__except' block.
Definition Scope.h:598
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
ScopeFlags
ScopeFlags - These are bitfields that are or'd together when creating a scope, which defines the sort...
Definition Scope.h:45
@ SEHFilterScope
We are currently in the filter expression of an SEH except block.
Definition Scope.h:131
@ SEHExceptScope
This scope corresponds to an SEH except.
Definition Scope.h:128
bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1034
@ ArmStreaming
Intrinsic is only available in normal mode.
Definition SemaARM.h:37
@ ArmStreamingCompatible
Intrinsic is only available in Streaming-SVE mode.
Definition SemaARM.h:38
bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1117
bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Definition SemaBPF.cpp:105
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
bool CheckDirectXBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaMIPS.cpp:25
bool CheckNVPTXBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaNVPTX.cpp:21
void checkArrayLiteral(QualType TargetType, ObjCArrayLiteral *ArrayLiteral)
Check an Objective-C array literal being converted to the given target type.
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
void adornBoolConversionDiagWithTernaryFixit(const Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder)
bool isSignedCharBool(QualType Ty)
void DiagnoseCStringFormatDirectiveInCFAPI(const NamedDecl *FDecl, Expr **Args, unsigned NumArgs)
Diagnose use of s directive in an NSString which is being passed as formatting string to formatting m...
void checkDictionaryLiteral(QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaPPC.cpp:113
void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg)
Definition SemaPPC.cpp:32
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition SemaPPC.cpp:422
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSPIRVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
SemaDiagnosticBuilder DiagIfDeviceCode(SourceLocation Loc, unsigned DiagID)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as device c...
Definition SemaSYCL.cpp: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:534
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10404
ContextualImplicitConverter(bool Suppress=false, bool SuppressConversion=false)
Definition Sema.h:10409
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:869
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:1449
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:13155
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1142
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:2756
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9415
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9423
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9460
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:7017
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:2078
SemaHexagon & Hexagon()
Definition Sema.h:1489
SemaSYCL & SYCL()
Definition Sema.h:1559
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:1726
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:840
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition Sema.h:1579
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:1309
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:227
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:937
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:1519
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1374
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:761
ASTContext & getASTContext() const
Definition Sema.h:940
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:762
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2638
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:1213
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:2745
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:933
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:1464
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:1479
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:1307
static const uint64_t MaximumAlignment
Definition Sema.h:1236
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:959
SemaHLSL & HLSL()
Definition Sema.h:1484
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1504
SemaRISCV & RISCV()
Definition Sema.h:1549
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
EltwiseBuiltinArgTyRestriction
Definition Sema.h:2811
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7053
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1738
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:1342
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:2718
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15535
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:2411
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:645
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:1447
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:1529
FormatArgumentPassingKind
Definition Sema.h:2648
@ FAPK_Elsewhere
Definition Sema.h:2652
@ FAPK_Fixed
Definition Sema.h:2649
@ FAPK_Variadic
Definition Sema.h:2650
@ FAPK_VAList
Definition Sema.h:2651
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:8258
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:14061
SourceManager & getSourceManager() const
Definition Sema.h:938
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:2640
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:1539
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:1268
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:1569
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:1312
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:790
DiagnosticsEngine & Diags
Definition Sema.h:1311
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:1514
void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction, const Expr *ThisArg, ArrayRef< const Expr * > Args)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:631
bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum)
BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a constant expression representing ...
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
@ AbstractParamType
Definition Sema.h:6317
SemaSPIRV & SPIRV()
Definition Sema.h:1554
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:1494
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6505
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:1574
SemaARM & ARM()
Definition Sema.h:1454
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition Expr.h:4649
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
child_range children()
Definition Stmt.cpp:304
StmtClass getStmtClass() const
Definition Stmt.h:1503
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1805
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1979
bool isUTF8() const
Definition Expr.h:1924
bool isWide() const
Definition Expr.h:1923
bool isPascal() const
Definition Expr.h:1928
unsigned getLength() const
Definition Expr.h:1915
StringLiteralKind getKind() const
Definition Expr.h:1918
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
getLocationOfByte - Return a source location that points to the specified byte of this string literal...
Definition Expr.cpp:1332
bool isUTF32() const
Definition Expr.h:1926
unsigned getByteLength() const
Definition Expr.h:1914
StringRef getString() const
Definition Expr.h:1873
bool isUTF16() const
Definition Expr.h:1925
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.h:1980
bool isOrdinary() const
Definition Expr.h:1922
unsigned getCharByteWidth() const
Definition Expr.h:1916
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3873
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3853
bool isUnion() const
Definition Decl.h:3963
Exposes information about the current target.
Definition TargetInfo.h:227
virtual bool supportsCpuSupports() const
virtual bool validateCpuIs(StringRef Name) const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
IntType getSizeType() const
Definition TargetInfo.h:389
virtual bool validateCpuSupports(StringRef Name) const
virtual bool supportsCpuIs() const
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
@ Type
The template argument is a type.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2735
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6282
A container of type source information.
Definition TypeBase.h:8418
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8429
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isBlockPointerType() const
Definition TypeBase.h:8704
bool isVoidType() const
Definition TypeBase.h:9050
bool isBooleanType() const
Definition TypeBase.h:9187
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2293
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9237
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:824
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2270
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2359
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2177
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9217
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition Type.cpp:2123
bool isVoidPointerType() const
Definition Type.cpp:749
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2521
bool isArrayType() const
Definition TypeBase.h:8783
bool isCharType() const
Definition Type.cpp:2197
bool isFunctionPointerType() const
Definition TypeBase.h:8751
bool isPointerType() const
Definition TypeBase.h:8684
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9094
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
bool isEnumeralType() const
Definition TypeBase.h:8815
bool isScalarType() const
Definition TypeBase.h:9156
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1958
bool isVariableArrayType() const
Definition TypeBase.h:8795
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2705
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9172
bool isExtVectorType() const
Definition TypeBase.h:8827
bool isExtVectorBoolType() const
Definition TypeBase.h:8831
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2744
bool isBitIntType() const
Definition TypeBase.h:8959
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9019
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8807
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8819
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2314
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3183
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2655
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9230
bool isMemberPointerType() const
Definition TypeBase.h:8765
bool isAtomicType() const
Definition TypeBase.h:8876
bool isFunctionProtoType() const
Definition TypeBase.h:2661
bool isMatrixType() const
Definition TypeBase.h:8847
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3205
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2864
bool isUnscopedEnumerationType() const
Definition Type.cpp:2190
bool isObjCObjectType() const
Definition TypeBase.h:8867
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9330
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9193
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2570
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2531
bool isFunctionType() const
Definition TypeBase.h:8680
bool isObjCObjectPointerType() const
Definition TypeBase.h:8863
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2401
bool isStructureOrClassType() const
Definition Type.cpp:743
bool isVectorType() const
Definition TypeBase.h:8823
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2409
bool isFloatingType() const
Definition Type.cpp:2393
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:2336
bool isAnyPointerType() const
Definition TypeBase.h:8692
TypeClass getTypeClass() const
Definition TypeBase.h:2445
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2471
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
bool isNullPtrType() const
Definition TypeBase.h:9087
bool isRecordType() const
Definition TypeBase.h:8811
bool isObjCRetainableType() const
Definition Type.cpp:5435
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2667
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5156
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2732
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3597
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2631
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
Expr * getSubExpr() const
Definition Expr.h:2291
Opcode getOpcode() const
Definition Expr.h:2286
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2368
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1039
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1127
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3420
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5578
Represents a variable declaration or definition.
Definition Decl.h:932
Represents a GCC generic vector type.
Definition TypeBase.h:4239
unsigned getNumElements() const
Definition TypeBase.h:4254
QualType getElementType() const
Definition TypeBase.h:4253
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2707
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
std::optional< ConversionSpecifier > getStandardSpecifier() const
const OptionalAmount & getFieldWidth() const
bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const
const LengthModifier & getLengthModifier() const
bool hasValidLengthModifier(const TargetInfo &Target, const LangOptions &LO) const
std::optional< LengthModifier > getCorrectedLengthModifier() const
Represents the length modifier in a format string in scanf/printf.
ArgType getArgType(ASTContext &Ctx) const
Class representing optional flags with location and representation information.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
const OptionalFlag & isPrivate() const
const OptionalAmount & getPrecision() const
const OptionalFlag & hasSpacePrefix() const
const OptionalFlag & isSensitive() const
const OptionalFlag & isLeftJustified() const
const OptionalFlag & hasLeadingZeros() const
const OptionalFlag & hasAlternativeForm() const
const PrintfConversionSpecifier & getConversionSpecifier() const
const OptionalFlag & hasPlusPrefix() const
const OptionalFlag & hasThousandsGrouping() const
ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const
Returns the builtin type that a data argument paired with this format specifier should have.
const OptionalFlag & isPublic() const
const ScanfConversionSpecifier & getConversionSpecifier() const
ArgType getArgType(ASTContext &Ctx) const
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition SPIR.cpp:35
Definition SPIR.cpp:47
Common components of both fprintf and fscanf format strings.
bool parseFormatStringHasFormattingSpecifiers(const char *Begin, const char *End, const LangOptions &LO, const TargetInfo &Target)
Return true if the given string has at least one formatting specifier.
bool ParsePrintfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target, bool isFreeBSDKPrintf)
bool ParseScanfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
bool ParseFormatStringHasSArg(const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
Pieces specific to fprintf format strings.
Pieces specific to fscanf format strings.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< PointerType > pointerType
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
ComparisonResult
Indicates the result of a tentative comparison.
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition Types.cpp:237
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ After
Like System, but searched after the system directories.
@ FixIt
Parse and apply any fixits to the source.
bool GT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1532
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1517
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1510
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1524
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2803
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1478
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1539
llvm::ImmutableSet< T > join(llvm::ImmutableSet< T > A, llvm::ImmutableSet< T > B, typename llvm::ImmutableSet< T >::Factory &F)
Computes the union of two ImmutableSets.
Definition Utils.h:39
void checkCaptureByLifetime(Sema &SemaRef, const CapturingEntity &Entity, Expr *Init)
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition FixIt.h:32
RangeSelector merge(RangeSelector First, RangeSelector Second)
Selects the merge of the two ranges, i.e.
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
Expr * IgnoreElidableImplicitConstructorSingleStep(Expr *E)
Definition IgnoreExpr.h:115
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
VariadicCallType
Definition Sema.h:513
bool hasSpecificAttr(const Container &container)
@ Arithmetic
An arithmetic operation.
Definition Sema.h:663
@ Comparison
A comparison.
Definition Sema.h:667
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:351
Expr * IgnoreExprNodes(Expr *E, FnTys &&... Fns)
Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *, Recursively apply each of the f...
Definition IgnoreExpr.h:24
@ Success
Annotation was successful.
Definition Parser.h:65
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:150
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
PointerAuthDiscArgKind
Definition Sema.h:594
std::string FormatUTFCodeUnitAsCodepoint(unsigned Value, QualType T)
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:125
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:258
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition JsonSupport.h:21
SemaARM::ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD)
Definition SemaARM.cpp:552
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
bool isFunctionOrMethodVariadic(const Decl *D)
Definition Attr.h:112
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:564
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:499
CastKind
CastKind - The kind of operation required for a conversion.
BuiltinCountedByRefKind
Definition Sema.h:521
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool hasImplicitObjectParameter(const Decl *D)
Definition Attr.h:126
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
for(const auto &A :T->param_types())
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition IgnoreExpr.h:144
unsigned getFunctionOrMethodNumParams(const Decl *D)
getFunctionOrMethodNumParams - Return number of function or method parameters.
Definition Attr.h:64
StringLiteralKind
Definition Expr.h:1769
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
@ CC_Win64
Definition Specifiers.h:286
@ CC_X86_64SysV
Definition Specifiers.h:287
@ Generic
not a target-specific vector type
Definition TypeBase.h:4200
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5991
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5984
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1772
unsigned long uint64_t
long int64_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:652
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:654
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:640
Extra information about a function prototype.
Definition TypeBase.h:5456
unsigned Indentation
The number of spaces to use to indent each line.
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13334
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13360
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13350
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13301
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6911
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2660
#define log2(__x)
Definition tgmath.h:970