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"
80#include "clang/Sema/SemaWasm.h"
81#include "clang/Sema/SemaX86.h"
82#include "llvm/ADT/APFloat.h"
83#include "llvm/ADT/APInt.h"
84#include "llvm/ADT/APSInt.h"
85#include "llvm/ADT/ArrayRef.h"
86#include "llvm/ADT/DenseMap.h"
87#include "llvm/ADT/FoldingSet.h"
88#include "llvm/ADT/STLExtras.h"
89#include "llvm/ADT/STLForwardCompat.h"
90#include "llvm/ADT/SmallBitVector.h"
91#include "llvm/ADT/SmallPtrSet.h"
92#include "llvm/ADT/SmallString.h"
93#include "llvm/ADT/SmallVector.h"
94#include "llvm/ADT/StringExtras.h"
95#include "llvm/ADT/StringRef.h"
96#include "llvm/ADT/StringSet.h"
97#include "llvm/ADT/StringSwitch.h"
98#include "llvm/Support/AtomicOrdering.h"
99#include "llvm/Support/Compiler.h"
100#include "llvm/Support/ConvertUTF.h"
101#include "llvm/Support/ErrorHandling.h"
102#include "llvm/Support/Format.h"
103#include "llvm/Support/Locale.h"
104#include "llvm/Support/MathExtras.h"
105#include "llvm/Support/SaveAndRestore.h"
106#include "llvm/Support/raw_ostream.h"
107#include "llvm/TargetParser/RISCVTargetParser.h"
108#include "llvm/TargetParser/Triple.h"
109#include <algorithm>
110#include <cassert>
111#include <cctype>
112#include <cstddef>
113#include <cstdint>
114#include <functional>
115#include <limits>
116#include <optional>
117#include <string>
118#include <tuple>
119#include <utility>
120
121using namespace clang;
122using namespace sema;
123
125 unsigned ByteNo) const {
126 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
127 Context.getTargetInfo());
128}
129
130static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
132 return (A << 8) | B;
133}
134
135bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
136 unsigned ArgCount = Call->getNumArgs();
137 if (ArgCount >= MinArgCount)
138 return false;
139
140 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
141 << 0 /*function call*/ << MinArgCount << ArgCount
142 << /*is non object*/ 0 << Call->getSourceRange();
143}
144
145bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
146 unsigned ArgCount = Call->getNumArgs();
147 if (ArgCount <= MaxArgCount)
148 return false;
149 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)
150 << 0 /*function call*/ << MaxArgCount << ArgCount
151 << /*is non object*/ 0 << Call->getSourceRange();
152}
153
154bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
155 unsigned MaxArgCount) {
156 return checkArgCountAtLeast(Call, MinArgCount) ||
157 checkArgCountAtMost(Call, MaxArgCount);
158}
159
160bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
161 unsigned ArgCount = Call->getNumArgs();
162 if (ArgCount == DesiredArgCount)
163 return false;
164
165 if (checkArgCountAtLeast(Call, DesiredArgCount))
166 return true;
167 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
168
169 // Highlight all the excess arguments.
170 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
171 Call->getArg(ArgCount - 1)->getEndLoc());
172
173 return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
174 << 0 /*function call*/ << DesiredArgCount << ArgCount
175 << /*is non object*/ 0 << Range;
176}
177
179 bool HasError = false;
180
181 for (const Expr *Arg : Call->arguments()) {
182 if (Arg->isValueDependent())
183 continue;
184
185 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
186 int DiagMsgKind = -1;
187 // Arguments must be pointers to constant strings and cannot use '$'.
188 if (!ArgString.has_value())
189 DiagMsgKind = 0;
190 else if (ArgString->find('$') != std::string::npos)
191 DiagMsgKind = 1;
192
193 if (DiagMsgKind >= 0) {
194 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
195 << DiagMsgKind << Arg->getSourceRange();
196 HasError = true;
197 }
198 }
199
200 return !HasError;
201}
202
204 if (Value->isTypeDependent())
205 return false;
206
207 InitializedEntity Entity =
209 ExprResult Result =
211 if (Result.isInvalid())
212 return true;
213 Value = Result.get();
214 return false;
215}
216
217/// Check that the first argument to __builtin_annotation is an integer
218/// and the second argument is a non-wide string literal.
219static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
220 if (S.checkArgCount(TheCall, 2))
221 return true;
222
223 // First argument should be an integer.
224 Expr *ValArg = TheCall->getArg(0);
225 QualType Ty = ValArg->getType();
226 if (!Ty->isIntegerType()) {
227 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
228 << ValArg->getSourceRange();
229 return true;
230 }
231
232 // Second argument should be a constant string.
233 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
234 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
235 if (!Literal || !Literal->isOrdinary()) {
236 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
237 << StrArg->getSourceRange();
238 return true;
239 }
240
241 TheCall->setType(Ty);
242 return false;
243}
244
245static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
246 // We need at least one argument.
247 if (TheCall->getNumArgs() < 1) {
248 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
249 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
250 << TheCall->getCallee()->getSourceRange();
251 return true;
252 }
253
254 // All arguments should be wide string literals.
255 for (Expr *Arg : TheCall->arguments()) {
256 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
257 if (!Literal || !Literal->isWide()) {
258 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
259 << Arg->getSourceRange();
260 return true;
261 }
262 }
263
264 return false;
265}
266
267/// Check that the argument to __builtin_addressof is a glvalue, and set the
268/// result type to the corresponding pointer type.
269static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
270 if (S.checkArgCount(TheCall, 1))
271 return true;
272
273 ExprResult Arg(TheCall->getArg(0));
274 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
275 if (ResultType.isNull())
276 return true;
277
278 TheCall->setArg(0, Arg.get());
279 TheCall->setType(ResultType);
280 return false;
281}
282
283/// Check that the argument to __builtin_function_start is a function.
284static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
285 if (S.checkArgCount(TheCall, 1))
286 return true;
287
288 if (TheCall->getArg(0)->containsErrors())
289 return true;
290
292 if (Arg.isInvalid())
293 return true;
294
295 TheCall->setArg(0, Arg.get());
296 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
298
299 if (!FD) {
300 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
301 << TheCall->getSourceRange();
302 return true;
303 }
304
305 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
306 TheCall->getBeginLoc());
307}
308
309/// Check the number of arguments and set the result type to
310/// the argument type.
311static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
312 if (S.checkArgCount(TheCall, 1))
313 return true;
314
315 TheCall->setType(TheCall->getArg(0)->getType());
316 return false;
317}
318
319/// Check that the value argument for __builtin_is_aligned(value, alignment) and
320/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
321/// type (but not a function pointer) and that the alignment is a power-of-two.
322static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
323 if (S.checkArgCount(TheCall, 2))
324 return true;
325
326 clang::Expr *Source = TheCall->getArg(0);
327 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
328
329 auto IsValidIntegerType = [](QualType Ty) {
330 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
331 };
332 QualType SrcTy = Source->getType();
333 // We should also be able to use it with arrays (but not functions!).
334 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
335 SrcTy = S.Context.getDecayedType(SrcTy);
336 }
337 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
338 SrcTy->isFunctionPointerType()) {
339 // FIXME: this is not quite the right error message since we don't allow
340 // floating point types, or member pointers.
341 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
342 << SrcTy;
343 return true;
344 }
345
346 clang::Expr *AlignOp = TheCall->getArg(1);
347 if (!IsValidIntegerType(AlignOp->getType())) {
348 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
349 << AlignOp->getType();
350 return true;
351 }
352 Expr::EvalResult AlignResult;
353 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
354 // We can't check validity of alignment if it is value dependent.
355 if (!AlignOp->isValueDependent() &&
356 AlignOp->EvaluateAsInt(AlignResult, S.Context,
358 llvm::APSInt AlignValue = AlignResult.Val.getInt();
359 llvm::APSInt MaxValue(
360 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
361 if (AlignValue < 1) {
362 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
363 return true;
364 }
365 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
366 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
367 << toString(MaxValue, 10);
368 return true;
369 }
370 if (!AlignValue.isPowerOf2()) {
371 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
372 return true;
373 }
374 if (AlignValue == 1) {
375 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
376 << IsBooleanAlignBuiltin;
377 }
378 }
379
382 SourceLocation(), Source);
383 if (SrcArg.isInvalid())
384 return true;
385 TheCall->setArg(0, SrcArg.get());
386 ExprResult AlignArg =
388 S.Context, AlignOp->getType(), false),
389 SourceLocation(), AlignOp);
390 if (AlignArg.isInvalid())
391 return true;
392 TheCall->setArg(1, AlignArg.get());
393 // For align_up/align_down, the return type is the same as the (potentially
394 // decayed) argument type including qualifiers. For is_aligned(), the result
395 // is always bool.
396 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
397 return false;
398}
399
400static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
401 if (S.checkArgCount(TheCall, 3))
402 return true;
403
404 std::pair<unsigned, const char *> Builtins[] = {
405 { Builtin::BI__builtin_add_overflow, "ckd_add" },
406 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
407 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
408 };
409
410 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
411 const char *> &P) {
412 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
414 S.getSourceManager(), S.getLangOpts()) == P.second;
415 });
416
417 auto ValidCkdIntType = [](QualType QT) {
418 // A valid checked integer type is an integer type other than a plain char,
419 // bool, a bit-precise type, or an enumeration type.
420 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
421 return (BT->getKind() >= BuiltinType::Short &&
422 BT->getKind() <= BuiltinType::Int128) || (
423 BT->getKind() >= BuiltinType::UShort &&
424 BT->getKind() <= BuiltinType::UInt128) ||
425 BT->getKind() == BuiltinType::UChar ||
426 BT->getKind() == BuiltinType::SChar;
427 return false;
428 };
429
430 // First two arguments should be integers.
431 for (unsigned I = 0; I < 2; ++I) {
433 if (Arg.isInvalid()) return true;
434 TheCall->setArg(I, Arg.get());
435
436 QualType Ty = Arg.get()->getType();
437 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
438 if (!IsValid) {
439 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
440 << CkdOperation << Ty << Arg.get()->getSourceRange();
441 return true;
442 }
443 }
444
445 // Third argument should be a pointer to a non-const integer.
446 // IRGen correctly handles volatile, restrict, and address spaces, and
447 // the other qualifiers aren't possible.
448 {
450 if (Arg.isInvalid()) return true;
451 TheCall->setArg(2, Arg.get());
452
453 QualType Ty = Arg.get()->getType();
454 const auto *PtrTy = Ty->getAs<PointerType>();
455 if (!PtrTy ||
456 !PtrTy->getPointeeType()->isIntegerType() ||
457 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
458 PtrTy->getPointeeType().isConstQualified()) {
459 S.Diag(Arg.get()->getBeginLoc(),
460 diag::err_overflow_builtin_must_be_ptr_int)
461 << CkdOperation << Ty << Arg.get()->getSourceRange();
462 return true;
463 }
464 }
465
466 // Disallow signed bit-precise integer args larger than 128 bits to mul
467 // function until we improve backend support.
468 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
469 for (unsigned I = 0; I < 3; ++I) {
470 const auto Arg = TheCall->getArg(I);
471 // Third argument will be a pointer.
472 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
473 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
474 S.getASTContext().getIntWidth(Ty) > 128)
475 return S.Diag(Arg->getBeginLoc(),
476 diag::err_overflow_builtin_bit_int_max_size)
477 << 128;
478 }
479 }
480
481 return false;
482}
483
484namespace {
485struct BuiltinDumpStructGenerator {
486 Sema &S;
487 CallExpr *TheCall;
488 SourceLocation Loc = TheCall->getBeginLoc();
489 SmallVector<Expr *, 32> Actions;
490 DiagnosticErrorTrap ErrorTracker;
491 PrintingPolicy Policy;
492
493 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
494 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
495 Policy(S.Context.getPrintingPolicy()) {
496 Policy.AnonymousTagNameStyle =
497 llvm::to_underlying(PrintingPolicy::AnonymousTagMode::Plain);
498 }
499
500 Expr *makeOpaqueValueExpr(Expr *Inner) {
501 auto *OVE = new (S.Context)
502 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
503 Inner->getObjectKind(), Inner);
504 Actions.push_back(OVE);
505 return OVE;
506 }
507
508 Expr *getStringLiteral(llvm::StringRef Str) {
510 // Wrap the literal in parentheses to attach a source location.
511 return new (S.Context) ParenExpr(Loc, Loc, Lit);
512 }
513
514 bool callPrintFunction(llvm::StringRef Format,
515 llvm::ArrayRef<Expr *> Exprs = {}) {
516 SmallVector<Expr *, 8> Args;
517 assert(TheCall->getNumArgs() >= 2);
518 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
519 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
520 Args.push_back(getStringLiteral(Format));
521 llvm::append_range(Args, Exprs);
522
523 // Register a note to explain why we're performing the call.
524 Sema::CodeSynthesisContext Ctx;
526 Ctx.PointOfInstantiation = Loc;
527 Ctx.CallArgs = Args.data();
528 Ctx.NumCallArgs = Args.size();
530
531 ExprResult RealCall =
532 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
533 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
534
536 if (!RealCall.isInvalid())
537 Actions.push_back(RealCall.get());
538 // Bail out if we've hit any errors, even if we managed to build the
539 // call. We don't want to produce more than one error.
540 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
541 }
542
543 Expr *getIndentString(unsigned Depth) {
544 if (!Depth)
545 return nullptr;
546
547 llvm::SmallString<32> Indent;
548 Indent.resize(Depth * Policy.Indentation, ' ');
549 return getStringLiteral(Indent);
550 }
551
552 Expr *getTypeString(QualType T) {
553 return getStringLiteral(T.getAsString(Policy));
554 }
555
556 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
557 llvm::raw_svector_ostream OS(Str);
558
559 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
560 // than trying to print a single character.
561 if (auto *BT = T->getAs<BuiltinType>()) {
562 switch (BT->getKind()) {
563 case BuiltinType::Bool:
564 OS << "%d";
565 return true;
566 case BuiltinType::Char_U:
567 case BuiltinType::UChar:
568 OS << "%hhu";
569 return true;
570 case BuiltinType::Char_S:
571 case BuiltinType::SChar:
572 OS << "%hhd";
573 return true;
574 default:
575 break;
576 }
577 }
578
579 analyze_printf::PrintfSpecifier Specifier;
580 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
581 // We were able to guess how to format this.
582 if (Specifier.getConversionSpecifier().getKind() ==
583 analyze_printf::PrintfConversionSpecifier::sArg) {
584 // Wrap double-quotes around a '%s' specifier and limit its maximum
585 // length. Ideally we'd also somehow escape special characters in the
586 // contents but printf doesn't support that.
587 // FIXME: '%s' formatting is not safe in general.
588 OS << '"';
589 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
590 Specifier.toString(OS);
591 OS << '"';
592 // FIXME: It would be nice to include a '...' if the string doesn't fit
593 // in the length limit.
594 } else {
595 Specifier.toString(OS);
596 }
597 return true;
598 }
599
600 if (T->isPointerType()) {
601 // Format all pointers with '%p'.
602 OS << "%p";
603 return true;
604 }
605
606 return false;
607 }
608
609 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
610 Expr *IndentLit = getIndentString(Depth);
611 Expr *TypeLit = getTypeString(S.Context.getCanonicalTagType(RD));
612 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
613 : callPrintFunction("%s", {TypeLit}))
614 return true;
615
616 return dumpRecordValue(RD, E, IndentLit, Depth);
617 }
618
619 // Dump a record value. E should be a pointer or lvalue referring to an RD.
620 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
621 unsigned Depth) {
622 // FIXME: Decide what to do if RD is a union. At least we should probably
623 // turn off printing `const char*` members with `%s`, because that is very
624 // likely to crash if that's not the active member. Whatever we decide, we
625 // should document it.
626
627 // Build an OpaqueValueExpr so we can refer to E more than once without
628 // triggering re-evaluation.
629 Expr *RecordArg = makeOpaqueValueExpr(E);
630 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
631
632 if (callPrintFunction(" {\n"))
633 return true;
634
635 // Dump each base class, regardless of whether they're aggregates.
636 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
637 for (const auto &Base : CXXRD->bases()) {
638 QualType BaseType =
639 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
640 : S.Context.getLValueReferenceType(Base.getType());
642 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
643 RecordArg);
644 if (BasePtr.isInvalid() ||
645 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
646 Depth + 1))
647 return true;
648 }
649 }
650
651 Expr *FieldIndentArg = getIndentString(Depth + 1);
652
653 // Dump each field.
654 for (auto *D : RD->decls()) {
655 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
656 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
657 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
658 continue;
659
660 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
661 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
662 getTypeString(FD->getType()),
663 getStringLiteral(FD->getName())};
664
665 if (FD->isBitField()) {
666 Format += ": %zu ";
667 QualType SizeT = S.Context.getSizeType();
668 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
669 FD->getBitWidthValue());
670 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
671 }
672
673 Format += "=";
674
677 CXXScopeSpec(), Loc, IFD,
678 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
680 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
682 DeclarationNameInfo(FD->getDeclName(), Loc));
683 if (Field.isInvalid())
684 return true;
685
686 auto *InnerRD = FD->getType()->getAsRecordDecl();
687 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
688 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
689 // Recursively print the values of members of aggregate record type.
690 if (callPrintFunction(Format, Args) ||
691 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
692 return true;
693 } else {
694 Format += " ";
695 if (appendFormatSpecifier(FD->getType(), Format)) {
696 // We know how to print this field.
697 Args.push_back(Field.get());
698 } else {
699 // We don't know how to print this field. Print out its address
700 // with a format specifier that a smart tool will be able to
701 // recognize and treat specially.
702 Format += "*%p";
703 ExprResult FieldAddr =
704 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
705 if (FieldAddr.isInvalid())
706 return true;
707 Args.push_back(FieldAddr.get());
708 }
709 Format += "\n";
710 if (callPrintFunction(Format, Args))
711 return true;
712 }
713 }
714
715 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
716 : callPrintFunction("}\n");
717 }
718
719 Expr *buildWrapper() {
720 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
722 TheCall->setType(Wrapper->getType());
723 TheCall->setValueKind(Wrapper->getValueKind());
724 return Wrapper;
725 }
726};
727} // namespace
728
730 if (S.checkArgCountAtLeast(TheCall, 2))
731 return ExprError();
732
733 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
734 if (PtrArgResult.isInvalid())
735 return ExprError();
736 TheCall->setArg(0, PtrArgResult.get());
737
738 // First argument should be a pointer to a struct.
739 QualType PtrArgType = PtrArgResult.get()->getType();
740 if (!PtrArgType->isPointerType() ||
741 !PtrArgType->getPointeeType()->isRecordType()) {
742 S.Diag(PtrArgResult.get()->getBeginLoc(),
743 diag::err_expected_struct_pointer_argument)
744 << 1 << TheCall->getDirectCallee() << PtrArgType;
745 return ExprError();
746 }
747 QualType Pointee = PtrArgType->getPointeeType();
748 const RecordDecl *RD = Pointee->getAsRecordDecl();
749 // Try to instantiate the class template as appropriate; otherwise, access to
750 // its data() may lead to a crash.
751 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
752 diag::err_incomplete_type))
753 return ExprError();
754 // Second argument is a callable, but we can't fully validate it until we try
755 // calling it.
756 QualType FnArgType = TheCall->getArg(1)->getType();
757 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
758 !FnArgType->isBlockPointerType() &&
759 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
760 auto *BT = FnArgType->getAs<BuiltinType>();
761 switch (BT ? BT->getKind() : BuiltinType::Void) {
762 case BuiltinType::Dependent:
763 case BuiltinType::Overload:
764 case BuiltinType::BoundMember:
765 case BuiltinType::PseudoObject:
766 case BuiltinType::UnknownAny:
767 case BuiltinType::BuiltinFn:
768 // This might be a callable.
769 break;
770
771 default:
772 S.Diag(TheCall->getArg(1)->getBeginLoc(),
773 diag::err_expected_callable_argument)
774 << 2 << TheCall->getDirectCallee() << FnArgType;
775 return ExprError();
776 }
777 }
778
779 BuiltinDumpStructGenerator Generator(S, TheCall);
780
781 // Wrap parentheses around the given pointer. This is not necessary for
782 // correct code generation, but it means that when we pretty-print the call
783 // arguments in our diagnostics we will produce '(&s)->n' instead of the
784 // incorrect '&s->n'.
785 Expr *PtrArg = PtrArgResult.get();
786 PtrArg = new (S.Context)
787 ParenExpr(PtrArg->getBeginLoc(),
788 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
789 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
790 return ExprError();
791
792 return Generator.buildWrapper();
793}
794
795static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
796 if (S.checkArgCount(BuiltinCall, 2))
797 return true;
798
799 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
800 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
801 Expr *Call = BuiltinCall->getArg(0);
802 Expr *Chain = BuiltinCall->getArg(1);
803
804 if (Call->getStmtClass() != Stmt::CallExprClass) {
805 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
806 << Call->getSourceRange();
807 return true;
808 }
809
810 auto CE = cast<CallExpr>(Call);
811 if (CE->getCallee()->getType()->isBlockPointerType()) {
812 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
813 << Call->getSourceRange();
814 return true;
815 }
816
817 const Decl *TargetDecl = CE->getCalleeDecl();
818 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
819 if (FD->getBuiltinID()) {
820 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
821 << Call->getSourceRange();
822 return true;
823 }
824
825 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
826 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
827 << Call->getSourceRange();
828 return true;
829 }
830
831 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
832 if (ChainResult.isInvalid())
833 return true;
834 if (!ChainResult.get()->getType()->isPointerType()) {
835 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
836 << Chain->getSourceRange();
837 return true;
838 }
839
840 QualType ReturnTy = CE->getCallReturnType(S.Context);
841 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
842 QualType BuiltinTy = S.Context.getFunctionType(
843 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
844 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
845
846 Builtin =
847 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
848
849 BuiltinCall->setType(CE->getType());
850 BuiltinCall->setValueKind(CE->getValueKind());
851 BuiltinCall->setObjectKind(CE->getObjectKind());
852 BuiltinCall->setCallee(Builtin);
853 BuiltinCall->setArg(1, ChainResult.get());
854
855 return false;
856}
857
858namespace {
859
860class ScanfDiagnosticFormatHandler
862 // Accepts the argument index (relative to the first destination index) of the
863 // argument whose size we want.
864 using ComputeSizeFunction =
865 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
866
867 // Accepts the argument index (relative to the first destination index), the
868 // destination size, and the source size).
869 using DiagnoseFunction =
870 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
871
872 ComputeSizeFunction ComputeSizeArgument;
873 DiagnoseFunction Diagnose;
874
875public:
876 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
877 DiagnoseFunction Diagnose)
878 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
879
880 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
881 const char *StartSpecifier,
882 unsigned specifierLen) override {
883 if (!FS.consumesDataArgument())
884 return true;
885
886 unsigned NulByte = 0;
887 switch ((FS.getConversionSpecifier().getKind())) {
888 default:
889 return true;
892 NulByte = 1;
893 break;
895 break;
896 }
897
898 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
899 if (FW.getHowSpecified() !=
900 analyze_format_string::OptionalAmount::HowSpecified::Constant)
901 return true;
902
903 unsigned SourceSize = FW.getConstantAmount() + NulByte;
904
905 std::optional<llvm::APSInt> DestSizeAPS =
906 ComputeSizeArgument(FS.getArgIndex());
907 if (!DestSizeAPS)
908 return true;
909
910 unsigned DestSize = DestSizeAPS->getZExtValue();
911
912 if (DestSize < SourceSize)
913 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
914
915 return true;
916 }
917};
918
919class EstimateSizeFormatHandler
921 size_t Size;
922 /// Whether the format string contains Linux kernel's format specifier
923 /// extension.
924 bool IsKernelCompatible = true;
925
926public:
927 EstimateSizeFormatHandler(StringRef Format)
928 : Size(std::min(Format.find(0), Format.size()) +
929 1 /* null byte always written by sprintf */) {}
930
931 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
932 const char *, unsigned SpecifierLen,
933 const TargetInfo &) override {
934
935 const size_t FieldWidth = computeFieldWidth(FS);
936 const size_t Precision = computePrecision(FS);
937
938 // The actual format.
939 switch (FS.getConversionSpecifier().getKind()) {
940 // Just a char.
943 Size += std::max(FieldWidth, (size_t)1);
944 break;
945 // Just an integer.
955 Size += std::max(FieldWidth, Precision);
956 break;
957
958 // %g style conversion switches between %f or %e style dynamically.
959 // %g removes trailing zeros, and does not print decimal point if there are
960 // no digits that follow it. Thus %g can print a single digit.
961 // FIXME: If it is alternative form:
962 // For g and G conversions, trailing zeros are not removed from the result.
965 Size += 1;
966 break;
967
968 // Floating point number in the form '[+]ddd.ddd'.
971 Size += std::max(FieldWidth, 1 /* integer part */ +
972 (Precision ? 1 + Precision
973 : 0) /* period + decimal */);
974 break;
975
976 // Floating point number in the form '[-]d.ddde[+-]dd'.
979 Size +=
980 std::max(FieldWidth,
981 1 /* integer part */ +
982 (Precision ? 1 + Precision : 0) /* period + decimal */ +
983 1 /* e or E letter */ + 2 /* exponent */);
984 break;
985
986 // Floating point number in the form '[-]0xh.hhhhp±dd'.
989 Size +=
990 std::max(FieldWidth,
991 2 /* 0x */ + 1 /* integer part */ +
992 (Precision ? 1 + Precision : 0) /* period + decimal */ +
993 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
994 break;
995
996 // Just a string.
999 Size += FieldWidth;
1000 break;
1001
1002 // Just a pointer in the form '0xddd'.
1004 // Linux kernel has its own extesion for `%p` specifier.
1005 // Kernel Document:
1006 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1007 IsKernelCompatible = false;
1008 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1009 break;
1010
1011 // A plain percent.
1013 Size += 1;
1014 break;
1015
1016 default:
1017 break;
1018 }
1019
1020 // If field width is specified, the sign/space is already accounted for
1021 // within the field width, so no additional size is needed.
1022 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1023 Size += 1;
1024
1025 if (FS.hasAlternativeForm()) {
1026 switch (FS.getConversionSpecifier().getKind()) {
1027 // For o conversion, it increases the precision, if and only if necessary,
1028 // to force the first digit of the result to be a zero
1029 // (if the value and precision are both 0, a single 0 is printed)
1031 // For b conversion, a nonzero result has 0b prefixed to it.
1033 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1034 // it.
1037 // Note: even when the prefix is added, if
1038 // (prefix_width <= FieldWidth - formatted_length) holds,
1039 // the prefix does not increase the format
1040 // size. e.g.(("%#3x", 0xf) is "0xf")
1041
1042 // If the result is zero, o, b, x, X adds nothing.
1043 break;
1044 // For a, A, e, E, f, F, g, and G conversions,
1045 // the result of converting a floating-point number always contains a
1046 // decimal-point
1055 Size += (Precision ? 0 : 1);
1056 break;
1057 // For other conversions, the behavior is undefined.
1058 default:
1059 break;
1060 }
1061 }
1062 assert(SpecifierLen <= Size && "no underflow");
1063 Size -= SpecifierLen;
1064 return true;
1065 }
1066
1067 size_t getSizeLowerBound() const { return Size; }
1068 bool isKernelCompatible() const { return IsKernelCompatible; }
1069
1070private:
1071 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1072 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1073 size_t FieldWidth = 0;
1075 FieldWidth = FW.getConstantAmount();
1076 return FieldWidth;
1077 }
1078
1079 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1080 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1081 size_t Precision = 0;
1082
1083 // See man 3 printf for default precision value based on the specifier.
1084 switch (FW.getHowSpecified()) {
1086 switch (FS.getConversionSpecifier().getKind()) {
1087 default:
1088 break;
1092 Precision = 1;
1093 break;
1100 Precision = 1;
1101 break;
1108 Precision = 6;
1109 break;
1111 Precision = 1;
1112 break;
1113 }
1114 break;
1116 Precision = FW.getConstantAmount();
1117 break;
1118 default:
1119 break;
1120 }
1121 return Precision;
1122 }
1123};
1124
1125} // namespace
1126
1127static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1128 StringRef &FormatStrRef, size_t &StrLen,
1129 ASTContext &Context) {
1130 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1131 Format && (Format->isOrdinary() || Format->isUTF8())) {
1132 FormatStrRef = Format->getString();
1133 const ConstantArrayType *T =
1134 Context.getAsConstantArrayType(Format->getType());
1135 assert(T && "String literal not of constant array type!");
1136 size_t TypeSize = T->getZExtSize();
1137 // In case there's a null byte somewhere.
1138 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1139 return true;
1140 }
1141 return false;
1142}
1143
1144void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1145 CallExpr *TheCall) {
1146 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1148 return;
1149
1150 bool UseDABAttr = false;
1151 const FunctionDecl *UseDecl = FD;
1152
1153 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1154 if (DABAttr) {
1155 UseDecl = DABAttr->getFunction();
1156 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1157 UseDABAttr = true;
1158 }
1159
1160 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1161
1162 if (!BuiltinID)
1163 return;
1164
1165 const TargetInfo &TI = getASTContext().getTargetInfo();
1166 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1167
1168 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1169 // If we refer to a diagnose_as_builtin attribute, we need to change the
1170 // argument index to refer to the arguments of the called function. Unless
1171 // the index is out of bounds, which presumably means it's a variadic
1172 // function.
1173 if (!UseDABAttr)
1174 return Index;
1175 unsigned DABIndices = DABAttr->argIndices_size();
1176 unsigned NewIndex = Index < DABIndices
1177 ? DABAttr->argIndices_begin()[Index]
1178 : Index - DABIndices + FD->getNumParams();
1179 if (NewIndex >= TheCall->getNumArgs())
1180 return std::nullopt;
1181 return NewIndex;
1182 };
1183
1184 auto ComputeExplicitObjectSizeArgument =
1185 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1186 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1187 if (!IndexOptional)
1188 return std::nullopt;
1189 unsigned NewIndex = *IndexOptional;
1190 Expr::EvalResult Result;
1191 Expr *SizeArg = TheCall->getArg(NewIndex);
1192 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1193 return std::nullopt;
1194 llvm::APSInt Integer = Result.Val.getInt();
1195 Integer.setIsUnsigned(true);
1196 return Integer;
1197 };
1198
1199 auto ComputeSizeArgument =
1200 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1201 // If the parameter has a pass_object_size attribute, then we should use its
1202 // (potentially) more strict checking mode. Otherwise, conservatively assume
1203 // type 0.
1204 int BOSType = 0;
1205 // This check can fail for variadic functions.
1206 if (Index < FD->getNumParams()) {
1207 if (const auto *POS =
1208 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1209 BOSType = POS->getType();
1210 }
1211
1212 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1213 if (!IndexOptional)
1214 return std::nullopt;
1215 unsigned NewIndex = *IndexOptional;
1216
1217 if (NewIndex >= TheCall->getNumArgs())
1218 return std::nullopt;
1219
1220 const Expr *ObjArg = TheCall->getArg(NewIndex);
1221 if (std::optional<uint64_t> ObjSize =
1222 ObjArg->tryEvaluateObjectSize(getASTContext(), BOSType)) {
1223 // Get the object size in the target's size_t width.
1224 return llvm::APSInt::getUnsigned(*ObjSize).extOrTrunc(SizeTypeWidth);
1225 }
1226 return std::nullopt;
1227 };
1228
1229 auto ComputeStrLenArgument =
1230 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1231 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1232 if (!IndexOptional)
1233 return std::nullopt;
1234 unsigned NewIndex = *IndexOptional;
1235
1236 const Expr *ObjArg = TheCall->getArg(NewIndex);
1237
1238 if (std::optional<uint64_t> Result =
1239 ObjArg->tryEvaluateStrLen(getASTContext())) {
1240 // Add 1 for null byte.
1241 return llvm::APSInt::getUnsigned(*Result + 1).extOrTrunc(SizeTypeWidth);
1242 }
1243 return std::nullopt;
1244 };
1245
1246 std::optional<llvm::APSInt> SourceSize;
1247 std::optional<llvm::APSInt> DestinationSize;
1248 unsigned DiagID = 0;
1249 bool IsChkVariant = false;
1250
1251 auto GetFunctionName = [&]() {
1252 std::string FunctionNameStr =
1253 getASTContext().BuiltinInfo.getName(BuiltinID);
1254 llvm::StringRef FunctionName = FunctionNameStr;
1255 // Skim off the details of whichever builtin was called to produce a better
1256 // diagnostic, as it's unlikely that the user wrote the __builtin
1257 // explicitly.
1258 if (IsChkVariant) {
1259 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1260 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1261 } else {
1262 FunctionName.consume_front("__builtin_");
1263 }
1264 return FunctionName.str();
1265 };
1266
1267 switch (BuiltinID) {
1268 default:
1269 return;
1270 case Builtin::BI__builtin_strcat:
1271 case Builtin::BIstrcat:
1272 case Builtin::BI__builtin_stpcpy:
1273 case Builtin::BIstpcpy:
1274 case Builtin::BI__builtin_strcpy:
1275 case Builtin::BIstrcpy: {
1276 DiagID = diag::warn_fortify_strlen_overflow;
1277 SourceSize = ComputeStrLenArgument(1);
1278 DestinationSize = ComputeSizeArgument(0);
1279 break;
1280 }
1281
1282 case Builtin::BI__builtin___strcat_chk:
1283 case Builtin::BI__builtin___stpcpy_chk:
1284 case Builtin::BI__builtin___strcpy_chk: {
1285 DiagID = diag::warn_fortify_strlen_overflow;
1286 SourceSize = ComputeStrLenArgument(1);
1287 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1288 IsChkVariant = true;
1289 break;
1290 }
1291
1292 case Builtin::BIscanf:
1293 case Builtin::BIfscanf:
1294 case Builtin::BIsscanf: {
1295 unsigned FormatIndex = 1;
1296 unsigned DataIndex = 2;
1297 if (BuiltinID == Builtin::BIscanf) {
1298 FormatIndex = 0;
1299 DataIndex = 1;
1300 }
1301
1302 const auto *FormatExpr =
1303 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1304
1305 StringRef FormatStrRef;
1306 size_t StrLen;
1307 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1308 return;
1309
1310 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1311 unsigned SourceSize) {
1312 DiagID = diag::warn_fortify_scanf_overflow;
1313 unsigned Index = ArgIndex + DataIndex;
1314 std::string FunctionName = GetFunctionName();
1315 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1316 PDiag(DiagID) << FunctionName << (Index + 1)
1317 << DestSize << SourceSize);
1318 };
1319
1320 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1321 return ComputeSizeArgument(Index + DataIndex);
1322 };
1323 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1324 const char *FormatBytes = FormatStrRef.data();
1326 FormatBytes + StrLen, getLangOpts(),
1327 Context.getTargetInfo());
1328
1329 // Unlike the other cases, in this one we have already issued the diagnostic
1330 // here, so no need to continue (because unlike the other cases, here the
1331 // diagnostic refers to the argument number).
1332 return;
1333 }
1334
1335 case Builtin::BIsprintf:
1336 case Builtin::BI__builtin___sprintf_chk: {
1337 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1338 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1339
1340 StringRef FormatStrRef;
1341 size_t StrLen;
1342 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1343 EstimateSizeFormatHandler H(FormatStrRef);
1344 const char *FormatBytes = FormatStrRef.data();
1346 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1347 Context.getTargetInfo(), false)) {
1348 DiagID = H.isKernelCompatible()
1349 ? diag::warn_format_overflow
1350 : diag::warn_format_overflow_non_kprintf;
1351 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1352 .extOrTrunc(SizeTypeWidth);
1353 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1354 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1355 IsChkVariant = true;
1356 } else {
1357 DestinationSize = ComputeSizeArgument(0);
1358 }
1359 break;
1360 }
1361 }
1362 return;
1363 }
1364 case Builtin::BI__builtin___memcpy_chk:
1365 case Builtin::BI__builtin___memmove_chk:
1366 case Builtin::BI__builtin___memset_chk:
1367 case Builtin::BI__builtin___strlcat_chk:
1368 case Builtin::BI__builtin___strlcpy_chk:
1369 case Builtin::BI__builtin___strncat_chk:
1370 case Builtin::BI__builtin___strncpy_chk:
1371 case Builtin::BI__builtin___stpncpy_chk:
1372 case Builtin::BI__builtin___memccpy_chk:
1373 case Builtin::BI__builtin___mempcpy_chk: {
1374 DiagID = diag::warn_builtin_chk_overflow;
1375 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1376 DestinationSize =
1377 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1378 IsChkVariant = true;
1379 break;
1380 }
1381
1382 case Builtin::BI__builtin___snprintf_chk:
1383 case Builtin::BI__builtin___vsnprintf_chk: {
1384 DiagID = diag::warn_builtin_chk_overflow;
1385 SourceSize = ComputeExplicitObjectSizeArgument(1);
1386 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1387 IsChkVariant = true;
1388 break;
1389 }
1390
1391 case Builtin::BIstrncat:
1392 case Builtin::BI__builtin_strncat:
1393 case Builtin::BIstrncpy:
1394 case Builtin::BI__builtin_strncpy:
1395 case Builtin::BIstpncpy:
1396 case Builtin::BI__builtin_stpncpy: {
1397 // Whether these functions overflow depends on the runtime strlen of the
1398 // string, not just the buffer size, so emitting the "always overflow"
1399 // diagnostic isn't quite right. We should still diagnose passing a buffer
1400 // size larger than the destination buffer though; this is a runtime abort
1401 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1402 DiagID = diag::warn_fortify_source_size_mismatch;
1403 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1404 DestinationSize = ComputeSizeArgument(0);
1405 break;
1406 }
1407
1408 case Builtin::BImemcpy:
1409 case Builtin::BI__builtin_memcpy:
1410 case Builtin::BImemmove:
1411 case Builtin::BI__builtin_memmove:
1412 case Builtin::BImemset:
1413 case Builtin::BI__builtin_memset:
1414 case Builtin::BImempcpy:
1415 case Builtin::BI__builtin_mempcpy: {
1416 DiagID = diag::warn_fortify_source_overflow;
1417 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1418 DestinationSize = ComputeSizeArgument(0);
1419 break;
1420 }
1421 case Builtin::BIsnprintf:
1422 case Builtin::BI__builtin_snprintf:
1423 case Builtin::BIvsnprintf:
1424 case Builtin::BI__builtin_vsnprintf: {
1425 DiagID = diag::warn_fortify_source_size_mismatch;
1426 SourceSize = ComputeExplicitObjectSizeArgument(1);
1427 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1428 StringRef FormatStrRef;
1429 size_t StrLen;
1430 if (SourceSize &&
1431 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1432 EstimateSizeFormatHandler H(FormatStrRef);
1433 const char *FormatBytes = FormatStrRef.data();
1435 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1436 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1437 llvm::APSInt FormatSize =
1438 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1439 .extOrTrunc(SizeTypeWidth);
1440 if (FormatSize > *SourceSize && *SourceSize != 0) {
1441 unsigned TruncationDiagID =
1442 H.isKernelCompatible() ? diag::warn_format_truncation
1443 : diag::warn_format_truncation_non_kprintf;
1444 SmallString<16> SpecifiedSizeStr;
1445 SmallString<16> FormatSizeStr;
1446 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1447 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1448 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1449 PDiag(TruncationDiagID)
1450 << GetFunctionName() << SpecifiedSizeStr
1451 << FormatSizeStr);
1452 }
1453 }
1454 }
1455 DestinationSize = ComputeSizeArgument(0);
1456 const Expr *LenArg = TheCall->getArg(1)->IgnoreCasts();
1457 const Expr *Dest = TheCall->getArg(0)->IgnoreCasts();
1458 IdentifierInfo *FnInfo = FD->getIdentifier();
1459 CheckSizeofMemaccessArgument(LenArg, Dest, FnInfo);
1460 }
1461 }
1462
1463 if (!SourceSize || !DestinationSize ||
1464 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1465 return;
1466
1467 std::string FunctionName = GetFunctionName();
1468
1469 SmallString<16> DestinationStr;
1470 SmallString<16> SourceStr;
1471 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1472 SourceSize->toString(SourceStr, /*Radix=*/10);
1473 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1474 PDiag(DiagID)
1475 << FunctionName << DestinationStr << SourceStr);
1476}
1477
1478static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1479 Scope::ScopeFlags NeededScopeFlags,
1480 unsigned DiagID) {
1481 // Scopes aren't available during instantiation. Fortunately, builtin
1482 // functions cannot be template args so they cannot be formed through template
1483 // instantiation. Therefore checking once during the parse is sufficient.
1484 if (SemaRef.inTemplateInstantiation())
1485 return false;
1486
1487 Scope *S = SemaRef.getCurScope();
1488 while (S && !S->isSEHExceptScope())
1489 S = S->getParent();
1490 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1491 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1492 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1493 << DRE->getDecl()->getIdentifier();
1494 return true;
1495 }
1496
1497 return false;
1498}
1499
1500// In OpenCL, __builtin_alloca_* should return a pointer to address space
1501// that corresponds to the stack address space i.e private address space.
1502static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1503 QualType RT = TheCall->getType();
1504 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1505 "__builtin_alloca has invalid address space");
1506
1507 RT = RT->getPointeeType();
1509 TheCall->setType(S.Context.getPointerType(RT));
1510}
1511
1512static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1513 if (S.checkArgCountAtLeast(TheCall, 1))
1514 return true;
1515
1516 for (Expr *Arg : TheCall->arguments()) {
1517 // If argument is dependent on a template parameter, we can't resolve now.
1518 if (Arg->isTypeDependent() || Arg->isValueDependent())
1519 continue;
1520 // Reject void types.
1521 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1522 if (ArgTy->isVoidType())
1523 return S.Diag(Arg->getBeginLoc(), diag::err_param_with_void_type);
1524 }
1525
1526 TheCall->setType(S.Context.getSizeType());
1527 return false;
1528}
1529
1530namespace {
1531enum PointerAuthOpKind {
1532 PAO_Strip,
1533 PAO_Sign,
1534 PAO_Auth,
1535 PAO_SignGeneric,
1536 PAO_Discriminator,
1537 PAO_BlendPointer,
1538 PAO_BlendInteger
1539};
1540}
1541
1543 if (getLangOpts().PointerAuthIntrinsics)
1544 return false;
1545
1546 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1547 return true;
1548}
1549
1550static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1552}
1553
1554static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1555 // Convert it to type 'int'.
1556 if (convertArgumentToType(S, Arg, S.Context.IntTy))
1557 return true;
1558
1559 // Value-dependent expressions are okay; wait for template instantiation.
1560 if (Arg->isValueDependent())
1561 return false;
1562
1563 unsigned KeyValue;
1564 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1565}
1566
1568 // Attempt to constant-evaluate the expression.
1569 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1570 if (!KeyValue) {
1571 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1572 << 0 << Arg->getSourceRange();
1573 return true;
1574 }
1575
1576 // Ask the target to validate the key parameter.
1577 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1579 {
1580 llvm::raw_svector_ostream Str(Value);
1581 Str << *KeyValue;
1582 }
1583
1584 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1585 << Value << Arg->getSourceRange();
1586 return true;
1587 }
1588
1589 Result = KeyValue->getZExtValue();
1590 return false;
1591}
1592
1595 unsigned &IntVal) {
1596 if (!Arg) {
1597 IntVal = 0;
1598 return true;
1599 }
1600
1601 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
1602 if (!Result) {
1603 Diag(Arg->getExprLoc(), diag::err_ptrauth_arg_not_ice);
1604 return false;
1605 }
1606
1607 unsigned Max;
1608 bool IsAddrDiscArg = false;
1609
1610 switch (Kind) {
1612 Max = 1;
1613 IsAddrDiscArg = true;
1614 break;
1617 break;
1618 };
1619
1621 if (IsAddrDiscArg)
1622 Diag(Arg->getExprLoc(), diag::err_ptrauth_address_discrimination_invalid)
1623 << Result->getExtValue();
1624 else
1625 Diag(Arg->getExprLoc(), diag::err_ptrauth_extra_discriminator_invalid)
1626 << Result->getExtValue() << Max;
1627
1628 return false;
1629 };
1630
1631 IntVal = Result->getZExtValue();
1632 return true;
1633}
1634
1635static std::pair<const ValueDecl *, CharUnits>
1637 // Must evaluate as a pointer.
1638 Expr::EvalResult Result;
1639 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1640 return {nullptr, CharUnits()};
1641
1642 const auto *BaseDecl =
1643 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1644 if (!BaseDecl)
1645 return {nullptr, CharUnits()};
1646
1647 return {BaseDecl, Result.Val.getLValueOffset()};
1648}
1649
1650static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1651 bool RequireConstant = false) {
1652 if (Arg->hasPlaceholderType()) {
1654 if (R.isInvalid())
1655 return true;
1656 Arg = R.get();
1657 }
1658
1659 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1660 return OpKind != PAO_BlendInteger;
1661 };
1662 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1663 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1664 OpKind == PAO_SignGeneric;
1665 };
1666
1667 // Require the value to have the right range of type.
1668 QualType ExpectedTy;
1669 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1670 ExpectedTy = Arg->getType().getUnqualifiedType();
1671 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1672 ExpectedTy = S.Context.VoidPtrTy;
1673 } else if (AllowsInteger(OpKind) &&
1675 ExpectedTy = S.Context.getUIntPtrType();
1676
1677 } else {
1678 // Diagnose the failures.
1679 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1680 << unsigned(OpKind == PAO_Discriminator ? 1
1681 : OpKind == PAO_BlendPointer ? 2
1682 : OpKind == PAO_BlendInteger ? 3
1683 : 0)
1684 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1685 << Arg->getType() << Arg->getSourceRange();
1686 return true;
1687 }
1688
1689 // Convert to that type. This should just be an lvalue-to-rvalue
1690 // conversion.
1691 if (convertArgumentToType(S, Arg, ExpectedTy))
1692 return true;
1693
1694 if (!RequireConstant) {
1695 // Warn about null pointers for non-generic sign and auth operations.
1696 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1698 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1699 ? diag::warn_ptrauth_sign_null_pointer
1700 : diag::warn_ptrauth_auth_null_pointer)
1701 << Arg->getSourceRange();
1702 }
1703
1704 return false;
1705 }
1706
1707 // Perform special checking on the arguments to ptrauth_sign_constant.
1708
1709 // The main argument.
1710 if (OpKind == PAO_Sign) {
1711 // Require the value we're signing to have a special form.
1712 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1713 bool Invalid;
1714
1715 // Must be rooted in a declaration reference.
1716 if (!BaseDecl)
1717 Invalid = true;
1718
1719 // If it's a function declaration, we can't have an offset.
1720 else if (isa<FunctionDecl>(BaseDecl))
1721 Invalid = !Offset.isZero();
1722
1723 // Otherwise we're fine.
1724 else
1725 Invalid = false;
1726
1727 if (Invalid)
1728 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1729 return Invalid;
1730 }
1731
1732 // The discriminator argument.
1733 assert(OpKind == PAO_Discriminator);
1734
1735 // Must be a pointer or integer or blend thereof.
1736 Expr *Pointer = nullptr;
1737 Expr *Integer = nullptr;
1738 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1739 if (Call->getBuiltinCallee() ==
1740 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1741 Pointer = Call->getArg(0);
1742 Integer = Call->getArg(1);
1743 }
1744 }
1745 if (!Pointer && !Integer) {
1746 if (Arg->getType()->isPointerType())
1747 Pointer = Arg;
1748 else
1749 Integer = Arg;
1750 }
1751
1752 // Check the pointer.
1753 bool Invalid = false;
1754 if (Pointer) {
1755 assert(Pointer->getType()->isPointerType());
1756
1757 // TODO: if we're initializing a global, check that the address is
1758 // somehow related to what we're initializing. This probably will
1759 // never really be feasible and we'll have to catch it at link-time.
1760 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
1761 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
1762 Invalid = true;
1763 }
1764
1765 // Check the integer.
1766 if (Integer) {
1767 assert(Integer->getType()->isIntegerType());
1768 if (!Integer->isEvaluatable(S.Context))
1769 Invalid = true;
1770 }
1771
1772 if (Invalid)
1773 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
1774 return Invalid;
1775}
1776
1778 if (S.checkArgCount(Call, 2))
1779 return ExprError();
1781 return ExprError();
1782 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
1783 checkPointerAuthKey(S, Call->getArgs()[1]))
1784 return ExprError();
1785
1786 Call->setType(Call->getArgs()[0]->getType());
1787 return Call;
1788}
1789
1791 if (S.checkArgCount(Call, 2))
1792 return ExprError();
1794 return ExprError();
1795 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
1796 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
1797 return ExprError();
1798
1799 Call->setType(S.Context.getUIntPtrType());
1800 return Call;
1801}
1802
1804 if (S.checkArgCount(Call, 2))
1805 return ExprError();
1807 return ExprError();
1808 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
1809 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
1810 return ExprError();
1811
1812 Call->setType(S.Context.getUIntPtrType());
1813 return Call;
1814}
1815
1817 PointerAuthOpKind OpKind,
1818 bool RequireConstant) {
1819 if (S.checkArgCount(Call, 3))
1820 return ExprError();
1822 return ExprError();
1823 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
1824 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1825 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
1826 RequireConstant))
1827 return ExprError();
1828
1829 Call->setType(Call->getArgs()[0]->getType());
1830 return Call;
1831}
1832
1834 if (S.checkArgCount(Call, 5))
1835 return ExprError();
1837 return ExprError();
1838 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1839 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1840 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1841 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1842 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
1843 return ExprError();
1844
1845 Call->setType(Call->getArgs()[0]->getType());
1846 return Call;
1847}
1848
1850 if (S.checkArgCount(Call, 6))
1851 return ExprError();
1853 return ExprError();
1854 const Expr *AddendExpr = Call->getArg(5);
1855 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(S.Context);
1856 if (!AddendIsConstInt) {
1857 const Expr *Arg = Call->getArg(5)->IgnoreParenImpCasts();
1858 DeclRefExpr *DRE = cast<DeclRefExpr>(Call->getCallee()->IgnoreParenCasts());
1859 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1860 S.Diag(Arg->getBeginLoc(), diag::err_constant_integer_last_arg_type)
1861 << FDecl->getDeclName() << Arg->getSourceRange();
1862 }
1863 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1864 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1865 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1866 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1867 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator) ||
1868 !AddendIsConstInt)
1869 return ExprError();
1870
1871 Call->setType(Call->getArgs()[0]->getType());
1872 return Call;
1873}
1874
1877 return ExprError();
1878
1879 // We've already performed normal call type-checking.
1880 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
1881
1882 // Operand must be an ordinary or UTF-8 string literal.
1883 const auto *Literal = dyn_cast<StringLiteral>(Arg);
1884 if (!Literal || Literal->getCharByteWidth() != 1) {
1885 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
1886 << (Literal ? 1 : 0) << Arg->getSourceRange();
1887 return ExprError();
1888 }
1889
1890 return Call;
1891}
1892
1894 if (S.checkArgCount(Call, 1))
1895 return ExprError();
1896 Expr *FirstArg = Call->getArg(0);
1897 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(FirstArg);
1898 if (FirstValue.isInvalid())
1899 return ExprError();
1900 Call->setArg(0, FirstValue.get());
1901 QualType FirstArgType = FirstArg->getType();
1902 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
1903 FirstArgType = S.Context.getDecayedType(FirstArgType);
1904
1905 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
1906 if (!FirstArgRecord) {
1907 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1908 << /*isPolymorphic=*/0 << FirstArgType;
1909 return ExprError();
1910 }
1911 if (S.RequireCompleteType(
1912 FirstArg->getBeginLoc(), FirstArgType->getPointeeType(),
1913 diag::err_get_vtable_pointer_requires_complete_type)) {
1914 return ExprError();
1915 }
1916
1917 if (!FirstArgRecord->isPolymorphic()) {
1918 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1919 << /*isPolymorphic=*/1 << FirstArgRecord;
1920 return ExprError();
1921 }
1923 Call->setType(ReturnType);
1924 return Call;
1925}
1926
1928 if (S.checkArgCount(TheCall, 1))
1929 return ExprError();
1930
1931 // Compute __builtin_launder's parameter type from the argument.
1932 // The parameter type is:
1933 // * The type of the argument if it's not an array or function type,
1934 // Otherwise,
1935 // * The decayed argument type.
1936 QualType ParamTy = [&]() {
1937 QualType ArgTy = TheCall->getArg(0)->getType();
1938 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1939 return S.Context.getPointerType(Ty->getElementType());
1940 if (ArgTy->isFunctionType()) {
1941 return S.Context.getPointerType(ArgTy);
1942 }
1943 return ArgTy;
1944 }();
1945
1946 TheCall->setType(ParamTy);
1947
1948 auto DiagSelect = [&]() -> std::optional<unsigned> {
1949 if (!ParamTy->isPointerType())
1950 return 0;
1951 if (ParamTy->isFunctionPointerType())
1952 return 1;
1953 if (ParamTy->isVoidPointerType())
1954 return 2;
1955 return std::optional<unsigned>{};
1956 }();
1957 if (DiagSelect) {
1958 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1959 << *DiagSelect << TheCall->getSourceRange();
1960 return ExprError();
1961 }
1962
1963 // We either have an incomplete class type, or we have a class template
1964 // whose instantiation has not been forced. Example:
1965 //
1966 // template <class T> struct Foo { T value; };
1967 // Foo<int> *p = nullptr;
1968 // auto *d = __builtin_launder(p);
1969 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1970 diag::err_incomplete_type))
1971 return ExprError();
1972
1973 assert(ParamTy->getPointeeType()->isObjectType() &&
1974 "Unhandled non-object pointer case");
1975
1976 InitializedEntity Entity =
1978 ExprResult Arg =
1979 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1980 if (Arg.isInvalid())
1981 return ExprError();
1982 TheCall->setArg(0, Arg.get());
1983
1984 return TheCall;
1985}
1986
1988 if (S.checkArgCount(TheCall, 1))
1989 return ExprError();
1990
1992 if (Arg.isInvalid())
1993 return ExprError();
1994 QualType ParamTy = Arg.get()->getType();
1995 TheCall->setArg(0, Arg.get());
1996 TheCall->setType(S.Context.BoolTy);
1997
1998 // Only accept pointers to objects as arguments, which should have object
1999 // pointer or void pointer types.
2000 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2001 // LWG4138: Function pointer types not allowed
2002 if (PT->getPointeeType()->isFunctionType()) {
2003 S.Diag(TheCall->getArg(0)->getExprLoc(),
2004 diag::err_builtin_is_within_lifetime_invalid_arg)
2005 << 1;
2006 return ExprError();
2007 }
2008 // Disallow VLAs too since those shouldn't be able to
2009 // be a template parameter for `std::is_within_lifetime`
2010 if (PT->getPointeeType()->isVariableArrayType()) {
2011 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
2012 << 1 << "__builtin_is_within_lifetime";
2013 return ExprError();
2014 }
2015 } else {
2016 S.Diag(TheCall->getArg(0)->getExprLoc(),
2017 diag::err_builtin_is_within_lifetime_invalid_arg)
2018 << 0;
2019 return ExprError();
2020 }
2021 return TheCall;
2022}
2023
2025 if (S.checkArgCount(TheCall, 3))
2026 return ExprError();
2027
2028 QualType Dest = TheCall->getArg(0)->getType();
2029 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2030 S.Diag(TheCall->getArg(0)->getExprLoc(),
2031 diag::err_builtin_trivially_relocate_invalid_arg_type)
2032 << /*a pointer*/ 0;
2033 return ExprError();
2034 }
2035
2036 QualType T = Dest->getPointeeType();
2037 if (S.RequireCompleteType(TheCall->getBeginLoc(), T,
2038 diag::err_incomplete_type))
2039 return ExprError();
2040
2041 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2042 T->isIncompleteArrayType()) {
2043 S.Diag(TheCall->getArg(0)->getExprLoc(),
2044 diag::err_builtin_trivially_relocate_invalid_arg_type)
2045 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2046 return ExprError();
2047 }
2048
2049 TheCall->setType(Dest);
2050
2051 QualType Src = TheCall->getArg(1)->getType();
2052 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2053 S.Diag(TheCall->getArg(1)->getExprLoc(),
2054 diag::err_builtin_trivially_relocate_invalid_arg_type)
2055 << /*the same*/ 3;
2056 return ExprError();
2057 }
2058
2059 Expr *SizeExpr = TheCall->getArg(2);
2060 ExprResult Size = S.DefaultLvalueConversion(SizeExpr);
2061 if (Size.isInvalid())
2062 return ExprError();
2063
2064 Size = S.tryConvertExprToType(Size.get(), S.getASTContext().getSizeType());
2065 if (Size.isInvalid())
2066 return ExprError();
2067 SizeExpr = Size.get();
2068 TheCall->setArg(2, SizeExpr);
2069
2070 return TheCall;
2071}
2072
2073// Emit an error and return true if the current object format type is in the
2074// list of unsupported types.
2076 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2077 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2078 llvm::Triple::ObjectFormatType CurObjFormat =
2079 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2080 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2081 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2082 << TheCall->getSourceRange();
2083 return true;
2084 }
2085 return false;
2086}
2087
2088// Emit an error and return true if the current architecture is not in the list
2089// of supported architectures.
2090static bool
2092 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2093 llvm::Triple::ArchType CurArch =
2094 S.getASTContext().getTargetInfo().getTriple().getArch();
2095 if (llvm::is_contained(SupportedArchs, CurArch))
2096 return false;
2097 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2098 << TheCall->getSourceRange();
2099 return true;
2100}
2101
2102static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2103 SourceLocation CallSiteLoc);
2104
2105bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2106 CallExpr *TheCall) {
2107 switch (TI.getTriple().getArch()) {
2108 default:
2109 // Some builtins don't require additional checking, so just consider these
2110 // acceptable.
2111 return false;
2112 case llvm::Triple::arm:
2113 case llvm::Triple::armeb:
2114 case llvm::Triple::thumb:
2115 case llvm::Triple::thumbeb:
2116 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2117 case llvm::Triple::aarch64:
2118 case llvm::Triple::aarch64_32:
2119 case llvm::Triple::aarch64_be:
2120 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2121 case llvm::Triple::bpfeb:
2122 case llvm::Triple::bpfel:
2123 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2124 case llvm::Triple::dxil:
2125 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2126 case llvm::Triple::hexagon:
2127 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2128 case llvm::Triple::mips:
2129 case llvm::Triple::mipsel:
2130 case llvm::Triple::mips64:
2131 case llvm::Triple::mips64el:
2132 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2133 case llvm::Triple::spirv:
2134 case llvm::Triple::spirv32:
2135 case llvm::Triple::spirv64:
2136 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2137 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2138 return false;
2139 case llvm::Triple::systemz:
2140 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2141 case llvm::Triple::x86:
2142 case llvm::Triple::x86_64:
2143 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2144 case llvm::Triple::ppc:
2145 case llvm::Triple::ppcle:
2146 case llvm::Triple::ppc64:
2147 case llvm::Triple::ppc64le:
2148 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2149 case llvm::Triple::amdgcn:
2150 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2151 case llvm::Triple::riscv32:
2152 case llvm::Triple::riscv64:
2153 case llvm::Triple::riscv32be:
2154 case llvm::Triple::riscv64be:
2155 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2156 case llvm::Triple::loongarch32:
2157 case llvm::Triple::loongarch64:
2158 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2159 TheCall);
2160 case llvm::Triple::wasm32:
2161 case llvm::Triple::wasm64:
2162 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2163 case llvm::Triple::nvptx:
2164 case llvm::Triple::nvptx64:
2165 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2166 }
2167}
2168
2170 return T->isDependentType() ||
2171 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2172}
2173
2174// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2175// not a valid type, emit an error message and return true. Otherwise return
2176// false.
2177static bool
2180 int ArgOrdinal) {
2181 clang::QualType EltTy =
2182 ArgTy->isVectorType() ? ArgTy->getAs<VectorType>()->getElementType()
2183 : ArgTy->isMatrixType() ? ArgTy->getAs<MatrixType>()->getElementType()
2184 : ArgTy;
2185
2186 switch (ArgTyRestr) {
2188 if (!ArgTy->getAs<VectorType>() && !isValidMathElementType(ArgTy)) {
2189 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2190 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2191 << ArgTy;
2192 }
2193 break;
2195 if (!EltTy->isRealFloatingType()) {
2196 // FIXME: make diagnostic's wording correct for matrices
2197 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2198 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2199 << /* floating-point */ 1 << ArgTy;
2200 }
2201 break;
2203 if (!EltTy->isIntegerType()) {
2204 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2205 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2206 << /* no fp */ 0 << ArgTy;
2207 }
2208 break;
2210 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2211 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2212 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2213 << /* or fp */ 1 << ArgTy;
2214 }
2215 break;
2216 }
2217
2218 return false;
2219}
2220
2221/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2222/// This checks that the target supports the builtin and that the string
2223/// argument is constant and valid.
2224static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2225 const TargetInfo *AuxTI, unsigned BuiltinID) {
2226 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2227 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2228 "Expecting __builtin_cpu_...");
2229
2230 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2231 const TargetInfo *TheTI = &TI;
2232 auto SupportsBI = [=](const TargetInfo *TInfo) {
2233 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2234 (!IsCPUSupports && TInfo->supportsCpuIs()));
2235 };
2236 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2237 TheTI = AuxTI;
2238
2239 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2240 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2241 return S.Diag(TheCall->getBeginLoc(),
2242 TI.getTriple().isOSAIX()
2243 ? diag::err_builtin_aix_os_unsupported
2244 : diag::err_builtin_target_unsupported)
2245 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2246
2247 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2248 // Check if the argument is a string literal.
2249 if (!isa<StringLiteral>(Arg))
2250 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2251 << Arg->getSourceRange();
2252
2253 // Check the contents of the string.
2254 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2255 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2256 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2257 << Arg->getSourceRange();
2258 return false;
2259 }
2260 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2261 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2262 << Arg->getSourceRange();
2263 return false;
2264}
2265
2266/// Checks that __builtin_bswapg was called with a single argument, which is an
2267/// unsigned integer, and overrides the return value type to the integer type.
2268static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2269 if (S.checkArgCount(TheCall, 1))
2270 return true;
2271 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2272 if (ArgRes.isInvalid())
2273 return true;
2274
2275 Expr *Arg = ArgRes.get();
2276 TheCall->setArg(0, Arg);
2277 if (Arg->isTypeDependent())
2278 return false;
2279
2280 QualType ArgTy = Arg->getType();
2281
2282 if (!ArgTy->isIntegerType()) {
2283 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2284 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2285 << ArgTy;
2286 return true;
2287 }
2288 if (const auto *BT = dyn_cast<BitIntType>(ArgTy)) {
2289 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2290 BT->getNumBits() != 1) {
2291 S.Diag(Arg->getBeginLoc(), diag::err_bswapg_invalid_bit_width)
2292 << ArgTy << BT->getNumBits();
2293 return true;
2294 }
2295 }
2296 TheCall->setType(ArgTy);
2297 return false;
2298}
2299
2300/// Checks that __builtin_bitreverseg was called with a single argument, which
2301/// is an integer
2302static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2303 if (S.checkArgCount(TheCall, 1))
2304 return true;
2305 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2306 if (ArgRes.isInvalid())
2307 return true;
2308
2309 Expr *Arg = ArgRes.get();
2310 TheCall->setArg(0, Arg);
2311 if (Arg->isTypeDependent())
2312 return false;
2313
2314 QualType ArgTy = Arg->getType();
2315
2316 if (!ArgTy->isIntegerType()) {
2317 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2318 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2319 << ArgTy;
2320 return true;
2321 }
2322 TheCall->setType(ArgTy);
2323 return false;
2324}
2325
2326/// Checks that __builtin_popcountg was called with a single argument, which is
2327/// an unsigned integer.
2328static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2329 if (S.checkArgCount(TheCall, 1))
2330 return true;
2331
2332 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2333 if (ArgRes.isInvalid())
2334 return true;
2335
2336 Expr *Arg = ArgRes.get();
2337 TheCall->setArg(0, Arg);
2338
2339 QualType ArgTy = Arg->getType();
2340
2341 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2342 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2343 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2344 << ArgTy;
2345 return true;
2346 }
2347 return false;
2348}
2349
2350/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2351/// an unsigned integer, and an optional second argument, which is promoted to
2352/// an 'int'.
2353static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2354 if (S.checkArgCountRange(TheCall, 1, 2))
2355 return true;
2356
2357 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2358 if (Arg0Res.isInvalid())
2359 return true;
2360
2361 Expr *Arg0 = Arg0Res.get();
2362 TheCall->setArg(0, Arg0);
2363
2364 QualType Arg0Ty = Arg0->getType();
2365
2366 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2367 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2368 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2369 << Arg0Ty;
2370 return true;
2371 }
2372
2373 if (TheCall->getNumArgs() > 1) {
2374 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2375 if (Arg1Res.isInvalid())
2376 return true;
2377
2378 Expr *Arg1 = Arg1Res.get();
2379 TheCall->setArg(1, Arg1);
2380
2381 QualType Arg1Ty = Arg1->getType();
2382
2383 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2384 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2385 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2386 return true;
2387 }
2388 }
2389
2390 return false;
2391}
2392
2394 unsigned ArgIndex;
2395 bool OnlyUnsigned;
2396
2398 QualType T) {
2399 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2400 << ArgIndex << /*scalar*/ 1
2401 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2402 << /*no fp*/ 0 << T;
2403 }
2404
2405public:
2406 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2407 : ContextualImplicitConverter(/*Suppress=*/false,
2408 /*SuppressConversion=*/true),
2409 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2410
2411 bool match(QualType T) override {
2412 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2413 }
2414
2416 QualType T) override {
2417 return emitError(S, Loc, T);
2418 }
2419
2421 QualType T) override {
2422 return emitError(S, Loc, T);
2423 }
2424
2426 QualType T,
2427 QualType ConvTy) override {
2428 return emitError(S, Loc, T);
2429 }
2430
2432 QualType ConvTy) override {
2433 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2434 }
2435
2437 QualType T) override {
2438 return emitError(S, Loc, T);
2439 }
2440
2442 QualType ConvTy) override {
2443 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2444 }
2445
2447 QualType T,
2448 QualType ConvTy) override {
2449 llvm_unreachable("conversion functions are permitted");
2450 }
2451};
2452
2453/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2454/// arguments, that the first argument is an unsigned integer type, and that
2455/// the second argument is an integer type.
2456static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2457 if (S.checkArgCount(TheCall, 2))
2458 return true;
2459
2460 // First argument (value to rotate) must be unsigned integer type.
2461 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2463 TheCall->getArg(0)->getBeginLoc(), TheCall->getArg(0), Arg0Converter);
2464 if (Arg0Res.isInvalid())
2465 return true;
2466
2467 Expr *Arg0 = Arg0Res.get();
2468 TheCall->setArg(0, Arg0);
2469
2470 QualType Arg0Ty = Arg0->getType();
2471 if (!Arg0Ty->isUnsignedIntegerType())
2472 return true;
2473
2474 // Second argument (rotation count) must be integer type.
2475 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2477 TheCall->getArg(1)->getBeginLoc(), TheCall->getArg(1), Arg1Converter);
2478 if (Arg1Res.isInvalid())
2479 return true;
2480
2481 Expr *Arg1 = Arg1Res.get();
2482 TheCall->setArg(1, Arg1);
2483
2484 QualType Arg1Ty = Arg1->getType();
2485 if (!Arg1Ty->isIntegerType())
2486 return true;
2487
2488 TheCall->setType(Arg0Ty);
2489 return false;
2490}
2491
2492static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2493 unsigned Pos, bool AllowConst,
2494 bool AllowAS) {
2495 QualType MaskTy = MaskArg->getType();
2496 if (!MaskTy->isExtVectorBoolType())
2497 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2498 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2499 << MaskTy;
2500
2501 QualType PtrTy = PtrArg->getType();
2502 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2503 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2504 << Pos << "scalar pointer";
2505
2506 QualType PointeeTy = PtrTy->getPointeeType();
2507 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2508 (!AllowConst && PointeeTy.isConstQualified()) ||
2509 (!AllowAS && PointeeTy.hasAddressSpace())) {
2512 return S.Diag(PtrArg->getExprLoc(),
2513 diag::err_typecheck_convert_incompatible)
2514 << PtrTy << Target << /*different qualifiers=*/5
2515 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2516 << PtrTy << Target;
2517 }
2518 return false;
2519}
2520
2521static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2522 bool TypeDependent = false;
2523 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2524 ExprResult Converted =
2526 if (Converted.isInvalid())
2527 return true;
2528 TheCall->setArg(Arg, Converted.get());
2529 TypeDependent |= Converted.get()->isTypeDependent();
2530 }
2531
2532 if (TypeDependent)
2533 TheCall->setType(S.Context.DependentTy);
2534 return false;
2535}
2536
2538 if (S.checkArgCountRange(TheCall, 2, 3))
2539 return ExprError();
2540
2541 if (ConvertMaskedBuiltinArgs(S, TheCall))
2542 return ExprError();
2543
2544 Expr *MaskArg = TheCall->getArg(0);
2545 Expr *PtrArg = TheCall->getArg(1);
2546 if (TheCall->isTypeDependent())
2547 return TheCall;
2548
2549 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2550 TheCall->getBuiltinCallee() ==
2551 Builtin::BI__builtin_masked_load))
2552 return ExprError();
2553
2554 QualType MaskTy = MaskArg->getType();
2555 QualType PtrTy = PtrArg->getType();
2556 QualType PointeeTy = PtrTy->getPointeeType();
2557 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2558
2560 MaskVecTy->getNumElements());
2561 if (TheCall->getNumArgs() == 3) {
2562 Expr *PassThruArg = TheCall->getArg(2);
2563 QualType PassThruTy = PassThruArg->getType();
2564 if (!S.Context.hasSameType(PassThruTy, RetTy))
2565 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2566 << /* third argument */ 3 << RetTy;
2567 }
2568
2569 TheCall->setType(RetTy);
2570 return TheCall;
2571}
2572
2574 if (S.checkArgCount(TheCall, 3))
2575 return ExprError();
2576
2577 if (ConvertMaskedBuiltinArgs(S, TheCall))
2578 return ExprError();
2579
2580 Expr *MaskArg = TheCall->getArg(0);
2581 Expr *ValArg = TheCall->getArg(1);
2582 Expr *PtrArg = TheCall->getArg(2);
2583 if (TheCall->isTypeDependent())
2584 return TheCall;
2585
2586 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2587 TheCall->getBuiltinCallee() ==
2588 Builtin::BI__builtin_masked_store))
2589 return ExprError();
2590
2591 QualType MaskTy = MaskArg->getType();
2592 QualType PtrTy = PtrArg->getType();
2593 QualType ValTy = ValArg->getType();
2594 if (!ValTy->isVectorType())
2595 return ExprError(
2596 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2597 << 2 << "vector");
2598
2599 QualType PointeeTy = PtrTy->getPointeeType();
2600 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2601 QualType MemoryTy = S.Context.getExtVectorType(PointeeTy.getUnqualifiedType(),
2602 MaskVecTy->getNumElements());
2603 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(),
2604 MemoryTy.getUnqualifiedType()))
2605 return ExprError(S.Diag(TheCall->getBeginLoc(),
2606 diag::err_vec_builtin_incompatible_vector)
2607 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2608 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2609 TheCall->getArg(1)->getEndLoc()));
2610
2611 TheCall->setType(S.Context.VoidTy);
2612 return TheCall;
2613}
2614
2616 if (S.checkArgCountRange(TheCall, 3, 4))
2617 return ExprError();
2618
2619 if (ConvertMaskedBuiltinArgs(S, TheCall))
2620 return ExprError();
2621
2622 Expr *MaskArg = TheCall->getArg(0);
2623 Expr *IdxArg = TheCall->getArg(1);
2624 Expr *PtrArg = TheCall->getArg(2);
2625 if (TheCall->isTypeDependent())
2626 return TheCall;
2627
2628 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
2629 /*AllowAS=*/true))
2630 return ExprError();
2631
2632 QualType IdxTy = IdxArg->getType();
2633 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2634 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2635 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2636 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2637 << IdxTy;
2638
2639 QualType MaskTy = MaskArg->getType();
2640 QualType PtrTy = PtrArg->getType();
2641 QualType PointeeTy = PtrTy->getPointeeType();
2642 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2643 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2644 return ExprError(
2645 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2647 TheCall->getBuiltinCallee())
2648 << MaskTy << IdxTy);
2649
2651 MaskVecTy->getNumElements());
2652 if (TheCall->getNumArgs() == 4) {
2653 Expr *PassThruArg = TheCall->getArg(3);
2654 QualType PassThruTy = PassThruArg->getType();
2655 if (!S.Context.hasSameType(PassThruTy, RetTy))
2656 return S.Diag(PassThruArg->getExprLoc(),
2657 diag::err_vec_masked_load_store_ptr)
2658 << /* fourth argument */ 4 << RetTy;
2659 }
2660
2661 TheCall->setType(RetTy);
2662 return TheCall;
2663}
2664
2666 if (S.checkArgCount(TheCall, 4))
2667 return ExprError();
2668
2669 if (ConvertMaskedBuiltinArgs(S, TheCall))
2670 return ExprError();
2671
2672 Expr *MaskArg = TheCall->getArg(0);
2673 Expr *IdxArg = TheCall->getArg(1);
2674 Expr *ValArg = TheCall->getArg(2);
2675 Expr *PtrArg = TheCall->getArg(3);
2676 if (TheCall->isTypeDependent())
2677 return TheCall;
2678
2679 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
2680 /*AllowAS=*/true))
2681 return ExprError();
2682
2683 QualType IdxTy = IdxArg->getType();
2684 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2685 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2686 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2687 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2688 << IdxTy;
2689
2690 QualType ValTy = ValArg->getType();
2691 QualType MaskTy = MaskArg->getType();
2692 QualType PtrTy = PtrArg->getType();
2693 QualType PointeeTy = PtrTy->getPointeeType();
2694
2695 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2696 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2697 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2698 return ExprError(
2699 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2701 TheCall->getBuiltinCallee())
2702 << MaskTy << IdxTy);
2703 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2704 return ExprError(
2705 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2707 TheCall->getBuiltinCallee())
2708 << MaskTy << ValTy);
2709
2711 MaskVecTy->getNumElements());
2712 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(), ArgTy))
2713 return ExprError(S.Diag(TheCall->getBeginLoc(),
2714 diag::err_vec_builtin_incompatible_vector)
2715 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2716 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2717 TheCall->getArg(1)->getEndLoc()));
2718
2719 TheCall->setType(S.Context.VoidTy);
2720 return TheCall;
2721}
2722
2724 SourceLocation Loc = TheCall->getBeginLoc();
2725 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2726 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2727
2728 if (Args.size() == 0) {
2729 S.Diag(TheCall->getBeginLoc(),
2730 diag::err_typecheck_call_too_few_args_at_least)
2731 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2732 << /*is_non_object=*/0 << TheCall->getSourceRange();
2733 return ExprError();
2734 }
2735
2736 QualType FuncT = Args[0]->getType();
2737
2738 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2739 if (Args.size() < 2) {
2740 S.Diag(TheCall->getBeginLoc(),
2741 diag::err_typecheck_call_too_few_args_at_least)
2742 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2743 << /*is_non_object=*/0 << TheCall->getSourceRange();
2744 return ExprError();
2745 }
2746
2747 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2748 QualType ObjectT = Args[1]->getType();
2749
2750 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
2751 return ExprError();
2752
2753 ExprResult ObjectArg = [&]() -> ExprResult {
2754 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2755 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2756 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2757 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2758 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2759 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2760 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
2761 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
2762 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
2763 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
2764 return Args[1];
2765 }
2766
2767 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2768 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2769 // reference_wrapper;
2770 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2771 if (RD->isInStdNamespace() &&
2772 RD->getDeclName().getAsString() == "reference_wrapper") {
2773 CXXScopeSpec SS;
2774 IdentifierInfo *GetName = &S.Context.Idents.get("get");
2775 UnqualifiedId GetID;
2776 GetID.setIdentifier(GetName, Loc);
2777
2779 S.getCurScope(), Args[1], Loc, tok::period, SS,
2780 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
2781
2782 if (MemExpr.isInvalid())
2783 return ExprError();
2784
2785 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
2786 }
2787 }
2788
2789 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
2790 // class T and t1 does not satisfy the previous two items;
2791
2792 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
2793 }();
2794
2795 if (ObjectArg.isInvalid())
2796 return ExprError();
2797
2798 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
2799 tok::periodstar, ObjectArg.get(), Args[0]);
2800 if (BinOp.isInvalid())
2801 return ExprError();
2802
2803 if (MPT->isMemberDataPointer())
2804 return BinOp;
2805
2806 auto *MemCall = new (S.Context)
2808
2809 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
2810 Args.drop_front(2), TheCall->getRParenLoc());
2811 }
2812 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
2813 Args.drop_front(), TheCall->getRParenLoc());
2814}
2815
2816// Performs a similar job to Sema::UsualUnaryConversions, but without any
2817// implicit promotion of integral/enumeration types.
2819 // First, convert to an r-value.
2821 if (Res.isInvalid())
2822 return ExprError();
2823
2824 // Promote floating-point types.
2825 return S.UsualUnaryFPConversions(Res.get());
2826}
2827
2829 if (const auto *TyA = VecTy->getAs<VectorType>())
2830 return TyA->getElementType();
2831 if (VecTy->isSizelessVectorType())
2832 return VecTy->getSizelessVectorEltType(Context);
2833 return QualType();
2834}
2835
2837Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2838 CallExpr *TheCall) {
2839 ExprResult TheCallResult(TheCall);
2840
2841 // Find out if any arguments are required to be integer constant expressions.
2842 unsigned ICEArguments = 0;
2844 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2846 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2847
2848 // If any arguments are required to be ICE's, check and diagnose.
2849 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2850 // Skip arguments not required to be ICE's.
2851 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2852
2853 llvm::APSInt Result;
2854 // If we don't have enough arguments, continue so we can issue better
2855 // diagnostic in checkArgCount(...)
2856 if (ArgNo < TheCall->getNumArgs() &&
2857 BuiltinConstantArg(TheCall, ArgNo, Result))
2858 return true;
2859 ICEArguments &= ~(1 << ArgNo);
2860 }
2861
2862 FPOptions FPO;
2863 switch (BuiltinID) {
2864 case Builtin::BI__builtin_cpu_supports:
2865 case Builtin::BI__builtin_cpu_is:
2866 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2867 Context.getAuxTargetInfo(), BuiltinID))
2868 return ExprError();
2869 break;
2870 case Builtin::BI__builtin_cpu_init:
2871 if (!Context.getTargetInfo().supportsCpuInit()) {
2872 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2873 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2874 return ExprError();
2875 }
2876 break;
2877 case Builtin::BI__builtin___CFStringMakeConstantString:
2878 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2879 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2881 *this, BuiltinID, TheCall,
2882 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2883 return ExprError();
2884 assert(TheCall->getNumArgs() == 1 &&
2885 "Wrong # arguments to builtin CFStringMakeConstantString");
2886 if (ObjC().CheckObjCString(TheCall->getArg(0)))
2887 return ExprError();
2888 break;
2889 case Builtin::BI__builtin_ms_va_start:
2890 case Builtin::BI__builtin_stdarg_start:
2891 case Builtin::BI__builtin_va_start:
2892 case Builtin::BI__builtin_c23_va_start:
2893 if (BuiltinVAStart(BuiltinID, TheCall))
2894 return ExprError();
2895 break;
2896 case Builtin::BI__va_start: {
2897 switch (Context.getTargetInfo().getTriple().getArch()) {
2898 case llvm::Triple::aarch64:
2899 case llvm::Triple::arm:
2900 case llvm::Triple::thumb:
2901 if (BuiltinVAStartARMMicrosoft(TheCall))
2902 return ExprError();
2903 break;
2904 default:
2905 if (BuiltinVAStart(BuiltinID, TheCall))
2906 return ExprError();
2907 break;
2908 }
2909 break;
2910 }
2911
2912 // The acquire, release, and no fence variants are ARM and AArch64 only.
2913 case Builtin::BI_interlockedbittestandset_acq:
2914 case Builtin::BI_interlockedbittestandset_rel:
2915 case Builtin::BI_interlockedbittestandset_nf:
2916 case Builtin::BI_interlockedbittestandreset_acq:
2917 case Builtin::BI_interlockedbittestandreset_rel:
2918 case Builtin::BI_interlockedbittestandreset_nf:
2920 *this, TheCall,
2921 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2922 return ExprError();
2923 break;
2924
2925 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2926 case Builtin::BI_bittest64:
2927 case Builtin::BI_bittestandcomplement64:
2928 case Builtin::BI_bittestandreset64:
2929 case Builtin::BI_bittestandset64:
2930 case Builtin::BI_interlockedbittestandreset64:
2931 case Builtin::BI_interlockedbittestandset64:
2933 *this, TheCall,
2934 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2935 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2936 return ExprError();
2937 break;
2938
2939 // The 64-bit acquire, release, and no fence variants are AArch64 only.
2940 case Builtin::BI_interlockedbittestandreset64_acq:
2941 case Builtin::BI_interlockedbittestandreset64_rel:
2942 case Builtin::BI_interlockedbittestandreset64_nf:
2943 case Builtin::BI_interlockedbittestandset64_acq:
2944 case Builtin::BI_interlockedbittestandset64_rel:
2945 case Builtin::BI_interlockedbittestandset64_nf:
2946 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
2947 return ExprError();
2948 break;
2949
2950 case Builtin::BI__builtin_set_flt_rounds:
2952 *this, TheCall,
2953 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
2954 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
2955 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
2956 llvm::Triple::ppc64le}))
2957 return ExprError();
2958 break;
2959
2960 case Builtin::BI__builtin_isgreater:
2961 case Builtin::BI__builtin_isgreaterequal:
2962 case Builtin::BI__builtin_isless:
2963 case Builtin::BI__builtin_islessequal:
2964 case Builtin::BI__builtin_islessgreater:
2965 case Builtin::BI__builtin_isunordered:
2966 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2967 return ExprError();
2968 break;
2969 case Builtin::BI__builtin_fpclassify:
2970 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
2971 return ExprError();
2972 break;
2973 case Builtin::BI__builtin_isfpclass:
2974 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
2975 return ExprError();
2976 break;
2977 case Builtin::BI__builtin_isfinite:
2978 case Builtin::BI__builtin_isinf:
2979 case Builtin::BI__builtin_isinf_sign:
2980 case Builtin::BI__builtin_isnan:
2981 case Builtin::BI__builtin_issignaling:
2982 case Builtin::BI__builtin_isnormal:
2983 case Builtin::BI__builtin_issubnormal:
2984 case Builtin::BI__builtin_iszero:
2985 case Builtin::BI__builtin_signbit:
2986 case Builtin::BI__builtin_signbitf:
2987 case Builtin::BI__builtin_signbitl:
2988 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
2989 return ExprError();
2990 break;
2991 case Builtin::BI__builtin_shufflevector:
2992 return BuiltinShuffleVector(TheCall);
2993 // TheCall will be freed by the smart pointer here, but that's fine, since
2994 // BuiltinShuffleVector guts it, but then doesn't release it.
2995 case Builtin::BI__builtin_masked_load:
2996 case Builtin::BI__builtin_masked_expand_load:
2997 return BuiltinMaskedLoad(*this, TheCall);
2998 case Builtin::BI__builtin_masked_store:
2999 case Builtin::BI__builtin_masked_compress_store:
3000 return BuiltinMaskedStore(*this, TheCall);
3001 case Builtin::BI__builtin_masked_gather:
3002 return BuiltinMaskedGather(*this, TheCall);
3003 case Builtin::BI__builtin_masked_scatter:
3004 return BuiltinMaskedScatter(*this, TheCall);
3005 case Builtin::BI__builtin_invoke:
3006 return BuiltinInvoke(*this, TheCall);
3007 case Builtin::BI__builtin_prefetch:
3008 if (BuiltinPrefetch(TheCall))
3009 return ExprError();
3010 break;
3011 case Builtin::BI__builtin_alloca_with_align:
3012 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3013 if (BuiltinAllocaWithAlign(TheCall))
3014 return ExprError();
3015 [[fallthrough]];
3016 case Builtin::BI__builtin_alloca:
3017 case Builtin::BI__builtin_alloca_uninitialized:
3018 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
3019 << TheCall->getDirectCallee();
3020 if (getLangOpts().OpenCL) {
3021 builtinAllocaAddrSpace(*this, TheCall);
3022 }
3023 break;
3024 case Builtin::BI__builtin_infer_alloc_token:
3025 if (checkBuiltinInferAllocToken(*this, TheCall))
3026 return ExprError();
3027 break;
3028 case Builtin::BI__arithmetic_fence:
3029 if (BuiltinArithmeticFence(TheCall))
3030 return ExprError();
3031 break;
3032 case Builtin::BI__assume:
3033 case Builtin::BI__builtin_assume:
3034 if (BuiltinAssume(TheCall))
3035 return ExprError();
3036 break;
3037 case Builtin::BI__builtin_assume_aligned:
3038 if (BuiltinAssumeAligned(TheCall))
3039 return ExprError();
3040 break;
3041 case Builtin::BI__builtin_dynamic_object_size:
3042 case Builtin::BI__builtin_object_size:
3043 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
3044 return ExprError();
3045 break;
3046 case Builtin::BI__builtin_longjmp:
3047 if (BuiltinLongjmp(TheCall))
3048 return ExprError();
3049 break;
3050 case Builtin::BI__builtin_setjmp:
3051 if (BuiltinSetjmp(TheCall))
3052 return ExprError();
3053 break;
3054 case Builtin::BI__builtin_complex:
3055 if (BuiltinComplex(TheCall))
3056 return ExprError();
3057 break;
3058 case Builtin::BI__builtin_classify_type:
3059 case Builtin::BI__builtin_constant_p: {
3060 if (checkArgCount(TheCall, 1))
3061 return true;
3063 if (Arg.isInvalid()) return true;
3064 TheCall->setArg(0, Arg.get());
3065 TheCall->setType(Context.IntTy);
3066 break;
3067 }
3068 case Builtin::BI__builtin_launder:
3069 return BuiltinLaunder(*this, TheCall);
3070 case Builtin::BI__builtin_is_within_lifetime:
3071 return BuiltinIsWithinLifetime(*this, TheCall);
3072 case Builtin::BI__builtin_trivially_relocate:
3073 return BuiltinTriviallyRelocate(*this, TheCall);
3074
3075 case Builtin::BI__sync_fetch_and_add:
3076 case Builtin::BI__sync_fetch_and_add_1:
3077 case Builtin::BI__sync_fetch_and_add_2:
3078 case Builtin::BI__sync_fetch_and_add_4:
3079 case Builtin::BI__sync_fetch_and_add_8:
3080 case Builtin::BI__sync_fetch_and_add_16:
3081 case Builtin::BI__sync_fetch_and_sub:
3082 case Builtin::BI__sync_fetch_and_sub_1:
3083 case Builtin::BI__sync_fetch_and_sub_2:
3084 case Builtin::BI__sync_fetch_and_sub_4:
3085 case Builtin::BI__sync_fetch_and_sub_8:
3086 case Builtin::BI__sync_fetch_and_sub_16:
3087 case Builtin::BI__sync_fetch_and_or:
3088 case Builtin::BI__sync_fetch_and_or_1:
3089 case Builtin::BI__sync_fetch_and_or_2:
3090 case Builtin::BI__sync_fetch_and_or_4:
3091 case Builtin::BI__sync_fetch_and_or_8:
3092 case Builtin::BI__sync_fetch_and_or_16:
3093 case Builtin::BI__sync_fetch_and_and:
3094 case Builtin::BI__sync_fetch_and_and_1:
3095 case Builtin::BI__sync_fetch_and_and_2:
3096 case Builtin::BI__sync_fetch_and_and_4:
3097 case Builtin::BI__sync_fetch_and_and_8:
3098 case Builtin::BI__sync_fetch_and_and_16:
3099 case Builtin::BI__sync_fetch_and_xor:
3100 case Builtin::BI__sync_fetch_and_xor_1:
3101 case Builtin::BI__sync_fetch_and_xor_2:
3102 case Builtin::BI__sync_fetch_and_xor_4:
3103 case Builtin::BI__sync_fetch_and_xor_8:
3104 case Builtin::BI__sync_fetch_and_xor_16:
3105 case Builtin::BI__sync_fetch_and_nand:
3106 case Builtin::BI__sync_fetch_and_nand_1:
3107 case Builtin::BI__sync_fetch_and_nand_2:
3108 case Builtin::BI__sync_fetch_and_nand_4:
3109 case Builtin::BI__sync_fetch_and_nand_8:
3110 case Builtin::BI__sync_fetch_and_nand_16:
3111 case Builtin::BI__sync_add_and_fetch:
3112 case Builtin::BI__sync_add_and_fetch_1:
3113 case Builtin::BI__sync_add_and_fetch_2:
3114 case Builtin::BI__sync_add_and_fetch_4:
3115 case Builtin::BI__sync_add_and_fetch_8:
3116 case Builtin::BI__sync_add_and_fetch_16:
3117 case Builtin::BI__sync_sub_and_fetch:
3118 case Builtin::BI__sync_sub_and_fetch_1:
3119 case Builtin::BI__sync_sub_and_fetch_2:
3120 case Builtin::BI__sync_sub_and_fetch_4:
3121 case Builtin::BI__sync_sub_and_fetch_8:
3122 case Builtin::BI__sync_sub_and_fetch_16:
3123 case Builtin::BI__sync_and_and_fetch:
3124 case Builtin::BI__sync_and_and_fetch_1:
3125 case Builtin::BI__sync_and_and_fetch_2:
3126 case Builtin::BI__sync_and_and_fetch_4:
3127 case Builtin::BI__sync_and_and_fetch_8:
3128 case Builtin::BI__sync_and_and_fetch_16:
3129 case Builtin::BI__sync_or_and_fetch:
3130 case Builtin::BI__sync_or_and_fetch_1:
3131 case Builtin::BI__sync_or_and_fetch_2:
3132 case Builtin::BI__sync_or_and_fetch_4:
3133 case Builtin::BI__sync_or_and_fetch_8:
3134 case Builtin::BI__sync_or_and_fetch_16:
3135 case Builtin::BI__sync_xor_and_fetch:
3136 case Builtin::BI__sync_xor_and_fetch_1:
3137 case Builtin::BI__sync_xor_and_fetch_2:
3138 case Builtin::BI__sync_xor_and_fetch_4:
3139 case Builtin::BI__sync_xor_and_fetch_8:
3140 case Builtin::BI__sync_xor_and_fetch_16:
3141 case Builtin::BI__sync_nand_and_fetch:
3142 case Builtin::BI__sync_nand_and_fetch_1:
3143 case Builtin::BI__sync_nand_and_fetch_2:
3144 case Builtin::BI__sync_nand_and_fetch_4:
3145 case Builtin::BI__sync_nand_and_fetch_8:
3146 case Builtin::BI__sync_nand_and_fetch_16:
3147 case Builtin::BI__sync_val_compare_and_swap:
3148 case Builtin::BI__sync_val_compare_and_swap_1:
3149 case Builtin::BI__sync_val_compare_and_swap_2:
3150 case Builtin::BI__sync_val_compare_and_swap_4:
3151 case Builtin::BI__sync_val_compare_and_swap_8:
3152 case Builtin::BI__sync_val_compare_and_swap_16:
3153 case Builtin::BI__sync_bool_compare_and_swap:
3154 case Builtin::BI__sync_bool_compare_and_swap_1:
3155 case Builtin::BI__sync_bool_compare_and_swap_2:
3156 case Builtin::BI__sync_bool_compare_and_swap_4:
3157 case Builtin::BI__sync_bool_compare_and_swap_8:
3158 case Builtin::BI__sync_bool_compare_and_swap_16:
3159 case Builtin::BI__sync_lock_test_and_set:
3160 case Builtin::BI__sync_lock_test_and_set_1:
3161 case Builtin::BI__sync_lock_test_and_set_2:
3162 case Builtin::BI__sync_lock_test_and_set_4:
3163 case Builtin::BI__sync_lock_test_and_set_8:
3164 case Builtin::BI__sync_lock_test_and_set_16:
3165 case Builtin::BI__sync_lock_release:
3166 case Builtin::BI__sync_lock_release_1:
3167 case Builtin::BI__sync_lock_release_2:
3168 case Builtin::BI__sync_lock_release_4:
3169 case Builtin::BI__sync_lock_release_8:
3170 case Builtin::BI__sync_lock_release_16:
3171 case Builtin::BI__sync_swap:
3172 case Builtin::BI__sync_swap_1:
3173 case Builtin::BI__sync_swap_2:
3174 case Builtin::BI__sync_swap_4:
3175 case Builtin::BI__sync_swap_8:
3176 case Builtin::BI__sync_swap_16:
3177 return BuiltinAtomicOverloaded(TheCallResult);
3178 case Builtin::BI__sync_synchronize:
3179 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
3180 << TheCall->getCallee()->getSourceRange();
3181 break;
3182 case Builtin::BI__builtin_nontemporal_load:
3183 case Builtin::BI__builtin_nontemporal_store:
3184 return BuiltinNontemporalOverloaded(TheCallResult);
3185 case Builtin::BI__builtin_memcpy_inline: {
3186 clang::Expr *SizeOp = TheCall->getArg(2);
3187 // We warn about copying to or from `nullptr` pointers when `size` is
3188 // greater than 0. When `size` is value dependent we cannot evaluate its
3189 // value so we bail out.
3190 if (SizeOp->isValueDependent())
3191 break;
3192 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
3193 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3194 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
3195 }
3196 break;
3197 }
3198 case Builtin::BI__builtin_memset_inline: {
3199 clang::Expr *SizeOp = TheCall->getArg(2);
3200 // We warn about filling to `nullptr` pointers when `size` is greater than
3201 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3202 // out.
3203 if (SizeOp->isValueDependent())
3204 break;
3205 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
3206 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3207 break;
3208 }
3209#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3210 case Builtin::BI##ID: \
3211 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3212#include "clang/Basic/Builtins.inc"
3213 case Builtin::BI__annotation:
3214 if (BuiltinMSVCAnnotation(*this, TheCall))
3215 return ExprError();
3216 break;
3217 case Builtin::BI__builtin_annotation:
3218 if (BuiltinAnnotation(*this, TheCall))
3219 return ExprError();
3220 break;
3221 case Builtin::BI__builtin_addressof:
3222 if (BuiltinAddressof(*this, TheCall))
3223 return ExprError();
3224 break;
3225 case Builtin::BI__builtin_function_start:
3226 if (BuiltinFunctionStart(*this, TheCall))
3227 return ExprError();
3228 break;
3229 case Builtin::BI__builtin_is_aligned:
3230 case Builtin::BI__builtin_align_up:
3231 case Builtin::BI__builtin_align_down:
3232 if (BuiltinAlignment(*this, TheCall, BuiltinID))
3233 return ExprError();
3234 break;
3235 case Builtin::BI__builtin_add_overflow:
3236 case Builtin::BI__builtin_sub_overflow:
3237 case Builtin::BI__builtin_mul_overflow:
3238 if (BuiltinOverflow(*this, TheCall, BuiltinID))
3239 return ExprError();
3240 break;
3241 case Builtin::BI__builtin_operator_new:
3242 case Builtin::BI__builtin_operator_delete: {
3243 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3244 ExprResult Res =
3245 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3246 return Res;
3247 }
3248 case Builtin::BI__builtin_dump_struct:
3249 return BuiltinDumpStruct(*this, TheCall);
3250 case Builtin::BI__builtin_expect_with_probability: {
3251 // We first want to ensure we are called with 3 arguments
3252 if (checkArgCount(TheCall, 3))
3253 return ExprError();
3254 // then check probability is constant float in range [0.0, 1.0]
3255 const Expr *ProbArg = TheCall->getArg(2);
3256 SmallVector<PartialDiagnosticAt, 8> Notes;
3257 Expr::EvalResult Eval;
3258 Eval.Diag = &Notes;
3259 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3260 !Eval.Val.isFloat()) {
3261 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3262 << ProbArg->getSourceRange();
3263 for (const PartialDiagnosticAt &PDiag : Notes)
3264 Diag(PDiag.first, PDiag.second);
3265 return ExprError();
3266 }
3267 llvm::APFloat Probability = Eval.Val.getFloat();
3268 bool LoseInfo = false;
3269 Probability.convert(llvm::APFloat::IEEEdouble(),
3270 llvm::RoundingMode::Dynamic, &LoseInfo);
3271 if (!(Probability >= llvm::APFloat(0.0) &&
3272 Probability <= llvm::APFloat(1.0))) {
3273 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3274 << ProbArg->getSourceRange();
3275 return ExprError();
3276 }
3277 break;
3278 }
3279 case Builtin::BI__builtin_preserve_access_index:
3280 if (BuiltinPreserveAI(*this, TheCall))
3281 return ExprError();
3282 break;
3283 case Builtin::BI__builtin_call_with_static_chain:
3284 if (BuiltinCallWithStaticChain(*this, TheCall))
3285 return ExprError();
3286 break;
3287 case Builtin::BI__exception_code:
3288 case Builtin::BI_exception_code:
3289 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3290 diag::err_seh___except_block))
3291 return ExprError();
3292 break;
3293 case Builtin::BI__exception_info:
3294 case Builtin::BI_exception_info:
3295 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3296 diag::err_seh___except_filter))
3297 return ExprError();
3298 break;
3299 case Builtin::BI__GetExceptionInfo:
3300 if (checkArgCount(TheCall, 1))
3301 return ExprError();
3302
3304 TheCall->getBeginLoc(),
3305 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3306 TheCall))
3307 return ExprError();
3308
3309 TheCall->setType(Context.VoidPtrTy);
3310 break;
3311 case Builtin::BIaddressof:
3312 case Builtin::BI__addressof:
3313 case Builtin::BIforward:
3314 case Builtin::BIforward_like:
3315 case Builtin::BImove:
3316 case Builtin::BImove_if_noexcept:
3317 case Builtin::BIas_const: {
3318 // These are all expected to be of the form
3319 // T &/&&/* f(U &/&&)
3320 // where T and U only differ in qualification.
3321 if (checkArgCount(TheCall, 1))
3322 return ExprError();
3323 QualType Param = FDecl->getParamDecl(0)->getType();
3324 QualType Result = FDecl->getReturnType();
3325 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3326 BuiltinID == Builtin::BI__addressof;
3327 if (!(Param->isReferenceType() &&
3328 (ReturnsPointer ? Result->isAnyPointerType()
3329 : Result->isReferenceType()) &&
3330 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3331 Result->getPointeeType()))) {
3332 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3333 << FDecl;
3334 return ExprError();
3335 }
3336 break;
3337 }
3338 case Builtin::BI__builtin_ptrauth_strip:
3339 return PointerAuthStrip(*this, TheCall);
3340 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3341 return PointerAuthBlendDiscriminator(*this, TheCall);
3342 case Builtin::BI__builtin_ptrauth_sign_constant:
3343 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3344 /*RequireConstant=*/true);
3345 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3346 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3347 /*RequireConstant=*/false);
3348 case Builtin::BI__builtin_ptrauth_auth:
3349 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3350 /*RequireConstant=*/false);
3351 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3352 return PointerAuthSignGenericData(*this, TheCall);
3353 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3354 return PointerAuthAuthAndResign(*this, TheCall);
3355 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3356 return PointerAuthAuthLoadRelativeAndSign(*this, TheCall);
3357 case Builtin::BI__builtin_ptrauth_string_discriminator:
3358 return PointerAuthStringDiscriminator(*this, TheCall);
3359
3360 case Builtin::BI__builtin_get_vtable_pointer:
3361 return GetVTablePointer(*this, TheCall);
3362
3363 // OpenCL v2.0, s6.13.16 - Pipe functions
3364 case Builtin::BIread_pipe:
3365 case Builtin::BIwrite_pipe:
3366 // Since those two functions are declared with var args, we need a semantic
3367 // check for the argument.
3368 if (OpenCL().checkBuiltinRWPipe(TheCall))
3369 return ExprError();
3370 break;
3371 case Builtin::BIreserve_read_pipe:
3372 case Builtin::BIreserve_write_pipe:
3373 case Builtin::BIwork_group_reserve_read_pipe:
3374 case Builtin::BIwork_group_reserve_write_pipe:
3375 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3376 return ExprError();
3377 break;
3378 case Builtin::BIsub_group_reserve_read_pipe:
3379 case Builtin::BIsub_group_reserve_write_pipe:
3380 if (OpenCL().checkSubgroupExt(TheCall) ||
3381 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3382 return ExprError();
3383 break;
3384 case Builtin::BIcommit_read_pipe:
3385 case Builtin::BIcommit_write_pipe:
3386 case Builtin::BIwork_group_commit_read_pipe:
3387 case Builtin::BIwork_group_commit_write_pipe:
3388 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3389 return ExprError();
3390 break;
3391 case Builtin::BIsub_group_commit_read_pipe:
3392 case Builtin::BIsub_group_commit_write_pipe:
3393 if (OpenCL().checkSubgroupExt(TheCall) ||
3394 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3395 return ExprError();
3396 break;
3397 case Builtin::BIget_pipe_num_packets:
3398 case Builtin::BIget_pipe_max_packets:
3399 if (OpenCL().checkBuiltinPipePackets(TheCall))
3400 return ExprError();
3401 break;
3402 case Builtin::BIto_global:
3403 case Builtin::BIto_local:
3404 case Builtin::BIto_private:
3405 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3406 return ExprError();
3407 break;
3408 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3409 case Builtin::BIenqueue_kernel:
3410 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3411 return ExprError();
3412 break;
3413 case Builtin::BIget_kernel_work_group_size:
3414 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3415 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3416 return ExprError();
3417 break;
3418 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3419 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3420 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3421 return ExprError();
3422 break;
3423 case Builtin::BI__builtin_os_log_format:
3424 Cleanup.setExprNeedsCleanups(true);
3425 [[fallthrough]];
3426 case Builtin::BI__builtin_os_log_format_buffer_size:
3427 if (BuiltinOSLogFormat(TheCall))
3428 return ExprError();
3429 break;
3430 case Builtin::BI__builtin_frame_address:
3431 case Builtin::BI__builtin_return_address: {
3432 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3433 return ExprError();
3434
3435 // -Wframe-address warning if non-zero passed to builtin
3436 // return/frame address.
3437 Expr::EvalResult Result;
3438 if (!TheCall->getArg(0)->isValueDependent() &&
3439 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3440 Result.Val.getInt() != 0)
3441 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3442 << ((BuiltinID == Builtin::BI__builtin_return_address)
3443 ? "__builtin_return_address"
3444 : "__builtin_frame_address")
3445 << TheCall->getSourceRange();
3446 break;
3447 }
3448
3449 case Builtin::BI__builtin_nondeterministic_value: {
3450 if (BuiltinNonDeterministicValue(TheCall))
3451 return ExprError();
3452 break;
3453 }
3454
3455 // __builtin_elementwise_abs restricts the element type to signed integers or
3456 // floating point types only.
3457 case Builtin::BI__builtin_elementwise_abs:
3460 return ExprError();
3461 break;
3462
3463 // These builtins restrict the element type to floating point
3464 // types only.
3465 case Builtin::BI__builtin_elementwise_acos:
3466 case Builtin::BI__builtin_elementwise_asin:
3467 case Builtin::BI__builtin_elementwise_atan:
3468 case Builtin::BI__builtin_elementwise_ceil:
3469 case Builtin::BI__builtin_elementwise_cos:
3470 case Builtin::BI__builtin_elementwise_cosh:
3471 case Builtin::BI__builtin_elementwise_exp:
3472 case Builtin::BI__builtin_elementwise_exp2:
3473 case Builtin::BI__builtin_elementwise_exp10:
3474 case Builtin::BI__builtin_elementwise_floor:
3475 case Builtin::BI__builtin_elementwise_log:
3476 case Builtin::BI__builtin_elementwise_log2:
3477 case Builtin::BI__builtin_elementwise_log10:
3478 case Builtin::BI__builtin_elementwise_roundeven:
3479 case Builtin::BI__builtin_elementwise_round:
3480 case Builtin::BI__builtin_elementwise_rint:
3481 case Builtin::BI__builtin_elementwise_nearbyint:
3482 case Builtin::BI__builtin_elementwise_sin:
3483 case Builtin::BI__builtin_elementwise_sinh:
3484 case Builtin::BI__builtin_elementwise_sqrt:
3485 case Builtin::BI__builtin_elementwise_tan:
3486 case Builtin::BI__builtin_elementwise_tanh:
3487 case Builtin::BI__builtin_elementwise_trunc:
3488 case Builtin::BI__builtin_elementwise_canonicalize:
3491 return ExprError();
3492 break;
3493 case Builtin::BI__builtin_elementwise_fma:
3494 if (BuiltinElementwiseTernaryMath(TheCall))
3495 return ExprError();
3496 break;
3497
3498 case Builtin::BI__builtin_elementwise_ldexp: {
3499 if (checkArgCount(TheCall, 2))
3500 return ExprError();
3501
3502 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
3503 if (A.isInvalid())
3504 return ExprError();
3505 QualType TyA = A.get()->getType();
3506 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
3508 return ExprError();
3509
3510 ExprResult Exp = UsualUnaryConversions(TheCall->getArg(1));
3511 if (Exp.isInvalid())
3512 return ExprError();
3513 QualType TyExp = Exp.get()->getType();
3514 if (checkMathBuiltinElementType(*this, Exp.get()->getBeginLoc(), TyExp,
3516 2))
3517 return ExprError();
3518
3519 // Check the two arguments are either scalars or vectors of equal length.
3520 const auto *Vec0 = TyA->getAs<VectorType>();
3521 const auto *Vec1 = TyExp->getAs<VectorType>();
3522 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3523 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3524 if (Arg0Length != Arg1Length) {
3525 Diag(Exp.get()->getBeginLoc(),
3526 diag::err_typecheck_vector_lengths_not_equal)
3527 << TyA << TyExp << A.get()->getSourceRange()
3528 << Exp.get()->getSourceRange();
3529 return ExprError();
3530 }
3531
3532 TheCall->setArg(0, A.get());
3533 TheCall->setArg(1, Exp.get());
3534 TheCall->setType(TyA);
3535 break;
3536 }
3537
3538 // These builtins restrict the element type to floating point
3539 // types only, and take in two arguments.
3540 case Builtin::BI__builtin_elementwise_minnum:
3541 case Builtin::BI__builtin_elementwise_maxnum:
3542 case Builtin::BI__builtin_elementwise_minimum:
3543 case Builtin::BI__builtin_elementwise_maximum:
3544 case Builtin::BI__builtin_elementwise_minimumnum:
3545 case Builtin::BI__builtin_elementwise_maximumnum:
3546 case Builtin::BI__builtin_elementwise_atan2:
3547 case Builtin::BI__builtin_elementwise_fmod:
3548 case Builtin::BI__builtin_elementwise_pow:
3549 if (BuiltinElementwiseMath(TheCall,
3551 return ExprError();
3552 break;
3553 // These builtins restrict the element type to integer
3554 // types only.
3555 case Builtin::BI__builtin_elementwise_add_sat:
3556 case Builtin::BI__builtin_elementwise_sub_sat:
3557 if (BuiltinElementwiseMath(TheCall,
3559 return ExprError();
3560 break;
3561 case Builtin::BI__builtin_elementwise_fshl:
3562 case Builtin::BI__builtin_elementwise_fshr:
3565 return ExprError();
3566 break;
3567 case Builtin::BI__builtin_elementwise_min:
3568 case Builtin::BI__builtin_elementwise_max: {
3569 if (BuiltinElementwiseMath(TheCall))
3570 return ExprError();
3571 Expr *Arg0 = TheCall->getArg(0);
3572 Expr *Arg1 = TheCall->getArg(1);
3573 QualType Ty0 = Arg0->getType();
3574 QualType Ty1 = Arg1->getType();
3575 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
3576 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
3577 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
3578 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
3579 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
3580 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin_no_suggestion)
3581 << Context.BuiltinInfo.getQuotedName(BuiltinID);
3582 break;
3583 }
3584 case Builtin::BI__builtin_elementwise_popcount:
3585 case Builtin::BI__builtin_elementwise_bitreverse:
3588 return ExprError();
3589 break;
3590 case Builtin::BI__builtin_elementwise_copysign: {
3591 if (checkArgCount(TheCall, 2))
3592 return ExprError();
3593
3594 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3595 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3596 if (Magnitude.isInvalid() || Sign.isInvalid())
3597 return ExprError();
3598
3599 QualType MagnitudeTy = Magnitude.get()->getType();
3600 QualType SignTy = Sign.get()->getType();
3602 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
3605 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
3607 return ExprError();
3608 }
3609
3610 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3611 return Diag(Sign.get()->getBeginLoc(),
3612 diag::err_typecheck_call_different_arg_types)
3613 << MagnitudeTy << SignTy;
3614 }
3615
3616 TheCall->setArg(0, Magnitude.get());
3617 TheCall->setArg(1, Sign.get());
3618 TheCall->setType(Magnitude.get()->getType());
3619 break;
3620 }
3621 case Builtin::BI__builtin_elementwise_clzg:
3622 case Builtin::BI__builtin_elementwise_ctzg:
3623 // These builtins can be unary or binary. Note for empty calls we call the
3624 // unary checker in order to not emit an error that says the function
3625 // expects 2 arguments, which would be misleading.
3626 if (TheCall->getNumArgs() <= 1) {
3629 return ExprError();
3630 } else if (BuiltinElementwiseMath(
3632 return ExprError();
3633 break;
3634 case Builtin::BI__builtin_reduce_max:
3635 case Builtin::BI__builtin_reduce_min: {
3636 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3637 return ExprError();
3638
3639 const Expr *Arg = TheCall->getArg(0);
3640 const auto *TyA = Arg->getType()->getAs<VectorType>();
3641
3642 QualType ElTy;
3643 if (TyA)
3644 ElTy = TyA->getElementType();
3645 else if (Arg->getType()->isSizelessVectorType())
3647
3648 if (ElTy.isNull()) {
3649 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3650 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3651 << Arg->getType();
3652 return ExprError();
3653 }
3654
3655 TheCall->setType(ElTy);
3656 break;
3657 }
3658 case Builtin::BI__builtin_reduce_maximum:
3659 case Builtin::BI__builtin_reduce_minimum: {
3660 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3661 return ExprError();
3662
3663 const Expr *Arg = TheCall->getArg(0);
3664 const auto *TyA = Arg->getType()->getAs<VectorType>();
3665
3666 QualType ElTy;
3667 if (TyA)
3668 ElTy = TyA->getElementType();
3669 else if (Arg->getType()->isSizelessVectorType())
3671
3672 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3673 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3674 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3675 << Arg->getType();
3676 return ExprError();
3677 }
3678
3679 TheCall->setType(ElTy);
3680 break;
3681 }
3682
3683 // These builtins support vectors of integers only.
3684 // TODO: ADD/MUL should support floating-point types.
3685 case Builtin::BI__builtin_reduce_add:
3686 case Builtin::BI__builtin_reduce_mul:
3687 case Builtin::BI__builtin_reduce_xor:
3688 case Builtin::BI__builtin_reduce_or:
3689 case Builtin::BI__builtin_reduce_and: {
3690 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3691 return ExprError();
3692
3693 const Expr *Arg = TheCall->getArg(0);
3694
3695 QualType ElTy = getVectorElementType(Context, Arg->getType());
3696 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3697 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3698 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3699 << Arg->getType();
3700 return ExprError();
3701 }
3702
3703 TheCall->setType(ElTy);
3704 break;
3705 }
3706
3707 case Builtin::BI__builtin_reduce_assoc_fadd:
3708 case Builtin::BI__builtin_reduce_in_order_fadd: {
3709 // For in-order reductions require the user to specify the start value.
3710 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
3711 if (InOrder ? checkArgCount(TheCall, 2) : checkArgCountRange(TheCall, 1, 2))
3712 return ExprError();
3713
3714 ExprResult Vec = UsualUnaryConversions(TheCall->getArg(0));
3715 if (Vec.isInvalid())
3716 return ExprError();
3717
3718 TheCall->setArg(0, Vec.get());
3719
3720 QualType ElTy = getVectorElementType(Context, Vec.get()->getType());
3721 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
3722 Diag(Vec.get()->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3723 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3724 << Vec.get()->getType();
3725 return ExprError();
3726 }
3727
3728 if (TheCall->getNumArgs() == 2) {
3729 ExprResult StartValue = UsualUnaryConversions(TheCall->getArg(1));
3730 if (StartValue.isInvalid())
3731 return ExprError();
3732
3733 if (!StartValue.get()->getType()->isRealFloatingType()) {
3734 Diag(StartValue.get()->getBeginLoc(),
3735 diag::err_builtin_invalid_arg_type)
3736 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
3737 << StartValue.get()->getType();
3738 return ExprError();
3739 }
3740 TheCall->setArg(1, StartValue.get());
3741 }
3742
3743 TheCall->setType(ElTy);
3744 break;
3745 }
3746
3747 case Builtin::BI__builtin_matrix_transpose:
3748 return BuiltinMatrixTranspose(TheCall, TheCallResult);
3749
3750 case Builtin::BI__builtin_matrix_column_major_load:
3751 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
3752
3753 case Builtin::BI__builtin_matrix_column_major_store:
3754 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
3755
3756 case Builtin::BI__builtin_verbose_trap:
3757 if (!checkBuiltinVerboseTrap(TheCall, *this))
3758 return ExprError();
3759 break;
3760
3761 case Builtin::BI__builtin_get_device_side_mangled_name: {
3762 auto Check = [](CallExpr *TheCall) {
3763 if (TheCall->getNumArgs() != 1)
3764 return false;
3765 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
3766 if (!DRE)
3767 return false;
3768 auto *D = DRE->getDecl();
3769 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
3770 return false;
3771 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3772 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3773 };
3774 if (!Check(TheCall)) {
3775 Diag(TheCall->getBeginLoc(),
3776 diag::err_hip_invalid_args_builtin_mangled_name);
3777 return ExprError();
3778 }
3779 break;
3780 }
3781 case Builtin::BI__builtin_bswapg:
3782 if (BuiltinBswapg(*this, TheCall))
3783 return ExprError();
3784 break;
3785 case Builtin::BI__builtin_bitreverseg:
3786 if (BuiltinBitreverseg(*this, TheCall))
3787 return ExprError();
3788 break;
3789 case Builtin::BI__builtin_popcountg:
3790 if (BuiltinPopcountg(*this, TheCall))
3791 return ExprError();
3792 break;
3793 case Builtin::BI__builtin_clzg:
3794 case Builtin::BI__builtin_ctzg:
3795 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
3796 return ExprError();
3797 break;
3798
3799 case Builtin::BI__builtin_stdc_rotate_left:
3800 case Builtin::BI__builtin_stdc_rotate_right:
3801 if (BuiltinRotateGeneric(*this, TheCall))
3802 return ExprError();
3803 break;
3804
3805 case Builtin::BI__builtin_allow_runtime_check: {
3806 Expr *Arg = TheCall->getArg(0);
3807 // Check if the argument is a string literal.
3809 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3810 << Arg->getSourceRange();
3811 return ExprError();
3812 }
3813 break;
3814 }
3815
3816 case Builtin::BI__builtin_allow_sanitize_check: {
3817 if (checkArgCount(TheCall, 1))
3818 return ExprError();
3819
3820 Expr *Arg = TheCall->getArg(0);
3821 // Check if the argument is a string literal.
3822 const StringLiteral *SanitizerName =
3823 dyn_cast<StringLiteral>(Arg->IgnoreParenImpCasts());
3824 if (!SanitizerName) {
3825 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3826 << Arg->getSourceRange();
3827 return ExprError();
3828 }
3829 // Validate the sanitizer name.
3830 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
3831 .Cases({"address", "thread", "memory", "hwaddress",
3832 "kernel-address", "kernel-memory", "kernel-hwaddress"},
3833 true)
3834 .Default(false)) {
3835 Diag(TheCall->getBeginLoc(), diag::err_invalid_builtin_argument)
3836 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
3837 << Arg->getSourceRange();
3838 return ExprError();
3839 }
3840 break;
3841 }
3842 case Builtin::BI__builtin_counted_by_ref:
3843 if (BuiltinCountedByRef(TheCall))
3844 return ExprError();
3845 break;
3846 }
3847
3848 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
3849 return ExprError();
3850
3851 // Since the target specific builtins for each arch overlap, only check those
3852 // of the arch we are compiling for.
3853 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
3854 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
3855 assert(Context.getAuxTargetInfo() &&
3856 "Aux Target Builtin, but not an aux target?");
3857
3858 if (CheckTSBuiltinFunctionCall(
3859 *Context.getAuxTargetInfo(),
3860 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
3861 return ExprError();
3862 } else {
3863 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
3864 TheCall))
3865 return ExprError();
3866 }
3867 }
3868
3869 return TheCallResult;
3870}
3871
3872bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3873 llvm::APSInt Result;
3874 // We can't check the value of a dependent argument.
3875 Expr *Arg = TheCall->getArg(ArgNum);
3876 if (Arg->isTypeDependent() || Arg->isValueDependent())
3877 return false;
3878
3879 // Check constant-ness first.
3880 if (BuiltinConstantArg(TheCall, ArgNum, Result))
3881 return true;
3882
3883 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3884 if (Result.isShiftedMask() || (~Result).isShiftedMask())
3885 return false;
3886
3887 return Diag(TheCall->getBeginLoc(),
3888 diag::err_argument_not_contiguous_bit_field)
3889 << ArgNum << Arg->getSourceRange();
3890}
3891
3892bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
3893 unsigned FirstArg, FormatStringInfo *FSI) {
3894 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
3895 bool IsVariadic = false;
3896 if (const FunctionType *FnTy = D->getFunctionType())
3897 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
3898 else if (const auto *BD = dyn_cast<BlockDecl>(D))
3899 IsVariadic = BD->isVariadic();
3900 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
3901 IsVariadic = OMD->isVariadic();
3902
3903 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
3904 IsVariadic, FSI);
3905}
3906
3907bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
3908 bool HasImplicitThisParam, bool IsVariadic,
3909 FormatStringInfo *FSI) {
3910 if (FirstArg == 0)
3912 else if (IsVariadic)
3914 else
3916 FSI->FormatIdx = FormatIdx - 1;
3917 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
3918
3919 // The way the format attribute works in GCC, the implicit this argument
3920 // of member functions is counted. However, it doesn't appear in our own
3921 // lists, so decrement format_idx in that case.
3922 if (HasImplicitThisParam) {
3923 if(FSI->FormatIdx == 0)
3924 return false;
3925 --FSI->FormatIdx;
3926 if (FSI->FirstDataArg != 0)
3927 --FSI->FirstDataArg;
3928 }
3929 return true;
3930}
3931
3932/// Checks if a the given expression evaluates to null.
3933///
3934/// Returns true if the value evaluates to null.
3935static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3936 // Treat (smart) pointers constructed from nullptr as null, whether we can
3937 // const-evaluate them or not.
3938 // This must happen first: the smart pointer expr might have _Nonnull type!
3942 return true;
3943
3944 // If the expression has non-null type, it doesn't evaluate to null.
3945 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
3946 if (*nullability == NullabilityKind::NonNull)
3947 return false;
3948 }
3949
3950 // As a special case, transparent unions initialized with zero are
3951 // considered null for the purposes of the nonnull attribute.
3952 if (const RecordType *UT = Expr->getType()->getAsUnionType();
3953 UT &&
3954 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
3955 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
3956 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
3957 Expr = ILE->getInit(0);
3958 }
3959
3960 bool Result;
3961 return (!Expr->isValueDependent() &&
3963 !Result);
3964}
3965
3967 const Expr *ArgExpr,
3968 SourceLocation CallSiteLoc) {
3969 if (CheckNonNullExpr(S, ArgExpr))
3970 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3971 S.PDiag(diag::warn_null_arg)
3972 << ArgExpr->getSourceRange());
3973}
3974
3975/// Determine whether the given type has a non-null nullability annotation.
3977 if (auto nullability = type->getNullability())
3978 return *nullability == NullabilityKind::NonNull;
3979
3980 return false;
3981}
3982
3984 const NamedDecl *FDecl,
3985 const FunctionProtoType *Proto,
3987 SourceLocation CallSiteLoc) {
3988 assert((FDecl || Proto) && "Need a function declaration or prototype");
3989
3990 // Already checked by constant evaluator.
3992 return;
3993 // Check the attributes attached to the method/function itself.
3994 llvm::SmallBitVector NonNullArgs;
3995 if (FDecl) {
3996 // Handle the nonnull attribute on the function/method declaration itself.
3997 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3998 if (!NonNull->args_size()) {
3999 // Easy case: all pointer arguments are nonnull.
4000 for (const auto *Arg : Args)
4001 if (S.isValidPointerAttrType(Arg->getType()))
4002 CheckNonNullArgument(S, Arg, CallSiteLoc);
4003 return;
4004 }
4005
4006 for (const ParamIdx &Idx : NonNull->args()) {
4007 unsigned IdxAST = Idx.getASTIndex();
4008 if (IdxAST >= Args.size())
4009 continue;
4010 if (NonNullArgs.empty())
4011 NonNullArgs.resize(Args.size());
4012 NonNullArgs.set(IdxAST);
4013 }
4014 }
4015 }
4016
4017 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4018 // Handle the nonnull attribute on the parameters of the
4019 // function/method.
4021 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4022 parms = FD->parameters();
4023 else
4024 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4025
4026 unsigned ParamIndex = 0;
4027 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4028 I != E; ++I, ++ParamIndex) {
4029 const ParmVarDecl *PVD = *I;
4030 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
4031 if (NonNullArgs.empty())
4032 NonNullArgs.resize(Args.size());
4033
4034 NonNullArgs.set(ParamIndex);
4035 }
4036 }
4037 } else {
4038 // If we have a non-function, non-method declaration but no
4039 // function prototype, try to dig out the function prototype.
4040 if (!Proto) {
4041 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4042 QualType type = VD->getType().getNonReferenceType();
4043 if (auto pointerType = type->getAs<PointerType>())
4044 type = pointerType->getPointeeType();
4045 else if (auto blockType = type->getAs<BlockPointerType>())
4046 type = blockType->getPointeeType();
4047 // FIXME: data member pointers?
4048
4049 // Dig out the function prototype, if there is one.
4050 Proto = type->getAs<FunctionProtoType>();
4051 }
4052 }
4053
4054 // Fill in non-null argument information from the nullability
4055 // information on the parameter types (if we have them).
4056 if (Proto) {
4057 unsigned Index = 0;
4058 for (auto paramType : Proto->getParamTypes()) {
4059 if (isNonNullType(paramType)) {
4060 if (NonNullArgs.empty())
4061 NonNullArgs.resize(Args.size());
4062
4063 NonNullArgs.set(Index);
4064 }
4065
4066 ++Index;
4067 }
4068 }
4069 }
4070
4071 // Check for non-null arguments.
4072 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4073 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4074 if (NonNullArgs[ArgIndex])
4075 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
4076 }
4077}
4078
4079void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4080 StringRef ParamName, QualType ArgTy,
4081 QualType ParamTy) {
4082
4083 // If a function accepts a pointer or reference type
4084 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4085 return;
4086
4087 // If the parameter is a pointer type, get the pointee type for the
4088 // argument too. If the parameter is a reference type, don't try to get
4089 // the pointee type for the argument.
4090 if (ParamTy->isPointerType())
4091 ArgTy = ArgTy->getPointeeType();
4092
4093 // Remove reference or pointer
4094 ParamTy = ParamTy->getPointeeType();
4095
4096 // Find expected alignment, and the actual alignment of the passed object.
4097 // getTypeAlignInChars requires complete types
4098 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4099 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4100 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4101 return;
4102
4103 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4104 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4105
4106 // If the argument is less aligned than the parameter, there is a
4107 // potential alignment issue.
4108 if (ArgAlign < ParamAlign)
4109 Diag(Loc, diag::warn_param_mismatched_alignment)
4110 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4111 << ParamName << (FDecl != nullptr) << FDecl;
4112}
4113
4114void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4115 const Expr *ThisArg,
4117 if (!FD || Args.empty())
4118 return;
4119 auto GetArgAt = [&](int Idx) -> const Expr * {
4120 if (Idx == LifetimeCaptureByAttr::Global ||
4121 Idx == LifetimeCaptureByAttr::Unknown)
4122 return nullptr;
4123 if (IsMemberFunction && Idx == 0)
4124 return ThisArg;
4125 return Args[Idx - IsMemberFunction];
4126 };
4127 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4128 unsigned ArgIdx) {
4129 if (!Attr)
4130 return;
4131
4132 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4133 for (int CapturingParamIdx : Attr->params()) {
4134 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4135 // initialization codepath.
4136 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4138 continue;
4139 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4140 CapturingEntity CE{Capturing};
4141 // Ensure that 'Captured' outlives the 'Capturing' entity.
4142 checkCaptureByLifetime(*this, CE, Captured);
4143 }
4144 };
4145 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4146 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(),
4147 I + IsMemberFunction);
4148 // Check when the implicit object param is captured.
4149 if (IsMemberFunction) {
4150 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4151 if (!TSI)
4152 return;
4154 for (TypeLoc TL = TSI->getTypeLoc();
4155 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4156 TL = ATL.getModifiedLoc())
4157 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4158 }
4159}
4160
4162 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4163 bool IsMemberFunction, SourceLocation Loc,
4164 SourceRange Range, VariadicCallType CallType) {
4165 // FIXME: We should check as much as we can in the template definition.
4166 if (CurContext->isDependentContext())
4167 return;
4168
4169 // Printf and scanf checking.
4170 llvm::SmallBitVector CheckedVarArgs;
4171 if (FDecl) {
4172 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4173 // Only create vector if there are format attributes.
4174 CheckedVarArgs.resize(Args.size());
4175 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
4176 CheckedVarArgs);
4177 }
4178
4179 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4180 CheckedVarArgs.resize(Args.size());
4181 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4182 CheckedVarArgs);
4183 }
4184 }
4185
4186 // Refuse POD arguments that weren't caught by the format string
4187 // checks above.
4188 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4189 if (CallType != VariadicCallType::DoesNotApply &&
4190 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4191 unsigned NumParams = Proto ? Proto->getNumParams()
4192 : isa_and_nonnull<FunctionDecl>(FDecl)
4193 ? cast<FunctionDecl>(FDecl)->getNumParams()
4194 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
4195 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4196 : 0;
4197
4198 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4199 // Args[ArgIdx] can be null in malformed code.
4200 if (const Expr *Arg = Args[ArgIdx]) {
4201 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4202 checkVariadicArgument(Arg, CallType);
4203 }
4204 }
4205 }
4206 if (FD)
4207 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4208 if (FDecl || Proto) {
4209 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4210
4211 // Type safety checking.
4212 if (FDecl) {
4213 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4214 CheckArgumentWithTypeTag(I, Args, Loc);
4215 }
4216 }
4217
4218 // Check that passed arguments match the alignment of original arguments.
4219 // Try to get the missing prototype from the declaration.
4220 if (!Proto && FDecl) {
4221 const auto *FT = FDecl->getFunctionType();
4222 if (isa_and_nonnull<FunctionProtoType>(FT))
4223 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4224 }
4225 if (Proto) {
4226 // For variadic functions, we may have more args than parameters.
4227 // For some K&R functions, we may have less args than parameters.
4228 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4229 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4230 bool IsScalableArg = false;
4231 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4232 // Args[ArgIdx] can be null in malformed code.
4233 if (const Expr *Arg = Args[ArgIdx]) {
4234 if (Arg->containsErrors())
4235 continue;
4236
4237 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4238 FDecl->hasLinkage() &&
4239 FDecl->getFormalLinkage() != Linkage::Internal &&
4241 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
4242
4243 QualType ParamTy = Proto->getParamType(ArgIdx);
4244 if (ParamTy->isSizelessVectorType())
4245 IsScalableArg = true;
4246 QualType ArgTy = Arg->getType();
4247 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4248 ArgTy, ParamTy);
4249 }
4250 }
4251
4252 // If the callee has an AArch64 SME attribute to indicate that it is an
4253 // __arm_streaming function, then the caller requires SME to be available.
4256 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
4257 llvm::StringMap<bool> CallerFeatureMap;
4258 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
4259 if (!CallerFeatureMap.contains("sme"))
4260 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4261 } else if (!Context.getTargetInfo().hasFeature("sme")) {
4262 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4263 }
4264 }
4265
4266 // If the call requires a streaming-mode change and has scalable vector
4267 // arguments or return values, then warn the user that the streaming and
4268 // non-streaming vector lengths may be different.
4269 // When both streaming and non-streaming vector lengths are defined and
4270 // mismatched, produce an error.
4271 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
4272 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4273 (IsScalableArg || IsScalableRet)) {
4274 bool IsCalleeStreaming =
4276 bool IsCalleeStreamingCompatible =
4277 ExtInfo.AArch64SMEAttributes &
4279 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
4280 if (!IsCalleeStreamingCompatible &&
4281 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4282 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4283 const LangOptions &LO = getLangOpts();
4284 unsigned VL = LO.VScaleMin * 128;
4285 unsigned SVL = LO.VScaleStreamingMin * 128;
4286 bool IsVLMismatch = VL && SVL && VL != SVL;
4287
4288 auto EmitDiag = [&](bool IsArg) {
4289 if (IsVLMismatch) {
4290 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4291 // Emit warning for streaming-compatible callers
4292 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
4293 << IsArg << IsCalleeStreaming << SVL << VL;
4294 else
4295 // Emit error otherwise
4296 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4297 << IsArg << SVL << VL;
4298 } else
4299 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4300 << IsArg;
4301 };
4302
4303 if (IsScalableArg)
4304 EmitDiag(true);
4305 if (IsScalableRet)
4306 EmitDiag(false);
4307 }
4308 }
4309
4310 FunctionType::ArmStateValue CalleeArmZAState =
4312 FunctionType::ArmStateValue CalleeArmZT0State =
4314 if (CalleeArmZAState != FunctionType::ARM_None ||
4315 CalleeArmZT0State != FunctionType::ARM_None) {
4316 bool CallerHasZAState = false;
4317 bool CallerHasZT0State = false;
4318 if (CallerFD) {
4319 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4320 if (Attr && Attr->isNewZA())
4321 CallerHasZAState = true;
4322 if (Attr && Attr->isNewZT0())
4323 CallerHasZT0State = true;
4324 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4325 CallerHasZAState |=
4327 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4329 CallerHasZT0State |=
4331 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4333 }
4334 }
4335
4336 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4337 Diag(Loc, diag::err_sme_za_call_no_za_state);
4338
4339 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4340 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4341
4342 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4343 CalleeArmZT0State != FunctionType::ARM_None) {
4344 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4345 Diag(Loc, diag::note_sme_use_preserves_za);
4346 }
4347 }
4348 }
4349
4350 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4351 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4352 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4353 if (!Arg->isValueDependent()) {
4354 Expr::EvalResult Align;
4355 if (Arg->EvaluateAsInt(Align, Context)) {
4356 const llvm::APSInt &I = Align.Val.getInt();
4357 if (!I.isPowerOf2())
4358 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4359 << Arg->getSourceRange();
4360
4361 if (I > Sema::MaximumAlignment)
4362 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4363 << Arg->getSourceRange() << Sema::MaximumAlignment;
4364 }
4365 }
4366 }
4367
4368 if (FD)
4369 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4370}
4371
4372void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4373 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4374 DiagnoseUseOfDecl(Decl, Loc);
4375 }
4376}
4377
4378void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4380 const FunctionProtoType *Proto,
4381 SourceLocation Loc) {
4382 VariadicCallType CallType = Proto->isVariadic()
4385
4386 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4387 CheckArgAlignment(
4388 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4389 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4390
4391 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4392 Loc, SourceRange(), CallType);
4393}
4394
4396 const FunctionProtoType *Proto) {
4397 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4398 isa<CXXMethodDecl>(FDecl);
4399 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4400 IsMemberOperatorCall;
4401 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4402 TheCall->getCallee());
4403 Expr** Args = TheCall->getArgs();
4404 unsigned NumArgs = TheCall->getNumArgs();
4405
4406 Expr *ImplicitThis = nullptr;
4407 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4408 // If this is a call to a member operator, hide the first
4409 // argument from checkCall.
4410 // FIXME: Our choice of AST representation here is less than ideal.
4411 ImplicitThis = Args[0];
4412 ++Args;
4413 --NumArgs;
4414 } else if (IsMemberFunction && !FDecl->isStatic() &&
4416 ImplicitThis =
4417 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4418
4419 if (ImplicitThis) {
4420 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4421 // used.
4422 QualType ThisType = ImplicitThis->getType();
4423 if (!ThisType->isPointerType()) {
4424 assert(!ThisType->isReferenceType());
4425 ThisType = Context.getPointerType(ThisType);
4426 }
4427
4428 QualType ThisTypeFromDecl = Context.getPointerType(
4429 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4430
4431 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4432 ThisTypeFromDecl);
4433 }
4434
4435 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4436 IsMemberFunction, TheCall->getRParenLoc(),
4437 TheCall->getCallee()->getSourceRange(), CallType);
4438
4439 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4440 // None of the checks below are needed for functions that don't have
4441 // simple names (e.g., C++ conversion functions).
4442 if (!FnInfo)
4443 return false;
4444
4445 // Enforce TCB except for builtin calls, which are always allowed.
4446 if (FDecl->getBuiltinID() == 0)
4447 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4448
4449 CheckAbsoluteValueFunction(TheCall, FDecl);
4450 CheckMaxUnsignedZero(TheCall, FDecl);
4451 CheckInfNaNFunction(TheCall, FDecl);
4452
4453 if (getLangOpts().ObjC)
4454 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4455
4456 unsigned CMId = FDecl->getMemoryFunctionKind();
4457
4458 // Handle memory setting and copying functions.
4459 switch (CMId) {
4460 case 0:
4461 return false;
4462 case Builtin::BIstrlcpy: // fallthrough
4463 case Builtin::BIstrlcat:
4464 CheckStrlcpycatArguments(TheCall, FnInfo);
4465 break;
4466 case Builtin::BIstrncat:
4467 CheckStrncatArguments(TheCall, FnInfo);
4468 break;
4469 case Builtin::BIfree:
4470 CheckFreeArguments(TheCall);
4471 break;
4472 default:
4473 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4474 }
4475
4476 return false;
4477}
4478
4479bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4480 const FunctionProtoType *Proto) {
4481 QualType Ty;
4482 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4483 Ty = V->getType().getNonReferenceType();
4484 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4485 Ty = F->getType().getNonReferenceType();
4486 else
4487 return false;
4488
4489 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4490 !Ty->isFunctionProtoType())
4491 return false;
4492
4493 VariadicCallType CallType;
4494 if (!Proto || !Proto->isVariadic()) {
4496 } else if (Ty->isBlockPointerType()) {
4497 CallType = VariadicCallType::Block;
4498 } else { // Ty->isFunctionPointerType()
4499 CallType = VariadicCallType::Function;
4500 }
4501
4502 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4503 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4504 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4505 TheCall->getCallee()->getSourceRange(), CallType);
4506
4507 return false;
4508}
4509
4510bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4511 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4512 TheCall->getCallee());
4513 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4514 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4515 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4516 TheCall->getCallee()->getSourceRange(), CallType);
4517
4518 return false;
4519}
4520
4521static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4522 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4523 return false;
4524
4525 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4526 switch (Op) {
4527 case AtomicExpr::AO__c11_atomic_init:
4528 case AtomicExpr::AO__opencl_atomic_init:
4529 llvm_unreachable("There is no ordering argument for an init");
4530
4531 case AtomicExpr::AO__c11_atomic_load:
4532 case AtomicExpr::AO__opencl_atomic_load:
4533 case AtomicExpr::AO__hip_atomic_load:
4534 case AtomicExpr::AO__atomic_load_n:
4535 case AtomicExpr::AO__atomic_load:
4536 case AtomicExpr::AO__scoped_atomic_load_n:
4537 case AtomicExpr::AO__scoped_atomic_load:
4538 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4539 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4540
4541 case AtomicExpr::AO__c11_atomic_store:
4542 case AtomicExpr::AO__opencl_atomic_store:
4543 case AtomicExpr::AO__hip_atomic_store:
4544 case AtomicExpr::AO__atomic_store:
4545 case AtomicExpr::AO__atomic_store_n:
4546 case AtomicExpr::AO__scoped_atomic_store:
4547 case AtomicExpr::AO__scoped_atomic_store_n:
4548 case AtomicExpr::AO__atomic_clear:
4549 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4550 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4551 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4552
4553 default:
4554 return true;
4555 }
4556}
4557
4558ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4560 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4561 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4562 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4563 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4564 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4565 Op);
4566}
4567
4569 SourceLocation RParenLoc, MultiExprArg Args,
4571 AtomicArgumentOrder ArgOrder) {
4572 // All the non-OpenCL operations take one of the following forms.
4573 // The OpenCL operations take the __c11 forms with one extra argument for
4574 // synchronization scope.
4575 enum {
4576 // C __c11_atomic_init(A *, C)
4577 Init,
4578
4579 // C __c11_atomic_load(A *, int)
4580 Load,
4581
4582 // void __atomic_load(A *, CP, int)
4583 LoadCopy,
4584
4585 // void __atomic_store(A *, CP, int)
4586 Copy,
4587
4588 // C __c11_atomic_add(A *, M, int)
4589 Arithmetic,
4590
4591 // C __atomic_exchange_n(A *, CP, int)
4592 Xchg,
4593
4594 // void __atomic_exchange(A *, C *, CP, int)
4595 GNUXchg,
4596
4597 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4598 C11CmpXchg,
4599
4600 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4601 GNUCmpXchg,
4602
4603 // bool __atomic_test_and_set(A *, int)
4604 TestAndSetByte,
4605
4606 // void __atomic_clear(A *, int)
4607 ClearByte,
4608 } Form = Init;
4609
4610 const unsigned NumForm = ClearByte + 1;
4611 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4612 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4613 // where:
4614 // C is an appropriate type,
4615 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4616 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4617 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4618 // the int parameters are for orderings.
4619
4620 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4621 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4622 "need to update code for modified forms");
4623 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4624 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4625 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4626 "need to update code for modified C11 atomics");
4627 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4628 Op <= AtomicExpr::AO__opencl_atomic_store;
4629 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4630 Op <= AtomicExpr::AO__hip_atomic_store;
4631 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4632 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4633 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4634 Op <= AtomicExpr::AO__c11_atomic_store) ||
4635 IsOpenCL;
4636 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4637 Op == AtomicExpr::AO__atomic_store_n ||
4638 Op == AtomicExpr::AO__atomic_exchange_n ||
4639 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4640 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4641 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4642 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4643 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4644 // Bit mask for extra allowed value types other than integers for atomic
4645 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4646 // allow floating point.
4647 enum ArithOpExtraValueType {
4648 AOEVT_None = 0,
4649 AOEVT_Pointer = 1,
4650 AOEVT_FP = 2,
4651 };
4652 unsigned ArithAllows = AOEVT_None;
4653
4654 switch (Op) {
4655 case AtomicExpr::AO__c11_atomic_init:
4656 case AtomicExpr::AO__opencl_atomic_init:
4657 Form = Init;
4658 break;
4659
4660 case AtomicExpr::AO__c11_atomic_load:
4661 case AtomicExpr::AO__opencl_atomic_load:
4662 case AtomicExpr::AO__hip_atomic_load:
4663 case AtomicExpr::AO__atomic_load_n:
4664 case AtomicExpr::AO__scoped_atomic_load_n:
4665 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4666 Form = Load;
4667 break;
4668
4669 case AtomicExpr::AO__atomic_load:
4670 case AtomicExpr::AO__scoped_atomic_load:
4671 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4672 Form = LoadCopy;
4673 break;
4674
4675 case AtomicExpr::AO__c11_atomic_store:
4676 case AtomicExpr::AO__opencl_atomic_store:
4677 case AtomicExpr::AO__hip_atomic_store:
4678 case AtomicExpr::AO__atomic_store:
4679 case AtomicExpr::AO__atomic_store_n:
4680 case AtomicExpr::AO__scoped_atomic_store:
4681 case AtomicExpr::AO__scoped_atomic_store_n:
4682 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4683 Form = Copy;
4684 break;
4685 case AtomicExpr::AO__atomic_fetch_add:
4686 case AtomicExpr::AO__atomic_fetch_sub:
4687 case AtomicExpr::AO__atomic_add_fetch:
4688 case AtomicExpr::AO__atomic_sub_fetch:
4689 case AtomicExpr::AO__scoped_atomic_fetch_add:
4690 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4691 case AtomicExpr::AO__scoped_atomic_add_fetch:
4692 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4693 case AtomicExpr::AO__c11_atomic_fetch_add:
4694 case AtomicExpr::AO__c11_atomic_fetch_sub:
4695 case AtomicExpr::AO__opencl_atomic_fetch_add:
4696 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4697 case AtomicExpr::AO__hip_atomic_fetch_add:
4698 case AtomicExpr::AO__hip_atomic_fetch_sub:
4699 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4700 Form = Arithmetic;
4701 break;
4702 case AtomicExpr::AO__atomic_fetch_max:
4703 case AtomicExpr::AO__atomic_fetch_min:
4704 case AtomicExpr::AO__atomic_max_fetch:
4705 case AtomicExpr::AO__atomic_min_fetch:
4706 case AtomicExpr::AO__scoped_atomic_fetch_max:
4707 case AtomicExpr::AO__scoped_atomic_fetch_min:
4708 case AtomicExpr::AO__scoped_atomic_max_fetch:
4709 case AtomicExpr::AO__scoped_atomic_min_fetch:
4710 case AtomicExpr::AO__c11_atomic_fetch_max:
4711 case AtomicExpr::AO__c11_atomic_fetch_min:
4712 case AtomicExpr::AO__opencl_atomic_fetch_max:
4713 case AtomicExpr::AO__opencl_atomic_fetch_min:
4714 case AtomicExpr::AO__hip_atomic_fetch_max:
4715 case AtomicExpr::AO__hip_atomic_fetch_min:
4716 ArithAllows = AOEVT_FP;
4717 Form = Arithmetic;
4718 break;
4719 case AtomicExpr::AO__c11_atomic_fetch_and:
4720 case AtomicExpr::AO__c11_atomic_fetch_or:
4721 case AtomicExpr::AO__c11_atomic_fetch_xor:
4722 case AtomicExpr::AO__hip_atomic_fetch_and:
4723 case AtomicExpr::AO__hip_atomic_fetch_or:
4724 case AtomicExpr::AO__hip_atomic_fetch_xor:
4725 case AtomicExpr::AO__c11_atomic_fetch_nand:
4726 case AtomicExpr::AO__opencl_atomic_fetch_and:
4727 case AtomicExpr::AO__opencl_atomic_fetch_or:
4728 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4729 case AtomicExpr::AO__atomic_fetch_and:
4730 case AtomicExpr::AO__atomic_fetch_or:
4731 case AtomicExpr::AO__atomic_fetch_xor:
4732 case AtomicExpr::AO__atomic_fetch_nand:
4733 case AtomicExpr::AO__atomic_and_fetch:
4734 case AtomicExpr::AO__atomic_or_fetch:
4735 case AtomicExpr::AO__atomic_xor_fetch:
4736 case AtomicExpr::AO__atomic_nand_fetch:
4737 case AtomicExpr::AO__atomic_fetch_uinc:
4738 case AtomicExpr::AO__atomic_fetch_udec:
4739 case AtomicExpr::AO__scoped_atomic_fetch_and:
4740 case AtomicExpr::AO__scoped_atomic_fetch_or:
4741 case AtomicExpr::AO__scoped_atomic_fetch_xor:
4742 case AtomicExpr::AO__scoped_atomic_fetch_nand:
4743 case AtomicExpr::AO__scoped_atomic_and_fetch:
4744 case AtomicExpr::AO__scoped_atomic_or_fetch:
4745 case AtomicExpr::AO__scoped_atomic_xor_fetch:
4746 case AtomicExpr::AO__scoped_atomic_nand_fetch:
4747 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
4748 case AtomicExpr::AO__scoped_atomic_fetch_udec:
4749 Form = Arithmetic;
4750 break;
4751
4752 case AtomicExpr::AO__c11_atomic_exchange:
4753 case AtomicExpr::AO__hip_atomic_exchange:
4754 case AtomicExpr::AO__opencl_atomic_exchange:
4755 case AtomicExpr::AO__atomic_exchange_n:
4756 case AtomicExpr::AO__scoped_atomic_exchange_n:
4757 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4758 Form = Xchg;
4759 break;
4760
4761 case AtomicExpr::AO__atomic_exchange:
4762 case AtomicExpr::AO__scoped_atomic_exchange:
4763 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4764 Form = GNUXchg;
4765 break;
4766
4767 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4768 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4769 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4770 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4771 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4772 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4773 Form = C11CmpXchg;
4774 break;
4775
4776 case AtomicExpr::AO__atomic_compare_exchange:
4777 case AtomicExpr::AO__atomic_compare_exchange_n:
4778 case AtomicExpr::AO__scoped_atomic_compare_exchange:
4779 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
4780 ArithAllows = AOEVT_Pointer;
4781 Form = GNUCmpXchg;
4782 break;
4783
4784 case AtomicExpr::AO__atomic_test_and_set:
4785 Form = TestAndSetByte;
4786 break;
4787
4788 case AtomicExpr::AO__atomic_clear:
4789 Form = ClearByte;
4790 break;
4791 }
4792
4793 unsigned AdjustedNumArgs = NumArgs[Form];
4794 if ((IsOpenCL || IsHIP || IsScoped) &&
4795 Op != AtomicExpr::AO__opencl_atomic_init)
4796 ++AdjustedNumArgs;
4797 // Check we have the right number of arguments.
4798 if (Args.size() < AdjustedNumArgs) {
4799 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4800 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4801 << /*is non object*/ 0 << ExprRange;
4802 return ExprError();
4803 } else if (Args.size() > AdjustedNumArgs) {
4804 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4805 diag::err_typecheck_call_too_many_args)
4806 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4807 << /*is non object*/ 0 << ExprRange;
4808 return ExprError();
4809 }
4810
4811 // Inspect the first argument of the atomic operation.
4812 Expr *Ptr = Args[0];
4814 if (ConvertedPtr.isInvalid())
4815 return ExprError();
4816
4817 Ptr = ConvertedPtr.get();
4818 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4819 if (!pointerType) {
4820 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4821 << Ptr->getType() << 0 << Ptr->getSourceRange();
4822 return ExprError();
4823 }
4824
4825 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4826 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4827 QualType ValType = AtomTy; // 'C'
4828 if (IsC11) {
4829 if (!AtomTy->isAtomicType()) {
4830 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4831 << Ptr->getType() << Ptr->getSourceRange();
4832 return ExprError();
4833 }
4834 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4836 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4837 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4838 << Ptr->getSourceRange();
4839 return ExprError();
4840 }
4841 ValType = AtomTy->castAs<AtomicType>()->getValueType();
4842 } else if (Form != Load && Form != LoadCopy) {
4843 if (ValType.isConstQualified()) {
4844 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4845 << Ptr->getType() << Ptr->getSourceRange();
4846 return ExprError();
4847 }
4848 }
4849
4850 if (Form != TestAndSetByte && Form != ClearByte) {
4851 // Pointer to object of size zero is not allowed.
4852 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
4853 diag::err_incomplete_type))
4854 return ExprError();
4855
4856 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
4857 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4858 << Ptr->getType() << 1 << Ptr->getSourceRange();
4859 return ExprError();
4860 }
4861 } else {
4862 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
4863 // non-const pointer type, including void* and pointers to incomplete
4864 // structs, but only access the first byte.
4865 AtomTy = Context.CharTy;
4866 AtomTy = AtomTy.withCVRQualifiers(
4867 pointerType->getPointeeType().getCVRQualifiers());
4868 QualType PointerQT = Context.getPointerType(AtomTy);
4869 pointerType = PointerQT->getAs<PointerType>();
4870 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
4871 ValType = AtomTy;
4872 }
4873
4874 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
4875 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4876 Diag(ExprRange.getBegin(),
4877 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4878 << 0 << Ptr->getType() << Ptr->getSourceRange();
4879 return ExprError();
4880 }
4881
4882 // For an arithmetic operation, the implied arithmetic must be well-formed.
4883 // For _n operations, the value type must also be a valid atomic type.
4884 if (Form == Arithmetic || IsN) {
4885 // GCC does not enforce these rules for GNU atomics, but we do to help catch
4886 // trivial type errors.
4887 auto IsAllowedValueType = [&](QualType ValType,
4888 unsigned AllowedType) -> bool {
4889 bool IsX87LongDouble =
4890 ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
4891 &Context.getTargetInfo().getLongDoubleFormat() ==
4892 &llvm::APFloat::x87DoubleExtended();
4893 if (ValType->isIntegerType())
4894 return true;
4895 if (ValType->isPointerType())
4896 return AllowedType & AOEVT_Pointer;
4897 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
4898 return false;
4899 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
4900 if (IsX87LongDouble)
4901 return false;
4902 return true;
4903 };
4904 if (!IsAllowedValueType(ValType, ArithAllows)) {
4905 auto DID = ArithAllows & AOEVT_FP
4906 ? (ArithAllows & AOEVT_Pointer
4907 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
4908 : diag::err_atomic_op_needs_atomic_int_or_fp)
4909 : (ArithAllows & AOEVT_Pointer
4910 ? diag::err_atomic_op_needs_atomic_int_or_ptr
4911 : diag::err_atomic_op_needs_atomic_int);
4912 Diag(ExprRange.getBegin(), DID)
4913 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4914 return ExprError();
4915 }
4916 if (IsC11 && ValType->isPointerType() &&
4918 diag::err_incomplete_type)) {
4919 return ExprError();
4920 }
4921 }
4922
4923 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4924 !AtomTy->isScalarType()) {
4925 // For GNU atomics, require a trivially-copyable type. This is not part of
4926 // the GNU atomics specification but we enforce it for consistency with
4927 // other atomics which generally all require a trivially-copyable type. This
4928 // is because atomics just copy bits.
4929 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4930 << Ptr->getType() << Ptr->getSourceRange();
4931 return ExprError();
4932 }
4933
4934 switch (ValType.getObjCLifetime()) {
4937 // okay
4938 break;
4939
4943 // FIXME: Can this happen? By this point, ValType should be known
4944 // to be trivially copyable.
4945 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4946 << ValType << Ptr->getSourceRange();
4947 return ExprError();
4948 }
4949
4950 // All atomic operations have an overload which takes a pointer to a volatile
4951 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4952 // into the result or the other operands. Similarly atomic_load takes a
4953 // pointer to a const 'A'.
4954 ValType.removeLocalVolatile();
4955 ValType.removeLocalConst();
4956 QualType ResultType = ValType;
4957 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
4958 Form == ClearByte)
4959 ResultType = Context.VoidTy;
4960 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
4961 ResultType = Context.BoolTy;
4962
4963 // The type of a parameter passed 'by value'. In the GNU atomics, such
4964 // arguments are actually passed as pointers.
4965 QualType ByValType = ValType; // 'CP'
4966 bool IsPassedByAddress = false;
4967 if (!IsC11 && !IsHIP && !IsN) {
4968 ByValType = Ptr->getType();
4969 IsPassedByAddress = true;
4970 }
4971
4972 SmallVector<Expr *, 5> APIOrderedArgs;
4973 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4974 APIOrderedArgs.push_back(Args[0]);
4975 switch (Form) {
4976 case Init:
4977 case Load:
4978 APIOrderedArgs.push_back(Args[1]); // Val1/Order
4979 break;
4980 case LoadCopy:
4981 case Copy:
4982 case Arithmetic:
4983 case Xchg:
4984 APIOrderedArgs.push_back(Args[2]); // Val1
4985 APIOrderedArgs.push_back(Args[1]); // Order
4986 break;
4987 case GNUXchg:
4988 APIOrderedArgs.push_back(Args[2]); // Val1
4989 APIOrderedArgs.push_back(Args[3]); // Val2
4990 APIOrderedArgs.push_back(Args[1]); // Order
4991 break;
4992 case C11CmpXchg:
4993 APIOrderedArgs.push_back(Args[2]); // Val1
4994 APIOrderedArgs.push_back(Args[4]); // Val2
4995 APIOrderedArgs.push_back(Args[1]); // Order
4996 APIOrderedArgs.push_back(Args[3]); // OrderFail
4997 break;
4998 case GNUCmpXchg:
4999 APIOrderedArgs.push_back(Args[2]); // Val1
5000 APIOrderedArgs.push_back(Args[4]); // Val2
5001 APIOrderedArgs.push_back(Args[5]); // Weak
5002 APIOrderedArgs.push_back(Args[1]); // Order
5003 APIOrderedArgs.push_back(Args[3]); // OrderFail
5004 break;
5005 case TestAndSetByte:
5006 case ClearByte:
5007 APIOrderedArgs.push_back(Args[1]); // Order
5008 break;
5009 }
5010 } else
5011 APIOrderedArgs.append(Args.begin(), Args.end());
5012
5013 // The first argument's non-CV pointer type is used to deduce the type of
5014 // subsequent arguments, except for:
5015 // - weak flag (always converted to bool)
5016 // - memory order (always converted to int)
5017 // - scope (always converted to int)
5018 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5019 QualType Ty;
5020 if (i < NumVals[Form] + 1) {
5021 switch (i) {
5022 case 0:
5023 // The first argument is always a pointer. It has a fixed type.
5024 // It is always dereferenced, a nullptr is undefined.
5025 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5026 // Nothing else to do: we already know all we want about this pointer.
5027 continue;
5028 case 1:
5029 // The second argument is the non-atomic operand. For arithmetic, this
5030 // is always passed by value, and for a compare_exchange it is always
5031 // passed by address. For the rest, GNU uses by-address and C11 uses
5032 // by-value.
5033 assert(Form != Load);
5034 if (Form == Arithmetic && ValType->isPointerType())
5035 Ty = Context.getPointerDiffType();
5036 else if (Form == Init || Form == Arithmetic)
5037 Ty = ValType;
5038 else if (Form == Copy || Form == Xchg) {
5039 if (IsPassedByAddress) {
5040 // The value pointer is always dereferenced, a nullptr is undefined.
5041 CheckNonNullArgument(*this, APIOrderedArgs[i],
5042 ExprRange.getBegin());
5043 }
5044 Ty = ByValType;
5045 } else {
5046 Expr *ValArg = APIOrderedArgs[i];
5047 // The value pointer is always dereferenced, a nullptr is undefined.
5048 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5050 // Keep address space of non-atomic pointer type.
5051 if (const PointerType *PtrTy =
5052 ValArg->getType()->getAs<PointerType>()) {
5053 AS = PtrTy->getPointeeType().getAddressSpace();
5054 }
5055 Ty = Context.getPointerType(
5056 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5057 }
5058 break;
5059 case 2:
5060 // The third argument to compare_exchange / GNU exchange is the desired
5061 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5062 if (IsPassedByAddress)
5063 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5064 Ty = ByValType;
5065 break;
5066 case 3:
5067 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5068 Ty = Context.BoolTy;
5069 break;
5070 }
5071 } else {
5072 // The order(s) and scope are always converted to int.
5073 Ty = Context.IntTy;
5074 }
5075
5076 InitializedEntity Entity =
5078 ExprResult Arg = APIOrderedArgs[i];
5079 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5080 if (Arg.isInvalid())
5081 return true;
5082 APIOrderedArgs[i] = Arg.get();
5083 }
5084
5085 // Permute the arguments into a 'consistent' order.
5086 SmallVector<Expr*, 5> SubExprs;
5087 SubExprs.push_back(Ptr);
5088 switch (Form) {
5089 case Init:
5090 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5091 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5092 break;
5093 case Load:
5094 case TestAndSetByte:
5095 case ClearByte:
5096 SubExprs.push_back(APIOrderedArgs[1]); // Order
5097 break;
5098 case LoadCopy:
5099 case Copy:
5100 case Arithmetic:
5101 case Xchg:
5102 SubExprs.push_back(APIOrderedArgs[2]); // Order
5103 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5104 break;
5105 case GNUXchg:
5106 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5107 SubExprs.push_back(APIOrderedArgs[3]); // Order
5108 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5109 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5110 break;
5111 case C11CmpXchg:
5112 SubExprs.push_back(APIOrderedArgs[3]); // Order
5113 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5114 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5115 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5116 break;
5117 case GNUCmpXchg:
5118 SubExprs.push_back(APIOrderedArgs[4]); // Order
5119 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5120 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5121 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5122 SubExprs.push_back(APIOrderedArgs[3]); // Weak
5123 break;
5124 }
5125
5126 // If the memory orders are constants, check they are valid.
5127 if (SubExprs.size() >= 2 && Form != Init) {
5128 std::optional<llvm::APSInt> Success =
5129 SubExprs[1]->getIntegerConstantExpr(Context);
5130 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
5131 Diag(SubExprs[1]->getBeginLoc(),
5132 diag::warn_atomic_op_has_invalid_memory_order)
5133 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5134 << SubExprs[1]->getSourceRange();
5135 }
5136 if (SubExprs.size() >= 5) {
5137 if (std::optional<llvm::APSInt> Failure =
5138 SubExprs[3]->getIntegerConstantExpr(Context)) {
5139 if (!llvm::is_contained(
5140 {llvm::AtomicOrderingCABI::relaxed,
5141 llvm::AtomicOrderingCABI::consume,
5142 llvm::AtomicOrderingCABI::acquire,
5143 llvm::AtomicOrderingCABI::seq_cst},
5144 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5145 Diag(SubExprs[3]->getBeginLoc(),
5146 diag::warn_atomic_op_has_invalid_memory_order)
5147 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5148 }
5149 }
5150 }
5151 }
5152
5153 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5154 auto *Scope = Args[Args.size() - 1];
5155 if (std::optional<llvm::APSInt> Result =
5156 Scope->getIntegerConstantExpr(Context)) {
5157 if (!ScopeModel->isValid(Result->getZExtValue()))
5158 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
5159 << Scope->getSourceRange();
5160 }
5161 SubExprs.push_back(Scope);
5162 }
5163
5164 AtomicExpr *AE = new (Context)
5165 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5166
5167 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5168 Op == AtomicExpr::AO__c11_atomic_store ||
5169 Op == AtomicExpr::AO__opencl_atomic_load ||
5170 Op == AtomicExpr::AO__hip_atomic_load ||
5171 Op == AtomicExpr::AO__opencl_atomic_store ||
5172 Op == AtomicExpr::AO__hip_atomic_store) &&
5173 Context.AtomicUsesUnsupportedLibcall(AE))
5174 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5175 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5176 Op == AtomicExpr::AO__opencl_atomic_load ||
5177 Op == AtomicExpr::AO__hip_atomic_load)
5178 ? 0
5179 : 1);
5180
5181 if (ValType->isBitIntType()) {
5182 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5183 return ExprError();
5184 }
5185
5186 return AE;
5187}
5188
5189/// checkBuiltinArgument - Given a call to a builtin function, perform
5190/// normal type-checking on the given argument, updating the call in
5191/// place. This is useful when a builtin function requires custom
5192/// type-checking for some of its arguments but not necessarily all of
5193/// them.
5194///
5195/// Returns true on error.
5196static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5197 FunctionDecl *Fn = E->getDirectCallee();
5198 assert(Fn && "builtin call without direct callee!");
5199
5200 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5201 InitializedEntity Entity =
5203
5204 ExprResult Arg = E->getArg(ArgIndex);
5205 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5206 if (Arg.isInvalid())
5207 return true;
5208
5209 E->setArg(ArgIndex, Arg.get());
5210 return false;
5211}
5212
5213ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5214 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5215 Expr *Callee = TheCall->getCallee();
5216 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5217 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5218
5219 // Ensure that we have at least one argument to do type inference from.
5220 if (TheCall->getNumArgs() < 1) {
5221 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5222 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5223 << Callee->getSourceRange();
5224 return ExprError();
5225 }
5226
5227 // Inspect the first argument of the atomic builtin. This should always be
5228 // a pointer type, whose element is an integral scalar or pointer type.
5229 // Because it is a pointer type, we don't have to worry about any implicit
5230 // casts here.
5231 // FIXME: We don't allow floating point scalars as input.
5232 Expr *FirstArg = TheCall->getArg(0);
5233 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5234 if (FirstArgResult.isInvalid())
5235 return ExprError();
5236 FirstArg = FirstArgResult.get();
5237 TheCall->setArg(0, FirstArg);
5238
5239 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5240 if (!pointerType) {
5241 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5242 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5243 return ExprError();
5244 }
5245
5246 QualType ValType = pointerType->getPointeeType();
5247 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5248 !ValType->isBlockPointerType()) {
5249 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5250 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5251 return ExprError();
5252 }
5253 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5254 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5255 Diag(FirstArg->getBeginLoc(),
5256 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5257 << 1 << ValType << FirstArg->getSourceRange();
5258 return ExprError();
5259 }
5260
5261 if (ValType.isConstQualified()) {
5262 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5263 << FirstArg->getType() << FirstArg->getSourceRange();
5264 return ExprError();
5265 }
5266
5267 switch (ValType.getObjCLifetime()) {
5270 // okay
5271 break;
5272
5276 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5277 << ValType << FirstArg->getSourceRange();
5278 return ExprError();
5279 }
5280
5281 // Strip any qualifiers off ValType.
5282 ValType = ValType.getUnqualifiedType();
5283
5284 // The majority of builtins return a value, but a few have special return
5285 // types, so allow them to override appropriately below.
5286 QualType ResultType = ValType;
5287
5288 // We need to figure out which concrete builtin this maps onto. For example,
5289 // __sync_fetch_and_add with a 2 byte object turns into
5290 // __sync_fetch_and_add_2.
5291#define BUILTIN_ROW(x) \
5292 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5293 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5294
5295 static const unsigned BuiltinIndices[][5] = {
5296 BUILTIN_ROW(__sync_fetch_and_add),
5297 BUILTIN_ROW(__sync_fetch_and_sub),
5298 BUILTIN_ROW(__sync_fetch_and_or),
5299 BUILTIN_ROW(__sync_fetch_and_and),
5300 BUILTIN_ROW(__sync_fetch_and_xor),
5301 BUILTIN_ROW(__sync_fetch_and_nand),
5302
5303 BUILTIN_ROW(__sync_add_and_fetch),
5304 BUILTIN_ROW(__sync_sub_and_fetch),
5305 BUILTIN_ROW(__sync_and_and_fetch),
5306 BUILTIN_ROW(__sync_or_and_fetch),
5307 BUILTIN_ROW(__sync_xor_and_fetch),
5308 BUILTIN_ROW(__sync_nand_and_fetch),
5309
5310 BUILTIN_ROW(__sync_val_compare_and_swap),
5311 BUILTIN_ROW(__sync_bool_compare_and_swap),
5312 BUILTIN_ROW(__sync_lock_test_and_set),
5313 BUILTIN_ROW(__sync_lock_release),
5314 BUILTIN_ROW(__sync_swap)
5315 };
5316#undef BUILTIN_ROW
5317
5318 // Determine the index of the size.
5319 unsigned SizeIndex;
5320 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5321 case 1: SizeIndex = 0; break;
5322 case 2: SizeIndex = 1; break;
5323 case 4: SizeIndex = 2; break;
5324 case 8: SizeIndex = 3; break;
5325 case 16: SizeIndex = 4; break;
5326 default:
5327 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5328 << FirstArg->getType() << FirstArg->getSourceRange();
5329 return ExprError();
5330 }
5331
5332 // Each of these builtins has one pointer argument, followed by some number of
5333 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5334 // that we ignore. Find out which row of BuiltinIndices to read from as well
5335 // as the number of fixed args.
5336 unsigned BuiltinID = FDecl->getBuiltinID();
5337 unsigned BuiltinIndex, NumFixed = 1;
5338 bool WarnAboutSemanticsChange = false;
5339 switch (BuiltinID) {
5340 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5341 case Builtin::BI__sync_fetch_and_add:
5342 case Builtin::BI__sync_fetch_and_add_1:
5343 case Builtin::BI__sync_fetch_and_add_2:
5344 case Builtin::BI__sync_fetch_and_add_4:
5345 case Builtin::BI__sync_fetch_and_add_8:
5346 case Builtin::BI__sync_fetch_and_add_16:
5347 BuiltinIndex = 0;
5348 break;
5349
5350 case Builtin::BI__sync_fetch_and_sub:
5351 case Builtin::BI__sync_fetch_and_sub_1:
5352 case Builtin::BI__sync_fetch_and_sub_2:
5353 case Builtin::BI__sync_fetch_and_sub_4:
5354 case Builtin::BI__sync_fetch_and_sub_8:
5355 case Builtin::BI__sync_fetch_and_sub_16:
5356 BuiltinIndex = 1;
5357 break;
5358
5359 case Builtin::BI__sync_fetch_and_or:
5360 case Builtin::BI__sync_fetch_and_or_1:
5361 case Builtin::BI__sync_fetch_and_or_2:
5362 case Builtin::BI__sync_fetch_and_or_4:
5363 case Builtin::BI__sync_fetch_and_or_8:
5364 case Builtin::BI__sync_fetch_and_or_16:
5365 BuiltinIndex = 2;
5366 break;
5367
5368 case Builtin::BI__sync_fetch_and_and:
5369 case Builtin::BI__sync_fetch_and_and_1:
5370 case Builtin::BI__sync_fetch_and_and_2:
5371 case Builtin::BI__sync_fetch_and_and_4:
5372 case Builtin::BI__sync_fetch_and_and_8:
5373 case Builtin::BI__sync_fetch_and_and_16:
5374 BuiltinIndex = 3;
5375 break;
5376
5377 case Builtin::BI__sync_fetch_and_xor:
5378 case Builtin::BI__sync_fetch_and_xor_1:
5379 case Builtin::BI__sync_fetch_and_xor_2:
5380 case Builtin::BI__sync_fetch_and_xor_4:
5381 case Builtin::BI__sync_fetch_and_xor_8:
5382 case Builtin::BI__sync_fetch_and_xor_16:
5383 BuiltinIndex = 4;
5384 break;
5385
5386 case Builtin::BI__sync_fetch_and_nand:
5387 case Builtin::BI__sync_fetch_and_nand_1:
5388 case Builtin::BI__sync_fetch_and_nand_2:
5389 case Builtin::BI__sync_fetch_and_nand_4:
5390 case Builtin::BI__sync_fetch_and_nand_8:
5391 case Builtin::BI__sync_fetch_and_nand_16:
5392 BuiltinIndex = 5;
5393 WarnAboutSemanticsChange = true;
5394 break;
5395
5396 case Builtin::BI__sync_add_and_fetch:
5397 case Builtin::BI__sync_add_and_fetch_1:
5398 case Builtin::BI__sync_add_and_fetch_2:
5399 case Builtin::BI__sync_add_and_fetch_4:
5400 case Builtin::BI__sync_add_and_fetch_8:
5401 case Builtin::BI__sync_add_and_fetch_16:
5402 BuiltinIndex = 6;
5403 break;
5404
5405 case Builtin::BI__sync_sub_and_fetch:
5406 case Builtin::BI__sync_sub_and_fetch_1:
5407 case Builtin::BI__sync_sub_and_fetch_2:
5408 case Builtin::BI__sync_sub_and_fetch_4:
5409 case Builtin::BI__sync_sub_and_fetch_8:
5410 case Builtin::BI__sync_sub_and_fetch_16:
5411 BuiltinIndex = 7;
5412 break;
5413
5414 case Builtin::BI__sync_and_and_fetch:
5415 case Builtin::BI__sync_and_and_fetch_1:
5416 case Builtin::BI__sync_and_and_fetch_2:
5417 case Builtin::BI__sync_and_and_fetch_4:
5418 case Builtin::BI__sync_and_and_fetch_8:
5419 case Builtin::BI__sync_and_and_fetch_16:
5420 BuiltinIndex = 8;
5421 break;
5422
5423 case Builtin::BI__sync_or_and_fetch:
5424 case Builtin::BI__sync_or_and_fetch_1:
5425 case Builtin::BI__sync_or_and_fetch_2:
5426 case Builtin::BI__sync_or_and_fetch_4:
5427 case Builtin::BI__sync_or_and_fetch_8:
5428 case Builtin::BI__sync_or_and_fetch_16:
5429 BuiltinIndex = 9;
5430 break;
5431
5432 case Builtin::BI__sync_xor_and_fetch:
5433 case Builtin::BI__sync_xor_and_fetch_1:
5434 case Builtin::BI__sync_xor_and_fetch_2:
5435 case Builtin::BI__sync_xor_and_fetch_4:
5436 case Builtin::BI__sync_xor_and_fetch_8:
5437 case Builtin::BI__sync_xor_and_fetch_16:
5438 BuiltinIndex = 10;
5439 break;
5440
5441 case Builtin::BI__sync_nand_and_fetch:
5442 case Builtin::BI__sync_nand_and_fetch_1:
5443 case Builtin::BI__sync_nand_and_fetch_2:
5444 case Builtin::BI__sync_nand_and_fetch_4:
5445 case Builtin::BI__sync_nand_and_fetch_8:
5446 case Builtin::BI__sync_nand_and_fetch_16:
5447 BuiltinIndex = 11;
5448 WarnAboutSemanticsChange = true;
5449 break;
5450
5451 case Builtin::BI__sync_val_compare_and_swap:
5452 case Builtin::BI__sync_val_compare_and_swap_1:
5453 case Builtin::BI__sync_val_compare_and_swap_2:
5454 case Builtin::BI__sync_val_compare_and_swap_4:
5455 case Builtin::BI__sync_val_compare_and_swap_8:
5456 case Builtin::BI__sync_val_compare_and_swap_16:
5457 BuiltinIndex = 12;
5458 NumFixed = 2;
5459 break;
5460
5461 case Builtin::BI__sync_bool_compare_and_swap:
5462 case Builtin::BI__sync_bool_compare_and_swap_1:
5463 case Builtin::BI__sync_bool_compare_and_swap_2:
5464 case Builtin::BI__sync_bool_compare_and_swap_4:
5465 case Builtin::BI__sync_bool_compare_and_swap_8:
5466 case Builtin::BI__sync_bool_compare_and_swap_16:
5467 BuiltinIndex = 13;
5468 NumFixed = 2;
5469 ResultType = Context.BoolTy;
5470 break;
5471
5472 case Builtin::BI__sync_lock_test_and_set:
5473 case Builtin::BI__sync_lock_test_and_set_1:
5474 case Builtin::BI__sync_lock_test_and_set_2:
5475 case Builtin::BI__sync_lock_test_and_set_4:
5476 case Builtin::BI__sync_lock_test_and_set_8:
5477 case Builtin::BI__sync_lock_test_and_set_16:
5478 BuiltinIndex = 14;
5479 break;
5480
5481 case Builtin::BI__sync_lock_release:
5482 case Builtin::BI__sync_lock_release_1:
5483 case Builtin::BI__sync_lock_release_2:
5484 case Builtin::BI__sync_lock_release_4:
5485 case Builtin::BI__sync_lock_release_8:
5486 case Builtin::BI__sync_lock_release_16:
5487 BuiltinIndex = 15;
5488 NumFixed = 0;
5489 ResultType = Context.VoidTy;
5490 break;
5491
5492 case Builtin::BI__sync_swap:
5493 case Builtin::BI__sync_swap_1:
5494 case Builtin::BI__sync_swap_2:
5495 case Builtin::BI__sync_swap_4:
5496 case Builtin::BI__sync_swap_8:
5497 case Builtin::BI__sync_swap_16:
5498 BuiltinIndex = 16;
5499 break;
5500 }
5501
5502 // Now that we know how many fixed arguments we expect, first check that we
5503 // have at least that many.
5504 if (TheCall->getNumArgs() < 1+NumFixed) {
5505 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5506 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5507 << Callee->getSourceRange();
5508 return ExprError();
5509 }
5510
5511 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5512 << Callee->getSourceRange();
5513
5514 if (WarnAboutSemanticsChange) {
5515 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5516 << Callee->getSourceRange();
5517 }
5518
5519 // Get the decl for the concrete builtin from this, we can tell what the
5520 // concrete integer type we should convert to is.
5521 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5522 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5523 FunctionDecl *NewBuiltinDecl;
5524 if (NewBuiltinID == BuiltinID)
5525 NewBuiltinDecl = FDecl;
5526 else {
5527 // Perform builtin lookup to avoid redeclaring it.
5528 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5529 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5530 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5531 assert(Res.getFoundDecl());
5532 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5533 if (!NewBuiltinDecl)
5534 return ExprError();
5535 }
5536
5537 // The first argument --- the pointer --- has a fixed type; we
5538 // deduce the types of the rest of the arguments accordingly. Walk
5539 // the remaining arguments, converting them to the deduced value type.
5540 for (unsigned i = 0; i != NumFixed; ++i) {
5541 ExprResult Arg = TheCall->getArg(i+1);
5542
5543 // GCC does an implicit conversion to the pointer or integer ValType. This
5544 // can fail in some cases (1i -> int**), check for this error case now.
5545 // Initialize the argument.
5546 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5547 ValType, /*consume*/ false);
5548 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5549 if (Arg.isInvalid())
5550 return ExprError();
5551
5552 // Okay, we have something that *can* be converted to the right type. Check
5553 // to see if there is a potentially weird extension going on here. This can
5554 // happen when you do an atomic operation on something like an char* and
5555 // pass in 42. The 42 gets converted to char. This is even more strange
5556 // for things like 45.123 -> char, etc.
5557 // FIXME: Do this check.
5558 TheCall->setArg(i+1, Arg.get());
5559 }
5560
5561 // Create a new DeclRefExpr to refer to the new decl.
5562 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5563 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5564 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5565 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5566
5567 // Set the callee in the CallExpr.
5568 // FIXME: This loses syntactic information.
5569 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5570 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5571 CK_BuiltinFnToFnPtr);
5572 TheCall->setCallee(PromotedCall.get());
5573
5574 // Change the result type of the call to match the original value type. This
5575 // is arbitrary, but the codegen for these builtins ins design to handle it
5576 // gracefully.
5577 TheCall->setType(ResultType);
5578
5579 // Prohibit problematic uses of bit-precise integer types with atomic
5580 // builtins. The arguments would have already been converted to the first
5581 // argument's type, so only need to check the first argument.
5582 const auto *BitIntValType = ValType->getAs<BitIntType>();
5583 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
5584 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5585 return ExprError();
5586 }
5587
5588 return TheCallResult;
5589}
5590
5591ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5592 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5593 DeclRefExpr *DRE =
5595 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5596 unsigned BuiltinID = FDecl->getBuiltinID();
5597 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5598 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5599 "Unexpected nontemporal load/store builtin!");
5600 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5601 unsigned numArgs = isStore ? 2 : 1;
5602
5603 // Ensure that we have the proper number of arguments.
5604 if (checkArgCount(TheCall, numArgs))
5605 return ExprError();
5606
5607 // Inspect the last argument of the nontemporal builtin. This should always
5608 // be a pointer type, from which we imply the type of the memory access.
5609 // Because it is a pointer type, we don't have to worry about any implicit
5610 // casts here.
5611 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5612 ExprResult PointerArgResult =
5614
5615 if (PointerArgResult.isInvalid())
5616 return ExprError();
5617 PointerArg = PointerArgResult.get();
5618 TheCall->setArg(numArgs - 1, PointerArg);
5619
5620 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5621 if (!pointerType) {
5622 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5623 << PointerArg->getType() << PointerArg->getSourceRange();
5624 return ExprError();
5625 }
5626
5627 QualType ValType = pointerType->getPointeeType();
5628
5629 // Strip any qualifiers off ValType.
5630 ValType = ValType.getUnqualifiedType();
5631 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5632 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5633 !ValType->isVectorType()) {
5634 Diag(DRE->getBeginLoc(),
5635 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5636 << PointerArg->getType() << PointerArg->getSourceRange();
5637 return ExprError();
5638 }
5639
5640 if (!isStore) {
5641 TheCall->setType(ValType);
5642 return TheCallResult;
5643 }
5644
5645 ExprResult ValArg = TheCall->getArg(0);
5646 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5647 Context, ValType, /*consume*/ false);
5648 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5649 if (ValArg.isInvalid())
5650 return ExprError();
5651
5652 TheCall->setArg(0, ValArg.get());
5653 TheCall->setType(Context.VoidTy);
5654 return TheCallResult;
5655}
5656
5657/// CheckObjCString - Checks that the format string argument to the os_log()
5658/// and os_trace() functions is correct, and converts it to const char *.
5659ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5660 Arg = Arg->IgnoreParenCasts();
5661 auto *Literal = dyn_cast<StringLiteral>(Arg);
5662 if (!Literal) {
5663 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5664 Literal = ObjcLiteral->getString();
5665 }
5666 }
5667
5668 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5669 return ExprError(
5670 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5671 << Arg->getSourceRange());
5672 }
5673
5674 ExprResult Result(Literal);
5675 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5676 InitializedEntity Entity =
5678 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5679 return Result;
5680}
5681
5682/// Check that the user is calling the appropriate va_start builtin for the
5683/// target and calling convention.
5684static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5685 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5686 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5687 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5688 TT.getArch() == llvm::Triple::aarch64_32);
5689 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5690 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5691 if (IsX64 || IsAArch64) {
5692 CallingConv CC = CC_C;
5693 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5694 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5695 if (IsMSVAStart) {
5696 // Don't allow this in System V ABI functions.
5697 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5698 return S.Diag(Fn->getBeginLoc(),
5699 diag::err_ms_va_start_used_in_sysv_function);
5700 } else {
5701 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5702 // On x64 Windows, don't allow this in System V ABI functions.
5703 // (Yes, that means there's no corresponding way to support variadic
5704 // System V ABI functions on Windows.)
5705 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5706 (!IsWindowsOrUEFI && CC == CC_Win64))
5707 return S.Diag(Fn->getBeginLoc(),
5708 diag::err_va_start_used_in_wrong_abi_function)
5709 << !IsWindowsOrUEFI;
5710 }
5711 return false;
5712 }
5713
5714 if (IsMSVAStart)
5715 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5716 return false;
5717}
5718
5720 ParmVarDecl **LastParam = nullptr) {
5721 // Determine whether the current function, block, or obj-c method is variadic
5722 // and get its parameter list.
5723 bool IsVariadic = false;
5725 DeclContext *Caller = S.CurContext;
5726 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5727 IsVariadic = Block->isVariadic();
5728 Params = Block->parameters();
5729 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5730 IsVariadic = FD->isVariadic();
5731 Params = FD->parameters();
5732 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5733 IsVariadic = MD->isVariadic();
5734 // FIXME: This isn't correct for methods (results in bogus warning).
5735 Params = MD->parameters();
5736 } else if (isa<CapturedDecl>(Caller)) {
5737 // We don't support va_start in a CapturedDecl.
5738 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5739 return true;
5740 } else {
5741 // This must be some other declcontext that parses exprs.
5742 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5743 return true;
5744 }
5745
5746 if (!IsVariadic) {
5747 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5748 return true;
5749 }
5750
5751 if (LastParam)
5752 *LastParam = Params.empty() ? nullptr : Params.back();
5753
5754 return false;
5755}
5756
5757bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5758 Expr *Fn = TheCall->getCallee();
5759 if (checkVAStartABI(*this, BuiltinID, Fn))
5760 return true;
5761
5762 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
5763 // This builtin requires one argument (the va_list), allows two arguments,
5764 // but diagnoses more than two arguments. e.g.,
5765 // __builtin_c23_va_start(); // error
5766 // __builtin_c23_va_start(list); // ok
5767 // __builtin_c23_va_start(list, param); // ok
5768 // __builtin_c23_va_start(list, anything, anything); // error
5769 // This differs from the GCC behavior in that they accept the last case
5770 // with a warning, but it doesn't seem like a useful behavior to allow.
5771 if (checkArgCountRange(TheCall, 1, 2))
5772 return true;
5773 } else {
5774 // In C23 mode, va_start only needs one argument. However, the builtin still
5775 // requires two arguments (which matches the behavior of the GCC builtin),
5776 // <stdarg.h> passes `0` as the second argument in C23 mode.
5777 if (checkArgCount(TheCall, 2))
5778 return true;
5779 }
5780
5781 // Type-check the first argument normally.
5782 if (checkBuiltinArgument(*this, TheCall, 0))
5783 return true;
5784
5785 // Check that the current function is variadic, and get its last parameter.
5786 ParmVarDecl *LastParam;
5787 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5788 return true;
5789
5790 // Verify that the second argument to the builtin is the last non-variadic
5791 // argument of the current function or method. In C23 mode, if the call is
5792 // not to __builtin_c23_va_start, and the second argument is an integer
5793 // constant expression with value 0, then we don't bother with this check.
5794 // For __builtin_c23_va_start, we only perform the check for the second
5795 // argument being the last argument to the current function if there is a
5796 // second argument present.
5797 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
5798 TheCall->getNumArgs() < 2) {
5799 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5800 return false;
5801 }
5802
5803 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5804 if (std::optional<llvm::APSInt> Val =
5806 Val && LangOpts.C23 && *Val == 0 &&
5807 BuiltinID != Builtin::BI__builtin_c23_va_start) {
5808 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5809 return false;
5810 }
5811
5812 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
5813 // next block.
5814 QualType Type;
5815 SourceLocation ParamLoc;
5816 bool IsCRegister = false;
5817 bool SecondArgIsLastNonVariadicArgument = false;
5818 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5819 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5820 SecondArgIsLastNonVariadicArgument = PV == LastParam;
5821
5822 Type = PV->getType();
5823 ParamLoc = PV->getLocation();
5824 IsCRegister =
5825 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5826 }
5827 }
5828
5829 if (!SecondArgIsLastNonVariadicArgument)
5830 Diag(TheCall->getArg(1)->getBeginLoc(),
5831 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
5832 else if (IsCRegister || Type->isReferenceType() ||
5833 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5834 // Promotable integers are UB, but enumerations need a bit of
5835 // extra checking to see what their promotable type actually is.
5836 if (!Context.isPromotableIntegerType(Type))
5837 return false;
5838 const auto *ED = Type->getAsEnumDecl();
5839 if (!ED)
5840 return true;
5841 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
5842 }()) {
5843 unsigned Reason = 0;
5844 if (Type->isReferenceType()) Reason = 1;
5845 else if (IsCRegister) Reason = 2;
5846 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5847 Diag(ParamLoc, diag::note_parameter_type) << Type;
5848 }
5849
5850 return false;
5851}
5852
5853bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
5854 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
5855 const LangOptions &LO = getLangOpts();
5856
5857 if (LO.CPlusPlus)
5858 return Arg->getType()
5860 .getTypePtr()
5861 ->getPointeeType()
5863
5864 // In C, allow aliasing through `char *`, this is required for AArch64 at
5865 // least.
5866 return true;
5867 };
5868
5869 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5870 // const char *named_addr);
5871
5872 Expr *Func = Call->getCallee();
5873
5874 if (Call->getNumArgs() < 3)
5875 return Diag(Call->getEndLoc(),
5876 diag::err_typecheck_call_too_few_args_at_least)
5877 << 0 /*function call*/ << 3 << Call->getNumArgs()
5878 << /*is non object*/ 0;
5879
5880 // Type-check the first argument normally.
5881 if (checkBuiltinArgument(*this, Call, 0))
5882 return true;
5883
5884 // Check that the current function is variadic.
5886 return true;
5887
5888 // __va_start on Windows does not validate the parameter qualifiers
5889
5890 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5891 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5892
5893 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5894 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5895
5896 const QualType &ConstCharPtrTy =
5897 Context.getPointerType(Context.CharTy.withConst());
5898 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
5899 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5900 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5901 << 0 /* qualifier difference */
5902 << 3 /* parameter mismatch */
5903 << 2 << Arg1->getType() << ConstCharPtrTy;
5904
5905 const QualType SizeTy = Context.getSizeType();
5906 if (!Context.hasSameType(
5908 SizeTy))
5909 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5910 << Arg2->getType() << SizeTy << 1 /* different class */
5911 << 0 /* qualifier difference */
5912 << 3 /* parameter mismatch */
5913 << 3 << Arg2->getType() << SizeTy;
5914
5915 return false;
5916}
5917
5918bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
5919 if (checkArgCount(TheCall, 2))
5920 return true;
5921
5922 if (BuiltinID == Builtin::BI__builtin_isunordered &&
5923 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
5924 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5925 << 1 << 0 << TheCall->getSourceRange();
5926
5927 ExprResult OrigArg0 = TheCall->getArg(0);
5928 ExprResult OrigArg1 = TheCall->getArg(1);
5929
5930 // Do standard promotions between the two arguments, returning their common
5931 // type.
5932 QualType Res = UsualArithmeticConversions(
5933 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
5934 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5935 return true;
5936
5937 // Make sure any conversions are pushed back into the call; this is
5938 // type safe since unordered compare builtins are declared as "_Bool
5939 // foo(...)".
5940 TheCall->setArg(0, OrigArg0.get());
5941 TheCall->setArg(1, OrigArg1.get());
5942
5943 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5944 return false;
5945
5946 // If the common type isn't a real floating type, then the arguments were
5947 // invalid for this operation.
5948 if (Res.isNull() || !Res->isRealFloatingType())
5949 return Diag(OrigArg0.get()->getBeginLoc(),
5950 diag::err_typecheck_call_invalid_ordered_compare)
5951 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5952 << SourceRange(OrigArg0.get()->getBeginLoc(),
5953 OrigArg1.get()->getEndLoc());
5954
5955 return false;
5956}
5957
5958bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
5959 unsigned BuiltinID) {
5960 if (checkArgCount(TheCall, NumArgs))
5961 return true;
5962
5963 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
5964 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
5965 BuiltinID == Builtin::BI__builtin_isinf ||
5966 BuiltinID == Builtin::BI__builtin_isinf_sign))
5967 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5968 << 0 << 0 << TheCall->getSourceRange();
5969
5970 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
5971 BuiltinID == Builtin::BI__builtin_isunordered))
5972 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5973 << 1 << 0 << TheCall->getSourceRange();
5974
5975 bool IsFPClass = NumArgs == 2;
5976
5977 // Find out position of floating-point argument.
5978 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
5979
5980 // We can count on all parameters preceding the floating-point just being int.
5981 // Try all of those.
5982 for (unsigned i = 0; i < FPArgNo; ++i) {
5983 Expr *Arg = TheCall->getArg(i);
5984
5985 if (Arg->isTypeDependent())
5986 return false;
5987
5990
5991 if (Res.isInvalid())
5992 return true;
5993 TheCall->setArg(i, Res.get());
5994 }
5995
5996 Expr *OrigArg = TheCall->getArg(FPArgNo);
5997
5998 if (OrigArg->isTypeDependent())
5999 return false;
6000
6001 // Usual Unary Conversions will convert half to float, which we want for
6002 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6003 // type how it is, but do normal L->Rvalue conversions.
6004 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
6005 ExprResult Res = UsualUnaryConversions(OrigArg);
6006
6007 if (!Res.isUsable())
6008 return true;
6009 OrigArg = Res.get();
6010 } else {
6012
6013 if (!Res.isUsable())
6014 return true;
6015 OrigArg = Res.get();
6016 }
6017 TheCall->setArg(FPArgNo, OrigArg);
6018
6019 QualType VectorResultTy;
6020 QualType ElementTy = OrigArg->getType();
6021 // TODO: When all classification function are implemented with is_fpclass,
6022 // vector argument can be supported in all of them.
6023 if (ElementTy->isVectorType() && IsFPClass) {
6024 VectorResultTy = GetSignedVectorType(ElementTy);
6025 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6026 }
6027
6028 // This operation requires a non-_Complex floating-point number.
6029 if (!ElementTy->isRealFloatingType())
6030 return Diag(OrigArg->getBeginLoc(),
6031 diag::err_typecheck_call_invalid_unary_fp)
6032 << OrigArg->getType() << OrigArg->getSourceRange();
6033
6034 // __builtin_isfpclass has integer parameter that specify test mask. It is
6035 // passed in (...), so it should be analyzed completely here.
6036 if (IsFPClass)
6037 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
6038 return true;
6039
6040 // TODO: enable this code to all classification functions.
6041 if (IsFPClass) {
6042 QualType ResultTy;
6043 if (!VectorResultTy.isNull())
6044 ResultTy = VectorResultTy;
6045 else
6046 ResultTy = Context.IntTy;
6047 TheCall->setType(ResultTy);
6048 }
6049
6050 return false;
6051}
6052
6053bool Sema::BuiltinComplex(CallExpr *TheCall) {
6054 if (checkArgCount(TheCall, 2))
6055 return true;
6056
6057 bool Dependent = false;
6058 for (unsigned I = 0; I != 2; ++I) {
6059 Expr *Arg = TheCall->getArg(I);
6060 QualType T = Arg->getType();
6061 if (T->isDependentType()) {
6062 Dependent = true;
6063 continue;
6064 }
6065
6066 // Despite supporting _Complex int, GCC requires a real floating point type
6067 // for the operands of __builtin_complex.
6068 if (!T->isRealFloatingType()) {
6069 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6070 << Arg->getType() << Arg->getSourceRange();
6071 }
6072
6073 ExprResult Converted = DefaultLvalueConversion(Arg);
6074 if (Converted.isInvalid())
6075 return true;
6076 TheCall->setArg(I, Converted.get());
6077 }
6078
6079 if (Dependent) {
6080 TheCall->setType(Context.DependentTy);
6081 return false;
6082 }
6083
6084 Expr *Real = TheCall->getArg(0);
6085 Expr *Imag = TheCall->getArg(1);
6086 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6087 return Diag(Real->getBeginLoc(),
6088 diag::err_typecheck_call_different_arg_types)
6089 << Real->getType() << Imag->getType()
6090 << Real->getSourceRange() << Imag->getSourceRange();
6091 }
6092
6093 TheCall->setType(Context.getComplexType(Real->getType()));
6094 return false;
6095}
6096
6097/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6098// This is declared to take (...), so we have to check everything.
6100 unsigned NumArgs = TheCall->getNumArgs();
6101 if (NumArgs < 2)
6102 return ExprError(Diag(TheCall->getEndLoc(),
6103 diag::err_typecheck_call_too_few_args_at_least)
6104 << 0 /*function call*/ << 2 << NumArgs
6105 << /*is non object*/ 0 << TheCall->getSourceRange());
6106
6107 // Determine which of the following types of shufflevector we're checking:
6108 // 1) unary, vector mask: (lhs, mask)
6109 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6110 QualType ResType = TheCall->getArg(0)->getType();
6111 unsigned NumElements = 0;
6112
6113 if (!TheCall->getArg(0)->isTypeDependent() &&
6114 !TheCall->getArg(1)->isTypeDependent()) {
6115 QualType LHSType = TheCall->getArg(0)->getType();
6116 QualType RHSType = TheCall->getArg(1)->getType();
6117
6118 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6119 return ExprError(
6120 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6121 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6122 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6123 TheCall->getArg(1)->getEndLoc()));
6124
6125 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6126 unsigned NumResElements = NumArgs - 2;
6127
6128 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6129 // with mask. If so, verify that RHS is an integer vector type with the
6130 // same number of elts as lhs.
6131 if (NumArgs == 2) {
6132 if (!RHSType->hasIntegerRepresentation() ||
6133 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
6134 return ExprError(Diag(TheCall->getBeginLoc(),
6135 diag::err_vec_builtin_incompatible_vector)
6136 << TheCall->getDirectCallee()
6137 << /*isMoreThanTwoArgs*/ false
6138 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6139 TheCall->getArg(1)->getEndLoc()));
6140 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6141 return ExprError(Diag(TheCall->getBeginLoc(),
6142 diag::err_vec_builtin_incompatible_vector)
6143 << TheCall->getDirectCallee()
6144 << /*isMoreThanTwoArgs*/ false
6145 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6146 TheCall->getArg(1)->getEndLoc()));
6147 } else if (NumElements != NumResElements) {
6148 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6149 ResType = ResType->isExtVectorType()
6150 ? Context.getExtVectorType(EltType, NumResElements)
6151 : Context.getVectorType(EltType, NumResElements,
6153 }
6154 }
6155
6156 for (unsigned I = 2; I != NumArgs; ++I) {
6157 Expr *Arg = TheCall->getArg(I);
6158 if (Arg->isTypeDependent() || Arg->isValueDependent())
6159 continue;
6160
6161 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
6162 if (!Result)
6163 return ExprError(Diag(TheCall->getBeginLoc(),
6164 diag::err_shufflevector_nonconstant_argument)
6165 << Arg->getSourceRange());
6166
6167 // Allow -1 which will be translated to undef in the IR.
6168 if (Result->isSigned() && Result->isAllOnes())
6169 ;
6170 else if (Result->getActiveBits() > 64 ||
6171 Result->getZExtValue() >= NumElements * 2)
6172 return ExprError(Diag(TheCall->getBeginLoc(),
6173 diag::err_shufflevector_argument_too_large)
6174 << Arg->getSourceRange());
6175
6176 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
6177 }
6178
6179 auto *Result = new (Context) ShuffleVectorExpr(
6180 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6181 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6182
6183 // All moved to Result.
6184 TheCall->shrinkNumArgs(0);
6185 return Result;
6186}
6187
6189 SourceLocation BuiltinLoc,
6190 SourceLocation RParenLoc) {
6193 QualType DstTy = TInfo->getType();
6194 QualType SrcTy = E->getType();
6195
6196 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6197 return ExprError(Diag(BuiltinLoc,
6198 diag::err_convertvector_non_vector)
6199 << E->getSourceRange());
6200 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6201 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
6202 << "second"
6203 << "__builtin_convertvector");
6204
6205 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6206 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6207 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6208 if (SrcElts != DstElts)
6209 return ExprError(Diag(BuiltinLoc,
6210 diag::err_convertvector_incompatible_vector)
6211 << E->getSourceRange());
6212 }
6213
6214 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
6215 RParenLoc, CurFPFeatureOverrides());
6216}
6217
6218bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6219 unsigned NumArgs = TheCall->getNumArgs();
6220
6221 if (NumArgs > 3)
6222 return Diag(TheCall->getEndLoc(),
6223 diag::err_typecheck_call_too_many_args_at_most)
6224 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6225 << TheCall->getSourceRange();
6226
6227 // Argument 0 is checked for us and the remaining arguments must be
6228 // constant integers.
6229 for (unsigned i = 1; i != NumArgs; ++i)
6230 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6231 return true;
6232
6233 return false;
6234}
6235
6236bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6237 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6238 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6239 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6240 if (checkArgCount(TheCall, 1))
6241 return true;
6242 Expr *Arg = TheCall->getArg(0);
6243 if (Arg->isInstantiationDependent())
6244 return false;
6245
6246 QualType ArgTy = Arg->getType();
6247 if (!ArgTy->hasFloatingRepresentation())
6248 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6249 << ArgTy;
6250 if (Arg->isLValue()) {
6251 ExprResult FirstArg = DefaultLvalueConversion(Arg);
6252 TheCall->setArg(0, FirstArg.get());
6253 }
6254 TheCall->setType(TheCall->getArg(0)->getType());
6255 return false;
6256}
6257
6258bool Sema::BuiltinAssume(CallExpr *TheCall) {
6259 Expr *Arg = TheCall->getArg(0);
6260 if (Arg->isInstantiationDependent()) return false;
6261
6262 if (Arg->HasSideEffects(Context))
6263 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6264 << Arg->getSourceRange()
6265 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6266
6267 return false;
6268}
6269
6270bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6271 // The alignment must be a constant integer.
6272 Expr *Arg = TheCall->getArg(1);
6273
6274 // We can't check the value of a dependent argument.
6275 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6276 if (const auto *UE =
6277 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6278 if (UE->getKind() == UETT_AlignOf ||
6279 UE->getKind() == UETT_PreferredAlignOf)
6280 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6281 << Arg->getSourceRange();
6282
6283 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6284
6285 if (!Result.isPowerOf2())
6286 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6287 << Arg->getSourceRange();
6288
6289 if (Result < Context.getCharWidth())
6290 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6291 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6292
6293 if (Result > std::numeric_limits<int32_t>::max())
6294 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6295 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6296 }
6297
6298 return false;
6299}
6300
6301bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6302 if (checkArgCountRange(TheCall, 2, 3))
6303 return true;
6304
6305 unsigned NumArgs = TheCall->getNumArgs();
6306 Expr *FirstArg = TheCall->getArg(0);
6307
6308 {
6309 ExprResult FirstArgResult =
6311 if (!FirstArgResult.get()->getType()->isPointerType()) {
6312 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
6313 << TheCall->getSourceRange();
6314 return true;
6315 }
6316 TheCall->setArg(0, FirstArgResult.get());
6317 }
6318
6319 // The alignment must be a constant integer.
6320 Expr *SecondArg = TheCall->getArg(1);
6321
6322 // We can't check the value of a dependent argument.
6323 if (!SecondArg->isValueDependent()) {
6324 llvm::APSInt Result;
6325 if (BuiltinConstantArg(TheCall, 1, Result))
6326 return true;
6327
6328 if (!Result.isPowerOf2())
6329 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6330 << SecondArg->getSourceRange();
6331
6333 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6334 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6335
6336 TheCall->setArg(1,
6338 }
6339
6340 if (NumArgs > 2) {
6341 Expr *ThirdArg = TheCall->getArg(2);
6342 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
6343 return true;
6344 TheCall->setArg(2, ThirdArg);
6345 }
6346
6347 return false;
6348}
6349
6350bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6351 unsigned BuiltinID =
6352 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6353 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6354
6355 unsigned NumArgs = TheCall->getNumArgs();
6356 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6357 if (NumArgs < NumRequiredArgs) {
6358 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6359 << 0 /* function call */ << NumRequiredArgs << NumArgs
6360 << /*is non object*/ 0 << TheCall->getSourceRange();
6361 }
6362 if (NumArgs >= NumRequiredArgs + 0x100) {
6363 return Diag(TheCall->getEndLoc(),
6364 diag::err_typecheck_call_too_many_args_at_most)
6365 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6366 << /*is non object*/ 0 << TheCall->getSourceRange();
6367 }
6368 unsigned i = 0;
6369
6370 // For formatting call, check buffer arg.
6371 if (!IsSizeCall) {
6372 ExprResult Arg(TheCall->getArg(i));
6373 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6374 Context, Context.VoidPtrTy, false);
6375 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6376 if (Arg.isInvalid())
6377 return true;
6378 TheCall->setArg(i, Arg.get());
6379 i++;
6380 }
6381
6382 // Check string literal arg.
6383 unsigned FormatIdx = i;
6384 {
6385 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6386 if (Arg.isInvalid())
6387 return true;
6388 TheCall->setArg(i, Arg.get());
6389 i++;
6390 }
6391
6392 // Make sure variadic args are scalar.
6393 unsigned FirstDataArg = i;
6394 while (i < NumArgs) {
6396 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6397 if (Arg.isInvalid())
6398 return true;
6399 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6400 if (ArgSize.getQuantity() >= 0x100) {
6401 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6402 << i << (int)ArgSize.getQuantity() << 0xff
6403 << TheCall->getSourceRange();
6404 }
6405 TheCall->setArg(i, Arg.get());
6406 i++;
6407 }
6408
6409 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6410 // call to avoid duplicate diagnostics.
6411 if (!IsSizeCall) {
6412 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6413 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6414 bool Success = CheckFormatArguments(
6415 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
6417 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
6418 if (!Success)
6419 return true;
6420 }
6421
6422 if (IsSizeCall) {
6423 TheCall->setType(Context.getSizeType());
6424 } else {
6425 TheCall->setType(Context.VoidPtrTy);
6426 }
6427 return false;
6428}
6429
6430bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6431 llvm::APSInt &Result) {
6432 Expr *Arg = TheCall->getArg(ArgNum);
6433
6434 if (Arg->isTypeDependent() || Arg->isValueDependent())
6435 return false;
6436
6437 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
6438 if (!R) {
6439 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6440 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6441 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6442 << FDecl->getDeclName() << Arg->getSourceRange();
6443 }
6444 Result = *R;
6445
6446 return false;
6447}
6448
6449bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6450 int High, bool RangeIsError) {
6452 return false;
6453 llvm::APSInt Result;
6454
6455 // We can't check the value of a dependent argument.
6456 Expr *Arg = TheCall->getArg(ArgNum);
6457 if (Arg->isTypeDependent() || Arg->isValueDependent())
6458 return false;
6459
6460 // Check constant-ness first.
6461 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6462 return true;
6463
6464 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6465 if (RangeIsError)
6466 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6467 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6468 else
6469 // Defer the warning until we know if the code will be emitted so that
6470 // dead code can ignore this.
6471 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6472 PDiag(diag::warn_argument_invalid_range)
6473 << toString(Result, 10) << Low << High
6474 << Arg->getSourceRange());
6475 }
6476
6477 return false;
6478}
6479
6480bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6481 unsigned Num) {
6482 llvm::APSInt Result;
6483
6484 // We can't check the value of a dependent argument.
6485 Expr *Arg = TheCall->getArg(ArgNum);
6486 if (Arg->isTypeDependent() || Arg->isValueDependent())
6487 return false;
6488
6489 // Check constant-ness first.
6490 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6491 return true;
6492
6493 if (Result.getSExtValue() % Num != 0)
6494 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6495 << Num << Arg->getSourceRange();
6496
6497 return false;
6498}
6499
6500bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6501 llvm::APSInt Result;
6502
6503 // We can't check the value of a dependent argument.
6504 Expr *Arg = TheCall->getArg(ArgNum);
6505 if (Arg->isTypeDependent() || Arg->isValueDependent())
6506 return false;
6507
6508 // Check constant-ness first.
6509 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6510 return true;
6511
6512 if (Result.isPowerOf2())
6513 return false;
6514
6515 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6516 << Arg->getSourceRange();
6517}
6518
6519static bool IsShiftedByte(llvm::APSInt Value) {
6520 if (Value.isNegative())
6521 return false;
6522
6523 // Check if it's a shifted byte, by shifting it down
6524 while (true) {
6525 // If the value fits in the bottom byte, the check passes.
6526 if (Value < 0x100)
6527 return true;
6528
6529 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6530 // fails.
6531 if ((Value & 0xFF) != 0)
6532 return false;
6533
6534 // If the bottom 8 bits are all 0, but something above that is nonzero,
6535 // then shifting the value right by 8 bits won't affect whether it's a
6536 // shifted byte or not. So do that, and go round again.
6537 Value >>= 8;
6538 }
6539}
6540
6541bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6542 unsigned ArgBits) {
6543 llvm::APSInt Result;
6544
6545 // We can't check the value of a dependent argument.
6546 Expr *Arg = TheCall->getArg(ArgNum);
6547 if (Arg->isTypeDependent() || Arg->isValueDependent())
6548 return false;
6549
6550 // Check constant-ness first.
6551 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6552 return true;
6553
6554 // Truncate to the given size.
6555 Result = Result.getLoBits(ArgBits);
6556 Result.setIsUnsigned(true);
6557
6558 if (IsShiftedByte(Result))
6559 return false;
6560
6561 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6562 << Arg->getSourceRange();
6563}
6564
6566 unsigned ArgNum,
6567 unsigned ArgBits) {
6568 llvm::APSInt Result;
6569
6570 // We can't check the value of a dependent argument.
6571 Expr *Arg = TheCall->getArg(ArgNum);
6572 if (Arg->isTypeDependent() || Arg->isValueDependent())
6573 return false;
6574
6575 // Check constant-ness first.
6576 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6577 return true;
6578
6579 // Truncate to the given size.
6580 Result = Result.getLoBits(ArgBits);
6581 Result.setIsUnsigned(true);
6582
6583 // Check to see if it's in either of the required forms.
6584 if (IsShiftedByte(Result) ||
6585 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6586 return false;
6587
6588 return Diag(TheCall->getBeginLoc(),
6589 diag::err_argument_not_shifted_byte_or_xxff)
6590 << Arg->getSourceRange();
6591}
6592
6593bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6594 if (!Context.getTargetInfo().hasSjLjLowering())
6595 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6596 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6597
6598 Expr *Arg = TheCall->getArg(1);
6599 llvm::APSInt Result;
6600
6601 // TODO: This is less than ideal. Overload this to take a value.
6602 if (BuiltinConstantArg(TheCall, 1, Result))
6603 return true;
6604
6605 if (Result != 1)
6606 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6607 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6608
6609 return false;
6610}
6611
6612bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6613 if (!Context.getTargetInfo().hasSjLjLowering())
6614 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6615 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6616 return false;
6617}
6618
6619bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6620 if (checkArgCount(TheCall, 1))
6621 return true;
6622
6623 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
6624 if (ArgRes.isInvalid())
6625 return true;
6626
6627 // For simplicity, we support only limited expressions for the argument.
6628 // Specifically a flexible array member or a pointer with counted_by:
6629 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
6630 // complex casting, which really shouldn't be a huge problem.
6631 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6632 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
6633 return Diag(Arg->getBeginLoc(),
6634 diag::err_builtin_counted_by_ref_invalid_arg)
6635 << Arg->getSourceRange();
6636
6637 if (Arg->HasSideEffects(Context))
6638 return Diag(Arg->getBeginLoc(),
6639 diag::err_builtin_counted_by_ref_has_side_effects)
6640 << Arg->getSourceRange();
6641
6642 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
6643 const auto *CATy =
6644 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6645
6646 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6647 // Member has counted_by attribute - return pointer to count field
6648 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
6649 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
6650 TheCall->setType(Context.getPointerType(CountFD->getType()));
6651 return false;
6652 }
6653 }
6654
6655 // FAMs and pointers without counted_by return void*
6656 QualType MemberTy = ME->getMemberDecl()->getType();
6657 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
6658 return Diag(Arg->getBeginLoc(),
6659 diag::err_builtin_counted_by_ref_invalid_arg)
6660 << Arg->getSourceRange();
6661 } else {
6662 return Diag(Arg->getBeginLoc(),
6663 diag::err_builtin_counted_by_ref_invalid_arg)
6664 << Arg->getSourceRange();
6665 }
6666
6667 TheCall->setType(Context.getPointerType(Context.VoidTy));
6668 return false;
6669}
6670
6671/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6672/// It allows leaking and modification of bounds safety information.
6673bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6675 const CallExpr *CE =
6676 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
6677 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6678 return false;
6679
6680 switch (K) {
6683 Diag(E->getExprLoc(),
6684 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6685 << 0 << E->getSourceRange();
6686 break;
6688 Diag(E->getExprLoc(),
6689 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6690 << 1 << E->getSourceRange();
6691 break;
6693 Diag(E->getExprLoc(),
6694 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6695 << 2 << E->getSourceRange();
6696 break;
6698 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6699 << 0 << E->getSourceRange();
6700 break;
6702 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6703 << 1 << E->getSourceRange();
6704 break;
6705 }
6706
6707 return true;
6708}
6709
6710namespace {
6711
6712class UncoveredArgHandler {
6713 enum { Unknown = -1, AllCovered = -2 };
6714
6715 signed FirstUncoveredArg = Unknown;
6716 SmallVector<const Expr *, 4> DiagnosticExprs;
6717
6718public:
6719 UncoveredArgHandler() = default;
6720
6721 bool hasUncoveredArg() const {
6722 return (FirstUncoveredArg >= 0);
6723 }
6724
6725 unsigned getUncoveredArg() const {
6726 assert(hasUncoveredArg() && "no uncovered argument");
6727 return FirstUncoveredArg;
6728 }
6729
6730 void setAllCovered() {
6731 // A string has been found with all arguments covered, so clear out
6732 // the diagnostics.
6733 DiagnosticExprs.clear();
6734 FirstUncoveredArg = AllCovered;
6735 }
6736
6737 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6738 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6739
6740 // Don't update if a previous string covers all arguments.
6741 if (FirstUncoveredArg == AllCovered)
6742 return;
6743
6744 // UncoveredArgHandler tracks the highest uncovered argument index
6745 // and with it all the strings that match this index.
6746 if (NewFirstUncoveredArg == FirstUncoveredArg)
6747 DiagnosticExprs.push_back(StrExpr);
6748 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6749 DiagnosticExprs.clear();
6750 DiagnosticExprs.push_back(StrExpr);
6751 FirstUncoveredArg = NewFirstUncoveredArg;
6752 }
6753 }
6754
6755 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6756};
6757
6758enum StringLiteralCheckType {
6759 SLCT_NotALiteral,
6760 SLCT_UncheckedLiteral,
6761 SLCT_CheckedLiteral
6762};
6763
6764} // namespace
6765
6766static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6767 BinaryOperatorKind BinOpKind,
6768 bool AddendIsRight) {
6769 unsigned BitWidth = Offset.getBitWidth();
6770 unsigned AddendBitWidth = Addend.getBitWidth();
6771 // There might be negative interim results.
6772 if (Addend.isUnsigned()) {
6773 Addend = Addend.zext(++AddendBitWidth);
6774 Addend.setIsSigned(true);
6775 }
6776 // Adjust the bit width of the APSInts.
6777 if (AddendBitWidth > BitWidth) {
6778 Offset = Offset.sext(AddendBitWidth);
6779 BitWidth = AddendBitWidth;
6780 } else if (BitWidth > AddendBitWidth) {
6781 Addend = Addend.sext(BitWidth);
6782 }
6783
6784 bool Ov = false;
6785 llvm::APSInt ResOffset = Offset;
6786 if (BinOpKind == BO_Add)
6787 ResOffset = Offset.sadd_ov(Addend, Ov);
6788 else {
6789 assert(AddendIsRight && BinOpKind == BO_Sub &&
6790 "operator must be add or sub with addend on the right");
6791 ResOffset = Offset.ssub_ov(Addend, Ov);
6792 }
6793
6794 // We add an offset to a pointer here so we should support an offset as big as
6795 // possible.
6796 if (Ov) {
6797 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6798 "index (intermediate) result too big");
6799 Offset = Offset.sext(2 * BitWidth);
6800 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6801 return;
6802 }
6803
6804 Offset = std::move(ResOffset);
6805}
6806
6807namespace {
6808
6809// This is a wrapper class around StringLiteral to support offsetted string
6810// literals as format strings. It takes the offset into account when returning
6811// the string and its length or the source locations to display notes correctly.
6812class FormatStringLiteral {
6813 const StringLiteral *FExpr;
6814 int64_t Offset;
6815
6816public:
6817 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6818 : FExpr(fexpr), Offset(Offset) {}
6819
6820 const StringLiteral *getFormatString() const { return FExpr; }
6821
6822 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
6823
6824 unsigned getByteLength() const {
6825 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6826 }
6827
6828 unsigned getLength() const { return FExpr->getLength() - Offset; }
6829 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6830
6831 StringLiteralKind getKind() const { return FExpr->getKind(); }
6832
6833 QualType getType() const { return FExpr->getType(); }
6834
6835 bool isAscii() const { return FExpr->isOrdinary(); }
6836 bool isWide() const { return FExpr->isWide(); }
6837 bool isUTF8() const { return FExpr->isUTF8(); }
6838 bool isUTF16() const { return FExpr->isUTF16(); }
6839 bool isUTF32() const { return FExpr->isUTF32(); }
6840 bool isPascal() const { return FExpr->isPascal(); }
6841
6842 SourceLocation getLocationOfByte(
6843 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6844 const TargetInfo &Target, unsigned *StartToken = nullptr,
6845 unsigned *StartTokenByteOffset = nullptr) const {
6846 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6847 StartToken, StartTokenByteOffset);
6848 }
6849
6850 SourceLocation getBeginLoc() const LLVM_READONLY {
6851 return FExpr->getBeginLoc().getLocWithOffset(Offset);
6852 }
6853
6854 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6855};
6856
6857} // namespace
6858
6859static void CheckFormatString(
6860 Sema &S, const FormatStringLiteral *FExpr,
6861 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
6863 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6864 bool inFunctionCall, VariadicCallType CallType,
6865 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6866 bool IgnoreStringsWithoutSpecifiers);
6867
6868static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
6869 const Expr *E);
6870
6871// Determine if an expression is a string literal or constant string.
6872// If this function returns false on the arguments to a function expecting a
6873// format string, we will usually need to emit a warning.
6874// True string literals are then checked by CheckFormatString.
6875static StringLiteralCheckType
6876checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
6877 const Expr *E, ArrayRef<const Expr *> Args,
6878 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
6879 unsigned firstDataArg, FormatStringType Type,
6880 VariadicCallType CallType, bool InFunctionCall,
6881 llvm::SmallBitVector &CheckedVarArgs,
6882 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
6883 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
6884 bool IgnoreStringsWithoutSpecifiers = false) {
6886 return SLCT_NotALiteral;
6887tryAgain:
6888 assert(Offset.isSigned() && "invalid offset");
6889
6890 if (E->isTypeDependent() || E->isValueDependent())
6891 return SLCT_NotALiteral;
6892
6893 E = E->IgnoreParenCasts();
6894
6896 // Technically -Wformat-nonliteral does not warn about this case.
6897 // The behavior of printf and friends in this case is implementation
6898 // dependent. Ideally if the format string cannot be null then
6899 // it should have a 'nonnull' attribute in the function prototype.
6900 return SLCT_UncheckedLiteral;
6901
6902 switch (E->getStmtClass()) {
6903 case Stmt::InitListExprClass:
6904 // Handle expressions like {"foobar"}.
6905 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
6906 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
6907 format_idx, firstDataArg, Type, CallType,
6908 /*InFunctionCall*/ false, CheckedVarArgs,
6909 UncoveredArg, Offset, CallerFormatParamIdx,
6910 IgnoreStringsWithoutSpecifiers);
6911 }
6912 return SLCT_NotALiteral;
6913 case Stmt::BinaryConditionalOperatorClass:
6914 case Stmt::ConditionalOperatorClass: {
6915 // The expression is a literal if both sub-expressions were, and it was
6916 // completely checked only if both sub-expressions were checked.
6919
6920 // Determine whether it is necessary to check both sub-expressions, for
6921 // example, because the condition expression is a constant that can be
6922 // evaluated at compile time.
6923 bool CheckLeft = true, CheckRight = true;
6924
6925 bool Cond;
6926 if (C->getCond()->EvaluateAsBooleanCondition(
6928 if (Cond)
6929 CheckRight = false;
6930 else
6931 CheckLeft = false;
6932 }
6933
6934 // We need to maintain the offsets for the right and the left hand side
6935 // separately to check if every possible indexed expression is a valid
6936 // string literal. They might have different offsets for different string
6937 // literals in the end.
6938 StringLiteralCheckType Left;
6939 if (!CheckLeft)
6940 Left = SLCT_UncheckedLiteral;
6941 else {
6942 Left = checkFormatStringExpr(S, ReferenceFormatString, C->getTrueExpr(),
6943 Args, APK, format_idx, firstDataArg, Type,
6944 CallType, InFunctionCall, CheckedVarArgs,
6945 UncoveredArg, Offset, CallerFormatParamIdx,
6946 IgnoreStringsWithoutSpecifiers);
6947 if (Left == SLCT_NotALiteral || !CheckRight) {
6948 return Left;
6949 }
6950 }
6951
6952 StringLiteralCheckType Right = checkFormatStringExpr(
6953 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
6954 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6955 UncoveredArg, Offset, CallerFormatParamIdx,
6956 IgnoreStringsWithoutSpecifiers);
6957
6958 return (CheckLeft && Left < Right) ? Left : Right;
6959 }
6960
6961 case Stmt::ImplicitCastExprClass:
6962 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6963 goto tryAgain;
6964
6965 case Stmt::OpaqueValueExprClass:
6966 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6967 E = src;
6968 goto tryAgain;
6969 }
6970 return SLCT_NotALiteral;
6971
6972 case Stmt::PredefinedExprClass:
6973 // While __func__, etc., are technically not string literals, they
6974 // cannot contain format specifiers and thus are not a security
6975 // liability.
6976 return SLCT_UncheckedLiteral;
6977
6978 case Stmt::DeclRefExprClass: {
6979 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6980
6981 // As an exception, do not flag errors for variables binding to
6982 // const string literals.
6983 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6984 bool isConstant = false;
6985 QualType T = DR->getType();
6986
6987 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6988 isConstant = AT->getElementType().isConstant(S.Context);
6989 } else if (const PointerType *PT = T->getAs<PointerType>()) {
6990 isConstant = T.isConstant(S.Context) &&
6991 PT->getPointeeType().isConstant(S.Context);
6992 } else if (T->isObjCObjectPointerType()) {
6993 // In ObjC, there is usually no "const ObjectPointer" type,
6994 // so don't check if the pointee type is constant.
6995 isConstant = T.isConstant(S.Context);
6996 }
6997
6998 if (isConstant) {
6999 if (const Expr *Init = VD->getAnyInitializer()) {
7000 // Look through initializers like const char c[] = { "foo" }
7001 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7002 if (InitList->isStringLiteralInit())
7003 Init = InitList->getInit(0)->IgnoreParenImpCasts();
7004 }
7005 return checkFormatStringExpr(
7006 S, ReferenceFormatString, Init, Args, APK, format_idx,
7007 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7008 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7009 }
7010 }
7011
7012 // When the format argument is an argument of this function, and this
7013 // function also has the format attribute, there are several interactions
7014 // for which there shouldn't be a warning. For instance, when calling
7015 // v*printf from a function that has the printf format attribute, we
7016 // should not emit a warning about using `fmt`, even though it's not
7017 // constant, because the arguments have already been checked for the
7018 // caller of `logmessage`:
7019 //
7020 // __attribute__((format(printf, 1, 2)))
7021 // void logmessage(char const *fmt, ...) {
7022 // va_list ap;
7023 // va_start(ap, fmt);
7024 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7025 // ...
7026 // }
7027 //
7028 // Another interaction that we need to support is using a format string
7029 // specified by the format_matches attribute:
7030 //
7031 // __attribute__((format_matches(printf, 1, "%s %d")))
7032 // void logmessage(char const *fmt, const char *a, int b) {
7033 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7034 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7035 // ...
7036 // }
7037 //
7038 // Yet another interaction that we need to support is calling a variadic
7039 // format function from a format function that has fixed arguments. For
7040 // instance:
7041 //
7042 // __attribute__((format(printf, 1, 2)))
7043 // void logstring(char const *fmt, char const *str) {
7044 // printf(fmt, str); /* do not emit a warning about "fmt" */
7045 // }
7046 //
7047 // Same (and perhaps more relatably) for the variadic template case:
7048 //
7049 // template<typename... Args>
7050 // __attribute__((format(printf, 1, 2)))
7051 // void log(const char *fmt, Args&&... args) {
7052 // printf(fmt, forward<Args>(args)...);
7053 // /* do not emit a warning about "fmt" */
7054 // }
7055 //
7056 // Due to implementation difficulty, we only check the format, not the
7057 // format arguments, in all cases.
7058 //
7059 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
7060 if (CallerFormatParamIdx)
7061 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7062 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
7063 for (const auto *PVFormatMatches :
7064 D->specific_attrs<FormatMatchesAttr>()) {
7065 Sema::FormatStringInfo CalleeFSI;
7066 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
7067 0, &CalleeFSI))
7068 continue;
7069 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7070 // If using the wrong type of format string, emit a diagnostic
7071 // here and stop checking to avoid irrelevant diagnostics.
7072 if (Type != S.GetFormatStringType(PVFormatMatches)) {
7073 S.Diag(Args[format_idx]->getBeginLoc(),
7074 diag::warn_format_string_type_incompatible)
7075 << PVFormatMatches->getType()->getName()
7077 if (!InFunctionCall) {
7078 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
7079 diag::note_format_string_defined);
7080 }
7081 return SLCT_UncheckedLiteral;
7082 }
7083 return checkFormatStringExpr(
7084 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
7085 Args, APK, format_idx, firstDataArg, Type, CallType,
7086 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7087 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7088 }
7089 }
7090
7091 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7092 Sema::FormatStringInfo CallerFSI;
7093 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
7094 PVFormat->getFirstArg(), &CallerFSI))
7095 continue;
7096 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7097 // We also check if the formats are compatible.
7098 // We can't pass a 'scanf' string to a 'printf' function.
7099 if (Type != S.GetFormatStringType(PVFormat)) {
7100 S.Diag(Args[format_idx]->getBeginLoc(),
7101 diag::warn_format_string_type_incompatible)
7102 << PVFormat->getType()->getName()
7104 if (!InFunctionCall) {
7105 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
7106 }
7107 return SLCT_UncheckedLiteral;
7108 }
7109 // Lastly, check that argument passing kinds transition in a
7110 // way that makes sense:
7111 // from a caller with FAPK_VAList, allow FAPK_VAList
7112 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7113 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7114 // from a caller with FAPK_Variadic, allow FAPK_VAList
7115 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
7120 return SLCT_UncheckedLiteral;
7121 }
7122 }
7123 }
7124 }
7125 }
7126 }
7127
7128 return SLCT_NotALiteral;
7129 }
7130
7131 case Stmt::CallExprClass:
7132 case Stmt::CXXMemberCallExprClass: {
7133 const CallExpr *CE = cast<CallExpr>(E);
7134 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7135 bool IsFirst = true;
7136 StringLiteralCheckType CommonResult;
7137 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7138 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7139 StringLiteralCheckType Result = checkFormatStringExpr(
7140 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7141 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7142 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7143 if (IsFirst) {
7144 CommonResult = Result;
7145 IsFirst = false;
7146 }
7147 }
7148 if (!IsFirst)
7149 return CommonResult;
7150
7151 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7152 unsigned BuiltinID = FD->getBuiltinID();
7153 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7154 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7155 const Expr *Arg = CE->getArg(0);
7156 return checkFormatStringExpr(
7157 S, ReferenceFormatString, Arg, Args, APK, format_idx,
7158 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7159 UncoveredArg, Offset, CallerFormatParamIdx,
7160 IgnoreStringsWithoutSpecifiers);
7161 }
7162 }
7163 }
7164 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
7165 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7166 format_idx, firstDataArg, Type, CallType,
7167 /*InFunctionCall*/ false, CheckedVarArgs,
7168 UncoveredArg, Offset, CallerFormatParamIdx,
7169 IgnoreStringsWithoutSpecifiers);
7170 return SLCT_NotALiteral;
7171 }
7172 case Stmt::ObjCMessageExprClass: {
7173 const auto *ME = cast<ObjCMessageExpr>(E);
7174 if (const auto *MD = ME->getMethodDecl()) {
7175 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7176 // As a special case heuristic, if we're using the method -[NSBundle
7177 // localizedStringForKey:value:table:], ignore any key strings that lack
7178 // format specifiers. The idea is that if the key doesn't have any
7179 // format specifiers then its probably just a key to map to the
7180 // localized strings. If it does have format specifiers though, then its
7181 // likely that the text of the key is the format string in the
7182 // programmer's language, and should be checked.
7183 const ObjCInterfaceDecl *IFace;
7184 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7185 IFace->getIdentifier()->isStr("NSBundle") &&
7186 MD->getSelector().isKeywordSelector(
7187 {"localizedStringForKey", "value", "table"})) {
7188 IgnoreStringsWithoutSpecifiers = true;
7189 }
7190
7191 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7192 return checkFormatStringExpr(
7193 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7194 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7195 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7196 }
7197 }
7198
7199 return SLCT_NotALiteral;
7200 }
7201 case Stmt::ObjCStringLiteralClass:
7202 case Stmt::StringLiteralClass: {
7203 const StringLiteral *StrE = nullptr;
7204
7205 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7206 StrE = ObjCFExpr->getString();
7207 else
7208 StrE = cast<StringLiteral>(E);
7209
7210 if (StrE) {
7211 if (Offset.isNegative() || Offset > StrE->getLength()) {
7212 // TODO: It would be better to have an explicit warning for out of
7213 // bounds literals.
7214 return SLCT_NotALiteral;
7215 }
7216 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7217 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
7218 format_idx, firstDataArg, Type, InFunctionCall,
7219 CallType, CheckedVarArgs, UncoveredArg,
7220 IgnoreStringsWithoutSpecifiers);
7221 return SLCT_CheckedLiteral;
7222 }
7223
7224 return SLCT_NotALiteral;
7225 }
7226 case Stmt::BinaryOperatorClass: {
7227 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7228
7229 // A string literal + an int offset is still a string literal.
7230 if (BinOp->isAdditiveOp()) {
7231 Expr::EvalResult LResult, RResult;
7232
7233 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7234 LResult, S.Context, Expr::SE_NoSideEffects,
7236 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7237 RResult, S.Context, Expr::SE_NoSideEffects,
7239
7240 if (LIsInt != RIsInt) {
7241 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7242
7243 if (LIsInt) {
7244 if (BinOpKind == BO_Add) {
7245 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7246 E = BinOp->getRHS();
7247 goto tryAgain;
7248 }
7249 } else {
7250 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7251 E = BinOp->getLHS();
7252 goto tryAgain;
7253 }
7254 }
7255 }
7256
7257 return SLCT_NotALiteral;
7258 }
7259 case Stmt::UnaryOperatorClass: {
7260 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7261 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7262 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7263 Expr::EvalResult IndexResult;
7264 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7267 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7268 /*RHS is int*/ true);
7269 E = ASE->getBase();
7270 goto tryAgain;
7271 }
7272 }
7273
7274 return SLCT_NotALiteral;
7275 }
7276
7277 default:
7278 return SLCT_NotALiteral;
7279 }
7280}
7281
7282// If this expression can be evaluated at compile-time,
7283// check if the result is a StringLiteral and return it
7284// otherwise return nullptr
7286 const Expr *E) {
7287 Expr::EvalResult Result;
7288 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
7289 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7290 if (isa_and_nonnull<StringLiteral>(LVE))
7291 return LVE;
7292 }
7293 return nullptr;
7294}
7295
7297 switch (FST) {
7299 return "scanf";
7301 return "printf";
7303 return "NSString";
7305 return "strftime";
7307 return "strfmon";
7309 return "kprintf";
7311 return "freebsd_kprintf";
7313 return "os_log";
7314 default:
7315 return "<unknown>";
7316 }
7317}
7318
7320 return llvm::StringSwitch<FormatStringType>(Flavor)
7321 .Cases({"gnu_scanf", "scanf"}, FormatStringType::Scanf)
7322 .Cases({"gnu_printf", "printf", "printf0", "syslog"},
7324 .Cases({"NSString", "CFString"}, FormatStringType::NSString)
7325 .Cases({"gnu_strftime", "strftime"}, FormatStringType::Strftime)
7326 .Cases({"gnu_strfmon", "strfmon"}, FormatStringType::Strfmon)
7327 .Cases({"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7329 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
7330 .Case("os_trace", FormatStringType::OSLog)
7331 .Case("os_log", FormatStringType::OSLog)
7332 .Default(FormatStringType::Unknown);
7333}
7334
7336 return GetFormatStringType(Format->getType()->getName());
7337}
7338
7339FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7340 return GetFormatStringType(Format->getType()->getName());
7341}
7342
7343bool Sema::CheckFormatArguments(const FormatAttr *Format,
7344 ArrayRef<const Expr *> Args, bool IsCXXMember,
7345 VariadicCallType CallType, SourceLocation Loc,
7346 SourceRange Range,
7347 llvm::SmallBitVector &CheckedVarArgs) {
7348 FormatStringInfo FSI;
7349 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
7350 IsCXXMember,
7351 CallType != VariadicCallType::DoesNotApply, &FSI))
7352 return CheckFormatArguments(
7353 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
7354 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
7355 return false;
7356}
7357
7358bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7359 ArrayRef<const Expr *> Args, bool IsCXXMember,
7360 VariadicCallType CallType, SourceLocation Loc,
7361 SourceRange Range,
7362 llvm::SmallBitVector &CheckedVarArgs) {
7363 FormatStringInfo FSI;
7364 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
7365 &FSI)) {
7366 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7367 return CheckFormatArguments(Args, FSI.ArgPassingKind,
7368 Format->getFormatString(), FSI.FormatIdx,
7369 FSI.FirstDataArg, GetFormatStringType(Format),
7370 CallType, Loc, Range, CheckedVarArgs);
7371 }
7372 return false;
7373}
7374
7377 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7378 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7379 SourceLocation Loc) {
7380 if (S->getDiagnostics().isIgnored(diag::warn_missing_format_attribute, Loc))
7381 return false;
7382
7383 DeclContext *DC = S->CurContext;
7384 if (!isa<ObjCMethodDecl>(DC) && !isa<FunctionDecl>(DC) && !isa<BlockDecl>(DC))
7385 return false;
7386 Decl *Caller = cast<Decl>(DC)->getCanonicalDecl();
7387
7388 unsigned NumCallerParams = getFunctionOrMethodNumParams(Caller);
7389
7390 // Find the offset to convert between attribute and parameter indexes.
7391 unsigned CallerArgumentIndexOffset =
7392 hasImplicitObjectParameter(Caller) ? 2 : 1;
7393
7394 unsigned FirstArgumentIndex = -1;
7395 switch (APK) {
7398 // As an extension, clang allows the format attribute on non-variadic
7399 // functions.
7400 // Caller must have fixed arguments to pass them to a fixed or variadic
7401 // function. Try to match caller and callee arguments. If successful, then
7402 // emit a diag with the caller idx, otherwise we can't determine the callee
7403 // arguments.
7404 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7405 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7406 // There aren't enough arguments in the caller to pass to callee.
7407 return false;
7408 }
7409 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7410 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7411 const auto *Arg =
7412 dyn_cast<DeclRefExpr>(Args[CalleeIdx]->IgnoreParenCasts());
7413 if (!Arg)
7414 return false;
7415 const auto *Param = dyn_cast<ParmVarDecl>(Arg->getDecl());
7416 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7417 return false;
7418 }
7419 FirstArgumentIndex =
7420 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7421 break;
7422 }
7424 // Caller arguments are either variadic or a va_list.
7425 FirstArgumentIndex = isFunctionOrMethodVariadic(Caller)
7426 ? (NumCallerParams + CallerArgumentIndexOffset)
7427 : 0;
7428 break;
7430 // The callee has a format_matches attribute. We will emit that instead.
7431 if (!ReferenceFormatString)
7432 return false;
7433 break;
7434 }
7435
7436 // Emit the diagnostic and fixit.
7437 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7438 StringRef FormatTypeName = S->GetFormatStringTypeName(FormatType);
7439 NamedDecl *ND = dyn_cast<NamedDecl>(Caller);
7440 do {
7441 std::string Attr, Fixit;
7442 llvm::raw_string_ostream AttrOS(Attr);
7444 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7445 << FirstArgumentIndex << ")";
7446 } else {
7447 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7448 << ", \"";
7449 AttrOS.write_escaped(ReferenceFormatString->getString());
7450 AttrOS << "\")";
7451 }
7452 AttrOS.flush();
7453 auto DB = S->Diag(Loc, diag::warn_missing_format_attribute) << Attr;
7454 if (ND)
7455 DB << ND;
7456 else
7457 DB << "block";
7458
7459 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7460 if (isa<BlockDecl>(Caller))
7461 break;
7462
7463 SourceLocation SL;
7464 llvm::raw_string_ostream IS(Fixit);
7465 // The attribute goes at the start of the declaration in C/C++ functions
7466 // and methods, but after the declaration for Objective-C methods.
7467 if (isa<ObjCMethodDecl>(Caller)) {
7468 IS << ' ';
7469 SL = Caller->getEndLoc();
7470 }
7471 const LangOptions &LO = S->getLangOpts();
7472 if (LO.C23 || LO.CPlusPlus11)
7473 IS << "[[gnu::" << Attr << "]]";
7474 else if (LO.ObjC || LO.GNUMode)
7475 IS << "__attribute__((" << Attr << "))";
7476 else
7477 break;
7478 if (!isa<ObjCMethodDecl>(Caller)) {
7479 IS << ' ';
7480 SL = Caller->getBeginLoc();
7481 }
7482 IS.flush();
7483
7484 DB << FixItHint::CreateInsertion(SL, Fixit);
7485 } while (false);
7486
7487 // Add implicit format or format_matches attribute.
7489 Caller->addAttr(FormatAttr::CreateImplicit(
7490 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7491 FormatStringIndex, FirstArgumentIndex));
7492 } else {
7493 Caller->addAttr(FormatMatchesAttr::CreateImplicit(
7494 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7495 FormatStringIndex, ReferenceFormatString));
7496 }
7497
7498 {
7499 auto DB = S->Diag(Caller->getLocation(), diag::note_entity_declared_at);
7500 if (ND)
7501 DB << ND;
7502 else
7503 DB << "block";
7504 }
7505 return true;
7506}
7507
7508bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7510 StringLiteral *ReferenceFormatString,
7511 unsigned format_idx, unsigned firstDataArg,
7513 VariadicCallType CallType, SourceLocation Loc,
7514 SourceRange Range,
7515 llvm::SmallBitVector &CheckedVarArgs) {
7516 // CHECK: printf/scanf-like function is called with no format string.
7517 if (format_idx >= Args.size()) {
7518 Diag(Loc, diag::warn_missing_format_string) << Range;
7519 return false;
7520 }
7521
7522 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7523
7524 // CHECK: format string is not a string literal.
7525 //
7526 // Dynamically generated format strings are difficult to
7527 // automatically vet at compile time. Requiring that format strings
7528 // are string literals: (1) permits the checking of format strings by
7529 // the compiler and thereby (2) can practically remove the source of
7530 // many format string exploits.
7531
7532 // Format string can be either ObjC string (e.g. @"%d") or
7533 // C string (e.g. "%d")
7534 // ObjC string uses the same format specifiers as C string, so we can use
7535 // the same format string checking logic for both ObjC and C strings.
7536 UncoveredArgHandler UncoveredArg;
7537 std::optional<unsigned> CallerParamIdx;
7538 StringLiteralCheckType CT = checkFormatStringExpr(
7539 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
7540 firstDataArg, Type, CallType,
7541 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
7542 /*no string offset*/ llvm::APSInt(64, false) = 0, &CallerParamIdx);
7543
7544 // Generate a diagnostic where an uncovered argument is detected.
7545 if (UncoveredArg.hasUncoveredArg()) {
7546 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7547 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7548 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7549 }
7550
7551 if (CT != SLCT_NotALiteral)
7552 // Literal format string found, check done!
7553 return CT == SLCT_CheckedLiteral;
7554
7555 // Do not emit diag when the string param is a macro expansion and the
7556 // format is either NSString or CFString. This is a hack to prevent
7557 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7558 // which are usually used in place of NS and CF string literals.
7559 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7561 SourceMgr.isInSystemMacro(FormatLoc))
7562 return false;
7563
7564 if (CallerParamIdx && CheckMissingFormatAttribute(
7565 this, Args, APK, ReferenceFormatString, format_idx,
7566 firstDataArg, Type, *CallerParamIdx, Loc))
7567 return false;
7568
7569 // Strftime is particular as it always uses a single 'time' argument,
7570 // so it is safe to pass a non-literal string.
7572 return false;
7573
7574 // If there are no arguments specified, warn with -Wformat-security, otherwise
7575 // warn only with -Wformat-nonliteral.
7576 if (Args.size() == firstDataArg) {
7577 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7578 << OrigFormatExpr->getSourceRange();
7579 switch (Type) {
7580 default:
7581 break;
7585 Diag(FormatLoc, diag::note_format_security_fixit)
7586 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7587 break;
7589 Diag(FormatLoc, diag::note_format_security_fixit)
7590 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7591 break;
7592 }
7593 } else {
7594 Diag(FormatLoc, diag::warn_format_nonliteral)
7595 << OrigFormatExpr->getSourceRange();
7596 }
7597 return false;
7598}
7599
7600namespace {
7601
7602class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7603protected:
7604 Sema &S;
7605 const FormatStringLiteral *FExpr;
7606 const Expr *OrigFormatExpr;
7607 const FormatStringType FSType;
7608 const unsigned FirstDataArg;
7609 const unsigned NumDataArgs;
7610 const char *Beg; // Start of format string.
7611 const Sema::FormatArgumentPassingKind ArgPassingKind;
7612 ArrayRef<const Expr *> Args;
7613 unsigned FormatIdx;
7614 llvm::SmallBitVector CoveredArgs;
7615 bool usesPositionalArgs = false;
7616 bool atFirstArg = true;
7617 bool inFunctionCall;
7618 VariadicCallType CallType;
7619 llvm::SmallBitVector &CheckedVarArgs;
7620 UncoveredArgHandler &UncoveredArg;
7621
7622public:
7623 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7624 const Expr *origFormatExpr, const FormatStringType type,
7625 unsigned firstDataArg, unsigned numDataArgs,
7626 const char *beg, Sema::FormatArgumentPassingKind APK,
7627 ArrayRef<const Expr *> Args, unsigned formatIdx,
7628 bool inFunctionCall, VariadicCallType callType,
7629 llvm::SmallBitVector &CheckedVarArgs,
7630 UncoveredArgHandler &UncoveredArg)
7631 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7632 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7633 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7634 inFunctionCall(inFunctionCall), CallType(callType),
7635 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7636 CoveredArgs.resize(numDataArgs);
7637 CoveredArgs.reset();
7638 }
7639
7640 bool HasFormatArguments() const {
7641 return ArgPassingKind == Sema::FAPK_Fixed ||
7642 ArgPassingKind == Sema::FAPK_Variadic;
7643 }
7644
7645 void DoneProcessing();
7646
7647 void HandleIncompleteSpecifier(const char *startSpecifier,
7648 unsigned specifierLen) override;
7649
7650 void HandleInvalidLengthModifier(
7651 const analyze_format_string::FormatSpecifier &FS,
7652 const analyze_format_string::ConversionSpecifier &CS,
7653 const char *startSpecifier, unsigned specifierLen,
7654 unsigned DiagID);
7655
7656 void HandleNonStandardLengthModifier(
7657 const analyze_format_string::FormatSpecifier &FS,
7658 const char *startSpecifier, unsigned specifierLen);
7659
7660 void HandleNonStandardConversionSpecifier(
7661 const analyze_format_string::ConversionSpecifier &CS,
7662 const char *startSpecifier, unsigned specifierLen);
7663
7664 void HandlePosition(const char *startPos, unsigned posLen) override;
7665
7666 void HandleInvalidPosition(const char *startSpecifier,
7667 unsigned specifierLen,
7669
7670 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7671
7672 void HandleNullChar(const char *nullCharacter) override;
7673
7674 template <typename Range>
7675 static void
7676 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7677 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7678 bool IsStringLocation, Range StringRange,
7679 ArrayRef<FixItHint> Fixit = {});
7680
7681protected:
7682 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7683 const char *startSpec,
7684 unsigned specifierLen,
7685 const char *csStart, unsigned csLen);
7686
7687 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7688 const char *startSpec,
7689 unsigned specifierLen);
7690
7691 SourceRange getFormatStringRange();
7692 CharSourceRange getSpecifierRange(const char *startSpecifier,
7693 unsigned specifierLen);
7694 SourceLocation getLocationOfByte(const char *x);
7695
7696 const Expr *getDataArg(unsigned i) const;
7697
7698 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7699 const analyze_format_string::ConversionSpecifier &CS,
7700 const char *startSpecifier, unsigned specifierLen,
7701 unsigned argIndex);
7702
7703 template <typename Range>
7704 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7705 bool IsStringLocation, Range StringRange,
7706 ArrayRef<FixItHint> Fixit = {});
7707};
7708
7709} // namespace
7710
7711SourceRange CheckFormatHandler::getFormatStringRange() {
7712 return OrigFormatExpr->getSourceRange();
7713}
7714
7715CharSourceRange CheckFormatHandler::
7716getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7717 SourceLocation Start = getLocationOfByte(startSpecifier);
7718 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7719
7720 // Advance the end SourceLocation by one due to half-open ranges.
7721 End = End.getLocWithOffset(1);
7722
7723 return CharSourceRange::getCharRange(Start, End);
7724}
7725
7726SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7727 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7729}
7730
7731void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7732 unsigned specifierLen){
7733 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7734 getLocationOfByte(startSpecifier),
7735 /*IsStringLocation*/true,
7736 getSpecifierRange(startSpecifier, specifierLen));
7737}
7738
7739void CheckFormatHandler::HandleInvalidLengthModifier(
7742 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7743 using namespace analyze_format_string;
7744
7745 const LengthModifier &LM = FS.getLengthModifier();
7746 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7747
7748 // See if we know how to fix this length modifier.
7749 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7750 if (FixedLM) {
7751 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7752 getLocationOfByte(LM.getStart()),
7753 /*IsStringLocation*/true,
7754 getSpecifierRange(startSpecifier, specifierLen));
7755
7756 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7757 << FixedLM->toString()
7758 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7759
7760 } else {
7761 FixItHint Hint;
7762 if (DiagID == diag::warn_format_nonsensical_length)
7763 Hint = FixItHint::CreateRemoval(LMRange);
7764
7765 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7766 getLocationOfByte(LM.getStart()),
7767 /*IsStringLocation*/true,
7768 getSpecifierRange(startSpecifier, specifierLen),
7769 Hint);
7770 }
7771}
7772
7773void CheckFormatHandler::HandleNonStandardLengthModifier(
7775 const char *startSpecifier, unsigned specifierLen) {
7776 using namespace analyze_format_string;
7777
7778 const LengthModifier &LM = FS.getLengthModifier();
7779 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7780
7781 // See if we know how to fix this length modifier.
7782 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7783 if (FixedLM) {
7784 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7785 << LM.toString() << 0,
7786 getLocationOfByte(LM.getStart()),
7787 /*IsStringLocation*/true,
7788 getSpecifierRange(startSpecifier, specifierLen));
7789
7790 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7791 << FixedLM->toString()
7792 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7793
7794 } else {
7795 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7796 << LM.toString() << 0,
7797 getLocationOfByte(LM.getStart()),
7798 /*IsStringLocation*/true,
7799 getSpecifierRange(startSpecifier, specifierLen));
7800 }
7801}
7802
7803void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7805 const char *startSpecifier, unsigned specifierLen) {
7806 using namespace analyze_format_string;
7807
7808 // See if we know how to fix this conversion specifier.
7809 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7810 if (FixedCS) {
7811 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7812 << CS.toString() << /*conversion specifier*/1,
7813 getLocationOfByte(CS.getStart()),
7814 /*IsStringLocation*/true,
7815 getSpecifierRange(startSpecifier, specifierLen));
7816
7817 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7818 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7819 << FixedCS->toString()
7820 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7821 } else {
7822 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7823 << CS.toString() << /*conversion specifier*/1,
7824 getLocationOfByte(CS.getStart()),
7825 /*IsStringLocation*/true,
7826 getSpecifierRange(startSpecifier, specifierLen));
7827 }
7828}
7829
7830void CheckFormatHandler::HandlePosition(const char *startPos,
7831 unsigned posLen) {
7832 if (!S.getDiagnostics().isIgnored(
7833 diag::warn_format_non_standard_positional_arg, SourceLocation()))
7834 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7835 getLocationOfByte(startPos),
7836 /*IsStringLocation*/ true,
7837 getSpecifierRange(startPos, posLen));
7838}
7839
7840void CheckFormatHandler::HandleInvalidPosition(
7841 const char *startSpecifier, unsigned specifierLen,
7843 if (!S.getDiagnostics().isIgnored(
7844 diag::warn_format_invalid_positional_specifier, SourceLocation()))
7845 EmitFormatDiagnostic(
7846 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
7847 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
7848 getSpecifierRange(startSpecifier, specifierLen));
7849}
7850
7851void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7852 unsigned posLen) {
7853 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
7854 SourceLocation()))
7855 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7856 getLocationOfByte(startPos),
7857 /*IsStringLocation*/ true,
7858 getSpecifierRange(startPos, posLen));
7859}
7860
7861void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7862 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7863 // The presence of a null character is likely an error.
7864 EmitFormatDiagnostic(
7865 S.PDiag(diag::warn_printf_format_string_contains_null_char),
7866 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7867 getFormatStringRange());
7868 }
7869}
7870
7871// Note that this may return NULL if there was an error parsing or building
7872// one of the argument expressions.
7873const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7874 return Args[FirstDataArg + i];
7875}
7876
7877void CheckFormatHandler::DoneProcessing() {
7878 // Does the number of data arguments exceed the number of
7879 // format conversions in the format string?
7880 if (HasFormatArguments()) {
7881 // Find any arguments that weren't covered.
7882 CoveredArgs.flip();
7883 signed notCoveredArg = CoveredArgs.find_first();
7884 if (notCoveredArg >= 0) {
7885 assert((unsigned)notCoveredArg < NumDataArgs);
7886 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7887 } else {
7888 UncoveredArg.setAllCovered();
7889 }
7890 }
7891}
7892
7893void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7894 const Expr *ArgExpr) {
7895 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
7896 "Invalid state");
7897
7898 if (!ArgExpr)
7899 return;
7900
7901 SourceLocation Loc = ArgExpr->getBeginLoc();
7902
7903 if (S.getSourceManager().isInSystemMacro(Loc))
7904 return;
7905
7906 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7907 for (auto E : DiagnosticExprs)
7908 PDiag << E->getSourceRange();
7909
7910 CheckFormatHandler::EmitFormatDiagnostic(
7911 S, IsFunctionCall, DiagnosticExprs[0],
7912 PDiag, Loc, /*IsStringLocation*/false,
7913 DiagnosticExprs[0]->getSourceRange());
7914}
7915
7916bool
7917CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7918 SourceLocation Loc,
7919 const char *startSpec,
7920 unsigned specifierLen,
7921 const char *csStart,
7922 unsigned csLen) {
7923 bool keepGoing = true;
7924 if (argIndex < NumDataArgs) {
7925 // Consider the argument coverered, even though the specifier doesn't
7926 // make sense.
7927 CoveredArgs.set(argIndex);
7928 }
7929 else {
7930 // If argIndex exceeds the number of data arguments we
7931 // don't issue a warning because that is just a cascade of warnings (and
7932 // they may have intended '%%' anyway). We don't want to continue processing
7933 // the format string after this point, however, as we will like just get
7934 // gibberish when trying to match arguments.
7935 keepGoing = false;
7936 }
7937
7938 StringRef Specifier(csStart, csLen);
7939
7940 // If the specifier in non-printable, it could be the first byte of a UTF-8
7941 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7942 // hex value.
7943 std::string CodePointStr;
7944 if (!llvm::sys::locale::isPrint(*csStart)) {
7945 llvm::UTF32 CodePoint;
7946 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7947 const llvm::UTF8 *E =
7948 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7949 llvm::ConversionResult Result =
7950 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7951
7952 if (Result != llvm::conversionOK) {
7953 unsigned char FirstChar = *csStart;
7954 CodePoint = (llvm::UTF32)FirstChar;
7955 }
7956
7957 llvm::raw_string_ostream OS(CodePointStr);
7958 if (CodePoint < 256)
7959 OS << "\\x" << llvm::format("%02x", CodePoint);
7960 else if (CodePoint <= 0xFFFF)
7961 OS << "\\u" << llvm::format("%04x", CodePoint);
7962 else
7963 OS << "\\U" << llvm::format("%08x", CodePoint);
7964 Specifier = CodePointStr;
7965 }
7966
7967 EmitFormatDiagnostic(
7968 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7969 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7970
7971 return keepGoing;
7972}
7973
7974void
7975CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7976 const char *startSpec,
7977 unsigned specifierLen) {
7978 EmitFormatDiagnostic(
7979 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7980 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7981}
7982
7983bool
7984CheckFormatHandler::CheckNumArgs(
7987 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7988
7989 if (HasFormatArguments() && argIndex >= NumDataArgs) {
7991 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7992 << (argIndex+1) << NumDataArgs)
7993 : S.PDiag(diag::warn_printf_insufficient_data_args);
7994 EmitFormatDiagnostic(
7995 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7996 getSpecifierRange(startSpecifier, specifierLen));
7997
7998 // Since more arguments than conversion tokens are given, by extension
7999 // all arguments are covered, so mark this as so.
8000 UncoveredArg.setAllCovered();
8001 return false;
8002 }
8003 return true;
8004}
8005
8006template<typename Range>
8007void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8008 SourceLocation Loc,
8009 bool IsStringLocation,
8010 Range StringRange,
8011 ArrayRef<FixItHint> FixIt) {
8012 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8013 Loc, IsStringLocation, StringRange, FixIt);
8014}
8015
8016/// If the format string is not within the function call, emit a note
8017/// so that the function call and string are in diagnostic messages.
8018///
8019/// \param InFunctionCall if true, the format string is within the function
8020/// call and only one diagnostic message will be produced. Otherwise, an
8021/// extra note will be emitted pointing to location of the format string.
8022///
8023/// \param ArgumentExpr the expression that is passed as the format string
8024/// argument in the function call. Used for getting locations when two
8025/// diagnostics are emitted.
8026///
8027/// \param PDiag the callee should already have provided any strings for the
8028/// diagnostic message. This function only adds locations and fixits
8029/// to diagnostics.
8030///
8031/// \param Loc primary location for diagnostic. If two diagnostics are
8032/// required, one will be at Loc and a new SourceLocation will be created for
8033/// the other one.
8034///
8035/// \param IsStringLocation if true, Loc points to the format string should be
8036/// used for the note. Otherwise, Loc points to the argument list and will
8037/// be used with PDiag.
8038///
8039/// \param StringRange some or all of the string to highlight. This is
8040/// templated so it can accept either a CharSourceRange or a SourceRange.
8041///
8042/// \param FixIt optional fix it hint for the format string.
8043template <typename Range>
8044void CheckFormatHandler::EmitFormatDiagnostic(
8045 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8046 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8047 Range StringRange, ArrayRef<FixItHint> FixIt) {
8048 if (InFunctionCall) {
8049 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8050 D << StringRange;
8051 D << FixIt;
8052 } else {
8053 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8054 << ArgumentExpr->getSourceRange();
8055
8057 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8058 diag::note_format_string_defined);
8059
8060 Note << StringRange;
8061 Note << FixIt;
8062 }
8063}
8064
8065//===--- CHECK: Printf format string checking -----------------------------===//
8066
8067namespace {
8068
8069class CheckPrintfHandler : public CheckFormatHandler {
8070public:
8071 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8072 const Expr *origFormatExpr, const FormatStringType type,
8073 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8074 const char *beg, Sema::FormatArgumentPassingKind APK,
8075 ArrayRef<const Expr *> Args, unsigned formatIdx,
8076 bool inFunctionCall, VariadicCallType CallType,
8077 llvm::SmallBitVector &CheckedVarArgs,
8078 UncoveredArgHandler &UncoveredArg)
8079 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8080 numDataArgs, beg, APK, Args, formatIdx,
8081 inFunctionCall, CallType, CheckedVarArgs,
8082 UncoveredArg) {}
8083
8084 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8085
8086 /// Returns true if '%@' specifiers are allowed in the format string.
8087 bool allowsObjCArg() const {
8088 return FSType == FormatStringType::NSString ||
8089 FSType == FormatStringType::OSLog ||
8090 FSType == FormatStringType::OSTrace;
8091 }
8092
8093 bool HandleInvalidPrintfConversionSpecifier(
8094 const analyze_printf::PrintfSpecifier &FS,
8095 const char *startSpecifier,
8096 unsigned specifierLen) override;
8097
8098 void handleInvalidMaskType(StringRef MaskType) override;
8099
8100 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8101 const char *startSpecifier, unsigned specifierLen,
8102 const TargetInfo &Target) override;
8103 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8104 const char *StartSpecifier,
8105 unsigned SpecifierLen,
8106 const Expr *E);
8107
8108 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8109 const char *startSpecifier, unsigned specifierLen);
8110 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8111 const analyze_printf::OptionalAmount &Amt,
8112 unsigned type,
8113 const char *startSpecifier, unsigned specifierLen);
8114 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8115 const analyze_printf::OptionalFlag &flag,
8116 const char *startSpecifier, unsigned specifierLen);
8117 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8118 const analyze_printf::OptionalFlag &ignoredFlag,
8119 const analyze_printf::OptionalFlag &flag,
8120 const char *startSpecifier, unsigned specifierLen);
8121 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8122 const Expr *E);
8123
8124 void HandleEmptyObjCModifierFlag(const char *startFlag,
8125 unsigned flagLen) override;
8126
8127 void HandleInvalidObjCModifierFlag(const char *startFlag,
8128 unsigned flagLen) override;
8129
8130 void
8131 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8132 const char *flagsEnd,
8133 const char *conversionPosition) override;
8134};
8135
8136/// Keeps around the information needed to verify that two specifiers are
8137/// compatible.
8138class EquatableFormatArgument {
8139public:
8140 enum SpecifierSensitivity : unsigned {
8141 SS_None,
8142 SS_Private,
8143 SS_Public,
8144 SS_Sensitive
8145 };
8146
8147 enum FormatArgumentRole : unsigned {
8148 FAR_Data,
8149 FAR_FieldWidth,
8150 FAR_Precision,
8151 FAR_Auxiliary, // FreeBSD kernel %b and %D
8152 };
8153
8154private:
8155 analyze_format_string::ArgType ArgType;
8157 StringRef SpecifierLetter;
8158 CharSourceRange Range;
8159 SourceLocation ElementLoc;
8160 FormatArgumentRole Role : 2;
8161 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8162 unsigned Position : 14;
8163 unsigned ModifierFor : 14; // not set for FAR_Data
8164
8165 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8166 bool InFunctionCall) const;
8167
8168public:
8169 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8171 StringRef SpecifierLetter,
8172 analyze_format_string::ArgType ArgType,
8173 FormatArgumentRole Role,
8174 SpecifierSensitivity Sensitivity, unsigned Position,
8175 unsigned ModifierFor)
8176 : ArgType(ArgType), LengthMod(LengthMod),
8177 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8178 Role(Role), Sensitivity(Sensitivity), Position(Position),
8179 ModifierFor(ModifierFor) {}
8180
8181 unsigned getPosition() const { return Position; }
8182 SourceLocation getSourceLocation() const { return ElementLoc; }
8183 CharSourceRange getSourceRange() const { return Range; }
8184 analyze_format_string::LengthModifier getLengthModifier() const {
8185 return analyze_format_string::LengthModifier(nullptr, LengthMod);
8186 }
8187 void setModifierFor(unsigned V) { ModifierFor = V; }
8188
8189 std::string buildFormatSpecifier() const {
8190 std::string result;
8191 llvm::raw_string_ostream(result)
8192 << getLengthModifier().toString() << SpecifierLetter;
8193 return result;
8194 }
8195
8196 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8197 const Expr *FmtExpr, bool InFunctionCall) const;
8198};
8199
8200/// Turns format strings into lists of EquatableSpecifier objects.
8201class DecomposePrintfHandler : public CheckPrintfHandler {
8202 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8203 bool HadError;
8204
8205 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8206 const Expr *origFormatExpr,
8207 const FormatStringType type, unsigned firstDataArg,
8208 unsigned numDataArgs, bool isObjC, const char *beg,
8210 ArrayRef<const Expr *> Args, unsigned formatIdx,
8211 bool inFunctionCall, VariadicCallType CallType,
8212 llvm::SmallBitVector &CheckedVarArgs,
8213 UncoveredArgHandler &UncoveredArg,
8214 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8215 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8216 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8217 inFunctionCall, CallType, CheckedVarArgs,
8218 UncoveredArg),
8219 Specs(Specs), HadError(false) {}
8220
8221public:
8222 static bool
8223 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8224 FormatStringType type, bool IsObjC, bool InFunctionCall,
8225 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8226
8227 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8228 const char *startSpecifier,
8229 unsigned specifierLen,
8230 const TargetInfo &Target) override;
8231};
8232
8233} // namespace
8234
8235bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8236 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8237 unsigned specifierLen) {
8240
8241 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8242 getLocationOfByte(CS.getStart()),
8243 startSpecifier, specifierLen,
8244 CS.getStart(), CS.getLength());
8245}
8246
8247void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8248 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8249}
8250
8251// Error out if struct or complex type argments are passed to os_log.
8253 QualType T) {
8254 if (FSType != FormatStringType::OSLog)
8255 return false;
8256 return T->isRecordType() || T->isComplexType();
8257}
8258
8259bool CheckPrintfHandler::HandleAmount(
8260 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8261 const char *startSpecifier, unsigned specifierLen) {
8262 if (Amt.hasDataArgument()) {
8263 if (HasFormatArguments()) {
8264 unsigned argIndex = Amt.getArgIndex();
8265 if (argIndex >= NumDataArgs) {
8266 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8267 << k,
8268 getLocationOfByte(Amt.getStart()),
8269 /*IsStringLocation*/ true,
8270 getSpecifierRange(startSpecifier, specifierLen));
8271 // Don't do any more checking. We will just emit
8272 // spurious errors.
8273 return false;
8274 }
8275
8276 // Type check the data argument. It should be an 'int'.
8277 // Although not in conformance with C99, we also allow the argument to be
8278 // an 'unsigned int' as that is a reasonably safe case. GCC also
8279 // doesn't emit a warning for that case.
8280 CoveredArgs.set(argIndex);
8281 const Expr *Arg = getDataArg(argIndex);
8282 if (!Arg)
8283 return false;
8284
8285 QualType T = Arg->getType();
8286
8287 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8288 assert(AT.isValid());
8289
8290 if (!AT.matchesType(S.Context, T)) {
8291 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8292 ? diag::err_printf_asterisk_wrong_type
8293 : diag::warn_printf_asterisk_wrong_type;
8294 EmitFormatDiagnostic(S.PDiag(DiagID)
8296 << T << Arg->getSourceRange(),
8297 getLocationOfByte(Amt.getStart()),
8298 /*IsStringLocation*/ true,
8299 getSpecifierRange(startSpecifier, specifierLen));
8300 // Don't do any more checking. We will just emit
8301 // spurious errors.
8302 return false;
8303 }
8304 }
8305 }
8306 return true;
8307}
8308
8309void CheckPrintfHandler::HandleInvalidAmount(
8312 unsigned type,
8313 const char *startSpecifier,
8314 unsigned specifierLen) {
8317
8318 FixItHint fixit =
8320 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8321 Amt.getConstantLength()))
8322 : FixItHint();
8323
8324 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8325 << type << CS.toString(),
8326 getLocationOfByte(Amt.getStart()),
8327 /*IsStringLocation*/true,
8328 getSpecifierRange(startSpecifier, specifierLen),
8329 fixit);
8330}
8331
8332void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8333 const analyze_printf::OptionalFlag &flag,
8334 const char *startSpecifier,
8335 unsigned specifierLen) {
8336 // Warn about pointless flag with a fixit removal.
8339 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8340 << flag.toString() << CS.toString(),
8341 getLocationOfByte(flag.getPosition()),
8342 /*IsStringLocation*/true,
8343 getSpecifierRange(startSpecifier, specifierLen),
8345 getSpecifierRange(flag.getPosition(), 1)));
8346}
8347
8348void CheckPrintfHandler::HandleIgnoredFlag(
8350 const analyze_printf::OptionalFlag &ignoredFlag,
8351 const analyze_printf::OptionalFlag &flag,
8352 const char *startSpecifier,
8353 unsigned specifierLen) {
8354 // Warn about ignored flag with a fixit removal.
8355 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8356 << ignoredFlag.toString() << flag.toString(),
8357 getLocationOfByte(ignoredFlag.getPosition()),
8358 /*IsStringLocation*/true,
8359 getSpecifierRange(startSpecifier, specifierLen),
8361 getSpecifierRange(ignoredFlag.getPosition(), 1)));
8362}
8363
8364void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8365 unsigned flagLen) {
8366 // Warn about an empty flag.
8367 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8368 getLocationOfByte(startFlag),
8369 /*IsStringLocation*/true,
8370 getSpecifierRange(startFlag, flagLen));
8371}
8372
8373void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8374 unsigned flagLen) {
8375 // Warn about an invalid flag.
8376 auto Range = getSpecifierRange(startFlag, flagLen);
8377 StringRef flag(startFlag, flagLen);
8378 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8379 getLocationOfByte(startFlag),
8380 /*IsStringLocation*/true,
8381 Range, FixItHint::CreateRemoval(Range));
8382}
8383
8384void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8385 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8386 // Warn about using '[...]' without a '@' conversion.
8387 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8388 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8389 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8390 getLocationOfByte(conversionPosition),
8391 /*IsStringLocation*/ true, Range,
8393}
8394
8395void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8396 const Expr *FmtExpr,
8397 bool InFunctionCall) const {
8398 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
8399 ElementLoc, true, Range);
8400}
8401
8402bool EquatableFormatArgument::VerifyCompatible(
8403 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8404 bool InFunctionCall) const {
8406 if (Role != Other.Role) {
8407 // diagnose and stop
8408 EmitDiagnostic(
8409 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8410 FmtExpr, InFunctionCall);
8411 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8412 return false;
8413 }
8414
8415 if (Role != FAR_Data) {
8416 if (ModifierFor != Other.ModifierFor) {
8417 // diagnose and stop
8418 EmitDiagnostic(S,
8419 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
8420 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8421 FmtExpr, InFunctionCall);
8422 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8423 return false;
8424 }
8425 return true;
8426 }
8427
8428 bool HadError = false;
8429 if (Sensitivity != Other.Sensitivity) {
8430 // diagnose and continue
8431 EmitDiagnostic(S,
8432 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
8433 << Sensitivity << Other.Sensitivity,
8434 FmtExpr, InFunctionCall);
8435 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8436 << 0 << Other.Range;
8437 }
8438
8439 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
8440 case MK::Match:
8441 break;
8442
8443 case MK::MatchPromotion:
8444 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8445 // MatchPromotion is treated as a failure by format_matches.
8446 case MK::NoMatch:
8447 case MK::NoMatchTypeConfusion:
8448 case MK::NoMatchPromotionTypeConfusion:
8449 EmitDiagnostic(S,
8450 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
8451 << buildFormatSpecifier()
8452 << Other.buildFormatSpecifier(),
8453 FmtExpr, InFunctionCall);
8454 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8455 << 0 << Other.Range;
8456 break;
8457
8458 case MK::NoMatchPedantic:
8459 EmitDiagnostic(S,
8460 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
8461 << buildFormatSpecifier()
8462 << Other.buildFormatSpecifier(),
8463 FmtExpr, InFunctionCall);
8464 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8465 << 0 << Other.Range;
8466 break;
8467
8468 case MK::NoMatchSignedness:
8469 EmitDiagnostic(S,
8470 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
8471 << buildFormatSpecifier()
8472 << Other.buildFormatSpecifier(),
8473 FmtExpr, InFunctionCall);
8474 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8475 << 0 << Other.Range;
8476 break;
8477 }
8478 return !HadError;
8479}
8480
8481bool DecomposePrintfHandler::GetSpecifiers(
8482 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8483 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8485 StringRef Data = FSL->getString();
8486 const char *Str = Data.data();
8487 llvm::SmallBitVector BV;
8488 UncoveredArgHandler UA;
8489 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8490 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8491 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8492 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8493 UA, Args);
8494
8496 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
8498 H.DoneProcessing();
8499 if (H.HadError)
8500 return false;
8501
8502 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
8503 const EquatableFormatArgument &B) {
8504 return A.getPosition() < B.getPosition();
8505 });
8506 return true;
8507}
8508
8509bool DecomposePrintfHandler::HandlePrintfSpecifier(
8510 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8511 unsigned specifierLen, const TargetInfo &Target) {
8512 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8513 specifierLen, Target)) {
8514 HadError = true;
8515 return false;
8516 }
8517
8518 // Do not add any specifiers to the list for %%. This is possibly incorrect
8519 // if using a precision/width with a data argument, but that combination is
8520 // meaningless and we wouldn't know which format to attach the
8521 // precision/width to.
8522 const auto &CS = FS.getConversionSpecifier();
8524 return true;
8525
8526 // have to patch these to have the right ModifierFor if they are used
8527 const unsigned Unset = ~0;
8528 unsigned FieldWidthIndex = Unset;
8529 unsigned PrecisionIndex = Unset;
8530
8531 // field width?
8532 const auto &FieldWidth = FS.getFieldWidth();
8533 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8534 FieldWidthIndex = Specs.size();
8535 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8536 getLocationOfByte(FieldWidth.getStart()),
8538 FieldWidth.getArgType(S.Context),
8539 EquatableFormatArgument::FAR_FieldWidth,
8540 EquatableFormatArgument::SS_None,
8541 FieldWidth.usesPositionalArg()
8542 ? FieldWidth.getPositionalArgIndex() - 1
8543 : FieldWidthIndex,
8544 0);
8545 }
8546 // precision?
8547 const auto &Precision = FS.getPrecision();
8548 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8549 PrecisionIndex = Specs.size();
8550 Specs.emplace_back(
8551 getSpecifierRange(startSpecifier, specifierLen),
8552 getLocationOfByte(Precision.getStart()),
8554 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
8555 EquatableFormatArgument::SS_None,
8556 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8557 : PrecisionIndex,
8558 0);
8559 }
8560
8561 // this specifier
8562 unsigned SpecIndex =
8563 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8564 if (FieldWidthIndex != Unset)
8565 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8566 if (PrecisionIndex != Unset)
8567 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8568
8569 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8570 if (FS.isPrivate())
8571 Sensitivity = EquatableFormatArgument::SS_Private;
8572 else if (FS.isPublic())
8573 Sensitivity = EquatableFormatArgument::SS_Public;
8574 else if (FS.isSensitive())
8575 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8576 else
8577 Sensitivity = EquatableFormatArgument::SS_None;
8578
8579 Specs.emplace_back(
8580 getSpecifierRange(startSpecifier, specifierLen),
8581 getLocationOfByte(CS.getStart()), FS.getLengthModifier().getKind(),
8582 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
8583 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
8584
8585 // auxiliary argument?
8588 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8589 getLocationOfByte(CS.getStart()),
8591 CS.getCharacters(),
8593 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
8594 SpecIndex + 1, SpecIndex);
8595 }
8596 return true;
8597}
8598
8599// Determines if the specified is a C++ class or struct containing
8600// a member with the specified name and kind (e.g. a CXXMethodDecl named
8601// "c_str()").
8602template<typename MemberKind>
8604CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8605 auto *RD = Ty->getAsCXXRecordDecl();
8607
8608 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8609 return Results;
8610
8611 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8613 R.suppressDiagnostics();
8614
8615 // We just need to include all members of the right kind turned up by the
8616 // filter, at this point.
8617 if (S.LookupQualifiedName(R, RD))
8618 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8619 NamedDecl *decl = (*I)->getUnderlyingDecl();
8620 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8621 Results.insert(FK);
8622 }
8623 return Results;
8624}
8625
8626/// Check if we could call '.c_str()' on an object.
8627///
8628/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8629/// allow the call, or if it would be ambiguous).
8631 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8632
8633 MethodSet Results =
8634 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8635 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8636 MI != ME; ++MI)
8637 if ((*MI)->getMinRequiredArguments() == 0)
8638 return true;
8639 return false;
8640}
8641
8642// Check if a (w)string was passed when a (w)char* was needed, and offer a
8643// better diagnostic if so. AT is assumed to be valid.
8644// Returns true when a c_str() conversion method is found.
8645bool CheckPrintfHandler::checkForCStrMembers(
8646 const analyze_printf::ArgType &AT, const Expr *E) {
8647 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8648
8649 MethodSet Results =
8651
8652 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8653 MI != ME; ++MI) {
8654 const CXXMethodDecl *Method = *MI;
8655 if (Method->getMinRequiredArguments() == 0 &&
8656 AT.matchesType(S.Context, Method->getReturnType())) {
8657 // FIXME: Suggest parens if the expression needs them.
8659 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8660 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8661 return true;
8662 }
8663 }
8664
8665 return false;
8666}
8667
8668bool CheckPrintfHandler::HandlePrintfSpecifier(
8669 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8670 unsigned specifierLen, const TargetInfo &Target) {
8671 using namespace analyze_format_string;
8672 using namespace analyze_printf;
8673
8674 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8675
8676 if (FS.consumesDataArgument()) {
8677 if (atFirstArg) {
8678 atFirstArg = false;
8679 usesPositionalArgs = FS.usesPositionalArg();
8680 }
8681 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8682 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8683 startSpecifier, specifierLen);
8684 return false;
8685 }
8686 }
8687
8688 // First check if the field width, precision, and conversion specifier
8689 // have matching data arguments.
8690 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8691 startSpecifier, specifierLen)) {
8692 return false;
8693 }
8694
8695 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8696 startSpecifier, specifierLen)) {
8697 return false;
8698 }
8699
8700 if (!CS.consumesDataArgument()) {
8701 // FIXME: Technically specifying a precision or field width here
8702 // makes no sense. Worth issuing a warning at some point.
8703 return true;
8704 }
8705
8706 // Consume the argument.
8707 unsigned argIndex = FS.getArgIndex();
8708 if (argIndex < NumDataArgs) {
8709 // The check to see if the argIndex is valid will come later.
8710 // We set the bit here because we may exit early from this
8711 // function if we encounter some other error.
8712 CoveredArgs.set(argIndex);
8713 }
8714
8715 // FreeBSD kernel extensions.
8716 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8717 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8718 // We need at least two arguments.
8719 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8720 return false;
8721
8722 if (HasFormatArguments()) {
8723 // Claim the second argument.
8724 CoveredArgs.set(argIndex + 1);
8725
8726 // Type check the first argument (int for %b, pointer for %D)
8727 const Expr *Ex = getDataArg(argIndex);
8728 const analyze_printf::ArgType &AT =
8729 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8730 ? ArgType(S.Context.IntTy)
8731 : ArgType::CPointerTy;
8732 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8733 EmitFormatDiagnostic(
8734 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8735 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8736 << false << Ex->getSourceRange(),
8737 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8738 getSpecifierRange(startSpecifier, specifierLen));
8739
8740 // Type check the second argument (char * for both %b and %D)
8741 Ex = getDataArg(argIndex + 1);
8743 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8744 EmitFormatDiagnostic(
8745 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8746 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8747 << false << Ex->getSourceRange(),
8748 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8749 getSpecifierRange(startSpecifier, specifierLen));
8750 }
8751 return true;
8752 }
8753
8754 // Check for using an Objective-C specific conversion specifier
8755 // in a non-ObjC literal.
8756 if (!allowsObjCArg() && CS.isObjCArg()) {
8757 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8758 specifierLen);
8759 }
8760
8761 // %P can only be used with os_log.
8762 if (FSType != FormatStringType::OSLog &&
8763 CS.getKind() == ConversionSpecifier::PArg) {
8764 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8765 specifierLen);
8766 }
8767
8768 // %n is not allowed with os_log.
8769 if (FSType == FormatStringType::OSLog &&
8770 CS.getKind() == ConversionSpecifier::nArg) {
8771 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8772 getLocationOfByte(CS.getStart()),
8773 /*IsStringLocation*/ false,
8774 getSpecifierRange(startSpecifier, specifierLen));
8775
8776 return true;
8777 }
8778
8779 // Only scalars are allowed for os_trace.
8780 if (FSType == FormatStringType::OSTrace &&
8781 (CS.getKind() == ConversionSpecifier::PArg ||
8782 CS.getKind() == ConversionSpecifier::sArg ||
8783 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8784 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8785 specifierLen);
8786 }
8787
8788 // Check for use of public/private annotation outside of os_log().
8789 if (FSType != FormatStringType::OSLog) {
8790 if (FS.isPublic().isSet()) {
8791 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8792 << "public",
8793 getLocationOfByte(FS.isPublic().getPosition()),
8794 /*IsStringLocation*/ false,
8795 getSpecifierRange(startSpecifier, specifierLen));
8796 }
8797 if (FS.isPrivate().isSet()) {
8798 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8799 << "private",
8800 getLocationOfByte(FS.isPrivate().getPosition()),
8801 /*IsStringLocation*/ false,
8802 getSpecifierRange(startSpecifier, specifierLen));
8803 }
8804 }
8805
8806 const llvm::Triple &Triple = Target.getTriple();
8807 if (CS.getKind() == ConversionSpecifier::nArg &&
8808 (Triple.isAndroid() || Triple.isOSFuchsia())) {
8809 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
8810 getLocationOfByte(CS.getStart()),
8811 /*IsStringLocation*/ false,
8812 getSpecifierRange(startSpecifier, specifierLen));
8813 }
8814
8815 // Check for invalid use of field width
8816 if (!FS.hasValidFieldWidth()) {
8817 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8818 startSpecifier, specifierLen);
8819 }
8820
8821 // Check for invalid use of precision
8822 if (!FS.hasValidPrecision()) {
8823 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8824 startSpecifier, specifierLen);
8825 }
8826
8827 // Precision is mandatory for %P specifier.
8828 if (CS.getKind() == ConversionSpecifier::PArg &&
8830 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8831 getLocationOfByte(startSpecifier),
8832 /*IsStringLocation*/ false,
8833 getSpecifierRange(startSpecifier, specifierLen));
8834 }
8835
8836 // Check each flag does not conflict with any other component.
8838 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8839 if (!FS.hasValidLeadingZeros())
8840 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8841 if (!FS.hasValidPlusPrefix())
8842 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8843 if (!FS.hasValidSpacePrefix())
8844 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8845 if (!FS.hasValidAlternativeForm())
8846 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8847 if (!FS.hasValidLeftJustified())
8848 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8849
8850 // Check that flags are not ignored by another flag
8851 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8852 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8853 startSpecifier, specifierLen);
8854 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8855 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8856 startSpecifier, specifierLen);
8857
8858 // Check the length modifier is valid with the given conversion specifier.
8860 S.getLangOpts()))
8861 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8862 diag::warn_format_nonsensical_length);
8863 else if (!FS.hasStandardLengthModifier())
8864 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8866 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8867 diag::warn_format_non_standard_conversion_spec);
8868
8870 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8871
8872 // The remaining checks depend on the data arguments.
8873 if (!HasFormatArguments())
8874 return true;
8875
8876 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8877 return false;
8878
8879 const Expr *Arg = getDataArg(argIndex);
8880 if (!Arg)
8881 return true;
8882
8883 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8884}
8885
8886static bool requiresParensToAddCast(const Expr *E) {
8887 // FIXME: We should have a general way to reason about operator
8888 // precedence and whether parens are actually needed here.
8889 // Take care of a few common cases where they aren't.
8890 const Expr *Inside = E->IgnoreImpCasts();
8891 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8892 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8893
8894 switch (Inside->getStmtClass()) {
8895 case Stmt::ArraySubscriptExprClass:
8896 case Stmt::CallExprClass:
8897 case Stmt::CharacterLiteralClass:
8898 case Stmt::CXXBoolLiteralExprClass:
8899 case Stmt::DeclRefExprClass:
8900 case Stmt::FloatingLiteralClass:
8901 case Stmt::IntegerLiteralClass:
8902 case Stmt::MemberExprClass:
8903 case Stmt::ObjCArrayLiteralClass:
8904 case Stmt::ObjCBoolLiteralExprClass:
8905 case Stmt::ObjCBoxedExprClass:
8906 case Stmt::ObjCDictionaryLiteralClass:
8907 case Stmt::ObjCEncodeExprClass:
8908 case Stmt::ObjCIvarRefExprClass:
8909 case Stmt::ObjCMessageExprClass:
8910 case Stmt::ObjCPropertyRefExprClass:
8911 case Stmt::ObjCStringLiteralClass:
8912 case Stmt::ObjCSubscriptRefExprClass:
8913 case Stmt::ParenExprClass:
8914 case Stmt::StringLiteralClass:
8915 case Stmt::UnaryOperatorClass:
8916 return false;
8917 default:
8918 return true;
8919 }
8920}
8921
8922static std::pair<QualType, StringRef>
8924 QualType IntendedTy,
8925 const Expr *E) {
8926 // Use a 'while' to peel off layers of typedefs.
8927 QualType TyTy = IntendedTy;
8928 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8929 StringRef Name = UserTy->getDecl()->getName();
8930 QualType CastTy = llvm::StringSwitch<QualType>(Name)
8931 .Case("CFIndex", Context.getNSIntegerType())
8932 .Case("NSInteger", Context.getNSIntegerType())
8933 .Case("NSUInteger", Context.getNSUIntegerType())
8934 .Case("SInt32", Context.IntTy)
8935 .Case("UInt32", Context.UnsignedIntTy)
8936 .Default(QualType());
8937
8938 if (!CastTy.isNull())
8939 return std::make_pair(CastTy, Name);
8940
8941 TyTy = UserTy->desugar();
8942 }
8943
8944 // Strip parens if necessary.
8945 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8946 return shouldNotPrintDirectly(Context,
8947 PE->getSubExpr()->getType(),
8948 PE->getSubExpr());
8949
8950 // If this is a conditional expression, then its result type is constructed
8951 // via usual arithmetic conversions and thus there might be no necessary
8952 // typedef sugar there. Recurse to operands to check for NSInteger &
8953 // Co. usage condition.
8954 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8955 QualType TrueTy, FalseTy;
8956 StringRef TrueName, FalseName;
8957
8958 std::tie(TrueTy, TrueName) =
8959 shouldNotPrintDirectly(Context,
8960 CO->getTrueExpr()->getType(),
8961 CO->getTrueExpr());
8962 std::tie(FalseTy, FalseName) =
8963 shouldNotPrintDirectly(Context,
8964 CO->getFalseExpr()->getType(),
8965 CO->getFalseExpr());
8966
8967 if (TrueTy == FalseTy)
8968 return std::make_pair(TrueTy, TrueName);
8969 else if (TrueTy.isNull())
8970 return std::make_pair(FalseTy, FalseName);
8971 else if (FalseTy.isNull())
8972 return std::make_pair(TrueTy, TrueName);
8973 }
8974
8975 return std::make_pair(QualType(), StringRef());
8976}
8977
8978/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8979/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8980/// type do not count.
8981static bool
8983 QualType From = ICE->getSubExpr()->getType();
8984 QualType To = ICE->getType();
8985 // It's an integer promotion if the destination type is the promoted
8986 // source type.
8987 if (ICE->getCastKind() == CK_IntegralCast &&
8989 S.Context.getPromotedIntegerType(From) == To)
8990 return true;
8991 // Look through vector types, since we do default argument promotion for
8992 // those in OpenCL.
8993 if (const auto *VecTy = From->getAs<ExtVectorType>())
8994 From = VecTy->getElementType();
8995 if (const auto *VecTy = To->getAs<ExtVectorType>())
8996 To = VecTy->getElementType();
8997 // It's a floating promotion if the source type is a lower rank.
8998 return ICE->getCastKind() == CK_FloatingCast &&
8999 S.Context.getFloatingTypeOrder(From, To) < 0;
9000}
9001
9004 DiagnosticsEngine &Diags, SourceLocation Loc) {
9006 if (Diags.isIgnored(
9007 diag::warn_format_conversion_argument_type_mismatch_signedness,
9008 Loc) ||
9009 Diags.isIgnored(
9010 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9011 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9013 }
9014 }
9015 return Match;
9016}
9017
9018bool
9019CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9020 const char *StartSpecifier,
9021 unsigned SpecifierLen,
9022 const Expr *E) {
9023 using namespace analyze_format_string;
9024 using namespace analyze_printf;
9025
9026 // Now type check the data expression that matches the
9027 // format specifier.
9028 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9029 if (!AT.isValid())
9030 return true;
9031
9032 QualType ExprTy = E->getType();
9033 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9034 ExprTy = TET->getUnderlyingExpr()->getType();
9035 }
9036
9037 if (const OverflowBehaviorType *OBT =
9038 dyn_cast<OverflowBehaviorType>(ExprTy.getCanonicalType()))
9039 ExprTy = OBT->getUnderlyingType();
9040
9041 // When using the format attribute in C++, you can receive a function or an
9042 // array that will necessarily decay to a pointer when passed to the final
9043 // format consumer. Apply decay before type comparison.
9044 if (ExprTy->canDecayToPointerType())
9045 ExprTy = S.Context.getDecayedType(ExprTy);
9046
9047 // Diagnose attempts to print a boolean value as a character. Unlike other
9048 // -Wformat diagnostics, this is fine from a type perspective, but it still
9049 // doesn't make sense.
9052 const CharSourceRange &CSR =
9053 getSpecifierRange(StartSpecifier, SpecifierLen);
9054 SmallString<4> FSString;
9055 llvm::raw_svector_ostream os(FSString);
9056 FS.toString(os);
9057 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9058 << FSString,
9059 E->getExprLoc(), false, CSR);
9060 return true;
9061 }
9062
9063 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9064 // dumping raw class data (like is-a pointer), not actual data.
9066 ExprTy->isObjCObjectPointerType()) {
9067 const CharSourceRange &CSR =
9068 getSpecifierRange(StartSpecifier, SpecifierLen);
9069 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
9070 E->getExprLoc(), false, CSR);
9071 return true;
9072 }
9073
9074 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9076 ArgType::MatchKind OrigMatch = Match;
9077
9079 if (Match == ArgType::Match)
9080 return true;
9081
9082 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9083 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9084
9085 // Look through argument promotions for our error message's reported type.
9086 // This includes the integral and floating promotions, but excludes array
9087 // and function pointer decay (seeing that an argument intended to be a
9088 // string has type 'char [6]' is probably more confusing than 'char *') and
9089 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9090 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9091 if (isArithmeticArgumentPromotion(S, ICE)) {
9092 E = ICE->getSubExpr();
9093 ExprTy = E->getType();
9094
9095 // Check if we didn't match because of an implicit cast from a 'char'
9096 // or 'short' to an 'int'. This is done because printf is a varargs
9097 // function.
9098 if (ICE->getType() == S.Context.IntTy ||
9099 ICE->getType() == S.Context.UnsignedIntTy) {
9100 // All further checking is done on the subexpression
9101 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
9102 if (OrigMatch == ArgType::NoMatchSignedness &&
9103 ImplicitMatch != ArgType::NoMatchSignedness)
9104 // If the original match was a signedness match this match on the
9105 // implicit cast type also need to be signedness match otherwise we
9106 // might introduce new unexpected warnings from -Wformat-signedness.
9107 return true;
9108 ImplicitMatch = handleFormatSignedness(
9109 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
9110 if (ImplicitMatch == ArgType::Match)
9111 return true;
9112 }
9113 }
9114 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9115 // Special case for 'a', which has type 'int' in C.
9116 // Note, however, that we do /not/ want to treat multibyte constants like
9117 // 'MooV' as characters! This form is deprecated but still exists. In
9118 // addition, don't treat expressions as of type 'char' if one byte length
9119 // modifier is provided.
9120 if (ExprTy == S.Context.IntTy &&
9122 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
9123 ExprTy = S.Context.CharTy;
9124 // To improve check results, we consider a character literal in C
9125 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9126 // more likely a type confusion situation, so we will suggest to
9127 // use '%hhd' instead by discarding the MatchPromotion.
9128 if (Match == ArgType::MatchPromotion)
9130 }
9131 }
9132 if (Match == ArgType::MatchPromotion) {
9133 // WG14 N2562 only clarified promotions in *printf
9134 // For NSLog in ObjC, just preserve -Wformat behavior
9135 if (!S.getLangOpts().ObjC &&
9136 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9137 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9138 return true;
9140 }
9141 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9142 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9143 Match = ImplicitMatch;
9144 assert(Match != ArgType::MatchPromotion);
9145
9146 // Look through unscoped enums to their underlying type.
9147 bool IsEnum = false;
9148 bool IsScopedEnum = false;
9149 QualType IntendedTy = ExprTy;
9150 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9151 IntendedTy = ED->getIntegerType();
9152 if (!ED->isScoped()) {
9153 ExprTy = IntendedTy;
9154 // This controls whether we're talking about the underlying type or not,
9155 // which we only want to do when it's an unscoped enum.
9156 IsEnum = true;
9157 } else {
9158 IsScopedEnum = true;
9159 }
9160 }
9161
9162 // %C in an Objective-C context prints a unichar, not a wchar_t.
9163 // If the argument is an integer of some kind, believe the %C and suggest
9164 // a cast instead of changing the conversion specifier.
9165 if (isObjCContext() &&
9168 !ExprTy->isCharType()) {
9169 // 'unichar' is defined as a typedef of unsigned short, but we should
9170 // prefer using the typedef if it is visible.
9171 IntendedTy = S.Context.UnsignedShortTy;
9172
9173 // While we are here, check if the value is an IntegerLiteral that happens
9174 // to be within the valid range.
9175 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9176 const llvm::APInt &V = IL->getValue();
9177 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9178 return true;
9179 }
9180
9181 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9183 if (S.LookupName(Result, S.getCurScope())) {
9184 NamedDecl *ND = Result.getFoundDecl();
9185 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9186 if (TD->getUnderlyingType() == IntendedTy)
9187 IntendedTy =
9189 /*Qualifier=*/std::nullopt, TD);
9190 }
9191 }
9192 }
9193
9194 // Special-case some of Darwin's platform-independence types by suggesting
9195 // casts to primitive types that are known to be large enough.
9196 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9197 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9198 QualType CastTy;
9199 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9200 if (!CastTy.isNull()) {
9201 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9202 // (long in ASTContext). Only complain to pedants or when they're the
9203 // underlying type of a scoped enum (which always needs a cast).
9204 if (!IsScopedEnum &&
9205 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9206 (AT.isSizeT() || AT.isPtrdiffT()) &&
9207 AT.matchesType(S.Context, CastTy))
9209 IntendedTy = CastTy;
9210 ShouldNotPrintDirectly = true;
9211 }
9212 }
9213
9214 // We may be able to offer a FixItHint if it is a supported type.
9215 PrintfSpecifier fixedFS = FS;
9216 bool Success =
9217 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9218
9219 if (Success) {
9220 // Get the fix string from the fixed format specifier
9221 SmallString<16> buf;
9222 llvm::raw_svector_ostream os(buf);
9223 fixedFS.toString(os);
9224
9225 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9226
9227 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9228 unsigned Diag;
9229 switch (Match) {
9230 case ArgType::Match:
9233 llvm_unreachable("expected non-matching");
9235 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9236 break;
9238 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9239 break;
9241 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9242 break;
9243 case ArgType::NoMatch:
9244 Diag = diag::warn_format_conversion_argument_type_mismatch;
9245 break;
9246 }
9247
9248 // In this case, the specifier is wrong and should be changed to match
9249 // the argument.
9250 EmitFormatDiagnostic(S.PDiag(Diag)
9252 << IntendedTy << IsEnum << E->getSourceRange(),
9253 E->getBeginLoc(),
9254 /*IsStringLocation*/ false, SpecRange,
9255 FixItHint::CreateReplacement(SpecRange, os.str()));
9256 } else {
9257 // The canonical type for formatting this value is different from the
9258 // actual type of the expression. (This occurs, for example, with Darwin's
9259 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9260 // should be printed as 'long' for 64-bit compatibility.)
9261 // Rather than emitting a normal format/argument mismatch, we want to
9262 // add a cast to the recommended type (and correct the format string
9263 // if necessary). We should also do so for scoped enumerations.
9264 SmallString<16> CastBuf;
9265 llvm::raw_svector_ostream CastFix(CastBuf);
9266 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9267 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9268 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9269
9271 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
9272 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
9273 E->getExprLoc());
9274 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9275 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9276
9277 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9278 // If there's already a cast present, just replace it.
9279 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9280 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9281
9282 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9283 // If the expression has high enough precedence,
9284 // just write the C-style cast.
9285 Hints.push_back(
9286 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9287 } else {
9288 // Otherwise, add parens around the expression as well as the cast.
9289 CastFix << "(";
9290 Hints.push_back(
9291 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9292
9293 // We don't use getLocForEndOfToken because it returns invalid source
9294 // locations for macro expansions (by design).
9298 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9299 }
9300
9301 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9302 // The expression has a type that should not be printed directly.
9303 // We extract the name from the typedef because we don't want to show
9304 // the underlying type in the diagnostic.
9305 StringRef Name;
9306 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9307 Name = TypedefTy->getDecl()->getName();
9308 else
9309 Name = CastTyName;
9310 unsigned Diag = Match == ArgType::NoMatchPedantic
9311 ? diag::warn_format_argument_needs_cast_pedantic
9312 : diag::warn_format_argument_needs_cast;
9313 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9314 << E->getSourceRange(),
9315 E->getBeginLoc(), /*IsStringLocation=*/false,
9316 SpecRange, Hints);
9317 } else {
9318 // In this case, the expression could be printed using a different
9319 // specifier, but we've decided that the specifier is probably correct
9320 // and we should cast instead. Just use the normal warning message.
9321
9322 unsigned Diag =
9323 IsScopedEnum
9324 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9325 : diag::warn_format_conversion_argument_type_mismatch;
9326
9327 EmitFormatDiagnostic(
9328 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9329 << IsEnum << E->getSourceRange(),
9330 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9331 }
9332 }
9333 } else {
9334 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9335 SpecifierLen);
9336 // Since the warning for passing non-POD types to variadic functions
9337 // was deferred until now, we emit a warning for non-POD
9338 // arguments here.
9339 bool EmitTypeMismatch = false;
9340 switch (S.isValidVarArgType(ExprTy)) {
9341 case VarArgKind::Valid:
9343 unsigned Diag;
9344 switch (Match) {
9345 case ArgType::Match:
9348 llvm_unreachable("expected non-matching");
9350 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9351 break;
9353 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9354 break;
9356 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9357 break;
9358 case ArgType::NoMatch:
9359 Diag = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)
9360 ? diag::err_format_conversion_argument_type_mismatch
9361 : diag::warn_format_conversion_argument_type_mismatch;
9362 break;
9363 }
9364
9365 EmitFormatDiagnostic(
9366 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9367 << IsEnum << CSR << E->getSourceRange(),
9368 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9369 break;
9370 }
9373 if (CallType == VariadicCallType::DoesNotApply) {
9374 EmitTypeMismatch = true;
9375 } else {
9376 EmitFormatDiagnostic(
9377 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9378 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9379 << AT.getRepresentativeTypeName(S.Context) << CSR
9380 << E->getSourceRange(),
9381 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9382 checkForCStrMembers(AT, E);
9383 }
9384 break;
9385
9387 if (CallType == VariadicCallType::DoesNotApply)
9388 EmitTypeMismatch = true;
9389 else if (ExprTy->isObjCObjectType())
9390 EmitFormatDiagnostic(
9391 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9392 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9393 << AT.getRepresentativeTypeName(S.Context) << CSR
9394 << E->getSourceRange(),
9395 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9396 else
9397 // FIXME: If this is an initializer list, suggest removing the braces
9398 // or inserting a cast to the target type.
9399 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9400 << isa<InitListExpr>(E) << ExprTy << CallType
9402 break;
9403 }
9404
9405 if (EmitTypeMismatch) {
9406 // The function is not variadic, so we do not generate warnings about
9407 // being allowed to pass that object as a variadic argument. Instead,
9408 // since there are inherently no printf specifiers for types which cannot
9409 // be passed as variadic arguments, emit a plain old specifier mismatch
9410 // argument.
9411 EmitFormatDiagnostic(
9412 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9413 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
9414 << E->getSourceRange(),
9415 E->getBeginLoc(), false, CSR);
9416 }
9417
9418 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9419 "format string specifier index out of range");
9420 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9421 }
9422
9423 return true;
9424}
9425
9426//===--- CHECK: Scanf format string checking ------------------------------===//
9427
9428namespace {
9429
9430class CheckScanfHandler : public CheckFormatHandler {
9431public:
9432 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9433 const Expr *origFormatExpr, FormatStringType type,
9434 unsigned firstDataArg, unsigned numDataArgs,
9435 const char *beg, Sema::FormatArgumentPassingKind APK,
9436 ArrayRef<const Expr *> Args, unsigned formatIdx,
9437 bool inFunctionCall, VariadicCallType CallType,
9438 llvm::SmallBitVector &CheckedVarArgs,
9439 UncoveredArgHandler &UncoveredArg)
9440 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9441 numDataArgs, beg, APK, Args, formatIdx,
9442 inFunctionCall, CallType, CheckedVarArgs,
9443 UncoveredArg) {}
9444
9445 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9446 const char *startSpecifier,
9447 unsigned specifierLen) override;
9448
9449 bool HandleInvalidScanfConversionSpecifier(
9450 const analyze_scanf::ScanfSpecifier &FS,
9451 const char *startSpecifier,
9452 unsigned specifierLen) override;
9453
9454 void HandleIncompleteScanList(const char *start, const char *end) override;
9455};
9456
9457} // namespace
9458
9459void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9460 const char *end) {
9461 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9462 getLocationOfByte(end), /*IsStringLocation*/true,
9463 getSpecifierRange(start, end - start));
9464}
9465
9466bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9468 const char *startSpecifier,
9469 unsigned specifierLen) {
9472
9473 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9474 getLocationOfByte(CS.getStart()),
9475 startSpecifier, specifierLen,
9476 CS.getStart(), CS.getLength());
9477}
9478
9479bool CheckScanfHandler::HandleScanfSpecifier(
9481 const char *startSpecifier,
9482 unsigned specifierLen) {
9483 using namespace analyze_scanf;
9484 using namespace analyze_format_string;
9485
9486 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9487
9488 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9489 // be used to decide if we are using positional arguments consistently.
9490 if (FS.consumesDataArgument()) {
9491 if (atFirstArg) {
9492 atFirstArg = false;
9493 usesPositionalArgs = FS.usesPositionalArg();
9494 }
9495 else if (usesPositionalArgs != FS.usesPositionalArg()) {
9496 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9497 startSpecifier, specifierLen);
9498 return false;
9499 }
9500 }
9501
9502 // Check if the field with is non-zero.
9503 const OptionalAmount &Amt = FS.getFieldWidth();
9505 if (Amt.getConstantAmount() == 0) {
9506 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9507 Amt.getConstantLength());
9508 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9509 getLocationOfByte(Amt.getStart()),
9510 /*IsStringLocation*/true, R,
9512 }
9513 }
9514
9515 if (!FS.consumesDataArgument()) {
9516 // FIXME: Technically specifying a precision or field width here
9517 // makes no sense. Worth issuing a warning at some point.
9518 return true;
9519 }
9520
9521 // Consume the argument.
9522 unsigned argIndex = FS.getArgIndex();
9523 if (argIndex < NumDataArgs) {
9524 // The check to see if the argIndex is valid will come later.
9525 // We set the bit here because we may exit early from this
9526 // function if we encounter some other error.
9527 CoveredArgs.set(argIndex);
9528 }
9529
9530 // Check the length modifier is valid with the given conversion specifier.
9532 S.getLangOpts()))
9533 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9534 diag::warn_format_nonsensical_length);
9535 else if (!FS.hasStandardLengthModifier())
9536 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9538 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9539 diag::warn_format_non_standard_conversion_spec);
9540
9542 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9543
9544 // The remaining checks depend on the data arguments.
9545 if (!HasFormatArguments())
9546 return true;
9547
9548 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9549 return false;
9550
9551 // Check that the argument type matches the format specifier.
9552 const Expr *Ex = getDataArg(argIndex);
9553 if (!Ex)
9554 return true;
9555
9557
9558 if (!AT.isValid()) {
9559 return true;
9560 }
9561
9563 AT.matchesType(S.Context, Ex->getType());
9566 return true;
9569
9570 ScanfSpecifier fixedFS = FS;
9571 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9572 S.getLangOpts(), S.Context);
9573
9574 unsigned Diag =
9575 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9576 : Signedness
9577 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9578 : diag::warn_format_conversion_argument_type_mismatch;
9579
9580 if (Success) {
9581 // Get the fix string from the fixed format specifier.
9582 SmallString<128> buf;
9583 llvm::raw_svector_ostream os(buf);
9584 fixedFS.toString(os);
9585
9586 EmitFormatDiagnostic(
9588 << Ex->getType() << false << Ex->getSourceRange(),
9589 Ex->getBeginLoc(),
9590 /*IsStringLocation*/ false,
9591 getSpecifierRange(startSpecifier, specifierLen),
9593 getSpecifierRange(startSpecifier, specifierLen), os.str()));
9594 } else {
9595 EmitFormatDiagnostic(S.PDiag(Diag)
9597 << Ex->getType() << false << Ex->getSourceRange(),
9598 Ex->getBeginLoc(),
9599 /*IsStringLocation*/ false,
9600 getSpecifierRange(startSpecifier, specifierLen));
9601 }
9602
9603 return true;
9604}
9605
9606static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9608 const StringLiteral *Fmt,
9610 const Expr *FmtExpr, bool InFunctionCall) {
9611 bool HadError = false;
9612 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9613 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9614 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9615 // In positional-style format strings, the same specifier can appear
9616 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9617 // are sorted by getPosition(), and we process each range of equal
9618 // getPosition() values as one group.
9619 // RefArgs are taken from a string literal that was given to
9620 // attribute(format_matches), and if we got this far, we have already
9621 // verified that if it has positional specifiers that appear in multiple
9622 // locations, then they are all mutually compatible. What's left for us to
9623 // do is verify that all specifiers with the same position in FmtArgs are
9624 // compatible with the RefArgs specifiers. We check each specifier from
9625 // FmtArgs against the first member of the RefArgs group.
9626 for (; FmtIter < FmtEnd; ++FmtIter) {
9627 // Clang does not diagnose missing format specifiers in positional-style
9628 // strings (TODO: which it probably should do, as it is UB to skip over a
9629 // format argument). Skip specifiers if needed.
9630 if (FmtIter->getPosition() < RefIter->getPosition())
9631 continue;
9632
9633 // Delimits a new getPosition() value.
9634 if (FmtIter->getPosition() > RefIter->getPosition())
9635 break;
9636
9637 HadError |=
9638 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
9639 }
9640
9641 // Jump RefIter to the start of the next group.
9642 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
9643 return Arg.getPosition() != RefIter->getPosition();
9644 });
9645 }
9646
9647 if (FmtIter < FmtEnd) {
9648 CheckFormatHandler::EmitFormatDiagnostic(
9649 S, InFunctionCall, FmtExpr,
9650 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
9651 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
9652 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
9653 } else if (RefIter < RefEnd) {
9654 CheckFormatHandler::EmitFormatDiagnostic(
9655 S, InFunctionCall, FmtExpr,
9656 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
9657 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
9658 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
9659 << 1 << RefIter->getSourceRange();
9660 }
9661 return !HadError;
9662}
9663
9665 Sema &S, const FormatStringLiteral *FExpr,
9666 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
9668 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
9669 bool inFunctionCall, VariadicCallType CallType,
9670 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
9671 bool IgnoreStringsWithoutSpecifiers) {
9672 // CHECK: is the format string a wide literal?
9673 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9674 CheckFormatHandler::EmitFormatDiagnostic(
9675 S, inFunctionCall, Args[format_idx],
9676 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9677 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9678 return;
9679 }
9680
9681 // Str - The format string. NOTE: this is NOT null-terminated!
9682 StringRef StrRef = FExpr->getString();
9683 const char *Str = StrRef.data();
9684 // Account for cases where the string literal is truncated in a declaration.
9685 const ConstantArrayType *T =
9686 S.Context.getAsConstantArrayType(FExpr->getType());
9687 assert(T && "String literal not of constant array type!");
9688 size_t TypeSize = T->getZExtSize();
9689 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9690 const unsigned numDataArgs = Args.size() - firstDataArg;
9691
9692 if (IgnoreStringsWithoutSpecifiers &&
9694 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9695 return;
9696
9697 // Emit a warning if the string literal is truncated and does not contain an
9698 // embedded null character.
9699 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9700 CheckFormatHandler::EmitFormatDiagnostic(
9701 S, inFunctionCall, Args[format_idx],
9702 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9703 FExpr->getBeginLoc(),
9704 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9705 return;
9706 }
9707
9708 // CHECK: empty format string?
9709 if (StrLen == 0 && numDataArgs > 0) {
9710 CheckFormatHandler::EmitFormatDiagnostic(
9711 S, inFunctionCall, Args[format_idx],
9712 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9713 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9714 return;
9715 }
9716
9721 bool IsObjC =
9723 if (ReferenceFormatString == nullptr) {
9724 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9725 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9726 inFunctionCall, CallType, CheckedVarArgs,
9727 UncoveredArg);
9728
9730 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
9733 H.DoneProcessing();
9734 } else {
9736 Type, ReferenceFormatString, FExpr->getFormatString(),
9737 inFunctionCall ? nullptr : Args[format_idx]);
9738 }
9739 } else if (Type == FormatStringType::Scanf) {
9740 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9741 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9742 CallType, CheckedVarArgs, UncoveredArg);
9743
9745 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9746 H.DoneProcessing();
9747 } // TODO: handle other formats
9748}
9749
9751 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9752 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9757 return true;
9758
9759 bool IsObjC =
9762 FormatStringLiteral RefLit = AuthoritativeFormatString;
9763 FormatStringLiteral TestLit = TestedFormatString;
9764 const Expr *Arg;
9765 bool DiagAtStringLiteral;
9766 if (FunctionCallArg) {
9767 Arg = FunctionCallArg;
9768 DiagAtStringLiteral = false;
9769 } else {
9770 Arg = TestedFormatString;
9771 DiagAtStringLiteral = true;
9772 }
9773 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
9774 AuthoritativeFormatString, Type,
9775 IsObjC, true, RefArgs) &&
9776 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
9777 DiagAtStringLiteral, FmtArgs)) {
9778 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
9779 TestedFormatString, FmtArgs, Arg,
9780 DiagAtStringLiteral);
9781 }
9782 return false;
9783}
9784
9786 const StringLiteral *Str) {
9791 return true;
9792
9793 FormatStringLiteral RefLit = Str;
9795 bool IsObjC =
9797 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
9798 true, Args))
9799 return false;
9800
9801 // Group arguments by getPosition() value, and check that each member of the
9802 // group is compatible with the first member. This verifies that when
9803 // positional arguments are used multiple times (such as %2$i %2$d), all uses
9804 // are mutually compatible. As an optimization, don't test the first member
9805 // against itself.
9806 bool HadError = false;
9807 auto Iter = Args.begin();
9808 auto End = Args.end();
9809 while (Iter != End) {
9810 const auto &FirstInGroup = *Iter;
9811 for (++Iter;
9812 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
9813 ++Iter) {
9814 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
9815 }
9816 }
9817 return !HadError;
9818}
9819
9821 // Str - The format string. NOTE: this is NOT null-terminated!
9822 StringRef StrRef = FExpr->getString();
9823 const char *Str = StrRef.data();
9824 // Account for cases where the string literal is truncated in a declaration.
9825 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9826 assert(T && "String literal not of constant array type!");
9827 size_t TypeSize = T->getZExtSize();
9828 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9829 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9830 getLangOpts(),
9831 Context.getTargetInfo());
9832}
9833
9834//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9835
9836// Returns the related absolute value function that is larger, of 0 if one
9837// does not exist.
9838static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9839 switch (AbsFunction) {
9840 default:
9841 return 0;
9842
9843 case Builtin::BI__builtin_abs:
9844 return Builtin::BI__builtin_labs;
9845 case Builtin::BI__builtin_labs:
9846 return Builtin::BI__builtin_llabs;
9847 case Builtin::BI__builtin_llabs:
9848 return 0;
9849
9850 case Builtin::BI__builtin_fabsf:
9851 return Builtin::BI__builtin_fabs;
9852 case Builtin::BI__builtin_fabs:
9853 return Builtin::BI__builtin_fabsl;
9854 case Builtin::BI__builtin_fabsl:
9855 return 0;
9856
9857 case Builtin::BI__builtin_cabsf:
9858 return Builtin::BI__builtin_cabs;
9859 case Builtin::BI__builtin_cabs:
9860 return Builtin::BI__builtin_cabsl;
9861 case Builtin::BI__builtin_cabsl:
9862 return 0;
9863
9864 case Builtin::BIabs:
9865 return Builtin::BIlabs;
9866 case Builtin::BIlabs:
9867 return Builtin::BIllabs;
9868 case Builtin::BIllabs:
9869 return 0;
9870
9871 case Builtin::BIfabsf:
9872 return Builtin::BIfabs;
9873 case Builtin::BIfabs:
9874 return Builtin::BIfabsl;
9875 case Builtin::BIfabsl:
9876 return 0;
9877
9878 case Builtin::BIcabsf:
9879 return Builtin::BIcabs;
9880 case Builtin::BIcabs:
9881 return Builtin::BIcabsl;
9882 case Builtin::BIcabsl:
9883 return 0;
9884 }
9885}
9886
9887// Returns the argument type of the absolute value function.
9889 unsigned AbsType) {
9890 if (AbsType == 0)
9891 return QualType();
9892
9894 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9896 return QualType();
9897
9899 if (!FT)
9900 return QualType();
9901
9902 if (FT->getNumParams() != 1)
9903 return QualType();
9904
9905 return FT->getParamType(0);
9906}
9907
9908// Returns the best absolute value function, or zero, based on type and
9909// current absolute value function.
9910static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9911 unsigned AbsFunctionKind) {
9912 unsigned BestKind = 0;
9913 uint64_t ArgSize = Context.getTypeSize(ArgType);
9914 for (unsigned Kind = AbsFunctionKind; Kind != 0;
9915 Kind = getLargerAbsoluteValueFunction(Kind)) {
9916 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9917 if (Context.getTypeSize(ParamType) >= ArgSize) {
9918 if (BestKind == 0)
9919 BestKind = Kind;
9920 else if (Context.hasSameType(ParamType, ArgType)) {
9921 BestKind = Kind;
9922 break;
9923 }
9924 }
9925 }
9926 return BestKind;
9927}
9928
9934
9936 if (T->isIntegralOrEnumerationType())
9937 return AVK_Integer;
9938 if (T->isRealFloatingType())
9939 return AVK_Floating;
9940 if (T->isAnyComplexType())
9941 return AVK_Complex;
9942
9943 llvm_unreachable("Type not integer, floating, or complex");
9944}
9945
9946// Changes the absolute value function to a different type. Preserves whether
9947// the function is a builtin.
9948static unsigned changeAbsFunction(unsigned AbsKind,
9949 AbsoluteValueKind ValueKind) {
9950 switch (ValueKind) {
9951 case AVK_Integer:
9952 switch (AbsKind) {
9953 default:
9954 return 0;
9955 case Builtin::BI__builtin_fabsf:
9956 case Builtin::BI__builtin_fabs:
9957 case Builtin::BI__builtin_fabsl:
9958 case Builtin::BI__builtin_cabsf:
9959 case Builtin::BI__builtin_cabs:
9960 case Builtin::BI__builtin_cabsl:
9961 return Builtin::BI__builtin_abs;
9962 case Builtin::BIfabsf:
9963 case Builtin::BIfabs:
9964 case Builtin::BIfabsl:
9965 case Builtin::BIcabsf:
9966 case Builtin::BIcabs:
9967 case Builtin::BIcabsl:
9968 return Builtin::BIabs;
9969 }
9970 case AVK_Floating:
9971 switch (AbsKind) {
9972 default:
9973 return 0;
9974 case Builtin::BI__builtin_abs:
9975 case Builtin::BI__builtin_labs:
9976 case Builtin::BI__builtin_llabs:
9977 case Builtin::BI__builtin_cabsf:
9978 case Builtin::BI__builtin_cabs:
9979 case Builtin::BI__builtin_cabsl:
9980 return Builtin::BI__builtin_fabsf;
9981 case Builtin::BIabs:
9982 case Builtin::BIlabs:
9983 case Builtin::BIllabs:
9984 case Builtin::BIcabsf:
9985 case Builtin::BIcabs:
9986 case Builtin::BIcabsl:
9987 return Builtin::BIfabsf;
9988 }
9989 case AVK_Complex:
9990 switch (AbsKind) {
9991 default:
9992 return 0;
9993 case Builtin::BI__builtin_abs:
9994 case Builtin::BI__builtin_labs:
9995 case Builtin::BI__builtin_llabs:
9996 case Builtin::BI__builtin_fabsf:
9997 case Builtin::BI__builtin_fabs:
9998 case Builtin::BI__builtin_fabsl:
9999 return Builtin::BI__builtin_cabsf;
10000 case Builtin::BIabs:
10001 case Builtin::BIlabs:
10002 case Builtin::BIllabs:
10003 case Builtin::BIfabsf:
10004 case Builtin::BIfabs:
10005 case Builtin::BIfabsl:
10006 return Builtin::BIcabsf;
10007 }
10008 }
10009 llvm_unreachable("Unable to convert function");
10010}
10011
10012static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10013 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10014 if (!FnInfo)
10015 return 0;
10016
10017 switch (FDecl->getBuiltinID()) {
10018 default:
10019 return 0;
10020 case Builtin::BI__builtin_abs:
10021 case Builtin::BI__builtin_fabs:
10022 case Builtin::BI__builtin_fabsf:
10023 case Builtin::BI__builtin_fabsl:
10024 case Builtin::BI__builtin_labs:
10025 case Builtin::BI__builtin_llabs:
10026 case Builtin::BI__builtin_cabs:
10027 case Builtin::BI__builtin_cabsf:
10028 case Builtin::BI__builtin_cabsl:
10029 case Builtin::BIabs:
10030 case Builtin::BIlabs:
10031 case Builtin::BIllabs:
10032 case Builtin::BIfabs:
10033 case Builtin::BIfabsf:
10034 case Builtin::BIfabsl:
10035 case Builtin::BIcabs:
10036 case Builtin::BIcabsf:
10037 case Builtin::BIcabsl:
10038 return FDecl->getBuiltinID();
10039 }
10040 llvm_unreachable("Unknown Builtin type");
10041}
10042
10043// If the replacement is valid, emit a note with replacement function.
10044// Additionally, suggest including the proper header if not already included.
10046 unsigned AbsKind, QualType ArgType) {
10047 bool EmitHeaderHint = true;
10048 const char *HeaderName = nullptr;
10049 std::string FunctionName;
10050 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10051 FunctionName = "std::abs";
10052 if (ArgType->isIntegralOrEnumerationType()) {
10053 HeaderName = "cstdlib";
10054 } else if (ArgType->isRealFloatingType()) {
10055 HeaderName = "cmath";
10056 } else {
10057 llvm_unreachable("Invalid Type");
10058 }
10059
10060 // Lookup all std::abs
10061 if (NamespaceDecl *Std = S.getStdNamespace()) {
10062 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10063 R.suppressDiagnostics();
10064 S.LookupQualifiedName(R, Std);
10065
10066 for (const auto *I : R) {
10067 const FunctionDecl *FDecl = nullptr;
10068 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10069 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10070 } else {
10071 FDecl = dyn_cast<FunctionDecl>(I);
10072 }
10073 if (!FDecl)
10074 continue;
10075
10076 // Found std::abs(), check that they are the right ones.
10077 if (FDecl->getNumParams() != 1)
10078 continue;
10079
10080 // Check that the parameter type can handle the argument.
10081 QualType ParamType = FDecl->getParamDecl(0)->getType();
10082 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10083 S.Context.getTypeSize(ArgType) <=
10084 S.Context.getTypeSize(ParamType)) {
10085 // Found a function, don't need the header hint.
10086 EmitHeaderHint = false;
10087 break;
10088 }
10089 }
10090 }
10091 } else {
10092 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10093 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10094
10095 if (HeaderName) {
10096 DeclarationName DN(&S.Context.Idents.get(FunctionName));
10097 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10098 R.suppressDiagnostics();
10099 S.LookupName(R, S.getCurScope());
10100
10101 if (R.isSingleResult()) {
10102 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10103 if (FD && FD->getBuiltinID() == AbsKind) {
10104 EmitHeaderHint = false;
10105 } else {
10106 return;
10107 }
10108 } else if (!R.empty()) {
10109 return;
10110 }
10111 }
10112 }
10113
10114 S.Diag(Loc, diag::note_replace_abs_function)
10115 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10116
10117 if (!HeaderName)
10118 return;
10119
10120 if (!EmitHeaderHint)
10121 return;
10122
10123 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10124 << FunctionName;
10125}
10126
10127template <std::size_t StrLen>
10128static bool IsStdFunction(const FunctionDecl *FDecl,
10129 const char (&Str)[StrLen]) {
10130 if (!FDecl)
10131 return false;
10132 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10133 return false;
10134 if (!FDecl->isInStdNamespace())
10135 return false;
10136
10137 return true;
10138}
10139
10140enum class MathCheck { NaN, Inf };
10141static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10142 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10143 return llvm::is_contained(names, calleeName);
10144 };
10145
10146 switch (Check) {
10147 case MathCheck::NaN:
10148 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10149 "__builtin_nanf16", "__builtin_nanf128"});
10150 case MathCheck::Inf:
10151 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10152 "__builtin_inff16", "__builtin_inff128"});
10153 }
10154 llvm_unreachable("unknown MathCheck");
10155}
10156
10157static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10158 if (FDecl->getName() != "infinity")
10159 return false;
10160
10161 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
10162 const CXXRecordDecl *RDecl = MDecl->getParent();
10163 if (RDecl->getName() != "numeric_limits")
10164 return false;
10165
10166 if (const NamespaceDecl *NSDecl =
10167 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
10168 return NSDecl->isStdNamespace();
10169 }
10170
10171 return false;
10172}
10173
10174void Sema::CheckInfNaNFunction(const CallExpr *Call,
10175 const FunctionDecl *FDecl) {
10176 if (!FDecl->getIdentifier())
10177 return;
10178
10179 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
10180 if (FPO.getNoHonorNaNs() &&
10181 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
10183 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10184 << 1 << 0 << Call->getSourceRange();
10185 return;
10186 }
10187
10188 if (FPO.getNoHonorInfs() &&
10189 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
10190 IsInfinityFunction(FDecl) ||
10192 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10193 << 0 << 0 << Call->getSourceRange();
10194 }
10195}
10196
10197void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10198 const FunctionDecl *FDecl) {
10199 if (Call->getNumArgs() != 1)
10200 return;
10201
10202 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10203 bool IsStdAbs = IsStdFunction(FDecl, "abs");
10204 if (AbsKind == 0 && !IsStdAbs)
10205 return;
10206
10207 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10208 QualType ParamType = Call->getArg(0)->getType();
10209
10210 // Unsigned types cannot be negative. Suggest removing the absolute value
10211 // function call.
10212 if (ArgType->isUnsignedIntegerType()) {
10213 std::string FunctionName =
10214 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10215 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10216 Diag(Call->getExprLoc(), diag::note_remove_abs)
10217 << FunctionName
10218 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10219 return;
10220 }
10221
10222 // Taking the absolute value of a pointer is very suspicious, they probably
10223 // wanted to index into an array, dereference a pointer, call a function, etc.
10224 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10225 unsigned DiagType = 0;
10226 if (ArgType->isFunctionType())
10227 DiagType = 1;
10228 else if (ArgType->isArrayType())
10229 DiagType = 2;
10230
10231 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10232 return;
10233 }
10234
10235 // std::abs has overloads which prevent most of the absolute value problems
10236 // from occurring.
10237 if (IsStdAbs)
10238 return;
10239
10240 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10241 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10242
10243 // The argument and parameter are the same kind. Check if they are the right
10244 // size.
10245 if (ArgValueKind == ParamValueKind) {
10246 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10247 return;
10248
10249 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10250 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10251 << FDecl << ArgType << ParamType;
10252
10253 if (NewAbsKind == 0)
10254 return;
10255
10256 emitReplacement(*this, Call->getExprLoc(),
10257 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10258 return;
10259 }
10260
10261 // ArgValueKind != ParamValueKind
10262 // The wrong type of absolute value function was used. Attempt to find the
10263 // proper one.
10264 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10265 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10266 if (NewAbsKind == 0)
10267 return;
10268
10269 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10270 << FDecl << ParamValueKind << ArgValueKind;
10271
10272 emitReplacement(*this, Call->getExprLoc(),
10273 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10274}
10275
10276//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10277void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10278 const FunctionDecl *FDecl) {
10279 if (!Call || !FDecl) return;
10280
10281 // Ignore template specializations and macros.
10282 if (inTemplateInstantiation()) return;
10283 if (Call->getExprLoc().isMacroID()) return;
10284
10285 // Only care about the one template argument, two function parameter std::max
10286 if (Call->getNumArgs() != 2) return;
10287 if (!IsStdFunction(FDecl, "max")) return;
10288 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10289 if (!ArgList) return;
10290 if (ArgList->size() != 1) return;
10291
10292 // Check that template type argument is unsigned integer.
10293 const auto& TA = ArgList->get(0);
10294 if (TA.getKind() != TemplateArgument::Type) return;
10295 QualType ArgType = TA.getAsType();
10296 if (!ArgType->isUnsignedIntegerType()) return;
10297
10298 // See if either argument is a literal zero.
10299 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10300 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10301 if (!MTE) return false;
10302 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10303 if (!Num) return false;
10304 if (Num->getValue() != 0) return false;
10305 return true;
10306 };
10307
10308 const Expr *FirstArg = Call->getArg(0);
10309 const Expr *SecondArg = Call->getArg(1);
10310 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10311 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10312
10313 // Only warn when exactly one argument is zero.
10314 if (IsFirstArgZero == IsSecondArgZero) return;
10315
10316 SourceRange FirstRange = FirstArg->getSourceRange();
10317 SourceRange SecondRange = SecondArg->getSourceRange();
10318
10319 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10320
10321 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10322 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10323
10324 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10325 SourceRange RemovalRange;
10326 if (IsFirstArgZero) {
10327 RemovalRange = SourceRange(FirstRange.getBegin(),
10328 SecondRange.getBegin().getLocWithOffset(-1));
10329 } else {
10330 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10331 SecondRange.getEnd());
10332 }
10333
10334 Diag(Call->getExprLoc(), diag::note_remove_max_call)
10335 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10336 << FixItHint::CreateRemoval(RemovalRange);
10337}
10338
10339//===--- CHECK: Standard memory functions ---------------------------------===//
10340
10341/// Takes the expression passed to the size_t parameter of functions
10342/// such as memcmp, strncat, etc and warns if it's a comparison.
10343///
10344/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10346 const IdentifierInfo *FnName,
10347 SourceLocation FnLoc,
10348 SourceLocation RParenLoc) {
10349 const auto *Size = dyn_cast<BinaryOperator>(E);
10350 if (!Size)
10351 return false;
10352
10353 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10354 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10355 return false;
10356
10357 SourceRange SizeRange = Size->getSourceRange();
10358 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10359 << SizeRange << FnName;
10360 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10361 << FnName
10363 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10364 << FixItHint::CreateRemoval(RParenLoc);
10365 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10366 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10368 ")");
10369
10370 return true;
10371}
10372
10373/// Determine whether the given type is or contains a dynamic class type
10374/// (e.g., whether it has a vtable).
10376 bool &IsContained) {
10377 // Look through array types while ignoring qualifiers.
10378 const Type *Ty = T->getBaseElementTypeUnsafe();
10379 IsContained = false;
10380
10381 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10382 RD = RD ? RD->getDefinition() : nullptr;
10383 if (!RD || RD->isInvalidDecl())
10384 return nullptr;
10385
10386 if (RD->isDynamicClass())
10387 return RD;
10388
10389 // Check all the fields. If any bases were dynamic, the class is dynamic.
10390 // It's impossible for a class to transitively contain itself by value, so
10391 // infinite recursion is impossible.
10392 for (auto *FD : RD->fields()) {
10393 bool SubContained;
10394 if (const CXXRecordDecl *ContainedRD =
10395 getContainedDynamicClass(FD->getType(), SubContained)) {
10396 IsContained = true;
10397 return ContainedRD;
10398 }
10399 }
10400
10401 return nullptr;
10402}
10403
10405 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10406 if (Unary->getKind() == UETT_SizeOf)
10407 return Unary;
10408 return nullptr;
10409}
10410
10411/// If E is a sizeof expression, returns its argument expression,
10412/// otherwise returns NULL.
10413static const Expr *getSizeOfExprArg(const Expr *E) {
10415 if (!SizeOf->isArgumentType())
10416 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10417 return nullptr;
10418}
10419
10420/// If E is a sizeof expression, returns its argument type.
10423 return SizeOf->getTypeOfArgument();
10424 return QualType();
10425}
10426
10427namespace {
10428
10429struct SearchNonTrivialToInitializeField
10430 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10431 using Super =
10432 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10433
10434 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10435
10436 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10437 SourceLocation SL) {
10438 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10439 asDerived().visitArray(PDIK, AT, SL);
10440 return;
10441 }
10442
10443 Super::visitWithKind(PDIK, FT, SL);
10444 }
10445
10446 void visitARCStrong(QualType FT, SourceLocation SL) {
10447 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10448 }
10449 void visitARCWeak(QualType FT, SourceLocation SL) {
10450 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10451 }
10452 void visitStruct(QualType FT, SourceLocation SL) {
10453 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10454 visit(FD->getType(), FD->getLocation());
10455 }
10456 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10457 const ArrayType *AT, SourceLocation SL) {
10458 visit(getContext().getBaseElementType(AT), SL);
10459 }
10460 void visitTrivial(QualType FT, SourceLocation SL) {}
10461
10462 static void diag(QualType RT, const Expr *E, Sema &S) {
10463 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10464 }
10465
10466 ASTContext &getContext() { return S.getASTContext(); }
10467
10468 const Expr *E;
10469 Sema &S;
10470};
10471
10472struct SearchNonTrivialToCopyField
10473 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10474 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10475
10476 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10477
10478 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10479 SourceLocation SL) {
10480 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10481 asDerived().visitArray(PCK, AT, SL);
10482 return;
10483 }
10484
10485 Super::visitWithKind(PCK, FT, SL);
10486 }
10487
10488 void visitARCStrong(QualType FT, SourceLocation SL) {
10489 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10490 }
10491 void visitARCWeak(QualType FT, SourceLocation SL) {
10492 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10493 }
10494 void visitPtrAuth(QualType FT, SourceLocation SL) {
10495 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10496 }
10497 void visitStruct(QualType FT, SourceLocation SL) {
10498 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10499 visit(FD->getType(), FD->getLocation());
10500 }
10501 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10502 SourceLocation SL) {
10503 visit(getContext().getBaseElementType(AT), SL);
10504 }
10505 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10506 SourceLocation SL) {}
10507 void visitTrivial(QualType FT, SourceLocation SL) {}
10508 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10509
10510 static void diag(QualType RT, const Expr *E, Sema &S) {
10511 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10512 }
10513
10514 ASTContext &getContext() { return S.getASTContext(); }
10515
10516 const Expr *E;
10517 Sema &S;
10518};
10519
10520}
10521
10522/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10523static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10524 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10525
10526 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10527 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10528 return false;
10529
10530 return doesExprLikelyComputeSize(BO->getLHS()) ||
10531 doesExprLikelyComputeSize(BO->getRHS());
10532 }
10533
10534 return getAsSizeOfExpr(SizeofExpr) != nullptr;
10535}
10536
10537/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10538///
10539/// \code
10540/// #define MACRO 0
10541/// foo(MACRO);
10542/// foo(0);
10543/// \endcode
10544///
10545/// This should return true for the first call to foo, but not for the second
10546/// (regardless of whether foo is a macro or function).
10548 SourceLocation CallLoc,
10549 SourceLocation ArgLoc) {
10550 if (!CallLoc.isMacroID())
10551 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10552
10553 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10554 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10555}
10556
10557/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10558/// last two arguments transposed.
10559static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10560 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10561 return;
10562
10563 const Expr *SizeArg =
10564 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10565
10566 auto isLiteralZero = [](const Expr *E) {
10567 return (isa<IntegerLiteral>(E) &&
10568 cast<IntegerLiteral>(E)->getValue() == 0) ||
10570 cast<CharacterLiteral>(E)->getValue() == 0);
10571 };
10572
10573 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10574 SourceLocation CallLoc = Call->getRParenLoc();
10576 if (isLiteralZero(SizeArg) &&
10577 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10578
10579 SourceLocation DiagLoc = SizeArg->getExprLoc();
10580
10581 // Some platforms #define bzero to __builtin_memset. See if this is the
10582 // case, and if so, emit a better diagnostic.
10583 if (BId == Builtin::BIbzero ||
10585 CallLoc, SM, S.getLangOpts()) == "bzero")) {
10586 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10587 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10588 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10589 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10590 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10591 }
10592 return;
10593 }
10594
10595 // If the second argument to a memset is a sizeof expression and the third
10596 // isn't, this is also likely an error. This should catch
10597 // 'memset(buf, sizeof(buf), 0xff)'.
10598 if (BId == Builtin::BImemset &&
10599 doesExprLikelyComputeSize(Call->getArg(1)) &&
10600 !doesExprLikelyComputeSize(Call->getArg(2))) {
10601 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10602 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10603 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10604 return;
10605 }
10606}
10607
10608void Sema::CheckMemaccessArguments(const CallExpr *Call,
10609 unsigned BId,
10610 IdentifierInfo *FnName) {
10611 assert(BId != 0);
10612
10613 // It is possible to have a non-standard definition of memset. Validate
10614 // we have enough arguments, and if not, abort further checking.
10615 unsigned ExpectedNumArgs =
10616 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10617 if (Call->getNumArgs() < ExpectedNumArgs)
10618 return;
10619
10620 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10621 BId == Builtin::BIstrndup ? 1 : 2);
10622 unsigned LenArg =
10623 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10624 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10625
10626 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10627 Call->getBeginLoc(), Call->getRParenLoc()))
10628 return;
10629
10630 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10631 CheckMemaccessSize(*this, BId, Call);
10632
10633 // We have special checking when the length is a sizeof expression.
10634 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10635
10636 // Although widely used, 'bzero' is not a standard function. Be more strict
10637 // with the argument types before allowing diagnostics and only allow the
10638 // form bzero(ptr, sizeof(...)).
10639 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10640 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10641 return;
10642
10643 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10644 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10645 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10646
10647 QualType DestTy = Dest->getType();
10648 QualType PointeeTy;
10649 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10650 PointeeTy = DestPtrTy->getPointeeType();
10651
10652 // Never warn about void type pointers. This can be used to suppress
10653 // false positives.
10654 if (PointeeTy->isVoidType())
10655 continue;
10656
10657 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10658 // actually comparing the expressions for equality. Because computing the
10659 // expression IDs can be expensive, we only do this if the diagnostic is
10660 // enabled.
10661 if (CheckSizeofMemaccessArgument(LenExpr, Dest, FnName))
10662 break;
10663
10664 // Also check for cases where the sizeof argument is the exact same
10665 // type as the memory argument, and where it points to a user-defined
10666 // record type.
10667 if (SizeOfArgTy != QualType()) {
10668 if (PointeeTy->isRecordType() &&
10669 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10670 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10671 PDiag(diag::warn_sizeof_pointer_type_memaccess)
10672 << FnName << SizeOfArgTy << ArgIdx
10673 << PointeeTy << Dest->getSourceRange()
10674 << LenExpr->getSourceRange());
10675 break;
10676 }
10677 }
10678 } else if (DestTy->isArrayType()) {
10679 PointeeTy = DestTy;
10680 }
10681
10682 if (PointeeTy == QualType())
10683 continue;
10684
10685 // Always complain about dynamic classes.
10686 bool IsContained;
10687 if (const CXXRecordDecl *ContainedRD =
10688 getContainedDynamicClass(PointeeTy, IsContained)) {
10689
10690 unsigned OperationType = 0;
10691 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10692 // "overwritten" if we're warning about the destination for any call
10693 // but memcmp; otherwise a verb appropriate to the call.
10694 if (ArgIdx != 0 || IsCmp) {
10695 if (BId == Builtin::BImemcpy)
10696 OperationType = 1;
10697 else if(BId == Builtin::BImemmove)
10698 OperationType = 2;
10699 else if (IsCmp)
10700 OperationType = 3;
10701 }
10702
10703 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10704 PDiag(diag::warn_dyn_class_memaccess)
10705 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10706 << IsContained << ContainedRD << OperationType
10707 << Call->getCallee()->getSourceRange());
10708 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10709 BId != Builtin::BImemset)
10711 Dest->getExprLoc(), Dest,
10712 PDiag(diag::warn_arc_object_memaccess)
10713 << ArgIdx << FnName << PointeeTy
10714 << Call->getCallee()->getSourceRange());
10715 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10716
10717 // FIXME: Do not consider incomplete types even though they may be
10718 // completed later. GCC does not diagnose such code, but we may want to
10719 // consider diagnosing it in the future, perhaps under a different, but
10720 // related, diagnostic group.
10721 bool NonTriviallyCopyableCXXRecord =
10722 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10723 !PointeeTy.isTriviallyCopyableType(Context);
10724
10725 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10727 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10728 PDiag(diag::warn_cstruct_memaccess)
10729 << ArgIdx << FnName << PointeeTy << 0);
10730 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10731 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10732 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10733 // FIXME: Limiting this warning to dest argument until we decide
10734 // whether it's valid for source argument too.
10735 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10736 PDiag(diag::warn_cxxstruct_memaccess)
10737 << FnName << PointeeTy);
10738 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10740 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10741 PDiag(diag::warn_cstruct_memaccess)
10742 << ArgIdx << FnName << PointeeTy << 1);
10743 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10744 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10745 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10746 // FIXME: Limiting this warning to dest argument until we decide
10747 // whether it's valid for source argument too.
10748 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10749 PDiag(diag::warn_cxxstruct_memaccess)
10750 << FnName << PointeeTy);
10751 } else {
10752 continue;
10753 }
10754 } else
10755 continue;
10756
10758 Dest->getExprLoc(), Dest,
10759 PDiag(diag::note_bad_memaccess_silence)
10760 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10761 break;
10762 }
10763}
10764
10765bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
10766 IdentifierInfo *FnName) {
10767 llvm::FoldingSetNodeID SizeOfArgID;
10768 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10769 if (!SizeOfArg)
10770 return false;
10771 // Computing this warning is expensive, so we only do so if the warning is
10772 // enabled.
10773 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10774 SizeOfArg->getExprLoc()))
10775 return false;
10776 QualType DestTy = Dest->getType();
10777 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
10778 if (!DestPtrTy)
10779 return false;
10780
10781 QualType PointeeTy = DestPtrTy->getPointeeType();
10782
10783 if (SizeOfArgID == llvm::FoldingSetNodeID())
10784 SizeOfArg->Profile(SizeOfArgID, Context, true);
10785
10786 llvm::FoldingSetNodeID DestID;
10787 Dest->Profile(DestID, Context, true);
10788 if (DestID == SizeOfArgID) {
10789 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10790 // over sizeof(src) as well.
10791 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10792 StringRef ReadableName = FnName->getName();
10793
10794 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest);
10795 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
10796 ActionIdx = 1; // If its an address-of operator, just remove it.
10797 if (!PointeeTy->isIncompleteType() &&
10798 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10799 ActionIdx = 2; // If the pointee's size is sizeof(char),
10800 // suggest an explicit length.
10801
10802 // If the function is defined as a builtin macro, do not show macro
10803 // expansion.
10804 SourceLocation SL = SizeOfArg->getExprLoc();
10805 SourceRange DSR = Dest->getSourceRange();
10806 SourceRange SSR = SizeOfArg->getSourceRange();
10807 SourceManager &SM = getSourceManager();
10808
10809 if (SM.isMacroArgExpansion(SL)) {
10810 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10811 SL = SM.getSpellingLoc(SL);
10812 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10813 SM.getSpellingLoc(DSR.getEnd()));
10814 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10815 SM.getSpellingLoc(SSR.getEnd()));
10816 }
10817
10818 DiagRuntimeBehavior(SL, SizeOfArg,
10819 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10820 << ReadableName << PointeeTy << DestTy << DSR
10821 << SSR);
10822 DiagRuntimeBehavior(SL, SizeOfArg,
10823 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10824 << ActionIdx << SSR);
10825 return true;
10826 }
10827 return false;
10828}
10829
10830// A little helper routine: ignore addition and subtraction of integer literals.
10831// This intentionally does not ignore all integer constant expressions because
10832// we don't want to remove sizeof().
10833static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10834 Ex = Ex->IgnoreParenCasts();
10835
10836 while (true) {
10837 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10838 if (!BO || !BO->isAdditiveOp())
10839 break;
10840
10841 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10842 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10843
10844 if (isa<IntegerLiteral>(RHS))
10845 Ex = LHS;
10846 else if (isa<IntegerLiteral>(LHS))
10847 Ex = RHS;
10848 else
10849 break;
10850 }
10851
10852 return Ex;
10853}
10854
10856 ASTContext &Context) {
10857 // Only handle constant-sized or VLAs, but not flexible members.
10858 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10859 // Only issue the FIXIT for arrays of size > 1.
10860 if (CAT->getZExtSize() <= 1)
10861 return false;
10862 } else if (!Ty->isVariableArrayType()) {
10863 return false;
10864 }
10865 return true;
10866}
10867
10868void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10869 IdentifierInfo *FnName) {
10870
10871 // Don't crash if the user has the wrong number of arguments
10872 unsigned NumArgs = Call->getNumArgs();
10873 if ((NumArgs != 3) && (NumArgs != 4))
10874 return;
10875
10876 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10877 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10878 const Expr *CompareWithSrc = nullptr;
10879
10880 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10881 Call->getBeginLoc(), Call->getRParenLoc()))
10882 return;
10883
10884 // Look for 'strlcpy(dst, x, sizeof(x))'
10885 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10886 CompareWithSrc = Ex;
10887 else {
10888 // Look for 'strlcpy(dst, x, strlen(x))'
10889 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10890 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10891 SizeCall->getNumArgs() == 1)
10892 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10893 }
10894 }
10895
10896 if (!CompareWithSrc)
10897 return;
10898
10899 // Determine if the argument to sizeof/strlen is equal to the source
10900 // argument. In principle there's all kinds of things you could do
10901 // here, for instance creating an == expression and evaluating it with
10902 // EvaluateAsBooleanCondition, but this uses a more direct technique:
10903 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10904 if (!SrcArgDRE)
10905 return;
10906
10907 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10908 if (!CompareWithSrcDRE ||
10909 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10910 return;
10911
10912 const Expr *OriginalSizeArg = Call->getArg(2);
10913 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10914 << OriginalSizeArg->getSourceRange() << FnName;
10915
10916 // Output a FIXIT hint if the destination is an array (rather than a
10917 // pointer to an array). This could be enhanced to handle some
10918 // pointers if we know the actual size, like if DstArg is 'array+2'
10919 // we could say 'sizeof(array)-2'.
10920 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10922 return;
10923
10924 SmallString<128> sizeString;
10925 llvm::raw_svector_ostream OS(sizeString);
10926 OS << "sizeof(";
10927 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10928 OS << ")";
10929
10930 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10931 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10932 OS.str());
10933}
10934
10935/// Check if two expressions refer to the same declaration.
10936static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10937 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10938 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10939 return D1->getDecl() == D2->getDecl();
10940 return false;
10941}
10942
10943static const Expr *getStrlenExprArg(const Expr *E) {
10944 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10945 const FunctionDecl *FD = CE->getDirectCallee();
10946 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10947 return nullptr;
10948 return CE->getArg(0)->IgnoreParenCasts();
10949 }
10950 return nullptr;
10951}
10952
10953void Sema::CheckStrncatArguments(const CallExpr *CE,
10954 const IdentifierInfo *FnName) {
10955 // Don't crash if the user has the wrong number of arguments.
10956 if (CE->getNumArgs() < 3)
10957 return;
10958 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10959 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10960 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10961
10962 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10963 CE->getRParenLoc()))
10964 return;
10965
10966 // Identify common expressions, which are wrongly used as the size argument
10967 // to strncat and may lead to buffer overflows.
10968 unsigned PatternType = 0;
10969 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10970 // - sizeof(dst)
10971 if (referToTheSameDecl(SizeOfArg, DstArg))
10972 PatternType = 1;
10973 // - sizeof(src)
10974 else if (referToTheSameDecl(SizeOfArg, SrcArg))
10975 PatternType = 2;
10976 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10977 if (BE->getOpcode() == BO_Sub) {
10978 const Expr *L = BE->getLHS()->IgnoreParenCasts();
10979 const Expr *R = BE->getRHS()->IgnoreParenCasts();
10980 // - sizeof(dst) - strlen(dst)
10981 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10983 PatternType = 1;
10984 // - sizeof(src) - (anything)
10985 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10986 PatternType = 2;
10987 }
10988 }
10989
10990 if (PatternType == 0)
10991 return;
10992
10993 // Generate the diagnostic.
10994 SourceLocation SL = LenArg->getBeginLoc();
10995 SourceRange SR = LenArg->getSourceRange();
10996 SourceManager &SM = getSourceManager();
10997
10998 // If the function is defined as a builtin macro, do not show macro expansion.
10999 if (SM.isMacroArgExpansion(SL)) {
11000 SL = SM.getSpellingLoc(SL);
11001 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11002 SM.getSpellingLoc(SR.getEnd()));
11003 }
11004
11005 // Check if the destination is an array (rather than a pointer to an array).
11006 QualType DstTy = DstArg->getType();
11007 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11008 Context);
11009 if (!isKnownSizeArray) {
11010 if (PatternType == 1)
11011 Diag(SL, diag::warn_strncat_wrong_size) << SR;
11012 else
11013 Diag(SL, diag::warn_strncat_src_size) << SR;
11014 return;
11015 }
11016
11017 if (PatternType == 1)
11018 Diag(SL, diag::warn_strncat_large_size) << SR;
11019 else
11020 Diag(SL, diag::warn_strncat_src_size) << SR;
11021
11022 SmallString<128> sizeString;
11023 llvm::raw_svector_ostream OS(sizeString);
11024 OS << "sizeof(";
11025 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11026 OS << ") - ";
11027 OS << "strlen(";
11028 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11029 OS << ") - 1";
11030
11031 Diag(SL, diag::note_strncat_wrong_size)
11032 << FixItHint::CreateReplacement(SR, OS.str());
11033}
11034
11035namespace {
11036void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11037 const UnaryOperator *UnaryExpr, const Decl *D) {
11039 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11040 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11041 return;
11042 }
11043}
11044
11045void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11046 const UnaryOperator *UnaryExpr) {
11047 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11048 const Decl *D = Lvalue->getDecl();
11049 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11050 if (!DD->getType()->isReferenceType())
11051 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11052 }
11053 }
11054
11055 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11056 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11057 Lvalue->getMemberDecl());
11058}
11059
11060void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11061 const UnaryOperator *UnaryExpr) {
11062 const auto *Lambda = dyn_cast<LambdaExpr>(
11064 if (!Lambda)
11065 return;
11066
11067 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11068 << CalleeName << 2 /*object: lambda expression*/;
11069}
11070
11071void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11072 const DeclRefExpr *Lvalue) {
11073 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11074 if (Var == nullptr)
11075 return;
11076
11077 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11078 << CalleeName << 0 /*object: */ << Var;
11079}
11080
11081void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11082 const CastExpr *Cast) {
11083 SmallString<128> SizeString;
11084 llvm::raw_svector_ostream OS(SizeString);
11085
11086 clang::CastKind Kind = Cast->getCastKind();
11087 if (Kind == clang::CK_BitCast &&
11088 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11089 return;
11090 if (Kind == clang::CK_IntegralToPointer &&
11092 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11093 return;
11094
11095 switch (Cast->getCastKind()) {
11096 case clang::CK_BitCast:
11097 case clang::CK_IntegralToPointer:
11098 case clang::CK_FunctionToPointerDecay:
11099 OS << '\'';
11100 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11101 OS << '\'';
11102 break;
11103 default:
11104 return;
11105 }
11106
11107 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11108 << CalleeName << 0 /*object: */ << OS.str();
11109}
11110} // namespace
11111
11112void Sema::CheckFreeArguments(const CallExpr *E) {
11113 const std::string CalleeName =
11114 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11115
11116 { // Prefer something that doesn't involve a cast to make things simpler.
11117 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11118 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11119 switch (UnaryExpr->getOpcode()) {
11120 case UnaryOperator::Opcode::UO_AddrOf:
11121 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11122 case UnaryOperator::Opcode::UO_Plus:
11123 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11124 default:
11125 break;
11126 }
11127
11128 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11129 if (Lvalue->getType()->isArrayType())
11130 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11131
11132 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11133 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11134 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11135 return;
11136 }
11137
11138 if (isa<BlockExpr>(Arg)) {
11139 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11140 << CalleeName << 1 /*object: block*/;
11141 return;
11142 }
11143 }
11144 // Maybe the cast was important, check after the other cases.
11145 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11146 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11147}
11148
11149void
11150Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11151 SourceLocation ReturnLoc,
11152 bool isObjCMethod,
11153 const AttrVec *Attrs,
11154 const FunctionDecl *FD) {
11155 // Check if the return value is null but should not be.
11156 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11157 (!isObjCMethod && isNonNullType(lhsType))) &&
11158 CheckNonNullExpr(*this, RetValExp))
11159 Diag(ReturnLoc, diag::warn_null_ret)
11160 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11161
11162 // C++11 [basic.stc.dynamic.allocation]p4:
11163 // If an allocation function declared with a non-throwing
11164 // exception-specification fails to allocate storage, it shall return
11165 // a null pointer. Any other allocation function that fails to allocate
11166 // storage shall indicate failure only by throwing an exception [...]
11167 if (FD) {
11169 if (Op == OO_New || Op == OO_Array_New) {
11170 const FunctionProtoType *Proto
11171 = FD->getType()->castAs<FunctionProtoType>();
11172 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11173 CheckNonNullExpr(*this, RetValExp))
11174 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11175 << FD << getLangOpts().CPlusPlus11;
11176 }
11177 }
11178
11179 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11180 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
11181 }
11182
11183 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11184 // here prevent the user from using a PPC MMA type as trailing return type.
11185 if (Context.getTargetInfo().getTriple().isPPC64())
11186 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11187}
11188
11190 const Expr *RHS, BinaryOperatorKind Opcode) {
11191 if (!BinaryOperator::isEqualityOp(Opcode))
11192 return;
11193
11194 // Match and capture subexpressions such as "(float) X == 0.1".
11195 const FloatingLiteral *FPLiteral;
11196 const CastExpr *FPCast;
11197 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11198 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11199 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11200 return FPLiteral && FPCast;
11201 };
11202
11203 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11204 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11205 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11206 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11207 TargetTy->isFloatingPoint()) {
11208 bool Lossy;
11209 llvm::APFloat TargetC = FPLiteral->getValue();
11210 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11211 llvm::APFloat::rmNearestTiesToEven, &Lossy);
11212 if (Lossy) {
11213 // If the literal cannot be represented in the source type, then a
11214 // check for == is always false and check for != is always true.
11215 Diag(Loc, diag::warn_float_compare_literal)
11216 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11217 << LHS->getSourceRange() << RHS->getSourceRange();
11218 return;
11219 }
11220 }
11221 }
11222
11223 // Match a more general floating-point equality comparison (-Wfloat-equal).
11224 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11225 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11226
11227 // Special case: check for x == x (which is OK).
11228 // Do not emit warnings for such cases.
11229 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11230 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11231 if (DRL->getDecl() == DRR->getDecl())
11232 return;
11233
11234 // Special case: check for comparisons against literals that can be exactly
11235 // represented by APFloat. In such cases, do not emit a warning. This
11236 // is a heuristic: often comparison against such literals are used to
11237 // detect if a value in a variable has not changed. This clearly can
11238 // lead to false negatives.
11239 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11240 if (FLL->isExact())
11241 return;
11242 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11243 if (FLR->isExact())
11244 return;
11245
11246 // Check for comparisons with builtin types.
11247 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
11248 CL && CL->getBuiltinCallee())
11249 return;
11250
11251 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
11252 CR && CR->getBuiltinCallee())
11253 return;
11254
11255 // Emit the diagnostic.
11256 Diag(Loc, diag::warn_floatingpoint_eq)
11257 << LHS->getSourceRange() << RHS->getSourceRange();
11258}
11259
11260//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11261//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11262
11263namespace {
11264
11265/// Structure recording the 'active' range of an integer-valued
11266/// expression.
11267struct IntRange {
11268 /// The number of bits active in the int. Note that this includes exactly one
11269 /// sign bit if !NonNegative.
11270 unsigned Width;
11271
11272 /// True if the int is known not to have negative values. If so, all leading
11273 /// bits before Width are known zero, otherwise they are known to be the
11274 /// same as the MSB within Width.
11275 bool NonNegative;
11276
11277 IntRange(unsigned Width, bool NonNegative)
11278 : Width(Width), NonNegative(NonNegative) {}
11279
11280 /// Number of bits excluding the sign bit.
11281 unsigned valueBits() const {
11282 return NonNegative ? Width : Width - 1;
11283 }
11284
11285 /// Returns the range of the bool type.
11286 static IntRange forBoolType() {
11287 return IntRange(1, true);
11288 }
11289
11290 /// Returns the range of an opaque value of the given integral type.
11291 static IntRange forValueOfType(ASTContext &C, QualType T) {
11292 return forValueOfCanonicalType(C,
11294 }
11295
11296 /// Returns the range of an opaque value of a canonical integral type.
11297 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11298 assert(T->isCanonicalUnqualified());
11299
11300 if (const auto *VT = dyn_cast<VectorType>(T))
11301 T = VT->getElementType().getTypePtr();
11302 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11303 T = MT->getElementType().getTypePtr();
11304 if (const auto *CT = dyn_cast<ComplexType>(T))
11305 T = CT->getElementType().getTypePtr();
11306 if (const auto *AT = dyn_cast<AtomicType>(T))
11307 T = AT->getValueType().getTypePtr();
11308 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11309 T = OBT->getUnderlyingType().getTypePtr();
11310
11311 if (!C.getLangOpts().CPlusPlus) {
11312 // For enum types in C code, use the underlying datatype.
11313 if (const auto *ED = T->getAsEnumDecl())
11314 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
11315 } else if (auto *Enum = T->getAsEnumDecl()) {
11316 // For enum types in C++, use the known bit width of the enumerators.
11317 // In C++11, enums can have a fixed underlying type. Use this type to
11318 // compute the range.
11319 if (Enum->isFixed()) {
11320 return IntRange(C.getIntWidth(QualType(T, 0)),
11321 !Enum->getIntegerType()->isSignedIntegerType());
11322 }
11323
11324 unsigned NumPositive = Enum->getNumPositiveBits();
11325 unsigned NumNegative = Enum->getNumNegativeBits();
11326
11327 if (NumNegative == 0)
11328 return IntRange(NumPositive, true/*NonNegative*/);
11329 else
11330 return IntRange(std::max(NumPositive + 1, NumNegative),
11331 false/*NonNegative*/);
11332 }
11333
11334 if (const auto *EIT = dyn_cast<BitIntType>(T))
11335 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11336
11337 const BuiltinType *BT = cast<BuiltinType>(T);
11338 assert(BT->isInteger());
11339
11340 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11341 }
11342
11343 /// Returns the "target" range of a canonical integral type, i.e.
11344 /// the range of values expressible in the type.
11345 ///
11346 /// This matches forValueOfCanonicalType except that enums have the
11347 /// full range of their type, not the range of their enumerators.
11348 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11349 assert(T->isCanonicalUnqualified());
11350
11351 if (const VectorType *VT = dyn_cast<VectorType>(T))
11352 T = VT->getElementType().getTypePtr();
11353 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11354 T = MT->getElementType().getTypePtr();
11355 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11356 T = CT->getElementType().getTypePtr();
11357 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11358 T = AT->getValueType().getTypePtr();
11359 if (const auto *ED = T->getAsEnumDecl())
11360 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
11361 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11362 T = OBT->getUnderlyingType().getTypePtr();
11363
11364 if (const auto *EIT = dyn_cast<BitIntType>(T))
11365 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11366
11367 const BuiltinType *BT = cast<BuiltinType>(T);
11368 assert(BT->isInteger());
11369
11370 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11371 }
11372
11373 /// Returns the supremum of two ranges: i.e. their conservative merge.
11374 static IntRange join(IntRange L, IntRange R) {
11375 bool Unsigned = L.NonNegative && R.NonNegative;
11376 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11377 L.NonNegative && R.NonNegative);
11378 }
11379
11380 /// Return the range of a bitwise-AND of the two ranges.
11381 static IntRange bit_and(IntRange L, IntRange R) {
11382 unsigned Bits = std::max(L.Width, R.Width);
11383 bool NonNegative = false;
11384 if (L.NonNegative) {
11385 Bits = std::min(Bits, L.Width);
11386 NonNegative = true;
11387 }
11388 if (R.NonNegative) {
11389 Bits = std::min(Bits, R.Width);
11390 NonNegative = true;
11391 }
11392 return IntRange(Bits, NonNegative);
11393 }
11394
11395 /// Return the range of a sum of the two ranges.
11396 static IntRange sum(IntRange L, IntRange R) {
11397 bool Unsigned = L.NonNegative && R.NonNegative;
11398 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11399 Unsigned);
11400 }
11401
11402 /// Return the range of a difference of the two ranges.
11403 static IntRange difference(IntRange L, IntRange R) {
11404 // We need a 1-bit-wider range if:
11405 // 1) LHS can be negative: least value can be reduced.
11406 // 2) RHS can be negative: greatest value can be increased.
11407 bool CanWiden = !L.NonNegative || !R.NonNegative;
11408 bool Unsigned = L.NonNegative && R.Width == 0;
11409 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11410 !Unsigned,
11411 Unsigned);
11412 }
11413
11414 /// Return the range of a product of the two ranges.
11415 static IntRange product(IntRange L, IntRange R) {
11416 // If both LHS and RHS can be negative, we can form
11417 // -2^L * -2^R = 2^(L + R)
11418 // which requires L + R + 1 value bits to represent.
11419 bool CanWiden = !L.NonNegative && !R.NonNegative;
11420 bool Unsigned = L.NonNegative && R.NonNegative;
11421 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11422 Unsigned);
11423 }
11424
11425 /// Return the range of a remainder operation between the two ranges.
11426 static IntRange rem(IntRange L, IntRange R) {
11427 // The result of a remainder can't be larger than the result of
11428 // either side. The sign of the result is the sign of the LHS.
11429 bool Unsigned = L.NonNegative;
11430 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11431 Unsigned);
11432 }
11433};
11434
11435} // namespace
11436
11437static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11438 if (value.isSigned() && value.isNegative())
11439 return IntRange(value.getSignificantBits(), false);
11440
11441 if (value.getBitWidth() > MaxWidth)
11442 value = value.trunc(MaxWidth);
11443
11444 // isNonNegative() just checks the sign bit without considering
11445 // signedness.
11446 return IntRange(value.getActiveBits(), true);
11447}
11448
11449static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11450 if (result.isInt())
11451 return GetValueRange(result.getInt(), MaxWidth);
11452
11453 if (result.isVector()) {
11454 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
11455 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11456 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
11457 R = IntRange::join(R, El);
11458 }
11459 return R;
11460 }
11461
11462 if (result.isComplexInt()) {
11463 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
11464 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
11465 return IntRange::join(R, I);
11466 }
11467
11468 // This can happen with lossless casts to intptr_t of "based" lvalues.
11469 // Assume it might use arbitrary bits.
11470 // FIXME: The only reason we need to pass the type in here is to get
11471 // the sign right on this one case. It would be nice if APValue
11472 // preserved this.
11473 assert(result.isLValue() || result.isAddrLabelDiff());
11474 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11475}
11476
11477static QualType GetExprType(const Expr *E) {
11478 QualType Ty = E->getType();
11479 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11480 Ty = AtomicRHS->getValueType();
11481 return Ty;
11482}
11483
11484/// Attempts to estimate an approximate range for the given integer expression.
11485/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11486/// reliable estimation cannot be determined.
11487///
11488/// \param MaxWidth The width to which the value will be truncated.
11489/// \param InConstantContext If \c true, interpret the expression within a
11490/// constant context.
11491/// \param Approximate If \c true, provide a likely range of values by assuming
11492/// that arithmetic on narrower types remains within those types.
11493/// If \c false, return a range that includes all possible values
11494/// resulting from the expression.
11495/// \returns A range of values that the expression might take, or
11496/// std::nullopt if a reliable estimation cannot be determined.
11497static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11498 unsigned MaxWidth,
11499 bool InConstantContext,
11500 bool Approximate) {
11501 E = E->IgnoreParens();
11502
11503 // Try a full evaluation first.
11504 Expr::EvalResult result;
11505 if (E->EvaluateAsRValue(result, C, InConstantContext))
11506 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
11507
11508 // I think we only want to look through implicit casts here; if the
11509 // user has an explicit widening cast, we should treat the value as
11510 // being of the new, wider type.
11511 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11512 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11513 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11514 Approximate);
11515
11516 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11517
11518 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11519 CE->getCastKind() == CK_BooleanToSignedIntegral;
11520
11521 // Assume that non-integer casts can span the full range of the type.
11522 if (!isIntegerCast)
11523 return OutputTypeRange;
11524
11525 std::optional<IntRange> SubRange = TryGetExprRange(
11526 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
11527 InConstantContext, Approximate);
11528 if (!SubRange)
11529 return std::nullopt;
11530
11531 // Bail out if the subexpr's range is as wide as the cast type.
11532 if (SubRange->Width >= OutputTypeRange.Width)
11533 return OutputTypeRange;
11534
11535 // Otherwise, we take the smaller width, and we're non-negative if
11536 // either the output type or the subexpr is.
11537 return IntRange(SubRange->Width,
11538 SubRange->NonNegative || OutputTypeRange.NonNegative);
11539 }
11540
11541 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11542 // If we can fold the condition, just take that operand.
11543 bool CondResult;
11544 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11545 return TryGetExprRange(
11546 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
11547 InConstantContext, Approximate);
11548
11549 // Otherwise, conservatively merge.
11550 // TryGetExprRange requires an integer expression, but a throw expression
11551 // results in a void type.
11552 Expr *TrueExpr = CO->getTrueExpr();
11553 if (TrueExpr->getType()->isVoidType())
11554 return std::nullopt;
11555
11556 std::optional<IntRange> L =
11557 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
11558 if (!L)
11559 return std::nullopt;
11560
11561 Expr *FalseExpr = CO->getFalseExpr();
11562 if (FalseExpr->getType()->isVoidType())
11563 return std::nullopt;
11564
11565 std::optional<IntRange> R =
11566 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
11567 if (!R)
11568 return std::nullopt;
11569
11570 return IntRange::join(*L, *R);
11571 }
11572
11573 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11574 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11575
11576 switch (BO->getOpcode()) {
11577 case BO_Cmp:
11578 llvm_unreachable("builtin <=> should have class type");
11579
11580 // Boolean-valued operations are single-bit and positive.
11581 case BO_LAnd:
11582 case BO_LOr:
11583 case BO_LT:
11584 case BO_GT:
11585 case BO_LE:
11586 case BO_GE:
11587 case BO_EQ:
11588 case BO_NE:
11589 return IntRange::forBoolType();
11590
11591 // The type of the assignments is the type of the LHS, so the RHS
11592 // is not necessarily the same type.
11593 case BO_MulAssign:
11594 case BO_DivAssign:
11595 case BO_RemAssign:
11596 case BO_AddAssign:
11597 case BO_SubAssign:
11598 case BO_XorAssign:
11599 case BO_OrAssign:
11600 // TODO: bitfields?
11601 return IntRange::forValueOfType(C, GetExprType(E));
11602
11603 // Simple assignments just pass through the RHS, which will have
11604 // been coerced to the LHS type.
11605 case BO_Assign:
11606 // TODO: bitfields?
11607 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11608 Approximate);
11609
11610 // Operations with opaque sources are black-listed.
11611 case BO_PtrMemD:
11612 case BO_PtrMemI:
11613 return IntRange::forValueOfType(C, GetExprType(E));
11614
11615 // Bitwise-and uses the *infinum* of the two source ranges.
11616 case BO_And:
11617 case BO_AndAssign:
11618 Combine = IntRange::bit_and;
11619 break;
11620
11621 // Left shift gets black-listed based on a judgement call.
11622 case BO_Shl:
11623 // ...except that we want to treat '1 << (blah)' as logically
11624 // positive. It's an important idiom.
11625 if (IntegerLiteral *I
11626 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11627 if (I->getValue() == 1) {
11628 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11629 return IntRange(R.Width, /*NonNegative*/ true);
11630 }
11631 }
11632 [[fallthrough]];
11633
11634 case BO_ShlAssign:
11635 return IntRange::forValueOfType(C, GetExprType(E));
11636
11637 // Right shift by a constant can narrow its left argument.
11638 case BO_Shr:
11639 case BO_ShrAssign: {
11640 std::optional<IntRange> L = TryGetExprRange(
11641 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11642 if (!L)
11643 return std::nullopt;
11644
11645 // If the shift amount is a positive constant, drop the width by
11646 // that much.
11647 if (std::optional<llvm::APSInt> shift =
11648 BO->getRHS()->getIntegerConstantExpr(C)) {
11649 if (shift->isNonNegative()) {
11650 if (shift->uge(L->Width))
11651 L->Width = (L->NonNegative ? 0 : 1);
11652 else
11653 L->Width -= shift->getZExtValue();
11654 }
11655 }
11656
11657 return L;
11658 }
11659
11660 // Comma acts as its right operand.
11661 case BO_Comma:
11662 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11663 Approximate);
11664
11665 case BO_Add:
11666 if (!Approximate)
11667 Combine = IntRange::sum;
11668 break;
11669
11670 case BO_Sub:
11671 if (BO->getLHS()->getType()->isPointerType())
11672 return IntRange::forValueOfType(C, GetExprType(E));
11673 if (!Approximate)
11674 Combine = IntRange::difference;
11675 break;
11676
11677 case BO_Mul:
11678 if (!Approximate)
11679 Combine = IntRange::product;
11680 break;
11681
11682 // The width of a division result is mostly determined by the size
11683 // of the LHS.
11684 case BO_Div: {
11685 // Don't 'pre-truncate' the operands.
11686 unsigned opWidth = C.getIntWidth(GetExprType(E));
11687 std::optional<IntRange> L = TryGetExprRange(
11688 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11689 if (!L)
11690 return std::nullopt;
11691
11692 // If the divisor is constant, use that.
11693 if (std::optional<llvm::APSInt> divisor =
11694 BO->getRHS()->getIntegerConstantExpr(C)) {
11695 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11696 if (log2 >= L->Width)
11697 L->Width = (L->NonNegative ? 0 : 1);
11698 else
11699 L->Width = std::min(L->Width - log2, MaxWidth);
11700 return L;
11701 }
11702
11703 // Otherwise, just use the LHS's width.
11704 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11705 // could be -1.
11706 std::optional<IntRange> R = TryGetExprRange(
11707 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11708 if (!R)
11709 return std::nullopt;
11710
11711 return IntRange(L->Width, L->NonNegative && R->NonNegative);
11712 }
11713
11714 case BO_Rem:
11715 Combine = IntRange::rem;
11716 break;
11717
11718 // The default behavior is okay for these.
11719 case BO_Xor:
11720 case BO_Or:
11721 break;
11722 }
11723
11724 // Combine the two ranges, but limit the result to the type in which we
11725 // performed the computation.
11726 QualType T = GetExprType(E);
11727 unsigned opWidth = C.getIntWidth(T);
11728 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
11729 InConstantContext, Approximate);
11730 if (!L)
11731 return std::nullopt;
11732
11733 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
11734 InConstantContext, Approximate);
11735 if (!R)
11736 return std::nullopt;
11737
11738 IntRange C = Combine(*L, *R);
11739 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11740 C.Width = std::min(C.Width, MaxWidth);
11741 return C;
11742 }
11743
11744 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11745 switch (UO->getOpcode()) {
11746 // Boolean-valued operations are white-listed.
11747 case UO_LNot:
11748 return IntRange::forBoolType();
11749
11750 // Operations with opaque sources are black-listed.
11751 case UO_Deref:
11752 case UO_AddrOf: // should be impossible
11753 return IntRange::forValueOfType(C, GetExprType(E));
11754
11755 case UO_Minus: {
11756 if (E->getType()->isUnsignedIntegerType()) {
11757 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11758 Approximate);
11759 }
11760
11761 std::optional<IntRange> SubRange = TryGetExprRange(
11762 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11763
11764 if (!SubRange)
11765 return std::nullopt;
11766
11767 // If the range was previously non-negative, we need an extra bit for the
11768 // sign bit. Otherwise, we need an extra bit because the negation of the
11769 // most-negative value is one bit wider than that value.
11770 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
11771 }
11772
11773 case UO_Not: {
11774 if (E->getType()->isUnsignedIntegerType()) {
11775 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11776 Approximate);
11777 }
11778
11779 std::optional<IntRange> SubRange = TryGetExprRange(
11780 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11781
11782 if (!SubRange)
11783 return std::nullopt;
11784
11785 // The width increments by 1 if the sub-expression cannot be negative
11786 // since it now can be.
11787 return IntRange(
11788 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
11789 false);
11790 }
11791
11792 default:
11793 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11794 Approximate);
11795 }
11796 }
11797
11798 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11799 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11800 Approximate);
11801
11802 if (const auto *BitField = E->getSourceBitField())
11803 return IntRange(BitField->getBitWidthValue(),
11804 BitField->getType()->isUnsignedIntegerOrEnumerationType());
11805
11806 if (GetExprType(E)->isVoidType())
11807 return std::nullopt;
11808
11809 return IntRange::forValueOfType(C, GetExprType(E));
11810}
11811
11812static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11813 bool InConstantContext,
11814 bool Approximate) {
11815 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11816 Approximate);
11817}
11818
11819/// Checks whether the given value, which currently has the given
11820/// source semantics, has the same value when coerced through the
11821/// target semantics.
11822static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11823 const llvm::fltSemantics &Src,
11824 const llvm::fltSemantics &Tgt) {
11825 llvm::APFloat truncated = value;
11826
11827 bool ignored;
11828 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11829 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11830
11831 return truncated.bitwiseIsEqual(value);
11832}
11833
11834/// Checks whether the given value, which currently has the given
11835/// source semantics, has the same value when coerced through the
11836/// target semantics.
11837///
11838/// The value might be a vector of floats (or a complex number).
11839static bool IsSameFloatAfterCast(const APValue &value,
11840 const llvm::fltSemantics &Src,
11841 const llvm::fltSemantics &Tgt) {
11842 if (value.isFloat())
11843 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11844
11845 if (value.isVector()) {
11846 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11847 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11848 return false;
11849 return true;
11850 }
11851
11852 if (value.isMatrix()) {
11853 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
11854 if (!IsSameFloatAfterCast(value.getMatrixElt(i), Src, Tgt))
11855 return false;
11856 return true;
11857 }
11858
11859 assert(value.isComplexFloat());
11860 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11861 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11862}
11863
11864static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11865 bool IsListInit = false);
11866
11867static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
11868 // Suppress cases where we are comparing against an enum constant.
11869 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11870 if (isa<EnumConstantDecl>(DR->getDecl()))
11871 return true;
11872
11873 // Suppress cases where the value is expanded from a macro, unless that macro
11874 // is how a language represents a boolean literal. This is the case in both C
11875 // and Objective-C.
11876 SourceLocation BeginLoc = E->getBeginLoc();
11877 if (BeginLoc.isMacroID()) {
11878 StringRef MacroName = Lexer::getImmediateMacroName(
11879 BeginLoc, S.getSourceManager(), S.getLangOpts());
11880 return MacroName != "YES" && MacroName != "NO" &&
11881 MacroName != "true" && MacroName != "false";
11882 }
11883
11884 return false;
11885}
11886
11887static bool isKnownToHaveUnsignedValue(const Expr *E) {
11888 return E->getType()->isIntegerType() &&
11889 (!E->getType()->isSignedIntegerType() ||
11891}
11892
11893namespace {
11894/// The promoted range of values of a type. In general this has the
11895/// following structure:
11896///
11897/// |-----------| . . . |-----------|
11898/// ^ ^ ^ ^
11899/// Min HoleMin HoleMax Max
11900///
11901/// ... where there is only a hole if a signed type is promoted to unsigned
11902/// (in which case Min and Max are the smallest and largest representable
11903/// values).
11904struct PromotedRange {
11905 // Min, or HoleMax if there is a hole.
11906 llvm::APSInt PromotedMin;
11907 // Max, or HoleMin if there is a hole.
11908 llvm::APSInt PromotedMax;
11909
11910 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11911 if (R.Width == 0)
11912 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11913 else if (R.Width >= BitWidth && !Unsigned) {
11914 // Promotion made the type *narrower*. This happens when promoting
11915 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11916 // Treat all values of 'signed int' as being in range for now.
11917 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11918 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11919 } else {
11920 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11921 .extOrTrunc(BitWidth);
11922 PromotedMin.setIsUnsigned(Unsigned);
11923
11924 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11925 .extOrTrunc(BitWidth);
11926 PromotedMax.setIsUnsigned(Unsigned);
11927 }
11928 }
11929
11930 // Determine whether this range is contiguous (has no hole).
11931 bool isContiguous() const { return PromotedMin <= PromotedMax; }
11932
11933 // Where a constant value is within the range.
11934 enum ComparisonResult {
11935 LT = 0x1,
11936 LE = 0x2,
11937 GT = 0x4,
11938 GE = 0x8,
11939 EQ = 0x10,
11940 NE = 0x20,
11941 InRangeFlag = 0x40,
11942
11943 Less = LE | LT | NE,
11944 Min = LE | InRangeFlag,
11945 InRange = InRangeFlag,
11946 Max = GE | InRangeFlag,
11947 Greater = GE | GT | NE,
11948
11949 OnlyValue = LE | GE | EQ | InRangeFlag,
11950 InHole = NE
11951 };
11952
11953 ComparisonResult compare(const llvm::APSInt &Value) const {
11954 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11955 Value.isUnsigned() == PromotedMin.isUnsigned());
11956 if (!isContiguous()) {
11957 assert(Value.isUnsigned() && "discontiguous range for signed compare");
11958 if (Value.isMinValue()) return Min;
11959 if (Value.isMaxValue()) return Max;
11960 if (Value >= PromotedMin) return InRange;
11961 if (Value <= PromotedMax) return InRange;
11962 return InHole;
11963 }
11964
11965 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11966 case -1: return Less;
11967 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11968 case 1:
11969 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11970 case -1: return InRange;
11971 case 0: return Max;
11972 case 1: return Greater;
11973 }
11974 }
11975
11976 llvm_unreachable("impossible compare result");
11977 }
11978
11979 static std::optional<StringRef>
11980 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11981 if (Op == BO_Cmp) {
11982 ComparisonResult LTFlag = LT, GTFlag = GT;
11983 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11984
11985 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11986 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11987 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11988 return std::nullopt;
11989 }
11990
11991 ComparisonResult TrueFlag, FalseFlag;
11992 if (Op == BO_EQ) {
11993 TrueFlag = EQ;
11994 FalseFlag = NE;
11995 } else if (Op == BO_NE) {
11996 TrueFlag = NE;
11997 FalseFlag = EQ;
11998 } else {
11999 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12000 TrueFlag = LT;
12001 FalseFlag = GE;
12002 } else {
12003 TrueFlag = GT;
12004 FalseFlag = LE;
12005 }
12006 if (Op == BO_GE || Op == BO_LE)
12007 std::swap(TrueFlag, FalseFlag);
12008 }
12009 if (R & TrueFlag)
12010 return StringRef("true");
12011 if (R & FalseFlag)
12012 return StringRef("false");
12013 return std::nullopt;
12014 }
12015};
12016}
12017
12018static bool HasEnumType(const Expr *E) {
12019 // Strip off implicit integral promotions.
12020 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12021 if (ICE->getCastKind() != CK_IntegralCast &&
12022 ICE->getCastKind() != CK_NoOp)
12023 break;
12024 E = ICE->getSubExpr();
12025 }
12026
12027 return E->getType()->isEnumeralType();
12028}
12029
12030static int classifyConstantValue(Expr *Constant) {
12031 // The values of this enumeration are used in the diagnostics
12032 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12033 enum ConstantValueKind {
12034 Miscellaneous = 0,
12035 LiteralTrue,
12036 LiteralFalse
12037 };
12038 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12039 return BL->getValue() ? ConstantValueKind::LiteralTrue
12040 : ConstantValueKind::LiteralFalse;
12041 return ConstantValueKind::Miscellaneous;
12042}
12043
12045 Expr *Constant, Expr *Other,
12046 const llvm::APSInt &Value,
12047 bool RhsConstant) {
12049 return false;
12050
12051 Expr *OriginalOther = Other;
12052
12053 Constant = Constant->IgnoreParenImpCasts();
12054 Other = Other->IgnoreParenImpCasts();
12055
12056 // Suppress warnings on tautological comparisons between values of the same
12057 // enumeration type. There are only two ways we could warn on this:
12058 // - If the constant is outside the range of representable values of
12059 // the enumeration. In such a case, we should warn about the cast
12060 // to enumeration type, not about the comparison.
12061 // - If the constant is the maximum / minimum in-range value. For an
12062 // enumeratin type, such comparisons can be meaningful and useful.
12063 if (Constant->getType()->isEnumeralType() &&
12064 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12065 return false;
12066
12067 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12068 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
12069 if (!OtherValueRange)
12070 return false;
12071
12072 QualType OtherT = Other->getType();
12073 if (const auto *AT = OtherT->getAs<AtomicType>())
12074 OtherT = AT->getValueType();
12075 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12076
12077 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12078 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12079 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12080 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
12081 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12082
12083 // Whether we're treating Other as being a bool because of the form of
12084 // expression despite it having another type (typically 'int' in C).
12085 bool OtherIsBooleanDespiteType =
12086 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12087 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12088 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12089
12090 // Check if all values in the range of possible values of this expression
12091 // lead to the same comparison outcome.
12092 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12093 Value.isUnsigned());
12094 auto Cmp = OtherPromotedValueRange.compare(Value);
12095 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12096 if (!Result)
12097 return false;
12098
12099 // Also consider the range determined by the type alone. This allows us to
12100 // classify the warning under the proper diagnostic group.
12101 bool TautologicalTypeCompare = false;
12102 {
12103 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12104 Value.isUnsigned());
12105 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12106 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12107 RhsConstant)) {
12108 TautologicalTypeCompare = true;
12109 Cmp = TypeCmp;
12110 Result = TypeResult;
12111 }
12112 }
12113
12114 // Don't warn if the non-constant operand actually always evaluates to the
12115 // same value.
12116 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12117 return false;
12118
12119 // Suppress the diagnostic for an in-range comparison if the constant comes
12120 // from a macro or enumerator. We don't want to diagnose
12121 //
12122 // some_long_value <= INT_MAX
12123 //
12124 // when sizeof(int) == sizeof(long).
12125 bool InRange = Cmp & PromotedRange::InRangeFlag;
12126 if (InRange && IsEnumConstOrFromMacro(S, Constant))
12127 return false;
12128
12129 // A comparison of an unsigned bit-field against 0 is really a type problem,
12130 // even though at the type level the bit-field might promote to 'signed int'.
12131 if (Other->refersToBitField() && InRange && Value == 0 &&
12132 Other->getType()->isUnsignedIntegerOrEnumerationType())
12133 TautologicalTypeCompare = true;
12134
12135 // If this is a comparison to an enum constant, include that
12136 // constant in the diagnostic.
12137 const EnumConstantDecl *ED = nullptr;
12138 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
12139 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12140
12141 // Should be enough for uint128 (39 decimal digits)
12142 SmallString<64> PrettySourceValue;
12143 llvm::raw_svector_ostream OS(PrettySourceValue);
12144 if (ED) {
12145 OS << '\'' << *ED << "' (" << Value << ")";
12146 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12147 Constant->IgnoreParenImpCasts())) {
12148 OS << (BL->getValue() ? "YES" : "NO");
12149 } else {
12150 OS << Value;
12151 }
12152
12153 if (!TautologicalTypeCompare) {
12154 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12155 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12156 << E->getOpcodeStr() << OS.str() << *Result
12157 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12158 return true;
12159 }
12160
12161 if (IsObjCSignedCharBool) {
12163 S.PDiag(diag::warn_tautological_compare_objc_bool)
12164 << OS.str() << *Result);
12165 return true;
12166 }
12167
12168 // FIXME: We use a somewhat different formatting for the in-range cases and
12169 // cases involving boolean values for historical reasons. We should pick a
12170 // consistent way of presenting these diagnostics.
12171 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12172
12174 E->getOperatorLoc(), E,
12175 S.PDiag(!InRange ? diag::warn_out_of_range_compare
12176 : diag::warn_tautological_bool_compare)
12177 << OS.str() << classifyConstantValue(Constant) << OtherT
12178 << OtherIsBooleanDespiteType << *Result
12179 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12180 } else {
12181 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12182 unsigned Diag =
12183 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12184 ? (HasEnumType(OriginalOther)
12185 ? diag::warn_unsigned_enum_always_true_comparison
12186 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12187 : diag::warn_unsigned_always_true_comparison)
12188 : diag::warn_tautological_constant_compare;
12189
12190 S.Diag(E->getOperatorLoc(), Diag)
12191 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12192 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12193 }
12194
12195 return true;
12196}
12197
12198/// Analyze the operands of the given comparison. Implements the
12199/// fallback case from AnalyzeComparison.
12204
12205/// Implements -Wsign-compare.
12206///
12207/// \param E the binary operator to check for warnings
12209 // The type the comparison is being performed in.
12210 QualType T = E->getLHS()->getType();
12211
12212 // Only analyze comparison operators where both sides have been converted to
12213 // the same type.
12214 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12215 return AnalyzeImpConvsInComparison(S, E);
12216
12217 // Don't analyze value-dependent comparisons directly.
12218 if (E->isValueDependent())
12219 return AnalyzeImpConvsInComparison(S, E);
12220
12221 Expr *LHS = E->getLHS();
12222 Expr *RHS = E->getRHS();
12223
12224 if (T->isIntegralType(S.Context)) {
12225 std::optional<llvm::APSInt> RHSValue =
12227 std::optional<llvm::APSInt> LHSValue =
12229
12230 // We don't care about expressions whose result is a constant.
12231 if (RHSValue && LHSValue)
12232 return AnalyzeImpConvsInComparison(S, E);
12233
12234 // We only care about expressions where just one side is literal
12235 if ((bool)RHSValue ^ (bool)LHSValue) {
12236 // Is the constant on the RHS or LHS?
12237 const bool RhsConstant = (bool)RHSValue;
12238 Expr *Const = RhsConstant ? RHS : LHS;
12239 Expr *Other = RhsConstant ? LHS : RHS;
12240 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12241
12242 // Check whether an integer constant comparison results in a value
12243 // of 'true' or 'false'.
12244 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12245 return AnalyzeImpConvsInComparison(S, E);
12246 }
12247 }
12248
12249 if (!T->hasUnsignedIntegerRepresentation()) {
12250 // We don't do anything special if this isn't an unsigned integral
12251 // comparison: we're only interested in integral comparisons, and
12252 // signed comparisons only happen in cases we don't care to warn about.
12253 return AnalyzeImpConvsInComparison(S, E);
12254 }
12255
12256 LHS = LHS->IgnoreParenImpCasts();
12257 RHS = RHS->IgnoreParenImpCasts();
12258
12259 if (!S.getLangOpts().CPlusPlus) {
12260 // Avoid warning about comparison of integers with different signs when
12261 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12262 // the type of `E`.
12263 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12264 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12265 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12266 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12267 }
12268
12269 // Check to see if one of the (unmodified) operands is of different
12270 // signedness.
12271 Expr *signedOperand, *unsignedOperand;
12273 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12274 "unsigned comparison between two signed integer expressions?");
12275 signedOperand = LHS;
12276 unsignedOperand = RHS;
12277 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12278 signedOperand = RHS;
12279 unsignedOperand = LHS;
12280 } else {
12281 return AnalyzeImpConvsInComparison(S, E);
12282 }
12283
12284 // Otherwise, calculate the effective range of the signed operand.
12285 std::optional<IntRange> signedRange =
12287 /*Approximate=*/true);
12288 if (!signedRange)
12289 return;
12290
12291 // Go ahead and analyze implicit conversions in the operands. Note
12292 // that we skip the implicit conversions on both sides.
12295
12296 // If the signed range is non-negative, -Wsign-compare won't fire.
12297 if (signedRange->NonNegative)
12298 return;
12299
12300 // For (in)equality comparisons, if the unsigned operand is a
12301 // constant which cannot collide with a overflowed signed operand,
12302 // then reinterpreting the signed operand as unsigned will not
12303 // change the result of the comparison.
12304 if (E->isEqualityOp()) {
12305 unsigned comparisonWidth = S.Context.getIntWidth(T);
12306 std::optional<IntRange> unsignedRange = TryGetExprRange(
12307 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
12308 /*Approximate=*/true);
12309 if (!unsignedRange)
12310 return;
12311
12312 // We should never be unable to prove that the unsigned operand is
12313 // non-negative.
12314 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12315
12316 if (unsignedRange->Width < comparisonWidth)
12317 return;
12318 }
12319
12321 S.PDiag(diag::warn_mixed_sign_comparison)
12322 << LHS->getType() << RHS->getType()
12323 << LHS->getSourceRange() << RHS->getSourceRange());
12324}
12325
12326/// Analyzes an attempt to assign the given value to a bitfield.
12327///
12328/// Returns true if there was something fishy about the attempt.
12330 SourceLocation InitLoc) {
12331 assert(Bitfield->isBitField());
12332 if (Bitfield->isInvalidDecl())
12333 return false;
12334
12335 // White-list bool bitfields.
12336 QualType BitfieldType = Bitfield->getType();
12337 if (BitfieldType->isBooleanType())
12338 return false;
12339
12340 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12341 // If the underlying enum type was not explicitly specified as an unsigned
12342 // type and the enum contain only positive values, MSVC++ will cause an
12343 // inconsistency by storing this as a signed type.
12344 if (S.getLangOpts().CPlusPlus11 &&
12345 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12346 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12347 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12348 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12349 << BitfieldEnumDecl;
12350 }
12351 }
12352
12353 // Ignore value- or type-dependent expressions.
12354 if (Bitfield->getBitWidth()->isValueDependent() ||
12355 Bitfield->getBitWidth()->isTypeDependent() ||
12356 Init->isValueDependent() ||
12357 Init->isTypeDependent())
12358 return false;
12359
12360 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12361 unsigned FieldWidth = Bitfield->getBitWidthValue();
12362
12363 Expr::EvalResult Result;
12364 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12366 // The RHS is not constant. If the RHS has an enum type, make sure the
12367 // bitfield is wide enough to hold all the values of the enum without
12368 // truncation.
12369 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12370 const PreferredTypeAttr *PTAttr = nullptr;
12371 if (!ED) {
12372 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12373 if (PTAttr)
12374 ED = PTAttr->getType()->getAsEnumDecl();
12375 }
12376 if (ED) {
12377 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12378
12379 // Enum types are implicitly signed on Windows, so check if there are any
12380 // negative enumerators to see if the enum was intended to be signed or
12381 // not.
12382 bool SignedEnum = ED->getNumNegativeBits() > 0;
12383
12384 // Check for surprising sign changes when assigning enum values to a
12385 // bitfield of different signedness. If the bitfield is signed and we
12386 // have exactly the right number of bits to store this unsigned enum,
12387 // suggest changing the enum to an unsigned type. This typically happens
12388 // on Windows where unfixed enums always use an underlying type of 'int'.
12389 unsigned DiagID = 0;
12390 if (SignedEnum && !SignedBitfield) {
12391 DiagID =
12392 PTAttr == nullptr
12393 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12394 : diag::
12395 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12396 } else if (SignedBitfield && !SignedEnum &&
12397 ED->getNumPositiveBits() == FieldWidth) {
12398 DiagID =
12399 PTAttr == nullptr
12400 ? diag::warn_signed_bitfield_enum_conversion
12401 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12402 }
12403 if (DiagID) {
12404 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12405 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12406 SourceRange TypeRange =
12407 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12408 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12409 << SignedEnum << TypeRange;
12410 if (PTAttr)
12411 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12412 << ED;
12413 }
12414
12415 // Compute the required bitwidth. If the enum has negative values, we need
12416 // one more bit than the normal number of positive bits to represent the
12417 // sign bit.
12418 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12419 ED->getNumNegativeBits())
12420 : ED->getNumPositiveBits();
12421
12422 // Check the bitwidth.
12423 if (BitsNeeded > FieldWidth) {
12424 Expr *WidthExpr = Bitfield->getBitWidth();
12425 auto DiagID =
12426 PTAttr == nullptr
12427 ? diag::warn_bitfield_too_small_for_enum
12428 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12429 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12430 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12431 << BitsNeeded << ED << WidthExpr->getSourceRange();
12432 if (PTAttr)
12433 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12434 << ED;
12435 }
12436 }
12437
12438 return false;
12439 }
12440
12441 llvm::APSInt Value = Result.Val.getInt();
12442
12443 unsigned OriginalWidth = Value.getBitWidth();
12444
12445 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12446 // false positives where the user is demonstrating they intend to use the
12447 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12448 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12449 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12450 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12451 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12452 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
12453 S.findMacroSpelling(MaybeMacroLoc, "true"))
12454 return false;
12455 }
12456
12457 if (!Value.isSigned() || Value.isNegative())
12458 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12459 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12460 OriginalWidth = Value.getSignificantBits();
12461
12462 if (OriginalWidth <= FieldWidth)
12463 return false;
12464
12465 // Compute the value which the bitfield will contain.
12466 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12467 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12468
12469 // Check whether the stored value is equal to the original value.
12470 TruncatedValue = TruncatedValue.extend(OriginalWidth);
12471 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12472 return false;
12473
12474 std::string PrettyValue = toString(Value, 10);
12475 std::string PrettyTrunc = toString(TruncatedValue, 10);
12476
12477 S.Diag(InitLoc, OneAssignedToOneBitBitfield
12478 ? diag::warn_impcast_single_bit_bitield_precision_constant
12479 : diag::warn_impcast_bitfield_precision_constant)
12480 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12481 << Init->getSourceRange();
12482
12483 return true;
12484}
12485
12486/// Analyze the given simple or compound assignment for warning-worthy
12487/// operations.
12489 // Just recurse on the LHS.
12491
12492 // We want to recurse on the RHS as normal unless we're assigning to
12493 // a bitfield.
12494 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12495 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12496 E->getOperatorLoc())) {
12497 // Recurse, ignoring any implicit conversions on the RHS.
12499 E->getOperatorLoc());
12500 }
12501 }
12502
12503 // Set context flag for overflow behavior type assignment analysis, use RAII
12504 // pattern to handle nested assignments.
12505 llvm::SaveAndRestore OBTAssignmentContext(
12507
12509
12510 // Diagnose implicitly sequentially-consistent atomic assignment.
12511 if (E->getLHS()->getType()->isAtomicType())
12512 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12513}
12514
12515/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12516static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12517 QualType T, SourceLocation CContext, unsigned diag,
12518 bool PruneControlFlow = false) {
12519 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12520 // address space annotations isn't really useful. The warnings aren't because
12521 // you're converting a `private int` to `unsigned int`, it is because you're
12522 // conerting `int` to `unsigned int`.
12523 if (SourceType.hasAddressSpace())
12524 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
12525 if (T.hasAddressSpace())
12527 if (PruneControlFlow) {
12529 S.PDiag(diag)
12530 << SourceType << T << E->getSourceRange()
12531 << SourceRange(CContext));
12532 return;
12533 }
12534 S.Diag(E->getExprLoc(), diag)
12535 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12536}
12537
12538/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12539static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
12540 SourceLocation CContext, unsigned diag,
12541 bool PruneControlFlow = false) {
12542 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
12543}
12544
12545/// Diagnose an implicit cast from a floating point value to an integer value.
12546static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
12547 SourceLocation CContext) {
12548 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12549 bool PruneWarnings = S.inTemplateInstantiation();
12550
12551 const Expr *InnerE = E->IgnoreParenImpCasts();
12552 // We also want to warn on, e.g., "int i = -1.234"
12553 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
12554 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12555 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12556
12557 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12558
12559 llvm::APFloat Value(0.0);
12560 bool IsConstant =
12562 if (!IsConstant) {
12563 if (S.ObjC().isSignedCharBool(T)) {
12565 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12566 << E->getType());
12567 }
12568
12569 return DiagnoseImpCast(S, E, T, CContext,
12570 diag::warn_impcast_float_integer, PruneWarnings);
12571 }
12572
12573 bool isExact = false;
12574
12575 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12576 T->hasUnsignedIntegerRepresentation());
12577 llvm::APFloat::opStatus Result = Value.convertToInteger(
12578 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12579
12580 // FIXME: Force the precision of the source value down so we don't print
12581 // digits which are usually useless (we don't really care here if we
12582 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12583 // would automatically print the shortest representation, but it's a bit
12584 // tricky to implement.
12585 SmallString<16> PrettySourceValue;
12586 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12587 precision = (precision * 59 + 195) / 196;
12588 Value.toString(PrettySourceValue, precision);
12589
12590 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
12592 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12593 << PrettySourceValue);
12594 }
12595
12596 if (Result == llvm::APFloat::opOK && isExact) {
12597 if (IsLiteral) return;
12598 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12599 PruneWarnings);
12600 }
12601
12602 // Conversion of a floating-point value to a non-bool integer where the
12603 // integral part cannot be represented by the integer type is undefined.
12604 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12605 return DiagnoseImpCast(
12606 S, E, T, CContext,
12607 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12608 : diag::warn_impcast_float_to_integer_out_of_range,
12609 PruneWarnings);
12610
12611 unsigned DiagID = 0;
12612 if (IsLiteral) {
12613 // Warn on floating point literal to integer.
12614 DiagID = diag::warn_impcast_literal_float_to_integer;
12615 } else if (IntegerValue == 0) {
12616 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
12617 return DiagnoseImpCast(S, E, T, CContext,
12618 diag::warn_impcast_float_integer, PruneWarnings);
12619 }
12620 // Warn on non-zero to zero conversion.
12621 DiagID = diag::warn_impcast_float_to_integer_zero;
12622 } else {
12623 if (IntegerValue.isUnsigned()) {
12624 if (!IntegerValue.isMaxValue()) {
12625 return DiagnoseImpCast(S, E, T, CContext,
12626 diag::warn_impcast_float_integer, PruneWarnings);
12627 }
12628 } else { // IntegerValue.isSigned()
12629 if (!IntegerValue.isMaxSignedValue() &&
12630 !IntegerValue.isMinSignedValue()) {
12631 return DiagnoseImpCast(S, E, T, CContext,
12632 diag::warn_impcast_float_integer, PruneWarnings);
12633 }
12634 }
12635 // Warn on evaluatable floating point expression to integer conversion.
12636 DiagID = diag::warn_impcast_float_to_integer;
12637 }
12638
12639 SmallString<16> PrettyTargetValue;
12640 if (IsBool)
12641 PrettyTargetValue = Value.isZero() ? "false" : "true";
12642 else
12643 IntegerValue.toString(PrettyTargetValue);
12644
12645 if (PruneWarnings) {
12647 S.PDiag(DiagID)
12648 << E->getType() << T.getUnqualifiedType()
12649 << PrettySourceValue << PrettyTargetValue
12650 << E->getSourceRange() << SourceRange(CContext));
12651 } else {
12652 S.Diag(E->getExprLoc(), DiagID)
12653 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12654 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12655 }
12656}
12657
12658/// Analyze the given compound assignment for the possible losing of
12659/// floating-point precision.
12661 assert(isa<CompoundAssignOperator>(E) &&
12662 "Must be compound assignment operation");
12663 // Recurse on the LHS and RHS in here
12666
12667 if (E->getLHS()->getType()->isAtomicType())
12668 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12669
12670 // Now check the outermost expression
12671 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12672 const auto *RBT = cast<CompoundAssignOperator>(E)
12673 ->getComputationResultType()
12674 ->getAs<BuiltinType>();
12675
12676 // The below checks assume source is floating point.
12677 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12678
12679 // If source is floating point but target is an integer.
12680 if (ResultBT->isInteger())
12681 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12682 E->getExprLoc(), diag::warn_impcast_float_integer);
12683
12684 if (!ResultBT->isFloatingPoint())
12685 return;
12686
12687 // If both source and target are floating points, warn about losing precision.
12689 QualType(ResultBT, 0), QualType(RBT, 0));
12690 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12691 // warn about dropping FP rank.
12692 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12693 diag::warn_impcast_float_result_precision);
12694}
12695
12696static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12697 IntRange Range) {
12698 if (!Range.Width) return "0";
12699
12700 llvm::APSInt ValueInRange = Value;
12701 ValueInRange.setIsSigned(!Range.NonNegative);
12702 ValueInRange = ValueInRange.trunc(Range.Width);
12703 return toString(ValueInRange, 10);
12704}
12705
12706static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
12707 bool ToBool) {
12708 if (!isa<ImplicitCastExpr>(Ex))
12709 return false;
12710
12711 const Expr *InnerE = Ex->IgnoreParenImpCasts();
12713 const Type *Source =
12715 if (Target->isDependentType())
12716 return false;
12717
12718 const auto *FloatCandidateBT =
12719 dyn_cast<BuiltinType>(ToBool ? Source : Target);
12720 const Type *BoolCandidateType = ToBool ? Target : Source;
12721
12722 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12723 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12724}
12725
12726static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
12727 SourceLocation CC) {
12728 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
12729 const Expr *CurrA = TheCall->getArg(I);
12730 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12731 continue;
12732
12733 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
12734 S, TheCall->getArg(I - 1), false));
12735 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
12736 S, TheCall->getArg(I + 1), false));
12737 if (IsSwapped) {
12738 // Warn on this floating-point to bool conversion.
12740 CurrA->getType(), CC,
12741 diag::warn_impcast_floating_point_to_bool);
12742 }
12743 }
12744}
12745
12747 SourceLocation CC) {
12748 // Don't warn on functions which have return type nullptr_t.
12749 if (isa<CallExpr>(E))
12750 return;
12751
12752 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12753 const Expr *NewE = E->IgnoreParenImpCasts();
12754 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
12755 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12756 if (!IsGNUNullExpr && !HasNullPtrType)
12757 return;
12758
12759 // Return if target type is a safe conversion.
12760 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12761 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12762 return;
12763
12764 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12765 E->getExprLoc()))
12766 return;
12767
12769
12770 // Venture through the macro stacks to get to the source of macro arguments.
12771 // The new location is a better location than the complete location that was
12772 // passed in.
12773 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12775
12776 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12777 if (IsGNUNullExpr && Loc.isMacroID()) {
12778 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12779 Loc, S.SourceMgr, S.getLangOpts());
12780 if (MacroName == "NULL")
12782 }
12783
12784 // Only warn if the null and context location are in the same macro expansion.
12785 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12786 return;
12787
12788 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12789 << HasNullPtrType << T << SourceRange(CC)
12791 S.getFixItZeroLiteralForType(T, Loc));
12792}
12793
12794// Helper function to filter out cases for constant width constant conversion.
12795// Don't warn on char array initialization or for non-decimal values.
12797 SourceLocation CC) {
12798 // If initializing from a constant, and the constant starts with '0',
12799 // then it is a binary, octal, or hexadecimal. Allow these constants
12800 // to fill all the bits, even if there is a sign change.
12801 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12802 const char FirstLiteralCharacter =
12803 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12804 if (FirstLiteralCharacter == '0')
12805 return false;
12806 }
12807
12808 // If the CC location points to a '{', and the type is char, then assume
12809 // assume it is an array initialization.
12810 if (CC.isValid() && T->isCharType()) {
12811 const char FirstContextCharacter =
12813 if (FirstContextCharacter == '{')
12814 return false;
12815 }
12816
12817 return true;
12818}
12819
12821 const auto *IL = dyn_cast<IntegerLiteral>(E);
12822 if (!IL) {
12823 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12824 if (UO->getOpcode() == UO_Minus)
12825 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12826 }
12827 }
12828
12829 return IL;
12830}
12831
12833 E = E->IgnoreParenImpCasts();
12834 SourceLocation ExprLoc = E->getExprLoc();
12835
12836 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12837 BinaryOperator::Opcode Opc = BO->getOpcode();
12838 Expr::EvalResult Result;
12839 // Do not diagnose unsigned shifts.
12840 if (Opc == BO_Shl) {
12841 const auto *LHS = getIntegerLiteral(BO->getLHS());
12842 const auto *RHS = getIntegerLiteral(BO->getRHS());
12843 if (LHS && LHS->getValue() == 0)
12844 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12845 else if (!E->isValueDependent() && LHS && RHS &&
12846 RHS->getValue().isNonNegative() &&
12848 S.Diag(ExprLoc, diag::warn_left_shift_always)
12849 << (Result.Val.getInt() != 0);
12850 else if (E->getType()->isSignedIntegerType())
12851 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
12854 ") != 0");
12855 }
12856 }
12857
12858 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12859 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12860 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12861 if (!LHS || !RHS)
12862 return;
12863 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12864 (RHS->getValue() == 0 || RHS->getValue() == 1))
12865 // Do not diagnose common idioms.
12866 return;
12867 if (LHS->getValue() != 0 && RHS->getValue() != 0)
12868 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12869 }
12870}
12871
12873 const Type *Target, Expr *E,
12874 QualType T,
12875 SourceLocation CC) {
12876 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
12877 Source != Target);
12878
12879 // Lone surrogates have a distinct representation in UTF-32.
12880 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
12881 // so don't warn on such conversion.
12882 if (Source->isChar16Type() && Target->isChar32Type())
12883 return;
12884
12885 Expr::EvalResult Result;
12888 llvm::APSInt Value(32);
12889 Value = Result.Val.getInt();
12890 bool IsASCII = Value <= 0x7F;
12891 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
12892 bool ConversionPreservesSemantics =
12893 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
12894
12895 if (!ConversionPreservesSemantics) {
12896 auto IsSingleCodeUnitCP = [](const QualType &T,
12897 const llvm::APSInt &Value) {
12898 if (T->isChar8Type())
12899 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
12900 if (T->isChar16Type())
12901 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
12902 assert(T->isChar32Type());
12903 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
12904 };
12905
12906 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
12907 << E->getType() << T
12908 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
12909 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
12910 }
12911 } else {
12912 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
12914 DiagnoseImpCast(S, E, T, CC,
12915 LosesPrecision ? diag::warn_impcast_unicode_precision
12916 : diag::warn_impcast_unicode_char_type);
12917 }
12918}
12919
12921 From = Context.getCanonicalType(From);
12922 To = Context.getCanonicalType(To);
12923 QualType MaybePointee = From->getPointeeType();
12924 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12925 From = MaybePointee;
12926 MaybePointee = To->getPointeeType();
12927 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12928 To = MaybePointee;
12929
12930 if (const auto *FromFn = From->getAs<FunctionType>()) {
12931 if (const auto *ToFn = To->getAs<FunctionType>()) {
12932 if (FromFn->getCFIUncheckedCalleeAttr() &&
12933 !ToFn->getCFIUncheckedCalleeAttr())
12934 return true;
12935 }
12936 }
12937 return false;
12938}
12939
12941 bool *ICContext, bool IsListInit) {
12942 if (E->isTypeDependent() || E->isValueDependent()) return;
12943
12944 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
12945 const Type *Target = Context.getCanonicalType(T).getTypePtr();
12946 if (Source == Target) return;
12947 if (Target->isDependentType()) return;
12948
12949 // If the conversion context location is invalid don't complain. We also
12950 // don't want to emit a warning if the issue occurs from the expansion of
12951 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12952 // delay this check as long as possible. Once we detect we are in that
12953 // scenario, we just return.
12954 if (CC.isInvalid())
12955 return;
12956
12957 if (Source->isAtomicType())
12958 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12959
12960 // Diagnose implicit casts to bool.
12961 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12962 if (isa<StringLiteral>(E))
12963 // Warn on string literal to bool. Checks for string literals in logical
12964 // and expressions, for instance, assert(0 && "error here"), are
12965 // prevented by a check in AnalyzeImplicitConversions().
12966 return DiagnoseImpCast(*this, E, T, CC,
12967 diag::warn_impcast_string_literal_to_bool);
12970 // This covers the literal expressions that evaluate to Objective-C
12971 // objects.
12972 return DiagnoseImpCast(*this, E, T, CC,
12973 diag::warn_impcast_objective_c_literal_to_bool);
12974 }
12975 if (Source->isPointerType() || Source->canDecayToPointerType()) {
12976 // Warn on pointer to bool conversion that is always true.
12978 SourceRange(CC));
12979 }
12980 }
12981
12983
12984 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12985 // is a typedef for signed char (macOS), then that constant value has to be 1
12986 // or 0.
12987 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
12990 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12992 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12993 << toString(Result.Val.getInt(), 10));
12994 }
12995 return;
12996 }
12997 }
12998
12999 // Check implicit casts from Objective-C collection literals to specialized
13000 // collection types, e.g., NSArray<NSString *> *.
13001 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13002 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
13003 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13004 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
13005
13006 // Strip vector types.
13007 if (isa<VectorType>(Source)) {
13008 if (Target->isSveVLSBuiltinType() &&
13009 (ARM().areCompatibleSveTypes(QualType(Target, 0),
13010 QualType(Source, 0)) ||
13011 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
13012 QualType(Source, 0))))
13013 return;
13014
13015 if (Target->isRVVVLSBuiltinType() &&
13016 (Context.areCompatibleRVVTypes(QualType(Target, 0),
13017 QualType(Source, 0)) ||
13018 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
13019 QualType(Source, 0))))
13020 return;
13021
13022 if (!isa<VectorType>(Target)) {
13023 if (SourceMgr.isInSystemMacro(CC))
13024 return;
13025 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
13026 }
13027 if (getLangOpts().HLSL &&
13028 Target->castAs<VectorType>()->getNumElements() <
13029 Source->castAs<VectorType>()->getNumElements()) {
13030 // Diagnose vector truncation but don't return. We may also want to
13031 // diagnose an element conversion.
13032 DiagnoseImpCast(*this, E, T, CC,
13033 diag::warn_hlsl_impcast_vector_truncation);
13034 }
13035
13036 // If the vector cast is cast between two vectors of the same size, it is
13037 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13038 if (!getLangOpts().HLSL &&
13039 Context.getTypeSize(Source) == Context.getTypeSize(Target))
13040 return;
13041
13042 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13043 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13044 }
13045 if (const auto *VecTy = dyn_cast<VectorType>(Target))
13046 Target = VecTy->getElementType().getTypePtr();
13047
13048 // Strip matrix types.
13049 if (isa<ConstantMatrixType>(Source)) {
13050 if (Target->isScalarType())
13051 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_matrix_scalar);
13052
13055 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13056 // Diagnose Matrix truncation but don't return. We may also want to
13057 // diagnose an element conversion.
13058 DiagnoseImpCast(*this, E, T, CC,
13059 diag::warn_hlsl_impcast_matrix_truncation);
13060 }
13061
13062 Source = cast<ConstantMatrixType>(Source)->getElementType().getTypePtr();
13063 Target = cast<ConstantMatrixType>(Target)->getElementType().getTypePtr();
13064 }
13065 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Target))
13066 Target = MatTy->getElementType().getTypePtr();
13067
13068 // Strip complex types.
13069 if (isa<ComplexType>(Source)) {
13070 if (!isa<ComplexType>(Target)) {
13071 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13072 return;
13073
13074 return DiagnoseImpCast(*this, E, T, CC,
13076 ? diag::err_impcast_complex_scalar
13077 : diag::warn_impcast_complex_scalar);
13078 }
13079
13080 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13081 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13082 }
13083
13084 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13085 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13086
13087 // Strip SVE vector types
13088 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13089 // Need the original target type for vector type checks
13090 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13091 // Handle conversion from scalable to fixed when msve-vector-bits is
13092 // specified
13093 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
13094 QualType(Source, 0)) ||
13095 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
13096 QualType(Source, 0)))
13097 return;
13098
13099 // If the vector cast is cast between two vectors of the same size, it is
13100 // a bitcast, not a conversion.
13101 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
13102 return;
13103
13104 Source = SourceBT->getSveEltType(Context).getTypePtr();
13105 }
13106
13107 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13108 Target = TargetBT->getSveEltType(Context).getTypePtr();
13109
13110 // If the source is floating point...
13111 if (SourceBT && SourceBT->isFloatingPoint()) {
13112 // ...and the target is floating point...
13113 if (TargetBT && TargetBT->isFloatingPoint()) {
13114 // ...then warn if we're dropping FP rank.
13115
13117 QualType(SourceBT, 0), QualType(TargetBT, 0));
13118 if (Order > 0) {
13119 // Don't warn about float constants that are precisely
13120 // representable in the target type.
13121 Expr::EvalResult result;
13122 if (E->EvaluateAsRValue(result, Context)) {
13123 // Value might be a float, a float vector, or a float complex.
13125 result.Val,
13126 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13127 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13128 return;
13129 }
13130
13131 if (SourceMgr.isInSystemMacro(CC))
13132 return;
13133
13134 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
13135 }
13136 // ... or possibly if we're increasing rank, too
13137 else if (Order < 0) {
13138 if (SourceMgr.isInSystemMacro(CC))
13139 return;
13140
13141 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
13142 }
13143 return;
13144 }
13145
13146 // If the target is integral, always warn.
13147 if (TargetBT && TargetBT->isInteger()) {
13148 if (SourceMgr.isInSystemMacro(CC))
13149 return;
13150
13151 DiagnoseFloatingImpCast(*this, E, T, CC);
13152 }
13153
13154 // Detect the case where a call result is converted from floating-point to
13155 // to bool, and the final argument to the call is converted from bool, to
13156 // discover this typo:
13157 //
13158 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13159 //
13160 // FIXME: This is an incredibly special case; is there some more general
13161 // way to detect this class of misplaced-parentheses bug?
13162 if (Target->isBooleanType() && isa<CallExpr>(E)) {
13163 // Check last argument of function call to see if it is an
13164 // implicit cast from a type matching the type the result
13165 // is being cast to.
13166 CallExpr *CEx = cast<CallExpr>(E);
13167 if (unsigned NumArgs = CEx->getNumArgs()) {
13168 Expr *LastA = CEx->getArg(NumArgs - 1);
13169 Expr *InnerE = LastA->IgnoreParenImpCasts();
13170 if (isa<ImplicitCastExpr>(LastA) &&
13171 InnerE->getType()->isBooleanType()) {
13172 // Warn on this floating-point to bool conversion
13173 DiagnoseImpCast(*this, E, T, CC,
13174 diag::warn_impcast_floating_point_to_bool);
13175 }
13176 }
13177 }
13178 return;
13179 }
13180
13181 // Valid casts involving fixed point types should be accounted for here.
13182 if (Source->isFixedPointType()) {
13183 if (Target->isUnsaturatedFixedPointType()) {
13187 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13188 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
13189 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
13190 if (Value > MaxVal || Value < MinVal) {
13192 PDiag(diag::warn_impcast_fixed_point_range)
13193 << Value.toString() << T
13194 << E->getSourceRange()
13195 << clang::SourceRange(CC));
13196 return;
13197 }
13198 }
13199 } else if (Target->isIntegerType()) {
13203 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13204
13205 bool Overflowed;
13206 llvm::APSInt IntResult = FXResult.convertToInt(
13207 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
13208 &Overflowed);
13209
13210 if (Overflowed) {
13212 PDiag(diag::warn_impcast_fixed_point_range)
13213 << FXResult.toString() << T
13214 << E->getSourceRange()
13215 << clang::SourceRange(CC));
13216 return;
13217 }
13218 }
13219 }
13220 } else if (Target->isUnsaturatedFixedPointType()) {
13221 if (Source->isIntegerType()) {
13225 llvm::APSInt Value = Result.Val.getInt();
13226
13227 bool Overflowed;
13228 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13229 Value, Context.getFixedPointSemantics(T), &Overflowed);
13230
13231 if (Overflowed) {
13233 PDiag(diag::warn_impcast_fixed_point_range)
13234 << toString(Value, /*Radix=*/10) << T
13235 << E->getSourceRange()
13236 << clang::SourceRange(CC));
13237 return;
13238 }
13239 }
13240 }
13241 }
13242
13243 // If we are casting an integer type to a floating point type without
13244 // initialization-list syntax, we might lose accuracy if the floating
13245 // point type has a narrower significand than the integer type.
13246 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13247 TargetBT->isFloatingType() && !IsListInit) {
13248 // Determine the number of precision bits in the source integer type.
13249 std::optional<IntRange> SourceRange =
13251 /*Approximate=*/true);
13252 if (!SourceRange)
13253 return;
13254 unsigned int SourcePrecision = SourceRange->Width;
13255
13256 // Determine the number of precision bits in the
13257 // target floating point type.
13258 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13259 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13260
13261 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13262 SourcePrecision > TargetPrecision) {
13263
13264 if (std::optional<llvm::APSInt> SourceInt =
13266 // If the source integer is a constant, convert it to the target
13267 // floating point type. Issue a warning if the value changes
13268 // during the whole conversion.
13269 llvm::APFloat TargetFloatValue(
13270 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13271 llvm::APFloat::opStatus ConversionStatus =
13272 TargetFloatValue.convertFromAPInt(
13273 *SourceInt, SourceBT->isSignedInteger(),
13274 llvm::APFloat::rmNearestTiesToEven);
13275
13276 if (ConversionStatus != llvm::APFloat::opOK) {
13277 SmallString<32> PrettySourceValue;
13278 SourceInt->toString(PrettySourceValue, 10);
13279 SmallString<32> PrettyTargetValue;
13280 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13281
13283 E->getExprLoc(), E,
13284 PDiag(diag::warn_impcast_integer_float_precision_constant)
13285 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13286 << E->getSourceRange() << clang::SourceRange(CC));
13287 }
13288 } else {
13289 // Otherwise, the implicit conversion may lose precision.
13290 DiagnoseImpCast(*this, E, T, CC,
13291 diag::warn_impcast_integer_float_precision);
13292 }
13293 }
13294 }
13295
13296 DiagnoseNullConversion(*this, E, T, CC);
13297
13299
13300 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13301 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
13302 return;
13303 }
13304
13305 if (Target->isBooleanType())
13306 DiagnoseIntInBoolContext(*this, E);
13307
13309 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
13310 << QualType(Source, 0) << QualType(Target, 0);
13311 }
13312
13313 if (!Source->isIntegerType() || !Target->isIntegerType())
13314 return;
13315
13316 // TODO: remove this early return once the false positives for constant->bool
13317 // in templates, macros, etc, are reduced or removed.
13318 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13319 return;
13320
13321 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
13322 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13324 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13325 << E->getType());
13326 }
13327 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13328 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
13329 if (!LikelySourceRange)
13330 return;
13331
13332 IntRange SourceTypeRange =
13333 IntRange::forTargetOfCanonicalType(Context, Source);
13334 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
13335
13336 if (LikelySourceRange->Width > TargetRange.Width) {
13337 // Check if target is a wrapping OBT - if so, don't warn about constant
13338 // conversion as this type may be used intentionally with implicit
13339 // truncation, especially during assignments.
13340 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13341 if (TargetOBT->isWrapKind()) {
13342 return;
13343 }
13344 }
13345
13346 // Check if source expression has an explicit __ob_wrap cast because if so,
13347 // wrapping was explicitly requested and we shouldn't warn
13348 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
13349 if (SourceOBT->isWrapKind()) {
13350 return;
13351 }
13352 }
13353
13354 // If the source is a constant, use a default-on diagnostic.
13355 // TODO: this should happen for bitfield stores, too.
13359 llvm::APSInt Value(32);
13360 Value = Result.Val.getInt();
13361
13362 if (SourceMgr.isInSystemMacro(CC))
13363 return;
13364
13365 std::string PrettySourceValue = toString(Value, 10);
13366 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13367
13369 PDiag(diag::warn_impcast_integer_precision_constant)
13370 << PrettySourceValue << PrettyTargetValue
13371 << E->getType() << T << E->getSourceRange()
13372 << SourceRange(CC));
13373 return;
13374 }
13375
13376 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13377 if (SourceMgr.isInSystemMacro(CC))
13378 return;
13379
13380 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
13381 if (UO->getOpcode() == UO_Minus)
13382 return DiagnoseImpCast(
13383 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
13384 }
13385
13386 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
13387 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
13388 /* pruneControlFlow */ true);
13389 return DiagnoseImpCast(*this, E, T, CC,
13390 diag::warn_impcast_integer_precision);
13391 }
13392
13393 if (TargetRange.Width > SourceTypeRange.Width) {
13394 if (auto *UO = dyn_cast<UnaryOperator>(E))
13395 if (UO->getOpcode() == UO_Minus)
13396 if (Source->isUnsignedIntegerType()) {
13397 if (Target->isUnsignedIntegerType())
13398 return DiagnoseImpCast(*this, E, T, CC,
13399 diag::warn_impcast_high_order_zero_bits);
13400 if (Target->isSignedIntegerType())
13401 return DiagnoseImpCast(*this, E, T, CC,
13402 diag::warn_impcast_nonnegative_result);
13403 }
13404 }
13405
13406 if (TargetRange.Width == LikelySourceRange->Width &&
13407 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13408 Source->isSignedIntegerType()) {
13409 // Warn when doing a signed to signed conversion, warn if the positive
13410 // source value is exactly the width of the target type, which will
13411 // cause a negative value to be stored.
13412
13415 !SourceMgr.isInSystemMacro(CC)) {
13416 llvm::APSInt Value = Result.Val.getInt();
13417 if (isSameWidthConstantConversion(*this, E, T, CC)) {
13418 std::string PrettySourceValue = toString(Value, 10);
13419 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13420
13421 Diag(E->getExprLoc(),
13422 PDiag(diag::warn_impcast_integer_precision_constant)
13423 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13424 << E->getSourceRange() << SourceRange(CC));
13425 return;
13426 }
13427 }
13428
13429 // Fall through for non-constants to give a sign conversion warning.
13430 }
13431
13432 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
13433 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13434 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13435 LikelySourceRange->Width == TargetRange.Width))) {
13436 if (SourceMgr.isInSystemMacro(CC))
13437 return;
13438
13439 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13440 TargetBT->isInteger() &&
13441 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13442 return;
13443 }
13444
13445 unsigned DiagID = diag::warn_impcast_integer_sign;
13446
13447 // Traditionally, gcc has warned about this under -Wsign-compare.
13448 // We also want to warn about it in -Wconversion.
13449 // So if -Wconversion is off, use a completely identical diagnostic
13450 // in the sign-compare group.
13451 // The conditional-checking code will
13452 if (ICContext) {
13453 DiagID = diag::warn_impcast_integer_sign_conditional;
13454 *ICContext = true;
13455 }
13456
13457 DiagnoseImpCast(*this, E, T, CC, DiagID);
13458 }
13459
13460 // If we're implicitly converting from an integer into an enumeration, that
13461 // is valid in C but invalid in C++.
13462 QualType SourceType = E->getEnumCoercedType(Context);
13463 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13464 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
13465 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
13466
13467 // Diagnose conversions between different enumeration types.
13468 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13469 // type, to give us better diagnostics.
13470 Source = Context.getCanonicalType(SourceType).getTypePtr();
13471
13472 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13473 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13474 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13475 TargetEnum->getDecl()->hasNameForLinkage() &&
13476 SourceEnum != TargetEnum) {
13477 if (SourceMgr.isInSystemMacro(CC))
13478 return;
13479
13480 return DiagnoseImpCast(*this, E, SourceType, T, CC,
13481 diag::warn_impcast_different_enum_types);
13482 }
13483}
13484
13486 SourceLocation CC, QualType T);
13487
13489 SourceLocation CC, bool &ICContext) {
13490 E = E->IgnoreParenImpCasts();
13491 // Diagnose incomplete type for second or third operand in C.
13492 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13493 S.RequireCompleteExprType(E, diag::err_incomplete_type);
13494
13495 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13496 return CheckConditionalOperator(S, CO, CC, T);
13497
13499 if (E->getType() != T)
13500 return S.CheckImplicitConversion(E, T, CC, &ICContext);
13501}
13502
13504 SourceLocation CC, QualType T) {
13506
13507 Expr *TrueExpr = E->getTrueExpr();
13508 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13509 TrueExpr = BCO->getCommon();
13510
13511 bool Suspicious = false;
13512 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13513 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13514
13515 if (T->isBooleanType())
13517
13518 // If -Wconversion would have warned about either of the candidates
13519 // for a signedness conversion to the context type...
13520 if (!Suspicious) return;
13521
13522 // ...but it's currently ignored...
13523 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13524 return;
13525
13526 // ...then check whether it would have warned about either of the
13527 // candidates for a signedness conversion to the condition type.
13528 if (E->getType() == T) return;
13529
13530 Suspicious = false;
13531 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
13532 &Suspicious);
13533 if (!Suspicious)
13535 E->getType(), CC, &Suspicious);
13536}
13537
13538/// Check conversion of given expression to boolean.
13539/// Input argument E is a logical expression.
13541 // Run the bool-like conversion checks only for C since there bools are
13542 // still not used as the return type from "boolean" operators or as the input
13543 // type for conditional operators.
13544 if (S.getLangOpts().CPlusPlus)
13545 return;
13547 return;
13549}
13550
13551namespace {
13552struct AnalyzeImplicitConversionsWorkItem {
13553 Expr *E;
13554 SourceLocation CC;
13555 bool IsListInit;
13556};
13557}
13558
13560 Sema &S, Expr *E, QualType T, SourceLocation CC,
13561 bool ExtraCheckForImplicitConversion,
13563 E = E->IgnoreParenImpCasts();
13564 WorkList.push_back({E, CC, false});
13565
13566 if (ExtraCheckForImplicitConversion && E->getType() != T)
13567 S.CheckImplicitConversion(E, T, CC);
13568}
13569
13570/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13571/// that should be visited are added to WorkList.
13573 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13575 Expr *OrigE = Item.E;
13576 SourceLocation CC = Item.CC;
13577
13578 QualType T = OrigE->getType();
13579 Expr *E = OrigE->IgnoreParenImpCasts();
13580
13581 // Propagate whether we are in a C++ list initialization expression.
13582 // If so, we do not issue warnings for implicit int-float conversion
13583 // precision loss, because C++11 narrowing already handles it.
13584 //
13585 // HLSL's initialization lists are special, so they shouldn't observe the C++
13586 // behavior here.
13587 bool IsListInit =
13588 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
13589 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
13590
13591 if (E->isTypeDependent() || E->isValueDependent())
13592 return;
13593
13594 Expr *SourceExpr = E;
13595 // Examine, but don't traverse into the source expression of an
13596 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13597 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13598 // evaluate it in the context of checking the specific conversion to T though.
13599 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13600 if (auto *Src = OVE->getSourceExpr())
13601 SourceExpr = Src;
13602
13603 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13604 if (UO->getOpcode() == UO_Not &&
13605 UO->getSubExpr()->isKnownToHaveBooleanValue())
13606 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13607 << OrigE->getSourceRange() << T->isBooleanType()
13608 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13609
13610 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
13611 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13612 BO->getLHS()->isKnownToHaveBooleanValue() &&
13613 BO->getRHS()->isKnownToHaveBooleanValue() &&
13614 BO->getLHS()->HasSideEffects(S.Context) &&
13615 BO->getRHS()->HasSideEffects(S.Context)) {
13617 const LangOptions &LO = S.getLangOpts();
13618 SourceLocation BLoc = BO->getOperatorLoc();
13619 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
13620 StringRef SR = clang::Lexer::getSourceText(
13621 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
13622 // To reduce false positives, only issue the diagnostic if the operator
13623 // is explicitly spelled as a punctuator. This suppresses the diagnostic
13624 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
13625 // in C, along with other macro spellings the user might invent.
13626 if (SR.str() == "&" || SR.str() == "|") {
13627
13628 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13629 << (BO->getOpcode() == BO_And ? "&" : "|")
13630 << OrigE->getSourceRange()
13632 BO->getOperatorLoc(),
13633 (BO->getOpcode() == BO_And ? "&&" : "||"));
13634 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13635 }
13636 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
13637 /// Analyze the given comma operator. The basic idea behind the analysis
13638 /// is to analyze the left and right operands slightly differently. The
13639 /// left operand needs to check whether the operand itself has an implicit
13640 /// conversion, but not whether the left operand induces an implicit
13641 /// conversion for the entire comma expression itself. This is similar to
13642 /// how CheckConditionalOperand behaves; it's as-if the correct operand
13643 /// were directly used for the implicit conversion check.
13644 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
13645 /*ExtraCheckForImplicitConversion=*/false, WorkList);
13646 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
13647 /*ExtraCheckForImplicitConversion=*/true, WorkList);
13648 return;
13649 }
13650 }
13651
13652 // For conditional operators, we analyze the arguments as if they
13653 // were being fed directly into the output.
13654 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13655 CheckConditionalOperator(S, CO, CC, T);
13656 return;
13657 }
13658
13659 // Check implicit argument conversions for function calls.
13660 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
13662
13663 // Go ahead and check any implicit conversions we might have skipped.
13664 // The non-canonical typecheck is just an optimization;
13665 // CheckImplicitConversion will filter out dead implicit conversions.
13666 if (SourceExpr->getType() != T)
13667 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
13668
13669 // Now continue drilling into this expression.
13670
13671 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13672 // The bound subexpressions in a PseudoObjectExpr are not reachable
13673 // as transitive children.
13674 // FIXME: Use a more uniform representation for this.
13675 for (auto *SE : POE->semantics())
13676 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13677 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13678 }
13679
13680 // Skip past explicit casts.
13681 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13682 E = CE->getSubExpr();
13683 // In the special case of a C++ function-style cast with braces,
13684 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
13685 // initializer. This InitListExpr basically belongs to the cast itself, so
13686 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
13688 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
13689 if (InitListE->getNumInits() == 1) {
13690 E = InitListE->getInit(0);
13691 }
13692 }
13693 }
13694 E = E->IgnoreParenImpCasts();
13695 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13696 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13697 WorkList.push_back({E, CC, IsListInit});
13698 return;
13699 }
13700
13701 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
13702 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
13703 // The base expression is only used to initialize the parameter for
13704 // arguments to `inout` parameters, so we only traverse down the base
13705 // expression for `inout` cases.
13706 if (OutArgE->isInOut())
13707 WorkList.push_back(
13708 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
13709 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
13710 return;
13711 }
13712
13713 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13714 // Do a somewhat different check with comparison operators.
13715 if (BO->isComparisonOp())
13716 return AnalyzeComparison(S, BO);
13717
13718 // And with simple assignments.
13719 if (BO->getOpcode() == BO_Assign)
13720 return AnalyzeAssignment(S, BO);
13721 // And with compound assignments.
13722 if (BO->isAssignmentOp())
13723 return AnalyzeCompoundAssignment(S, BO);
13724 }
13725
13726 // These break the otherwise-useful invariant below. Fortunately,
13727 // we don't really need to recurse into them, because any internal
13728 // expressions should have been analyzed already when they were
13729 // built into statements.
13730 if (isa<StmtExpr>(E)) return;
13731
13732 // Don't descend into unevaluated contexts.
13733 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13734
13735 // Now just recurse over the expression's children.
13736 CC = E->getExprLoc();
13737 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13738 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13739 for (Stmt *SubStmt : E->children()) {
13740 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13741 if (!ChildExpr)
13742 continue;
13743
13744 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
13745 if (ChildExpr == CSE->getOperand())
13746 // Do not recurse over a CoroutineSuspendExpr's operand.
13747 // The operand is also a subexpression of getCommonExpr(), and
13748 // recursing into it directly would produce duplicate diagnostics.
13749 continue;
13750
13751 if (IsLogicalAndOperator &&
13753 // Ignore checking string literals that are in logical and operators.
13754 // This is a common pattern for asserts.
13755 continue;
13756 WorkList.push_back({ChildExpr, CC, IsListInit});
13757 }
13758
13759 if (BO && BO->isLogicalOp()) {
13760 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13761 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13762 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13763
13764 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13765 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13766 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13767 }
13768
13769 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13770 if (U->getOpcode() == UO_LNot) {
13771 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13772 } else if (U->getOpcode() != UO_AddrOf) {
13773 if (U->getSubExpr()->getType()->isAtomicType())
13774 S.Diag(U->getSubExpr()->getBeginLoc(),
13775 diag::warn_atomic_implicit_seq_cst);
13776 }
13777 }
13778}
13779
13780/// AnalyzeImplicitConversions - Find and report any interesting
13781/// implicit conversions in the given expression. There are a couple
13782/// of competing diagnostics here, -Wconversion and -Wsign-compare.
13784 bool IsListInit/*= false*/) {
13786 WorkList.push_back({OrigE, CC, IsListInit});
13787 while (!WorkList.empty())
13788 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13789}
13790
13791// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13792// Returns true when emitting a warning about taking the address of a reference.
13793static bool CheckForReference(Sema &SemaRef, const Expr *E,
13794 const PartialDiagnostic &PD) {
13795 E = E->IgnoreParenImpCasts();
13796
13797 const FunctionDecl *FD = nullptr;
13798
13799 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13800 if (!DRE->getDecl()->getType()->isReferenceType())
13801 return false;
13802 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13803 if (!M->getMemberDecl()->getType()->isReferenceType())
13804 return false;
13805 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13806 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13807 return false;
13808 FD = Call->getDirectCallee();
13809 } else {
13810 return false;
13811 }
13812
13813 SemaRef.Diag(E->getExprLoc(), PD);
13814
13815 // If possible, point to location of function.
13816 if (FD) {
13817 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13818 }
13819
13820 return true;
13821}
13822
13823// Returns true if the SourceLocation is expanded from any macro body.
13824// Returns false if the SourceLocation is invalid, is from not in a macro
13825// expansion, or is from expanded from a top-level macro argument.
13827 if (Loc.isInvalid())
13828 return false;
13829
13830 while (Loc.isMacroID()) {
13831 if (SM.isMacroBodyExpansion(Loc))
13832 return true;
13833 Loc = SM.getImmediateMacroCallerLoc(Loc);
13834 }
13835
13836 return false;
13837}
13838
13841 bool IsEqual, SourceRange Range) {
13842 if (!E)
13843 return;
13844
13845 // Don't warn inside macros.
13846 if (E->getExprLoc().isMacroID()) {
13848 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13849 IsInAnyMacroBody(SM, Range.getBegin()))
13850 return;
13851 }
13852 E = E->IgnoreImpCasts();
13853
13854 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13855
13856 if (isa<CXXThisExpr>(E)) {
13857 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13858 : diag::warn_this_bool_conversion;
13859 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13860 return;
13861 }
13862
13863 bool IsAddressOf = false;
13864
13865 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
13866 if (UO->getOpcode() != UO_AddrOf)
13867 return;
13868 IsAddressOf = true;
13869 E = UO->getSubExpr();
13870 }
13871
13872 if (IsAddressOf) {
13873 unsigned DiagID = IsCompare
13874 ? diag::warn_address_of_reference_null_compare
13875 : diag::warn_address_of_reference_bool_conversion;
13876 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13877 << IsEqual;
13878 if (CheckForReference(*this, E, PD)) {
13879 return;
13880 }
13881 }
13882
13883 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13884 bool IsParam = isa<NonNullAttr>(NonnullAttr);
13885 std::string Str;
13886 llvm::raw_string_ostream S(Str);
13887 E->printPretty(S, nullptr, getPrintingPolicy());
13888 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13889 : diag::warn_cast_nonnull_to_bool;
13890 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13891 << E->getSourceRange() << Range << IsEqual;
13892 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13893 };
13894
13895 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13896 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13897 if (auto *Callee = Call->getDirectCallee()) {
13898 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13899 ComplainAboutNonnullParamOrCall(A);
13900 return;
13901 }
13902 }
13903 }
13904
13905 // Complain if we are converting a lambda expression to a boolean value
13906 // outside of instantiation.
13907 if (!inTemplateInstantiation()) {
13908 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
13909 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
13910 MRecordDecl && MRecordDecl->isLambda()) {
13911 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
13912 << /*LambdaPointerConversionOperatorType=*/3
13913 << MRecordDecl->getSourceRange() << Range << IsEqual;
13914 return;
13915 }
13916 }
13917 }
13918
13919 // Expect to find a single Decl. Skip anything more complicated.
13920 ValueDecl *D = nullptr;
13921 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13922 D = R->getDecl();
13923 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13924 D = M->getMemberDecl();
13925 }
13926
13927 // Weak Decls can be null.
13928 if (!D || D->isWeak())
13929 return;
13930
13931 // Check for parameter decl with nonnull attribute
13932 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13933 if (getCurFunction() &&
13934 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13935 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13936 ComplainAboutNonnullParamOrCall(A);
13937 return;
13938 }
13939
13940 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13941 // Skip function template not specialized yet.
13943 return;
13944 auto ParamIter = llvm::find(FD->parameters(), PV);
13945 assert(ParamIter != FD->param_end());
13946 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13947
13948 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13949 if (!NonNull->args_size()) {
13950 ComplainAboutNonnullParamOrCall(NonNull);
13951 return;
13952 }
13953
13954 for (const ParamIdx &ArgNo : NonNull->args()) {
13955 if (ArgNo.getASTIndex() == ParamNo) {
13956 ComplainAboutNonnullParamOrCall(NonNull);
13957 return;
13958 }
13959 }
13960 }
13961 }
13962 }
13963 }
13964
13965 QualType T = D->getType();
13966 const bool IsArray = T->isArrayType();
13967 const bool IsFunction = T->isFunctionType();
13968
13969 // Address of function is used to silence the function warning.
13970 if (IsAddressOf && IsFunction) {
13971 return;
13972 }
13973
13974 // Found nothing.
13975 if (!IsAddressOf && !IsFunction && !IsArray)
13976 return;
13977
13978 // Pretty print the expression for the diagnostic.
13979 std::string Str;
13980 llvm::raw_string_ostream S(Str);
13981 E->printPretty(S, nullptr, getPrintingPolicy());
13982
13983 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13984 : diag::warn_impcast_pointer_to_bool;
13985 enum {
13986 AddressOf,
13987 FunctionPointer,
13988 ArrayPointer
13989 } DiagType;
13990 if (IsAddressOf)
13991 DiagType = AddressOf;
13992 else if (IsFunction)
13993 DiagType = FunctionPointer;
13994 else if (IsArray)
13995 DiagType = ArrayPointer;
13996 else
13997 llvm_unreachable("Could not determine diagnostic.");
13998 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13999 << Range << IsEqual;
14000
14001 if (!IsFunction)
14002 return;
14003
14004 // Suggest '&' to silence the function warning.
14005 Diag(E->getExprLoc(), diag::note_function_warning_silence)
14007
14008 // Check to see if '()' fixit should be emitted.
14009 QualType ReturnType;
14010 UnresolvedSet<4> NonTemplateOverloads;
14011 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14012 if (ReturnType.isNull())
14013 return;
14014
14015 if (IsCompare) {
14016 // There are two cases here. If there is null constant, the only suggest
14017 // for a pointer return type. If the null is 0, then suggest if the return
14018 // type is a pointer or an integer type.
14019 if (!ReturnType->isPointerType()) {
14020 if (NullKind == Expr::NPCK_ZeroExpression ||
14021 NullKind == Expr::NPCK_ZeroLiteral) {
14022 if (!ReturnType->isIntegerType())
14023 return;
14024 } else {
14025 return;
14026 }
14027 }
14028 } else { // !IsCompare
14029 // For function to bool, only suggest if the function pointer has bool
14030 // return type.
14031 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14032 return;
14033 }
14034 Diag(E->getExprLoc(), diag::note_function_to_function_call)
14036}
14037
14039 SourceLocation CC) {
14040 QualType Source = E->getType();
14041 QualType Target = T;
14042
14043 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14044 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14045 // Overflow behavior type is being stripped - issue warning
14046 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14047 Target->isUnsignedIntegerType()) {
14048 // For unsigned wrap to unsigned conversions, use pedantic version
14049 unsigned DiagId =
14051 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14052 : diag::warn_impcast_overflow_behavior_pedantic;
14053 DiagnoseImpCast(*this, E, T, CC, DiagId);
14054 } else {
14055 unsigned DiagId = InOverflowBehaviorAssignmentContext
14056 ? diag::warn_impcast_overflow_behavior_assignment
14057 : diag::warn_impcast_overflow_behavior;
14058 DiagnoseImpCast(*this, E, T, CC, DiagId);
14059 }
14060 }
14061 }
14062
14063 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14064 if (TargetOBT->isWrapKind()) {
14065 return true;
14066 }
14067 }
14068
14069 return false;
14070}
14071
14072void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14073 // Don't diagnose in unevaluated contexts.
14075 return;
14076
14077 // Don't diagnose for value- or type-dependent expressions.
14078 if (E->isTypeDependent() || E->isValueDependent())
14079 return;
14080
14081 // Check for array bounds violations in cases where the check isn't triggered
14082 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14083 // ArraySubscriptExpr is on the RHS of a variable initialization.
14084 CheckArrayAccess(E);
14085
14086 // This is not the right CC for (e.g.) a variable initialization.
14087 AnalyzeImplicitConversions(*this, E, CC);
14088}
14089
14090void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14091 ::CheckBoolLikeConversion(*this, E, CC);
14092}
14093
14094void Sema::CheckForIntOverflow (const Expr *E) {
14095 // Use a work list to deal with nested struct initializers.
14096 SmallVector<const Expr *, 2> Exprs(1, E);
14097
14098 do {
14099 const Expr *OriginalE = Exprs.pop_back_val();
14100 const Expr *E = OriginalE->IgnoreParenCasts();
14101
14104 continue;
14105 }
14106
14107 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
14108 Exprs.append(InitList->inits().begin(), InitList->inits().end());
14109 else if (isa<ObjCBoxedExpr>(OriginalE))
14111 else if (const auto *Call = dyn_cast<CallExpr>(E))
14112 Exprs.append(Call->arg_begin(), Call->arg_end());
14113 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
14114 Exprs.append(Message->arg_begin(), Message->arg_end());
14115 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
14116 Exprs.append(Construct->arg_begin(), Construct->arg_end());
14117 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
14118 Exprs.push_back(Temporary->getSubExpr());
14119 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
14120 Exprs.push_back(Array->getIdx());
14121 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
14122 Exprs.push_back(Compound->getInitializer());
14123 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
14124 New && New->isArray()) {
14125 if (auto ArraySize = New->getArraySize())
14126 Exprs.push_back(*ArraySize);
14127 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
14128 Exprs.push_back(MTE->getSubExpr());
14129 } while (!Exprs.empty());
14130}
14131
14132namespace {
14133
14134/// Visitor for expressions which looks for unsequenced operations on the
14135/// same object.
14136class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14137 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14138
14139 /// A tree of sequenced regions within an expression. Two regions are
14140 /// unsequenced if one is an ancestor or a descendent of the other. When we
14141 /// finish processing an expression with sequencing, such as a comma
14142 /// expression, we fold its tree nodes into its parent, since they are
14143 /// unsequenced with respect to nodes we will visit later.
14144 class SequenceTree {
14145 struct Value {
14146 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14147 unsigned Parent : 31;
14148 LLVM_PREFERRED_TYPE(bool)
14149 unsigned Merged : 1;
14150 };
14151 SmallVector<Value, 8> Values;
14152
14153 public:
14154 /// A region within an expression which may be sequenced with respect
14155 /// to some other region.
14156 class Seq {
14157 friend class SequenceTree;
14158
14159 unsigned Index;
14160
14161 explicit Seq(unsigned N) : Index(N) {}
14162
14163 public:
14164 Seq() : Index(0) {}
14165 };
14166
14167 SequenceTree() { Values.push_back(Value(0)); }
14168 Seq root() const { return Seq(0); }
14169
14170 /// Create a new sequence of operations, which is an unsequenced
14171 /// subset of \p Parent. This sequence of operations is sequenced with
14172 /// respect to other children of \p Parent.
14173 Seq allocate(Seq Parent) {
14174 Values.push_back(Value(Parent.Index));
14175 return Seq(Values.size() - 1);
14176 }
14177
14178 /// Merge a sequence of operations into its parent.
14179 void merge(Seq S) {
14180 Values[S.Index].Merged = true;
14181 }
14182
14183 /// Determine whether two operations are unsequenced. This operation
14184 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14185 /// should have been merged into its parent as appropriate.
14186 bool isUnsequenced(Seq Cur, Seq Old) {
14187 unsigned C = representative(Cur.Index);
14188 unsigned Target = representative(Old.Index);
14189 while (C >= Target) {
14190 if (C == Target)
14191 return true;
14192 C = Values[C].Parent;
14193 }
14194 return false;
14195 }
14196
14197 private:
14198 /// Pick a representative for a sequence.
14199 unsigned representative(unsigned K) {
14200 if (Values[K].Merged)
14201 // Perform path compression as we go.
14202 return Values[K].Parent = representative(Values[K].Parent);
14203 return K;
14204 }
14205 };
14206
14207 /// An object for which we can track unsequenced uses.
14208 using Object = const NamedDecl *;
14209
14210 /// Different flavors of object usage which we track. We only track the
14211 /// least-sequenced usage of each kind.
14212 enum UsageKind {
14213 /// A read of an object. Multiple unsequenced reads are OK.
14214 UK_Use,
14215
14216 /// A modification of an object which is sequenced before the value
14217 /// computation of the expression, such as ++n in C++.
14218 UK_ModAsValue,
14219
14220 /// A modification of an object which is not sequenced before the value
14221 /// computation of the expression, such as n++.
14222 UK_ModAsSideEffect,
14223
14224 UK_Count = UK_ModAsSideEffect + 1
14225 };
14226
14227 /// Bundle together a sequencing region and the expression corresponding
14228 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14229 struct Usage {
14230 const Expr *UsageExpr = nullptr;
14231 SequenceTree::Seq Seq;
14232
14233 Usage() = default;
14234 };
14235
14236 struct UsageInfo {
14237 Usage Uses[UK_Count];
14238
14239 /// Have we issued a diagnostic for this object already?
14240 bool Diagnosed = false;
14241
14242 UsageInfo();
14243 };
14244 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14245
14246 Sema &SemaRef;
14247
14248 /// Sequenced regions within the expression.
14249 SequenceTree Tree;
14250
14251 /// Declaration modifications and references which we have seen.
14252 UsageInfoMap UsageMap;
14253
14254 /// The region we are currently within.
14255 SequenceTree::Seq Region;
14256
14257 /// Filled in with declarations which were modified as a side-effect
14258 /// (that is, post-increment operations).
14259 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14260
14261 /// Expressions to check later. We defer checking these to reduce
14262 /// stack usage.
14263 SmallVectorImpl<const Expr *> &WorkList;
14264
14265 /// RAII object wrapping the visitation of a sequenced subexpression of an
14266 /// expression. At the end of this process, the side-effects of the evaluation
14267 /// become sequenced with respect to the value computation of the result, so
14268 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14269 /// UK_ModAsValue.
14270 struct SequencedSubexpression {
14271 SequencedSubexpression(SequenceChecker &Self)
14272 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14273 Self.ModAsSideEffect = &ModAsSideEffect;
14274 }
14275
14276 ~SequencedSubexpression() {
14277 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14278 // Add a new usage with usage kind UK_ModAsValue, and then restore
14279 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14280 // the previous one was empty).
14281 UsageInfo &UI = Self.UsageMap[M.first];
14282 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14283 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14284 SideEffectUsage = M.second;
14285 }
14286 Self.ModAsSideEffect = OldModAsSideEffect;
14287 }
14288
14289 SequenceChecker &Self;
14290 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14291 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14292 };
14293
14294 /// RAII object wrapping the visitation of a subexpression which we might
14295 /// choose to evaluate as a constant. If any subexpression is evaluated and
14296 /// found to be non-constant, this allows us to suppress the evaluation of
14297 /// the outer expression.
14298 class EvaluationTracker {
14299 public:
14300 EvaluationTracker(SequenceChecker &Self)
14301 : Self(Self), Prev(Self.EvalTracker) {
14302 Self.EvalTracker = this;
14303 }
14304
14305 ~EvaluationTracker() {
14306 Self.EvalTracker = Prev;
14307 if (Prev)
14308 Prev->EvalOK &= EvalOK;
14309 }
14310
14311 bool evaluate(const Expr *E, bool &Result) {
14312 if (!EvalOK || E->isValueDependent())
14313 return false;
14314 EvalOK = E->EvaluateAsBooleanCondition(
14315 Result, Self.SemaRef.Context,
14316 Self.SemaRef.isConstantEvaluatedContext());
14317 return EvalOK;
14318 }
14319
14320 private:
14321 SequenceChecker &Self;
14322 EvaluationTracker *Prev;
14323 bool EvalOK = true;
14324 } *EvalTracker = nullptr;
14325
14326 /// Find the object which is produced by the specified expression,
14327 /// if any.
14328 Object getObject(const Expr *E, bool Mod) const {
14329 E = E->IgnoreParenCasts();
14330 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14331 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14332 return getObject(UO->getSubExpr(), Mod);
14333 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14334 if (BO->getOpcode() == BO_Comma)
14335 return getObject(BO->getRHS(), Mod);
14336 if (Mod && BO->isAssignmentOp())
14337 return getObject(BO->getLHS(), Mod);
14338 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14339 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14340 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14341 return ME->getMemberDecl();
14342 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14343 // FIXME: If this is a reference, map through to its value.
14344 return DRE->getDecl();
14345 return nullptr;
14346 }
14347
14348 /// Note that an object \p O was modified or used by an expression
14349 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14350 /// the object \p O as obtained via the \p UsageMap.
14351 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14352 // Get the old usage for the given object and usage kind.
14353 Usage &U = UI.Uses[UK];
14354 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14355 // If we have a modification as side effect and are in a sequenced
14356 // subexpression, save the old Usage so that we can restore it later
14357 // in SequencedSubexpression::~SequencedSubexpression.
14358 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14359 ModAsSideEffect->push_back(std::make_pair(O, U));
14360 // Then record the new usage with the current sequencing region.
14361 U.UsageExpr = UsageExpr;
14362 U.Seq = Region;
14363 }
14364 }
14365
14366 /// Check whether a modification or use of an object \p O in an expression
14367 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14368 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14369 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14370 /// usage and false we are checking for a mod-use unsequenced usage.
14371 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14372 UsageKind OtherKind, bool IsModMod) {
14373 if (UI.Diagnosed)
14374 return;
14375
14376 const Usage &U = UI.Uses[OtherKind];
14377 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14378 return;
14379
14380 const Expr *Mod = U.UsageExpr;
14381 const Expr *ModOrUse = UsageExpr;
14382 if (OtherKind == UK_Use)
14383 std::swap(Mod, ModOrUse);
14384
14385 SemaRef.DiagRuntimeBehavior(
14386 Mod->getExprLoc(), {Mod, ModOrUse},
14387 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14388 : diag::warn_unsequenced_mod_use)
14389 << O << SourceRange(ModOrUse->getExprLoc()));
14390 UI.Diagnosed = true;
14391 }
14392
14393 // A note on note{Pre, Post}{Use, Mod}:
14394 //
14395 // (It helps to follow the algorithm with an expression such as
14396 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14397 // operations before C++17 and both are well-defined in C++17).
14398 //
14399 // When visiting a node which uses/modify an object we first call notePreUse
14400 // or notePreMod before visiting its sub-expression(s). At this point the
14401 // children of the current node have not yet been visited and so the eventual
14402 // uses/modifications resulting from the children of the current node have not
14403 // been recorded yet.
14404 //
14405 // We then visit the children of the current node. After that notePostUse or
14406 // notePostMod is called. These will 1) detect an unsequenced modification
14407 // as side effect (as in "k++ + k") and 2) add a new usage with the
14408 // appropriate usage kind.
14409 //
14410 // We also have to be careful that some operation sequences modification as
14411 // side effect as well (for example: || or ,). To account for this we wrap
14412 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14413 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14414 // which record usages which are modifications as side effect, and then
14415 // downgrade them (or more accurately restore the previous usage which was a
14416 // modification as side effect) when exiting the scope of the sequenced
14417 // subexpression.
14418
14419 void notePreUse(Object O, const Expr *UseExpr) {
14420 UsageInfo &UI = UsageMap[O];
14421 // Uses conflict with other modifications.
14422 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14423 }
14424
14425 void notePostUse(Object O, const Expr *UseExpr) {
14426 UsageInfo &UI = UsageMap[O];
14427 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14428 /*IsModMod=*/false);
14429 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14430 }
14431
14432 void notePreMod(Object O, const Expr *ModExpr) {
14433 UsageInfo &UI = UsageMap[O];
14434 // Modifications conflict with other modifications and with uses.
14435 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14436 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14437 }
14438
14439 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14440 UsageInfo &UI = UsageMap[O];
14441 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14442 /*IsModMod=*/true);
14443 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14444 }
14445
14446public:
14447 SequenceChecker(Sema &S, const Expr *E,
14448 SmallVectorImpl<const Expr *> &WorkList)
14449 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14450 Visit(E);
14451 // Silence a -Wunused-private-field since WorkList is now unused.
14452 // TODO: Evaluate if it can be used, and if not remove it.
14453 (void)this->WorkList;
14454 }
14455
14456 void VisitStmt(const Stmt *S) {
14457 // Skip all statements which aren't expressions for now.
14458 }
14459
14460 void VisitExpr(const Expr *E) {
14461 // By default, just recurse to evaluated subexpressions.
14462 Base::VisitStmt(E);
14463 }
14464
14465 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14466 for (auto *Sub : CSE->children()) {
14467 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
14468 if (!ChildExpr)
14469 continue;
14470
14471 if (ChildExpr == CSE->getOperand())
14472 // Do not recurse over a CoroutineSuspendExpr's operand.
14473 // The operand is also a subexpression of getCommonExpr(), and
14474 // recursing into it directly could confuse object management
14475 // for the sake of sequence tracking.
14476 continue;
14477
14478 Visit(Sub);
14479 }
14480 }
14481
14482 void VisitCastExpr(const CastExpr *E) {
14483 Object O = Object();
14484 if (E->getCastKind() == CK_LValueToRValue)
14485 O = getObject(E->getSubExpr(), false);
14486
14487 if (O)
14488 notePreUse(O, E);
14489 VisitExpr(E);
14490 if (O)
14491 notePostUse(O, E);
14492 }
14493
14494 void VisitSequencedExpressions(const Expr *SequencedBefore,
14495 const Expr *SequencedAfter) {
14496 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14497 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14498 SequenceTree::Seq OldRegion = Region;
14499
14500 {
14501 SequencedSubexpression SeqBefore(*this);
14502 Region = BeforeRegion;
14503 Visit(SequencedBefore);
14504 }
14505
14506 Region = AfterRegion;
14507 Visit(SequencedAfter);
14508
14509 Region = OldRegion;
14510
14511 Tree.merge(BeforeRegion);
14512 Tree.merge(AfterRegion);
14513 }
14514
14515 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14516 // C++17 [expr.sub]p1:
14517 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14518 // expression E1 is sequenced before the expression E2.
14519 if (SemaRef.getLangOpts().CPlusPlus17)
14520 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14521 else {
14522 Visit(ASE->getLHS());
14523 Visit(ASE->getRHS());
14524 }
14525 }
14526
14527 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14528 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14529 void VisitBinPtrMem(const BinaryOperator *BO) {
14530 // C++17 [expr.mptr.oper]p4:
14531 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14532 // the expression E1 is sequenced before the expression E2.
14533 if (SemaRef.getLangOpts().CPlusPlus17)
14534 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14535 else {
14536 Visit(BO->getLHS());
14537 Visit(BO->getRHS());
14538 }
14539 }
14540
14541 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14542 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14543 void VisitBinShlShr(const BinaryOperator *BO) {
14544 // C++17 [expr.shift]p4:
14545 // The expression E1 is sequenced before the expression E2.
14546 if (SemaRef.getLangOpts().CPlusPlus17)
14547 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14548 else {
14549 Visit(BO->getLHS());
14550 Visit(BO->getRHS());
14551 }
14552 }
14553
14554 void VisitBinComma(const BinaryOperator *BO) {
14555 // C++11 [expr.comma]p1:
14556 // Every value computation and side effect associated with the left
14557 // expression is sequenced before every value computation and side
14558 // effect associated with the right expression.
14559 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14560 }
14561
14562 void VisitBinAssign(const BinaryOperator *BO) {
14563 SequenceTree::Seq RHSRegion;
14564 SequenceTree::Seq LHSRegion;
14565 if (SemaRef.getLangOpts().CPlusPlus17) {
14566 RHSRegion = Tree.allocate(Region);
14567 LHSRegion = Tree.allocate(Region);
14568 } else {
14569 RHSRegion = Region;
14570 LHSRegion = Region;
14571 }
14572 SequenceTree::Seq OldRegion = Region;
14573
14574 // C++11 [expr.ass]p1:
14575 // [...] the assignment is sequenced after the value computation
14576 // of the right and left operands, [...]
14577 //
14578 // so check it before inspecting the operands and update the
14579 // map afterwards.
14580 Object O = getObject(BO->getLHS(), /*Mod=*/true);
14581 if (O)
14582 notePreMod(O, BO);
14583
14584 if (SemaRef.getLangOpts().CPlusPlus17) {
14585 // C++17 [expr.ass]p1:
14586 // [...] The right operand is sequenced before the left operand. [...]
14587 {
14588 SequencedSubexpression SeqBefore(*this);
14589 Region = RHSRegion;
14590 Visit(BO->getRHS());
14591 }
14592
14593 Region = LHSRegion;
14594 Visit(BO->getLHS());
14595
14596 if (O && isa<CompoundAssignOperator>(BO))
14597 notePostUse(O, BO);
14598
14599 } else {
14600 // C++11 does not specify any sequencing between the LHS and RHS.
14601 Region = LHSRegion;
14602 Visit(BO->getLHS());
14603
14604 if (O && isa<CompoundAssignOperator>(BO))
14605 notePostUse(O, BO);
14606
14607 Region = RHSRegion;
14608 Visit(BO->getRHS());
14609 }
14610
14611 // C++11 [expr.ass]p1:
14612 // the assignment is sequenced [...] before the value computation of the
14613 // assignment expression.
14614 // C11 6.5.16/3 has no such rule.
14615 Region = OldRegion;
14616 if (O)
14617 notePostMod(O, BO,
14618 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14619 : UK_ModAsSideEffect);
14620 if (SemaRef.getLangOpts().CPlusPlus17) {
14621 Tree.merge(RHSRegion);
14622 Tree.merge(LHSRegion);
14623 }
14624 }
14625
14626 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14627 VisitBinAssign(CAO);
14628 }
14629
14630 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14631 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14632 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14633 Object O = getObject(UO->getSubExpr(), true);
14634 if (!O)
14635 return VisitExpr(UO);
14636
14637 notePreMod(O, UO);
14638 Visit(UO->getSubExpr());
14639 // C++11 [expr.pre.incr]p1:
14640 // the expression ++x is equivalent to x+=1
14641 notePostMod(O, UO,
14642 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14643 : UK_ModAsSideEffect);
14644 }
14645
14646 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14647 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14648 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14649 Object O = getObject(UO->getSubExpr(), true);
14650 if (!O)
14651 return VisitExpr(UO);
14652
14653 notePreMod(O, UO);
14654 Visit(UO->getSubExpr());
14655 notePostMod(O, UO, UK_ModAsSideEffect);
14656 }
14657
14658 void VisitBinLOr(const BinaryOperator *BO) {
14659 // C++11 [expr.log.or]p2:
14660 // If the second expression is evaluated, every value computation and
14661 // side effect associated with the first expression is sequenced before
14662 // every value computation and side effect associated with the
14663 // second expression.
14664 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14665 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14666 SequenceTree::Seq OldRegion = Region;
14667
14668 EvaluationTracker Eval(*this);
14669 {
14670 SequencedSubexpression Sequenced(*this);
14671 Region = LHSRegion;
14672 Visit(BO->getLHS());
14673 }
14674
14675 // C++11 [expr.log.or]p1:
14676 // [...] the second operand is not evaluated if the first operand
14677 // evaluates to true.
14678 bool EvalResult = false;
14679 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14680 bool ShouldVisitRHS = !EvalOK || !EvalResult;
14681 if (ShouldVisitRHS) {
14682 Region = RHSRegion;
14683 Visit(BO->getRHS());
14684 }
14685
14686 Region = OldRegion;
14687 Tree.merge(LHSRegion);
14688 Tree.merge(RHSRegion);
14689 }
14690
14691 void VisitBinLAnd(const BinaryOperator *BO) {
14692 // C++11 [expr.log.and]p2:
14693 // If the second expression is evaluated, every value computation and
14694 // side effect associated with the first expression is sequenced before
14695 // every value computation and side effect associated with the
14696 // second expression.
14697 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14698 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14699 SequenceTree::Seq OldRegion = Region;
14700
14701 EvaluationTracker Eval(*this);
14702 {
14703 SequencedSubexpression Sequenced(*this);
14704 Region = LHSRegion;
14705 Visit(BO->getLHS());
14706 }
14707
14708 // C++11 [expr.log.and]p1:
14709 // [...] the second operand is not evaluated if the first operand is false.
14710 bool EvalResult = false;
14711 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14712 bool ShouldVisitRHS = !EvalOK || EvalResult;
14713 if (ShouldVisitRHS) {
14714 Region = RHSRegion;
14715 Visit(BO->getRHS());
14716 }
14717
14718 Region = OldRegion;
14719 Tree.merge(LHSRegion);
14720 Tree.merge(RHSRegion);
14721 }
14722
14723 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14724 // C++11 [expr.cond]p1:
14725 // [...] Every value computation and side effect associated with the first
14726 // expression is sequenced before every value computation and side effect
14727 // associated with the second or third expression.
14728 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14729
14730 // No sequencing is specified between the true and false expression.
14731 // However since exactly one of both is going to be evaluated we can
14732 // consider them to be sequenced. This is needed to avoid warning on
14733 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14734 // both the true and false expressions because we can't evaluate x.
14735 // This will still allow us to detect an expression like (pre C++17)
14736 // "(x ? y += 1 : y += 2) = y".
14737 //
14738 // We don't wrap the visitation of the true and false expression with
14739 // SequencedSubexpression because we don't want to downgrade modifications
14740 // as side effect in the true and false expressions after the visition
14741 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14742 // not warn between the two "y++", but we should warn between the "y++"
14743 // and the "y".
14744 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14745 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14746 SequenceTree::Seq OldRegion = Region;
14747
14748 EvaluationTracker Eval(*this);
14749 {
14750 SequencedSubexpression Sequenced(*this);
14751 Region = ConditionRegion;
14752 Visit(CO->getCond());
14753 }
14754
14755 // C++11 [expr.cond]p1:
14756 // [...] The first expression is contextually converted to bool (Clause 4).
14757 // It is evaluated and if it is true, the result of the conditional
14758 // expression is the value of the second expression, otherwise that of the
14759 // third expression. Only one of the second and third expressions is
14760 // evaluated. [...]
14761 bool EvalResult = false;
14762 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14763 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
14764 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
14765 if (ShouldVisitTrueExpr) {
14766 Region = TrueRegion;
14767 Visit(CO->getTrueExpr());
14768 }
14769 if (ShouldVisitFalseExpr) {
14770 Region = FalseRegion;
14771 Visit(CO->getFalseExpr());
14772 }
14773
14774 Region = OldRegion;
14775 Tree.merge(ConditionRegion);
14776 Tree.merge(TrueRegion);
14777 Tree.merge(FalseRegion);
14778 }
14779
14780 void VisitCallExpr(const CallExpr *CE) {
14781 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14782
14783 if (CE->isUnevaluatedBuiltinCall(Context))
14784 return;
14785
14786 // C++11 [intro.execution]p15:
14787 // When calling a function [...], every value computation and side effect
14788 // associated with any argument expression, or with the postfix expression
14789 // designating the called function, is sequenced before execution of every
14790 // expression or statement in the body of the function [and thus before
14791 // the value computation of its result].
14792 SequencedSubexpression Sequenced(*this);
14793 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14794 // C++17 [expr.call]p5
14795 // The postfix-expression is sequenced before each expression in the
14796 // expression-list and any default argument. [...]
14797 SequenceTree::Seq CalleeRegion;
14798 SequenceTree::Seq OtherRegion;
14799 if (SemaRef.getLangOpts().CPlusPlus17) {
14800 CalleeRegion = Tree.allocate(Region);
14801 OtherRegion = Tree.allocate(Region);
14802 } else {
14803 CalleeRegion = Region;
14804 OtherRegion = Region;
14805 }
14806 SequenceTree::Seq OldRegion = Region;
14807
14808 // Visit the callee expression first.
14809 Region = CalleeRegion;
14810 if (SemaRef.getLangOpts().CPlusPlus17) {
14811 SequencedSubexpression Sequenced(*this);
14812 Visit(CE->getCallee());
14813 } else {
14814 Visit(CE->getCallee());
14815 }
14816
14817 // Then visit the argument expressions.
14818 Region = OtherRegion;
14819 for (const Expr *Argument : CE->arguments())
14820 Visit(Argument);
14821
14822 Region = OldRegion;
14823 if (SemaRef.getLangOpts().CPlusPlus17) {
14824 Tree.merge(CalleeRegion);
14825 Tree.merge(OtherRegion);
14826 }
14827 });
14828 }
14829
14830 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14831 // C++17 [over.match.oper]p2:
14832 // [...] the operator notation is first transformed to the equivalent
14833 // function-call notation as summarized in Table 12 (where @ denotes one
14834 // of the operators covered in the specified subclause). However, the
14835 // operands are sequenced in the order prescribed for the built-in
14836 // operator (Clause 8).
14837 //
14838 // From the above only overloaded binary operators and overloaded call
14839 // operators have sequencing rules in C++17 that we need to handle
14840 // separately.
14841 if (!SemaRef.getLangOpts().CPlusPlus17 ||
14842 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14843 return VisitCallExpr(CXXOCE);
14844
14845 enum {
14846 NoSequencing,
14847 LHSBeforeRHS,
14848 RHSBeforeLHS,
14849 LHSBeforeRest
14850 } SequencingKind;
14851 switch (CXXOCE->getOperator()) {
14852 case OO_Equal:
14853 case OO_PlusEqual:
14854 case OO_MinusEqual:
14855 case OO_StarEqual:
14856 case OO_SlashEqual:
14857 case OO_PercentEqual:
14858 case OO_CaretEqual:
14859 case OO_AmpEqual:
14860 case OO_PipeEqual:
14861 case OO_LessLessEqual:
14862 case OO_GreaterGreaterEqual:
14863 SequencingKind = RHSBeforeLHS;
14864 break;
14865
14866 case OO_LessLess:
14867 case OO_GreaterGreater:
14868 case OO_AmpAmp:
14869 case OO_PipePipe:
14870 case OO_Comma:
14871 case OO_ArrowStar:
14872 case OO_Subscript:
14873 SequencingKind = LHSBeforeRHS;
14874 break;
14875
14876 case OO_Call:
14877 SequencingKind = LHSBeforeRest;
14878 break;
14879
14880 default:
14881 SequencingKind = NoSequencing;
14882 break;
14883 }
14884
14885 if (SequencingKind == NoSequencing)
14886 return VisitCallExpr(CXXOCE);
14887
14888 // This is a call, so all subexpressions are sequenced before the result.
14889 SequencedSubexpression Sequenced(*this);
14890
14891 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14892 assert(SemaRef.getLangOpts().CPlusPlus17 &&
14893 "Should only get there with C++17 and above!");
14894 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14895 "Should only get there with an overloaded binary operator"
14896 " or an overloaded call operator!");
14897
14898 if (SequencingKind == LHSBeforeRest) {
14899 assert(CXXOCE->getOperator() == OO_Call &&
14900 "We should only have an overloaded call operator here!");
14901
14902 // This is very similar to VisitCallExpr, except that we only have the
14903 // C++17 case. The postfix-expression is the first argument of the
14904 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14905 // are in the following arguments.
14906 //
14907 // Note that we intentionally do not visit the callee expression since
14908 // it is just a decayed reference to a function.
14909 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14910 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14911 SequenceTree::Seq OldRegion = Region;
14912
14913 assert(CXXOCE->getNumArgs() >= 1 &&
14914 "An overloaded call operator must have at least one argument"
14915 " for the postfix-expression!");
14916 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14917 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14918 CXXOCE->getNumArgs() - 1);
14919
14920 // Visit the postfix-expression first.
14921 {
14922 Region = PostfixExprRegion;
14923 SequencedSubexpression Sequenced(*this);
14924 Visit(PostfixExpr);
14925 }
14926
14927 // Then visit the argument expressions.
14928 Region = ArgsRegion;
14929 for (const Expr *Arg : Args)
14930 Visit(Arg);
14931
14932 Region = OldRegion;
14933 Tree.merge(PostfixExprRegion);
14934 Tree.merge(ArgsRegion);
14935 } else {
14936 assert(CXXOCE->getNumArgs() == 2 &&
14937 "Should only have two arguments here!");
14938 assert((SequencingKind == LHSBeforeRHS ||
14939 SequencingKind == RHSBeforeLHS) &&
14940 "Unexpected sequencing kind!");
14941
14942 // We do not visit the callee expression since it is just a decayed
14943 // reference to a function.
14944 const Expr *E1 = CXXOCE->getArg(0);
14945 const Expr *E2 = CXXOCE->getArg(1);
14946 if (SequencingKind == RHSBeforeLHS)
14947 std::swap(E1, E2);
14948
14949 return VisitSequencedExpressions(E1, E2);
14950 }
14951 });
14952 }
14953
14954 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14955 // This is a call, so all subexpressions are sequenced before the result.
14956 SequencedSubexpression Sequenced(*this);
14957
14958 if (!CCE->isListInitialization())
14959 return VisitExpr(CCE);
14960
14961 // In C++11, list initializations are sequenced.
14962 SequenceExpressionsInOrder(
14963 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
14964 }
14965
14966 void VisitInitListExpr(const InitListExpr *ILE) {
14967 if (!SemaRef.getLangOpts().CPlusPlus11)
14968 return VisitExpr(ILE);
14969
14970 // In C++11, list initializations are sequenced.
14971 SequenceExpressionsInOrder(ILE->inits());
14972 }
14973
14974 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
14975 // C++20 parenthesized list initializations are sequenced. See C++20
14976 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
14977 SequenceExpressionsInOrder(PLIE->getInitExprs());
14978 }
14979
14980private:
14981 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
14983 SequenceTree::Seq Parent = Region;
14984 for (const Expr *E : ExpressionList) {
14985 if (!E)
14986 continue;
14987 Region = Tree.allocate(Parent);
14988 Elts.push_back(Region);
14989 Visit(E);
14990 }
14991
14992 // Forget that the initializers are sequenced.
14993 Region = Parent;
14994 for (unsigned I = 0; I < Elts.size(); ++I)
14995 Tree.merge(Elts[I]);
14996 }
14997};
14998
14999SequenceChecker::UsageInfo::UsageInfo() = default;
15000
15001} // namespace
15002
15003void Sema::CheckUnsequencedOperations(const Expr *E) {
15004 SmallVector<const Expr *, 8> WorkList;
15005 WorkList.push_back(E);
15006 while (!WorkList.empty()) {
15007 const Expr *Item = WorkList.pop_back_val();
15008 SequenceChecker(*this, Item, WorkList);
15009 }
15010}
15011
15012void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15013 bool IsConstexpr) {
15014 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15015 IsConstexpr || isa<ConstantExpr>(E));
15016 CheckImplicitConversions(E, CheckLoc);
15017 if (!E->isInstantiationDependent())
15018 CheckUnsequencedOperations(E);
15019 if (!IsConstexpr && !E->isValueDependent())
15020 CheckForIntOverflow(E);
15021}
15022
15023void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15024 FieldDecl *BitField,
15025 Expr *Init) {
15026 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
15027}
15028
15030 SourceLocation Loc) {
15031 if (!PType->isVariablyModifiedType())
15032 return;
15033 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
15034 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
15035 return;
15036 }
15037 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
15038 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
15039 return;
15040 }
15041 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
15042 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
15043 return;
15044 }
15045
15046 const ArrayType *AT = S.Context.getAsArrayType(PType);
15047 if (!AT)
15048 return;
15049
15052 return;
15053 }
15054
15055 S.Diag(Loc, diag::err_array_star_in_function_definition);
15056}
15057
15059 bool CheckParameterNames) {
15060 bool HasInvalidParm = false;
15061 for (ParmVarDecl *Param : Parameters) {
15062 assert(Param && "null in a parameter list");
15063 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15064 // function declarator that is part of a function definition of
15065 // that function shall not have incomplete type.
15066 //
15067 // C++23 [dcl.fct.def.general]/p2
15068 // The type of a parameter [...] for a function definition
15069 // shall not be a (possibly cv-qualified) class type that is incomplete
15070 // or abstract within the function body unless the function is deleted.
15071 if (!Param->isInvalidDecl() &&
15072 (RequireCompleteType(Param->getLocation(), Param->getType(),
15073 diag::err_typecheck_decl_incomplete_type) ||
15074 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
15075 diag::err_abstract_type_in_decl,
15077 Param->setInvalidDecl();
15078 HasInvalidParm = true;
15079 }
15080
15081 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15082 // declaration of each parameter shall include an identifier.
15083 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15084 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15085 // Diagnose this as an extension in C17 and earlier.
15086 if (!getLangOpts().C23)
15087 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
15088 }
15089
15090 // C99 6.7.5.3p12:
15091 // If the function declarator is not part of a definition of that
15092 // function, parameters may have incomplete type and may use the [*]
15093 // notation in their sequences of declarator specifiers to specify
15094 // variable length array types.
15095 QualType PType = Param->getOriginalType();
15096 // FIXME: This diagnostic should point the '[*]' if source-location
15097 // information is added for it.
15098 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15099
15100 // If the parameter is a c++ class type and it has to be destructed in the
15101 // callee function, declare the destructor so that it can be called by the
15102 // callee function. Do not perform any direct access check on the dtor here.
15103 if (!Param->isInvalidDecl()) {
15104 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15105 if (!ClassDecl->isInvalidDecl() &&
15106 !ClassDecl->hasIrrelevantDestructor() &&
15107 !ClassDecl->isDependentContext() &&
15108 ClassDecl->isParamDestroyedInCallee()) {
15110 MarkFunctionReferenced(Param->getLocation(), Destructor);
15111 DiagnoseUseOfDecl(Destructor, Param->getLocation());
15112 }
15113 }
15114 }
15115
15116 // Parameters with the pass_object_size attribute only need to be marked
15117 // constant at function definitions. Because we lack information about
15118 // whether we're on a declaration or definition when we're instantiating the
15119 // attribute, we need to check for constness here.
15120 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15121 if (!Param->getType().isConstQualified())
15122 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15123 << Attr->getSpelling() << 1;
15124
15125 // Check for parameter names shadowing fields from the class.
15126 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15127 // The owning context for the parameter should be the function, but we
15128 // want to see if this function's declaration context is a record.
15129 DeclContext *DC = Param->getDeclContext();
15130 if (DC && DC->isFunctionOrMethod()) {
15131 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15132 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15133 RD, /*DeclIsField*/ false);
15134 }
15135 }
15136
15137 if (!Param->isInvalidDecl() &&
15138 Param->getOriginalType()->isWebAssemblyTableType()) {
15139 Param->setInvalidDecl();
15140 HasInvalidParm = true;
15141 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
15142 }
15143 }
15144
15145 return HasInvalidParm;
15146}
15147
15148std::optional<std::pair<
15150 *E,
15152 &Ctx);
15153
15154/// Compute the alignment and offset of the base class object given the
15155/// derived-to-base cast expression and the alignment and offset of the derived
15156/// class object.
15157static std::pair<CharUnits, CharUnits>
15159 CharUnits BaseAlignment, CharUnits Offset,
15160 ASTContext &Ctx) {
15161 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15162 ++PathI) {
15163 const CXXBaseSpecifier *Base = *PathI;
15164 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15165 if (Base->isVirtual()) {
15166 // The complete object may have a lower alignment than the non-virtual
15167 // alignment of the base, in which case the base may be misaligned. Choose
15168 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15169 // conservative lower bound of the complete object alignment.
15170 CharUnits NonVirtualAlignment =
15172 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15173 Offset = CharUnits::Zero();
15174 } else {
15175 const ASTRecordLayout &RL =
15176 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15177 Offset += RL.getBaseClassOffset(BaseDecl);
15178 }
15179 DerivedType = Base->getType();
15180 }
15181
15182 return std::make_pair(BaseAlignment, Offset);
15183}
15184
15185/// Compute the alignment and offset of a binary additive operator.
15186static std::optional<std::pair<CharUnits, CharUnits>>
15188 bool IsSub, ASTContext &Ctx) {
15189 QualType PointeeType = PtrE->getType()->getPointeeType();
15190
15191 if (!PointeeType->isConstantSizeType())
15192 return std::nullopt;
15193
15194 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15195
15196 if (!P)
15197 return std::nullopt;
15198
15199 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15200 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15201 CharUnits Offset = EltSize * IdxRes->getExtValue();
15202 if (IsSub)
15203 Offset = -Offset;
15204 return std::make_pair(P->first, P->second + Offset);
15205 }
15206
15207 // If the integer expression isn't a constant expression, compute the lower
15208 // bound of the alignment using the alignment and offset of the pointer
15209 // expression and the element size.
15210 return std::make_pair(
15211 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15212 CharUnits::Zero());
15213}
15214
15215/// This helper function takes an lvalue expression and returns the alignment of
15216/// a VarDecl and a constant offset from the VarDecl.
15217std::optional<std::pair<
15218 CharUnits,
15220 ASTContext &Ctx) {
15221 E = E->IgnoreParens();
15222 switch (E->getStmtClass()) {
15223 default:
15224 break;
15225 case Stmt::CStyleCastExprClass:
15226 case Stmt::CXXStaticCastExprClass:
15227 case Stmt::ImplicitCastExprClass: {
15228 auto *CE = cast<CastExpr>(E);
15229 const Expr *From = CE->getSubExpr();
15230 switch (CE->getCastKind()) {
15231 default:
15232 break;
15233 case CK_NoOp:
15234 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15235 case CK_UncheckedDerivedToBase:
15236 case CK_DerivedToBase: {
15237 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15238 if (!P)
15239 break;
15240 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15241 P->second, Ctx);
15242 }
15243 }
15244 break;
15245 }
15246 case Stmt::ArraySubscriptExprClass: {
15247 auto *ASE = cast<ArraySubscriptExpr>(E);
15249 false, Ctx);
15250 }
15251 case Stmt::DeclRefExprClass: {
15252 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15253 // FIXME: If VD is captured by copy or is an escaping __block variable,
15254 // use the alignment of VD's type.
15255 if (!VD->getType()->isReferenceType()) {
15256 // Dependent alignment cannot be resolved -> bail out.
15257 if (VD->hasDependentAlignment())
15258 break;
15259 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15260 }
15261 if (VD->hasInit())
15262 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15263 }
15264 break;
15265 }
15266 case Stmt::MemberExprClass: {
15267 auto *ME = cast<MemberExpr>(E);
15268 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15269 if (!FD || FD->getType()->isReferenceType() ||
15270 FD->getParent()->isInvalidDecl())
15271 break;
15272 std::optional<std::pair<CharUnits, CharUnits>> P;
15273 if (ME->isArrow())
15274 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15275 else
15276 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15277 if (!P)
15278 break;
15279 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15280 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15281 return std::make_pair(P->first,
15282 P->second + CharUnits::fromQuantity(Offset));
15283 }
15284 case Stmt::UnaryOperatorClass: {
15285 auto *UO = cast<UnaryOperator>(E);
15286 switch (UO->getOpcode()) {
15287 default:
15288 break;
15289 case UO_Deref:
15291 }
15292 break;
15293 }
15294 case Stmt::BinaryOperatorClass: {
15295 auto *BO = cast<BinaryOperator>(E);
15296 auto Opcode = BO->getOpcode();
15297 switch (Opcode) {
15298 default:
15299 break;
15300 case BO_Comma:
15302 }
15303 break;
15304 }
15305 }
15306 return std::nullopt;
15307}
15308
15309/// This helper function takes a pointer expression and returns the alignment of
15310/// a VarDecl and a constant offset from the VarDecl.
15311std::optional<std::pair<
15313 *E,
15315 &Ctx) {
15316 E = E->IgnoreParens();
15317 switch (E->getStmtClass()) {
15318 default:
15319 break;
15320 case Stmt::CStyleCastExprClass:
15321 case Stmt::CXXStaticCastExprClass:
15322 case Stmt::ImplicitCastExprClass: {
15323 auto *CE = cast<CastExpr>(E);
15324 const Expr *From = CE->getSubExpr();
15325 switch (CE->getCastKind()) {
15326 default:
15327 break;
15328 case CK_NoOp:
15329 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15330 case CK_ArrayToPointerDecay:
15331 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15332 case CK_UncheckedDerivedToBase:
15333 case CK_DerivedToBase: {
15334 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15335 if (!P)
15336 break;
15338 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15339 }
15340 }
15341 break;
15342 }
15343 case Stmt::CXXThisExprClass: {
15344 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15346 return std::make_pair(Alignment, CharUnits::Zero());
15347 }
15348 case Stmt::UnaryOperatorClass: {
15349 auto *UO = cast<UnaryOperator>(E);
15350 if (UO->getOpcode() == UO_AddrOf)
15352 break;
15353 }
15354 case Stmt::BinaryOperatorClass: {
15355 auto *BO = cast<BinaryOperator>(E);
15356 auto Opcode = BO->getOpcode();
15357 switch (Opcode) {
15358 default:
15359 break;
15360 case BO_Add:
15361 case BO_Sub: {
15362 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15363 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15364 std::swap(LHS, RHS);
15365 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15366 Ctx);
15367 }
15368 case BO_Comma:
15369 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15370 }
15371 break;
15372 }
15373 }
15374 return std::nullopt;
15375}
15376
15378 // See if we can compute the alignment of a VarDecl and an offset from it.
15379 std::optional<std::pair<CharUnits, CharUnits>> P =
15381
15382 if (P)
15383 return P->first.alignmentAtOffset(P->second);
15384
15385 // If that failed, return the type's alignment.
15387}
15388
15390 // This is actually a lot of work to potentially be doing on every
15391 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15392 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15393 return;
15394
15395 // Ignore dependent types.
15396 if (T->isDependentType() || Op->getType()->isDependentType())
15397 return;
15398
15399 // Require that the destination be a pointer type.
15400 const PointerType *DestPtr = T->getAs<PointerType>();
15401 if (!DestPtr) return;
15402
15403 // If the destination has alignment 1, we're done.
15404 QualType DestPointee = DestPtr->getPointeeType();
15405 if (DestPointee->isIncompleteType()) return;
15406 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15407 if (DestAlign.isOne()) return;
15408
15409 // Require that the source be a pointer type.
15410 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15411 if (!SrcPtr) return;
15412 QualType SrcPointee = SrcPtr->getPointeeType();
15413
15414 // Explicitly allow casts from cv void*. We already implicitly
15415 // allowed casts to cv void*, since they have alignment 1.
15416 // Also allow casts involving incomplete types, which implicitly
15417 // includes 'void'.
15418 if (SrcPointee->isIncompleteType()) return;
15419
15420 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15421
15422 if (SrcAlign >= DestAlign) return;
15423
15424 Diag(TRange.getBegin(), diag::warn_cast_align)
15425 << Op->getType() << T
15426 << static_cast<unsigned>(SrcAlign.getQuantity())
15427 << static_cast<unsigned>(DestAlign.getQuantity())
15428 << TRange << Op->getSourceRange();
15429}
15430
15431void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15432 const ArraySubscriptExpr *ASE,
15433 bool AllowOnePastEnd, bool IndexNegated) {
15434 // Already diagnosed by the constant evaluator.
15436 return;
15437
15438 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15439 if (IndexExpr->isValueDependent())
15440 return;
15441
15442 const Type *EffectiveType =
15444 BaseExpr = BaseExpr->IgnoreParenCasts();
15445 const ConstantArrayType *ArrayTy =
15446 Context.getAsConstantArrayType(BaseExpr->getType());
15447
15449 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15450
15451 const Type *BaseType =
15452 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15453 bool IsUnboundedArray =
15454 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15455 Context, StrictFlexArraysLevel,
15456 /*IgnoreTemplateOrMacroSubstitution=*/true);
15457 if (EffectiveType->isDependentType() ||
15458 (!IsUnboundedArray && BaseType->isDependentType()))
15459 return;
15460
15462 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15463 return;
15464
15465 llvm::APSInt index = Result.Val.getInt();
15466 if (IndexNegated) {
15467 index.setIsUnsigned(false);
15468 index = -index;
15469 }
15470
15471 if (IsUnboundedArray) {
15472 if (EffectiveType->isFunctionType())
15473 return;
15474 if (index.isUnsigned() || !index.isNegative()) {
15475 const auto &ASTC = getASTContext();
15476 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15477 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15478 if (index.getBitWidth() < AddrBits)
15479 index = index.zext(AddrBits);
15480 std::optional<CharUnits> ElemCharUnits =
15481 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15482 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15483 // pointer) bounds-checking isn't meaningful.
15484 if (!ElemCharUnits || ElemCharUnits->isZero())
15485 return;
15486 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15487 // If index has more active bits than address space, we already know
15488 // we have a bounds violation to warn about. Otherwise, compute
15489 // address of (index + 1)th element, and warn about bounds violation
15490 // only if that address exceeds address space.
15491 if (index.getActiveBits() <= AddrBits) {
15492 bool Overflow;
15493 llvm::APInt Product(index);
15494 Product += 1;
15495 Product = Product.umul_ov(ElemBytes, Overflow);
15496 if (!Overflow && Product.getActiveBits() <= AddrBits)
15497 return;
15498 }
15499
15500 // Need to compute max possible elements in address space, since that
15501 // is included in diag message.
15502 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15503 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15504 MaxElems += 1;
15505 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15506 MaxElems = MaxElems.udiv(ElemBytes);
15507
15508 unsigned DiagID =
15509 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15510 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15511
15512 // Diag message shows element size in bits and in "bytes" (platform-
15513 // dependent CharUnits)
15514 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15515 PDiag(DiagID) << index << AddrBits
15516 << (unsigned)ASTC.toBits(*ElemCharUnits)
15517 << ElemBytes << MaxElems
15518 << MaxElems.getZExtValue()
15519 << IndexExpr->getSourceRange());
15520
15521 const NamedDecl *ND = nullptr;
15522 // Try harder to find a NamedDecl to point at in the note.
15523 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15524 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15525 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15526 ND = DRE->getDecl();
15527 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15528 ND = ME->getMemberDecl();
15529
15530 if (ND)
15531 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15532 PDiag(diag::note_array_declared_here) << ND);
15533 }
15534 return;
15535 }
15536
15537 if (index.isUnsigned() || !index.isNegative()) {
15538 // It is possible that the type of the base expression after
15539 // IgnoreParenCasts is incomplete, even though the type of the base
15540 // expression before IgnoreParenCasts is complete (see PR39746 for an
15541 // example). In this case we have no information about whether the array
15542 // access exceeds the array bounds. However we can still diagnose an array
15543 // access which precedes the array bounds.
15544 if (BaseType->isIncompleteType())
15545 return;
15546
15547 llvm::APInt size = ArrayTy->getSize();
15548
15549 if (BaseType != EffectiveType) {
15550 // Make sure we're comparing apples to apples when comparing index to
15551 // size.
15552 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15553 uint64_t array_typesize = Context.getTypeSize(BaseType);
15554
15555 // Handle ptrarith_typesize being zero, such as when casting to void*.
15556 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
15557 if (!ptrarith_typesize)
15558 ptrarith_typesize = Context.getCharWidth();
15559
15560 if (ptrarith_typesize != array_typesize) {
15561 // There's a cast to a different size type involved.
15562 uint64_t ratio = array_typesize / ptrarith_typesize;
15563
15564 // TODO: Be smarter about handling cases where array_typesize is not a
15565 // multiple of ptrarith_typesize.
15566 if (ptrarith_typesize * ratio == array_typesize)
15567 size *= llvm::APInt(size.getBitWidth(), ratio);
15568 }
15569 }
15570
15571 if (size.getBitWidth() > index.getBitWidth())
15572 index = index.zext(size.getBitWidth());
15573 else if (size.getBitWidth() < index.getBitWidth())
15574 size = size.zext(index.getBitWidth());
15575
15576 // For array subscripting the index must be less than size, but for pointer
15577 // arithmetic also allow the index (offset) to be equal to size since
15578 // computing the next address after the end of the array is legal and
15579 // commonly done e.g. in C++ iterators and range-based for loops.
15580 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15581 return;
15582
15583 // Suppress the warning if the subscript expression (as identified by the
15584 // ']' location) and the index expression are both from macro expansions
15585 // within a system header.
15586 if (ASE) {
15587 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15588 ASE->getRBracketLoc());
15589 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15590 SourceLocation IndexLoc =
15591 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15592 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15593 return;
15594 }
15595 }
15596
15597 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15598 : diag::warn_ptr_arith_exceeds_bounds;
15599 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
15600 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
15601
15602 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15603 PDiag(DiagID)
15604 << index << ArrayTy->desugar() << CastMsg
15605 << CastMsgTy << IndexExpr->getSourceRange());
15606 } else {
15607 unsigned DiagID = diag::warn_array_index_precedes_bounds;
15608 if (!ASE) {
15609 DiagID = diag::warn_ptr_arith_precedes_bounds;
15610 if (index.isNegative()) index = -index;
15611 }
15612
15613 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15614 PDiag(DiagID) << index << IndexExpr->getSourceRange());
15615 }
15616
15617 const NamedDecl *ND = nullptr;
15618 // Try harder to find a NamedDecl to point at in the note.
15619 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15620 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15621 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15622 ND = DRE->getDecl();
15623 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15624 ND = ME->getMemberDecl();
15625
15626 if (ND)
15627 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15628 PDiag(diag::note_array_declared_here) << ND);
15629}
15630
15631void Sema::CheckArrayAccess(const Expr *expr) {
15632 int AllowOnePastEnd = 0;
15633 while (expr) {
15634 expr = expr->IgnoreParenImpCasts();
15635 switch (expr->getStmtClass()) {
15636 case Stmt::ArraySubscriptExprClass: {
15637 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15638 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15639 AllowOnePastEnd > 0);
15640 expr = ASE->getBase();
15641 break;
15642 }
15643 case Stmt::MemberExprClass: {
15644 expr = cast<MemberExpr>(expr)->getBase();
15645 break;
15646 }
15647 case Stmt::CXXMemberCallExprClass: {
15648 expr = cast<CXXMemberCallExpr>(expr)->getImplicitObjectArgument();
15649 break;
15650 }
15651 case Stmt::ArraySectionExprClass: {
15652 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
15653 // FIXME: We should probably be checking all of the elements to the
15654 // 'length' here as well.
15655 if (ASE->getLowerBound())
15656 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15657 /*ASE=*/nullptr, AllowOnePastEnd > 0);
15658 return;
15659 }
15660 case Stmt::UnaryOperatorClass: {
15661 // Only unwrap the * and & unary operators
15662 const UnaryOperator *UO = cast<UnaryOperator>(expr);
15663 expr = UO->getSubExpr();
15664 switch (UO->getOpcode()) {
15665 case UO_AddrOf:
15666 AllowOnePastEnd++;
15667 break;
15668 case UO_Deref:
15669 AllowOnePastEnd--;
15670 break;
15671 default:
15672 return;
15673 }
15674 break;
15675 }
15676 case Stmt::ConditionalOperatorClass: {
15677 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15678 if (const Expr *lhs = cond->getLHS())
15679 CheckArrayAccess(lhs);
15680 if (const Expr *rhs = cond->getRHS())
15681 CheckArrayAccess(rhs);
15682 return;
15683 }
15684 case Stmt::CXXOperatorCallExprClass: {
15685 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15686 for (const auto *Arg : OCE->arguments())
15687 CheckArrayAccess(Arg);
15688 return;
15689 }
15690 default:
15691 return;
15692 }
15693 }
15694}
15695
15697 Expr *RHS, bool isProperty) {
15698 // Check if RHS is an Objective-C object literal, which also can get
15699 // immediately zapped in a weak reference. Note that we explicitly
15700 // allow ObjCStringLiterals, since those are designed to never really die.
15701 RHS = RHS->IgnoreParenImpCasts();
15702
15703 // This enum needs to match with the 'select' in
15704 // warn_objc_arc_literal_assign (off-by-1).
15706 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
15707 return false;
15708
15709 S.Diag(Loc, diag::warn_arc_literal_assign)
15710 << (unsigned) Kind
15711 << (isProperty ? 0 : 1)
15712 << RHS->getSourceRange();
15713
15714 return true;
15715}
15716
15719 Expr *RHS, bool isProperty) {
15720 // Strip off any implicit cast added to get to the one ARC-specific.
15721 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15722 if (cast->getCastKind() == CK_ARCConsumeObject) {
15723 S.Diag(Loc, diag::warn_arc_retained_assign)
15725 << (isProperty ? 0 : 1)
15726 << RHS->getSourceRange();
15727 return true;
15728 }
15729 RHS = cast->getSubExpr();
15730 }
15731
15732 if (LT == Qualifiers::OCL_Weak &&
15733 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15734 return true;
15735
15736 return false;
15737}
15738
15740 QualType LHS, Expr *RHS) {
15742
15744 return false;
15745
15746 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15747 return true;
15748
15749 return false;
15750}
15751
15753 Expr *LHS, Expr *RHS) {
15754 QualType LHSType;
15755 // PropertyRef on LHS type need be directly obtained from
15756 // its declaration as it has a PseudoType.
15758 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15759 if (PRE && !PRE->isImplicitProperty()) {
15760 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15761 if (PD)
15762 LHSType = PD->getType();
15763 }
15764
15765 if (LHSType.isNull())
15766 LHSType = LHS->getType();
15767
15769
15770 if (LT == Qualifiers::OCL_Weak) {
15771 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15773 }
15774
15775 if (checkUnsafeAssigns(Loc, LHSType, RHS))
15776 return;
15777
15778 // FIXME. Check for other life times.
15779 if (LT != Qualifiers::OCL_None)
15780 return;
15781
15782 if (PRE) {
15783 if (PRE->isImplicitProperty())
15784 return;
15785 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15786 if (!PD)
15787 return;
15788
15789 unsigned Attributes = PD->getPropertyAttributes();
15790 if (Attributes & ObjCPropertyAttribute::kind_assign) {
15791 // when 'assign' attribute was not explicitly specified
15792 // by user, ignore it and rely on property type itself
15793 // for lifetime info.
15794 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15795 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15796 LHSType->isObjCRetainableType())
15797 return;
15798
15799 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15800 if (cast->getCastKind() == CK_ARCConsumeObject) {
15801 Diag(Loc, diag::warn_arc_retained_property_assign)
15802 << RHS->getSourceRange();
15803 return;
15804 }
15805 RHS = cast->getSubExpr();
15806 }
15807 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15808 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15809 return;
15810 }
15811 }
15812}
15813
15814//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15815
15816static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15817 SourceLocation StmtLoc,
15818 const NullStmt *Body) {
15819 // Do not warn if the body is a macro that expands to nothing, e.g:
15820 //
15821 // #define CALL(x)
15822 // if (condition)
15823 // CALL(0);
15824 if (Body->hasLeadingEmptyMacro())
15825 return false;
15826
15827 // Get line numbers of statement and body.
15828 bool StmtLineInvalid;
15829 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15830 &StmtLineInvalid);
15831 if (StmtLineInvalid)
15832 return false;
15833
15834 bool BodyLineInvalid;
15835 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15836 &BodyLineInvalid);
15837 if (BodyLineInvalid)
15838 return false;
15839
15840 // Warn if null statement and body are on the same line.
15841 if (StmtLine != BodyLine)
15842 return false;
15843
15844 return true;
15845}
15846
15848 const Stmt *Body,
15849 unsigned DiagID) {
15850 // Since this is a syntactic check, don't emit diagnostic for template
15851 // instantiations, this just adds noise.
15853 return;
15854
15855 // The body should be a null statement.
15856 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15857 if (!NBody)
15858 return;
15859
15860 // Do the usual checks.
15861 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15862 return;
15863
15864 Diag(NBody->getSemiLoc(), DiagID);
15865 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15866}
15867
15869 const Stmt *PossibleBody) {
15870 assert(!CurrentInstantiationScope); // Ensured by caller
15871
15872 SourceLocation StmtLoc;
15873 const Stmt *Body;
15874 unsigned DiagID;
15875 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15876 StmtLoc = FS->getRParenLoc();
15877 Body = FS->getBody();
15878 DiagID = diag::warn_empty_for_body;
15879 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15880 StmtLoc = WS->getRParenLoc();
15881 Body = WS->getBody();
15882 DiagID = diag::warn_empty_while_body;
15883 } else
15884 return; // Neither `for' nor `while'.
15885
15886 // The body should be a null statement.
15887 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15888 if (!NBody)
15889 return;
15890
15891 // Skip expensive checks if diagnostic is disabled.
15892 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15893 return;
15894
15895 // Do the usual checks.
15896 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15897 return;
15898
15899 // `for(...);' and `while(...);' are popular idioms, so in order to keep
15900 // noise level low, emit diagnostics only if for/while is followed by a
15901 // CompoundStmt, e.g.:
15902 // for (int i = 0; i < n; i++);
15903 // {
15904 // a(i);
15905 // }
15906 // or if for/while is followed by a statement with more indentation
15907 // than for/while itself:
15908 // for (int i = 0; i < n; i++);
15909 // a(i);
15910 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15911 if (!ProbableTypo) {
15912 bool BodyColInvalid;
15913 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15914 PossibleBody->getBeginLoc(), &BodyColInvalid);
15915 if (BodyColInvalid)
15916 return;
15917
15918 bool StmtColInvalid;
15919 unsigned StmtCol =
15920 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15921 if (StmtColInvalid)
15922 return;
15923
15924 if (BodyCol > StmtCol)
15925 ProbableTypo = true;
15926 }
15927
15928 if (ProbableTypo) {
15929 Diag(NBody->getSemiLoc(), DiagID);
15930 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15931 }
15932}
15933
15934//===--- CHECK: Warn on self move with std::move. -------------------------===//
15935
15936void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15937 SourceLocation OpLoc) {
15938 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15939 return;
15940
15942 return;
15943
15944 // Strip parens and casts away.
15945 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15946 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15947
15948 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
15949 // which we can treat as an inlined std::move
15950 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
15951 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
15952 RHSExpr = CE->getArg(0);
15953 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
15954 CXXSCE && CXXSCE->isXValue())
15955 RHSExpr = CXXSCE->getSubExpr();
15956 else
15957 return;
15958
15959 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15960 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15961
15962 // Two DeclRefExpr's, check that the decls are the same.
15963 if (LHSDeclRef && RHSDeclRef) {
15964 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15965 return;
15966 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15967 RHSDeclRef->getDecl()->getCanonicalDecl())
15968 return;
15969
15970 auto D = Diag(OpLoc, diag::warn_self_move)
15971 << LHSExpr->getType() << LHSExpr->getSourceRange()
15972 << RHSExpr->getSourceRange();
15973 if (const FieldDecl *F =
15975 D << 1 << F
15976 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15977 else
15978 D << 0;
15979 return;
15980 }
15981
15982 // Member variables require a different approach to check for self moves.
15983 // MemberExpr's are the same if every nested MemberExpr refers to the same
15984 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15985 // the base Expr's are CXXThisExpr's.
15986 const Expr *LHSBase = LHSExpr;
15987 const Expr *RHSBase = RHSExpr;
15988 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15989 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15990 if (!LHSME || !RHSME)
15991 return;
15992
15993 while (LHSME && RHSME) {
15994 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15995 RHSME->getMemberDecl()->getCanonicalDecl())
15996 return;
15997
15998 LHSBase = LHSME->getBase();
15999 RHSBase = RHSME->getBase();
16000 LHSME = dyn_cast<MemberExpr>(LHSBase);
16001 RHSME = dyn_cast<MemberExpr>(RHSBase);
16002 }
16003
16004 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16005 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16006 if (LHSDeclRef && RHSDeclRef) {
16007 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16008 return;
16009 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16010 RHSDeclRef->getDecl()->getCanonicalDecl())
16011 return;
16012
16013 Diag(OpLoc, diag::warn_self_move)
16014 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16015 << RHSExpr->getSourceRange();
16016 return;
16017 }
16018
16019 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16020 Diag(OpLoc, diag::warn_self_move)
16021 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16022 << RHSExpr->getSourceRange();
16023}
16024
16025//===--- Layout compatibility ----------------------------------------------//
16026
16027static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16028
16029/// Check if two enumeration types are layout-compatible.
16030static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16031 const EnumDecl *ED2) {
16032 // C++11 [dcl.enum] p8:
16033 // Two enumeration types are layout-compatible if they have the same
16034 // underlying type.
16035 return ED1->isComplete() && ED2->isComplete() &&
16036 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16037}
16038
16039/// Check if two fields are layout-compatible.
16040/// Can be used on union members, which are exempt from alignment requirement
16041/// of common initial sequence.
16042static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16043 const FieldDecl *Field2,
16044 bool AreUnionMembers = false) {
16045#ifndef NDEBUG
16046 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16047 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16048 assert(((Field1Parent->isStructureOrClassType() &&
16049 Field2Parent->isStructureOrClassType()) ||
16050 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16051 "Can't evaluate layout compatibility between a struct field and a "
16052 "union field.");
16053 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16054 (AreUnionMembers && Field1Parent->isUnionType())) &&
16055 "AreUnionMembers should be 'true' for union fields (only).");
16056#endif
16057
16058 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16059 return false;
16060
16061 if (Field1->isBitField() != Field2->isBitField())
16062 return false;
16063
16064 if (Field1->isBitField()) {
16065 // Make sure that the bit-fields are the same length.
16066 unsigned Bits1 = Field1->getBitWidthValue();
16067 unsigned Bits2 = Field2->getBitWidthValue();
16068
16069 if (Bits1 != Bits2)
16070 return false;
16071 }
16072
16073 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16074 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16075 return false;
16076
16077 if (!AreUnionMembers &&
16078 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16079 return false;
16080
16081 return true;
16082}
16083
16084/// Check if two standard-layout structs are layout-compatible.
16085/// (C++11 [class.mem] p17)
16086static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16087 const RecordDecl *RD2) {
16088 // Get to the class where the fields are declared
16089 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
16090 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16091
16092 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
16093 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16094
16095 // Check the fields.
16096 return llvm::equal(RD1->fields(), RD2->fields(),
16097 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16098 return isLayoutCompatible(C, F1, F2);
16099 });
16100}
16101
16102/// Check if two standard-layout unions are layout-compatible.
16103/// (C++11 [class.mem] p18)
16104static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16105 const RecordDecl *RD2) {
16106 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16107 RD2->fields());
16108
16109 for (auto *Field1 : RD1->fields()) {
16110 auto I = UnmatchedFields.begin();
16111 auto E = UnmatchedFields.end();
16112
16113 for ( ; I != E; ++I) {
16114 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
16115 bool Result = UnmatchedFields.erase(*I);
16116 (void) Result;
16117 assert(Result);
16118 break;
16119 }
16120 }
16121 if (I == E)
16122 return false;
16123 }
16124
16125 return UnmatchedFields.empty();
16126}
16127
16128static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16129 const RecordDecl *RD2) {
16130 if (RD1->isUnion() != RD2->isUnion())
16131 return false;
16132
16133 if (RD1->isUnion())
16134 return isLayoutCompatibleUnion(C, RD1, RD2);
16135 else
16136 return isLayoutCompatibleStruct(C, RD1, RD2);
16137}
16138
16139/// Check if two types are layout-compatible in C++11 sense.
16140static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16141 if (T1.isNull() || T2.isNull())
16142 return false;
16143
16144 // C++20 [basic.types] p11:
16145 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16146 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16147 // or layout-compatible standard-layout class types (11.4).
16150
16151 if (C.hasSameType(T1, T2))
16152 return true;
16153
16154 const Type::TypeClass TC1 = T1->getTypeClass();
16155 const Type::TypeClass TC2 = T2->getTypeClass();
16156
16157 if (TC1 != TC2)
16158 return false;
16159
16160 if (TC1 == Type::Enum)
16161 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
16162 if (TC1 == Type::Record) {
16163 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16164 return false;
16165
16167 T2->castAsRecordDecl());
16168 }
16169
16170 return false;
16171}
16172
16174 return isLayoutCompatible(getASTContext(), T1, T2);
16175}
16176
16177//===-------------- Pointer interconvertibility ----------------------------//
16178
16180 const TypeSourceInfo *Derived) {
16181 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16182 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16183
16184 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16185 getASTContext().hasSameType(BaseT, DerivedT))
16186 return true;
16187
16188 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
16189 return false;
16190
16191 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16192 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16193 return true;
16194
16195 return false;
16196}
16197
16198//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16199
16200/// Given a type tag expression find the type tag itself.
16201///
16202/// \param TypeExpr Type tag expression, as it appears in user's code.
16203///
16204/// \param VD Declaration of an identifier that appears in a type tag.
16205///
16206/// \param MagicValue Type tag magic value.
16207///
16208/// \param isConstantEvaluated whether the evalaution should be performed in
16209
16210/// constant context.
16211static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16212 const ValueDecl **VD, uint64_t *MagicValue,
16213 bool isConstantEvaluated) {
16214 while(true) {
16215 if (!TypeExpr)
16216 return false;
16217
16218 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16219
16220 switch (TypeExpr->getStmtClass()) {
16221 case Stmt::UnaryOperatorClass: {
16222 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16223 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16224 TypeExpr = UO->getSubExpr();
16225 continue;
16226 }
16227 return false;
16228 }
16229
16230 case Stmt::DeclRefExprClass: {
16231 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16232 *VD = DRE->getDecl();
16233 return true;
16234 }
16235
16236 case Stmt::IntegerLiteralClass: {
16237 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16238 llvm::APInt MagicValueAPInt = IL->getValue();
16239 if (MagicValueAPInt.getActiveBits() <= 64) {
16240 *MagicValue = MagicValueAPInt.getZExtValue();
16241 return true;
16242 } else
16243 return false;
16244 }
16245
16246 case Stmt::BinaryConditionalOperatorClass:
16247 case Stmt::ConditionalOperatorClass: {
16248 const AbstractConditionalOperator *ACO =
16250 bool Result;
16251 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16252 isConstantEvaluated)) {
16253 if (Result)
16254 TypeExpr = ACO->getTrueExpr();
16255 else
16256 TypeExpr = ACO->getFalseExpr();
16257 continue;
16258 }
16259 return false;
16260 }
16261
16262 case Stmt::BinaryOperatorClass: {
16263 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16264 if (BO->getOpcode() == BO_Comma) {
16265 TypeExpr = BO->getRHS();
16266 continue;
16267 }
16268 return false;
16269 }
16270
16271 default:
16272 return false;
16273 }
16274 }
16275}
16276
16277/// Retrieve the C type corresponding to type tag TypeExpr.
16278///
16279/// \param TypeExpr Expression that specifies a type tag.
16280///
16281/// \param MagicValues Registered magic values.
16282///
16283/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16284/// kind.
16285///
16286/// \param TypeInfo Information about the corresponding C type.
16287///
16288/// \param isConstantEvaluated whether the evalaution should be performed in
16289/// constant context.
16290///
16291/// \returns true if the corresponding C type was found.
16293 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16294 const ASTContext &Ctx,
16295 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16296 *MagicValues,
16297 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16298 bool isConstantEvaluated) {
16299 FoundWrongKind = false;
16300
16301 // Variable declaration that has type_tag_for_datatype attribute.
16302 const ValueDecl *VD = nullptr;
16303
16304 uint64_t MagicValue;
16305
16306 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16307 return false;
16308
16309 if (VD) {
16310 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16311 if (I->getArgumentKind() != ArgumentKind) {
16312 FoundWrongKind = true;
16313 return false;
16314 }
16315 TypeInfo.Type = I->getMatchingCType();
16316 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16317 TypeInfo.MustBeNull = I->getMustBeNull();
16318 return true;
16319 }
16320 return false;
16321 }
16322
16323 if (!MagicValues)
16324 return false;
16325
16326 llvm::DenseMap<Sema::TypeTagMagicValue,
16328 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16329 if (I == MagicValues->end())
16330 return false;
16331
16332 TypeInfo = I->second;
16333 return true;
16334}
16335
16337 uint64_t MagicValue, QualType Type,
16338 bool LayoutCompatible,
16339 bool MustBeNull) {
16340 if (!TypeTagForDatatypeMagicValues)
16341 TypeTagForDatatypeMagicValues.reset(
16342 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16343
16344 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16345 (*TypeTagForDatatypeMagicValues)[Magic] =
16346 TypeTagData(Type, LayoutCompatible, MustBeNull);
16347}
16348
16349static bool IsSameCharType(QualType T1, QualType T2) {
16350 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16351 if (!BT1)
16352 return false;
16353
16354 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16355 if (!BT2)
16356 return false;
16357
16358 BuiltinType::Kind T1Kind = BT1->getKind();
16359 BuiltinType::Kind T2Kind = BT2->getKind();
16360
16361 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16362 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16363 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16364 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16365}
16366
16367void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16368 const ArrayRef<const Expr *> ExprArgs,
16369 SourceLocation CallSiteLoc) {
16370 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16371 bool IsPointerAttr = Attr->getIsPointer();
16372
16373 // Retrieve the argument representing the 'type_tag'.
16374 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16375 if (TypeTagIdxAST >= ExprArgs.size()) {
16376 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16377 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16378 return;
16379 }
16380 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16381 bool FoundWrongKind;
16382 TypeTagData TypeInfo;
16383 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16384 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16385 TypeInfo, isConstantEvaluatedContext())) {
16386 if (FoundWrongKind)
16387 Diag(TypeTagExpr->getExprLoc(),
16388 diag::warn_type_tag_for_datatype_wrong_kind)
16389 << TypeTagExpr->getSourceRange();
16390 return;
16391 }
16392
16393 // Retrieve the argument representing the 'arg_idx'.
16394 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16395 if (ArgumentIdxAST >= ExprArgs.size()) {
16396 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16397 << 1 << Attr->getArgumentIdx().getSourceIndex();
16398 return;
16399 }
16400 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16401 if (IsPointerAttr) {
16402 // Skip implicit cast of pointer to `void *' (as a function argument).
16403 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16404 if (ICE->getType()->isVoidPointerType() &&
16405 ICE->getCastKind() == CK_BitCast)
16406 ArgumentExpr = ICE->getSubExpr();
16407 }
16408 QualType ArgumentType = ArgumentExpr->getType();
16409
16410 // Passing a `void*' pointer shouldn't trigger a warning.
16411 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16412 return;
16413
16414 if (TypeInfo.MustBeNull) {
16415 // Type tag with matching void type requires a null pointer.
16416 if (!ArgumentExpr->isNullPointerConstant(Context,
16418 Diag(ArgumentExpr->getExprLoc(),
16419 diag::warn_type_safety_null_pointer_required)
16420 << ArgumentKind->getName()
16421 << ArgumentExpr->getSourceRange()
16422 << TypeTagExpr->getSourceRange();
16423 }
16424 return;
16425 }
16426
16427 QualType RequiredType = TypeInfo.Type;
16428 if (IsPointerAttr)
16429 RequiredType = Context.getPointerType(RequiredType);
16430
16431 bool mismatch = false;
16432 if (!TypeInfo.LayoutCompatible) {
16433 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16434
16435 // C++11 [basic.fundamental] p1:
16436 // Plain char, signed char, and unsigned char are three distinct types.
16437 //
16438 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16439 // char' depending on the current char signedness mode.
16440 if (mismatch)
16441 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16442 RequiredType->getPointeeType())) ||
16443 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16444 mismatch = false;
16445 } else
16446 if (IsPointerAttr)
16447 mismatch = !isLayoutCompatible(Context,
16448 ArgumentType->getPointeeType(),
16449 RequiredType->getPointeeType());
16450 else
16451 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16452
16453 if (mismatch)
16454 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16455 << ArgumentType << ArgumentKind
16456 << TypeInfo.LayoutCompatible << RequiredType
16457 << ArgumentExpr->getSourceRange()
16458 << TypeTagExpr->getSourceRange();
16459}
16460
16461void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16462 CharUnits Alignment) {
16463 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
16464 Alignment);
16465}
16466
16468 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16469 const NamedDecl *ND = m.RD;
16470 if (ND->getName().empty()) {
16471 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16472 ND = TD;
16473 }
16474 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16475 << m.MD << ND << m.E->getSourceRange();
16476 }
16478}
16479
16481 E = E->IgnoreParens();
16482 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16483 return;
16484 if (isa<UnaryOperator>(E) &&
16485 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16486 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16487 if (isa<MemberExpr>(Op)) {
16488 auto &MisalignedMembersForExpr =
16490 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
16491 if (MA != MisalignedMembersForExpr.end() &&
16492 (T->isDependentType() || T->isIntegerType() ||
16493 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16494 Context.getTypeAlignInChars(
16495 T->getPointeeType()) <= MA->Alignment))))
16496 MisalignedMembersForExpr.erase(MA);
16497 }
16498 }
16499}
16500
16502 Expr *E,
16503 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16504 Action) {
16505 const auto *ME = dyn_cast<MemberExpr>(E);
16506 if (!ME)
16507 return;
16508
16509 // No need to check expressions with an __unaligned-qualified type.
16510 if (E->getType().getQualifiers().hasUnaligned())
16511 return;
16512
16513 // For a chain of MemberExpr like "a.b.c.d" this list
16514 // will keep FieldDecl's like [d, c, b].
16515 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16516 const MemberExpr *TopME = nullptr;
16517 bool AnyIsPacked = false;
16518 do {
16519 QualType BaseType = ME->getBase()->getType();
16520 if (BaseType->isDependentType())
16521 return;
16522 if (ME->isArrow())
16523 BaseType = BaseType->getPointeeType();
16524 auto *RD = BaseType->castAsRecordDecl();
16525 if (RD->isInvalidDecl())
16526 return;
16527
16528 ValueDecl *MD = ME->getMemberDecl();
16529 auto *FD = dyn_cast<FieldDecl>(MD);
16530 // We do not care about non-data members.
16531 if (!FD || FD->isInvalidDecl())
16532 return;
16533
16534 AnyIsPacked =
16535 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16536 ReverseMemberChain.push_back(FD);
16537
16538 TopME = ME;
16539 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16540 } while (ME);
16541 assert(TopME && "We did not compute a topmost MemberExpr!");
16542
16543 // Not the scope of this diagnostic.
16544 if (!AnyIsPacked)
16545 return;
16546
16547 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16548 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16549 // TODO: The innermost base of the member expression may be too complicated.
16550 // For now, just disregard these cases. This is left for future
16551 // improvement.
16552 if (!DRE && !isa<CXXThisExpr>(TopBase))
16553 return;
16554
16555 // Alignment expected by the whole expression.
16556 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16557
16558 // No need to do anything else with this case.
16559 if (ExpectedAlignment.isOne())
16560 return;
16561
16562 // Synthesize offset of the whole access.
16563 CharUnits Offset;
16564 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16565 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16566
16567 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16568 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16569 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
16570
16571 // The base expression of the innermost MemberExpr may give
16572 // stronger guarantees than the class containing the member.
16573 if (DRE && !TopME->isArrow()) {
16574 const ValueDecl *VD = DRE->getDecl();
16575 if (!VD->getType()->isReferenceType())
16576 CompleteObjectAlignment =
16577 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16578 }
16579
16580 // Check if the synthesized offset fulfills the alignment.
16581 if (!Offset.isMultipleOf(ExpectedAlignment) ||
16582 // It may fulfill the offset it but the effective alignment may still be
16583 // lower than the expected expression alignment.
16584 CompleteObjectAlignment < ExpectedAlignment) {
16585 // If this happens, we want to determine a sensible culprit of this.
16586 // Intuitively, watching the chain of member expressions from right to
16587 // left, we start with the required alignment (as required by the field
16588 // type) but some packed attribute in that chain has reduced the alignment.
16589 // It may happen that another packed structure increases it again. But if
16590 // we are here such increase has not been enough. So pointing the first
16591 // FieldDecl that either is packed or else its RecordDecl is,
16592 // seems reasonable.
16593 FieldDecl *FD = nullptr;
16594 CharUnits Alignment;
16595 for (FieldDecl *FDI : ReverseMemberChain) {
16596 if (FDI->hasAttr<PackedAttr>() ||
16597 FDI->getParent()->hasAttr<PackedAttr>()) {
16598 FD = FDI;
16599 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
16600 Context.getTypeAlignInChars(
16601 Context.getCanonicalTagType(FD->getParent())));
16602 break;
16603 }
16604 }
16605 assert(FD && "We did not find a packed FieldDecl!");
16606 Action(E, FD->getParent(), FD, Alignment);
16607 }
16608}
16609
16610void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16611 using namespace std::placeholders;
16612
16614 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16615 _2, _3, _4));
16616}
16617
16619 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16620 if (checkArgCount(TheCall, 1))
16621 return true;
16622
16623 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
16624 if (A.isInvalid())
16625 return true;
16626
16627 TheCall->setArg(0, A.get());
16628 QualType TyA = A.get()->getType();
16629
16630 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
16631 ArgTyRestr, 1))
16632 return true;
16633
16634 TheCall->setType(TyA);
16635 return false;
16636}
16637
16638bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
16639 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16640 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
16641 TheCall->setType(*Res);
16642 return false;
16643 }
16644 return true;
16645}
16646
16648 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
16649 if (!Res)
16650 return true;
16651
16652 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
16653 TheCall->setType(VecTy0->getElementType());
16654 else
16655 TheCall->setType(*Res);
16656
16657 return false;
16658}
16659
16661 SourceLocation Loc) {
16663 R = RHS->getEnumCoercedType(S.Context);
16664 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
16666 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
16667 << LHS->getSourceRange() << RHS->getSourceRange()
16668 << /*Arithmetic Between*/ 0 << L << R;
16669 }
16670 return false;
16671}
16672
16673/// Check if all arguments have the same type. If the types don't match, emit an
16674/// error message and return true. Otherwise return false.
16675///
16676/// For scalars we directly compare their unqualified types. But even if we
16677/// compare unqualified vector types, a difference in qualifiers in the element
16678/// types can make the vector types be considered not equal. For example,
16679/// vector of 4 'const float' values vs vector of 4 'float' values.
16680/// So we compare unqualified types of their elements and number of elements.
16682 ArrayRef<Expr *> Args) {
16683 assert(!Args.empty() && "Should have at least one argument.");
16684
16685 Expr *Arg0 = Args.front();
16686 QualType Ty0 = Arg0->getType();
16687
16688 auto EmitError = [&](Expr *ArgI) {
16689 SemaRef.Diag(Arg0->getBeginLoc(),
16690 diag::err_typecheck_call_different_arg_types)
16691 << Arg0->getType() << ArgI->getType();
16692 };
16693
16694 // Compare scalar types.
16695 if (!Ty0->isVectorType()) {
16696 for (Expr *ArgI : Args.drop_front())
16697 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
16698 EmitError(ArgI);
16699 return true;
16700 }
16701
16702 return false;
16703 }
16704
16705 // Compare vector types.
16706 const auto *Vec0 = Ty0->castAs<VectorType>();
16707 for (Expr *ArgI : Args.drop_front()) {
16708 const auto *VecI = ArgI->getType()->getAs<VectorType>();
16709 if (!VecI ||
16710 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
16711 VecI->getElementType()) ||
16712 Vec0->getNumElements() != VecI->getNumElements()) {
16713 EmitError(ArgI);
16714 return true;
16715 }
16716 }
16717
16718 return false;
16719}
16720
16721std::optional<QualType>
16723 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16724 if (checkArgCount(TheCall, 2))
16725 return std::nullopt;
16726
16728 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
16729 return std::nullopt;
16730
16731 Expr *Args[2];
16732 for (int I = 0; I < 2; ++I) {
16733 ExprResult Converted =
16734 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16735 if (Converted.isInvalid())
16736 return std::nullopt;
16737 Args[I] = Converted.get();
16738 }
16739
16740 SourceLocation LocA = Args[0]->getBeginLoc();
16741 QualType TyA = Args[0]->getType();
16742
16743 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
16744 return std::nullopt;
16745
16746 if (checkBuiltinVectorMathArgTypes(*this, Args))
16747 return std::nullopt;
16748
16749 TheCall->setArg(0, Args[0]);
16750 TheCall->setArg(1, Args[1]);
16751 return TyA;
16752}
16753
16755 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16756 if (checkArgCount(TheCall, 3))
16757 return true;
16758
16759 SourceLocation Loc = TheCall->getExprLoc();
16760 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
16761 TheCall->getArg(1), Loc) ||
16762 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
16763 TheCall->getArg(2), Loc))
16764 return true;
16765
16766 Expr *Args[3];
16767 for (int I = 0; I < 3; ++I) {
16768 ExprResult Converted =
16769 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16770 if (Converted.isInvalid())
16771 return true;
16772 Args[I] = Converted.get();
16773 }
16774
16775 int ArgOrdinal = 1;
16776 for (Expr *Arg : Args) {
16777 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
16778 ArgTyRestr, ArgOrdinal++))
16779 return true;
16780 }
16781
16782 if (checkBuiltinVectorMathArgTypes(*this, Args))
16783 return true;
16784
16785 for (int I = 0; I < 3; ++I)
16786 TheCall->setArg(I, Args[I]);
16787
16788 TheCall->setType(Args[0]->getType());
16789 return false;
16790}
16791
16792bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16793 if (checkArgCount(TheCall, 1))
16794 return true;
16795
16796 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16797 if (A.isInvalid())
16798 return true;
16799
16800 TheCall->setArg(0, A.get());
16801 return false;
16802}
16803
16804bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
16805 if (checkArgCount(TheCall, 1))
16806 return true;
16807
16808 ExprResult Arg = TheCall->getArg(0);
16809 QualType TyArg = Arg.get()->getType();
16810
16811 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
16812 return Diag(TheCall->getArg(0)->getBeginLoc(),
16813 diag::err_builtin_invalid_arg_type)
16814 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
16815
16816 TheCall->setType(TyArg);
16817 return false;
16818}
16819
16820ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
16821 ExprResult CallResult) {
16822 if (checkArgCount(TheCall, 1))
16823 return ExprError();
16824
16825 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16826 if (MatrixArg.isInvalid())
16827 return MatrixArg;
16828 Expr *Matrix = MatrixArg.get();
16829
16830 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16831 if (!MType) {
16832 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16833 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
16834 << Matrix->getType();
16835 return ExprError();
16836 }
16837
16838 // Create returned matrix type by swapping rows and columns of the argument
16839 // matrix type.
16840 QualType ResultType = Context.getConstantMatrixType(
16841 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16842
16843 // Change the return type to the type of the returned matrix.
16844 TheCall->setType(ResultType);
16845
16846 // Update call argument to use the possibly converted matrix argument.
16847 TheCall->setArg(0, Matrix);
16848 return CallResult;
16849}
16850
16851// Get and verify the matrix dimensions.
16852static std::optional<unsigned>
16854 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
16855 if (!Value) {
16856 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16857 << Name;
16858 return {};
16859 }
16860 uint64_t Dim = Value->getZExtValue();
16861 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
16862 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16863 << Name << S.Context.getLangOpts().MaxMatrixDimension;
16864 return {};
16865 }
16866 return Dim;
16867}
16868
16869ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16870 ExprResult CallResult) {
16871 if (!getLangOpts().MatrixTypes) {
16872 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16873 return ExprError();
16874 }
16875
16876 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
16878 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
16879 << /*column*/ 1 << /*load*/ 0;
16880 return ExprError();
16881 }
16882
16883 if (checkArgCount(TheCall, 4))
16884 return ExprError();
16885
16886 unsigned PtrArgIdx = 0;
16887 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16888 Expr *RowsExpr = TheCall->getArg(1);
16889 Expr *ColumnsExpr = TheCall->getArg(2);
16890 Expr *StrideExpr = TheCall->getArg(3);
16891
16892 bool ArgError = false;
16893
16894 // Check pointer argument.
16895 {
16897 if (PtrConv.isInvalid())
16898 return PtrConv;
16899 PtrExpr = PtrConv.get();
16900 TheCall->setArg(0, PtrExpr);
16901 if (PtrExpr->isTypeDependent()) {
16902 TheCall->setType(Context.DependentTy);
16903 return TheCall;
16904 }
16905 }
16906
16907 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16908 QualType ElementTy;
16909 if (!PtrTy) {
16910 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16911 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
16912 << PtrExpr->getType();
16913 ArgError = true;
16914 } else {
16915 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16916
16918 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16919 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
16920 << /* no fp */ 0 << PtrExpr->getType();
16921 ArgError = true;
16922 }
16923 }
16924
16925 // Apply default Lvalue conversions and convert the expression to size_t.
16926 auto ApplyArgumentConversions = [this](Expr *E) {
16928 if (Conv.isInvalid())
16929 return Conv;
16930
16931 return tryConvertExprToType(Conv.get(), Context.getSizeType());
16932 };
16933
16934 // Apply conversion to row and column expressions.
16935 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16936 if (!RowsConv.isInvalid()) {
16937 RowsExpr = RowsConv.get();
16938 TheCall->setArg(1, RowsExpr);
16939 } else
16940 RowsExpr = nullptr;
16941
16942 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16943 if (!ColumnsConv.isInvalid()) {
16944 ColumnsExpr = ColumnsConv.get();
16945 TheCall->setArg(2, ColumnsExpr);
16946 } else
16947 ColumnsExpr = nullptr;
16948
16949 // If any part of the result matrix type is still pending, just use
16950 // Context.DependentTy, until all parts are resolved.
16951 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16952 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16953 TheCall->setType(Context.DependentTy);
16954 return CallResult;
16955 }
16956
16957 // Check row and column dimensions.
16958 std::optional<unsigned> MaybeRows;
16959 if (RowsExpr)
16960 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16961
16962 std::optional<unsigned> MaybeColumns;
16963 if (ColumnsExpr)
16964 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16965
16966 // Check stride argument.
16967 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16968 if (StrideConv.isInvalid())
16969 return ExprError();
16970 StrideExpr = StrideConv.get();
16971 TheCall->setArg(3, StrideExpr);
16972
16973 if (MaybeRows) {
16974 if (std::optional<llvm::APSInt> Value =
16975 StrideExpr->getIntegerConstantExpr(Context)) {
16976 uint64_t Stride = Value->getZExtValue();
16977 if (Stride < *MaybeRows) {
16978 Diag(StrideExpr->getBeginLoc(),
16979 diag::err_builtin_matrix_stride_too_small);
16980 ArgError = true;
16981 }
16982 }
16983 }
16984
16985 if (ArgError || !MaybeRows || !MaybeColumns)
16986 return ExprError();
16987
16988 TheCall->setType(
16989 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16990 return CallResult;
16991}
16992
16993ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16994 ExprResult CallResult) {
16995 if (!getLangOpts().MatrixTypes) {
16996 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16997 return ExprError();
16998 }
16999
17000 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17002 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17003 << /*column*/ 1 << /*store*/ 1;
17004 return ExprError();
17005 }
17006
17007 if (checkArgCount(TheCall, 3))
17008 return ExprError();
17009
17010 unsigned PtrArgIdx = 1;
17011 Expr *MatrixExpr = TheCall->getArg(0);
17012 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17013 Expr *StrideExpr = TheCall->getArg(2);
17014
17015 bool ArgError = false;
17016
17017 {
17018 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17019 if (MatrixConv.isInvalid())
17020 return MatrixConv;
17021 MatrixExpr = MatrixConv.get();
17022 TheCall->setArg(0, MatrixExpr);
17023 }
17024 if (MatrixExpr->isTypeDependent()) {
17025 TheCall->setType(Context.DependentTy);
17026 return TheCall;
17027 }
17028
17029 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17030 if (!MatrixTy) {
17031 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17032 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17033 ArgError = true;
17034 }
17035
17036 {
17038 if (PtrConv.isInvalid())
17039 return PtrConv;
17040 PtrExpr = PtrConv.get();
17041 TheCall->setArg(1, PtrExpr);
17042 if (PtrExpr->isTypeDependent()) {
17043 TheCall->setType(Context.DependentTy);
17044 return TheCall;
17045 }
17046 }
17047
17048 // Check pointer argument.
17049 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17050 if (!PtrTy) {
17051 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17052 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17053 << PtrExpr->getType();
17054 ArgError = true;
17055 } else {
17056 QualType ElementTy = PtrTy->getPointeeType();
17057 if (ElementTy.isConstQualified()) {
17058 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17059 ArgError = true;
17060 }
17061 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17062 if (MatrixTy &&
17063 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17064 Diag(PtrExpr->getBeginLoc(),
17065 diag::err_builtin_matrix_pointer_arg_mismatch)
17066 << ElementTy << MatrixTy->getElementType();
17067 ArgError = true;
17068 }
17069 }
17070
17071 // Apply default Lvalue conversions and convert the stride expression to
17072 // size_t.
17073 {
17074 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17075 if (StrideConv.isInvalid())
17076 return StrideConv;
17077
17078 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17079 if (StrideConv.isInvalid())
17080 return StrideConv;
17081 StrideExpr = StrideConv.get();
17082 TheCall->setArg(2, StrideExpr);
17083 }
17084
17085 // Check stride argument.
17086 if (MatrixTy) {
17087 if (std::optional<llvm::APSInt> Value =
17088 StrideExpr->getIntegerConstantExpr(Context)) {
17089 uint64_t Stride = Value->getZExtValue();
17090 if (Stride < MatrixTy->getNumRows()) {
17091 Diag(StrideExpr->getBeginLoc(),
17092 diag::err_builtin_matrix_stride_too_small);
17093 ArgError = true;
17094 }
17095 }
17096 }
17097
17098 if (ArgError)
17099 return ExprError();
17100
17101 return CallResult;
17102}
17103
17105 const NamedDecl *Callee) {
17106 // This warning does not make sense in code that has no runtime behavior.
17108 return;
17109
17110 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17111
17112 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17113 return;
17114
17115 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17116 // all TCBs the callee is a part of.
17117 llvm::StringSet<> CalleeTCBs;
17118 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17119 CalleeTCBs.insert(A->getTCBName());
17120 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17121 CalleeTCBs.insert(A->getTCBName());
17122
17123 // Go through the TCBs the caller is a part of and emit warnings if Caller
17124 // is in a TCB that the Callee is not.
17125 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17126 StringRef CallerTCB = A->getTCBName();
17127 if (CalleeTCBs.count(CallerTCB) == 0) {
17128 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17129 << Callee << CallerTCB;
17130 }
17131 }
17132}
Defines the clang::ASTContext interface.
#define V(N, I)
Provides definitions for the various language-specific address spaces.
Defines the Diagnostic-related interfaces.
static bool getTypeString(SmallStringEnc &Enc, const Decl *D, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC)
The XCore ABI includes a type information section that communicates symbol type information to the li...
Definition XCore.cpp:630
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
std::shared_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token's formatting.
unsigned IsFirst
Indicates that this is the first token of the file.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
#define SM(sm)
Defines the clang::OpenCLOptions class.
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis functions specific to BPF.
static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout unions are layout-compatible.
static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, const ValueDecl **VD, uint64_t *MagicValue, bool isConstantEvaluated)
Given a type tag expression find the type tag itself.
static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, SourceLocation CC, QualType T)
static QualType getSizeOfArgType(const Expr *E)
If E is a sizeof expression, returns its argument type.
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, SourceLocation CallSiteLoc)
static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind, bool RequireConstant=false)
static 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 bool IsSameCharType(QualType T1, QualType T2)
static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E)
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall)
static bool isArgumentExpandedFromMacro(SourceManager &SM, SourceLocation CallLoc, SourceLocation ArgLoc)
Check if the ArgLoc originated from a macro passed to the call at CallLoc.
static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth)
static const IntegerLiteral * getIntegerLiteral(Expr *E)
static bool CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall, ArrayRef< llvm::Triple::ArchType > SupportedArchs)
static const Expr * maybeConstEvalStringLiteral(ASTContext &Context, const Expr *E)
static bool IsStdFunction(const FunctionDecl *FDecl, const char(&Str)[StrLen])
static void AnalyzeAssignment(Sema &S, BinaryOperator *E)
Analyze the given simple or compound assignment for warning-worthy operations.
static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_function_start is a function.
static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall)
static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, SourceLocation StmtLoc, const NullStmt *Body)
static std::pair< CharUnits, CharUnits > getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, CharUnits BaseAlignment, CharUnits Offset, ASTContext &Ctx)
Compute the alignment and offset of the base class object given the derived-to-base cast expression a...
static std::pair< const ValueDecl *, CharUnits > findConstantBaseAndOffset(Sema &S, Expr *E)
static 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 checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
static bool isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE)
Return true if ICE is an implicit argument promotion of an arithmetic type.
static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, bool IsListInit=false)
AnalyzeImplicitConversions - Find and report any interesting implicit conversions in the given expres...
static std::optional< std::pair< CharUnits, CharUnits > > getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, bool IsSub, ASTContext &Ctx)
Compute the alignment and offset of a binary additive operator.
static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
This file declares semantic analysis for DirectX constructs.
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis functions specific to Hexagon.
This file declares semantic analysis functions specific to LoongArch.
This file declares semantic analysis functions specific to MIPS.
This file declares semantic analysis functions specific to NVPTX.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis routines for OpenCL.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SPIRV constructs.
This file declares semantic analysis functions specific to SystemZ.
This file declares semantic analysis functions specific to Wasm.
This file declares semantic analysis functions specific to X86.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Provides definitions for the atomic synchronization scopes.
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)
__device__ __2f16 float __ockl_bool s
@ GE_None
No error.
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatch
The conversion specifier and the argument types are incompatible.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ MatchPromotion
The conversion specifier and the argument type are compatible because of default argument promotions.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
@ NoMatchTypeConfusion
The conversion specifier and the argument type are compatible, but still seems likely to be an error.
@ NoMatchPromotionTypeConfusion
The conversion specifier and the argument type are compatible but still seems likely to be an error.
unsigned getLength() const
const char * toString() const
const char * getStart() const
const char * getStart() const
HowSpecified getHowSpecified() const
unsigned getConstantAmount() const
unsigned getConstantLength() const
bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx, bool IsObjCLiteral)
Changes the specifier and length according to a QualType, retaining any flags or options.
void toString(raw_ostream &os) const
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
const LValueBase getLValueBase() const
Definition APValue.cpp:1015
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:226
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:798
Builtin::Context & BuiltinInfo
Definition ASTContext.h:800
const LangOptions & getLangOpts() const
Definition ASTContext.h:952
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:851
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:917
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:4356
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4534
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4540
SourceLocation getQuestionLoc() const
Definition Expr.h:4383
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4546
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:7296
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7300
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2724
SourceLocation getRBracketLoc() const
Definition Expr.h:2772
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2753
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3772
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3786
QualType getElementType() const
Definition TypeBase.h:3784
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6927
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:7076
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:7058
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:4041
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4174
Expr * getLHS() const
Definition Expr.h:4091
SourceLocation getOperatorLoc() const
Definition Expr.h:4083
SourceLocation getExprLoc() const
Definition Expr.h:4082
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2133
Expr * getRHS() const
Definition Expr.h:4093
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4127
Opcode getOpcode() const
Definition Expr.h:4086
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4138
BinaryOperatorKind Opcode
Definition Expr.h:4046
Pointer to a block type.
Definition TypeBase.h:3592
This class is used for builtin types like 'int'.
Definition TypeBase.h:3214
bool isInteger() const
Definition TypeBase.h:3275
bool isFloatingPoint() const
Definition TypeBase.h:3287
bool isSignedInteger() const
Definition TypeBase.h:3279
bool isUnsignedInteger() const
Definition TypeBase.h:3283
Kind getKind() const
Definition TypeBase.h:3262
std::string getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:85
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition Builtins.h:382
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition Builtins.cpp:80
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition Expr.h:3972
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a call to a C++ constructor.
Definition ExprCXX.h:1549
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition ExprCXX.h:1631
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1689
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2946
Represents a C++ destructor within a class.
Definition DeclCXX.h:2876
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:85
SourceLocation getExprLoc() const LLVM_READONLY
Definition ExprCXX.h:155
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:5142
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5182
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1225
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1214
bool isDynamicClass() const
Definition DeclCXX.h:574
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:74
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2946
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3150
SourceLocation getBeginLoc() const
Definition Expr.h:3280
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3163
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1592
arg_iterator arg_begin()
Definition Expr.h:3203
arg_iterator arg_end()
Definition Expr.h:3206
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3129
bool isCallToStdMove() const
Definition Expr.cpp:3642
Expr * getCallee()
Definition Expr.h:3093
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3137
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3239
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3140
arg_range arguments()
Definition Expr.h:3198
SourceLocation getEndLoc() const
Definition Expr.h:3299
SourceLocation getRParenLoc() const
Definition Expr.h:3277
Decl * getCalleeDecl()
Definition Expr.h:3123
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:1597
void setCallee(Expr *F)
Definition Expr.h:3095
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition Expr.h:3182
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:3679
path_iterator path_begin()
Definition Expr.h:3749
CastKind getCastKind() const
Definition Expr.h:3723
path_iterator path_end()
Definition Expr.h:3750
Expr * getSubExpr()
Definition Expr.h:3729
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:4394
Expr * getLHS() const
Definition Expr.h:4428
Expr * getRHS() const
Definition Expr.h:4429
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3810
QualType desugar() const
Definition TypeBase.h:3911
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3866
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:350
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4437
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4459
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:5673
Expr * getOperand() const
Definition ExprCXX.h:5325
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool isStdNamespace() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
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:488
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1366
ValueDecl * getDecl()
Definition Expr.h:1341
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1471
SourceLocation getBeginLoc() const
Definition Expr.h:1352
SourceLocation getLocation() const
Definition Expr.h:1349
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:449
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:435
T * getAttr() const
Definition DeclBase.h:573
void addAttr(Attr *A)
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:560
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
bool isInvalidDecl() const
Definition DeclBase.h:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:427
The name of a declaration.
std::string getAsString() const
Retrieve the human-readable string for this name.
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2000
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:959
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3438
Represents an enum.
Definition Decl.h:4028
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4260
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4201
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
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:677
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition Expr.h:674
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3095
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:3090
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3078
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:3086
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:206
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:4229
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:834
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:838
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:3074
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3082
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:3688
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:3070
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:805
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:814
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:817
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:807
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:4068
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:266
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:277
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:226
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:137
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition TypeBase.h:4317
Represents a member of a struct/union/class.
Definition Decl.h:3175
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3278
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4753
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3411
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3291
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
llvm::APFloat getValue() const
Definition Expr.h:1669
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2889
Represents a function declaration or definition.
Definition Decl.h:2015
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4554
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2812
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3763
param_iterator param_end()
Definition Decl.h:2802
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3866
QualType getReturnType() const
Definition Decl.h:2860
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2789
param_iterator param_begin()
Definition Decl.h:2801
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3134
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4330
bool isStatic() const
Definition Decl.h:2944
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4145
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4131
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3827
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5357
unsigned getNumParams() const
Definition TypeBase.h:5635
QualType getParamType(unsigned i) const
Definition TypeBase.h:5637
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5761
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5646
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5756
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5642
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4553
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4862
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4858
QualType getReturnType() const
Definition TypeBase.h:4893
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:3856
Describes an C or C++ initializer list.
Definition Expr.h:5302
ArrayRef< Expr * > inits()
Definition Expr.h:5352
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:975
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:1038
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1074
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:1121
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:858
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:4387
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4408
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3367
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3450
Expr * getBase() const
Definition Expr.h:3444
bool isArrow() const
Definition Expr.h:3551
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3703
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1942
Represent a C++ namespace.
Definition Decl.h:592
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition Stmt.h:1704
bool hasLeadingEmptyMacro() const
Definition Stmt.h:1718
SourceLocation getSemiLoc() const
Definition Stmt.h:1715
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:277
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2185
Represents a parameter to a function.
Definition Decl.h:1805
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:3378
QualType getPointeeType() const
Definition TypeBase.h:3388
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6803
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5188
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8515
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2912
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1459
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1220
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:8431
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8557
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8471
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1444
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition TypeBase.h:8483
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8525
void removeLocalVolatile()
Definition TypeBase.h:8547
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1185
void removeLocalConst()
Definition TypeBase.h:8539
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8504
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8552
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1684
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8477
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1338
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1448
@ 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:4342
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4428
field_range fields() const
Definition Decl.h:4545
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4420
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
bool isSEHExceptScope() const
Determine whether this scope is a SEH '__except' block.
Definition Scope.h:616
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
ScopeFlags
ScopeFlags - These are bitfields that are or'd together when creating a scope, which defines the sort...
Definition Scope.h:45
@ SEHFilterScope
We are currently in the filter expression of an SEH except block.
Definition Scope.h:131
@ SEHExceptScope
This scope corresponds to an SEH except.
Definition Scope.h:128
bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1027
@ 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:1207
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:414
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSPIRVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaWasm.cpp:289
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaX86.cpp:535
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10391
ContextualImplicitConverter(bool Suppress=false, bool SuppressConversion=false)
Definition Sema.h:10396
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
const FieldDecl * getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned)
Returns a field in a CXXRecordDecl that has the same name as the decl SelfAssigned when inside a CXXM...
bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const
Returns true if From is a function or pointer to a function with the cfi_unchecked_callee attribute b...
SemaAMDGPU & AMDGPU()
Definition Sema.h:1444
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:13135
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1137
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:2714
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9402
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9410
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9447
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:6996
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:2073
SemaHexagon & Hexagon()
Definition Sema.h:1484
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:1711
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:837
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition Sema.h:1574
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:1304
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:225
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC, bool *ICContext=nullptr, bool IsListInit=false)
SemaObjC & ObjC()
Definition Sema.h:1514
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1369
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:758
ASTContext & getASTContext() const
Definition Sema.h:939
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:757
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2633
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:1208
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:2740
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low, int High, bool RangeIsError=true)
BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr TheCall is a constant express...
bool IsLayoutCompatible(QualType T1, QualType T2) const
const LangOptions & getLangOpts() const
Definition Sema.h:932
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
SemaBPF & BPF()
Definition Sema.h:1459
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:1474
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:1302
static const uint64_t MaximumAlignment
Definition Sema.h:1231
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:956
SemaHLSL & HLSL()
Definition Sema.h:1479
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1499
SemaRISCV & RISCV()
Definition Sema.h:1544
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:2806
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7032
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1723
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:1337
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:2713
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15511
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:2369
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:643
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:1442
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:1524
FormatArgumentPassingKind
Definition Sema.h:2643
@ FAPK_Elsewhere
Definition Sema.h:2647
@ FAPK_Fixed
Definition Sema.h:2644
@ FAPK_Variadic
Definition Sema.h:2645
@ FAPK_VAList
Definition Sema.h:2646
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:8248
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:14047
SourceManager & getSourceManager() const
Definition Sema.h:937
static FormatStringType GetFormatStringType(StringRef FormatFlavor)
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount, unsigned MaxArgCount)
Checks that a call expression's argument count is in the desired range.
bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str)
Verify that one format string (as understood by attribute(format)) is self-consistent; for instance,...
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Binary Operators. 'Tok' is the token for the operator.
bool isConstantEvaluatedContext() const
Definition Sema.h:2635
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:1534
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:1263
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:1564
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:1307
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:787
DiagnosticsEngine & Diags
Definition Sema.h:1306
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:1509
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:626
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:6296
SemaSPIRV & SPIRV()
Definition Sema.h:1549
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:1489
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6484
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:1569
SemaARM & ARM()
Definition Sema.h:1449
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:4646
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:1494
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:1802
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1976
bool isUTF8() const
Definition Expr.h:1921
bool isWide() const
Definition Expr.h:1920
bool isPascal() const
Definition Expr.h:1925
unsigned getLength() const
Definition Expr.h:1912
StringLiteralKind getKind() const
Definition Expr.h:1915
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:1326
bool isUTF32() const
Definition Expr.h:1923
unsigned getByteLength() const
Definition Expr.h:1911
StringRef getString() const
Definition Expr.h:1870
bool isUTF16() const
Definition Expr.h:1922
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.h:1977
bool isOrdinary() const
Definition Expr.h:1919
unsigned getCharByteWidth() const
Definition Expr.h:1913
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3853
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3833
bool isUnion() const
Definition Decl.h:3943
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:6268
A container of type source information.
Definition TypeBase.h:8402
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:8413
The base class of the type hierarchy.
Definition TypeBase.h:1866
bool isBlockPointerType() const
Definition TypeBase.h:8688
bool isVoidType() const
Definition TypeBase.h:9034
bool isBooleanType() const
Definition TypeBase.h:9171
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2254
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9221
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:789
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2231
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2308
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2138
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:9201
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:2084
bool isVoidPointerType() const
Definition Type.cpp:714
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2470
bool isArrayType() const
Definition TypeBase.h:8767
bool isCharType() const
Definition Type.cpp:2158
bool isFunctionPointerType() const
Definition TypeBase.h:8735
bool isPointerType() const
Definition TypeBase.h:8668
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9078
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9328
bool isReferenceType() const
Definition TypeBase.h:8692
bool isEnumeralType() const
Definition TypeBase.h:8799
bool isScalarType() const
Definition TypeBase.h:9140
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:1923
bool isVariableArrayType() const
Definition TypeBase.h:8779
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2652
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:754
bool isExtVectorType() const
Definition TypeBase.h:8811
bool isExtVectorBoolType() const
Definition TypeBase.h:8815
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2691
bool isBitIntType() const
Definition TypeBase.h:8943
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9003
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8791
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2832
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2275
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3169
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2602
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9214
bool isAtomicType() const
Definition TypeBase.h:8860
bool isFunctionProtoType() const
Definition TypeBase.h:2649
bool isMatrixType() const
Definition TypeBase.h:8831
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3147
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:2850
bool isUnscopedEnumerationType() const
Definition Type.cpp:2151
bool isObjCObjectType() const
Definition TypeBase.h:8851
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9314
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9177
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2558
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:2480
bool isFunctionType() const
Definition TypeBase.h:8664
bool isObjCObjectPointerType() const
Definition TypeBase.h:8847
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2350
bool isStructureOrClassType() const
Definition Type.cpp:708
bool isVectorType() const
Definition TypeBase.h:8807
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2358
bool isFloatingType() const
Definition Type.cpp:2342
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:2285
bool isAnyPointerType() const
Definition TypeBase.h:8676
TypeClass getTypeClass() const
Definition TypeBase.h:2433
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2459
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9261
bool isNullPtrType() const
Definition TypeBase.h:9071
bool isRecordType() const
Definition TypeBase.h:8795
bool isObjCRetainableType() const
Definition Type.cpp:5368
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5098
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2614
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2679
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3577
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2628
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
Expr * getSubExpr() const
Definition Expr.h:2288
Opcode getOpcode() const
Definition Expr.h:2283
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2365
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1033
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1121
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3402
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:5582
Represents a variable declaration or definition.
Definition Decl.h:926
Represents a GCC generic vector type.
Definition TypeBase.h:4225
unsigned getNumElements() const
Definition TypeBase.h:4240
QualType getElementType() const
Definition TypeBase.h:4239
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2698
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
std::optional< ConversionSpecifier > getStandardSpecifier() const
const OptionalAmount & getFieldWidth() const
bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const
const LengthModifier & getLengthModifier() const
bool hasValidLengthModifier(const TargetInfo &Target, const LangOptions &LO) const
std::optional< LengthModifier > getCorrectedLengthModifier() const
ArgType getArgType(ASTContext &Ctx) const
Class representing optional flags with location and representation information.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
const OptionalFlag & isPrivate() const
const OptionalAmount & getPrecision() const
const OptionalFlag & hasSpacePrefix() const
const OptionalFlag & isSensitive() const
const OptionalFlag & isLeftJustified() const
const OptionalFlag & hasLeadingZeros() const
const OptionalFlag & hasAlternativeForm() const
const PrintfConversionSpecifier & getConversionSpecifier() const
const OptionalFlag & hasPlusPrefix() const
const OptionalFlag & hasThousandsGrouping() const
ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const
Returns the builtin type that a data argument paired with this format specifier should have.
const OptionalFlag & isPublic() const
const ScanfConversionSpecifier & getConversionSpecifier() const
ArgType getArgType(ASTContext &Ctx) const
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition SPIR.cpp:35
Definition SPIR.cpp:47
Common components of both fprintf and fscanf format strings.
bool parseFormatStringHasFormattingSpecifiers(const char *Begin, const char *End, const LangOptions &LO, const TargetInfo &Target)
Return true if the given string has at least one formatting specifier.
bool ParsePrintfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target, bool isFreeBSDKPrintf)
bool ParseScanfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
bool ParseFormatStringHasSArg(const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
Pieces specific to fprintf format strings.
Pieces specific to fscanf format strings.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< PointerType > pointerType
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
ComparisonResult
Indicates the result of a tentative comparison.
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition Types.cpp:216
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ After
Like System, but searched after the system directories.
@ FixIt
Parse and apply any fixits to the source.
bool GT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1346
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1331
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1324
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1338
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2542
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1292
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1353
void checkCaptureByLifetime(Sema &SemaRef, const CapturingEntity &Entity, Expr *Init)
llvm::json::Array Array
llvm::json::Object Object
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:350
Expr * IgnoreExprNodes(Expr *E, FnTys &&... Fns)
Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *, Recursively apply each of the f...
Definition IgnoreExpr.h: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:149
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
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:124
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:257
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition JsonSupport.h:21
SemaARM::ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD)
Definition SemaARM.cpp:545
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
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:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
for(const auto &A :T->param_types())
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition IgnoreExpr.h:144
unsigned getFunctionOrMethodNumParams(const Decl *D)
getFunctionOrMethodNumParams - Return number of function or method parameters.
Definition Attr.h:64
StringLiteralKind
Definition Expr.h:1766
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_Win64
Definition Specifiers.h:285
@ CC_X86_64SysV
Definition Specifiers.h:286
@ Generic
not a target-specific vector type
Definition TypeBase.h:4186
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5977
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5970
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1761
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:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650
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:636
Extra information about a function prototype.
Definition TypeBase.h:5442
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:13317
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13343
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13333
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13284
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6890
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2655
#define log2(__x)
Definition tgmath.h:970