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 QualType EltTy = ArgTy;
2182 if (auto *VecTy = EltTy->getAs<VectorType>())
2183 EltTy = VecTy->getElementType();
2184
2185 switch (ArgTyRestr) {
2187 if (!ArgTy->getAs<VectorType>() && !isValidMathElementType(ArgTy)) {
2188 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2189 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2190 << ArgTy;
2191 }
2192 break;
2194 if (!EltTy->isRealFloatingType()) {
2195 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2196 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2197 << /* floating-point */ 1 << ArgTy;
2198 }
2199 break;
2201 if (!EltTy->isIntegerType()) {
2202 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2203 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2204 << /* no fp */ 0 << ArgTy;
2205 }
2206 break;
2208 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2209 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2210 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2211 << /* or fp */ 1 << ArgTy;
2212 }
2213 break;
2214 }
2215
2216 return false;
2217}
2218
2219/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2220/// This checks that the target supports the builtin and that the string
2221/// argument is constant and valid.
2222static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2223 const TargetInfo *AuxTI, unsigned BuiltinID) {
2224 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2225 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2226 "Expecting __builtin_cpu_...");
2227
2228 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2229 const TargetInfo *TheTI = &TI;
2230 auto SupportsBI = [=](const TargetInfo *TInfo) {
2231 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2232 (!IsCPUSupports && TInfo->supportsCpuIs()));
2233 };
2234 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2235 TheTI = AuxTI;
2236
2237 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2238 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2239 return S.Diag(TheCall->getBeginLoc(),
2240 TI.getTriple().isOSAIX()
2241 ? diag::err_builtin_aix_os_unsupported
2242 : diag::err_builtin_target_unsupported)
2243 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2244
2245 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2246 // Check if the argument is a string literal.
2247 if (!isa<StringLiteral>(Arg))
2248 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2249 << Arg->getSourceRange();
2250
2251 // Check the contents of the string.
2252 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2253 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2254 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2255 << Arg->getSourceRange();
2256 return false;
2257 }
2258 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2259 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2260 << Arg->getSourceRange();
2261 return false;
2262}
2263
2264/// Checks that __builtin_bswapg was called with a single argument, which is an
2265/// unsigned integer, and overrides the return value type to the integer type.
2266static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2267 if (S.checkArgCount(TheCall, 1))
2268 return true;
2269 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2270 if (ArgRes.isInvalid())
2271 return true;
2272
2273 Expr *Arg = ArgRes.get();
2274 TheCall->setArg(0, Arg);
2275 if (Arg->isTypeDependent())
2276 return false;
2277
2278 QualType ArgTy = Arg->getType();
2279
2280 if (!ArgTy->isIntegerType()) {
2281 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2282 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2283 << ArgTy;
2284 return true;
2285 }
2286 if (const auto *BT = dyn_cast<BitIntType>(ArgTy)) {
2287 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2288 BT->getNumBits() != 1) {
2289 S.Diag(Arg->getBeginLoc(), diag::err_bswapg_invalid_bit_width)
2290 << ArgTy << BT->getNumBits();
2291 return true;
2292 }
2293 }
2294 TheCall->setType(ArgTy);
2295 return false;
2296}
2297
2298/// Checks that __builtin_bitreverseg was called with a single argument, which
2299/// is an integer
2300static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2301 if (S.checkArgCount(TheCall, 1))
2302 return true;
2303 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2304 if (ArgRes.isInvalid())
2305 return true;
2306
2307 Expr *Arg = ArgRes.get();
2308 TheCall->setArg(0, Arg);
2309 if (Arg->isTypeDependent())
2310 return false;
2311
2312 QualType ArgTy = Arg->getType();
2313
2314 if (!ArgTy->isIntegerType()) {
2315 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2316 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2317 << ArgTy;
2318 return true;
2319 }
2320 TheCall->setType(ArgTy);
2321 return false;
2322}
2323
2324/// Checks that __builtin_popcountg was called with a single argument, which is
2325/// an unsigned integer.
2326static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2327 if (S.checkArgCount(TheCall, 1))
2328 return true;
2329
2330 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2331 if (ArgRes.isInvalid())
2332 return true;
2333
2334 Expr *Arg = ArgRes.get();
2335 TheCall->setArg(0, Arg);
2336
2337 QualType ArgTy = Arg->getType();
2338
2339 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2340 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2341 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2342 << ArgTy;
2343 return true;
2344 }
2345 return false;
2346}
2347
2348/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2349/// an unsigned integer, and an optional second argument, which is promoted to
2350/// an 'int'.
2351static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2352 if (S.checkArgCountRange(TheCall, 1, 2))
2353 return true;
2354
2355 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2356 if (Arg0Res.isInvalid())
2357 return true;
2358
2359 Expr *Arg0 = Arg0Res.get();
2360 TheCall->setArg(0, Arg0);
2361
2362 QualType Arg0Ty = Arg0->getType();
2363
2364 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2365 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2366 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2367 << Arg0Ty;
2368 return true;
2369 }
2370
2371 if (TheCall->getNumArgs() > 1) {
2372 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2373 if (Arg1Res.isInvalid())
2374 return true;
2375
2376 Expr *Arg1 = Arg1Res.get();
2377 TheCall->setArg(1, Arg1);
2378
2379 QualType Arg1Ty = Arg1->getType();
2380
2381 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2382 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2383 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2384 return true;
2385 }
2386 }
2387
2388 return false;
2389}
2390
2392 unsigned ArgIndex;
2393 bool OnlyUnsigned;
2394
2396 QualType T) {
2397 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2398 << ArgIndex << /*scalar*/ 1
2399 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2400 << /*no fp*/ 0 << T;
2401 }
2402
2403public:
2404 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2405 : ContextualImplicitConverter(/*Suppress=*/false,
2406 /*SuppressConversion=*/true),
2407 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2408
2409 bool match(QualType T) override {
2410 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2411 }
2412
2414 QualType T) override {
2415 return emitError(S, Loc, T);
2416 }
2417
2419 QualType T) override {
2420 return emitError(S, Loc, T);
2421 }
2422
2424 QualType T,
2425 QualType ConvTy) override {
2426 return emitError(S, Loc, T);
2427 }
2428
2430 QualType ConvTy) override {
2431 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2432 }
2433
2435 QualType T) override {
2436 return emitError(S, Loc, T);
2437 }
2438
2440 QualType ConvTy) override {
2441 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2442 }
2443
2445 QualType T,
2446 QualType ConvTy) override {
2447 llvm_unreachable("conversion functions are permitted");
2448 }
2449};
2450
2451/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2452/// arguments, that the first argument is an unsigned integer type, and that
2453/// the second argument is an integer type.
2454static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2455 if (S.checkArgCount(TheCall, 2))
2456 return true;
2457
2458 // First argument (value to rotate) must be unsigned integer type.
2459 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2461 TheCall->getArg(0)->getBeginLoc(), TheCall->getArg(0), Arg0Converter);
2462 if (Arg0Res.isInvalid())
2463 return true;
2464
2465 Expr *Arg0 = Arg0Res.get();
2466 TheCall->setArg(0, Arg0);
2467
2468 QualType Arg0Ty = Arg0->getType();
2469 if (!Arg0Ty->isUnsignedIntegerType())
2470 return true;
2471
2472 // Second argument (rotation count) must be integer type.
2473 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2475 TheCall->getArg(1)->getBeginLoc(), TheCall->getArg(1), Arg1Converter);
2476 if (Arg1Res.isInvalid())
2477 return true;
2478
2479 Expr *Arg1 = Arg1Res.get();
2480 TheCall->setArg(1, Arg1);
2481
2482 QualType Arg1Ty = Arg1->getType();
2483 if (!Arg1Ty->isIntegerType())
2484 return true;
2485
2486 TheCall->setType(Arg0Ty);
2487 return false;
2488}
2489
2490static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2491 unsigned Pos, bool AllowConst,
2492 bool AllowAS) {
2493 QualType MaskTy = MaskArg->getType();
2494 if (!MaskTy->isExtVectorBoolType())
2495 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2496 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2497 << MaskTy;
2498
2499 QualType PtrTy = PtrArg->getType();
2500 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2501 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2502 << Pos << "scalar pointer";
2503
2504 QualType PointeeTy = PtrTy->getPointeeType();
2505 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2506 (!AllowConst && PointeeTy.isConstQualified()) ||
2507 (!AllowAS && PointeeTy.hasAddressSpace())) {
2510 return S.Diag(PtrArg->getExprLoc(),
2511 diag::err_typecheck_convert_incompatible)
2512 << PtrTy << Target << /*different qualifiers=*/5
2513 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2514 << PtrTy << Target;
2515 }
2516 return false;
2517}
2518
2519static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2520 bool TypeDependent = false;
2521 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2522 ExprResult Converted =
2524 if (Converted.isInvalid())
2525 return true;
2526 TheCall->setArg(Arg, Converted.get());
2527 TypeDependent |= Converted.get()->isTypeDependent();
2528 }
2529
2530 if (TypeDependent)
2531 TheCall->setType(S.Context.DependentTy);
2532 return false;
2533}
2534
2536 if (S.checkArgCountRange(TheCall, 2, 3))
2537 return ExprError();
2538
2539 if (ConvertMaskedBuiltinArgs(S, TheCall))
2540 return ExprError();
2541
2542 Expr *MaskArg = TheCall->getArg(0);
2543 Expr *PtrArg = TheCall->getArg(1);
2544 if (TheCall->isTypeDependent())
2545 return TheCall;
2546
2547 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2548 TheCall->getBuiltinCallee() ==
2549 Builtin::BI__builtin_masked_load))
2550 return ExprError();
2551
2552 QualType MaskTy = MaskArg->getType();
2553 QualType PtrTy = PtrArg->getType();
2554 QualType PointeeTy = PtrTy->getPointeeType();
2555 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2556
2558 MaskVecTy->getNumElements());
2559 if (TheCall->getNumArgs() == 3) {
2560 Expr *PassThruArg = TheCall->getArg(2);
2561 QualType PassThruTy = PassThruArg->getType();
2562 if (!S.Context.hasSameType(PassThruTy, RetTy))
2563 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2564 << /* third argument */ 3 << RetTy;
2565 }
2566
2567 TheCall->setType(RetTy);
2568 return TheCall;
2569}
2570
2572 if (S.checkArgCount(TheCall, 3))
2573 return ExprError();
2574
2575 if (ConvertMaskedBuiltinArgs(S, TheCall))
2576 return ExprError();
2577
2578 Expr *MaskArg = TheCall->getArg(0);
2579 Expr *ValArg = TheCall->getArg(1);
2580 Expr *PtrArg = TheCall->getArg(2);
2581 if (TheCall->isTypeDependent())
2582 return TheCall;
2583
2584 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2585 TheCall->getBuiltinCallee() ==
2586 Builtin::BI__builtin_masked_store))
2587 return ExprError();
2588
2589 QualType MaskTy = MaskArg->getType();
2590 QualType PtrTy = PtrArg->getType();
2591 QualType ValTy = ValArg->getType();
2592 if (!ValTy->isVectorType())
2593 return ExprError(
2594 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2595 << 2 << "vector");
2596
2597 QualType PointeeTy = PtrTy->getPointeeType();
2598 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2599 QualType MemoryTy = S.Context.getExtVectorType(PointeeTy.getUnqualifiedType(),
2600 MaskVecTy->getNumElements());
2601 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(),
2602 MemoryTy.getUnqualifiedType()))
2603 return ExprError(S.Diag(TheCall->getBeginLoc(),
2604 diag::err_vec_builtin_incompatible_vector)
2605 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2606 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2607 TheCall->getArg(1)->getEndLoc()));
2608
2609 TheCall->setType(S.Context.VoidTy);
2610 return TheCall;
2611}
2612
2614 if (S.checkArgCountRange(TheCall, 3, 4))
2615 return ExprError();
2616
2617 if (ConvertMaskedBuiltinArgs(S, TheCall))
2618 return ExprError();
2619
2620 Expr *MaskArg = TheCall->getArg(0);
2621 Expr *IdxArg = TheCall->getArg(1);
2622 Expr *PtrArg = TheCall->getArg(2);
2623 if (TheCall->isTypeDependent())
2624 return TheCall;
2625
2626 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
2627 /*AllowAS=*/true))
2628 return ExprError();
2629
2630 QualType IdxTy = IdxArg->getType();
2631 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2632 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2633 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2634 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2635 << IdxTy;
2636
2637 QualType MaskTy = MaskArg->getType();
2638 QualType PtrTy = PtrArg->getType();
2639 QualType PointeeTy = PtrTy->getPointeeType();
2640 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2641 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2642 return ExprError(
2643 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2645 TheCall->getBuiltinCallee())
2646 << MaskTy << IdxTy);
2647
2649 MaskVecTy->getNumElements());
2650 if (TheCall->getNumArgs() == 4) {
2651 Expr *PassThruArg = TheCall->getArg(3);
2652 QualType PassThruTy = PassThruArg->getType();
2653 if (!S.Context.hasSameType(PassThruTy, RetTy))
2654 return S.Diag(PassThruArg->getExprLoc(),
2655 diag::err_vec_masked_load_store_ptr)
2656 << /* fourth argument */ 4 << RetTy;
2657 }
2658
2659 TheCall->setType(RetTy);
2660 return TheCall;
2661}
2662
2664 if (S.checkArgCount(TheCall, 4))
2665 return ExprError();
2666
2667 if (ConvertMaskedBuiltinArgs(S, TheCall))
2668 return ExprError();
2669
2670 Expr *MaskArg = TheCall->getArg(0);
2671 Expr *IdxArg = TheCall->getArg(1);
2672 Expr *ValArg = TheCall->getArg(2);
2673 Expr *PtrArg = TheCall->getArg(3);
2674 if (TheCall->isTypeDependent())
2675 return TheCall;
2676
2677 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
2678 /*AllowAS=*/true))
2679 return ExprError();
2680
2681 QualType IdxTy = IdxArg->getType();
2682 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2683 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2684 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2685 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2686 << IdxTy;
2687
2688 QualType ValTy = ValArg->getType();
2689 QualType MaskTy = MaskArg->getType();
2690 QualType PtrTy = PtrArg->getType();
2691 QualType PointeeTy = PtrTy->getPointeeType();
2692
2693 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2694 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2695 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2696 return ExprError(
2697 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2699 TheCall->getBuiltinCallee())
2700 << MaskTy << IdxTy);
2701 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2702 return ExprError(
2703 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2705 TheCall->getBuiltinCallee())
2706 << MaskTy << ValTy);
2707
2709 MaskVecTy->getNumElements());
2710 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(), ArgTy))
2711 return ExprError(S.Diag(TheCall->getBeginLoc(),
2712 diag::err_vec_builtin_incompatible_vector)
2713 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2714 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2715 TheCall->getArg(1)->getEndLoc()));
2716
2717 TheCall->setType(S.Context.VoidTy);
2718 return TheCall;
2719}
2720
2722 SourceLocation Loc = TheCall->getBeginLoc();
2723 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2724 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2725
2726 if (Args.size() == 0) {
2727 S.Diag(TheCall->getBeginLoc(),
2728 diag::err_typecheck_call_too_few_args_at_least)
2729 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2730 << /*is_non_object=*/0 << TheCall->getSourceRange();
2731 return ExprError();
2732 }
2733
2734 QualType FuncT = Args[0]->getType();
2735
2736 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2737 if (Args.size() < 2) {
2738 S.Diag(TheCall->getBeginLoc(),
2739 diag::err_typecheck_call_too_few_args_at_least)
2740 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2741 << /*is_non_object=*/0 << TheCall->getSourceRange();
2742 return ExprError();
2743 }
2744
2745 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2746 QualType ObjectT = Args[1]->getType();
2747
2748 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
2749 return ExprError();
2750
2751 ExprResult ObjectArg = [&]() -> ExprResult {
2752 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2753 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2754 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2755 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2756 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2757 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2758 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
2759 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
2760 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
2761 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
2762 return Args[1];
2763 }
2764
2765 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2766 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2767 // reference_wrapper;
2768 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2769 if (RD->isInStdNamespace() &&
2770 RD->getDeclName().getAsString() == "reference_wrapper") {
2771 CXXScopeSpec SS;
2772 IdentifierInfo *GetName = &S.Context.Idents.get("get");
2773 UnqualifiedId GetID;
2774 GetID.setIdentifier(GetName, Loc);
2775
2777 S.getCurScope(), Args[1], Loc, tok::period, SS,
2778 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
2779
2780 if (MemExpr.isInvalid())
2781 return ExprError();
2782
2783 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
2784 }
2785 }
2786
2787 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
2788 // class T and t1 does not satisfy the previous two items;
2789
2790 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
2791 }();
2792
2793 if (ObjectArg.isInvalid())
2794 return ExprError();
2795
2796 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
2797 tok::periodstar, ObjectArg.get(), Args[0]);
2798 if (BinOp.isInvalid())
2799 return ExprError();
2800
2801 if (MPT->isMemberDataPointer())
2802 return BinOp;
2803
2804 auto *MemCall = new (S.Context)
2806
2807 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
2808 Args.drop_front(2), TheCall->getRParenLoc());
2809 }
2810 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
2811 Args.drop_front(), TheCall->getRParenLoc());
2812}
2813
2814// Performs a similar job to Sema::UsualUnaryConversions, but without any
2815// implicit promotion of integral/enumeration types.
2817 // First, convert to an r-value.
2819 if (Res.isInvalid())
2820 return ExprError();
2821
2822 // Promote floating-point types.
2823 return S.UsualUnaryFPConversions(Res.get());
2824}
2825
2827 if (const auto *TyA = VecTy->getAs<VectorType>())
2828 return TyA->getElementType();
2829 if (VecTy->isSizelessVectorType())
2830 return VecTy->getSizelessVectorEltType(Context);
2831 return QualType();
2832}
2833
2835Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2836 CallExpr *TheCall) {
2837 ExprResult TheCallResult(TheCall);
2838
2839 // Find out if any arguments are required to be integer constant expressions.
2840 unsigned ICEArguments = 0;
2842 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2844 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2845
2846 // If any arguments are required to be ICE's, check and diagnose.
2847 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2848 // Skip arguments not required to be ICE's.
2849 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2850
2851 llvm::APSInt Result;
2852 // If we don't have enough arguments, continue so we can issue better
2853 // diagnostic in checkArgCount(...)
2854 if (ArgNo < TheCall->getNumArgs() &&
2855 BuiltinConstantArg(TheCall, ArgNo, Result))
2856 return true;
2857 ICEArguments &= ~(1 << ArgNo);
2858 }
2859
2860 FPOptions FPO;
2861 switch (BuiltinID) {
2862 case Builtin::BI__builtin_cpu_supports:
2863 case Builtin::BI__builtin_cpu_is:
2864 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2865 Context.getAuxTargetInfo(), BuiltinID))
2866 return ExprError();
2867 break;
2868 case Builtin::BI__builtin_cpu_init:
2869 if (!Context.getTargetInfo().supportsCpuInit()) {
2870 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2871 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2872 return ExprError();
2873 }
2874 break;
2875 case Builtin::BI__builtin___CFStringMakeConstantString:
2876 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2877 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2879 *this, BuiltinID, TheCall,
2880 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2881 return ExprError();
2882 assert(TheCall->getNumArgs() == 1 &&
2883 "Wrong # arguments to builtin CFStringMakeConstantString");
2884 if (ObjC().CheckObjCString(TheCall->getArg(0)))
2885 return ExprError();
2886 break;
2887 case Builtin::BI__builtin_ms_va_start:
2888 case Builtin::BI__builtin_stdarg_start:
2889 case Builtin::BI__builtin_va_start:
2890 case Builtin::BI__builtin_c23_va_start:
2891 if (BuiltinVAStart(BuiltinID, TheCall))
2892 return ExprError();
2893 break;
2894 case Builtin::BI__va_start: {
2895 switch (Context.getTargetInfo().getTriple().getArch()) {
2896 case llvm::Triple::aarch64:
2897 case llvm::Triple::arm:
2898 case llvm::Triple::thumb:
2899 if (BuiltinVAStartARMMicrosoft(TheCall))
2900 return ExprError();
2901 break;
2902 default:
2903 if (BuiltinVAStart(BuiltinID, TheCall))
2904 return ExprError();
2905 break;
2906 }
2907 break;
2908 }
2909
2910 // The acquire, release, and no fence variants are ARM and AArch64 only.
2911 case Builtin::BI_interlockedbittestandset_acq:
2912 case Builtin::BI_interlockedbittestandset_rel:
2913 case Builtin::BI_interlockedbittestandset_nf:
2914 case Builtin::BI_interlockedbittestandreset_acq:
2915 case Builtin::BI_interlockedbittestandreset_rel:
2916 case Builtin::BI_interlockedbittestandreset_nf:
2918 *this, TheCall,
2919 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2920 return ExprError();
2921 break;
2922
2923 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2924 case Builtin::BI_bittest64:
2925 case Builtin::BI_bittestandcomplement64:
2926 case Builtin::BI_bittestandreset64:
2927 case Builtin::BI_bittestandset64:
2928 case Builtin::BI_interlockedbittestandreset64:
2929 case Builtin::BI_interlockedbittestandset64:
2931 *this, TheCall,
2932 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2933 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2934 return ExprError();
2935 break;
2936
2937 // The 64-bit acquire, release, and no fence variants are AArch64 only.
2938 case Builtin::BI_interlockedbittestandreset64_acq:
2939 case Builtin::BI_interlockedbittestandreset64_rel:
2940 case Builtin::BI_interlockedbittestandreset64_nf:
2941 case Builtin::BI_interlockedbittestandset64_acq:
2942 case Builtin::BI_interlockedbittestandset64_rel:
2943 case Builtin::BI_interlockedbittestandset64_nf:
2944 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
2945 return ExprError();
2946 break;
2947
2948 case Builtin::BI__builtin_set_flt_rounds:
2950 *this, TheCall,
2951 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
2952 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
2953 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
2954 llvm::Triple::ppc64le}))
2955 return ExprError();
2956 break;
2957
2958 case Builtin::BI__builtin_isgreater:
2959 case Builtin::BI__builtin_isgreaterequal:
2960 case Builtin::BI__builtin_isless:
2961 case Builtin::BI__builtin_islessequal:
2962 case Builtin::BI__builtin_islessgreater:
2963 case Builtin::BI__builtin_isunordered:
2964 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2965 return ExprError();
2966 break;
2967 case Builtin::BI__builtin_fpclassify:
2968 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
2969 return ExprError();
2970 break;
2971 case Builtin::BI__builtin_isfpclass:
2972 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
2973 return ExprError();
2974 break;
2975 case Builtin::BI__builtin_isfinite:
2976 case Builtin::BI__builtin_isinf:
2977 case Builtin::BI__builtin_isinf_sign:
2978 case Builtin::BI__builtin_isnan:
2979 case Builtin::BI__builtin_issignaling:
2980 case Builtin::BI__builtin_isnormal:
2981 case Builtin::BI__builtin_issubnormal:
2982 case Builtin::BI__builtin_iszero:
2983 case Builtin::BI__builtin_signbit:
2984 case Builtin::BI__builtin_signbitf:
2985 case Builtin::BI__builtin_signbitl:
2986 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
2987 return ExprError();
2988 break;
2989 case Builtin::BI__builtin_shufflevector:
2990 return BuiltinShuffleVector(TheCall);
2991 // TheCall will be freed by the smart pointer here, but that's fine, since
2992 // BuiltinShuffleVector guts it, but then doesn't release it.
2993 case Builtin::BI__builtin_masked_load:
2994 case Builtin::BI__builtin_masked_expand_load:
2995 return BuiltinMaskedLoad(*this, TheCall);
2996 case Builtin::BI__builtin_masked_store:
2997 case Builtin::BI__builtin_masked_compress_store:
2998 return BuiltinMaskedStore(*this, TheCall);
2999 case Builtin::BI__builtin_masked_gather:
3000 return BuiltinMaskedGather(*this, TheCall);
3001 case Builtin::BI__builtin_masked_scatter:
3002 return BuiltinMaskedScatter(*this, TheCall);
3003 case Builtin::BI__builtin_invoke:
3004 return BuiltinInvoke(*this, TheCall);
3005 case Builtin::BI__builtin_prefetch:
3006 if (BuiltinPrefetch(TheCall))
3007 return ExprError();
3008 break;
3009 case Builtin::BI__builtin_alloca_with_align:
3010 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3011 if (BuiltinAllocaWithAlign(TheCall))
3012 return ExprError();
3013 [[fallthrough]];
3014 case Builtin::BI__builtin_alloca:
3015 case Builtin::BI__builtin_alloca_uninitialized:
3016 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
3017 << TheCall->getDirectCallee();
3018 if (getLangOpts().OpenCL) {
3019 builtinAllocaAddrSpace(*this, TheCall);
3020 }
3021 break;
3022 case Builtin::BI__builtin_infer_alloc_token:
3023 if (checkBuiltinInferAllocToken(*this, TheCall))
3024 return ExprError();
3025 break;
3026 case Builtin::BI__arithmetic_fence:
3027 if (BuiltinArithmeticFence(TheCall))
3028 return ExprError();
3029 break;
3030 case Builtin::BI__assume:
3031 case Builtin::BI__builtin_assume:
3032 if (BuiltinAssume(TheCall))
3033 return ExprError();
3034 break;
3035 case Builtin::BI__builtin_assume_aligned:
3036 if (BuiltinAssumeAligned(TheCall))
3037 return ExprError();
3038 break;
3039 case Builtin::BI__builtin_dynamic_object_size:
3040 case Builtin::BI__builtin_object_size:
3041 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
3042 return ExprError();
3043 break;
3044 case Builtin::BI__builtin_longjmp:
3045 if (BuiltinLongjmp(TheCall))
3046 return ExprError();
3047 break;
3048 case Builtin::BI__builtin_setjmp:
3049 if (BuiltinSetjmp(TheCall))
3050 return ExprError();
3051 break;
3052 case Builtin::BI__builtin_classify_type:
3053 if (checkArgCount(TheCall, 1))
3054 return true;
3055 TheCall->setType(Context.IntTy);
3056 break;
3057 case Builtin::BI__builtin_complex:
3058 if (BuiltinComplex(TheCall))
3059 return ExprError();
3060 break;
3061 case Builtin::BI__builtin_constant_p: {
3062 if (checkArgCount(TheCall, 1))
3063 return true;
3065 if (Arg.isInvalid()) return true;
3066 TheCall->setArg(0, Arg.get());
3067 TheCall->setType(Context.IntTy);
3068 break;
3069 }
3070 case Builtin::BI__builtin_launder:
3071 return BuiltinLaunder(*this, TheCall);
3072 case Builtin::BI__builtin_is_within_lifetime:
3073 return BuiltinIsWithinLifetime(*this, TheCall);
3074 case Builtin::BI__builtin_trivially_relocate:
3075 return BuiltinTriviallyRelocate(*this, TheCall);
3076
3077 case Builtin::BI__sync_fetch_and_add:
3078 case Builtin::BI__sync_fetch_and_add_1:
3079 case Builtin::BI__sync_fetch_and_add_2:
3080 case Builtin::BI__sync_fetch_and_add_4:
3081 case Builtin::BI__sync_fetch_and_add_8:
3082 case Builtin::BI__sync_fetch_and_add_16:
3083 case Builtin::BI__sync_fetch_and_sub:
3084 case Builtin::BI__sync_fetch_and_sub_1:
3085 case Builtin::BI__sync_fetch_and_sub_2:
3086 case Builtin::BI__sync_fetch_and_sub_4:
3087 case Builtin::BI__sync_fetch_and_sub_8:
3088 case Builtin::BI__sync_fetch_and_sub_16:
3089 case Builtin::BI__sync_fetch_and_or:
3090 case Builtin::BI__sync_fetch_and_or_1:
3091 case Builtin::BI__sync_fetch_and_or_2:
3092 case Builtin::BI__sync_fetch_and_or_4:
3093 case Builtin::BI__sync_fetch_and_or_8:
3094 case Builtin::BI__sync_fetch_and_or_16:
3095 case Builtin::BI__sync_fetch_and_and:
3096 case Builtin::BI__sync_fetch_and_and_1:
3097 case Builtin::BI__sync_fetch_and_and_2:
3098 case Builtin::BI__sync_fetch_and_and_4:
3099 case Builtin::BI__sync_fetch_and_and_8:
3100 case Builtin::BI__sync_fetch_and_and_16:
3101 case Builtin::BI__sync_fetch_and_xor:
3102 case Builtin::BI__sync_fetch_and_xor_1:
3103 case Builtin::BI__sync_fetch_and_xor_2:
3104 case Builtin::BI__sync_fetch_and_xor_4:
3105 case Builtin::BI__sync_fetch_and_xor_8:
3106 case Builtin::BI__sync_fetch_and_xor_16:
3107 case Builtin::BI__sync_fetch_and_nand:
3108 case Builtin::BI__sync_fetch_and_nand_1:
3109 case Builtin::BI__sync_fetch_and_nand_2:
3110 case Builtin::BI__sync_fetch_and_nand_4:
3111 case Builtin::BI__sync_fetch_and_nand_8:
3112 case Builtin::BI__sync_fetch_and_nand_16:
3113 case Builtin::BI__sync_add_and_fetch:
3114 case Builtin::BI__sync_add_and_fetch_1:
3115 case Builtin::BI__sync_add_and_fetch_2:
3116 case Builtin::BI__sync_add_and_fetch_4:
3117 case Builtin::BI__sync_add_and_fetch_8:
3118 case Builtin::BI__sync_add_and_fetch_16:
3119 case Builtin::BI__sync_sub_and_fetch:
3120 case Builtin::BI__sync_sub_and_fetch_1:
3121 case Builtin::BI__sync_sub_and_fetch_2:
3122 case Builtin::BI__sync_sub_and_fetch_4:
3123 case Builtin::BI__sync_sub_and_fetch_8:
3124 case Builtin::BI__sync_sub_and_fetch_16:
3125 case Builtin::BI__sync_and_and_fetch:
3126 case Builtin::BI__sync_and_and_fetch_1:
3127 case Builtin::BI__sync_and_and_fetch_2:
3128 case Builtin::BI__sync_and_and_fetch_4:
3129 case Builtin::BI__sync_and_and_fetch_8:
3130 case Builtin::BI__sync_and_and_fetch_16:
3131 case Builtin::BI__sync_or_and_fetch:
3132 case Builtin::BI__sync_or_and_fetch_1:
3133 case Builtin::BI__sync_or_and_fetch_2:
3134 case Builtin::BI__sync_or_and_fetch_4:
3135 case Builtin::BI__sync_or_and_fetch_8:
3136 case Builtin::BI__sync_or_and_fetch_16:
3137 case Builtin::BI__sync_xor_and_fetch:
3138 case Builtin::BI__sync_xor_and_fetch_1:
3139 case Builtin::BI__sync_xor_and_fetch_2:
3140 case Builtin::BI__sync_xor_and_fetch_4:
3141 case Builtin::BI__sync_xor_and_fetch_8:
3142 case Builtin::BI__sync_xor_and_fetch_16:
3143 case Builtin::BI__sync_nand_and_fetch:
3144 case Builtin::BI__sync_nand_and_fetch_1:
3145 case Builtin::BI__sync_nand_and_fetch_2:
3146 case Builtin::BI__sync_nand_and_fetch_4:
3147 case Builtin::BI__sync_nand_and_fetch_8:
3148 case Builtin::BI__sync_nand_and_fetch_16:
3149 case Builtin::BI__sync_val_compare_and_swap:
3150 case Builtin::BI__sync_val_compare_and_swap_1:
3151 case Builtin::BI__sync_val_compare_and_swap_2:
3152 case Builtin::BI__sync_val_compare_and_swap_4:
3153 case Builtin::BI__sync_val_compare_and_swap_8:
3154 case Builtin::BI__sync_val_compare_and_swap_16:
3155 case Builtin::BI__sync_bool_compare_and_swap:
3156 case Builtin::BI__sync_bool_compare_and_swap_1:
3157 case Builtin::BI__sync_bool_compare_and_swap_2:
3158 case Builtin::BI__sync_bool_compare_and_swap_4:
3159 case Builtin::BI__sync_bool_compare_and_swap_8:
3160 case Builtin::BI__sync_bool_compare_and_swap_16:
3161 case Builtin::BI__sync_lock_test_and_set:
3162 case Builtin::BI__sync_lock_test_and_set_1:
3163 case Builtin::BI__sync_lock_test_and_set_2:
3164 case Builtin::BI__sync_lock_test_and_set_4:
3165 case Builtin::BI__sync_lock_test_and_set_8:
3166 case Builtin::BI__sync_lock_test_and_set_16:
3167 case Builtin::BI__sync_lock_release:
3168 case Builtin::BI__sync_lock_release_1:
3169 case Builtin::BI__sync_lock_release_2:
3170 case Builtin::BI__sync_lock_release_4:
3171 case Builtin::BI__sync_lock_release_8:
3172 case Builtin::BI__sync_lock_release_16:
3173 case Builtin::BI__sync_swap:
3174 case Builtin::BI__sync_swap_1:
3175 case Builtin::BI__sync_swap_2:
3176 case Builtin::BI__sync_swap_4:
3177 case Builtin::BI__sync_swap_8:
3178 case Builtin::BI__sync_swap_16:
3179 return BuiltinAtomicOverloaded(TheCallResult);
3180 case Builtin::BI__sync_synchronize:
3181 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
3182 << TheCall->getCallee()->getSourceRange();
3183 break;
3184 case Builtin::BI__builtin_nontemporal_load:
3185 case Builtin::BI__builtin_nontemporal_store:
3186 return BuiltinNontemporalOverloaded(TheCallResult);
3187 case Builtin::BI__builtin_memcpy_inline: {
3188 clang::Expr *SizeOp = TheCall->getArg(2);
3189 // We warn about copying to or from `nullptr` pointers when `size` is
3190 // greater than 0. When `size` is value dependent we cannot evaluate its
3191 // value so we bail out.
3192 if (SizeOp->isValueDependent())
3193 break;
3194 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
3195 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3196 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
3197 }
3198 break;
3199 }
3200 case Builtin::BI__builtin_memset_inline: {
3201 clang::Expr *SizeOp = TheCall->getArg(2);
3202 // We warn about filling to `nullptr` pointers when `size` is greater than
3203 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3204 // out.
3205 if (SizeOp->isValueDependent())
3206 break;
3207 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
3208 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3209 break;
3210 }
3211#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3212 case Builtin::BI##ID: \
3213 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3214#include "clang/Basic/Builtins.inc"
3215 case Builtin::BI__annotation:
3216 if (BuiltinMSVCAnnotation(*this, TheCall))
3217 return ExprError();
3218 break;
3219 case Builtin::BI__builtin_annotation:
3220 if (BuiltinAnnotation(*this, TheCall))
3221 return ExprError();
3222 break;
3223 case Builtin::BI__builtin_addressof:
3224 if (BuiltinAddressof(*this, TheCall))
3225 return ExprError();
3226 break;
3227 case Builtin::BI__builtin_function_start:
3228 if (BuiltinFunctionStart(*this, TheCall))
3229 return ExprError();
3230 break;
3231 case Builtin::BI__builtin_is_aligned:
3232 case Builtin::BI__builtin_align_up:
3233 case Builtin::BI__builtin_align_down:
3234 if (BuiltinAlignment(*this, TheCall, BuiltinID))
3235 return ExprError();
3236 break;
3237 case Builtin::BI__builtin_add_overflow:
3238 case Builtin::BI__builtin_sub_overflow:
3239 case Builtin::BI__builtin_mul_overflow:
3240 if (BuiltinOverflow(*this, TheCall, BuiltinID))
3241 return ExprError();
3242 break;
3243 case Builtin::BI__builtin_operator_new:
3244 case Builtin::BI__builtin_operator_delete: {
3245 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3246 ExprResult Res =
3247 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3248 return Res;
3249 }
3250 case Builtin::BI__builtin_dump_struct:
3251 return BuiltinDumpStruct(*this, TheCall);
3252 case Builtin::BI__builtin_expect_with_probability: {
3253 // We first want to ensure we are called with 3 arguments
3254 if (checkArgCount(TheCall, 3))
3255 return ExprError();
3256 // then check probability is constant float in range [0.0, 1.0]
3257 const Expr *ProbArg = TheCall->getArg(2);
3258 SmallVector<PartialDiagnosticAt, 8> Notes;
3259 Expr::EvalResult Eval;
3260 Eval.Diag = &Notes;
3261 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3262 !Eval.Val.isFloat()) {
3263 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3264 << ProbArg->getSourceRange();
3265 for (const PartialDiagnosticAt &PDiag : Notes)
3266 Diag(PDiag.first, PDiag.second);
3267 return ExprError();
3268 }
3269 llvm::APFloat Probability = Eval.Val.getFloat();
3270 bool LoseInfo = false;
3271 Probability.convert(llvm::APFloat::IEEEdouble(),
3272 llvm::RoundingMode::Dynamic, &LoseInfo);
3273 if (!(Probability >= llvm::APFloat(0.0) &&
3274 Probability <= llvm::APFloat(1.0))) {
3275 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3276 << ProbArg->getSourceRange();
3277 return ExprError();
3278 }
3279 break;
3280 }
3281 case Builtin::BI__builtin_preserve_access_index:
3282 if (BuiltinPreserveAI(*this, TheCall))
3283 return ExprError();
3284 break;
3285 case Builtin::BI__builtin_call_with_static_chain:
3286 if (BuiltinCallWithStaticChain(*this, TheCall))
3287 return ExprError();
3288 break;
3289 case Builtin::BI__exception_code:
3290 case Builtin::BI_exception_code:
3291 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3292 diag::err_seh___except_block))
3293 return ExprError();
3294 break;
3295 case Builtin::BI__exception_info:
3296 case Builtin::BI_exception_info:
3297 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3298 diag::err_seh___except_filter))
3299 return ExprError();
3300 break;
3301 case Builtin::BI__GetExceptionInfo:
3302 if (checkArgCount(TheCall, 1))
3303 return ExprError();
3304
3306 TheCall->getBeginLoc(),
3307 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3308 TheCall))
3309 return ExprError();
3310
3311 TheCall->setType(Context.VoidPtrTy);
3312 break;
3313 case Builtin::BIaddressof:
3314 case Builtin::BI__addressof:
3315 case Builtin::BIforward:
3316 case Builtin::BIforward_like:
3317 case Builtin::BImove:
3318 case Builtin::BImove_if_noexcept:
3319 case Builtin::BIas_const: {
3320 // These are all expected to be of the form
3321 // T &/&&/* f(U &/&&)
3322 // where T and U only differ in qualification.
3323 if (checkArgCount(TheCall, 1))
3324 return ExprError();
3325 QualType Param = FDecl->getParamDecl(0)->getType();
3326 QualType Result = FDecl->getReturnType();
3327 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3328 BuiltinID == Builtin::BI__addressof;
3329 if (!(Param->isReferenceType() &&
3330 (ReturnsPointer ? Result->isAnyPointerType()
3331 : Result->isReferenceType()) &&
3332 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3333 Result->getPointeeType()))) {
3334 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3335 << FDecl;
3336 return ExprError();
3337 }
3338 break;
3339 }
3340 case Builtin::BI__builtin_ptrauth_strip:
3341 return PointerAuthStrip(*this, TheCall);
3342 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3343 return PointerAuthBlendDiscriminator(*this, TheCall);
3344 case Builtin::BI__builtin_ptrauth_sign_constant:
3345 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3346 /*RequireConstant=*/true);
3347 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3348 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3349 /*RequireConstant=*/false);
3350 case Builtin::BI__builtin_ptrauth_auth:
3351 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3352 /*RequireConstant=*/false);
3353 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3354 return PointerAuthSignGenericData(*this, TheCall);
3355 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3356 return PointerAuthAuthAndResign(*this, TheCall);
3357 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3358 return PointerAuthAuthLoadRelativeAndSign(*this, TheCall);
3359 case Builtin::BI__builtin_ptrauth_string_discriminator:
3360 return PointerAuthStringDiscriminator(*this, TheCall);
3361
3362 case Builtin::BI__builtin_get_vtable_pointer:
3363 return GetVTablePointer(*this, TheCall);
3364
3365 // OpenCL v2.0, s6.13.16 - Pipe functions
3366 case Builtin::BIread_pipe:
3367 case Builtin::BIwrite_pipe:
3368 // Since those two functions are declared with var args, we need a semantic
3369 // check for the argument.
3370 if (OpenCL().checkBuiltinRWPipe(TheCall))
3371 return ExprError();
3372 break;
3373 case Builtin::BIreserve_read_pipe:
3374 case Builtin::BIreserve_write_pipe:
3375 case Builtin::BIwork_group_reserve_read_pipe:
3376 case Builtin::BIwork_group_reserve_write_pipe:
3377 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3378 return ExprError();
3379 break;
3380 case Builtin::BIsub_group_reserve_read_pipe:
3381 case Builtin::BIsub_group_reserve_write_pipe:
3382 if (OpenCL().checkSubgroupExt(TheCall) ||
3383 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3384 return ExprError();
3385 break;
3386 case Builtin::BIcommit_read_pipe:
3387 case Builtin::BIcommit_write_pipe:
3388 case Builtin::BIwork_group_commit_read_pipe:
3389 case Builtin::BIwork_group_commit_write_pipe:
3390 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3391 return ExprError();
3392 break;
3393 case Builtin::BIsub_group_commit_read_pipe:
3394 case Builtin::BIsub_group_commit_write_pipe:
3395 if (OpenCL().checkSubgroupExt(TheCall) ||
3396 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3397 return ExprError();
3398 break;
3399 case Builtin::BIget_pipe_num_packets:
3400 case Builtin::BIget_pipe_max_packets:
3401 if (OpenCL().checkBuiltinPipePackets(TheCall))
3402 return ExprError();
3403 break;
3404 case Builtin::BIto_global:
3405 case Builtin::BIto_local:
3406 case Builtin::BIto_private:
3407 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3408 return ExprError();
3409 break;
3410 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3411 case Builtin::BIenqueue_kernel:
3412 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3413 return ExprError();
3414 break;
3415 case Builtin::BIget_kernel_work_group_size:
3416 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3417 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3418 return ExprError();
3419 break;
3420 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3421 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3422 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3423 return ExprError();
3424 break;
3425 case Builtin::BI__builtin_os_log_format:
3426 Cleanup.setExprNeedsCleanups(true);
3427 [[fallthrough]];
3428 case Builtin::BI__builtin_os_log_format_buffer_size:
3429 if (BuiltinOSLogFormat(TheCall))
3430 return ExprError();
3431 break;
3432 case Builtin::BI__builtin_frame_address:
3433 case Builtin::BI__builtin_return_address: {
3434 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3435 return ExprError();
3436
3437 // -Wframe-address warning if non-zero passed to builtin
3438 // return/frame address.
3439 Expr::EvalResult Result;
3440 if (!TheCall->getArg(0)->isValueDependent() &&
3441 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3442 Result.Val.getInt() != 0)
3443 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3444 << ((BuiltinID == Builtin::BI__builtin_return_address)
3445 ? "__builtin_return_address"
3446 : "__builtin_frame_address")
3447 << TheCall->getSourceRange();
3448 break;
3449 }
3450
3451 case Builtin::BI__builtin_nondeterministic_value: {
3452 if (BuiltinNonDeterministicValue(TheCall))
3453 return ExprError();
3454 break;
3455 }
3456
3457 // __builtin_elementwise_abs restricts the element type to signed integers or
3458 // floating point types only.
3459 case Builtin::BI__builtin_elementwise_abs:
3462 return ExprError();
3463 break;
3464
3465 // These builtins restrict the element type to floating point
3466 // types only.
3467 case Builtin::BI__builtin_elementwise_acos:
3468 case Builtin::BI__builtin_elementwise_asin:
3469 case Builtin::BI__builtin_elementwise_atan:
3470 case Builtin::BI__builtin_elementwise_ceil:
3471 case Builtin::BI__builtin_elementwise_cos:
3472 case Builtin::BI__builtin_elementwise_cosh:
3473 case Builtin::BI__builtin_elementwise_exp:
3474 case Builtin::BI__builtin_elementwise_exp2:
3475 case Builtin::BI__builtin_elementwise_exp10:
3476 case Builtin::BI__builtin_elementwise_floor:
3477 case Builtin::BI__builtin_elementwise_log:
3478 case Builtin::BI__builtin_elementwise_log2:
3479 case Builtin::BI__builtin_elementwise_log10:
3480 case Builtin::BI__builtin_elementwise_roundeven:
3481 case Builtin::BI__builtin_elementwise_round:
3482 case Builtin::BI__builtin_elementwise_rint:
3483 case Builtin::BI__builtin_elementwise_nearbyint:
3484 case Builtin::BI__builtin_elementwise_sin:
3485 case Builtin::BI__builtin_elementwise_sinh:
3486 case Builtin::BI__builtin_elementwise_sqrt:
3487 case Builtin::BI__builtin_elementwise_tan:
3488 case Builtin::BI__builtin_elementwise_tanh:
3489 case Builtin::BI__builtin_elementwise_trunc:
3490 case Builtin::BI__builtin_elementwise_canonicalize:
3493 return ExprError();
3494 break;
3495 case Builtin::BI__builtin_elementwise_fma:
3496 if (BuiltinElementwiseTernaryMath(TheCall))
3497 return ExprError();
3498 break;
3499
3500 case Builtin::BI__builtin_elementwise_ldexp: {
3501 if (checkArgCount(TheCall, 2))
3502 return ExprError();
3503
3504 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
3505 if (A.isInvalid())
3506 return ExprError();
3507 QualType TyA = A.get()->getType();
3508 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
3510 return ExprError();
3511
3512 ExprResult Exp = UsualUnaryConversions(TheCall->getArg(1));
3513 if (Exp.isInvalid())
3514 return ExprError();
3515 QualType TyExp = Exp.get()->getType();
3516 if (checkMathBuiltinElementType(*this, Exp.get()->getBeginLoc(), TyExp,
3518 2))
3519 return ExprError();
3520
3521 // Check the two arguments are either scalars or vectors of equal length.
3522 const auto *Vec0 = TyA->getAs<VectorType>();
3523 const auto *Vec1 = TyExp->getAs<VectorType>();
3524 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3525 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3526 if (Arg0Length != Arg1Length) {
3527 Diag(Exp.get()->getBeginLoc(),
3528 diag::err_typecheck_vector_lengths_not_equal)
3529 << TyA << TyExp << A.get()->getSourceRange()
3530 << Exp.get()->getSourceRange();
3531 return ExprError();
3532 }
3533
3534 TheCall->setArg(0, A.get());
3535 TheCall->setArg(1, Exp.get());
3536 TheCall->setType(TyA);
3537 break;
3538 }
3539
3540 // These builtins restrict the element type to floating point
3541 // types only, and take in two arguments.
3542 case Builtin::BI__builtin_elementwise_minnum:
3543 case Builtin::BI__builtin_elementwise_maxnum:
3544 case Builtin::BI__builtin_elementwise_minimum:
3545 case Builtin::BI__builtin_elementwise_maximum:
3546 case Builtin::BI__builtin_elementwise_minimumnum:
3547 case Builtin::BI__builtin_elementwise_maximumnum:
3548 case Builtin::BI__builtin_elementwise_atan2:
3549 case Builtin::BI__builtin_elementwise_fmod:
3550 case Builtin::BI__builtin_elementwise_pow:
3551 if (BuiltinElementwiseMath(TheCall,
3553 return ExprError();
3554 break;
3555 // These builtins restrict the element type to integer
3556 // types only.
3557 case Builtin::BI__builtin_elementwise_add_sat:
3558 case Builtin::BI__builtin_elementwise_sub_sat:
3559 if (BuiltinElementwiseMath(TheCall,
3561 return ExprError();
3562 break;
3563 case Builtin::BI__builtin_elementwise_fshl:
3564 case Builtin::BI__builtin_elementwise_fshr:
3567 return ExprError();
3568 break;
3569 case Builtin::BI__builtin_elementwise_min:
3570 case Builtin::BI__builtin_elementwise_max: {
3571 if (BuiltinElementwiseMath(TheCall))
3572 return ExprError();
3573 Expr *Arg0 = TheCall->getArg(0);
3574 Expr *Arg1 = TheCall->getArg(1);
3575 QualType Ty0 = Arg0->getType();
3576 QualType Ty1 = Arg1->getType();
3577 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
3578 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
3579 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
3580 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
3581 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
3582 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin_no_suggestion)
3583 << Context.BuiltinInfo.getQuotedName(BuiltinID);
3584 break;
3585 }
3586 case Builtin::BI__builtin_elementwise_popcount:
3587 case Builtin::BI__builtin_elementwise_bitreverse:
3590 return ExprError();
3591 break;
3592 case Builtin::BI__builtin_elementwise_copysign: {
3593 if (checkArgCount(TheCall, 2))
3594 return ExprError();
3595
3596 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3597 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3598 if (Magnitude.isInvalid() || Sign.isInvalid())
3599 return ExprError();
3600
3601 QualType MagnitudeTy = Magnitude.get()->getType();
3602 QualType SignTy = Sign.get()->getType();
3604 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
3607 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
3609 return ExprError();
3610 }
3611
3612 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3613 return Diag(Sign.get()->getBeginLoc(),
3614 diag::err_typecheck_call_different_arg_types)
3615 << MagnitudeTy << SignTy;
3616 }
3617
3618 TheCall->setArg(0, Magnitude.get());
3619 TheCall->setArg(1, Sign.get());
3620 TheCall->setType(Magnitude.get()->getType());
3621 break;
3622 }
3623 case Builtin::BI__builtin_elementwise_clzg:
3624 case Builtin::BI__builtin_elementwise_ctzg:
3625 // These builtins can be unary or binary. Note for empty calls we call the
3626 // unary checker in order to not emit an error that says the function
3627 // expects 2 arguments, which would be misleading.
3628 if (TheCall->getNumArgs() <= 1) {
3631 return ExprError();
3632 } else if (BuiltinElementwiseMath(
3634 return ExprError();
3635 break;
3636 case Builtin::BI__builtin_reduce_max:
3637 case Builtin::BI__builtin_reduce_min: {
3638 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3639 return ExprError();
3640
3641 const Expr *Arg = TheCall->getArg(0);
3642 const auto *TyA = Arg->getType()->getAs<VectorType>();
3643
3644 QualType ElTy;
3645 if (TyA)
3646 ElTy = TyA->getElementType();
3647 else if (Arg->getType()->isSizelessVectorType())
3649
3650 if (ElTy.isNull()) {
3651 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3652 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3653 << Arg->getType();
3654 return ExprError();
3655 }
3656
3657 TheCall->setType(ElTy);
3658 break;
3659 }
3660 case Builtin::BI__builtin_reduce_maximum:
3661 case Builtin::BI__builtin_reduce_minimum: {
3662 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3663 return ExprError();
3664
3665 const Expr *Arg = TheCall->getArg(0);
3666 const auto *TyA = Arg->getType()->getAs<VectorType>();
3667
3668 QualType ElTy;
3669 if (TyA)
3670 ElTy = TyA->getElementType();
3671 else if (Arg->getType()->isSizelessVectorType())
3673
3674 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3675 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3676 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3677 << Arg->getType();
3678 return ExprError();
3679 }
3680
3681 TheCall->setType(ElTy);
3682 break;
3683 }
3684
3685 // These builtins support vectors of integers only.
3686 // TODO: ADD/MUL should support floating-point types.
3687 case Builtin::BI__builtin_reduce_add:
3688 case Builtin::BI__builtin_reduce_mul:
3689 case Builtin::BI__builtin_reduce_xor:
3690 case Builtin::BI__builtin_reduce_or:
3691 case Builtin::BI__builtin_reduce_and: {
3692 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3693 return ExprError();
3694
3695 const Expr *Arg = TheCall->getArg(0);
3696
3697 QualType ElTy = getVectorElementType(Context, Arg->getType());
3698 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3699 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3700 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3701 << Arg->getType();
3702 return ExprError();
3703 }
3704
3705 TheCall->setType(ElTy);
3706 break;
3707 }
3708
3709 case Builtin::BI__builtin_reduce_assoc_fadd:
3710 case Builtin::BI__builtin_reduce_in_order_fadd: {
3711 // For in-order reductions require the user to specify the start value.
3712 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
3713 if (InOrder ? checkArgCount(TheCall, 2) : checkArgCountRange(TheCall, 1, 2))
3714 return ExprError();
3715
3716 ExprResult Vec = UsualUnaryConversions(TheCall->getArg(0));
3717 if (Vec.isInvalid())
3718 return ExprError();
3719
3720 TheCall->setArg(0, Vec.get());
3721
3722 QualType ElTy = getVectorElementType(Context, Vec.get()->getType());
3723 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
3724 Diag(Vec.get()->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3725 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3726 << Vec.get()->getType();
3727 return ExprError();
3728 }
3729
3730 if (TheCall->getNumArgs() == 2) {
3731 ExprResult StartValue = UsualUnaryConversions(TheCall->getArg(1));
3732 if (StartValue.isInvalid())
3733 return ExprError();
3734
3735 if (!StartValue.get()->getType()->isRealFloatingType()) {
3736 Diag(StartValue.get()->getBeginLoc(),
3737 diag::err_builtin_invalid_arg_type)
3738 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
3739 << StartValue.get()->getType();
3740 return ExprError();
3741 }
3742 TheCall->setArg(1, StartValue.get());
3743 }
3744
3745 TheCall->setType(ElTy);
3746 break;
3747 }
3748
3749 case Builtin::BI__builtin_matrix_transpose:
3750 return BuiltinMatrixTranspose(TheCall, TheCallResult);
3751
3752 case Builtin::BI__builtin_matrix_column_major_load:
3753 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
3754
3755 case Builtin::BI__builtin_matrix_column_major_store:
3756 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
3757
3758 case Builtin::BI__builtin_verbose_trap:
3759 if (!checkBuiltinVerboseTrap(TheCall, *this))
3760 return ExprError();
3761 break;
3762
3763 case Builtin::BI__builtin_get_device_side_mangled_name: {
3764 auto Check = [](CallExpr *TheCall) {
3765 if (TheCall->getNumArgs() != 1)
3766 return false;
3767 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
3768 if (!DRE)
3769 return false;
3770 auto *D = DRE->getDecl();
3771 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
3772 return false;
3773 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3774 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3775 };
3776 if (!Check(TheCall)) {
3777 Diag(TheCall->getBeginLoc(),
3778 diag::err_hip_invalid_args_builtin_mangled_name);
3779 return ExprError();
3780 }
3781 break;
3782 }
3783 case Builtin::BI__builtin_bswapg:
3784 if (BuiltinBswapg(*this, TheCall))
3785 return ExprError();
3786 break;
3787 case Builtin::BI__builtin_bitreverseg:
3788 if (BuiltinBitreverseg(*this, TheCall))
3789 return ExprError();
3790 break;
3791 case Builtin::BI__builtin_popcountg:
3792 if (BuiltinPopcountg(*this, TheCall))
3793 return ExprError();
3794 break;
3795 case Builtin::BI__builtin_clzg:
3796 case Builtin::BI__builtin_ctzg:
3797 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
3798 return ExprError();
3799 break;
3800
3801 case Builtin::BI__builtin_stdc_rotate_left:
3802 case Builtin::BI__builtin_stdc_rotate_right:
3803 if (BuiltinRotateGeneric(*this, TheCall))
3804 return ExprError();
3805 break;
3806
3807 case Builtin::BI__builtin_allow_runtime_check: {
3808 Expr *Arg = TheCall->getArg(0);
3809 // Check if the argument is a string literal.
3811 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3812 << Arg->getSourceRange();
3813 return ExprError();
3814 }
3815 break;
3816 }
3817
3818 case Builtin::BI__builtin_allow_sanitize_check: {
3819 if (checkArgCount(TheCall, 1))
3820 return ExprError();
3821
3822 Expr *Arg = TheCall->getArg(0);
3823 // Check if the argument is a string literal.
3824 const StringLiteral *SanitizerName =
3825 dyn_cast<StringLiteral>(Arg->IgnoreParenImpCasts());
3826 if (!SanitizerName) {
3827 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3828 << Arg->getSourceRange();
3829 return ExprError();
3830 }
3831 // Validate the sanitizer name.
3832 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
3833 .Cases({"address", "thread", "memory", "hwaddress",
3834 "kernel-address", "kernel-memory", "kernel-hwaddress"},
3835 true)
3836 .Default(false)) {
3837 Diag(TheCall->getBeginLoc(), diag::err_invalid_builtin_argument)
3838 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
3839 << Arg->getSourceRange();
3840 return ExprError();
3841 }
3842 break;
3843 }
3844 case Builtin::BI__builtin_counted_by_ref:
3845 if (BuiltinCountedByRef(TheCall))
3846 return ExprError();
3847 break;
3848 }
3849
3850 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
3851 return ExprError();
3852
3853 // Since the target specific builtins for each arch overlap, only check those
3854 // of the arch we are compiling for.
3855 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
3856 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
3857 assert(Context.getAuxTargetInfo() &&
3858 "Aux Target Builtin, but not an aux target?");
3859
3860 if (CheckTSBuiltinFunctionCall(
3861 *Context.getAuxTargetInfo(),
3862 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
3863 return ExprError();
3864 } else {
3865 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
3866 TheCall))
3867 return ExprError();
3868 }
3869 }
3870
3871 return TheCallResult;
3872}
3873
3874bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3875 llvm::APSInt Result;
3876 // We can't check the value of a dependent argument.
3877 Expr *Arg = TheCall->getArg(ArgNum);
3878 if (Arg->isTypeDependent() || Arg->isValueDependent())
3879 return false;
3880
3881 // Check constant-ness first.
3882 if (BuiltinConstantArg(TheCall, ArgNum, Result))
3883 return true;
3884
3885 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3886 if (Result.isShiftedMask() || (~Result).isShiftedMask())
3887 return false;
3888
3889 return Diag(TheCall->getBeginLoc(),
3890 diag::err_argument_not_contiguous_bit_field)
3891 << ArgNum << Arg->getSourceRange();
3892}
3893
3894bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
3895 unsigned FirstArg, FormatStringInfo *FSI) {
3896 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
3897 bool IsVariadic = false;
3898 if (const FunctionType *FnTy = D->getFunctionType())
3899 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
3900 else if (const auto *BD = dyn_cast<BlockDecl>(D))
3901 IsVariadic = BD->isVariadic();
3902 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
3903 IsVariadic = OMD->isVariadic();
3904
3905 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
3906 IsVariadic, FSI);
3907}
3908
3909bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
3910 bool HasImplicitThisParam, bool IsVariadic,
3911 FormatStringInfo *FSI) {
3912 if (FirstArg == 0)
3914 else if (IsVariadic)
3916 else
3918 FSI->FormatIdx = FormatIdx - 1;
3919 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
3920
3921 // The way the format attribute works in GCC, the implicit this argument
3922 // of member functions is counted. However, it doesn't appear in our own
3923 // lists, so decrement format_idx in that case.
3924 if (HasImplicitThisParam) {
3925 if(FSI->FormatIdx == 0)
3926 return false;
3927 --FSI->FormatIdx;
3928 if (FSI->FirstDataArg != 0)
3929 --FSI->FirstDataArg;
3930 }
3931 return true;
3932}
3933
3934/// Checks if a the given expression evaluates to null.
3935///
3936/// Returns true if the value evaluates to null.
3937static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3938 // Treat (smart) pointers constructed from nullptr as null, whether we can
3939 // const-evaluate them or not.
3940 // This must happen first: the smart pointer expr might have _Nonnull type!
3944 return true;
3945
3946 // If the expression has non-null type, it doesn't evaluate to null.
3947 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
3948 if (*nullability == NullabilityKind::NonNull)
3949 return false;
3950 }
3951
3952 // As a special case, transparent unions initialized with zero are
3953 // considered null for the purposes of the nonnull attribute.
3954 if (const RecordType *UT = Expr->getType()->getAsUnionType();
3955 UT &&
3956 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
3957 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
3958 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
3959 Expr = ILE->getInit(0);
3960 }
3961
3962 bool Result;
3963 return (!Expr->isValueDependent() &&
3965 !Result);
3966}
3967
3969 const Expr *ArgExpr,
3970 SourceLocation CallSiteLoc) {
3971 if (CheckNonNullExpr(S, ArgExpr))
3972 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3973 S.PDiag(diag::warn_null_arg)
3974 << ArgExpr->getSourceRange());
3975}
3976
3977/// Determine whether the given type has a non-null nullability annotation.
3979 if (auto nullability = type->getNullability())
3980 return *nullability == NullabilityKind::NonNull;
3981
3982 return false;
3983}
3984
3986 const NamedDecl *FDecl,
3987 const FunctionProtoType *Proto,
3989 SourceLocation CallSiteLoc) {
3990 assert((FDecl || Proto) && "Need a function declaration or prototype");
3991
3992 // Already checked by constant evaluator.
3994 return;
3995 // Check the attributes attached to the method/function itself.
3996 llvm::SmallBitVector NonNullArgs;
3997 if (FDecl) {
3998 // Handle the nonnull attribute on the function/method declaration itself.
3999 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4000 if (!NonNull->args_size()) {
4001 // Easy case: all pointer arguments are nonnull.
4002 for (const auto *Arg : Args)
4003 if (S.isValidPointerAttrType(Arg->getType()))
4004 CheckNonNullArgument(S, Arg, CallSiteLoc);
4005 return;
4006 }
4007
4008 for (const ParamIdx &Idx : NonNull->args()) {
4009 unsigned IdxAST = Idx.getASTIndex();
4010 if (IdxAST >= Args.size())
4011 continue;
4012 if (NonNullArgs.empty())
4013 NonNullArgs.resize(Args.size());
4014 NonNullArgs.set(IdxAST);
4015 }
4016 }
4017 }
4018
4019 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4020 // Handle the nonnull attribute on the parameters of the
4021 // function/method.
4023 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4024 parms = FD->parameters();
4025 else
4026 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4027
4028 unsigned ParamIndex = 0;
4029 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4030 I != E; ++I, ++ParamIndex) {
4031 const ParmVarDecl *PVD = *I;
4032 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
4033 if (NonNullArgs.empty())
4034 NonNullArgs.resize(Args.size());
4035
4036 NonNullArgs.set(ParamIndex);
4037 }
4038 }
4039 } else {
4040 // If we have a non-function, non-method declaration but no
4041 // function prototype, try to dig out the function prototype.
4042 if (!Proto) {
4043 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4044 QualType type = VD->getType().getNonReferenceType();
4045 if (auto pointerType = type->getAs<PointerType>())
4046 type = pointerType->getPointeeType();
4047 else if (auto blockType = type->getAs<BlockPointerType>())
4048 type = blockType->getPointeeType();
4049 // FIXME: data member pointers?
4050
4051 // Dig out the function prototype, if there is one.
4052 Proto = type->getAs<FunctionProtoType>();
4053 }
4054 }
4055
4056 // Fill in non-null argument information from the nullability
4057 // information on the parameter types (if we have them).
4058 if (Proto) {
4059 unsigned Index = 0;
4060 for (auto paramType : Proto->getParamTypes()) {
4061 if (isNonNullType(paramType)) {
4062 if (NonNullArgs.empty())
4063 NonNullArgs.resize(Args.size());
4064
4065 NonNullArgs.set(Index);
4066 }
4067
4068 ++Index;
4069 }
4070 }
4071 }
4072
4073 // Check for non-null arguments.
4074 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4075 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4076 if (NonNullArgs[ArgIndex])
4077 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
4078 }
4079}
4080
4081void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4082 StringRef ParamName, QualType ArgTy,
4083 QualType ParamTy) {
4084
4085 // If a function accepts a pointer or reference type
4086 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4087 return;
4088
4089 // If the parameter is a pointer type, get the pointee type for the
4090 // argument too. If the parameter is a reference type, don't try to get
4091 // the pointee type for the argument.
4092 if (ParamTy->isPointerType())
4093 ArgTy = ArgTy->getPointeeType();
4094
4095 // Remove reference or pointer
4096 ParamTy = ParamTy->getPointeeType();
4097
4098 // Find expected alignment, and the actual alignment of the passed object.
4099 // getTypeAlignInChars requires complete types
4100 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4101 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4102 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4103 return;
4104
4105 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4106 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4107
4108 // If the argument is less aligned than the parameter, there is a
4109 // potential alignment issue.
4110 if (ArgAlign < ParamAlign)
4111 Diag(Loc, diag::warn_param_mismatched_alignment)
4112 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4113 << ParamName << (FDecl != nullptr) << FDecl;
4114}
4115
4116void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4117 const Expr *ThisArg,
4119 if (!FD || Args.empty())
4120 return;
4121 auto GetArgAt = [&](int Idx) -> const Expr * {
4122 if (Idx == LifetimeCaptureByAttr::Global ||
4123 Idx == LifetimeCaptureByAttr::Unknown)
4124 return nullptr;
4125 if (IsMemberFunction && Idx == 0)
4126 return ThisArg;
4127 return Args[Idx - IsMemberFunction];
4128 };
4129 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4130 unsigned ArgIdx) {
4131 if (!Attr)
4132 return;
4133
4134 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4135 for (int CapturingParamIdx : Attr->params()) {
4136 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4137 // initialization codepath.
4138 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4140 continue;
4141 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4142 CapturingEntity CE{Capturing};
4143 // Ensure that 'Captured' outlives the 'Capturing' entity.
4144 checkCaptureByLifetime(*this, CE, Captured);
4145 }
4146 };
4147 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4148 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(),
4149 I + IsMemberFunction);
4150 // Check when the implicit object param is captured.
4151 if (IsMemberFunction) {
4152 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4153 if (!TSI)
4154 return;
4156 for (TypeLoc TL = TSI->getTypeLoc();
4157 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4158 TL = ATL.getModifiedLoc())
4159 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4160 }
4161}
4162
4164 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4165 bool IsMemberFunction, SourceLocation Loc,
4166 SourceRange Range, VariadicCallType CallType) {
4167 // FIXME: We should check as much as we can in the template definition.
4168 if (CurContext->isDependentContext())
4169 return;
4170
4171 // Printf and scanf checking.
4172 llvm::SmallBitVector CheckedVarArgs;
4173 if (FDecl) {
4174 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4175 // Only create vector if there are format attributes.
4176 CheckedVarArgs.resize(Args.size());
4177 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
4178 CheckedVarArgs);
4179 }
4180
4181 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4182 CheckedVarArgs.resize(Args.size());
4183 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4184 CheckedVarArgs);
4185 }
4186 }
4187
4188 // Refuse POD arguments that weren't caught by the format string
4189 // checks above.
4190 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4191 if (CallType != VariadicCallType::DoesNotApply &&
4192 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4193 unsigned NumParams = Proto ? Proto->getNumParams()
4194 : isa_and_nonnull<FunctionDecl>(FDecl)
4195 ? cast<FunctionDecl>(FDecl)->getNumParams()
4196 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
4197 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4198 : 0;
4199
4200 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4201 // Args[ArgIdx] can be null in malformed code.
4202 if (const Expr *Arg = Args[ArgIdx]) {
4203 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4204 checkVariadicArgument(Arg, CallType);
4205 }
4206 }
4207 }
4208 if (FD)
4209 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4210 if (FDecl || Proto) {
4211 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4212
4213 // Type safety checking.
4214 if (FDecl) {
4215 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4216 CheckArgumentWithTypeTag(I, Args, Loc);
4217 }
4218 }
4219
4220 // Check that passed arguments match the alignment of original arguments.
4221 // Try to get the missing prototype from the declaration.
4222 if (!Proto && FDecl) {
4223 const auto *FT = FDecl->getFunctionType();
4224 if (isa_and_nonnull<FunctionProtoType>(FT))
4225 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4226 }
4227 if (Proto) {
4228 // For variadic functions, we may have more args than parameters.
4229 // For some K&R functions, we may have less args than parameters.
4230 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4231 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4232 bool IsScalableArg = false;
4233 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4234 // Args[ArgIdx] can be null in malformed code.
4235 if (const Expr *Arg = Args[ArgIdx]) {
4236 if (Arg->containsErrors())
4237 continue;
4238
4239 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4240 FDecl->hasLinkage() &&
4241 FDecl->getFormalLinkage() != Linkage::Internal &&
4243 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
4244
4245 QualType ParamTy = Proto->getParamType(ArgIdx);
4246 if (ParamTy->isSizelessVectorType())
4247 IsScalableArg = true;
4248 QualType ArgTy = Arg->getType();
4249 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4250 ArgTy, ParamTy);
4251 }
4252 }
4253
4254 // If the callee has an AArch64 SME attribute to indicate that it is an
4255 // __arm_streaming function, then the caller requires SME to be available.
4258 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
4259 llvm::StringMap<bool> CallerFeatureMap;
4260 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
4261 if (!CallerFeatureMap.contains("sme"))
4262 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4263 } else if (!Context.getTargetInfo().hasFeature("sme")) {
4264 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4265 }
4266 }
4267
4268 // If the call requires a streaming-mode change and has scalable vector
4269 // arguments or return values, then warn the user that the streaming and
4270 // non-streaming vector lengths may be different.
4271 // When both streaming and non-streaming vector lengths are defined and
4272 // mismatched, produce an error.
4273 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
4274 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4275 (IsScalableArg || IsScalableRet)) {
4276 bool IsCalleeStreaming =
4278 bool IsCalleeStreamingCompatible =
4279 ExtInfo.AArch64SMEAttributes &
4281 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
4282 if (!IsCalleeStreamingCompatible &&
4283 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4284 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4285 const LangOptions &LO = getLangOpts();
4286 unsigned VL = LO.VScaleMin * 128;
4287 unsigned SVL = LO.VScaleStreamingMin * 128;
4288 bool IsVLMismatch = VL && SVL && VL != SVL;
4289
4290 auto EmitDiag = [&](bool IsArg) {
4291 if (IsVLMismatch) {
4292 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4293 // Emit warning for streaming-compatible callers
4294 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
4295 << IsArg << IsCalleeStreaming << SVL << VL;
4296 else
4297 // Emit error otherwise
4298 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4299 << IsArg << SVL << VL;
4300 } else
4301 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4302 << IsArg;
4303 };
4304
4305 if (IsScalableArg)
4306 EmitDiag(true);
4307 if (IsScalableRet)
4308 EmitDiag(false);
4309 }
4310 }
4311
4312 FunctionType::ArmStateValue CalleeArmZAState =
4314 FunctionType::ArmStateValue CalleeArmZT0State =
4316 if (CalleeArmZAState != FunctionType::ARM_None ||
4317 CalleeArmZT0State != FunctionType::ARM_None) {
4318 bool CallerHasZAState = false;
4319 bool CallerHasZT0State = false;
4320 if (CallerFD) {
4321 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4322 if (Attr && Attr->isNewZA())
4323 CallerHasZAState = true;
4324 if (Attr && Attr->isNewZT0())
4325 CallerHasZT0State = true;
4326 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4327 CallerHasZAState |=
4329 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4331 CallerHasZT0State |=
4333 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4335 }
4336 }
4337
4338 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4339 Diag(Loc, diag::err_sme_za_call_no_za_state);
4340
4341 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4342 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4343
4344 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4345 CalleeArmZT0State != FunctionType::ARM_None) {
4346 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4347 Diag(Loc, diag::note_sme_use_preserves_za);
4348 }
4349 }
4350 }
4351
4352 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4353 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4354 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4355 if (!Arg->isValueDependent()) {
4356 Expr::EvalResult Align;
4357 if (Arg->EvaluateAsInt(Align, Context)) {
4358 const llvm::APSInt &I = Align.Val.getInt();
4359 if (!I.isPowerOf2())
4360 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4361 << Arg->getSourceRange();
4362
4363 if (I > Sema::MaximumAlignment)
4364 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4365 << Arg->getSourceRange() << Sema::MaximumAlignment;
4366 }
4367 }
4368 }
4369
4370 if (FD)
4371 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4372}
4373
4374void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4375 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4376 DiagnoseUseOfDecl(Decl, Loc);
4377 }
4378}
4379
4380void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4382 const FunctionProtoType *Proto,
4383 SourceLocation Loc) {
4384 VariadicCallType CallType = Proto->isVariadic()
4387
4388 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4389 CheckArgAlignment(
4390 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4391 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4392
4393 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4394 Loc, SourceRange(), CallType);
4395}
4396
4398 const FunctionProtoType *Proto) {
4399 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4400 isa<CXXMethodDecl>(FDecl);
4401 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4402 IsMemberOperatorCall;
4403 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4404 TheCall->getCallee());
4405 Expr** Args = TheCall->getArgs();
4406 unsigned NumArgs = TheCall->getNumArgs();
4407
4408 Expr *ImplicitThis = nullptr;
4409 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4410 // If this is a call to a member operator, hide the first
4411 // argument from checkCall.
4412 // FIXME: Our choice of AST representation here is less than ideal.
4413 ImplicitThis = Args[0];
4414 ++Args;
4415 --NumArgs;
4416 } else if (IsMemberFunction && !FDecl->isStatic() &&
4418 ImplicitThis =
4419 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4420
4421 if (ImplicitThis) {
4422 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4423 // used.
4424 QualType ThisType = ImplicitThis->getType();
4425 if (!ThisType->isPointerType()) {
4426 assert(!ThisType->isReferenceType());
4427 ThisType = Context.getPointerType(ThisType);
4428 }
4429
4430 QualType ThisTypeFromDecl = Context.getPointerType(
4431 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4432
4433 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4434 ThisTypeFromDecl);
4435 }
4436
4437 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4438 IsMemberFunction, TheCall->getRParenLoc(),
4439 TheCall->getCallee()->getSourceRange(), CallType);
4440
4441 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4442 // None of the checks below are needed for functions that don't have
4443 // simple names (e.g., C++ conversion functions).
4444 if (!FnInfo)
4445 return false;
4446
4447 // Enforce TCB except for builtin calls, which are always allowed.
4448 if (FDecl->getBuiltinID() == 0)
4449 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4450
4451 CheckAbsoluteValueFunction(TheCall, FDecl);
4452 CheckMaxUnsignedZero(TheCall, FDecl);
4453 CheckInfNaNFunction(TheCall, FDecl);
4454
4455 if (getLangOpts().ObjC)
4456 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4457
4458 unsigned CMId = FDecl->getMemoryFunctionKind();
4459
4460 // Handle memory setting and copying functions.
4461 switch (CMId) {
4462 case 0:
4463 return false;
4464 case Builtin::BIstrlcpy: // fallthrough
4465 case Builtin::BIstrlcat:
4466 CheckStrlcpycatArguments(TheCall, FnInfo);
4467 break;
4468 case Builtin::BIstrncat:
4469 CheckStrncatArguments(TheCall, FnInfo);
4470 break;
4471 case Builtin::BIfree:
4472 CheckFreeArguments(TheCall);
4473 break;
4474 default:
4475 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4476 }
4477
4478 return false;
4479}
4480
4481bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4482 const FunctionProtoType *Proto) {
4483 QualType Ty;
4484 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4485 Ty = V->getType().getNonReferenceType();
4486 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4487 Ty = F->getType().getNonReferenceType();
4488 else
4489 return false;
4490
4491 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4492 !Ty->isFunctionProtoType())
4493 return false;
4494
4495 VariadicCallType CallType;
4496 if (!Proto || !Proto->isVariadic()) {
4498 } else if (Ty->isBlockPointerType()) {
4499 CallType = VariadicCallType::Block;
4500 } else { // Ty->isFunctionPointerType()
4501 CallType = VariadicCallType::Function;
4502 }
4503
4504 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4505 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4506 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4507 TheCall->getCallee()->getSourceRange(), CallType);
4508
4509 return false;
4510}
4511
4512bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4513 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4514 TheCall->getCallee());
4515 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4516 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4517 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4518 TheCall->getCallee()->getSourceRange(), CallType);
4519
4520 return false;
4521}
4522
4523static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4524 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4525 return false;
4526
4527 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4528 switch (Op) {
4529 case AtomicExpr::AO__c11_atomic_init:
4530 case AtomicExpr::AO__opencl_atomic_init:
4531 llvm_unreachable("There is no ordering argument for an init");
4532
4533 case AtomicExpr::AO__c11_atomic_load:
4534 case AtomicExpr::AO__opencl_atomic_load:
4535 case AtomicExpr::AO__hip_atomic_load:
4536 case AtomicExpr::AO__atomic_load_n:
4537 case AtomicExpr::AO__atomic_load:
4538 case AtomicExpr::AO__scoped_atomic_load_n:
4539 case AtomicExpr::AO__scoped_atomic_load:
4540 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4541 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4542
4543 case AtomicExpr::AO__c11_atomic_store:
4544 case AtomicExpr::AO__opencl_atomic_store:
4545 case AtomicExpr::AO__hip_atomic_store:
4546 case AtomicExpr::AO__atomic_store:
4547 case AtomicExpr::AO__atomic_store_n:
4548 case AtomicExpr::AO__scoped_atomic_store:
4549 case AtomicExpr::AO__scoped_atomic_store_n:
4550 case AtomicExpr::AO__atomic_clear:
4551 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4552 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4553 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4554
4555 default:
4556 return true;
4557 }
4558}
4559
4560ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4562 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4563 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4564 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4565 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4566 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4567 Op);
4568}
4569
4571 SourceLocation RParenLoc, MultiExprArg Args,
4573 AtomicArgumentOrder ArgOrder) {
4574 // All the non-OpenCL operations take one of the following forms.
4575 // The OpenCL operations take the __c11 forms with one extra argument for
4576 // synchronization scope.
4577 enum {
4578 // C __c11_atomic_init(A *, C)
4579 Init,
4580
4581 // C __c11_atomic_load(A *, int)
4582 Load,
4583
4584 // void __atomic_load(A *, CP, int)
4585 LoadCopy,
4586
4587 // void __atomic_store(A *, CP, int)
4588 Copy,
4589
4590 // C __c11_atomic_add(A *, M, int)
4591 Arithmetic,
4592
4593 // C __atomic_exchange_n(A *, CP, int)
4594 Xchg,
4595
4596 // void __atomic_exchange(A *, C *, CP, int)
4597 GNUXchg,
4598
4599 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4600 C11CmpXchg,
4601
4602 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4603 GNUCmpXchg,
4604
4605 // bool __atomic_test_and_set(A *, int)
4606 TestAndSetByte,
4607
4608 // void __atomic_clear(A *, int)
4609 ClearByte,
4610 } Form = Init;
4611
4612 const unsigned NumForm = ClearByte + 1;
4613 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4614 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4615 // where:
4616 // C is an appropriate type,
4617 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4618 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4619 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4620 // the int parameters are for orderings.
4621
4622 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4623 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4624 "need to update code for modified forms");
4625 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4626 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4627 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4628 "need to update code for modified C11 atomics");
4629 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4630 Op <= AtomicExpr::AO__opencl_atomic_store;
4631 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4632 Op <= AtomicExpr::AO__hip_atomic_store;
4633 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4634 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4635 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4636 Op <= AtomicExpr::AO__c11_atomic_store) ||
4637 IsOpenCL;
4638 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4639 Op == AtomicExpr::AO__atomic_store_n ||
4640 Op == AtomicExpr::AO__atomic_exchange_n ||
4641 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4642 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4643 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4644 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4645 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4646 // Bit mask for extra allowed value types other than integers for atomic
4647 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4648 // allow floating point.
4649 enum ArithOpExtraValueType {
4650 AOEVT_None = 0,
4651 AOEVT_Pointer = 1,
4652 AOEVT_FP = 2,
4653 };
4654 unsigned ArithAllows = AOEVT_None;
4655
4656 switch (Op) {
4657 case AtomicExpr::AO__c11_atomic_init:
4658 case AtomicExpr::AO__opencl_atomic_init:
4659 Form = Init;
4660 break;
4661
4662 case AtomicExpr::AO__c11_atomic_load:
4663 case AtomicExpr::AO__opencl_atomic_load:
4664 case AtomicExpr::AO__hip_atomic_load:
4665 case AtomicExpr::AO__atomic_load_n:
4666 case AtomicExpr::AO__scoped_atomic_load_n:
4667 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4668 Form = Load;
4669 break;
4670
4671 case AtomicExpr::AO__atomic_load:
4672 case AtomicExpr::AO__scoped_atomic_load:
4673 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4674 Form = LoadCopy;
4675 break;
4676
4677 case AtomicExpr::AO__c11_atomic_store:
4678 case AtomicExpr::AO__opencl_atomic_store:
4679 case AtomicExpr::AO__hip_atomic_store:
4680 case AtomicExpr::AO__atomic_store:
4681 case AtomicExpr::AO__atomic_store_n:
4682 case AtomicExpr::AO__scoped_atomic_store:
4683 case AtomicExpr::AO__scoped_atomic_store_n:
4684 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4685 Form = Copy;
4686 break;
4687 case AtomicExpr::AO__atomic_fetch_add:
4688 case AtomicExpr::AO__atomic_fetch_sub:
4689 case AtomicExpr::AO__atomic_add_fetch:
4690 case AtomicExpr::AO__atomic_sub_fetch:
4691 case AtomicExpr::AO__scoped_atomic_fetch_add:
4692 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4693 case AtomicExpr::AO__scoped_atomic_add_fetch:
4694 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4695 case AtomicExpr::AO__c11_atomic_fetch_add:
4696 case AtomicExpr::AO__c11_atomic_fetch_sub:
4697 case AtomicExpr::AO__opencl_atomic_fetch_add:
4698 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4699 case AtomicExpr::AO__hip_atomic_fetch_add:
4700 case AtomicExpr::AO__hip_atomic_fetch_sub:
4701 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4702 Form = Arithmetic;
4703 break;
4704 case AtomicExpr::AO__atomic_fetch_max:
4705 case AtomicExpr::AO__atomic_fetch_min:
4706 case AtomicExpr::AO__atomic_max_fetch:
4707 case AtomicExpr::AO__atomic_min_fetch:
4708 case AtomicExpr::AO__scoped_atomic_fetch_max:
4709 case AtomicExpr::AO__scoped_atomic_fetch_min:
4710 case AtomicExpr::AO__scoped_atomic_max_fetch:
4711 case AtomicExpr::AO__scoped_atomic_min_fetch:
4712 case AtomicExpr::AO__c11_atomic_fetch_max:
4713 case AtomicExpr::AO__c11_atomic_fetch_min:
4714 case AtomicExpr::AO__opencl_atomic_fetch_max:
4715 case AtomicExpr::AO__opencl_atomic_fetch_min:
4716 case AtomicExpr::AO__hip_atomic_fetch_max:
4717 case AtomicExpr::AO__hip_atomic_fetch_min:
4718 ArithAllows = AOEVT_FP;
4719 Form = Arithmetic;
4720 break;
4721 case AtomicExpr::AO__c11_atomic_fetch_and:
4722 case AtomicExpr::AO__c11_atomic_fetch_or:
4723 case AtomicExpr::AO__c11_atomic_fetch_xor:
4724 case AtomicExpr::AO__hip_atomic_fetch_and:
4725 case AtomicExpr::AO__hip_atomic_fetch_or:
4726 case AtomicExpr::AO__hip_atomic_fetch_xor:
4727 case AtomicExpr::AO__c11_atomic_fetch_nand:
4728 case AtomicExpr::AO__opencl_atomic_fetch_and:
4729 case AtomicExpr::AO__opencl_atomic_fetch_or:
4730 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4731 case AtomicExpr::AO__atomic_fetch_and:
4732 case AtomicExpr::AO__atomic_fetch_or:
4733 case AtomicExpr::AO__atomic_fetch_xor:
4734 case AtomicExpr::AO__atomic_fetch_nand:
4735 case AtomicExpr::AO__atomic_and_fetch:
4736 case AtomicExpr::AO__atomic_or_fetch:
4737 case AtomicExpr::AO__atomic_xor_fetch:
4738 case AtomicExpr::AO__atomic_nand_fetch:
4739 case AtomicExpr::AO__atomic_fetch_uinc:
4740 case AtomicExpr::AO__atomic_fetch_udec:
4741 case AtomicExpr::AO__scoped_atomic_fetch_and:
4742 case AtomicExpr::AO__scoped_atomic_fetch_or:
4743 case AtomicExpr::AO__scoped_atomic_fetch_xor:
4744 case AtomicExpr::AO__scoped_atomic_fetch_nand:
4745 case AtomicExpr::AO__scoped_atomic_and_fetch:
4746 case AtomicExpr::AO__scoped_atomic_or_fetch:
4747 case AtomicExpr::AO__scoped_atomic_xor_fetch:
4748 case AtomicExpr::AO__scoped_atomic_nand_fetch:
4749 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
4750 case AtomicExpr::AO__scoped_atomic_fetch_udec:
4751 Form = Arithmetic;
4752 break;
4753
4754 case AtomicExpr::AO__c11_atomic_exchange:
4755 case AtomicExpr::AO__hip_atomic_exchange:
4756 case AtomicExpr::AO__opencl_atomic_exchange:
4757 case AtomicExpr::AO__atomic_exchange_n:
4758 case AtomicExpr::AO__scoped_atomic_exchange_n:
4759 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4760 Form = Xchg;
4761 break;
4762
4763 case AtomicExpr::AO__atomic_exchange:
4764 case AtomicExpr::AO__scoped_atomic_exchange:
4765 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4766 Form = GNUXchg;
4767 break;
4768
4769 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4770 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4771 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4772 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4773 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4774 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4775 Form = C11CmpXchg;
4776 break;
4777
4778 case AtomicExpr::AO__atomic_compare_exchange:
4779 case AtomicExpr::AO__atomic_compare_exchange_n:
4780 case AtomicExpr::AO__scoped_atomic_compare_exchange:
4781 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
4782 ArithAllows = AOEVT_Pointer;
4783 Form = GNUCmpXchg;
4784 break;
4785
4786 case AtomicExpr::AO__atomic_test_and_set:
4787 Form = TestAndSetByte;
4788 break;
4789
4790 case AtomicExpr::AO__atomic_clear:
4791 Form = ClearByte;
4792 break;
4793 }
4794
4795 unsigned AdjustedNumArgs = NumArgs[Form];
4796 if ((IsOpenCL || IsHIP || IsScoped) &&
4797 Op != AtomicExpr::AO__opencl_atomic_init)
4798 ++AdjustedNumArgs;
4799 // Check we have the right number of arguments.
4800 if (Args.size() < AdjustedNumArgs) {
4801 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4802 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4803 << /*is non object*/ 0 << ExprRange;
4804 return ExprError();
4805 } else if (Args.size() > AdjustedNumArgs) {
4806 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4807 diag::err_typecheck_call_too_many_args)
4808 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4809 << /*is non object*/ 0 << ExprRange;
4810 return ExprError();
4811 }
4812
4813 // Inspect the first argument of the atomic operation.
4814 Expr *Ptr = Args[0];
4816 if (ConvertedPtr.isInvalid())
4817 return ExprError();
4818
4819 Ptr = ConvertedPtr.get();
4820 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4821 if (!pointerType) {
4822 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4823 << Ptr->getType() << 0 << Ptr->getSourceRange();
4824 return ExprError();
4825 }
4826
4827 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4828 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4829 QualType ValType = AtomTy; // 'C'
4830 if (IsC11) {
4831 if (!AtomTy->isAtomicType()) {
4832 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4833 << Ptr->getType() << Ptr->getSourceRange();
4834 return ExprError();
4835 }
4836 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4838 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4839 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4840 << Ptr->getSourceRange();
4841 return ExprError();
4842 }
4843 ValType = AtomTy->castAs<AtomicType>()->getValueType();
4844 } else if (Form != Load && Form != LoadCopy) {
4845 if (ValType.isConstQualified()) {
4846 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4847 << Ptr->getType() << Ptr->getSourceRange();
4848 return ExprError();
4849 }
4850 }
4851
4852 if (Form != TestAndSetByte && Form != ClearByte) {
4853 // Pointer to object of size zero is not allowed.
4854 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
4855 diag::err_incomplete_type))
4856 return ExprError();
4857
4858 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
4859 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4860 << Ptr->getType() << 1 << Ptr->getSourceRange();
4861 return ExprError();
4862 }
4863 } else {
4864 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
4865 // non-const pointer type, including void* and pointers to incomplete
4866 // structs, but only access the first byte.
4867 AtomTy = Context.CharTy;
4868 AtomTy = AtomTy.withCVRQualifiers(
4869 pointerType->getPointeeType().getCVRQualifiers());
4870 QualType PointerQT = Context.getPointerType(AtomTy);
4871 pointerType = PointerQT->getAs<PointerType>();
4872 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
4873 ValType = AtomTy;
4874 }
4875
4876 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
4877 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4878 Diag(ExprRange.getBegin(),
4879 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4880 << 0 << Ptr->getType() << Ptr->getSourceRange();
4881 return ExprError();
4882 }
4883
4884 // For an arithmetic operation, the implied arithmetic must be well-formed.
4885 // For _n operations, the value type must also be a valid atomic type.
4886 if (Form == Arithmetic || IsN) {
4887 // GCC does not enforce these rules for GNU atomics, but we do to help catch
4888 // trivial type errors.
4889 auto IsAllowedValueType = [&](QualType ValType,
4890 unsigned AllowedType) -> bool {
4891 bool IsX87LongDouble =
4892 ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
4893 &Context.getTargetInfo().getLongDoubleFormat() ==
4894 &llvm::APFloat::x87DoubleExtended();
4895 if (ValType->isIntegerType())
4896 return true;
4897 if (ValType->isPointerType())
4898 return AllowedType & AOEVT_Pointer;
4899 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
4900 return false;
4901 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
4902 if (IsX87LongDouble)
4903 return false;
4904 return true;
4905 };
4906 if (!IsAllowedValueType(ValType, ArithAllows)) {
4907 auto DID = ArithAllows & AOEVT_FP
4908 ? (ArithAllows & AOEVT_Pointer
4909 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
4910 : diag::err_atomic_op_needs_atomic_int_or_fp)
4911 : (ArithAllows & AOEVT_Pointer
4912 ? diag::err_atomic_op_needs_atomic_int_or_ptr
4913 : diag::err_atomic_op_needs_atomic_int);
4914 Diag(ExprRange.getBegin(), DID)
4915 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4916 return ExprError();
4917 }
4918 if (IsC11 && ValType->isPointerType() &&
4920 diag::err_incomplete_type)) {
4921 return ExprError();
4922 }
4923 }
4924
4925 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4926 !AtomTy->isScalarType()) {
4927 // For GNU atomics, require a trivially-copyable type. This is not part of
4928 // the GNU atomics specification but we enforce it for consistency with
4929 // other atomics which generally all require a trivially-copyable type. This
4930 // is because atomics just copy bits.
4931 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4932 << Ptr->getType() << Ptr->getSourceRange();
4933 return ExprError();
4934 }
4935
4936 switch (ValType.getObjCLifetime()) {
4939 // okay
4940 break;
4941
4945 // FIXME: Can this happen? By this point, ValType should be known
4946 // to be trivially copyable.
4947 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4948 << ValType << Ptr->getSourceRange();
4949 return ExprError();
4950 }
4951
4952 // All atomic operations have an overload which takes a pointer to a volatile
4953 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4954 // into the result or the other operands. Similarly atomic_load takes a
4955 // pointer to a const 'A'.
4956 ValType.removeLocalVolatile();
4957 ValType.removeLocalConst();
4958 QualType ResultType = ValType;
4959 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
4960 Form == ClearByte)
4961 ResultType = Context.VoidTy;
4962 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
4963 ResultType = Context.BoolTy;
4964
4965 // The type of a parameter passed 'by value'. In the GNU atomics, such
4966 // arguments are actually passed as pointers.
4967 QualType ByValType = ValType; // 'CP'
4968 bool IsPassedByAddress = false;
4969 if (!IsC11 && !IsHIP && !IsN) {
4970 ByValType = Ptr->getType();
4971 IsPassedByAddress = true;
4972 }
4973
4974 SmallVector<Expr *, 5> APIOrderedArgs;
4975 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4976 APIOrderedArgs.push_back(Args[0]);
4977 switch (Form) {
4978 case Init:
4979 case Load:
4980 APIOrderedArgs.push_back(Args[1]); // Val1/Order
4981 break;
4982 case LoadCopy:
4983 case Copy:
4984 case Arithmetic:
4985 case Xchg:
4986 APIOrderedArgs.push_back(Args[2]); // Val1
4987 APIOrderedArgs.push_back(Args[1]); // Order
4988 break;
4989 case GNUXchg:
4990 APIOrderedArgs.push_back(Args[2]); // Val1
4991 APIOrderedArgs.push_back(Args[3]); // Val2
4992 APIOrderedArgs.push_back(Args[1]); // Order
4993 break;
4994 case C11CmpXchg:
4995 APIOrderedArgs.push_back(Args[2]); // Val1
4996 APIOrderedArgs.push_back(Args[4]); // Val2
4997 APIOrderedArgs.push_back(Args[1]); // Order
4998 APIOrderedArgs.push_back(Args[3]); // OrderFail
4999 break;
5000 case GNUCmpXchg:
5001 APIOrderedArgs.push_back(Args[2]); // Val1
5002 APIOrderedArgs.push_back(Args[4]); // Val2
5003 APIOrderedArgs.push_back(Args[5]); // Weak
5004 APIOrderedArgs.push_back(Args[1]); // Order
5005 APIOrderedArgs.push_back(Args[3]); // OrderFail
5006 break;
5007 case TestAndSetByte:
5008 case ClearByte:
5009 APIOrderedArgs.push_back(Args[1]); // Order
5010 break;
5011 }
5012 } else
5013 APIOrderedArgs.append(Args.begin(), Args.end());
5014
5015 // The first argument's non-CV pointer type is used to deduce the type of
5016 // subsequent arguments, except for:
5017 // - weak flag (always converted to bool)
5018 // - memory order (always converted to int)
5019 // - scope (always converted to int)
5020 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5021 QualType Ty;
5022 if (i < NumVals[Form] + 1) {
5023 switch (i) {
5024 case 0:
5025 // The first argument is always a pointer. It has a fixed type.
5026 // It is always dereferenced, a nullptr is undefined.
5027 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5028 // Nothing else to do: we already know all we want about this pointer.
5029 continue;
5030 case 1:
5031 // The second argument is the non-atomic operand. For arithmetic, this
5032 // is always passed by value, and for a compare_exchange it is always
5033 // passed by address. For the rest, GNU uses by-address and C11 uses
5034 // by-value.
5035 assert(Form != Load);
5036 if (Form == Arithmetic && ValType->isPointerType())
5037 Ty = Context.getPointerDiffType();
5038 else if (Form == Init || Form == Arithmetic)
5039 Ty = ValType;
5040 else if (Form == Copy || Form == Xchg) {
5041 if (IsPassedByAddress) {
5042 // The value pointer is always dereferenced, a nullptr is undefined.
5043 CheckNonNullArgument(*this, APIOrderedArgs[i],
5044 ExprRange.getBegin());
5045 }
5046 Ty = ByValType;
5047 } else {
5048 Expr *ValArg = APIOrderedArgs[i];
5049 // The value pointer is always dereferenced, a nullptr is undefined.
5050 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5052 // Keep address space of non-atomic pointer type.
5053 if (const PointerType *PtrTy =
5054 ValArg->getType()->getAs<PointerType>()) {
5055 AS = PtrTy->getPointeeType().getAddressSpace();
5056 }
5057 Ty = Context.getPointerType(
5058 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5059 }
5060 break;
5061 case 2:
5062 // The third argument to compare_exchange / GNU exchange is the desired
5063 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5064 if (IsPassedByAddress)
5065 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5066 Ty = ByValType;
5067 break;
5068 case 3:
5069 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5070 Ty = Context.BoolTy;
5071 break;
5072 }
5073 } else {
5074 // The order(s) and scope are always converted to int.
5075 Ty = Context.IntTy;
5076 }
5077
5078 InitializedEntity Entity =
5080 ExprResult Arg = APIOrderedArgs[i];
5081 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5082 if (Arg.isInvalid())
5083 return true;
5084 APIOrderedArgs[i] = Arg.get();
5085 }
5086
5087 // Permute the arguments into a 'consistent' order.
5088 SmallVector<Expr*, 5> SubExprs;
5089 SubExprs.push_back(Ptr);
5090 switch (Form) {
5091 case Init:
5092 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5093 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5094 break;
5095 case Load:
5096 case TestAndSetByte:
5097 case ClearByte:
5098 SubExprs.push_back(APIOrderedArgs[1]); // Order
5099 break;
5100 case LoadCopy:
5101 case Copy:
5102 case Arithmetic:
5103 case Xchg:
5104 SubExprs.push_back(APIOrderedArgs[2]); // Order
5105 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5106 break;
5107 case GNUXchg:
5108 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5109 SubExprs.push_back(APIOrderedArgs[3]); // Order
5110 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5111 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5112 break;
5113 case C11CmpXchg:
5114 SubExprs.push_back(APIOrderedArgs[3]); // Order
5115 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5116 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5117 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5118 break;
5119 case GNUCmpXchg:
5120 SubExprs.push_back(APIOrderedArgs[4]); // Order
5121 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5122 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5123 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5124 SubExprs.push_back(APIOrderedArgs[3]); // Weak
5125 break;
5126 }
5127
5128 // If the memory orders are constants, check they are valid.
5129 if (SubExprs.size() >= 2 && Form != Init) {
5130 std::optional<llvm::APSInt> Success =
5131 SubExprs[1]->getIntegerConstantExpr(Context);
5132 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
5133 Diag(SubExprs[1]->getBeginLoc(),
5134 diag::warn_atomic_op_has_invalid_memory_order)
5135 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5136 << SubExprs[1]->getSourceRange();
5137 }
5138 if (SubExprs.size() >= 5) {
5139 if (std::optional<llvm::APSInt> Failure =
5140 SubExprs[3]->getIntegerConstantExpr(Context)) {
5141 if (!llvm::is_contained(
5142 {llvm::AtomicOrderingCABI::relaxed,
5143 llvm::AtomicOrderingCABI::consume,
5144 llvm::AtomicOrderingCABI::acquire,
5145 llvm::AtomicOrderingCABI::seq_cst},
5146 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5147 Diag(SubExprs[3]->getBeginLoc(),
5148 diag::warn_atomic_op_has_invalid_memory_order)
5149 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5150 }
5151 }
5152 }
5153 }
5154
5155 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5156 auto *Scope = Args[Args.size() - 1];
5157 if (std::optional<llvm::APSInt> Result =
5158 Scope->getIntegerConstantExpr(Context)) {
5159 if (!ScopeModel->isValid(Result->getZExtValue()))
5160 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
5161 << Scope->getSourceRange();
5162 }
5163 SubExprs.push_back(Scope);
5164 }
5165
5166 AtomicExpr *AE = new (Context)
5167 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5168
5169 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5170 Op == AtomicExpr::AO__c11_atomic_store ||
5171 Op == AtomicExpr::AO__opencl_atomic_load ||
5172 Op == AtomicExpr::AO__hip_atomic_load ||
5173 Op == AtomicExpr::AO__opencl_atomic_store ||
5174 Op == AtomicExpr::AO__hip_atomic_store) &&
5175 Context.AtomicUsesUnsupportedLibcall(AE))
5176 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5177 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5178 Op == AtomicExpr::AO__opencl_atomic_load ||
5179 Op == AtomicExpr::AO__hip_atomic_load)
5180 ? 0
5181 : 1);
5182
5183 if (ValType->isBitIntType()) {
5184 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5185 return ExprError();
5186 }
5187
5188 return AE;
5189}
5190
5191/// checkBuiltinArgument - Given a call to a builtin function, perform
5192/// normal type-checking on the given argument, updating the call in
5193/// place. This is useful when a builtin function requires custom
5194/// type-checking for some of its arguments but not necessarily all of
5195/// them.
5196///
5197/// Returns true on error.
5198static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5199 FunctionDecl *Fn = E->getDirectCallee();
5200 assert(Fn && "builtin call without direct callee!");
5201
5202 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5203 InitializedEntity Entity =
5205
5206 ExprResult Arg = E->getArg(ArgIndex);
5207 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5208 if (Arg.isInvalid())
5209 return true;
5210
5211 E->setArg(ArgIndex, Arg.get());
5212 return false;
5213}
5214
5215ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5216 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5217 Expr *Callee = TheCall->getCallee();
5218 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5219 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5220
5221 // Ensure that we have at least one argument to do type inference from.
5222 if (TheCall->getNumArgs() < 1) {
5223 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5224 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5225 << Callee->getSourceRange();
5226 return ExprError();
5227 }
5228
5229 // Inspect the first argument of the atomic builtin. This should always be
5230 // a pointer type, whose element is an integral scalar or pointer type.
5231 // Because it is a pointer type, we don't have to worry about any implicit
5232 // casts here.
5233 // FIXME: We don't allow floating point scalars as input.
5234 Expr *FirstArg = TheCall->getArg(0);
5235 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5236 if (FirstArgResult.isInvalid())
5237 return ExprError();
5238 FirstArg = FirstArgResult.get();
5239 TheCall->setArg(0, FirstArg);
5240
5241 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5242 if (!pointerType) {
5243 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5244 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5245 return ExprError();
5246 }
5247
5248 QualType ValType = pointerType->getPointeeType();
5249 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5250 !ValType->isBlockPointerType()) {
5251 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5252 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5253 return ExprError();
5254 }
5255 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5256 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5257 Diag(FirstArg->getBeginLoc(),
5258 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5259 << 1 << ValType << FirstArg->getSourceRange();
5260 return ExprError();
5261 }
5262
5263 if (ValType.isConstQualified()) {
5264 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5265 << FirstArg->getType() << FirstArg->getSourceRange();
5266 return ExprError();
5267 }
5268
5269 switch (ValType.getObjCLifetime()) {
5272 // okay
5273 break;
5274
5278 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5279 << ValType << FirstArg->getSourceRange();
5280 return ExprError();
5281 }
5282
5283 // Strip any qualifiers off ValType.
5284 ValType = ValType.getUnqualifiedType();
5285
5286 // The majority of builtins return a value, but a few have special return
5287 // types, so allow them to override appropriately below.
5288 QualType ResultType = ValType;
5289
5290 // We need to figure out which concrete builtin this maps onto. For example,
5291 // __sync_fetch_and_add with a 2 byte object turns into
5292 // __sync_fetch_and_add_2.
5293#define BUILTIN_ROW(x) \
5294 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5295 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5296
5297 static const unsigned BuiltinIndices[][5] = {
5298 BUILTIN_ROW(__sync_fetch_and_add),
5299 BUILTIN_ROW(__sync_fetch_and_sub),
5300 BUILTIN_ROW(__sync_fetch_and_or),
5301 BUILTIN_ROW(__sync_fetch_and_and),
5302 BUILTIN_ROW(__sync_fetch_and_xor),
5303 BUILTIN_ROW(__sync_fetch_and_nand),
5304
5305 BUILTIN_ROW(__sync_add_and_fetch),
5306 BUILTIN_ROW(__sync_sub_and_fetch),
5307 BUILTIN_ROW(__sync_and_and_fetch),
5308 BUILTIN_ROW(__sync_or_and_fetch),
5309 BUILTIN_ROW(__sync_xor_and_fetch),
5310 BUILTIN_ROW(__sync_nand_and_fetch),
5311
5312 BUILTIN_ROW(__sync_val_compare_and_swap),
5313 BUILTIN_ROW(__sync_bool_compare_and_swap),
5314 BUILTIN_ROW(__sync_lock_test_and_set),
5315 BUILTIN_ROW(__sync_lock_release),
5316 BUILTIN_ROW(__sync_swap)
5317 };
5318#undef BUILTIN_ROW
5319
5320 // Determine the index of the size.
5321 unsigned SizeIndex;
5322 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5323 case 1: SizeIndex = 0; break;
5324 case 2: SizeIndex = 1; break;
5325 case 4: SizeIndex = 2; break;
5326 case 8: SizeIndex = 3; break;
5327 case 16: SizeIndex = 4; break;
5328 default:
5329 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5330 << FirstArg->getType() << FirstArg->getSourceRange();
5331 return ExprError();
5332 }
5333
5334 // Each of these builtins has one pointer argument, followed by some number of
5335 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5336 // that we ignore. Find out which row of BuiltinIndices to read from as well
5337 // as the number of fixed args.
5338 unsigned BuiltinID = FDecl->getBuiltinID();
5339 unsigned BuiltinIndex, NumFixed = 1;
5340 bool WarnAboutSemanticsChange = false;
5341 switch (BuiltinID) {
5342 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5343 case Builtin::BI__sync_fetch_and_add:
5344 case Builtin::BI__sync_fetch_and_add_1:
5345 case Builtin::BI__sync_fetch_and_add_2:
5346 case Builtin::BI__sync_fetch_and_add_4:
5347 case Builtin::BI__sync_fetch_and_add_8:
5348 case Builtin::BI__sync_fetch_and_add_16:
5349 BuiltinIndex = 0;
5350 break;
5351
5352 case Builtin::BI__sync_fetch_and_sub:
5353 case Builtin::BI__sync_fetch_and_sub_1:
5354 case Builtin::BI__sync_fetch_and_sub_2:
5355 case Builtin::BI__sync_fetch_and_sub_4:
5356 case Builtin::BI__sync_fetch_and_sub_8:
5357 case Builtin::BI__sync_fetch_and_sub_16:
5358 BuiltinIndex = 1;
5359 break;
5360
5361 case Builtin::BI__sync_fetch_and_or:
5362 case Builtin::BI__sync_fetch_and_or_1:
5363 case Builtin::BI__sync_fetch_and_or_2:
5364 case Builtin::BI__sync_fetch_and_or_4:
5365 case Builtin::BI__sync_fetch_and_or_8:
5366 case Builtin::BI__sync_fetch_and_or_16:
5367 BuiltinIndex = 2;
5368 break;
5369
5370 case Builtin::BI__sync_fetch_and_and:
5371 case Builtin::BI__sync_fetch_and_and_1:
5372 case Builtin::BI__sync_fetch_and_and_2:
5373 case Builtin::BI__sync_fetch_and_and_4:
5374 case Builtin::BI__sync_fetch_and_and_8:
5375 case Builtin::BI__sync_fetch_and_and_16:
5376 BuiltinIndex = 3;
5377 break;
5378
5379 case Builtin::BI__sync_fetch_and_xor:
5380 case Builtin::BI__sync_fetch_and_xor_1:
5381 case Builtin::BI__sync_fetch_and_xor_2:
5382 case Builtin::BI__sync_fetch_and_xor_4:
5383 case Builtin::BI__sync_fetch_and_xor_8:
5384 case Builtin::BI__sync_fetch_and_xor_16:
5385 BuiltinIndex = 4;
5386 break;
5387
5388 case Builtin::BI__sync_fetch_and_nand:
5389 case Builtin::BI__sync_fetch_and_nand_1:
5390 case Builtin::BI__sync_fetch_and_nand_2:
5391 case Builtin::BI__sync_fetch_and_nand_4:
5392 case Builtin::BI__sync_fetch_and_nand_8:
5393 case Builtin::BI__sync_fetch_and_nand_16:
5394 BuiltinIndex = 5;
5395 WarnAboutSemanticsChange = true;
5396 break;
5397
5398 case Builtin::BI__sync_add_and_fetch:
5399 case Builtin::BI__sync_add_and_fetch_1:
5400 case Builtin::BI__sync_add_and_fetch_2:
5401 case Builtin::BI__sync_add_and_fetch_4:
5402 case Builtin::BI__sync_add_and_fetch_8:
5403 case Builtin::BI__sync_add_and_fetch_16:
5404 BuiltinIndex = 6;
5405 break;
5406
5407 case Builtin::BI__sync_sub_and_fetch:
5408 case Builtin::BI__sync_sub_and_fetch_1:
5409 case Builtin::BI__sync_sub_and_fetch_2:
5410 case Builtin::BI__sync_sub_and_fetch_4:
5411 case Builtin::BI__sync_sub_and_fetch_8:
5412 case Builtin::BI__sync_sub_and_fetch_16:
5413 BuiltinIndex = 7;
5414 break;
5415
5416 case Builtin::BI__sync_and_and_fetch:
5417 case Builtin::BI__sync_and_and_fetch_1:
5418 case Builtin::BI__sync_and_and_fetch_2:
5419 case Builtin::BI__sync_and_and_fetch_4:
5420 case Builtin::BI__sync_and_and_fetch_8:
5421 case Builtin::BI__sync_and_and_fetch_16:
5422 BuiltinIndex = 8;
5423 break;
5424
5425 case Builtin::BI__sync_or_and_fetch:
5426 case Builtin::BI__sync_or_and_fetch_1:
5427 case Builtin::BI__sync_or_and_fetch_2:
5428 case Builtin::BI__sync_or_and_fetch_4:
5429 case Builtin::BI__sync_or_and_fetch_8:
5430 case Builtin::BI__sync_or_and_fetch_16:
5431 BuiltinIndex = 9;
5432 break;
5433
5434 case Builtin::BI__sync_xor_and_fetch:
5435 case Builtin::BI__sync_xor_and_fetch_1:
5436 case Builtin::BI__sync_xor_and_fetch_2:
5437 case Builtin::BI__sync_xor_and_fetch_4:
5438 case Builtin::BI__sync_xor_and_fetch_8:
5439 case Builtin::BI__sync_xor_and_fetch_16:
5440 BuiltinIndex = 10;
5441 break;
5442
5443 case Builtin::BI__sync_nand_and_fetch:
5444 case Builtin::BI__sync_nand_and_fetch_1:
5445 case Builtin::BI__sync_nand_and_fetch_2:
5446 case Builtin::BI__sync_nand_and_fetch_4:
5447 case Builtin::BI__sync_nand_and_fetch_8:
5448 case Builtin::BI__sync_nand_and_fetch_16:
5449 BuiltinIndex = 11;
5450 WarnAboutSemanticsChange = true;
5451 break;
5452
5453 case Builtin::BI__sync_val_compare_and_swap:
5454 case Builtin::BI__sync_val_compare_and_swap_1:
5455 case Builtin::BI__sync_val_compare_and_swap_2:
5456 case Builtin::BI__sync_val_compare_and_swap_4:
5457 case Builtin::BI__sync_val_compare_and_swap_8:
5458 case Builtin::BI__sync_val_compare_and_swap_16:
5459 BuiltinIndex = 12;
5460 NumFixed = 2;
5461 break;
5462
5463 case Builtin::BI__sync_bool_compare_and_swap:
5464 case Builtin::BI__sync_bool_compare_and_swap_1:
5465 case Builtin::BI__sync_bool_compare_and_swap_2:
5466 case Builtin::BI__sync_bool_compare_and_swap_4:
5467 case Builtin::BI__sync_bool_compare_and_swap_8:
5468 case Builtin::BI__sync_bool_compare_and_swap_16:
5469 BuiltinIndex = 13;
5470 NumFixed = 2;
5471 ResultType = Context.BoolTy;
5472 break;
5473
5474 case Builtin::BI__sync_lock_test_and_set:
5475 case Builtin::BI__sync_lock_test_and_set_1:
5476 case Builtin::BI__sync_lock_test_and_set_2:
5477 case Builtin::BI__sync_lock_test_and_set_4:
5478 case Builtin::BI__sync_lock_test_and_set_8:
5479 case Builtin::BI__sync_lock_test_and_set_16:
5480 BuiltinIndex = 14;
5481 break;
5482
5483 case Builtin::BI__sync_lock_release:
5484 case Builtin::BI__sync_lock_release_1:
5485 case Builtin::BI__sync_lock_release_2:
5486 case Builtin::BI__sync_lock_release_4:
5487 case Builtin::BI__sync_lock_release_8:
5488 case Builtin::BI__sync_lock_release_16:
5489 BuiltinIndex = 15;
5490 NumFixed = 0;
5491 ResultType = Context.VoidTy;
5492 break;
5493
5494 case Builtin::BI__sync_swap:
5495 case Builtin::BI__sync_swap_1:
5496 case Builtin::BI__sync_swap_2:
5497 case Builtin::BI__sync_swap_4:
5498 case Builtin::BI__sync_swap_8:
5499 case Builtin::BI__sync_swap_16:
5500 BuiltinIndex = 16;
5501 break;
5502 }
5503
5504 // Now that we know how many fixed arguments we expect, first check that we
5505 // have at least that many.
5506 if (TheCall->getNumArgs() < 1+NumFixed) {
5507 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5508 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5509 << Callee->getSourceRange();
5510 return ExprError();
5511 }
5512
5513 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5514 << Callee->getSourceRange();
5515
5516 if (WarnAboutSemanticsChange) {
5517 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5518 << Callee->getSourceRange();
5519 }
5520
5521 // Get the decl for the concrete builtin from this, we can tell what the
5522 // concrete integer type we should convert to is.
5523 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5524 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5525 FunctionDecl *NewBuiltinDecl;
5526 if (NewBuiltinID == BuiltinID)
5527 NewBuiltinDecl = FDecl;
5528 else {
5529 // Perform builtin lookup to avoid redeclaring it.
5530 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5531 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5532 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5533 assert(Res.getFoundDecl());
5534 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5535 if (!NewBuiltinDecl)
5536 return ExprError();
5537 }
5538
5539 // The first argument --- the pointer --- has a fixed type; we
5540 // deduce the types of the rest of the arguments accordingly. Walk
5541 // the remaining arguments, converting them to the deduced value type.
5542 for (unsigned i = 0; i != NumFixed; ++i) {
5543 ExprResult Arg = TheCall->getArg(i+1);
5544
5545 // GCC does an implicit conversion to the pointer or integer ValType. This
5546 // can fail in some cases (1i -> int**), check for this error case now.
5547 // Initialize the argument.
5548 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5549 ValType, /*consume*/ false);
5550 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5551 if (Arg.isInvalid())
5552 return ExprError();
5553
5554 // Okay, we have something that *can* be converted to the right type. Check
5555 // to see if there is a potentially weird extension going on here. This can
5556 // happen when you do an atomic operation on something like an char* and
5557 // pass in 42. The 42 gets converted to char. This is even more strange
5558 // for things like 45.123 -> char, etc.
5559 // FIXME: Do this check.
5560 TheCall->setArg(i+1, Arg.get());
5561 }
5562
5563 // Create a new DeclRefExpr to refer to the new decl.
5564 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5565 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5566 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5567 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5568
5569 // Set the callee in the CallExpr.
5570 // FIXME: This loses syntactic information.
5571 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5572 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5573 CK_BuiltinFnToFnPtr);
5574 TheCall->setCallee(PromotedCall.get());
5575
5576 // Change the result type of the call to match the original value type. This
5577 // is arbitrary, but the codegen for these builtins ins design to handle it
5578 // gracefully.
5579 TheCall->setType(ResultType);
5580
5581 // Prohibit problematic uses of bit-precise integer types with atomic
5582 // builtins. The arguments would have already been converted to the first
5583 // argument's type, so only need to check the first argument.
5584 const auto *BitIntValType = ValType->getAs<BitIntType>();
5585 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
5586 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5587 return ExprError();
5588 }
5589
5590 return TheCallResult;
5591}
5592
5593ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5594 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5595 DeclRefExpr *DRE =
5597 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5598 unsigned BuiltinID = FDecl->getBuiltinID();
5599 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5600 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5601 "Unexpected nontemporal load/store builtin!");
5602 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5603 unsigned numArgs = isStore ? 2 : 1;
5604
5605 // Ensure that we have the proper number of arguments.
5606 if (checkArgCount(TheCall, numArgs))
5607 return ExprError();
5608
5609 // Inspect the last argument of the nontemporal builtin. This should always
5610 // be a pointer type, from which we imply the type of the memory access.
5611 // Because it is a pointer type, we don't have to worry about any implicit
5612 // casts here.
5613 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5614 ExprResult PointerArgResult =
5616
5617 if (PointerArgResult.isInvalid())
5618 return ExprError();
5619 PointerArg = PointerArgResult.get();
5620 TheCall->setArg(numArgs - 1, PointerArg);
5621
5622 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5623 if (!pointerType) {
5624 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5625 << PointerArg->getType() << PointerArg->getSourceRange();
5626 return ExprError();
5627 }
5628
5629 QualType ValType = pointerType->getPointeeType();
5630
5631 // Strip any qualifiers off ValType.
5632 ValType = ValType.getUnqualifiedType();
5633 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5634 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5635 !ValType->isVectorType()) {
5636 Diag(DRE->getBeginLoc(),
5637 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5638 << PointerArg->getType() << PointerArg->getSourceRange();
5639 return ExprError();
5640 }
5641
5642 if (!isStore) {
5643 TheCall->setType(ValType);
5644 return TheCallResult;
5645 }
5646
5647 ExprResult ValArg = TheCall->getArg(0);
5648 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5649 Context, ValType, /*consume*/ false);
5650 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5651 if (ValArg.isInvalid())
5652 return ExprError();
5653
5654 TheCall->setArg(0, ValArg.get());
5655 TheCall->setType(Context.VoidTy);
5656 return TheCallResult;
5657}
5658
5659/// CheckObjCString - Checks that the format string argument to the os_log()
5660/// and os_trace() functions is correct, and converts it to const char *.
5661ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5662 Arg = Arg->IgnoreParenCasts();
5663 auto *Literal = dyn_cast<StringLiteral>(Arg);
5664 if (!Literal) {
5665 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5666 Literal = ObjcLiteral->getString();
5667 }
5668 }
5669
5670 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5671 return ExprError(
5672 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5673 << Arg->getSourceRange());
5674 }
5675
5676 ExprResult Result(Literal);
5677 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5678 InitializedEntity Entity =
5680 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5681 return Result;
5682}
5683
5684/// Check that the user is calling the appropriate va_start builtin for the
5685/// target and calling convention.
5686static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5687 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5688 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5689 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5690 TT.getArch() == llvm::Triple::aarch64_32);
5691 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5692 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5693 if (IsX64 || IsAArch64) {
5694 CallingConv CC = CC_C;
5695 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5696 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5697 if (IsMSVAStart) {
5698 // Don't allow this in System V ABI functions.
5699 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5700 return S.Diag(Fn->getBeginLoc(),
5701 diag::err_ms_va_start_used_in_sysv_function);
5702 } else {
5703 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5704 // On x64 Windows, don't allow this in System V ABI functions.
5705 // (Yes, that means there's no corresponding way to support variadic
5706 // System V ABI functions on Windows.)
5707 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5708 (!IsWindowsOrUEFI && CC == CC_Win64))
5709 return S.Diag(Fn->getBeginLoc(),
5710 diag::err_va_start_used_in_wrong_abi_function)
5711 << !IsWindowsOrUEFI;
5712 }
5713 return false;
5714 }
5715
5716 if (IsMSVAStart)
5717 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5718 return false;
5719}
5720
5722 ParmVarDecl **LastParam = nullptr) {
5723 // Determine whether the current function, block, or obj-c method is variadic
5724 // and get its parameter list.
5725 bool IsVariadic = false;
5727 DeclContext *Caller = S.CurContext;
5728 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5729 IsVariadic = Block->isVariadic();
5730 Params = Block->parameters();
5731 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5732 IsVariadic = FD->isVariadic();
5733 Params = FD->parameters();
5734 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5735 IsVariadic = MD->isVariadic();
5736 // FIXME: This isn't correct for methods (results in bogus warning).
5737 Params = MD->parameters();
5738 } else if (isa<CapturedDecl>(Caller)) {
5739 // We don't support va_start in a CapturedDecl.
5740 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5741 return true;
5742 } else {
5743 // This must be some other declcontext that parses exprs.
5744 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5745 return true;
5746 }
5747
5748 if (!IsVariadic) {
5749 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5750 return true;
5751 }
5752
5753 if (LastParam)
5754 *LastParam = Params.empty() ? nullptr : Params.back();
5755
5756 return false;
5757}
5758
5759bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5760 Expr *Fn = TheCall->getCallee();
5761 if (checkVAStartABI(*this, BuiltinID, Fn))
5762 return true;
5763
5764 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
5765 // This builtin requires one argument (the va_list), allows two arguments,
5766 // but diagnoses more than two arguments. e.g.,
5767 // __builtin_c23_va_start(); // error
5768 // __builtin_c23_va_start(list); // ok
5769 // __builtin_c23_va_start(list, param); // ok
5770 // __builtin_c23_va_start(list, anything, anything); // error
5771 // This differs from the GCC behavior in that they accept the last case
5772 // with a warning, but it doesn't seem like a useful behavior to allow.
5773 if (checkArgCountRange(TheCall, 1, 2))
5774 return true;
5775 } else {
5776 // In C23 mode, va_start only needs one argument. However, the builtin still
5777 // requires two arguments (which matches the behavior of the GCC builtin),
5778 // <stdarg.h> passes `0` as the second argument in C23 mode.
5779 if (checkArgCount(TheCall, 2))
5780 return true;
5781 }
5782
5783 // Type-check the first argument normally.
5784 if (checkBuiltinArgument(*this, TheCall, 0))
5785 return true;
5786
5787 // Check that the current function is variadic, and get its last parameter.
5788 ParmVarDecl *LastParam;
5789 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5790 return true;
5791
5792 // Verify that the second argument to the builtin is the last non-variadic
5793 // argument of the current function or method. In C23 mode, if the call is
5794 // not to __builtin_c23_va_start, and the second argument is an integer
5795 // constant expression with value 0, then we don't bother with this check.
5796 // For __builtin_c23_va_start, we only perform the check for the second
5797 // argument being the last argument to the current function if there is a
5798 // second argument present.
5799 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
5800 TheCall->getNumArgs() < 2) {
5801 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5802 return false;
5803 }
5804
5805 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5806 if (std::optional<llvm::APSInt> Val =
5808 Val && LangOpts.C23 && *Val == 0 &&
5809 BuiltinID != Builtin::BI__builtin_c23_va_start) {
5810 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5811 return false;
5812 }
5813
5814 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
5815 // next block.
5816 QualType Type;
5817 SourceLocation ParamLoc;
5818 bool IsCRegister = false;
5819 bool SecondArgIsLastNonVariadicArgument = false;
5820 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5821 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5822 SecondArgIsLastNonVariadicArgument = PV == LastParam;
5823
5824 Type = PV->getType();
5825 ParamLoc = PV->getLocation();
5826 IsCRegister =
5827 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5828 }
5829 }
5830
5831 if (!SecondArgIsLastNonVariadicArgument)
5832 Diag(TheCall->getArg(1)->getBeginLoc(),
5833 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
5834 else if (IsCRegister || Type->isReferenceType() ||
5835 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5836 // Promotable integers are UB, but enumerations need a bit of
5837 // extra checking to see what their promotable type actually is.
5838 if (!Context.isPromotableIntegerType(Type))
5839 return false;
5840 const auto *ED = Type->getAsEnumDecl();
5841 if (!ED)
5842 return true;
5843 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
5844 }()) {
5845 unsigned Reason = 0;
5846 if (Type->isReferenceType()) Reason = 1;
5847 else if (IsCRegister) Reason = 2;
5848 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5849 Diag(ParamLoc, diag::note_parameter_type) << Type;
5850 }
5851
5852 return false;
5853}
5854
5855bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
5856 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
5857 const LangOptions &LO = getLangOpts();
5858
5859 if (LO.CPlusPlus)
5860 return Arg->getType()
5862 .getTypePtr()
5863 ->getPointeeType()
5865
5866 // In C, allow aliasing through `char *`, this is required for AArch64 at
5867 // least.
5868 return true;
5869 };
5870
5871 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5872 // const char *named_addr);
5873
5874 Expr *Func = Call->getCallee();
5875
5876 if (Call->getNumArgs() < 3)
5877 return Diag(Call->getEndLoc(),
5878 diag::err_typecheck_call_too_few_args_at_least)
5879 << 0 /*function call*/ << 3 << Call->getNumArgs()
5880 << /*is non object*/ 0;
5881
5882 // Type-check the first argument normally.
5883 if (checkBuiltinArgument(*this, Call, 0))
5884 return true;
5885
5886 // Check that the current function is variadic.
5888 return true;
5889
5890 // __va_start on Windows does not validate the parameter qualifiers
5891
5892 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5893 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5894
5895 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5896 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5897
5898 const QualType &ConstCharPtrTy =
5899 Context.getPointerType(Context.CharTy.withConst());
5900 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
5901 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5902 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5903 << 0 /* qualifier difference */
5904 << 3 /* parameter mismatch */
5905 << 2 << Arg1->getType() << ConstCharPtrTy;
5906
5907 const QualType SizeTy = Context.getSizeType();
5908 if (!Context.hasSameType(
5910 SizeTy))
5911 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5912 << Arg2->getType() << SizeTy << 1 /* different class */
5913 << 0 /* qualifier difference */
5914 << 3 /* parameter mismatch */
5915 << 3 << Arg2->getType() << SizeTy;
5916
5917 return false;
5918}
5919
5920bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
5921 if (checkArgCount(TheCall, 2))
5922 return true;
5923
5924 if (BuiltinID == Builtin::BI__builtin_isunordered &&
5925 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
5926 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5927 << 1 << 0 << TheCall->getSourceRange();
5928
5929 ExprResult OrigArg0 = TheCall->getArg(0);
5930 ExprResult OrigArg1 = TheCall->getArg(1);
5931
5932 // Do standard promotions between the two arguments, returning their common
5933 // type.
5934 QualType Res = UsualArithmeticConversions(
5935 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
5936 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5937 return true;
5938
5939 // Make sure any conversions are pushed back into the call; this is
5940 // type safe since unordered compare builtins are declared as "_Bool
5941 // foo(...)".
5942 TheCall->setArg(0, OrigArg0.get());
5943 TheCall->setArg(1, OrigArg1.get());
5944
5945 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5946 return false;
5947
5948 // If the common type isn't a real floating type, then the arguments were
5949 // invalid for this operation.
5950 if (Res.isNull() || !Res->isRealFloatingType())
5951 return Diag(OrigArg0.get()->getBeginLoc(),
5952 diag::err_typecheck_call_invalid_ordered_compare)
5953 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5954 << SourceRange(OrigArg0.get()->getBeginLoc(),
5955 OrigArg1.get()->getEndLoc());
5956
5957 return false;
5958}
5959
5960bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
5961 unsigned BuiltinID) {
5962 if (checkArgCount(TheCall, NumArgs))
5963 return true;
5964
5965 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
5966 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
5967 BuiltinID == Builtin::BI__builtin_isinf ||
5968 BuiltinID == Builtin::BI__builtin_isinf_sign))
5969 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5970 << 0 << 0 << TheCall->getSourceRange();
5971
5972 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
5973 BuiltinID == Builtin::BI__builtin_isunordered))
5974 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5975 << 1 << 0 << TheCall->getSourceRange();
5976
5977 bool IsFPClass = NumArgs == 2;
5978
5979 // Find out position of floating-point argument.
5980 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
5981
5982 // We can count on all parameters preceding the floating-point just being int.
5983 // Try all of those.
5984 for (unsigned i = 0; i < FPArgNo; ++i) {
5985 Expr *Arg = TheCall->getArg(i);
5986
5987 if (Arg->isTypeDependent())
5988 return false;
5989
5992
5993 if (Res.isInvalid())
5994 return true;
5995 TheCall->setArg(i, Res.get());
5996 }
5997
5998 Expr *OrigArg = TheCall->getArg(FPArgNo);
5999
6000 if (OrigArg->isTypeDependent())
6001 return false;
6002
6003 // Usual Unary Conversions will convert half to float, which we want for
6004 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6005 // type how it is, but do normal L->Rvalue conversions.
6006 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
6007 ExprResult Res = UsualUnaryConversions(OrigArg);
6008
6009 if (!Res.isUsable())
6010 return true;
6011 OrigArg = Res.get();
6012 } else {
6014
6015 if (!Res.isUsable())
6016 return true;
6017 OrigArg = Res.get();
6018 }
6019 TheCall->setArg(FPArgNo, OrigArg);
6020
6021 QualType VectorResultTy;
6022 QualType ElementTy = OrigArg->getType();
6023 // TODO: When all classification function are implemented with is_fpclass,
6024 // vector argument can be supported in all of them.
6025 if (ElementTy->isVectorType() && IsFPClass) {
6026 VectorResultTy = GetSignedVectorType(ElementTy);
6027 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6028 }
6029
6030 // This operation requires a non-_Complex floating-point number.
6031 if (!ElementTy->isRealFloatingType())
6032 return Diag(OrigArg->getBeginLoc(),
6033 diag::err_typecheck_call_invalid_unary_fp)
6034 << OrigArg->getType() << OrigArg->getSourceRange();
6035
6036 // __builtin_isfpclass has integer parameter that specify test mask. It is
6037 // passed in (...), so it should be analyzed completely here.
6038 if (IsFPClass)
6039 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
6040 return true;
6041
6042 // TODO: enable this code to all classification functions.
6043 if (IsFPClass) {
6044 QualType ResultTy;
6045 if (!VectorResultTy.isNull())
6046 ResultTy = VectorResultTy;
6047 else
6048 ResultTy = Context.IntTy;
6049 TheCall->setType(ResultTy);
6050 }
6051
6052 return false;
6053}
6054
6055bool Sema::BuiltinComplex(CallExpr *TheCall) {
6056 if (checkArgCount(TheCall, 2))
6057 return true;
6058
6059 bool Dependent = false;
6060 for (unsigned I = 0; I != 2; ++I) {
6061 Expr *Arg = TheCall->getArg(I);
6062 QualType T = Arg->getType();
6063 if (T->isDependentType()) {
6064 Dependent = true;
6065 continue;
6066 }
6067
6068 // Despite supporting _Complex int, GCC requires a real floating point type
6069 // for the operands of __builtin_complex.
6070 if (!T->isRealFloatingType()) {
6071 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6072 << Arg->getType() << Arg->getSourceRange();
6073 }
6074
6075 ExprResult Converted = DefaultLvalueConversion(Arg);
6076 if (Converted.isInvalid())
6077 return true;
6078 TheCall->setArg(I, Converted.get());
6079 }
6080
6081 if (Dependent) {
6082 TheCall->setType(Context.DependentTy);
6083 return false;
6084 }
6085
6086 Expr *Real = TheCall->getArg(0);
6087 Expr *Imag = TheCall->getArg(1);
6088 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6089 return Diag(Real->getBeginLoc(),
6090 diag::err_typecheck_call_different_arg_types)
6091 << Real->getType() << Imag->getType()
6092 << Real->getSourceRange() << Imag->getSourceRange();
6093 }
6094
6095 TheCall->setType(Context.getComplexType(Real->getType()));
6096 return false;
6097}
6098
6099/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6100// This is declared to take (...), so we have to check everything.
6102 unsigned NumArgs = TheCall->getNumArgs();
6103 if (NumArgs < 2)
6104 return ExprError(Diag(TheCall->getEndLoc(),
6105 diag::err_typecheck_call_too_few_args_at_least)
6106 << 0 /*function call*/ << 2 << NumArgs
6107 << /*is non object*/ 0 << TheCall->getSourceRange());
6108
6109 // Determine which of the following types of shufflevector we're checking:
6110 // 1) unary, vector mask: (lhs, mask)
6111 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6112 QualType ResType = TheCall->getArg(0)->getType();
6113 unsigned NumElements = 0;
6114
6115 if (!TheCall->getArg(0)->isTypeDependent() &&
6116 !TheCall->getArg(1)->isTypeDependent()) {
6117 QualType LHSType = TheCall->getArg(0)->getType();
6118 QualType RHSType = TheCall->getArg(1)->getType();
6119
6120 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6121 return ExprError(
6122 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6123 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6124 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6125 TheCall->getArg(1)->getEndLoc()));
6126
6127 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6128 unsigned NumResElements = NumArgs - 2;
6129
6130 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6131 // with mask. If so, verify that RHS is an integer vector type with the
6132 // same number of elts as lhs.
6133 if (NumArgs == 2) {
6134 if (!RHSType->hasIntegerRepresentation() ||
6135 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
6136 return ExprError(Diag(TheCall->getBeginLoc(),
6137 diag::err_vec_builtin_incompatible_vector)
6138 << TheCall->getDirectCallee()
6139 << /*isMoreThanTwoArgs*/ false
6140 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6141 TheCall->getArg(1)->getEndLoc()));
6142 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6143 return ExprError(Diag(TheCall->getBeginLoc(),
6144 diag::err_vec_builtin_incompatible_vector)
6145 << TheCall->getDirectCallee()
6146 << /*isMoreThanTwoArgs*/ false
6147 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6148 TheCall->getArg(1)->getEndLoc()));
6149 } else if (NumElements != NumResElements) {
6150 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6151 ResType = ResType->isExtVectorType()
6152 ? Context.getExtVectorType(EltType, NumResElements)
6153 : Context.getVectorType(EltType, NumResElements,
6155 }
6156 }
6157
6158 for (unsigned I = 2; I != NumArgs; ++I) {
6159 Expr *Arg = TheCall->getArg(I);
6160 if (Arg->isTypeDependent() || Arg->isValueDependent())
6161 continue;
6162
6163 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
6164 if (!Result)
6165 return ExprError(Diag(TheCall->getBeginLoc(),
6166 diag::err_shufflevector_nonconstant_argument)
6167 << Arg->getSourceRange());
6168
6169 // Allow -1 which will be translated to undef in the IR.
6170 if (Result->isSigned() && Result->isAllOnes())
6171 ;
6172 else if (Result->getActiveBits() > 64 ||
6173 Result->getZExtValue() >= NumElements * 2)
6174 return ExprError(Diag(TheCall->getBeginLoc(),
6175 diag::err_shufflevector_argument_too_large)
6176 << Arg->getSourceRange());
6177
6178 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
6179 }
6180
6181 auto *Result = new (Context) ShuffleVectorExpr(
6182 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6183 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6184
6185 // All moved to Result.
6186 TheCall->shrinkNumArgs(0);
6187 return Result;
6188}
6189
6191 SourceLocation BuiltinLoc,
6192 SourceLocation RParenLoc) {
6195 QualType DstTy = TInfo->getType();
6196 QualType SrcTy = E->getType();
6197
6198 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6199 return ExprError(Diag(BuiltinLoc,
6200 diag::err_convertvector_non_vector)
6201 << E->getSourceRange());
6202 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6203 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
6204 << "second"
6205 << "__builtin_convertvector");
6206
6207 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6208 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6209 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6210 if (SrcElts != DstElts)
6211 return ExprError(Diag(BuiltinLoc,
6212 diag::err_convertvector_incompatible_vector)
6213 << E->getSourceRange());
6214 }
6215
6216 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
6217 RParenLoc, CurFPFeatureOverrides());
6218}
6219
6220bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6221 unsigned NumArgs = TheCall->getNumArgs();
6222
6223 if (NumArgs > 3)
6224 return Diag(TheCall->getEndLoc(),
6225 diag::err_typecheck_call_too_many_args_at_most)
6226 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6227 << TheCall->getSourceRange();
6228
6229 // Argument 0 is checked for us and the remaining arguments must be
6230 // constant integers.
6231 for (unsigned i = 1; i != NumArgs; ++i)
6232 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6233 return true;
6234
6235 return false;
6236}
6237
6238bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6239 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6240 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6241 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6242 if (checkArgCount(TheCall, 1))
6243 return true;
6244 Expr *Arg = TheCall->getArg(0);
6245 if (Arg->isInstantiationDependent())
6246 return false;
6247
6248 QualType ArgTy = Arg->getType();
6249 if (!ArgTy->hasFloatingRepresentation())
6250 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6251 << ArgTy;
6252 if (Arg->isLValue()) {
6253 ExprResult FirstArg = DefaultLvalueConversion(Arg);
6254 TheCall->setArg(0, FirstArg.get());
6255 }
6256 TheCall->setType(TheCall->getArg(0)->getType());
6257 return false;
6258}
6259
6260bool Sema::BuiltinAssume(CallExpr *TheCall) {
6261 Expr *Arg = TheCall->getArg(0);
6262 if (Arg->isInstantiationDependent()) return false;
6263
6264 if (Arg->HasSideEffects(Context))
6265 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6266 << Arg->getSourceRange()
6267 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6268
6269 return false;
6270}
6271
6272bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6273 // The alignment must be a constant integer.
6274 Expr *Arg = TheCall->getArg(1);
6275
6276 // We can't check the value of a dependent argument.
6277 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6278 if (const auto *UE =
6279 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6280 if (UE->getKind() == UETT_AlignOf ||
6281 UE->getKind() == UETT_PreferredAlignOf)
6282 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6283 << Arg->getSourceRange();
6284
6285 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6286
6287 if (!Result.isPowerOf2())
6288 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6289 << Arg->getSourceRange();
6290
6291 if (Result < Context.getCharWidth())
6292 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6293 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6294
6295 if (Result > std::numeric_limits<int32_t>::max())
6296 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6297 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6298 }
6299
6300 return false;
6301}
6302
6303bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6304 if (checkArgCountRange(TheCall, 2, 3))
6305 return true;
6306
6307 unsigned NumArgs = TheCall->getNumArgs();
6308 Expr *FirstArg = TheCall->getArg(0);
6309
6310 {
6311 ExprResult FirstArgResult =
6313 if (!FirstArgResult.get()->getType()->isPointerType()) {
6314 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
6315 << TheCall->getSourceRange();
6316 return true;
6317 }
6318 TheCall->setArg(0, FirstArgResult.get());
6319 }
6320
6321 // The alignment must be a constant integer.
6322 Expr *SecondArg = TheCall->getArg(1);
6323
6324 // We can't check the value of a dependent argument.
6325 if (!SecondArg->isValueDependent()) {
6326 llvm::APSInt Result;
6327 if (BuiltinConstantArg(TheCall, 1, Result))
6328 return true;
6329
6330 if (!Result.isPowerOf2())
6331 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6332 << SecondArg->getSourceRange();
6333
6335 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6336 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6337
6338 TheCall->setArg(1,
6340 }
6341
6342 if (NumArgs > 2) {
6343 Expr *ThirdArg = TheCall->getArg(2);
6344 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
6345 return true;
6346 TheCall->setArg(2, ThirdArg);
6347 }
6348
6349 return false;
6350}
6351
6352bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6353 unsigned BuiltinID =
6354 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6355 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6356
6357 unsigned NumArgs = TheCall->getNumArgs();
6358 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6359 if (NumArgs < NumRequiredArgs) {
6360 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6361 << 0 /* function call */ << NumRequiredArgs << NumArgs
6362 << /*is non object*/ 0 << TheCall->getSourceRange();
6363 }
6364 if (NumArgs >= NumRequiredArgs + 0x100) {
6365 return Diag(TheCall->getEndLoc(),
6366 diag::err_typecheck_call_too_many_args_at_most)
6367 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6368 << /*is non object*/ 0 << TheCall->getSourceRange();
6369 }
6370 unsigned i = 0;
6371
6372 // For formatting call, check buffer arg.
6373 if (!IsSizeCall) {
6374 ExprResult Arg(TheCall->getArg(i));
6375 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6376 Context, Context.VoidPtrTy, false);
6377 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6378 if (Arg.isInvalid())
6379 return true;
6380 TheCall->setArg(i, Arg.get());
6381 i++;
6382 }
6383
6384 // Check string literal arg.
6385 unsigned FormatIdx = i;
6386 {
6387 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6388 if (Arg.isInvalid())
6389 return true;
6390 TheCall->setArg(i, Arg.get());
6391 i++;
6392 }
6393
6394 // Make sure variadic args are scalar.
6395 unsigned FirstDataArg = i;
6396 while (i < NumArgs) {
6398 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6399 if (Arg.isInvalid())
6400 return true;
6401 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6402 if (ArgSize.getQuantity() >= 0x100) {
6403 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6404 << i << (int)ArgSize.getQuantity() << 0xff
6405 << TheCall->getSourceRange();
6406 }
6407 TheCall->setArg(i, Arg.get());
6408 i++;
6409 }
6410
6411 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6412 // call to avoid duplicate diagnostics.
6413 if (!IsSizeCall) {
6414 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6415 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6416 bool Success = CheckFormatArguments(
6417 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
6419 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
6420 if (!Success)
6421 return true;
6422 }
6423
6424 if (IsSizeCall) {
6425 TheCall->setType(Context.getSizeType());
6426 } else {
6427 TheCall->setType(Context.VoidPtrTy);
6428 }
6429 return false;
6430}
6431
6432bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6433 llvm::APSInt &Result) {
6434 Expr *Arg = TheCall->getArg(ArgNum);
6435
6436 if (Arg->isTypeDependent() || Arg->isValueDependent())
6437 return false;
6438
6439 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
6440 if (!R) {
6441 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6442 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6443 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6444 << FDecl->getDeclName() << Arg->getSourceRange();
6445 }
6446 Result = *R;
6447
6448 return false;
6449}
6450
6451bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6452 int High, bool RangeIsError) {
6454 return false;
6455 llvm::APSInt Result;
6456
6457 // We can't check the value of a dependent argument.
6458 Expr *Arg = TheCall->getArg(ArgNum);
6459 if (Arg->isTypeDependent() || Arg->isValueDependent())
6460 return false;
6461
6462 // Check constant-ness first.
6463 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6464 return true;
6465
6466 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6467 if (RangeIsError)
6468 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6469 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6470 else
6471 // Defer the warning until we know if the code will be emitted so that
6472 // dead code can ignore this.
6473 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6474 PDiag(diag::warn_argument_invalid_range)
6475 << toString(Result, 10) << Low << High
6476 << Arg->getSourceRange());
6477 }
6478
6479 return false;
6480}
6481
6482bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6483 unsigned Num) {
6484 llvm::APSInt Result;
6485
6486 // We can't check the value of a dependent argument.
6487 Expr *Arg = TheCall->getArg(ArgNum);
6488 if (Arg->isTypeDependent() || Arg->isValueDependent())
6489 return false;
6490
6491 // Check constant-ness first.
6492 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6493 return true;
6494
6495 if (Result.getSExtValue() % Num != 0)
6496 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6497 << Num << Arg->getSourceRange();
6498
6499 return false;
6500}
6501
6502bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6503 llvm::APSInt Result;
6504
6505 // We can't check the value of a dependent argument.
6506 Expr *Arg = TheCall->getArg(ArgNum);
6507 if (Arg->isTypeDependent() || Arg->isValueDependent())
6508 return false;
6509
6510 // Check constant-ness first.
6511 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6512 return true;
6513
6514 if (Result.isPowerOf2())
6515 return false;
6516
6517 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6518 << Arg->getSourceRange();
6519}
6520
6521static bool IsShiftedByte(llvm::APSInt Value) {
6522 if (Value.isNegative())
6523 return false;
6524
6525 // Check if it's a shifted byte, by shifting it down
6526 while (true) {
6527 // If the value fits in the bottom byte, the check passes.
6528 if (Value < 0x100)
6529 return true;
6530
6531 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6532 // fails.
6533 if ((Value & 0xFF) != 0)
6534 return false;
6535
6536 // If the bottom 8 bits are all 0, but something above that is nonzero,
6537 // then shifting the value right by 8 bits won't affect whether it's a
6538 // shifted byte or not. So do that, and go round again.
6539 Value >>= 8;
6540 }
6541}
6542
6543bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6544 unsigned ArgBits) {
6545 llvm::APSInt Result;
6546
6547 // We can't check the value of a dependent argument.
6548 Expr *Arg = TheCall->getArg(ArgNum);
6549 if (Arg->isTypeDependent() || Arg->isValueDependent())
6550 return false;
6551
6552 // Check constant-ness first.
6553 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6554 return true;
6555
6556 // Truncate to the given size.
6557 Result = Result.getLoBits(ArgBits);
6558 Result.setIsUnsigned(true);
6559
6560 if (IsShiftedByte(Result))
6561 return false;
6562
6563 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6564 << Arg->getSourceRange();
6565}
6566
6568 unsigned ArgNum,
6569 unsigned ArgBits) {
6570 llvm::APSInt Result;
6571
6572 // We can't check the value of a dependent argument.
6573 Expr *Arg = TheCall->getArg(ArgNum);
6574 if (Arg->isTypeDependent() || Arg->isValueDependent())
6575 return false;
6576
6577 // Check constant-ness first.
6578 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6579 return true;
6580
6581 // Truncate to the given size.
6582 Result = Result.getLoBits(ArgBits);
6583 Result.setIsUnsigned(true);
6584
6585 // Check to see if it's in either of the required forms.
6586 if (IsShiftedByte(Result) ||
6587 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6588 return false;
6589
6590 return Diag(TheCall->getBeginLoc(),
6591 diag::err_argument_not_shifted_byte_or_xxff)
6592 << Arg->getSourceRange();
6593}
6594
6595bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6596 if (!Context.getTargetInfo().hasSjLjLowering())
6597 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6598 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6599
6600 Expr *Arg = TheCall->getArg(1);
6601 llvm::APSInt Result;
6602
6603 // TODO: This is less than ideal. Overload this to take a value.
6604 if (BuiltinConstantArg(TheCall, 1, Result))
6605 return true;
6606
6607 if (Result != 1)
6608 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6609 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6610
6611 return false;
6612}
6613
6614bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6615 if (!Context.getTargetInfo().hasSjLjLowering())
6616 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6617 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6618 return false;
6619}
6620
6621bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6622 if (checkArgCount(TheCall, 1))
6623 return true;
6624
6625 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
6626 if (ArgRes.isInvalid())
6627 return true;
6628
6629 // For simplicity, we support only limited expressions for the argument.
6630 // Specifically a flexible array member or a pointer with counted_by:
6631 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
6632 // complex casting, which really shouldn't be a huge problem.
6633 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6634 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
6635 return Diag(Arg->getBeginLoc(),
6636 diag::err_builtin_counted_by_ref_invalid_arg)
6637 << Arg->getSourceRange();
6638
6639 if (Arg->HasSideEffects(Context))
6640 return Diag(Arg->getBeginLoc(),
6641 diag::err_builtin_counted_by_ref_has_side_effects)
6642 << Arg->getSourceRange();
6643
6644 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
6645 const auto *CATy =
6646 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6647
6648 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6649 // Member has counted_by attribute - return pointer to count field
6650 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
6651 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
6652 TheCall->setType(Context.getPointerType(CountFD->getType()));
6653 return false;
6654 }
6655 }
6656
6657 // FAMs and pointers without counted_by return void*
6658 QualType MemberTy = ME->getMemberDecl()->getType();
6659 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
6660 return Diag(Arg->getBeginLoc(),
6661 diag::err_builtin_counted_by_ref_invalid_arg)
6662 << Arg->getSourceRange();
6663 } else {
6664 return Diag(Arg->getBeginLoc(),
6665 diag::err_builtin_counted_by_ref_invalid_arg)
6666 << Arg->getSourceRange();
6667 }
6668
6669 TheCall->setType(Context.getPointerType(Context.VoidTy));
6670 return false;
6671}
6672
6673/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6674/// It allows leaking and modification of bounds safety information.
6675bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6677 const CallExpr *CE =
6678 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
6679 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6680 return false;
6681
6682 switch (K) {
6685 Diag(E->getExprLoc(),
6686 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6687 << 0 << E->getSourceRange();
6688 break;
6690 Diag(E->getExprLoc(),
6691 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6692 << 1 << E->getSourceRange();
6693 break;
6695 Diag(E->getExprLoc(),
6696 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6697 << 2 << E->getSourceRange();
6698 break;
6700 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6701 << 0 << E->getSourceRange();
6702 break;
6704 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6705 << 1 << E->getSourceRange();
6706 break;
6707 }
6708
6709 return true;
6710}
6711
6712namespace {
6713
6714class UncoveredArgHandler {
6715 enum { Unknown = -1, AllCovered = -2 };
6716
6717 signed FirstUncoveredArg = Unknown;
6718 SmallVector<const Expr *, 4> DiagnosticExprs;
6719
6720public:
6721 UncoveredArgHandler() = default;
6722
6723 bool hasUncoveredArg() const {
6724 return (FirstUncoveredArg >= 0);
6725 }
6726
6727 unsigned getUncoveredArg() const {
6728 assert(hasUncoveredArg() && "no uncovered argument");
6729 return FirstUncoveredArg;
6730 }
6731
6732 void setAllCovered() {
6733 // A string has been found with all arguments covered, so clear out
6734 // the diagnostics.
6735 DiagnosticExprs.clear();
6736 FirstUncoveredArg = AllCovered;
6737 }
6738
6739 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6740 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6741
6742 // Don't update if a previous string covers all arguments.
6743 if (FirstUncoveredArg == AllCovered)
6744 return;
6745
6746 // UncoveredArgHandler tracks the highest uncovered argument index
6747 // and with it all the strings that match this index.
6748 if (NewFirstUncoveredArg == FirstUncoveredArg)
6749 DiagnosticExprs.push_back(StrExpr);
6750 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6751 DiagnosticExprs.clear();
6752 DiagnosticExprs.push_back(StrExpr);
6753 FirstUncoveredArg = NewFirstUncoveredArg;
6754 }
6755 }
6756
6757 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6758};
6759
6760enum StringLiteralCheckType {
6761 SLCT_NotALiteral,
6762 SLCT_UncheckedLiteral,
6763 SLCT_CheckedLiteral
6764};
6765
6766} // namespace
6767
6768static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6769 BinaryOperatorKind BinOpKind,
6770 bool AddendIsRight) {
6771 unsigned BitWidth = Offset.getBitWidth();
6772 unsigned AddendBitWidth = Addend.getBitWidth();
6773 // There might be negative interim results.
6774 if (Addend.isUnsigned()) {
6775 Addend = Addend.zext(++AddendBitWidth);
6776 Addend.setIsSigned(true);
6777 }
6778 // Adjust the bit width of the APSInts.
6779 if (AddendBitWidth > BitWidth) {
6780 Offset = Offset.sext(AddendBitWidth);
6781 BitWidth = AddendBitWidth;
6782 } else if (BitWidth > AddendBitWidth) {
6783 Addend = Addend.sext(BitWidth);
6784 }
6785
6786 bool Ov = false;
6787 llvm::APSInt ResOffset = Offset;
6788 if (BinOpKind == BO_Add)
6789 ResOffset = Offset.sadd_ov(Addend, Ov);
6790 else {
6791 assert(AddendIsRight && BinOpKind == BO_Sub &&
6792 "operator must be add or sub with addend on the right");
6793 ResOffset = Offset.ssub_ov(Addend, Ov);
6794 }
6795
6796 // We add an offset to a pointer here so we should support an offset as big as
6797 // possible.
6798 if (Ov) {
6799 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6800 "index (intermediate) result too big");
6801 Offset = Offset.sext(2 * BitWidth);
6802 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6803 return;
6804 }
6805
6806 Offset = std::move(ResOffset);
6807}
6808
6809namespace {
6810
6811// This is a wrapper class around StringLiteral to support offsetted string
6812// literals as format strings. It takes the offset into account when returning
6813// the string and its length or the source locations to display notes correctly.
6814class FormatStringLiteral {
6815 const StringLiteral *FExpr;
6816 int64_t Offset;
6817
6818public:
6819 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6820 : FExpr(fexpr), Offset(Offset) {}
6821
6822 const StringLiteral *getFormatString() const { return FExpr; }
6823
6824 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
6825
6826 unsigned getByteLength() const {
6827 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6828 }
6829
6830 unsigned getLength() const { return FExpr->getLength() - Offset; }
6831 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6832
6833 StringLiteralKind getKind() const { return FExpr->getKind(); }
6834
6835 QualType getType() const { return FExpr->getType(); }
6836
6837 bool isAscii() const { return FExpr->isOrdinary(); }
6838 bool isWide() const { return FExpr->isWide(); }
6839 bool isUTF8() const { return FExpr->isUTF8(); }
6840 bool isUTF16() const { return FExpr->isUTF16(); }
6841 bool isUTF32() const { return FExpr->isUTF32(); }
6842 bool isPascal() const { return FExpr->isPascal(); }
6843
6844 SourceLocation getLocationOfByte(
6845 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6846 const TargetInfo &Target, unsigned *StartToken = nullptr,
6847 unsigned *StartTokenByteOffset = nullptr) const {
6848 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6849 StartToken, StartTokenByteOffset);
6850 }
6851
6852 SourceLocation getBeginLoc() const LLVM_READONLY {
6853 return FExpr->getBeginLoc().getLocWithOffset(Offset);
6854 }
6855
6856 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6857};
6858
6859} // namespace
6860
6861static void CheckFormatString(
6862 Sema &S, const FormatStringLiteral *FExpr,
6863 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
6865 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6866 bool inFunctionCall, VariadicCallType CallType,
6867 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6868 bool IgnoreStringsWithoutSpecifiers);
6869
6870static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
6871 const Expr *E);
6872
6873// Determine if an expression is a string literal or constant string.
6874// If this function returns false on the arguments to a function expecting a
6875// format string, we will usually need to emit a warning.
6876// True string literals are then checked by CheckFormatString.
6877static StringLiteralCheckType
6878checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
6879 const Expr *E, ArrayRef<const Expr *> Args,
6880 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
6881 unsigned firstDataArg, FormatStringType Type,
6882 VariadicCallType CallType, bool InFunctionCall,
6883 llvm::SmallBitVector &CheckedVarArgs,
6884 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
6885 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
6886 bool IgnoreStringsWithoutSpecifiers = false) {
6888 return SLCT_NotALiteral;
6889tryAgain:
6890 assert(Offset.isSigned() && "invalid offset");
6891
6892 if (E->isTypeDependent() || E->isValueDependent())
6893 return SLCT_NotALiteral;
6894
6895 E = E->IgnoreParenCasts();
6896
6898 // Technically -Wformat-nonliteral does not warn about this case.
6899 // The behavior of printf and friends in this case is implementation
6900 // dependent. Ideally if the format string cannot be null then
6901 // it should have a 'nonnull' attribute in the function prototype.
6902 return SLCT_UncheckedLiteral;
6903
6904 switch (E->getStmtClass()) {
6905 case Stmt::InitListExprClass:
6906 // Handle expressions like {"foobar"}.
6907 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
6908 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
6909 format_idx, firstDataArg, Type, CallType,
6910 /*InFunctionCall*/ false, CheckedVarArgs,
6911 UncoveredArg, Offset, CallerFormatParamIdx,
6912 IgnoreStringsWithoutSpecifiers);
6913 }
6914 return SLCT_NotALiteral;
6915 case Stmt::BinaryConditionalOperatorClass:
6916 case Stmt::ConditionalOperatorClass: {
6917 // The expression is a literal if both sub-expressions were, and it was
6918 // completely checked only if both sub-expressions were checked.
6921
6922 // Determine whether it is necessary to check both sub-expressions, for
6923 // example, because the condition expression is a constant that can be
6924 // evaluated at compile time.
6925 bool CheckLeft = true, CheckRight = true;
6926
6927 bool Cond;
6928 if (C->getCond()->EvaluateAsBooleanCondition(
6930 if (Cond)
6931 CheckRight = false;
6932 else
6933 CheckLeft = false;
6934 }
6935
6936 // We need to maintain the offsets for the right and the left hand side
6937 // separately to check if every possible indexed expression is a valid
6938 // string literal. They might have different offsets for different string
6939 // literals in the end.
6940 StringLiteralCheckType Left;
6941 if (!CheckLeft)
6942 Left = SLCT_UncheckedLiteral;
6943 else {
6944 Left = checkFormatStringExpr(S, ReferenceFormatString, C->getTrueExpr(),
6945 Args, APK, format_idx, firstDataArg, Type,
6946 CallType, InFunctionCall, CheckedVarArgs,
6947 UncoveredArg, Offset, CallerFormatParamIdx,
6948 IgnoreStringsWithoutSpecifiers);
6949 if (Left == SLCT_NotALiteral || !CheckRight) {
6950 return Left;
6951 }
6952 }
6953
6954 StringLiteralCheckType Right = checkFormatStringExpr(
6955 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
6956 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6957 UncoveredArg, Offset, CallerFormatParamIdx,
6958 IgnoreStringsWithoutSpecifiers);
6959
6960 return (CheckLeft && Left < Right) ? Left : Right;
6961 }
6962
6963 case Stmt::ImplicitCastExprClass:
6964 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6965 goto tryAgain;
6966
6967 case Stmt::OpaqueValueExprClass:
6968 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6969 E = src;
6970 goto tryAgain;
6971 }
6972 return SLCT_NotALiteral;
6973
6974 case Stmt::PredefinedExprClass:
6975 // While __func__, etc., are technically not string literals, they
6976 // cannot contain format specifiers and thus are not a security
6977 // liability.
6978 return SLCT_UncheckedLiteral;
6979
6980 case Stmt::DeclRefExprClass: {
6981 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6982
6983 // As an exception, do not flag errors for variables binding to
6984 // const string literals.
6985 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6986 bool isConstant = false;
6987 QualType T = DR->getType();
6988
6989 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6990 isConstant = AT->getElementType().isConstant(S.Context);
6991 } else if (const PointerType *PT = T->getAs<PointerType>()) {
6992 isConstant = T.isConstant(S.Context) &&
6993 PT->getPointeeType().isConstant(S.Context);
6994 } else if (T->isObjCObjectPointerType()) {
6995 // In ObjC, there is usually no "const ObjectPointer" type,
6996 // so don't check if the pointee type is constant.
6997 isConstant = T.isConstant(S.Context);
6998 }
6999
7000 if (isConstant) {
7001 if (const Expr *Init = VD->getAnyInitializer()) {
7002 // Look through initializers like const char c[] = { "foo" }
7003 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7004 if (InitList->isStringLiteralInit())
7005 Init = InitList->getInit(0)->IgnoreParenImpCasts();
7006 }
7007 return checkFormatStringExpr(
7008 S, ReferenceFormatString, Init, Args, APK, format_idx,
7009 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7010 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7011 }
7012 }
7013
7014 // When the format argument is an argument of this function, and this
7015 // function also has the format attribute, there are several interactions
7016 // for which there shouldn't be a warning. For instance, when calling
7017 // v*printf from a function that has the printf format attribute, we
7018 // should not emit a warning about using `fmt`, even though it's not
7019 // constant, because the arguments have already been checked for the
7020 // caller of `logmessage`:
7021 //
7022 // __attribute__((format(printf, 1, 2)))
7023 // void logmessage(char const *fmt, ...) {
7024 // va_list ap;
7025 // va_start(ap, fmt);
7026 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7027 // ...
7028 // }
7029 //
7030 // Another interaction that we need to support is using a format string
7031 // specified by the format_matches attribute:
7032 //
7033 // __attribute__((format_matches(printf, 1, "%s %d")))
7034 // void logmessage(char const *fmt, const char *a, int b) {
7035 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7036 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7037 // ...
7038 // }
7039 //
7040 // Yet another interaction that we need to support is calling a variadic
7041 // format function from a format function that has fixed arguments. For
7042 // instance:
7043 //
7044 // __attribute__((format(printf, 1, 2)))
7045 // void logstring(char const *fmt, char const *str) {
7046 // printf(fmt, str); /* do not emit a warning about "fmt" */
7047 // }
7048 //
7049 // Same (and perhaps more relatably) for the variadic template case:
7050 //
7051 // template<typename... Args>
7052 // __attribute__((format(printf, 1, 2)))
7053 // void log(const char *fmt, Args&&... args) {
7054 // printf(fmt, forward<Args>(args)...);
7055 // /* do not emit a warning about "fmt" */
7056 // }
7057 //
7058 // Due to implementation difficulty, we only check the format, not the
7059 // format arguments, in all cases.
7060 //
7061 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
7062 if (CallerFormatParamIdx)
7063 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7064 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
7065 for (const auto *PVFormatMatches :
7066 D->specific_attrs<FormatMatchesAttr>()) {
7067 Sema::FormatStringInfo CalleeFSI;
7068 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
7069 0, &CalleeFSI))
7070 continue;
7071 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7072 // If using the wrong type of format string, emit a diagnostic
7073 // here and stop checking to avoid irrelevant diagnostics.
7074 if (Type != S.GetFormatStringType(PVFormatMatches)) {
7075 S.Diag(Args[format_idx]->getBeginLoc(),
7076 diag::warn_format_string_type_incompatible)
7077 << PVFormatMatches->getType()->getName()
7079 if (!InFunctionCall) {
7080 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
7081 diag::note_format_string_defined);
7082 }
7083 return SLCT_UncheckedLiteral;
7084 }
7085 return checkFormatStringExpr(
7086 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
7087 Args, APK, format_idx, firstDataArg, Type, CallType,
7088 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7089 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7090 }
7091 }
7092
7093 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7094 Sema::FormatStringInfo CallerFSI;
7095 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
7096 PVFormat->getFirstArg(), &CallerFSI))
7097 continue;
7098 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7099 // We also check if the formats are compatible.
7100 // We can't pass a 'scanf' string to a 'printf' function.
7101 if (Type != S.GetFormatStringType(PVFormat)) {
7102 S.Diag(Args[format_idx]->getBeginLoc(),
7103 diag::warn_format_string_type_incompatible)
7104 << PVFormat->getType()->getName()
7106 if (!InFunctionCall) {
7107 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
7108 }
7109 return SLCT_UncheckedLiteral;
7110 }
7111 // Lastly, check that argument passing kinds transition in a
7112 // way that makes sense:
7113 // from a caller with FAPK_VAList, allow FAPK_VAList
7114 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7115 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7116 // from a caller with FAPK_Variadic, allow FAPK_VAList
7117 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
7122 return SLCT_UncheckedLiteral;
7123 }
7124 }
7125 }
7126 }
7127 }
7128 }
7129
7130 return SLCT_NotALiteral;
7131 }
7132
7133 case Stmt::CallExprClass:
7134 case Stmt::CXXMemberCallExprClass: {
7135 const CallExpr *CE = cast<CallExpr>(E);
7136 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7137 bool IsFirst = true;
7138 StringLiteralCheckType CommonResult;
7139 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7140 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7141 StringLiteralCheckType Result = checkFormatStringExpr(
7142 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7143 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7144 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7145 if (IsFirst) {
7146 CommonResult = Result;
7147 IsFirst = false;
7148 }
7149 }
7150 if (!IsFirst)
7151 return CommonResult;
7152
7153 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7154 unsigned BuiltinID = FD->getBuiltinID();
7155 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7156 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7157 const Expr *Arg = CE->getArg(0);
7158 return checkFormatStringExpr(
7159 S, ReferenceFormatString, Arg, Args, APK, format_idx,
7160 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7161 UncoveredArg, Offset, CallerFormatParamIdx,
7162 IgnoreStringsWithoutSpecifiers);
7163 }
7164 }
7165 }
7166 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
7167 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7168 format_idx, firstDataArg, Type, CallType,
7169 /*InFunctionCall*/ false, CheckedVarArgs,
7170 UncoveredArg, Offset, CallerFormatParamIdx,
7171 IgnoreStringsWithoutSpecifiers);
7172 return SLCT_NotALiteral;
7173 }
7174 case Stmt::ObjCMessageExprClass: {
7175 const auto *ME = cast<ObjCMessageExpr>(E);
7176 if (const auto *MD = ME->getMethodDecl()) {
7177 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7178 // As a special case heuristic, if we're using the method -[NSBundle
7179 // localizedStringForKey:value:table:], ignore any key strings that lack
7180 // format specifiers. The idea is that if the key doesn't have any
7181 // format specifiers then its probably just a key to map to the
7182 // localized strings. If it does have format specifiers though, then its
7183 // likely that the text of the key is the format string in the
7184 // programmer's language, and should be checked.
7185 const ObjCInterfaceDecl *IFace;
7186 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7187 IFace->getIdentifier()->isStr("NSBundle") &&
7188 MD->getSelector().isKeywordSelector(
7189 {"localizedStringForKey", "value", "table"})) {
7190 IgnoreStringsWithoutSpecifiers = true;
7191 }
7192
7193 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7194 return checkFormatStringExpr(
7195 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7196 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7197 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7198 }
7199 }
7200
7201 return SLCT_NotALiteral;
7202 }
7203 case Stmt::ObjCStringLiteralClass:
7204 case Stmt::StringLiteralClass: {
7205 const StringLiteral *StrE = nullptr;
7206
7207 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7208 StrE = ObjCFExpr->getString();
7209 else
7210 StrE = cast<StringLiteral>(E);
7211
7212 if (StrE) {
7213 if (Offset.isNegative() || Offset > StrE->getLength()) {
7214 // TODO: It would be better to have an explicit warning for out of
7215 // bounds literals.
7216 return SLCT_NotALiteral;
7217 }
7218 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7219 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
7220 format_idx, firstDataArg, Type, InFunctionCall,
7221 CallType, CheckedVarArgs, UncoveredArg,
7222 IgnoreStringsWithoutSpecifiers);
7223 return SLCT_CheckedLiteral;
7224 }
7225
7226 return SLCT_NotALiteral;
7227 }
7228 case Stmt::BinaryOperatorClass: {
7229 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7230
7231 // A string literal + an int offset is still a string literal.
7232 if (BinOp->isAdditiveOp()) {
7233 Expr::EvalResult LResult, RResult;
7234
7235 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7236 LResult, S.Context, Expr::SE_NoSideEffects,
7238 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7239 RResult, S.Context, Expr::SE_NoSideEffects,
7241
7242 if (LIsInt != RIsInt) {
7243 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7244
7245 if (LIsInt) {
7246 if (BinOpKind == BO_Add) {
7247 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7248 E = BinOp->getRHS();
7249 goto tryAgain;
7250 }
7251 } else {
7252 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7253 E = BinOp->getLHS();
7254 goto tryAgain;
7255 }
7256 }
7257 }
7258
7259 return SLCT_NotALiteral;
7260 }
7261 case Stmt::UnaryOperatorClass: {
7262 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7263 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7264 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7265 Expr::EvalResult IndexResult;
7266 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7269 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7270 /*RHS is int*/ true);
7271 E = ASE->getBase();
7272 goto tryAgain;
7273 }
7274 }
7275
7276 return SLCT_NotALiteral;
7277 }
7278
7279 default:
7280 return SLCT_NotALiteral;
7281 }
7282}
7283
7284// If this expression can be evaluated at compile-time,
7285// check if the result is a StringLiteral and return it
7286// otherwise return nullptr
7288 const Expr *E) {
7289 Expr::EvalResult Result;
7290 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
7291 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7292 if (isa_and_nonnull<StringLiteral>(LVE))
7293 return LVE;
7294 }
7295 return nullptr;
7296}
7297
7299 switch (FST) {
7301 return "scanf";
7303 return "printf";
7305 return "NSString";
7307 return "strftime";
7309 return "strfmon";
7311 return "kprintf";
7313 return "freebsd_kprintf";
7315 return "os_log";
7316 default:
7317 return "<unknown>";
7318 }
7319}
7320
7322 return llvm::StringSwitch<FormatStringType>(Flavor)
7323 .Cases({"gnu_scanf", "scanf"}, FormatStringType::Scanf)
7324 .Cases({"gnu_printf", "printf", "printf0", "syslog"},
7326 .Cases({"NSString", "CFString"}, FormatStringType::NSString)
7327 .Cases({"gnu_strftime", "strftime"}, FormatStringType::Strftime)
7328 .Cases({"gnu_strfmon", "strfmon"}, FormatStringType::Strfmon)
7329 .Cases({"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7331 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
7332 .Case("os_trace", FormatStringType::OSLog)
7333 .Case("os_log", FormatStringType::OSLog)
7334 .Default(FormatStringType::Unknown);
7335}
7336
7338 return GetFormatStringType(Format->getType()->getName());
7339}
7340
7341FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7342 return GetFormatStringType(Format->getType()->getName());
7343}
7344
7345bool Sema::CheckFormatArguments(const FormatAttr *Format,
7346 ArrayRef<const Expr *> Args, bool IsCXXMember,
7347 VariadicCallType CallType, SourceLocation Loc,
7348 SourceRange Range,
7349 llvm::SmallBitVector &CheckedVarArgs) {
7350 FormatStringInfo FSI;
7351 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
7352 IsCXXMember,
7353 CallType != VariadicCallType::DoesNotApply, &FSI))
7354 return CheckFormatArguments(
7355 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
7356 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
7357 return false;
7358}
7359
7360bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7361 ArrayRef<const Expr *> Args, bool IsCXXMember,
7362 VariadicCallType CallType, SourceLocation Loc,
7363 SourceRange Range,
7364 llvm::SmallBitVector &CheckedVarArgs) {
7365 FormatStringInfo FSI;
7366 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
7367 &FSI)) {
7368 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7369 return CheckFormatArguments(Args, FSI.ArgPassingKind,
7370 Format->getFormatString(), FSI.FormatIdx,
7371 FSI.FirstDataArg, GetFormatStringType(Format),
7372 CallType, Loc, Range, CheckedVarArgs);
7373 }
7374 return false;
7375}
7376
7379 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7380 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7381 SourceLocation Loc) {
7382 if (S->getDiagnostics().isIgnored(diag::warn_missing_format_attribute, Loc))
7383 return false;
7384
7385 DeclContext *DC = S->CurContext;
7386 if (!isa<ObjCMethodDecl>(DC) && !isa<FunctionDecl>(DC) && !isa<BlockDecl>(DC))
7387 return false;
7388 Decl *Caller = cast<Decl>(DC)->getCanonicalDecl();
7389
7390 unsigned NumCallerParams = getFunctionOrMethodNumParams(Caller);
7391
7392 // Find the offset to convert between attribute and parameter indexes.
7393 unsigned CallerArgumentIndexOffset =
7394 hasImplicitObjectParameter(Caller) ? 2 : 1;
7395
7396 unsigned FirstArgumentIndex = -1;
7397 switch (APK) {
7400 // As an extension, clang allows the format attribute on non-variadic
7401 // functions.
7402 // Caller must have fixed arguments to pass them to a fixed or variadic
7403 // function. Try to match caller and callee arguments. If successful, then
7404 // emit a diag with the caller idx, otherwise we can't determine the callee
7405 // arguments.
7406 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7407 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7408 // There aren't enough arguments in the caller to pass to callee.
7409 return false;
7410 }
7411 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7412 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7413 const auto *Arg =
7414 dyn_cast<DeclRefExpr>(Args[CalleeIdx]->IgnoreParenCasts());
7415 if (!Arg)
7416 return false;
7417 const auto *Param = dyn_cast<ParmVarDecl>(Arg->getDecl());
7418 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7419 return false;
7420 }
7421 FirstArgumentIndex =
7422 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7423 break;
7424 }
7426 // Caller arguments are either variadic or a va_list.
7427 FirstArgumentIndex = isFunctionOrMethodVariadic(Caller)
7428 ? (NumCallerParams + CallerArgumentIndexOffset)
7429 : 0;
7430 break;
7432 // The callee has a format_matches attribute. We will emit that instead.
7433 if (!ReferenceFormatString)
7434 return false;
7435 break;
7436 }
7437
7438 // Emit the diagnostic and fixit.
7439 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7440 StringRef FormatTypeName = S->GetFormatStringTypeName(FormatType);
7441 NamedDecl *ND = dyn_cast<NamedDecl>(Caller);
7442 do {
7443 std::string Attr, Fixit;
7444 llvm::raw_string_ostream AttrOS(Attr);
7446 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7447 << FirstArgumentIndex << ")";
7448 } else {
7449 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7450 << ", \"";
7451 AttrOS.write_escaped(ReferenceFormatString->getString());
7452 AttrOS << "\")";
7453 }
7454 AttrOS.flush();
7455 auto DB = S->Diag(Loc, diag::warn_missing_format_attribute) << Attr;
7456 if (ND)
7457 DB << ND;
7458 else
7459 DB << "block";
7460
7461 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7462 if (isa<BlockDecl>(Caller))
7463 break;
7464
7465 SourceLocation SL;
7466 llvm::raw_string_ostream IS(Fixit);
7467 // The attribute goes at the start of the declaration in C/C++ functions
7468 // and methods, but after the declaration for Objective-C methods.
7469 if (isa<ObjCMethodDecl>(Caller)) {
7470 IS << ' ';
7471 SL = Caller->getEndLoc();
7472 }
7473 const LangOptions &LO = S->getLangOpts();
7474 if (LO.C23 || LO.CPlusPlus11)
7475 IS << "[[gnu::" << Attr << "]]";
7476 else if (LO.ObjC || LO.GNUMode)
7477 IS << "__attribute__((" << Attr << "))";
7478 else
7479 break;
7480 if (!isa<ObjCMethodDecl>(Caller)) {
7481 IS << ' ';
7482 SL = Caller->getBeginLoc();
7483 }
7484 IS.flush();
7485
7486 DB << FixItHint::CreateInsertion(SL, Fixit);
7487 } while (false);
7488
7489 // Add implicit format or format_matches attribute.
7491 Caller->addAttr(FormatAttr::CreateImplicit(
7492 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7493 FormatStringIndex, FirstArgumentIndex));
7494 } else {
7495 Caller->addAttr(FormatMatchesAttr::CreateImplicit(
7496 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7497 FormatStringIndex, ReferenceFormatString));
7498 }
7499
7500 {
7501 auto DB = S->Diag(Caller->getLocation(), diag::note_entity_declared_at);
7502 if (ND)
7503 DB << ND;
7504 else
7505 DB << "block";
7506 }
7507 return true;
7508}
7509
7510bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7512 StringLiteral *ReferenceFormatString,
7513 unsigned format_idx, unsigned firstDataArg,
7515 VariadicCallType CallType, SourceLocation Loc,
7516 SourceRange Range,
7517 llvm::SmallBitVector &CheckedVarArgs) {
7518 // CHECK: printf/scanf-like function is called with no format string.
7519 if (format_idx >= Args.size()) {
7520 Diag(Loc, diag::warn_missing_format_string) << Range;
7521 return false;
7522 }
7523
7524 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7525
7526 // CHECK: format string is not a string literal.
7527 //
7528 // Dynamically generated format strings are difficult to
7529 // automatically vet at compile time. Requiring that format strings
7530 // are string literals: (1) permits the checking of format strings by
7531 // the compiler and thereby (2) can practically remove the source of
7532 // many format string exploits.
7533
7534 // Format string can be either ObjC string (e.g. @"%d") or
7535 // C string (e.g. "%d")
7536 // ObjC string uses the same format specifiers as C string, so we can use
7537 // the same format string checking logic for both ObjC and C strings.
7538 UncoveredArgHandler UncoveredArg;
7539 std::optional<unsigned> CallerParamIdx;
7540 StringLiteralCheckType CT = checkFormatStringExpr(
7541 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
7542 firstDataArg, Type, CallType,
7543 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
7544 /*no string offset*/ llvm::APSInt(64, false) = 0, &CallerParamIdx);
7545
7546 // Generate a diagnostic where an uncovered argument is detected.
7547 if (UncoveredArg.hasUncoveredArg()) {
7548 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7549 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7550 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7551 }
7552
7553 if (CT != SLCT_NotALiteral)
7554 // Literal format string found, check done!
7555 return CT == SLCT_CheckedLiteral;
7556
7557 // Do not emit diag when the string param is a macro expansion and the
7558 // format is either NSString or CFString. This is a hack to prevent
7559 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7560 // which are usually used in place of NS and CF string literals.
7561 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7563 SourceMgr.isInSystemMacro(FormatLoc))
7564 return false;
7565
7566 if (CallerParamIdx && CheckMissingFormatAttribute(
7567 this, Args, APK, ReferenceFormatString, format_idx,
7568 firstDataArg, Type, *CallerParamIdx, Loc))
7569 return false;
7570
7571 // Strftime is particular as it always uses a single 'time' argument,
7572 // so it is safe to pass a non-literal string.
7574 return false;
7575
7576 // If there are no arguments specified, warn with -Wformat-security, otherwise
7577 // warn only with -Wformat-nonliteral.
7578 if (Args.size() == firstDataArg) {
7579 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7580 << OrigFormatExpr->getSourceRange();
7581 switch (Type) {
7582 default:
7583 break;
7587 Diag(FormatLoc, diag::note_format_security_fixit)
7588 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7589 break;
7591 Diag(FormatLoc, diag::note_format_security_fixit)
7592 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7593 break;
7594 }
7595 } else {
7596 Diag(FormatLoc, diag::warn_format_nonliteral)
7597 << OrigFormatExpr->getSourceRange();
7598 }
7599 return false;
7600}
7601
7602namespace {
7603
7604class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7605protected:
7606 Sema &S;
7607 const FormatStringLiteral *FExpr;
7608 const Expr *OrigFormatExpr;
7609 const FormatStringType FSType;
7610 const unsigned FirstDataArg;
7611 const unsigned NumDataArgs;
7612 const char *Beg; // Start of format string.
7613 const Sema::FormatArgumentPassingKind ArgPassingKind;
7614 ArrayRef<const Expr *> Args;
7615 unsigned FormatIdx;
7616 llvm::SmallBitVector CoveredArgs;
7617 bool usesPositionalArgs = false;
7618 bool atFirstArg = true;
7619 bool inFunctionCall;
7620 VariadicCallType CallType;
7621 llvm::SmallBitVector &CheckedVarArgs;
7622 UncoveredArgHandler &UncoveredArg;
7623
7624public:
7625 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7626 const Expr *origFormatExpr, const FormatStringType type,
7627 unsigned firstDataArg, unsigned numDataArgs,
7628 const char *beg, Sema::FormatArgumentPassingKind APK,
7629 ArrayRef<const Expr *> Args, unsigned formatIdx,
7630 bool inFunctionCall, VariadicCallType callType,
7631 llvm::SmallBitVector &CheckedVarArgs,
7632 UncoveredArgHandler &UncoveredArg)
7633 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7634 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7635 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7636 inFunctionCall(inFunctionCall), CallType(callType),
7637 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7638 CoveredArgs.resize(numDataArgs);
7639 CoveredArgs.reset();
7640 }
7641
7642 bool HasFormatArguments() const {
7643 return ArgPassingKind == Sema::FAPK_Fixed ||
7644 ArgPassingKind == Sema::FAPK_Variadic;
7645 }
7646
7647 void DoneProcessing();
7648
7649 void HandleIncompleteSpecifier(const char *startSpecifier,
7650 unsigned specifierLen) override;
7651
7652 void HandleInvalidLengthModifier(
7653 const analyze_format_string::FormatSpecifier &FS,
7654 const analyze_format_string::ConversionSpecifier &CS,
7655 const char *startSpecifier, unsigned specifierLen,
7656 unsigned DiagID);
7657
7658 void HandleNonStandardLengthModifier(
7659 const analyze_format_string::FormatSpecifier &FS,
7660 const char *startSpecifier, unsigned specifierLen);
7661
7662 void HandleNonStandardConversionSpecifier(
7663 const analyze_format_string::ConversionSpecifier &CS,
7664 const char *startSpecifier, unsigned specifierLen);
7665
7666 void HandlePosition(const char *startPos, unsigned posLen) override;
7667
7668 void HandleInvalidPosition(const char *startSpecifier,
7669 unsigned specifierLen,
7671
7672 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7673
7674 void HandleNullChar(const char *nullCharacter) override;
7675
7676 template <typename Range>
7677 static void
7678 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7679 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7680 bool IsStringLocation, Range StringRange,
7681 ArrayRef<FixItHint> Fixit = {});
7682
7683protected:
7684 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7685 const char *startSpec,
7686 unsigned specifierLen,
7687 const char *csStart, unsigned csLen);
7688
7689 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7690 const char *startSpec,
7691 unsigned specifierLen);
7692
7693 SourceRange getFormatStringRange();
7694 CharSourceRange getSpecifierRange(const char *startSpecifier,
7695 unsigned specifierLen);
7696 SourceLocation getLocationOfByte(const char *x);
7697
7698 const Expr *getDataArg(unsigned i) const;
7699
7700 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7701 const analyze_format_string::ConversionSpecifier &CS,
7702 const char *startSpecifier, unsigned specifierLen,
7703 unsigned argIndex);
7704
7705 template <typename Range>
7706 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7707 bool IsStringLocation, Range StringRange,
7708 ArrayRef<FixItHint> Fixit = {});
7709};
7710
7711} // namespace
7712
7713SourceRange CheckFormatHandler::getFormatStringRange() {
7714 return OrigFormatExpr->getSourceRange();
7715}
7716
7717CharSourceRange CheckFormatHandler::
7718getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7719 SourceLocation Start = getLocationOfByte(startSpecifier);
7720 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7721
7722 // Advance the end SourceLocation by one due to half-open ranges.
7723 End = End.getLocWithOffset(1);
7724
7725 return CharSourceRange::getCharRange(Start, End);
7726}
7727
7728SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7729 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7731}
7732
7733void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7734 unsigned specifierLen){
7735 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7736 getLocationOfByte(startSpecifier),
7737 /*IsStringLocation*/true,
7738 getSpecifierRange(startSpecifier, specifierLen));
7739}
7740
7741void CheckFormatHandler::HandleInvalidLengthModifier(
7744 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7745 using namespace analyze_format_string;
7746
7747 const LengthModifier &LM = FS.getLengthModifier();
7748 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7749
7750 // See if we know how to fix this length modifier.
7751 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7752 if (FixedLM) {
7753 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7754 getLocationOfByte(LM.getStart()),
7755 /*IsStringLocation*/true,
7756 getSpecifierRange(startSpecifier, specifierLen));
7757
7758 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7759 << FixedLM->toString()
7760 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7761
7762 } else {
7763 FixItHint Hint;
7764 if (DiagID == diag::warn_format_nonsensical_length)
7765 Hint = FixItHint::CreateRemoval(LMRange);
7766
7767 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7768 getLocationOfByte(LM.getStart()),
7769 /*IsStringLocation*/true,
7770 getSpecifierRange(startSpecifier, specifierLen),
7771 Hint);
7772 }
7773}
7774
7775void CheckFormatHandler::HandleNonStandardLengthModifier(
7777 const char *startSpecifier, unsigned specifierLen) {
7778 using namespace analyze_format_string;
7779
7780 const LengthModifier &LM = FS.getLengthModifier();
7781 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7782
7783 // See if we know how to fix this length modifier.
7784 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7785 if (FixedLM) {
7786 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7787 << LM.toString() << 0,
7788 getLocationOfByte(LM.getStart()),
7789 /*IsStringLocation*/true,
7790 getSpecifierRange(startSpecifier, specifierLen));
7791
7792 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7793 << FixedLM->toString()
7794 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7795
7796 } else {
7797 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7798 << LM.toString() << 0,
7799 getLocationOfByte(LM.getStart()),
7800 /*IsStringLocation*/true,
7801 getSpecifierRange(startSpecifier, specifierLen));
7802 }
7803}
7804
7805void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7807 const char *startSpecifier, unsigned specifierLen) {
7808 using namespace analyze_format_string;
7809
7810 // See if we know how to fix this conversion specifier.
7811 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7812 if (FixedCS) {
7813 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7814 << CS.toString() << /*conversion specifier*/1,
7815 getLocationOfByte(CS.getStart()),
7816 /*IsStringLocation*/true,
7817 getSpecifierRange(startSpecifier, specifierLen));
7818
7819 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7820 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7821 << FixedCS->toString()
7822 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7823 } else {
7824 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7825 << CS.toString() << /*conversion specifier*/1,
7826 getLocationOfByte(CS.getStart()),
7827 /*IsStringLocation*/true,
7828 getSpecifierRange(startSpecifier, specifierLen));
7829 }
7830}
7831
7832void CheckFormatHandler::HandlePosition(const char *startPos,
7833 unsigned posLen) {
7834 if (!S.getDiagnostics().isIgnored(
7835 diag::warn_format_non_standard_positional_arg, SourceLocation()))
7836 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7837 getLocationOfByte(startPos),
7838 /*IsStringLocation*/ true,
7839 getSpecifierRange(startPos, posLen));
7840}
7841
7842void CheckFormatHandler::HandleInvalidPosition(
7843 const char *startSpecifier, unsigned specifierLen,
7845 if (!S.getDiagnostics().isIgnored(
7846 diag::warn_format_invalid_positional_specifier, SourceLocation()))
7847 EmitFormatDiagnostic(
7848 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
7849 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
7850 getSpecifierRange(startSpecifier, specifierLen));
7851}
7852
7853void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7854 unsigned posLen) {
7855 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
7856 SourceLocation()))
7857 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7858 getLocationOfByte(startPos),
7859 /*IsStringLocation*/ true,
7860 getSpecifierRange(startPos, posLen));
7861}
7862
7863void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7864 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7865 // The presence of a null character is likely an error.
7866 EmitFormatDiagnostic(
7867 S.PDiag(diag::warn_printf_format_string_contains_null_char),
7868 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7869 getFormatStringRange());
7870 }
7871}
7872
7873// Note that this may return NULL if there was an error parsing or building
7874// one of the argument expressions.
7875const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7876 return Args[FirstDataArg + i];
7877}
7878
7879void CheckFormatHandler::DoneProcessing() {
7880 // Does the number of data arguments exceed the number of
7881 // format conversions in the format string?
7882 if (HasFormatArguments()) {
7883 // Find any arguments that weren't covered.
7884 CoveredArgs.flip();
7885 signed notCoveredArg = CoveredArgs.find_first();
7886 if (notCoveredArg >= 0) {
7887 assert((unsigned)notCoveredArg < NumDataArgs);
7888 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7889 } else {
7890 UncoveredArg.setAllCovered();
7891 }
7892 }
7893}
7894
7895void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7896 const Expr *ArgExpr) {
7897 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
7898 "Invalid state");
7899
7900 if (!ArgExpr)
7901 return;
7902
7903 SourceLocation Loc = ArgExpr->getBeginLoc();
7904
7905 if (S.getSourceManager().isInSystemMacro(Loc))
7906 return;
7907
7908 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7909 for (auto E : DiagnosticExprs)
7910 PDiag << E->getSourceRange();
7911
7912 CheckFormatHandler::EmitFormatDiagnostic(
7913 S, IsFunctionCall, DiagnosticExprs[0],
7914 PDiag, Loc, /*IsStringLocation*/false,
7915 DiagnosticExprs[0]->getSourceRange());
7916}
7917
7918bool
7919CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7920 SourceLocation Loc,
7921 const char *startSpec,
7922 unsigned specifierLen,
7923 const char *csStart,
7924 unsigned csLen) {
7925 bool keepGoing = true;
7926 if (argIndex < NumDataArgs) {
7927 // Consider the argument coverered, even though the specifier doesn't
7928 // make sense.
7929 CoveredArgs.set(argIndex);
7930 }
7931 else {
7932 // If argIndex exceeds the number of data arguments we
7933 // don't issue a warning because that is just a cascade of warnings (and
7934 // they may have intended '%%' anyway). We don't want to continue processing
7935 // the format string after this point, however, as we will like just get
7936 // gibberish when trying to match arguments.
7937 keepGoing = false;
7938 }
7939
7940 StringRef Specifier(csStart, csLen);
7941
7942 // If the specifier in non-printable, it could be the first byte of a UTF-8
7943 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7944 // hex value.
7945 std::string CodePointStr;
7946 if (!llvm::sys::locale::isPrint(*csStart)) {
7947 llvm::UTF32 CodePoint;
7948 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7949 const llvm::UTF8 *E =
7950 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7951 llvm::ConversionResult Result =
7952 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7953
7954 if (Result != llvm::conversionOK) {
7955 unsigned char FirstChar = *csStart;
7956 CodePoint = (llvm::UTF32)FirstChar;
7957 }
7958
7959 llvm::raw_string_ostream OS(CodePointStr);
7960 if (CodePoint < 256)
7961 OS << "\\x" << llvm::format("%02x", CodePoint);
7962 else if (CodePoint <= 0xFFFF)
7963 OS << "\\u" << llvm::format("%04x", CodePoint);
7964 else
7965 OS << "\\U" << llvm::format("%08x", CodePoint);
7966 Specifier = CodePointStr;
7967 }
7968
7969 EmitFormatDiagnostic(
7970 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7971 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7972
7973 return keepGoing;
7974}
7975
7976void
7977CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7978 const char *startSpec,
7979 unsigned specifierLen) {
7980 EmitFormatDiagnostic(
7981 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7982 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7983}
7984
7985bool
7986CheckFormatHandler::CheckNumArgs(
7989 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7990
7991 if (HasFormatArguments() && argIndex >= NumDataArgs) {
7993 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7994 << (argIndex+1) << NumDataArgs)
7995 : S.PDiag(diag::warn_printf_insufficient_data_args);
7996 EmitFormatDiagnostic(
7997 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7998 getSpecifierRange(startSpecifier, specifierLen));
7999
8000 // Since more arguments than conversion tokens are given, by extension
8001 // all arguments are covered, so mark this as so.
8002 UncoveredArg.setAllCovered();
8003 return false;
8004 }
8005 return true;
8006}
8007
8008template<typename Range>
8009void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8010 SourceLocation Loc,
8011 bool IsStringLocation,
8012 Range StringRange,
8013 ArrayRef<FixItHint> FixIt) {
8014 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8015 Loc, IsStringLocation, StringRange, FixIt);
8016}
8017
8018/// If the format string is not within the function call, emit a note
8019/// so that the function call and string are in diagnostic messages.
8020///
8021/// \param InFunctionCall if true, the format string is within the function
8022/// call and only one diagnostic message will be produced. Otherwise, an
8023/// extra note will be emitted pointing to location of the format string.
8024///
8025/// \param ArgumentExpr the expression that is passed as the format string
8026/// argument in the function call. Used for getting locations when two
8027/// diagnostics are emitted.
8028///
8029/// \param PDiag the callee should already have provided any strings for the
8030/// diagnostic message. This function only adds locations and fixits
8031/// to diagnostics.
8032///
8033/// \param Loc primary location for diagnostic. If two diagnostics are
8034/// required, one will be at Loc and a new SourceLocation will be created for
8035/// the other one.
8036///
8037/// \param IsStringLocation if true, Loc points to the format string should be
8038/// used for the note. Otherwise, Loc points to the argument list and will
8039/// be used with PDiag.
8040///
8041/// \param StringRange some or all of the string to highlight. This is
8042/// templated so it can accept either a CharSourceRange or a SourceRange.
8043///
8044/// \param FixIt optional fix it hint for the format string.
8045template <typename Range>
8046void CheckFormatHandler::EmitFormatDiagnostic(
8047 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8048 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8049 Range StringRange, ArrayRef<FixItHint> FixIt) {
8050 if (InFunctionCall) {
8051 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8052 D << StringRange;
8053 D << FixIt;
8054 } else {
8055 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8056 << ArgumentExpr->getSourceRange();
8057
8059 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8060 diag::note_format_string_defined);
8061
8062 Note << StringRange;
8063 Note << FixIt;
8064 }
8065}
8066
8067//===--- CHECK: Printf format string checking -----------------------------===//
8068
8069namespace {
8070
8071class CheckPrintfHandler : public CheckFormatHandler {
8072public:
8073 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8074 const Expr *origFormatExpr, const FormatStringType type,
8075 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8076 const char *beg, Sema::FormatArgumentPassingKind APK,
8077 ArrayRef<const Expr *> Args, unsigned formatIdx,
8078 bool inFunctionCall, VariadicCallType CallType,
8079 llvm::SmallBitVector &CheckedVarArgs,
8080 UncoveredArgHandler &UncoveredArg)
8081 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8082 numDataArgs, beg, APK, Args, formatIdx,
8083 inFunctionCall, CallType, CheckedVarArgs,
8084 UncoveredArg) {}
8085
8086 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8087
8088 /// Returns true if '%@' specifiers are allowed in the format string.
8089 bool allowsObjCArg() const {
8090 return FSType == FormatStringType::NSString ||
8091 FSType == FormatStringType::OSLog ||
8092 FSType == FormatStringType::OSTrace;
8093 }
8094
8095 bool HandleInvalidPrintfConversionSpecifier(
8096 const analyze_printf::PrintfSpecifier &FS,
8097 const char *startSpecifier,
8098 unsigned specifierLen) override;
8099
8100 void handleInvalidMaskType(StringRef MaskType) override;
8101
8102 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8103 const char *startSpecifier, unsigned specifierLen,
8104 const TargetInfo &Target) override;
8105 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8106 const char *StartSpecifier,
8107 unsigned SpecifierLen,
8108 const Expr *E);
8109
8110 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8111 const char *startSpecifier, unsigned specifierLen);
8112 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8113 const analyze_printf::OptionalAmount &Amt,
8114 unsigned type,
8115 const char *startSpecifier, unsigned specifierLen);
8116 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8117 const analyze_printf::OptionalFlag &flag,
8118 const char *startSpecifier, unsigned specifierLen);
8119 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8120 const analyze_printf::OptionalFlag &ignoredFlag,
8121 const analyze_printf::OptionalFlag &flag,
8122 const char *startSpecifier, unsigned specifierLen);
8123 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8124 const Expr *E);
8125
8126 void HandleEmptyObjCModifierFlag(const char *startFlag,
8127 unsigned flagLen) override;
8128
8129 void HandleInvalidObjCModifierFlag(const char *startFlag,
8130 unsigned flagLen) override;
8131
8132 void
8133 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8134 const char *flagsEnd,
8135 const char *conversionPosition) override;
8136};
8137
8138/// Keeps around the information needed to verify that two specifiers are
8139/// compatible.
8140class EquatableFormatArgument {
8141public:
8142 enum SpecifierSensitivity : unsigned {
8143 SS_None,
8144 SS_Private,
8145 SS_Public,
8146 SS_Sensitive
8147 };
8148
8149 enum FormatArgumentRole : unsigned {
8150 FAR_Data,
8151 FAR_FieldWidth,
8152 FAR_Precision,
8153 FAR_Auxiliary, // FreeBSD kernel %b and %D
8154 };
8155
8156private:
8157 analyze_format_string::ArgType ArgType;
8159 StringRef SpecifierLetter;
8160 CharSourceRange Range;
8161 SourceLocation ElementLoc;
8162 FormatArgumentRole Role : 2;
8163 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8164 unsigned Position : 14;
8165 unsigned ModifierFor : 14; // not set for FAR_Data
8166
8167 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8168 bool InFunctionCall) const;
8169
8170public:
8171 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8173 StringRef SpecifierLetter,
8174 analyze_format_string::ArgType ArgType,
8175 FormatArgumentRole Role,
8176 SpecifierSensitivity Sensitivity, unsigned Position,
8177 unsigned ModifierFor)
8178 : ArgType(ArgType), LengthMod(LengthMod),
8179 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8180 Role(Role), Sensitivity(Sensitivity), Position(Position),
8181 ModifierFor(ModifierFor) {}
8182
8183 unsigned getPosition() const { return Position; }
8184 SourceLocation getSourceLocation() const { return ElementLoc; }
8185 CharSourceRange getSourceRange() const { return Range; }
8186 analyze_format_string::LengthModifier getLengthModifier() const {
8187 return analyze_format_string::LengthModifier(nullptr, LengthMod);
8188 }
8189 void setModifierFor(unsigned V) { ModifierFor = V; }
8190
8191 std::string buildFormatSpecifier() const {
8192 std::string result;
8193 llvm::raw_string_ostream(result)
8194 << getLengthModifier().toString() << SpecifierLetter;
8195 return result;
8196 }
8197
8198 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8199 const Expr *FmtExpr, bool InFunctionCall) const;
8200};
8201
8202/// Turns format strings into lists of EquatableSpecifier objects.
8203class DecomposePrintfHandler : public CheckPrintfHandler {
8204 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8205 bool HadError;
8206
8207 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8208 const Expr *origFormatExpr,
8209 const FormatStringType type, unsigned firstDataArg,
8210 unsigned numDataArgs, bool isObjC, const char *beg,
8212 ArrayRef<const Expr *> Args, unsigned formatIdx,
8213 bool inFunctionCall, VariadicCallType CallType,
8214 llvm::SmallBitVector &CheckedVarArgs,
8215 UncoveredArgHandler &UncoveredArg,
8216 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8217 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8218 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8219 inFunctionCall, CallType, CheckedVarArgs,
8220 UncoveredArg),
8221 Specs(Specs), HadError(false) {}
8222
8223public:
8224 static bool
8225 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8226 FormatStringType type, bool IsObjC, bool InFunctionCall,
8227 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8228
8229 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8230 const char *startSpecifier,
8231 unsigned specifierLen,
8232 const TargetInfo &Target) override;
8233};
8234
8235} // namespace
8236
8237bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8238 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8239 unsigned specifierLen) {
8242
8243 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8244 getLocationOfByte(CS.getStart()),
8245 startSpecifier, specifierLen,
8246 CS.getStart(), CS.getLength());
8247}
8248
8249void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8250 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8251}
8252
8253// Error out if struct or complex type argments are passed to os_log.
8255 QualType T) {
8256 if (FSType != FormatStringType::OSLog)
8257 return false;
8258 return T->isRecordType() || T->isComplexType();
8259}
8260
8261bool CheckPrintfHandler::HandleAmount(
8262 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8263 const char *startSpecifier, unsigned specifierLen) {
8264 if (Amt.hasDataArgument()) {
8265 if (HasFormatArguments()) {
8266 unsigned argIndex = Amt.getArgIndex();
8267 if (argIndex >= NumDataArgs) {
8268 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8269 << k,
8270 getLocationOfByte(Amt.getStart()),
8271 /*IsStringLocation*/ true,
8272 getSpecifierRange(startSpecifier, specifierLen));
8273 // Don't do any more checking. We will just emit
8274 // spurious errors.
8275 return false;
8276 }
8277
8278 // Type check the data argument. It should be an 'int'.
8279 // Although not in conformance with C99, we also allow the argument to be
8280 // an 'unsigned int' as that is a reasonably safe case. GCC also
8281 // doesn't emit a warning for that case.
8282 CoveredArgs.set(argIndex);
8283 const Expr *Arg = getDataArg(argIndex);
8284 if (!Arg)
8285 return false;
8286
8287 QualType T = Arg->getType();
8288
8289 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8290 assert(AT.isValid());
8291
8292 if (!AT.matchesType(S.Context, T)) {
8293 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8294 ? diag::err_printf_asterisk_wrong_type
8295 : diag::warn_printf_asterisk_wrong_type;
8296 EmitFormatDiagnostic(S.PDiag(DiagID)
8298 << T << Arg->getSourceRange(),
8299 getLocationOfByte(Amt.getStart()),
8300 /*IsStringLocation*/ true,
8301 getSpecifierRange(startSpecifier, specifierLen));
8302 // Don't do any more checking. We will just emit
8303 // spurious errors.
8304 return false;
8305 }
8306 }
8307 }
8308 return true;
8309}
8310
8311void CheckPrintfHandler::HandleInvalidAmount(
8314 unsigned type,
8315 const char *startSpecifier,
8316 unsigned specifierLen) {
8319
8320 FixItHint fixit =
8322 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8323 Amt.getConstantLength()))
8324 : FixItHint();
8325
8326 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8327 << type << CS.toString(),
8328 getLocationOfByte(Amt.getStart()),
8329 /*IsStringLocation*/true,
8330 getSpecifierRange(startSpecifier, specifierLen),
8331 fixit);
8332}
8333
8334void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8335 const analyze_printf::OptionalFlag &flag,
8336 const char *startSpecifier,
8337 unsigned specifierLen) {
8338 // Warn about pointless flag with a fixit removal.
8341 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8342 << flag.toString() << CS.toString(),
8343 getLocationOfByte(flag.getPosition()),
8344 /*IsStringLocation*/true,
8345 getSpecifierRange(startSpecifier, specifierLen),
8347 getSpecifierRange(flag.getPosition(), 1)));
8348}
8349
8350void CheckPrintfHandler::HandleIgnoredFlag(
8352 const analyze_printf::OptionalFlag &ignoredFlag,
8353 const analyze_printf::OptionalFlag &flag,
8354 const char *startSpecifier,
8355 unsigned specifierLen) {
8356 // Warn about ignored flag with a fixit removal.
8357 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8358 << ignoredFlag.toString() << flag.toString(),
8359 getLocationOfByte(ignoredFlag.getPosition()),
8360 /*IsStringLocation*/true,
8361 getSpecifierRange(startSpecifier, specifierLen),
8363 getSpecifierRange(ignoredFlag.getPosition(), 1)));
8364}
8365
8366void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8367 unsigned flagLen) {
8368 // Warn about an empty flag.
8369 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8370 getLocationOfByte(startFlag),
8371 /*IsStringLocation*/true,
8372 getSpecifierRange(startFlag, flagLen));
8373}
8374
8375void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8376 unsigned flagLen) {
8377 // Warn about an invalid flag.
8378 auto Range = getSpecifierRange(startFlag, flagLen);
8379 StringRef flag(startFlag, flagLen);
8380 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8381 getLocationOfByte(startFlag),
8382 /*IsStringLocation*/true,
8383 Range, FixItHint::CreateRemoval(Range));
8384}
8385
8386void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8387 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8388 // Warn about using '[...]' without a '@' conversion.
8389 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8390 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8391 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8392 getLocationOfByte(conversionPosition),
8393 /*IsStringLocation*/ true, Range,
8395}
8396
8397void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8398 const Expr *FmtExpr,
8399 bool InFunctionCall) const {
8400 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
8401 ElementLoc, true, Range);
8402}
8403
8404bool EquatableFormatArgument::VerifyCompatible(
8405 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8406 bool InFunctionCall) const {
8408 if (Role != Other.Role) {
8409 // diagnose and stop
8410 EmitDiagnostic(
8411 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8412 FmtExpr, InFunctionCall);
8413 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8414 return false;
8415 }
8416
8417 if (Role != FAR_Data) {
8418 if (ModifierFor != Other.ModifierFor) {
8419 // diagnose and stop
8420 EmitDiagnostic(S,
8421 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
8422 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8423 FmtExpr, InFunctionCall);
8424 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8425 return false;
8426 }
8427 return true;
8428 }
8429
8430 bool HadError = false;
8431 if (Sensitivity != Other.Sensitivity) {
8432 // diagnose and continue
8433 EmitDiagnostic(S,
8434 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
8435 << Sensitivity << Other.Sensitivity,
8436 FmtExpr, InFunctionCall);
8437 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8438 << 0 << Other.Range;
8439 }
8440
8441 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
8442 case MK::Match:
8443 break;
8444
8445 case MK::MatchPromotion:
8446 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8447 // MatchPromotion is treated as a failure by format_matches.
8448 case MK::NoMatch:
8449 case MK::NoMatchTypeConfusion:
8450 case MK::NoMatchPromotionTypeConfusion:
8451 EmitDiagnostic(S,
8452 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
8453 << buildFormatSpecifier()
8454 << Other.buildFormatSpecifier(),
8455 FmtExpr, InFunctionCall);
8456 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8457 << 0 << Other.Range;
8458 break;
8459
8460 case MK::NoMatchPedantic:
8461 EmitDiagnostic(S,
8462 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
8463 << buildFormatSpecifier()
8464 << Other.buildFormatSpecifier(),
8465 FmtExpr, InFunctionCall);
8466 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8467 << 0 << Other.Range;
8468 break;
8469
8470 case MK::NoMatchSignedness:
8471 EmitDiagnostic(S,
8472 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
8473 << buildFormatSpecifier()
8474 << Other.buildFormatSpecifier(),
8475 FmtExpr, InFunctionCall);
8476 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8477 << 0 << Other.Range;
8478 break;
8479 }
8480 return !HadError;
8481}
8482
8483bool DecomposePrintfHandler::GetSpecifiers(
8484 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8485 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8487 StringRef Data = FSL->getString();
8488 const char *Str = Data.data();
8489 llvm::SmallBitVector BV;
8490 UncoveredArgHandler UA;
8491 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8492 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8493 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8494 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8495 UA, Args);
8496
8498 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
8500 H.DoneProcessing();
8501 if (H.HadError)
8502 return false;
8503
8504 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
8505 const EquatableFormatArgument &B) {
8506 return A.getPosition() < B.getPosition();
8507 });
8508 return true;
8509}
8510
8511bool DecomposePrintfHandler::HandlePrintfSpecifier(
8512 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8513 unsigned specifierLen, const TargetInfo &Target) {
8514 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8515 specifierLen, Target)) {
8516 HadError = true;
8517 return false;
8518 }
8519
8520 // Do not add any specifiers to the list for %%. This is possibly incorrect
8521 // if using a precision/width with a data argument, but that combination is
8522 // meaningless and we wouldn't know which format to attach the
8523 // precision/width to.
8524 const auto &CS = FS.getConversionSpecifier();
8526 return true;
8527
8528 // have to patch these to have the right ModifierFor if they are used
8529 const unsigned Unset = ~0;
8530 unsigned FieldWidthIndex = Unset;
8531 unsigned PrecisionIndex = Unset;
8532
8533 // field width?
8534 const auto &FieldWidth = FS.getFieldWidth();
8535 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8536 FieldWidthIndex = Specs.size();
8537 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8538 getLocationOfByte(FieldWidth.getStart()),
8540 FieldWidth.getArgType(S.Context),
8541 EquatableFormatArgument::FAR_FieldWidth,
8542 EquatableFormatArgument::SS_None,
8543 FieldWidth.usesPositionalArg()
8544 ? FieldWidth.getPositionalArgIndex() - 1
8545 : FieldWidthIndex,
8546 0);
8547 }
8548 // precision?
8549 const auto &Precision = FS.getPrecision();
8550 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8551 PrecisionIndex = Specs.size();
8552 Specs.emplace_back(
8553 getSpecifierRange(startSpecifier, specifierLen),
8554 getLocationOfByte(Precision.getStart()),
8556 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
8557 EquatableFormatArgument::SS_None,
8558 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8559 : PrecisionIndex,
8560 0);
8561 }
8562
8563 // this specifier
8564 unsigned SpecIndex =
8565 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8566 if (FieldWidthIndex != Unset)
8567 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8568 if (PrecisionIndex != Unset)
8569 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8570
8571 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8572 if (FS.isPrivate())
8573 Sensitivity = EquatableFormatArgument::SS_Private;
8574 else if (FS.isPublic())
8575 Sensitivity = EquatableFormatArgument::SS_Public;
8576 else if (FS.isSensitive())
8577 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8578 else
8579 Sensitivity = EquatableFormatArgument::SS_None;
8580
8581 Specs.emplace_back(
8582 getSpecifierRange(startSpecifier, specifierLen),
8583 getLocationOfByte(CS.getStart()), FS.getLengthModifier().getKind(),
8584 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
8585 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
8586
8587 // auxiliary argument?
8590 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8591 getLocationOfByte(CS.getStart()),
8593 CS.getCharacters(),
8595 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
8596 SpecIndex + 1, SpecIndex);
8597 }
8598 return true;
8599}
8600
8601// Determines if the specified is a C++ class or struct containing
8602// a member with the specified name and kind (e.g. a CXXMethodDecl named
8603// "c_str()").
8604template<typename MemberKind>
8606CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8607 auto *RD = Ty->getAsCXXRecordDecl();
8609
8610 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8611 return Results;
8612
8613 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8616
8617 // We just need to include all members of the right kind turned up by the
8618 // filter, at this point.
8619 if (S.LookupQualifiedName(R, RD))
8620 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8621 NamedDecl *decl = (*I)->getUnderlyingDecl();
8622 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8623 Results.insert(FK);
8624 }
8625 return Results;
8626}
8627
8628/// Check if we could call '.c_str()' on an object.
8629///
8630/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8631/// allow the call, or if it would be ambiguous).
8633 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8634
8635 MethodSet Results =
8636 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8637 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8638 MI != ME; ++MI)
8639 if ((*MI)->getMinRequiredArguments() == 0)
8640 return true;
8641 return false;
8642}
8643
8644// Check if a (w)string was passed when a (w)char* was needed, and offer a
8645// better diagnostic if so. AT is assumed to be valid.
8646// Returns true when a c_str() conversion method is found.
8647bool CheckPrintfHandler::checkForCStrMembers(
8648 const analyze_printf::ArgType &AT, const Expr *E) {
8649 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8650
8651 MethodSet Results =
8653
8654 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8655 MI != ME; ++MI) {
8656 const CXXMethodDecl *Method = *MI;
8657 if (Method->getMinRequiredArguments() == 0 &&
8658 AT.matchesType(S.Context, Method->getReturnType())) {
8659 // FIXME: Suggest parens if the expression needs them.
8661 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8662 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8663 return true;
8664 }
8665 }
8666
8667 return false;
8668}
8669
8670bool CheckPrintfHandler::HandlePrintfSpecifier(
8671 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8672 unsigned specifierLen, const TargetInfo &Target) {
8673 using namespace analyze_format_string;
8674 using namespace analyze_printf;
8675
8676 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8677
8678 if (FS.consumesDataArgument()) {
8679 if (atFirstArg) {
8680 atFirstArg = false;
8681 usesPositionalArgs = FS.usesPositionalArg();
8682 }
8683 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8684 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8685 startSpecifier, specifierLen);
8686 return false;
8687 }
8688 }
8689
8690 // First check if the field width, precision, and conversion specifier
8691 // have matching data arguments.
8692 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8693 startSpecifier, specifierLen)) {
8694 return false;
8695 }
8696
8697 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8698 startSpecifier, specifierLen)) {
8699 return false;
8700 }
8701
8702 if (!CS.consumesDataArgument()) {
8703 // FIXME: Technically specifying a precision or field width here
8704 // makes no sense. Worth issuing a warning at some point.
8705 return true;
8706 }
8707
8708 // Consume the argument.
8709 unsigned argIndex = FS.getArgIndex();
8710 if (argIndex < NumDataArgs) {
8711 // The check to see if the argIndex is valid will come later.
8712 // We set the bit here because we may exit early from this
8713 // function if we encounter some other error.
8714 CoveredArgs.set(argIndex);
8715 }
8716
8717 // FreeBSD kernel extensions.
8718 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8719 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8720 // We need at least two arguments.
8721 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8722 return false;
8723
8724 if (HasFormatArguments()) {
8725 // Claim the second argument.
8726 CoveredArgs.set(argIndex + 1);
8727
8728 // Type check the first argument (int for %b, pointer for %D)
8729 const Expr *Ex = getDataArg(argIndex);
8730 const analyze_printf::ArgType &AT =
8731 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8732 ? ArgType(S.Context.IntTy)
8733 : ArgType::CPointerTy;
8734 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8735 EmitFormatDiagnostic(
8736 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8737 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8738 << false << Ex->getSourceRange(),
8739 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8740 getSpecifierRange(startSpecifier, specifierLen));
8741
8742 // Type check the second argument (char * for both %b and %D)
8743 Ex = getDataArg(argIndex + 1);
8745 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8746 EmitFormatDiagnostic(
8747 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8748 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8749 << false << Ex->getSourceRange(),
8750 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8751 getSpecifierRange(startSpecifier, specifierLen));
8752 }
8753 return true;
8754 }
8755
8756 // Check for using an Objective-C specific conversion specifier
8757 // in a non-ObjC literal.
8758 if (!allowsObjCArg() && CS.isObjCArg()) {
8759 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8760 specifierLen);
8761 }
8762
8763 // %P can only be used with os_log.
8764 if (FSType != FormatStringType::OSLog &&
8765 CS.getKind() == ConversionSpecifier::PArg) {
8766 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8767 specifierLen);
8768 }
8769
8770 // %n is not allowed with os_log.
8771 if (FSType == FormatStringType::OSLog &&
8772 CS.getKind() == ConversionSpecifier::nArg) {
8773 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8774 getLocationOfByte(CS.getStart()),
8775 /*IsStringLocation*/ false,
8776 getSpecifierRange(startSpecifier, specifierLen));
8777
8778 return true;
8779 }
8780
8781 // Only scalars are allowed for os_trace.
8782 if (FSType == FormatStringType::OSTrace &&
8783 (CS.getKind() == ConversionSpecifier::PArg ||
8784 CS.getKind() == ConversionSpecifier::sArg ||
8785 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8786 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8787 specifierLen);
8788 }
8789
8790 // Check for use of public/private annotation outside of os_log().
8791 if (FSType != FormatStringType::OSLog) {
8792 if (FS.isPublic().isSet()) {
8793 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8794 << "public",
8795 getLocationOfByte(FS.isPublic().getPosition()),
8796 /*IsStringLocation*/ false,
8797 getSpecifierRange(startSpecifier, specifierLen));
8798 }
8799 if (FS.isPrivate().isSet()) {
8800 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8801 << "private",
8802 getLocationOfByte(FS.isPrivate().getPosition()),
8803 /*IsStringLocation*/ false,
8804 getSpecifierRange(startSpecifier, specifierLen));
8805 }
8806 }
8807
8808 const llvm::Triple &Triple = Target.getTriple();
8809 if (CS.getKind() == ConversionSpecifier::nArg &&
8810 (Triple.isAndroid() || Triple.isOSFuchsia())) {
8811 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
8812 getLocationOfByte(CS.getStart()),
8813 /*IsStringLocation*/ false,
8814 getSpecifierRange(startSpecifier, specifierLen));
8815 }
8816
8817 // Check for invalid use of field width
8818 if (!FS.hasValidFieldWidth()) {
8819 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8820 startSpecifier, specifierLen);
8821 }
8822
8823 // Check for invalid use of precision
8824 if (!FS.hasValidPrecision()) {
8825 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8826 startSpecifier, specifierLen);
8827 }
8828
8829 // Precision is mandatory for %P specifier.
8830 if (CS.getKind() == ConversionSpecifier::PArg &&
8832 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8833 getLocationOfByte(startSpecifier),
8834 /*IsStringLocation*/ false,
8835 getSpecifierRange(startSpecifier, specifierLen));
8836 }
8837
8838 // Check each flag does not conflict with any other component.
8840 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8841 if (!FS.hasValidLeadingZeros())
8842 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8843 if (!FS.hasValidPlusPrefix())
8844 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8845 if (!FS.hasValidSpacePrefix())
8846 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8847 if (!FS.hasValidAlternativeForm())
8848 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8849 if (!FS.hasValidLeftJustified())
8850 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8851
8852 // Check that flags are not ignored by another flag
8853 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8854 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8855 startSpecifier, specifierLen);
8856 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8857 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8858 startSpecifier, specifierLen);
8859
8860 // Check the length modifier is valid with the given conversion specifier.
8862 S.getLangOpts()))
8863 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8864 diag::warn_format_nonsensical_length);
8865 else if (!FS.hasStandardLengthModifier())
8866 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8868 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8869 diag::warn_format_non_standard_conversion_spec);
8870
8872 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8873
8874 // The remaining checks depend on the data arguments.
8875 if (!HasFormatArguments())
8876 return true;
8877
8878 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8879 return false;
8880
8881 const Expr *Arg = getDataArg(argIndex);
8882 if (!Arg)
8883 return true;
8884
8885 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8886}
8887
8888static bool requiresParensToAddCast(const Expr *E) {
8889 // FIXME: We should have a general way to reason about operator
8890 // precedence and whether parens are actually needed here.
8891 // Take care of a few common cases where they aren't.
8892 const Expr *Inside = E->IgnoreImpCasts();
8893 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8894 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8895
8896 switch (Inside->getStmtClass()) {
8897 case Stmt::ArraySubscriptExprClass:
8898 case Stmt::CallExprClass:
8899 case Stmt::CharacterLiteralClass:
8900 case Stmt::CXXBoolLiteralExprClass:
8901 case Stmt::DeclRefExprClass:
8902 case Stmt::FloatingLiteralClass:
8903 case Stmt::IntegerLiteralClass:
8904 case Stmt::MemberExprClass:
8905 case Stmt::ObjCArrayLiteralClass:
8906 case Stmt::ObjCBoolLiteralExprClass:
8907 case Stmt::ObjCBoxedExprClass:
8908 case Stmt::ObjCDictionaryLiteralClass:
8909 case Stmt::ObjCEncodeExprClass:
8910 case Stmt::ObjCIvarRefExprClass:
8911 case Stmt::ObjCMessageExprClass:
8912 case Stmt::ObjCPropertyRefExprClass:
8913 case Stmt::ObjCStringLiteralClass:
8914 case Stmt::ObjCSubscriptRefExprClass:
8915 case Stmt::ParenExprClass:
8916 case Stmt::StringLiteralClass:
8917 case Stmt::UnaryOperatorClass:
8918 return false;
8919 default:
8920 return true;
8921 }
8922}
8923
8924static std::pair<QualType, StringRef>
8926 QualType IntendedTy,
8927 const Expr *E) {
8928 // Use a 'while' to peel off layers of typedefs.
8929 QualType TyTy = IntendedTy;
8930 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8931 StringRef Name = UserTy->getDecl()->getName();
8932 QualType CastTy = llvm::StringSwitch<QualType>(Name)
8933 .Case("CFIndex", Context.getNSIntegerType())
8934 .Case("NSInteger", Context.getNSIntegerType())
8935 .Case("NSUInteger", Context.getNSUIntegerType())
8936 .Case("SInt32", Context.IntTy)
8937 .Case("UInt32", Context.UnsignedIntTy)
8938 .Default(QualType());
8939
8940 if (!CastTy.isNull())
8941 return std::make_pair(CastTy, Name);
8942
8943 TyTy = UserTy->desugar();
8944 }
8945
8946 // Strip parens if necessary.
8947 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8948 return shouldNotPrintDirectly(Context,
8949 PE->getSubExpr()->getType(),
8950 PE->getSubExpr());
8951
8952 // If this is a conditional expression, then its result type is constructed
8953 // via usual arithmetic conversions and thus there might be no necessary
8954 // typedef sugar there. Recurse to operands to check for NSInteger &
8955 // Co. usage condition.
8956 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8957 QualType TrueTy, FalseTy;
8958 StringRef TrueName, FalseName;
8959
8960 std::tie(TrueTy, TrueName) =
8961 shouldNotPrintDirectly(Context,
8962 CO->getTrueExpr()->getType(),
8963 CO->getTrueExpr());
8964 std::tie(FalseTy, FalseName) =
8965 shouldNotPrintDirectly(Context,
8966 CO->getFalseExpr()->getType(),
8967 CO->getFalseExpr());
8968
8969 if (TrueTy == FalseTy)
8970 return std::make_pair(TrueTy, TrueName);
8971 else if (TrueTy.isNull())
8972 return std::make_pair(FalseTy, FalseName);
8973 else if (FalseTy.isNull())
8974 return std::make_pair(TrueTy, TrueName);
8975 }
8976
8977 return std::make_pair(QualType(), StringRef());
8978}
8979
8980/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8981/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8982/// type do not count.
8983static bool
8985 QualType From = ICE->getSubExpr()->getType();
8986 QualType To = ICE->getType();
8987 // It's an integer promotion if the destination type is the promoted
8988 // source type.
8989 if (ICE->getCastKind() == CK_IntegralCast &&
8991 S.Context.getPromotedIntegerType(From) == To)
8992 return true;
8993 // Look through vector types, since we do default argument promotion for
8994 // those in OpenCL.
8995 if (const auto *VecTy = From->getAs<ExtVectorType>())
8996 From = VecTy->getElementType();
8997 if (const auto *VecTy = To->getAs<ExtVectorType>())
8998 To = VecTy->getElementType();
8999 // It's a floating promotion if the source type is a lower rank.
9000 return ICE->getCastKind() == CK_FloatingCast &&
9001 S.Context.getFloatingTypeOrder(From, To) < 0;
9002}
9003
9006 DiagnosticsEngine &Diags, SourceLocation Loc) {
9008 if (Diags.isIgnored(
9009 diag::warn_format_conversion_argument_type_mismatch_signedness,
9010 Loc) ||
9011 Diags.isIgnored(
9012 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9013 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9015 }
9016 }
9017 return Match;
9018}
9019
9020bool
9021CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9022 const char *StartSpecifier,
9023 unsigned SpecifierLen,
9024 const Expr *E) {
9025 using namespace analyze_format_string;
9026 using namespace analyze_printf;
9027
9028 // Now type check the data expression that matches the
9029 // format specifier.
9030 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9031 if (!AT.isValid())
9032 return true;
9033
9034 QualType ExprTy = E->getType();
9035 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9036 ExprTy = TET->getUnderlyingExpr()->getType();
9037 }
9038
9039 if (const OverflowBehaviorType *OBT =
9040 dyn_cast<OverflowBehaviorType>(ExprTy.getCanonicalType()))
9041 ExprTy = OBT->getUnderlyingType();
9042
9043 // When using the format attribute in C++, you can receive a function or an
9044 // array that will necessarily decay to a pointer when passed to the final
9045 // format consumer. Apply decay before type comparison.
9046 if (ExprTy->canDecayToPointerType())
9047 ExprTy = S.Context.getDecayedType(ExprTy);
9048
9049 // Diagnose attempts to print a boolean value as a character. Unlike other
9050 // -Wformat diagnostics, this is fine from a type perspective, but it still
9051 // doesn't make sense.
9054 const CharSourceRange &CSR =
9055 getSpecifierRange(StartSpecifier, SpecifierLen);
9056 SmallString<4> FSString;
9057 llvm::raw_svector_ostream os(FSString);
9058 FS.toString(os);
9059 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9060 << FSString,
9061 E->getExprLoc(), false, CSR);
9062 return true;
9063 }
9064
9065 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9066 // dumping raw class data (like is-a pointer), not actual data.
9068 ExprTy->isObjCObjectPointerType()) {
9069 const CharSourceRange &CSR =
9070 getSpecifierRange(StartSpecifier, SpecifierLen);
9071 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
9072 E->getExprLoc(), false, CSR);
9073 return true;
9074 }
9075
9076 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9078 ArgType::MatchKind OrigMatch = Match;
9079
9081 if (Match == ArgType::Match)
9082 return true;
9083
9084 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9085 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9086
9087 // Look through argument promotions for our error message's reported type.
9088 // This includes the integral and floating promotions, but excludes array
9089 // and function pointer decay (seeing that an argument intended to be a
9090 // string has type 'char [6]' is probably more confusing than 'char *') and
9091 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9092 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9093 if (isArithmeticArgumentPromotion(S, ICE)) {
9094 E = ICE->getSubExpr();
9095 ExprTy = E->getType();
9096
9097 // Check if we didn't match because of an implicit cast from a 'char'
9098 // or 'short' to an 'int'. This is done because printf is a varargs
9099 // function.
9100 if (ICE->getType() == S.Context.IntTy ||
9101 ICE->getType() == S.Context.UnsignedIntTy) {
9102 // All further checking is done on the subexpression
9103 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
9104 if (OrigMatch == ArgType::NoMatchSignedness &&
9105 ImplicitMatch != ArgType::NoMatchSignedness)
9106 // If the original match was a signedness match this match on the
9107 // implicit cast type also need to be signedness match otherwise we
9108 // might introduce new unexpected warnings from -Wformat-signedness.
9109 return true;
9110 ImplicitMatch = handleFormatSignedness(
9111 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
9112 if (ImplicitMatch == ArgType::Match)
9113 return true;
9114 }
9115 }
9116 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9117 // Special case for 'a', which has type 'int' in C.
9118 // Note, however, that we do /not/ want to treat multibyte constants like
9119 // 'MooV' as characters! This form is deprecated but still exists. In
9120 // addition, don't treat expressions as of type 'char' if one byte length
9121 // modifier is provided.
9122 if (ExprTy == S.Context.IntTy &&
9124 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
9125 ExprTy = S.Context.CharTy;
9126 // To improve check results, we consider a character literal in C
9127 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9128 // more likely a type confusion situation, so we will suggest to
9129 // use '%hhd' instead by discarding the MatchPromotion.
9130 if (Match == ArgType::MatchPromotion)
9132 }
9133 }
9134 if (Match == ArgType::MatchPromotion) {
9135 // WG14 N2562 only clarified promotions in *printf
9136 // For NSLog in ObjC, just preserve -Wformat behavior
9137 if (!S.getLangOpts().ObjC &&
9138 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9139 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9140 return true;
9142 }
9143 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9144 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9145 Match = ImplicitMatch;
9146 assert(Match != ArgType::MatchPromotion);
9147
9148 // Look through unscoped enums to their underlying type.
9149 bool IsEnum = false;
9150 bool IsScopedEnum = false;
9151 QualType IntendedTy = ExprTy;
9152 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9153 IntendedTy = ED->getIntegerType();
9154 if (!ED->isScoped()) {
9155 ExprTy = IntendedTy;
9156 // This controls whether we're talking about the underlying type or not,
9157 // which we only want to do when it's an unscoped enum.
9158 IsEnum = true;
9159 } else {
9160 IsScopedEnum = true;
9161 }
9162 }
9163
9164 // %C in an Objective-C context prints a unichar, not a wchar_t.
9165 // If the argument is an integer of some kind, believe the %C and suggest
9166 // a cast instead of changing the conversion specifier.
9167 if (isObjCContext() &&
9170 !ExprTy->isCharType()) {
9171 // 'unichar' is defined as a typedef of unsigned short, but we should
9172 // prefer using the typedef if it is visible.
9173 IntendedTy = S.Context.UnsignedShortTy;
9174
9175 // While we are here, check if the value is an IntegerLiteral that happens
9176 // to be within the valid range.
9177 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9178 const llvm::APInt &V = IL->getValue();
9179 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9180 return true;
9181 }
9182
9183 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9185 if (S.LookupName(Result, S.getCurScope())) {
9186 NamedDecl *ND = Result.getFoundDecl();
9187 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9188 if (TD->getUnderlyingType() == IntendedTy)
9189 IntendedTy =
9191 /*Qualifier=*/std::nullopt, TD);
9192 }
9193 }
9194 }
9195
9196 // Special-case some of Darwin's platform-independence types by suggesting
9197 // casts to primitive types that are known to be large enough.
9198 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9199 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9200 QualType CastTy;
9201 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9202 if (!CastTy.isNull()) {
9203 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9204 // (long in ASTContext). Only complain to pedants or when they're the
9205 // underlying type of a scoped enum (which always needs a cast).
9206 if (!IsScopedEnum &&
9207 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9208 (AT.isSizeT() || AT.isPtrdiffT()) &&
9209 AT.matchesType(S.Context, CastTy))
9211 IntendedTy = CastTy;
9212 ShouldNotPrintDirectly = true;
9213 }
9214 }
9215
9216 // We may be able to offer a FixItHint if it is a supported type.
9217 PrintfSpecifier fixedFS = FS;
9218 bool Success =
9219 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9220
9221 if (Success) {
9222 // Get the fix string from the fixed format specifier
9223 SmallString<16> buf;
9224 llvm::raw_svector_ostream os(buf);
9225 fixedFS.toString(os);
9226
9227 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9228
9229 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9230 unsigned Diag;
9231 switch (Match) {
9232 case ArgType::Match:
9235 llvm_unreachable("expected non-matching");
9237 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9238 break;
9240 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9241 break;
9243 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9244 break;
9245 case ArgType::NoMatch:
9246 Diag = diag::warn_format_conversion_argument_type_mismatch;
9247 break;
9248 }
9249
9250 // In this case, the specifier is wrong and should be changed to match
9251 // the argument.
9252 EmitFormatDiagnostic(S.PDiag(Diag)
9254 << IntendedTy << IsEnum << E->getSourceRange(),
9255 E->getBeginLoc(),
9256 /*IsStringLocation*/ false, SpecRange,
9257 FixItHint::CreateReplacement(SpecRange, os.str()));
9258 } else {
9259 // The canonical type for formatting this value is different from the
9260 // actual type of the expression. (This occurs, for example, with Darwin's
9261 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9262 // should be printed as 'long' for 64-bit compatibility.)
9263 // Rather than emitting a normal format/argument mismatch, we want to
9264 // add a cast to the recommended type (and correct the format string
9265 // if necessary). We should also do so for scoped enumerations.
9266 SmallString<16> CastBuf;
9267 llvm::raw_svector_ostream CastFix(CastBuf);
9268 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9269 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9270 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9271
9273 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
9274 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
9275 E->getExprLoc());
9276 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9277 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9278
9279 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9280 // If there's already a cast present, just replace it.
9281 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9282 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9283
9284 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9285 // If the expression has high enough precedence,
9286 // just write the C-style cast.
9287 Hints.push_back(
9288 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9289 } else {
9290 // Otherwise, add parens around the expression as well as the cast.
9291 CastFix << "(";
9292 Hints.push_back(
9293 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9294
9295 // We don't use getLocForEndOfToken because it returns invalid source
9296 // locations for macro expansions (by design).
9300 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9301 }
9302
9303 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9304 // The expression has a type that should not be printed directly.
9305 // We extract the name from the typedef because we don't want to show
9306 // the underlying type in the diagnostic.
9307 StringRef Name;
9308 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9309 Name = TypedefTy->getDecl()->getName();
9310 else
9311 Name = CastTyName;
9312 unsigned Diag = Match == ArgType::NoMatchPedantic
9313 ? diag::warn_format_argument_needs_cast_pedantic
9314 : diag::warn_format_argument_needs_cast;
9315 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9316 << E->getSourceRange(),
9317 E->getBeginLoc(), /*IsStringLocation=*/false,
9318 SpecRange, Hints);
9319 } else {
9320 // In this case, the expression could be printed using a different
9321 // specifier, but we've decided that the specifier is probably correct
9322 // and we should cast instead. Just use the normal warning message.
9323
9324 unsigned Diag =
9325 IsScopedEnum
9326 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9327 : diag::warn_format_conversion_argument_type_mismatch;
9328
9329 EmitFormatDiagnostic(
9330 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9331 << IsEnum << E->getSourceRange(),
9332 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9333 }
9334 }
9335 } else {
9336 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9337 SpecifierLen);
9338 // Since the warning for passing non-POD types to variadic functions
9339 // was deferred until now, we emit a warning for non-POD
9340 // arguments here.
9341 bool EmitTypeMismatch = false;
9342 switch (S.isValidVarArgType(ExprTy)) {
9343 case VarArgKind::Valid:
9345 unsigned Diag;
9346 switch (Match) {
9347 case ArgType::Match:
9350 llvm_unreachable("expected non-matching");
9352 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9353 break;
9355 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9356 break;
9358 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9359 break;
9360 case ArgType::NoMatch:
9361 Diag = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)
9362 ? diag::err_format_conversion_argument_type_mismatch
9363 : diag::warn_format_conversion_argument_type_mismatch;
9364 break;
9365 }
9366
9367 EmitFormatDiagnostic(
9368 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9369 << IsEnum << CSR << E->getSourceRange(),
9370 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9371 break;
9372 }
9375 if (CallType == VariadicCallType::DoesNotApply) {
9376 EmitTypeMismatch = true;
9377 } else {
9378 EmitFormatDiagnostic(
9379 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9380 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9381 << AT.getRepresentativeTypeName(S.Context) << CSR
9382 << E->getSourceRange(),
9383 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9384 checkForCStrMembers(AT, E);
9385 }
9386 break;
9387
9389 if (CallType == VariadicCallType::DoesNotApply)
9390 EmitTypeMismatch = true;
9391 else if (ExprTy->isObjCObjectType())
9392 EmitFormatDiagnostic(
9393 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9394 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9395 << AT.getRepresentativeTypeName(S.Context) << CSR
9396 << E->getSourceRange(),
9397 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9398 else
9399 // FIXME: If this is an initializer list, suggest removing the braces
9400 // or inserting a cast to the target type.
9401 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9402 << isa<InitListExpr>(E) << ExprTy << CallType
9404 break;
9405 }
9406
9407 if (EmitTypeMismatch) {
9408 // The function is not variadic, so we do not generate warnings about
9409 // being allowed to pass that object as a variadic argument. Instead,
9410 // since there are inherently no printf specifiers for types which cannot
9411 // be passed as variadic arguments, emit a plain old specifier mismatch
9412 // argument.
9413 EmitFormatDiagnostic(
9414 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9415 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
9416 << E->getSourceRange(),
9417 E->getBeginLoc(), false, CSR);
9418 }
9419
9420 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9421 "format string specifier index out of range");
9422 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9423 }
9424
9425 return true;
9426}
9427
9428//===--- CHECK: Scanf format string checking ------------------------------===//
9429
9430namespace {
9431
9432class CheckScanfHandler : public CheckFormatHandler {
9433public:
9434 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9435 const Expr *origFormatExpr, FormatStringType type,
9436 unsigned firstDataArg, unsigned numDataArgs,
9437 const char *beg, Sema::FormatArgumentPassingKind APK,
9438 ArrayRef<const Expr *> Args, unsigned formatIdx,
9439 bool inFunctionCall, VariadicCallType CallType,
9440 llvm::SmallBitVector &CheckedVarArgs,
9441 UncoveredArgHandler &UncoveredArg)
9442 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9443 numDataArgs, beg, APK, Args, formatIdx,
9444 inFunctionCall, CallType, CheckedVarArgs,
9445 UncoveredArg) {}
9446
9447 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9448 const char *startSpecifier,
9449 unsigned specifierLen) override;
9450
9451 bool HandleInvalidScanfConversionSpecifier(
9452 const analyze_scanf::ScanfSpecifier &FS,
9453 const char *startSpecifier,
9454 unsigned specifierLen) override;
9455
9456 void HandleIncompleteScanList(const char *start, const char *end) override;
9457};
9458
9459} // namespace
9460
9461void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9462 const char *end) {
9463 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9464 getLocationOfByte(end), /*IsStringLocation*/true,
9465 getSpecifierRange(start, end - start));
9466}
9467
9468bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9470 const char *startSpecifier,
9471 unsigned specifierLen) {
9474
9475 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9476 getLocationOfByte(CS.getStart()),
9477 startSpecifier, specifierLen,
9478 CS.getStart(), CS.getLength());
9479}
9480
9481bool CheckScanfHandler::HandleScanfSpecifier(
9483 const char *startSpecifier,
9484 unsigned specifierLen) {
9485 using namespace analyze_scanf;
9486 using namespace analyze_format_string;
9487
9488 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9489
9490 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9491 // be used to decide if we are using positional arguments consistently.
9492 if (FS.consumesDataArgument()) {
9493 if (atFirstArg) {
9494 atFirstArg = false;
9495 usesPositionalArgs = FS.usesPositionalArg();
9496 }
9497 else if (usesPositionalArgs != FS.usesPositionalArg()) {
9498 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9499 startSpecifier, specifierLen);
9500 return false;
9501 }
9502 }
9503
9504 // Check if the field with is non-zero.
9505 const OptionalAmount &Amt = FS.getFieldWidth();
9507 if (Amt.getConstantAmount() == 0) {
9508 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9509 Amt.getConstantLength());
9510 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9511 getLocationOfByte(Amt.getStart()),
9512 /*IsStringLocation*/true, R,
9514 }
9515 }
9516
9517 if (!FS.consumesDataArgument()) {
9518 // FIXME: Technically specifying a precision or field width here
9519 // makes no sense. Worth issuing a warning at some point.
9520 return true;
9521 }
9522
9523 // Consume the argument.
9524 unsigned argIndex = FS.getArgIndex();
9525 if (argIndex < NumDataArgs) {
9526 // The check to see if the argIndex is valid will come later.
9527 // We set the bit here because we may exit early from this
9528 // function if we encounter some other error.
9529 CoveredArgs.set(argIndex);
9530 }
9531
9532 // Check the length modifier is valid with the given conversion specifier.
9534 S.getLangOpts()))
9535 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9536 diag::warn_format_nonsensical_length);
9537 else if (!FS.hasStandardLengthModifier())
9538 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9540 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9541 diag::warn_format_non_standard_conversion_spec);
9542
9544 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9545
9546 // The remaining checks depend on the data arguments.
9547 if (!HasFormatArguments())
9548 return true;
9549
9550 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9551 return false;
9552
9553 // Check that the argument type matches the format specifier.
9554 const Expr *Ex = getDataArg(argIndex);
9555 if (!Ex)
9556 return true;
9557
9559
9560 if (!AT.isValid()) {
9561 return true;
9562 }
9563
9565 AT.matchesType(S.Context, Ex->getType());
9568 return true;
9571
9572 ScanfSpecifier fixedFS = FS;
9573 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9574 S.getLangOpts(), S.Context);
9575
9576 unsigned Diag =
9577 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9578 : Signedness
9579 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9580 : diag::warn_format_conversion_argument_type_mismatch;
9581
9582 if (Success) {
9583 // Get the fix string from the fixed format specifier.
9584 SmallString<128> buf;
9585 llvm::raw_svector_ostream os(buf);
9586 fixedFS.toString(os);
9587
9588 EmitFormatDiagnostic(
9590 << Ex->getType() << false << Ex->getSourceRange(),
9591 Ex->getBeginLoc(),
9592 /*IsStringLocation*/ false,
9593 getSpecifierRange(startSpecifier, specifierLen),
9595 getSpecifierRange(startSpecifier, specifierLen), os.str()));
9596 } else {
9597 EmitFormatDiagnostic(S.PDiag(Diag)
9599 << Ex->getType() << false << Ex->getSourceRange(),
9600 Ex->getBeginLoc(),
9601 /*IsStringLocation*/ false,
9602 getSpecifierRange(startSpecifier, specifierLen));
9603 }
9604
9605 return true;
9606}
9607
9608static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9610 const StringLiteral *Fmt,
9612 const Expr *FmtExpr, bool InFunctionCall) {
9613 bool HadError = false;
9614 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9615 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9616 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9617 // In positional-style format strings, the same specifier can appear
9618 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9619 // are sorted by getPosition(), and we process each range of equal
9620 // getPosition() values as one group.
9621 // RefArgs are taken from a string literal that was given to
9622 // attribute(format_matches), and if we got this far, we have already
9623 // verified that if it has positional specifiers that appear in multiple
9624 // locations, then they are all mutually compatible. What's left for us to
9625 // do is verify that all specifiers with the same position in FmtArgs are
9626 // compatible with the RefArgs specifiers. We check each specifier from
9627 // FmtArgs against the first member of the RefArgs group.
9628 for (; FmtIter < FmtEnd; ++FmtIter) {
9629 // Clang does not diagnose missing format specifiers in positional-style
9630 // strings (TODO: which it probably should do, as it is UB to skip over a
9631 // format argument). Skip specifiers if needed.
9632 if (FmtIter->getPosition() < RefIter->getPosition())
9633 continue;
9634
9635 // Delimits a new getPosition() value.
9636 if (FmtIter->getPosition() > RefIter->getPosition())
9637 break;
9638
9639 HadError |=
9640 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
9641 }
9642
9643 // Jump RefIter to the start of the next group.
9644 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
9645 return Arg.getPosition() != RefIter->getPosition();
9646 });
9647 }
9648
9649 if (FmtIter < FmtEnd) {
9650 CheckFormatHandler::EmitFormatDiagnostic(
9651 S, InFunctionCall, FmtExpr,
9652 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
9653 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
9654 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
9655 } else if (RefIter < RefEnd) {
9656 CheckFormatHandler::EmitFormatDiagnostic(
9657 S, InFunctionCall, FmtExpr,
9658 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
9659 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
9660 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
9661 << 1 << RefIter->getSourceRange();
9662 }
9663 return !HadError;
9664}
9665
9667 Sema &S, const FormatStringLiteral *FExpr,
9668 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
9670 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
9671 bool inFunctionCall, VariadicCallType CallType,
9672 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
9673 bool IgnoreStringsWithoutSpecifiers) {
9674 // CHECK: is the format string a wide literal?
9675 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9676 CheckFormatHandler::EmitFormatDiagnostic(
9677 S, inFunctionCall, Args[format_idx],
9678 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9679 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9680 return;
9681 }
9682
9683 // Str - The format string. NOTE: this is NOT null-terminated!
9684 StringRef StrRef = FExpr->getString();
9685 const char *Str = StrRef.data();
9686 // Account for cases where the string literal is truncated in a declaration.
9687 const ConstantArrayType *T =
9688 S.Context.getAsConstantArrayType(FExpr->getType());
9689 assert(T && "String literal not of constant array type!");
9690 size_t TypeSize = T->getZExtSize();
9691 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9692 const unsigned numDataArgs = Args.size() - firstDataArg;
9693
9694 if (IgnoreStringsWithoutSpecifiers &&
9696 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9697 return;
9698
9699 // Emit a warning if the string literal is truncated and does not contain an
9700 // embedded null character.
9701 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9702 CheckFormatHandler::EmitFormatDiagnostic(
9703 S, inFunctionCall, Args[format_idx],
9704 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9705 FExpr->getBeginLoc(),
9706 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9707 return;
9708 }
9709
9710 // CHECK: empty format string?
9711 if (StrLen == 0 && numDataArgs > 0) {
9712 CheckFormatHandler::EmitFormatDiagnostic(
9713 S, inFunctionCall, Args[format_idx],
9714 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9715 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9716 return;
9717 }
9718
9723 bool IsObjC =
9725 if (ReferenceFormatString == nullptr) {
9726 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9727 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9728 inFunctionCall, CallType, CheckedVarArgs,
9729 UncoveredArg);
9730
9732 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
9735 H.DoneProcessing();
9736 } else {
9738 Type, ReferenceFormatString, FExpr->getFormatString(),
9739 inFunctionCall ? nullptr : Args[format_idx]);
9740 }
9741 } else if (Type == FormatStringType::Scanf) {
9742 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9743 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9744 CallType, CheckedVarArgs, UncoveredArg);
9745
9747 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9748 H.DoneProcessing();
9749 } // TODO: handle other formats
9750}
9751
9753 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9754 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9759 return true;
9760
9761 bool IsObjC =
9764 FormatStringLiteral RefLit = AuthoritativeFormatString;
9765 FormatStringLiteral TestLit = TestedFormatString;
9766 const Expr *Arg;
9767 bool DiagAtStringLiteral;
9768 if (FunctionCallArg) {
9769 Arg = FunctionCallArg;
9770 DiagAtStringLiteral = false;
9771 } else {
9772 Arg = TestedFormatString;
9773 DiagAtStringLiteral = true;
9774 }
9775 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
9776 AuthoritativeFormatString, Type,
9777 IsObjC, true, RefArgs) &&
9778 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
9779 DiagAtStringLiteral, FmtArgs)) {
9780 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
9781 TestedFormatString, FmtArgs, Arg,
9782 DiagAtStringLiteral);
9783 }
9784 return false;
9785}
9786
9788 const StringLiteral *Str) {
9793 return true;
9794
9795 FormatStringLiteral RefLit = Str;
9797 bool IsObjC =
9799 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
9800 true, Args))
9801 return false;
9802
9803 // Group arguments by getPosition() value, and check that each member of the
9804 // group is compatible with the first member. This verifies that when
9805 // positional arguments are used multiple times (such as %2$i %2$d), all uses
9806 // are mutually compatible. As an optimization, don't test the first member
9807 // against itself.
9808 bool HadError = false;
9809 auto Iter = Args.begin();
9810 auto End = Args.end();
9811 while (Iter != End) {
9812 const auto &FirstInGroup = *Iter;
9813 for (++Iter;
9814 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
9815 ++Iter) {
9816 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
9817 }
9818 }
9819 return !HadError;
9820}
9821
9823 // Str - The format string. NOTE: this is NOT null-terminated!
9824 StringRef StrRef = FExpr->getString();
9825 const char *Str = StrRef.data();
9826 // Account for cases where the string literal is truncated in a declaration.
9827 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9828 assert(T && "String literal not of constant array type!");
9829 size_t TypeSize = T->getZExtSize();
9830 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9831 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9832 getLangOpts(),
9833 Context.getTargetInfo());
9834}
9835
9836//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9837
9838// Returns the related absolute value function that is larger, of 0 if one
9839// does not exist.
9840static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9841 switch (AbsFunction) {
9842 default:
9843 return 0;
9844
9845 case Builtin::BI__builtin_abs:
9846 return Builtin::BI__builtin_labs;
9847 case Builtin::BI__builtin_labs:
9848 return Builtin::BI__builtin_llabs;
9849 case Builtin::BI__builtin_llabs:
9850 return 0;
9851
9852 case Builtin::BI__builtin_fabsf:
9853 return Builtin::BI__builtin_fabs;
9854 case Builtin::BI__builtin_fabs:
9855 return Builtin::BI__builtin_fabsl;
9856 case Builtin::BI__builtin_fabsl:
9857 return 0;
9858
9859 case Builtin::BI__builtin_cabsf:
9860 return Builtin::BI__builtin_cabs;
9861 case Builtin::BI__builtin_cabs:
9862 return Builtin::BI__builtin_cabsl;
9863 case Builtin::BI__builtin_cabsl:
9864 return 0;
9865
9866 case Builtin::BIabs:
9867 return Builtin::BIlabs;
9868 case Builtin::BIlabs:
9869 return Builtin::BIllabs;
9870 case Builtin::BIllabs:
9871 return 0;
9872
9873 case Builtin::BIfabsf:
9874 return Builtin::BIfabs;
9875 case Builtin::BIfabs:
9876 return Builtin::BIfabsl;
9877 case Builtin::BIfabsl:
9878 return 0;
9879
9880 case Builtin::BIcabsf:
9881 return Builtin::BIcabs;
9882 case Builtin::BIcabs:
9883 return Builtin::BIcabsl;
9884 case Builtin::BIcabsl:
9885 return 0;
9886 }
9887}
9888
9889// Returns the argument type of the absolute value function.
9891 unsigned AbsType) {
9892 if (AbsType == 0)
9893 return QualType();
9894
9896 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9898 return QualType();
9899
9901 if (!FT)
9902 return QualType();
9903
9904 if (FT->getNumParams() != 1)
9905 return QualType();
9906
9907 return FT->getParamType(0);
9908}
9909
9910// Returns the best absolute value function, or zero, based on type and
9911// current absolute value function.
9912static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9913 unsigned AbsFunctionKind) {
9914 unsigned BestKind = 0;
9915 uint64_t ArgSize = Context.getTypeSize(ArgType);
9916 for (unsigned Kind = AbsFunctionKind; Kind != 0;
9917 Kind = getLargerAbsoluteValueFunction(Kind)) {
9918 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9919 if (Context.getTypeSize(ParamType) >= ArgSize) {
9920 if (BestKind == 0)
9921 BestKind = Kind;
9922 else if (Context.hasSameType(ParamType, ArgType)) {
9923 BestKind = Kind;
9924 break;
9925 }
9926 }
9927 }
9928 return BestKind;
9929}
9930
9936
9938 if (T->isIntegralOrEnumerationType())
9939 return AVK_Integer;
9940 if (T->isRealFloatingType())
9941 return AVK_Floating;
9942 if (T->isAnyComplexType())
9943 return AVK_Complex;
9944
9945 llvm_unreachable("Type not integer, floating, or complex");
9946}
9947
9948// Changes the absolute value function to a different type. Preserves whether
9949// the function is a builtin.
9950static unsigned changeAbsFunction(unsigned AbsKind,
9951 AbsoluteValueKind ValueKind) {
9952 switch (ValueKind) {
9953 case AVK_Integer:
9954 switch (AbsKind) {
9955 default:
9956 return 0;
9957 case Builtin::BI__builtin_fabsf:
9958 case Builtin::BI__builtin_fabs:
9959 case Builtin::BI__builtin_fabsl:
9960 case Builtin::BI__builtin_cabsf:
9961 case Builtin::BI__builtin_cabs:
9962 case Builtin::BI__builtin_cabsl:
9963 return Builtin::BI__builtin_abs;
9964 case Builtin::BIfabsf:
9965 case Builtin::BIfabs:
9966 case Builtin::BIfabsl:
9967 case Builtin::BIcabsf:
9968 case Builtin::BIcabs:
9969 case Builtin::BIcabsl:
9970 return Builtin::BIabs;
9971 }
9972 case AVK_Floating:
9973 switch (AbsKind) {
9974 default:
9975 return 0;
9976 case Builtin::BI__builtin_abs:
9977 case Builtin::BI__builtin_labs:
9978 case Builtin::BI__builtin_llabs:
9979 case Builtin::BI__builtin_cabsf:
9980 case Builtin::BI__builtin_cabs:
9981 case Builtin::BI__builtin_cabsl:
9982 return Builtin::BI__builtin_fabsf;
9983 case Builtin::BIabs:
9984 case Builtin::BIlabs:
9985 case Builtin::BIllabs:
9986 case Builtin::BIcabsf:
9987 case Builtin::BIcabs:
9988 case Builtin::BIcabsl:
9989 return Builtin::BIfabsf;
9990 }
9991 case AVK_Complex:
9992 switch (AbsKind) {
9993 default:
9994 return 0;
9995 case Builtin::BI__builtin_abs:
9996 case Builtin::BI__builtin_labs:
9997 case Builtin::BI__builtin_llabs:
9998 case Builtin::BI__builtin_fabsf:
9999 case Builtin::BI__builtin_fabs:
10000 case Builtin::BI__builtin_fabsl:
10001 return Builtin::BI__builtin_cabsf;
10002 case Builtin::BIabs:
10003 case Builtin::BIlabs:
10004 case Builtin::BIllabs:
10005 case Builtin::BIfabsf:
10006 case Builtin::BIfabs:
10007 case Builtin::BIfabsl:
10008 return Builtin::BIcabsf;
10009 }
10010 }
10011 llvm_unreachable("Unable to convert function");
10012}
10013
10014static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10015 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10016 if (!FnInfo)
10017 return 0;
10018
10019 switch (FDecl->getBuiltinID()) {
10020 default:
10021 return 0;
10022 case Builtin::BI__builtin_abs:
10023 case Builtin::BI__builtin_fabs:
10024 case Builtin::BI__builtin_fabsf:
10025 case Builtin::BI__builtin_fabsl:
10026 case Builtin::BI__builtin_labs:
10027 case Builtin::BI__builtin_llabs:
10028 case Builtin::BI__builtin_cabs:
10029 case Builtin::BI__builtin_cabsf:
10030 case Builtin::BI__builtin_cabsl:
10031 case Builtin::BIabs:
10032 case Builtin::BIlabs:
10033 case Builtin::BIllabs:
10034 case Builtin::BIfabs:
10035 case Builtin::BIfabsf:
10036 case Builtin::BIfabsl:
10037 case Builtin::BIcabs:
10038 case Builtin::BIcabsf:
10039 case Builtin::BIcabsl:
10040 return FDecl->getBuiltinID();
10041 }
10042 llvm_unreachable("Unknown Builtin type");
10043}
10044
10045// If the replacement is valid, emit a note with replacement function.
10046// Additionally, suggest including the proper header if not already included.
10048 unsigned AbsKind, QualType ArgType) {
10049 bool EmitHeaderHint = true;
10050 const char *HeaderName = nullptr;
10051 std::string FunctionName;
10052 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10053 FunctionName = "std::abs";
10054 if (ArgType->isIntegralOrEnumerationType()) {
10055 HeaderName = "cstdlib";
10056 } else if (ArgType->isRealFloatingType()) {
10057 HeaderName = "cmath";
10058 } else {
10059 llvm_unreachable("Invalid Type");
10060 }
10061
10062 // Lookup all std::abs
10063 if (NamespaceDecl *Std = S.getStdNamespace()) {
10064 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10066 S.LookupQualifiedName(R, Std);
10067
10068 for (const auto *I : R) {
10069 const FunctionDecl *FDecl = nullptr;
10070 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10071 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10072 } else {
10073 FDecl = dyn_cast<FunctionDecl>(I);
10074 }
10075 if (!FDecl)
10076 continue;
10077
10078 // Found std::abs(), check that they are the right ones.
10079 if (FDecl->getNumParams() != 1)
10080 continue;
10081
10082 // Check that the parameter type can handle the argument.
10083 QualType ParamType = FDecl->getParamDecl(0)->getType();
10084 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10085 S.Context.getTypeSize(ArgType) <=
10086 S.Context.getTypeSize(ParamType)) {
10087 // Found a function, don't need the header hint.
10088 EmitHeaderHint = false;
10089 break;
10090 }
10091 }
10092 }
10093 } else {
10094 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10095 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10096
10097 if (HeaderName) {
10098 DeclarationName DN(&S.Context.Idents.get(FunctionName));
10099 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10101 S.LookupName(R, S.getCurScope());
10102
10103 if (R.isSingleResult()) {
10104 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10105 if (FD && FD->getBuiltinID() == AbsKind) {
10106 EmitHeaderHint = false;
10107 } else {
10108 return;
10109 }
10110 } else if (!R.empty()) {
10111 return;
10112 }
10113 }
10114 }
10115
10116 S.Diag(Loc, diag::note_replace_abs_function)
10117 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10118
10119 if (!HeaderName)
10120 return;
10121
10122 if (!EmitHeaderHint)
10123 return;
10124
10125 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10126 << FunctionName;
10127}
10128
10129template <std::size_t StrLen>
10130static bool IsStdFunction(const FunctionDecl *FDecl,
10131 const char (&Str)[StrLen]) {
10132 if (!FDecl)
10133 return false;
10134 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10135 return false;
10136 if (!FDecl->isInStdNamespace())
10137 return false;
10138
10139 return true;
10140}
10141
10142enum class MathCheck { NaN, Inf };
10143static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10144 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10145 return llvm::is_contained(names, calleeName);
10146 };
10147
10148 switch (Check) {
10149 case MathCheck::NaN:
10150 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10151 "__builtin_nanf16", "__builtin_nanf128"});
10152 case MathCheck::Inf:
10153 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10154 "__builtin_inff16", "__builtin_inff128"});
10155 }
10156 llvm_unreachable("unknown MathCheck");
10157}
10158
10159static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10160 if (FDecl->getName() != "infinity")
10161 return false;
10162
10163 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
10164 const CXXRecordDecl *RDecl = MDecl->getParent();
10165 if (RDecl->getName() != "numeric_limits")
10166 return false;
10167
10168 if (const NamespaceDecl *NSDecl =
10169 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
10170 return NSDecl->isStdNamespace();
10171 }
10172
10173 return false;
10174}
10175
10176void Sema::CheckInfNaNFunction(const CallExpr *Call,
10177 const FunctionDecl *FDecl) {
10178 if (!FDecl->getIdentifier())
10179 return;
10180
10181 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
10182 if (FPO.getNoHonorNaNs() &&
10183 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
10185 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10186 << 1 << 0 << Call->getSourceRange();
10187 return;
10188 }
10189
10190 if (FPO.getNoHonorInfs() &&
10191 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
10192 IsInfinityFunction(FDecl) ||
10194 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10195 << 0 << 0 << Call->getSourceRange();
10196 }
10197}
10198
10199void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10200 const FunctionDecl *FDecl) {
10201 if (Call->getNumArgs() != 1)
10202 return;
10203
10204 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10205 bool IsStdAbs = IsStdFunction(FDecl, "abs");
10206 if (AbsKind == 0 && !IsStdAbs)
10207 return;
10208
10209 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10210 QualType ParamType = Call->getArg(0)->getType();
10211
10212 // Unsigned types cannot be negative. Suggest removing the absolute value
10213 // function call.
10214 if (ArgType->isUnsignedIntegerType()) {
10215 std::string FunctionName =
10216 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10217 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10218 Diag(Call->getExprLoc(), diag::note_remove_abs)
10219 << FunctionName
10220 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10221 return;
10222 }
10223
10224 // Taking the absolute value of a pointer is very suspicious, they probably
10225 // wanted to index into an array, dereference a pointer, call a function, etc.
10226 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10227 unsigned DiagType = 0;
10228 if (ArgType->isFunctionType())
10229 DiagType = 1;
10230 else if (ArgType->isArrayType())
10231 DiagType = 2;
10232
10233 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10234 return;
10235 }
10236
10237 // std::abs has overloads which prevent most of the absolute value problems
10238 // from occurring.
10239 if (IsStdAbs)
10240 return;
10241
10242 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10243 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10244
10245 // The argument and parameter are the same kind. Check if they are the right
10246 // size.
10247 if (ArgValueKind == ParamValueKind) {
10248 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10249 return;
10250
10251 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10252 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10253 << FDecl << ArgType << ParamType;
10254
10255 if (NewAbsKind == 0)
10256 return;
10257
10258 emitReplacement(*this, Call->getExprLoc(),
10259 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10260 return;
10261 }
10262
10263 // ArgValueKind != ParamValueKind
10264 // The wrong type of absolute value function was used. Attempt to find the
10265 // proper one.
10266 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10267 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10268 if (NewAbsKind == 0)
10269 return;
10270
10271 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10272 << FDecl << ParamValueKind << ArgValueKind;
10273
10274 emitReplacement(*this, Call->getExprLoc(),
10275 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10276}
10277
10278//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10279void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10280 const FunctionDecl *FDecl) {
10281 if (!Call || !FDecl) return;
10282
10283 // Ignore template specializations and macros.
10284 if (inTemplateInstantiation()) return;
10285 if (Call->getExprLoc().isMacroID()) return;
10286
10287 // Only care about the one template argument, two function parameter std::max
10288 if (Call->getNumArgs() != 2) return;
10289 if (!IsStdFunction(FDecl, "max")) return;
10290 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10291 if (!ArgList) return;
10292 if (ArgList->size() != 1) return;
10293
10294 // Check that template type argument is unsigned integer.
10295 const auto& TA = ArgList->get(0);
10296 if (TA.getKind() != TemplateArgument::Type) return;
10297 QualType ArgType = TA.getAsType();
10298 if (!ArgType->isUnsignedIntegerType()) return;
10299
10300 // See if either argument is a literal zero.
10301 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10302 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10303 if (!MTE) return false;
10304 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10305 if (!Num) return false;
10306 if (Num->getValue() != 0) return false;
10307 return true;
10308 };
10309
10310 const Expr *FirstArg = Call->getArg(0);
10311 const Expr *SecondArg = Call->getArg(1);
10312 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10313 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10314
10315 // Only warn when exactly one argument is zero.
10316 if (IsFirstArgZero == IsSecondArgZero) return;
10317
10318 SourceRange FirstRange = FirstArg->getSourceRange();
10319 SourceRange SecondRange = SecondArg->getSourceRange();
10320
10321 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10322
10323 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10324 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10325
10326 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10327 SourceRange RemovalRange;
10328 if (IsFirstArgZero) {
10329 RemovalRange = SourceRange(FirstRange.getBegin(),
10330 SecondRange.getBegin().getLocWithOffset(-1));
10331 } else {
10332 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10333 SecondRange.getEnd());
10334 }
10335
10336 Diag(Call->getExprLoc(), diag::note_remove_max_call)
10337 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10338 << FixItHint::CreateRemoval(RemovalRange);
10339}
10340
10341//===--- CHECK: Standard memory functions ---------------------------------===//
10342
10343/// Takes the expression passed to the size_t parameter of functions
10344/// such as memcmp, strncat, etc and warns if it's a comparison.
10345///
10346/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10348 const IdentifierInfo *FnName,
10349 SourceLocation FnLoc,
10350 SourceLocation RParenLoc) {
10351 const auto *Size = dyn_cast<BinaryOperator>(E);
10352 if (!Size)
10353 return false;
10354
10355 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10356 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10357 return false;
10358
10359 SourceRange SizeRange = Size->getSourceRange();
10360 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10361 << SizeRange << FnName;
10362 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10363 << FnName
10365 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10366 << FixItHint::CreateRemoval(RParenLoc);
10367 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10368 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10370 ")");
10371
10372 return true;
10373}
10374
10375/// Determine whether the given type is or contains a dynamic class type
10376/// (e.g., whether it has a vtable).
10378 bool &IsContained) {
10379 // Look through array types while ignoring qualifiers.
10380 const Type *Ty = T->getBaseElementTypeUnsafe();
10381 IsContained = false;
10382
10383 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10384 RD = RD ? RD->getDefinition() : nullptr;
10385 if (!RD || RD->isInvalidDecl())
10386 return nullptr;
10387
10388 if (RD->isDynamicClass())
10389 return RD;
10390
10391 // Check all the fields. If any bases were dynamic, the class is dynamic.
10392 // It's impossible for a class to transitively contain itself by value, so
10393 // infinite recursion is impossible.
10394 for (auto *FD : RD->fields()) {
10395 bool SubContained;
10396 if (const CXXRecordDecl *ContainedRD =
10397 getContainedDynamicClass(FD->getType(), SubContained)) {
10398 IsContained = true;
10399 return ContainedRD;
10400 }
10401 }
10402
10403 return nullptr;
10404}
10405
10407 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10408 if (Unary->getKind() == UETT_SizeOf)
10409 return Unary;
10410 return nullptr;
10411}
10412
10413/// If E is a sizeof expression, returns its argument expression,
10414/// otherwise returns NULL.
10415static const Expr *getSizeOfExprArg(const Expr *E) {
10417 if (!SizeOf->isArgumentType())
10418 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10419 return nullptr;
10420}
10421
10422/// If E is a sizeof expression, returns its argument type.
10425 return SizeOf->getTypeOfArgument();
10426 return QualType();
10427}
10428
10429namespace {
10430
10431struct SearchNonTrivialToInitializeField
10432 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10433 using Super =
10434 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10435
10436 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10437
10438 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10439 SourceLocation SL) {
10440 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10441 asDerived().visitArray(PDIK, AT, SL);
10442 return;
10443 }
10444
10445 Super::visitWithKind(PDIK, FT, SL);
10446 }
10447
10448 void visitARCStrong(QualType FT, SourceLocation SL) {
10449 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10450 }
10451 void visitARCWeak(QualType FT, SourceLocation SL) {
10452 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10453 }
10454 void visitStruct(QualType FT, SourceLocation SL) {
10455 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10456 visit(FD->getType(), FD->getLocation());
10457 }
10458 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10459 const ArrayType *AT, SourceLocation SL) {
10460 visit(getContext().getBaseElementType(AT), SL);
10461 }
10462 void visitTrivial(QualType FT, SourceLocation SL) {}
10463
10464 static void diag(QualType RT, const Expr *E, Sema &S) {
10465 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10466 }
10467
10468 ASTContext &getContext() { return S.getASTContext(); }
10469
10470 const Expr *E;
10471 Sema &S;
10472};
10473
10474struct SearchNonTrivialToCopyField
10475 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10476 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10477
10478 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10479
10480 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10481 SourceLocation SL) {
10482 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10483 asDerived().visitArray(PCK, AT, SL);
10484 return;
10485 }
10486
10487 Super::visitWithKind(PCK, FT, SL);
10488 }
10489
10490 void visitARCStrong(QualType FT, SourceLocation SL) {
10491 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10492 }
10493 void visitARCWeak(QualType FT, SourceLocation SL) {
10494 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10495 }
10496 void visitPtrAuth(QualType FT, SourceLocation SL) {
10497 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10498 }
10499 void visitStruct(QualType FT, SourceLocation SL) {
10500 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10501 visit(FD->getType(), FD->getLocation());
10502 }
10503 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10504 SourceLocation SL) {
10505 visit(getContext().getBaseElementType(AT), SL);
10506 }
10507 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10508 SourceLocation SL) {}
10509 void visitTrivial(QualType FT, SourceLocation SL) {}
10510 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10511
10512 static void diag(QualType RT, const Expr *E, Sema &S) {
10513 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10514 }
10515
10516 ASTContext &getContext() { return S.getASTContext(); }
10517
10518 const Expr *E;
10519 Sema &S;
10520};
10521
10522}
10523
10524/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10525static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10526 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10527
10528 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10529 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10530 return false;
10531
10532 return doesExprLikelyComputeSize(BO->getLHS()) ||
10533 doesExprLikelyComputeSize(BO->getRHS());
10534 }
10535
10536 return getAsSizeOfExpr(SizeofExpr) != nullptr;
10537}
10538
10539/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10540///
10541/// \code
10542/// #define MACRO 0
10543/// foo(MACRO);
10544/// foo(0);
10545/// \endcode
10546///
10547/// This should return true for the first call to foo, but not for the second
10548/// (regardless of whether foo is a macro or function).
10550 SourceLocation CallLoc,
10551 SourceLocation ArgLoc) {
10552 if (!CallLoc.isMacroID())
10553 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10554
10555 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10556 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10557}
10558
10559/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10560/// last two arguments transposed.
10561static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10562 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10563 return;
10564
10565 const Expr *SizeArg =
10566 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10567
10568 auto isLiteralZero = [](const Expr *E) {
10569 return (isa<IntegerLiteral>(E) &&
10570 cast<IntegerLiteral>(E)->getValue() == 0) ||
10572 cast<CharacterLiteral>(E)->getValue() == 0);
10573 };
10574
10575 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10576 SourceLocation CallLoc = Call->getRParenLoc();
10578 if (isLiteralZero(SizeArg) &&
10579 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10580
10581 SourceLocation DiagLoc = SizeArg->getExprLoc();
10582
10583 // Some platforms #define bzero to __builtin_memset. See if this is the
10584 // case, and if so, emit a better diagnostic.
10585 if (BId == Builtin::BIbzero ||
10587 CallLoc, SM, S.getLangOpts()) == "bzero")) {
10588 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10589 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10590 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10591 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10592 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10593 }
10594 return;
10595 }
10596
10597 // If the second argument to a memset is a sizeof expression and the third
10598 // isn't, this is also likely an error. This should catch
10599 // 'memset(buf, sizeof(buf), 0xff)'.
10600 if (BId == Builtin::BImemset &&
10601 doesExprLikelyComputeSize(Call->getArg(1)) &&
10602 !doesExprLikelyComputeSize(Call->getArg(2))) {
10603 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10604 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10605 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10606 return;
10607 }
10608}
10609
10610void Sema::CheckMemaccessArguments(const CallExpr *Call,
10611 unsigned BId,
10612 IdentifierInfo *FnName) {
10613 assert(BId != 0);
10614
10615 // It is possible to have a non-standard definition of memset. Validate
10616 // we have enough arguments, and if not, abort further checking.
10617 unsigned ExpectedNumArgs =
10618 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10619 if (Call->getNumArgs() < ExpectedNumArgs)
10620 return;
10621
10622 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10623 BId == Builtin::BIstrndup ? 1 : 2);
10624 unsigned LenArg =
10625 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10626 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10627
10628 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10629 Call->getBeginLoc(), Call->getRParenLoc()))
10630 return;
10631
10632 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10633 CheckMemaccessSize(*this, BId, Call);
10634
10635 // We have special checking when the length is a sizeof expression.
10636 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10637
10638 // Although widely used, 'bzero' is not a standard function. Be more strict
10639 // with the argument types before allowing diagnostics and only allow the
10640 // form bzero(ptr, sizeof(...)).
10641 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10642 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10643 return;
10644
10645 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10646 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10647 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10648
10649 QualType DestTy = Dest->getType();
10650 QualType PointeeTy;
10651 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10652 PointeeTy = DestPtrTy->getPointeeType();
10653
10654 // Never warn about void type pointers. This can be used to suppress
10655 // false positives.
10656 if (PointeeTy->isVoidType())
10657 continue;
10658
10659 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10660 // actually comparing the expressions for equality. Because computing the
10661 // expression IDs can be expensive, we only do this if the diagnostic is
10662 // enabled.
10663 if (CheckSizeofMemaccessArgument(LenExpr, Dest, FnName))
10664 break;
10665
10666 // Also check for cases where the sizeof argument is the exact same
10667 // type as the memory argument, and where it points to a user-defined
10668 // record type.
10669 if (SizeOfArgTy != QualType()) {
10670 if (PointeeTy->isRecordType() &&
10671 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10672 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10673 PDiag(diag::warn_sizeof_pointer_type_memaccess)
10674 << FnName << SizeOfArgTy << ArgIdx
10675 << PointeeTy << Dest->getSourceRange()
10676 << LenExpr->getSourceRange());
10677 break;
10678 }
10679 }
10680 } else if (DestTy->isArrayType()) {
10681 PointeeTy = DestTy;
10682 }
10683
10684 if (PointeeTy == QualType())
10685 continue;
10686
10687 // Always complain about dynamic classes.
10688 bool IsContained;
10689 if (const CXXRecordDecl *ContainedRD =
10690 getContainedDynamicClass(PointeeTy, IsContained)) {
10691
10692 unsigned OperationType = 0;
10693 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10694 // "overwritten" if we're warning about the destination for any call
10695 // but memcmp; otherwise a verb appropriate to the call.
10696 if (ArgIdx != 0 || IsCmp) {
10697 if (BId == Builtin::BImemcpy)
10698 OperationType = 1;
10699 else if(BId == Builtin::BImemmove)
10700 OperationType = 2;
10701 else if (IsCmp)
10702 OperationType = 3;
10703 }
10704
10705 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10706 PDiag(diag::warn_dyn_class_memaccess)
10707 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10708 << IsContained << ContainedRD << OperationType
10709 << Call->getCallee()->getSourceRange());
10710 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10711 BId != Builtin::BImemset)
10713 Dest->getExprLoc(), Dest,
10714 PDiag(diag::warn_arc_object_memaccess)
10715 << ArgIdx << FnName << PointeeTy
10716 << Call->getCallee()->getSourceRange());
10717 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10718
10719 // FIXME: Do not consider incomplete types even though they may be
10720 // completed later. GCC does not diagnose such code, but we may want to
10721 // consider diagnosing it in the future, perhaps under a different, but
10722 // related, diagnostic group.
10723 bool NonTriviallyCopyableCXXRecord =
10724 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10725 !PointeeTy.isTriviallyCopyableType(Context);
10726
10727 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10729 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10730 PDiag(diag::warn_cstruct_memaccess)
10731 << ArgIdx << FnName << PointeeTy << 0);
10732 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10733 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10734 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10735 // FIXME: Limiting this warning to dest argument until we decide
10736 // whether it's valid for source argument too.
10737 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10738 PDiag(diag::warn_cxxstruct_memaccess)
10739 << FnName << PointeeTy);
10740 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10742 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10743 PDiag(diag::warn_cstruct_memaccess)
10744 << ArgIdx << FnName << PointeeTy << 1);
10745 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10746 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10747 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10748 // FIXME: Limiting this warning to dest argument until we decide
10749 // whether it's valid for source argument too.
10750 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10751 PDiag(diag::warn_cxxstruct_memaccess)
10752 << FnName << PointeeTy);
10753 } else {
10754 continue;
10755 }
10756 } else
10757 continue;
10758
10760 Dest->getExprLoc(), Dest,
10761 PDiag(diag::note_bad_memaccess_silence)
10762 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10763 break;
10764 }
10765}
10766
10767bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
10768 IdentifierInfo *FnName) {
10769 llvm::FoldingSetNodeID SizeOfArgID;
10770 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10771 if (!SizeOfArg)
10772 return false;
10773 // Computing this warning is expensive, so we only do so if the warning is
10774 // enabled.
10775 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10776 SizeOfArg->getExprLoc()))
10777 return false;
10778 QualType DestTy = Dest->getType();
10779 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
10780 if (!DestPtrTy)
10781 return false;
10782
10783 QualType PointeeTy = DestPtrTy->getPointeeType();
10784
10785 if (SizeOfArgID == llvm::FoldingSetNodeID())
10786 SizeOfArg->Profile(SizeOfArgID, Context, true);
10787
10788 llvm::FoldingSetNodeID DestID;
10789 Dest->Profile(DestID, Context, true);
10790 if (DestID == SizeOfArgID) {
10791 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10792 // over sizeof(src) as well.
10793 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10794 StringRef ReadableName = FnName->getName();
10795
10796 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest);
10797 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
10798 ActionIdx = 1; // If its an address-of operator, just remove it.
10799 if (!PointeeTy->isIncompleteType() &&
10800 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10801 ActionIdx = 2; // If the pointee's size is sizeof(char),
10802 // suggest an explicit length.
10803
10804 // If the function is defined as a builtin macro, do not show macro
10805 // expansion.
10806 SourceLocation SL = SizeOfArg->getExprLoc();
10807 SourceRange DSR = Dest->getSourceRange();
10808 SourceRange SSR = SizeOfArg->getSourceRange();
10809 SourceManager &SM = getSourceManager();
10810
10811 if (SM.isMacroArgExpansion(SL)) {
10812 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10813 SL = SM.getSpellingLoc(SL);
10814 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10815 SM.getSpellingLoc(DSR.getEnd()));
10816 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10817 SM.getSpellingLoc(SSR.getEnd()));
10818 }
10819
10820 DiagRuntimeBehavior(SL, SizeOfArg,
10821 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10822 << ReadableName << PointeeTy << DestTy << DSR
10823 << SSR);
10824 DiagRuntimeBehavior(SL, SizeOfArg,
10825 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10826 << ActionIdx << SSR);
10827 return true;
10828 }
10829 return false;
10830}
10831
10832// A little helper routine: ignore addition and subtraction of integer literals.
10833// This intentionally does not ignore all integer constant expressions because
10834// we don't want to remove sizeof().
10835static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10836 Ex = Ex->IgnoreParenCasts();
10837
10838 while (true) {
10839 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10840 if (!BO || !BO->isAdditiveOp())
10841 break;
10842
10843 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10844 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10845
10846 if (isa<IntegerLiteral>(RHS))
10847 Ex = LHS;
10848 else if (isa<IntegerLiteral>(LHS))
10849 Ex = RHS;
10850 else
10851 break;
10852 }
10853
10854 return Ex;
10855}
10856
10858 ASTContext &Context) {
10859 // Only handle constant-sized or VLAs, but not flexible members.
10860 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10861 // Only issue the FIXIT for arrays of size > 1.
10862 if (CAT->getZExtSize() <= 1)
10863 return false;
10864 } else if (!Ty->isVariableArrayType()) {
10865 return false;
10866 }
10867 return true;
10868}
10869
10870void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10871 IdentifierInfo *FnName) {
10872
10873 // Don't crash if the user has the wrong number of arguments
10874 unsigned NumArgs = Call->getNumArgs();
10875 if ((NumArgs != 3) && (NumArgs != 4))
10876 return;
10877
10878 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10879 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10880 const Expr *CompareWithSrc = nullptr;
10881
10882 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10883 Call->getBeginLoc(), Call->getRParenLoc()))
10884 return;
10885
10886 // Look for 'strlcpy(dst, x, sizeof(x))'
10887 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10888 CompareWithSrc = Ex;
10889 else {
10890 // Look for 'strlcpy(dst, x, strlen(x))'
10891 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10892 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10893 SizeCall->getNumArgs() == 1)
10894 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10895 }
10896 }
10897
10898 if (!CompareWithSrc)
10899 return;
10900
10901 // Determine if the argument to sizeof/strlen is equal to the source
10902 // argument. In principle there's all kinds of things you could do
10903 // here, for instance creating an == expression and evaluating it with
10904 // EvaluateAsBooleanCondition, but this uses a more direct technique:
10905 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10906 if (!SrcArgDRE)
10907 return;
10908
10909 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10910 if (!CompareWithSrcDRE ||
10911 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10912 return;
10913
10914 const Expr *OriginalSizeArg = Call->getArg(2);
10915 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10916 << OriginalSizeArg->getSourceRange() << FnName;
10917
10918 // Output a FIXIT hint if the destination is an array (rather than a
10919 // pointer to an array). This could be enhanced to handle some
10920 // pointers if we know the actual size, like if DstArg is 'array+2'
10921 // we could say 'sizeof(array)-2'.
10922 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10924 return;
10925
10926 SmallString<128> sizeString;
10927 llvm::raw_svector_ostream OS(sizeString);
10928 OS << "sizeof(";
10929 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10930 OS << ")";
10931
10932 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10933 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10934 OS.str());
10935}
10936
10937/// Check if two expressions refer to the same declaration.
10938static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10939 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10940 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10941 return D1->getDecl() == D2->getDecl();
10942 return false;
10943}
10944
10945static const Expr *getStrlenExprArg(const Expr *E) {
10946 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10947 const FunctionDecl *FD = CE->getDirectCallee();
10948 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10949 return nullptr;
10950 return CE->getArg(0)->IgnoreParenCasts();
10951 }
10952 return nullptr;
10953}
10954
10955void Sema::CheckStrncatArguments(const CallExpr *CE,
10956 const IdentifierInfo *FnName) {
10957 // Don't crash if the user has the wrong number of arguments.
10958 if (CE->getNumArgs() < 3)
10959 return;
10960 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10961 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10962 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10963
10964 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10965 CE->getRParenLoc()))
10966 return;
10967
10968 // Identify common expressions, which are wrongly used as the size argument
10969 // to strncat and may lead to buffer overflows.
10970 unsigned PatternType = 0;
10971 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10972 // - sizeof(dst)
10973 if (referToTheSameDecl(SizeOfArg, DstArg))
10974 PatternType = 1;
10975 // - sizeof(src)
10976 else if (referToTheSameDecl(SizeOfArg, SrcArg))
10977 PatternType = 2;
10978 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10979 if (BE->getOpcode() == BO_Sub) {
10980 const Expr *L = BE->getLHS()->IgnoreParenCasts();
10981 const Expr *R = BE->getRHS()->IgnoreParenCasts();
10982 // - sizeof(dst) - strlen(dst)
10983 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10985 PatternType = 1;
10986 // - sizeof(src) - (anything)
10987 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10988 PatternType = 2;
10989 }
10990 }
10991
10992 if (PatternType == 0)
10993 return;
10994
10995 // Generate the diagnostic.
10996 SourceLocation SL = LenArg->getBeginLoc();
10997 SourceRange SR = LenArg->getSourceRange();
10998 SourceManager &SM = getSourceManager();
10999
11000 // If the function is defined as a builtin macro, do not show macro expansion.
11001 if (SM.isMacroArgExpansion(SL)) {
11002 SL = SM.getSpellingLoc(SL);
11003 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11004 SM.getSpellingLoc(SR.getEnd()));
11005 }
11006
11007 // Check if the destination is an array (rather than a pointer to an array).
11008 QualType DstTy = DstArg->getType();
11009 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11010 Context);
11011 if (!isKnownSizeArray) {
11012 if (PatternType == 1)
11013 Diag(SL, diag::warn_strncat_wrong_size) << SR;
11014 else
11015 Diag(SL, diag::warn_strncat_src_size) << SR;
11016 return;
11017 }
11018
11019 if (PatternType == 1)
11020 Diag(SL, diag::warn_strncat_large_size) << SR;
11021 else
11022 Diag(SL, diag::warn_strncat_src_size) << SR;
11023
11024 SmallString<128> sizeString;
11025 llvm::raw_svector_ostream OS(sizeString);
11026 OS << "sizeof(";
11027 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11028 OS << ") - ";
11029 OS << "strlen(";
11030 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11031 OS << ") - 1";
11032
11033 Diag(SL, diag::note_strncat_wrong_size)
11034 << FixItHint::CreateReplacement(SR, OS.str());
11035}
11036
11037namespace {
11038void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11039 const UnaryOperator *UnaryExpr, const Decl *D) {
11041 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11042 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11043 return;
11044 }
11045}
11046
11047void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11048 const UnaryOperator *UnaryExpr) {
11049 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11050 const Decl *D = Lvalue->getDecl();
11051 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11052 if (!DD->getType()->isReferenceType())
11053 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11054 }
11055 }
11056
11057 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11058 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11059 Lvalue->getMemberDecl());
11060}
11061
11062void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11063 const UnaryOperator *UnaryExpr) {
11064 const auto *Lambda = dyn_cast<LambdaExpr>(
11066 if (!Lambda)
11067 return;
11068
11069 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11070 << CalleeName << 2 /*object: lambda expression*/;
11071}
11072
11073void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11074 const DeclRefExpr *Lvalue) {
11075 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11076 if (Var == nullptr)
11077 return;
11078
11079 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11080 << CalleeName << 0 /*object: */ << Var;
11081}
11082
11083void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11084 const CastExpr *Cast) {
11085 SmallString<128> SizeString;
11086 llvm::raw_svector_ostream OS(SizeString);
11087
11088 clang::CastKind Kind = Cast->getCastKind();
11089 if (Kind == clang::CK_BitCast &&
11090 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11091 return;
11092 if (Kind == clang::CK_IntegralToPointer &&
11094 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11095 return;
11096
11097 switch (Cast->getCastKind()) {
11098 case clang::CK_BitCast:
11099 case clang::CK_IntegralToPointer:
11100 case clang::CK_FunctionToPointerDecay:
11101 OS << '\'';
11102 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11103 OS << '\'';
11104 break;
11105 default:
11106 return;
11107 }
11108
11109 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11110 << CalleeName << 0 /*object: */ << OS.str();
11111}
11112} // namespace
11113
11114void Sema::CheckFreeArguments(const CallExpr *E) {
11115 const std::string CalleeName =
11116 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11117
11118 { // Prefer something that doesn't involve a cast to make things simpler.
11119 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11120 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11121 switch (UnaryExpr->getOpcode()) {
11122 case UnaryOperator::Opcode::UO_AddrOf:
11123 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11124 case UnaryOperator::Opcode::UO_Plus:
11125 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11126 default:
11127 break;
11128 }
11129
11130 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11131 if (Lvalue->getType()->isArrayType())
11132 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11133
11134 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11135 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11136 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11137 return;
11138 }
11139
11140 if (isa<BlockExpr>(Arg)) {
11141 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11142 << CalleeName << 1 /*object: block*/;
11143 return;
11144 }
11145 }
11146 // Maybe the cast was important, check after the other cases.
11147 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11148 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11149}
11150
11151void
11152Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11153 SourceLocation ReturnLoc,
11154 bool isObjCMethod,
11155 const AttrVec *Attrs,
11156 const FunctionDecl *FD) {
11157 // Check if the return value is null but should not be.
11158 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11159 (!isObjCMethod && isNonNullType(lhsType))) &&
11160 CheckNonNullExpr(*this, RetValExp))
11161 Diag(ReturnLoc, diag::warn_null_ret)
11162 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11163
11164 // C++11 [basic.stc.dynamic.allocation]p4:
11165 // If an allocation function declared with a non-throwing
11166 // exception-specification fails to allocate storage, it shall return
11167 // a null pointer. Any other allocation function that fails to allocate
11168 // storage shall indicate failure only by throwing an exception [...]
11169 if (FD) {
11171 if (Op == OO_New || Op == OO_Array_New) {
11172 const FunctionProtoType *Proto
11173 = FD->getType()->castAs<FunctionProtoType>();
11174 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11175 CheckNonNullExpr(*this, RetValExp))
11176 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11177 << FD << getLangOpts().CPlusPlus11;
11178 }
11179 }
11180
11181 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11182 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
11183 }
11184
11185 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11186 // here prevent the user from using a PPC MMA type as trailing return type.
11187 if (Context.getTargetInfo().getTriple().isPPC64())
11188 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11189}
11190
11192 const Expr *RHS, BinaryOperatorKind Opcode) {
11193 if (!BinaryOperator::isEqualityOp(Opcode))
11194 return;
11195
11196 // Match and capture subexpressions such as "(float) X == 0.1".
11197 const FloatingLiteral *FPLiteral;
11198 const CastExpr *FPCast;
11199 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11200 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11201 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11202 return FPLiteral && FPCast;
11203 };
11204
11205 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11206 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11207 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11208 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11209 TargetTy->isFloatingPoint()) {
11210 bool Lossy;
11211 llvm::APFloat TargetC = FPLiteral->getValue();
11212 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11213 llvm::APFloat::rmNearestTiesToEven, &Lossy);
11214 if (Lossy) {
11215 // If the literal cannot be represented in the source type, then a
11216 // check for == is always false and check for != is always true.
11217 Diag(Loc, diag::warn_float_compare_literal)
11218 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11219 << LHS->getSourceRange() << RHS->getSourceRange();
11220 return;
11221 }
11222 }
11223 }
11224
11225 // Match a more general floating-point equality comparison (-Wfloat-equal).
11226 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11227 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11228
11229 // Special case: check for x == x (which is OK).
11230 // Do not emit warnings for such cases.
11231 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11232 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11233 if (DRL->getDecl() == DRR->getDecl())
11234 return;
11235
11236 // Special case: check for comparisons against literals that can be exactly
11237 // represented by APFloat. In such cases, do not emit a warning. This
11238 // is a heuristic: often comparison against such literals are used to
11239 // detect if a value in a variable has not changed. This clearly can
11240 // lead to false negatives.
11241 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11242 if (FLL->isExact())
11243 return;
11244 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11245 if (FLR->isExact())
11246 return;
11247
11248 // Check for comparisons with builtin types.
11249 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
11250 CL && CL->getBuiltinCallee())
11251 return;
11252
11253 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
11254 CR && CR->getBuiltinCallee())
11255 return;
11256
11257 // Emit the diagnostic.
11258 Diag(Loc, diag::warn_floatingpoint_eq)
11259 << LHS->getSourceRange() << RHS->getSourceRange();
11260}
11261
11262//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11263//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11264
11265namespace {
11266
11267/// Structure recording the 'active' range of an integer-valued
11268/// expression.
11269struct IntRange {
11270 /// The number of bits active in the int. Note that this includes exactly one
11271 /// sign bit if !NonNegative.
11272 unsigned Width;
11273
11274 /// True if the int is known not to have negative values. If so, all leading
11275 /// bits before Width are known zero, otherwise they are known to be the
11276 /// same as the MSB within Width.
11277 bool NonNegative;
11278
11279 IntRange(unsigned Width, bool NonNegative)
11280 : Width(Width), NonNegative(NonNegative) {}
11281
11282 /// Number of bits excluding the sign bit.
11283 unsigned valueBits() const {
11284 return NonNegative ? Width : Width - 1;
11285 }
11286
11287 /// Returns the range of the bool type.
11288 static IntRange forBoolType() {
11289 return IntRange(1, true);
11290 }
11291
11292 /// Returns the range of an opaque value of the given integral type.
11293 static IntRange forValueOfType(ASTContext &C, QualType T) {
11294 return forValueOfCanonicalType(C,
11296 }
11297
11298 /// Returns the range of an opaque value of a canonical integral type.
11299 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11300 assert(T->isCanonicalUnqualified());
11301
11302 if (const auto *VT = dyn_cast<VectorType>(T))
11303 T = VT->getElementType().getTypePtr();
11304 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11305 T = MT->getElementType().getTypePtr();
11306 if (const auto *CT = dyn_cast<ComplexType>(T))
11307 T = CT->getElementType().getTypePtr();
11308 if (const auto *AT = dyn_cast<AtomicType>(T))
11309 T = AT->getValueType().getTypePtr();
11310 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11311 T = OBT->getUnderlyingType().getTypePtr();
11312
11313 if (!C.getLangOpts().CPlusPlus) {
11314 // For enum types in C code, use the underlying datatype.
11315 if (const auto *ED = T->getAsEnumDecl())
11316 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
11317 } else if (auto *Enum = T->getAsEnumDecl()) {
11318 // For enum types in C++, use the known bit width of the enumerators.
11319 // In C++11, enums can have a fixed underlying type. Use this type to
11320 // compute the range.
11321 if (Enum->isFixed()) {
11322 return IntRange(C.getIntWidth(QualType(T, 0)),
11323 !Enum->getIntegerType()->isSignedIntegerType());
11324 }
11325
11326 unsigned NumPositive = Enum->getNumPositiveBits();
11327 unsigned NumNegative = Enum->getNumNegativeBits();
11328
11329 if (NumNegative == 0)
11330 return IntRange(NumPositive, true/*NonNegative*/);
11331 else
11332 return IntRange(std::max(NumPositive + 1, NumNegative),
11333 false/*NonNegative*/);
11334 }
11335
11336 if (const auto *EIT = dyn_cast<BitIntType>(T))
11337 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11338
11339 const BuiltinType *BT = cast<BuiltinType>(T);
11340 assert(BT->isInteger());
11341
11342 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11343 }
11344
11345 /// Returns the "target" range of a canonical integral type, i.e.
11346 /// the range of values expressible in the type.
11347 ///
11348 /// This matches forValueOfCanonicalType except that enums have the
11349 /// full range of their type, not the range of their enumerators.
11350 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11351 assert(T->isCanonicalUnqualified());
11352
11353 if (const VectorType *VT = dyn_cast<VectorType>(T))
11354 T = VT->getElementType().getTypePtr();
11355 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11356 T = MT->getElementType().getTypePtr();
11357 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11358 T = CT->getElementType().getTypePtr();
11359 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11360 T = AT->getValueType().getTypePtr();
11361 if (const auto *ED = T->getAsEnumDecl())
11362 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
11363 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11364 T = OBT->getUnderlyingType().getTypePtr();
11365
11366 if (const auto *EIT = dyn_cast<BitIntType>(T))
11367 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11368
11369 const BuiltinType *BT = cast<BuiltinType>(T);
11370 assert(BT->isInteger());
11371
11372 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11373 }
11374
11375 /// Returns the supremum of two ranges: i.e. their conservative merge.
11376 static IntRange join(IntRange L, IntRange R) {
11377 bool Unsigned = L.NonNegative && R.NonNegative;
11378 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11379 L.NonNegative && R.NonNegative);
11380 }
11381
11382 /// Return the range of a bitwise-AND of the two ranges.
11383 static IntRange bit_and(IntRange L, IntRange R) {
11384 unsigned Bits = std::max(L.Width, R.Width);
11385 bool NonNegative = false;
11386 if (L.NonNegative) {
11387 Bits = std::min(Bits, L.Width);
11388 NonNegative = true;
11389 }
11390 if (R.NonNegative) {
11391 Bits = std::min(Bits, R.Width);
11392 NonNegative = true;
11393 }
11394 return IntRange(Bits, NonNegative);
11395 }
11396
11397 /// Return the range of a sum of the two ranges.
11398 static IntRange sum(IntRange L, IntRange R) {
11399 bool Unsigned = L.NonNegative && R.NonNegative;
11400 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11401 Unsigned);
11402 }
11403
11404 /// Return the range of a difference of the two ranges.
11405 static IntRange difference(IntRange L, IntRange R) {
11406 // We need a 1-bit-wider range if:
11407 // 1) LHS can be negative: least value can be reduced.
11408 // 2) RHS can be negative: greatest value can be increased.
11409 bool CanWiden = !L.NonNegative || !R.NonNegative;
11410 bool Unsigned = L.NonNegative && R.Width == 0;
11411 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11412 !Unsigned,
11413 Unsigned);
11414 }
11415
11416 /// Return the range of a product of the two ranges.
11417 static IntRange product(IntRange L, IntRange R) {
11418 // If both LHS and RHS can be negative, we can form
11419 // -2^L * -2^R = 2^(L + R)
11420 // which requires L + R + 1 value bits to represent.
11421 bool CanWiden = !L.NonNegative && !R.NonNegative;
11422 bool Unsigned = L.NonNegative && R.NonNegative;
11423 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11424 Unsigned);
11425 }
11426
11427 /// Return the range of a remainder operation between the two ranges.
11428 static IntRange rem(IntRange L, IntRange R) {
11429 // The result of a remainder can't be larger than the result of
11430 // either side. The sign of the result is the sign of the LHS.
11431 bool Unsigned = L.NonNegative;
11432 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11433 Unsigned);
11434 }
11435};
11436
11437} // namespace
11438
11439static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11440 if (value.isSigned() && value.isNegative())
11441 return IntRange(value.getSignificantBits(), false);
11442
11443 if (value.getBitWidth() > MaxWidth)
11444 value = value.trunc(MaxWidth);
11445
11446 // isNonNegative() just checks the sign bit without considering
11447 // signedness.
11448 return IntRange(value.getActiveBits(), true);
11449}
11450
11451static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11452 if (result.isInt())
11453 return GetValueRange(result.getInt(), MaxWidth);
11454
11455 if (result.isVector()) {
11456 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
11457 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11458 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
11459 R = IntRange::join(R, El);
11460 }
11461 return R;
11462 }
11463
11464 if (result.isComplexInt()) {
11465 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
11466 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
11467 return IntRange::join(R, I);
11468 }
11469
11470 // This can happen with lossless casts to intptr_t of "based" lvalues.
11471 // Assume it might use arbitrary bits.
11472 // FIXME: The only reason we need to pass the type in here is to get
11473 // the sign right on this one case. It would be nice if APValue
11474 // preserved this.
11475 assert(result.isLValue() || result.isAddrLabelDiff());
11476 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11477}
11478
11479static QualType GetExprType(const Expr *E) {
11480 QualType Ty = E->getType();
11481 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11482 Ty = AtomicRHS->getValueType();
11483 return Ty;
11484}
11485
11486/// Attempts to estimate an approximate range for the given integer expression.
11487/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11488/// reliable estimation cannot be determined.
11489///
11490/// \param MaxWidth The width to which the value will be truncated.
11491/// \param InConstantContext If \c true, interpret the expression within a
11492/// constant context.
11493/// \param Approximate If \c true, provide a likely range of values by assuming
11494/// that arithmetic on narrower types remains within those types.
11495/// If \c false, return a range that includes all possible values
11496/// resulting from the expression.
11497/// \returns A range of values that the expression might take, or
11498/// std::nullopt if a reliable estimation cannot be determined.
11499static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11500 unsigned MaxWidth,
11501 bool InConstantContext,
11502 bool Approximate) {
11503 E = E->IgnoreParens();
11504
11505 // Try a full evaluation first.
11506 Expr::EvalResult result;
11507 if (E->EvaluateAsRValue(result, C, InConstantContext))
11508 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
11509
11510 // I think we only want to look through implicit casts here; if the
11511 // user has an explicit widening cast, we should treat the value as
11512 // being of the new, wider type.
11513 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11514 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11515 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11516 Approximate);
11517
11518 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11519
11520 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11521 CE->getCastKind() == CK_BooleanToSignedIntegral;
11522
11523 // Assume that non-integer casts can span the full range of the type.
11524 if (!isIntegerCast)
11525 return OutputTypeRange;
11526
11527 std::optional<IntRange> SubRange = TryGetExprRange(
11528 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
11529 InConstantContext, Approximate);
11530 if (!SubRange)
11531 return std::nullopt;
11532
11533 // Bail out if the subexpr's range is as wide as the cast type.
11534 if (SubRange->Width >= OutputTypeRange.Width)
11535 return OutputTypeRange;
11536
11537 // Otherwise, we take the smaller width, and we're non-negative if
11538 // either the output type or the subexpr is.
11539 return IntRange(SubRange->Width,
11540 SubRange->NonNegative || OutputTypeRange.NonNegative);
11541 }
11542
11543 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11544 // If we can fold the condition, just take that operand.
11545 bool CondResult;
11546 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11547 return TryGetExprRange(
11548 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
11549 InConstantContext, Approximate);
11550
11551 // Otherwise, conservatively merge.
11552 // TryGetExprRange requires an integer expression, but a throw expression
11553 // results in a void type.
11554 Expr *TrueExpr = CO->getTrueExpr();
11555 if (TrueExpr->getType()->isVoidType())
11556 return std::nullopt;
11557
11558 std::optional<IntRange> L =
11559 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
11560 if (!L)
11561 return std::nullopt;
11562
11563 Expr *FalseExpr = CO->getFalseExpr();
11564 if (FalseExpr->getType()->isVoidType())
11565 return std::nullopt;
11566
11567 std::optional<IntRange> R =
11568 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
11569 if (!R)
11570 return std::nullopt;
11571
11572 return IntRange::join(*L, *R);
11573 }
11574
11575 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11576 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11577
11578 switch (BO->getOpcode()) {
11579 case BO_Cmp:
11580 llvm_unreachable("builtin <=> should have class type");
11581
11582 // Boolean-valued operations are single-bit and positive.
11583 case BO_LAnd:
11584 case BO_LOr:
11585 case BO_LT:
11586 case BO_GT:
11587 case BO_LE:
11588 case BO_GE:
11589 case BO_EQ:
11590 case BO_NE:
11591 return IntRange::forBoolType();
11592
11593 // The type of the assignments is the type of the LHS, so the RHS
11594 // is not necessarily the same type.
11595 case BO_MulAssign:
11596 case BO_DivAssign:
11597 case BO_RemAssign:
11598 case BO_AddAssign:
11599 case BO_SubAssign:
11600 case BO_XorAssign:
11601 case BO_OrAssign:
11602 // TODO: bitfields?
11603 return IntRange::forValueOfType(C, GetExprType(E));
11604
11605 // Simple assignments just pass through the RHS, which will have
11606 // been coerced to the LHS type.
11607 case BO_Assign:
11608 // TODO: bitfields?
11609 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11610 Approximate);
11611
11612 // Operations with opaque sources are black-listed.
11613 case BO_PtrMemD:
11614 case BO_PtrMemI:
11615 return IntRange::forValueOfType(C, GetExprType(E));
11616
11617 // Bitwise-and uses the *infinum* of the two source ranges.
11618 case BO_And:
11619 case BO_AndAssign:
11620 Combine = IntRange::bit_and;
11621 break;
11622
11623 // Left shift gets black-listed based on a judgement call.
11624 case BO_Shl:
11625 // ...except that we want to treat '1 << (blah)' as logically
11626 // positive. It's an important idiom.
11627 if (IntegerLiteral *I
11628 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11629 if (I->getValue() == 1) {
11630 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11631 return IntRange(R.Width, /*NonNegative*/ true);
11632 }
11633 }
11634 [[fallthrough]];
11635
11636 case BO_ShlAssign:
11637 return IntRange::forValueOfType(C, GetExprType(E));
11638
11639 // Right shift by a constant can narrow its left argument.
11640 case BO_Shr:
11641 case BO_ShrAssign: {
11642 std::optional<IntRange> L = TryGetExprRange(
11643 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11644 if (!L)
11645 return std::nullopt;
11646
11647 // If the shift amount is a positive constant, drop the width by
11648 // that much.
11649 if (std::optional<llvm::APSInt> shift =
11650 BO->getRHS()->getIntegerConstantExpr(C)) {
11651 if (shift->isNonNegative()) {
11652 if (shift->uge(L->Width))
11653 L->Width = (L->NonNegative ? 0 : 1);
11654 else
11655 L->Width -= shift->getZExtValue();
11656 }
11657 }
11658
11659 return L;
11660 }
11661
11662 // Comma acts as its right operand.
11663 case BO_Comma:
11664 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11665 Approximate);
11666
11667 case BO_Add:
11668 if (!Approximate)
11669 Combine = IntRange::sum;
11670 break;
11671
11672 case BO_Sub:
11673 if (BO->getLHS()->getType()->isPointerType())
11674 return IntRange::forValueOfType(C, GetExprType(E));
11675 if (!Approximate)
11676 Combine = IntRange::difference;
11677 break;
11678
11679 case BO_Mul:
11680 if (!Approximate)
11681 Combine = IntRange::product;
11682 break;
11683
11684 // The width of a division result is mostly determined by the size
11685 // of the LHS.
11686 case BO_Div: {
11687 // Don't 'pre-truncate' the operands.
11688 unsigned opWidth = C.getIntWidth(GetExprType(E));
11689 std::optional<IntRange> L = TryGetExprRange(
11690 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11691 if (!L)
11692 return std::nullopt;
11693
11694 // If the divisor is constant, use that.
11695 if (std::optional<llvm::APSInt> divisor =
11696 BO->getRHS()->getIntegerConstantExpr(C)) {
11697 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11698 if (log2 >= L->Width)
11699 L->Width = (L->NonNegative ? 0 : 1);
11700 else
11701 L->Width = std::min(L->Width - log2, MaxWidth);
11702 return L;
11703 }
11704
11705 // Otherwise, just use the LHS's width.
11706 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11707 // could be -1.
11708 std::optional<IntRange> R = TryGetExprRange(
11709 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11710 if (!R)
11711 return std::nullopt;
11712
11713 return IntRange(L->Width, L->NonNegative && R->NonNegative);
11714 }
11715
11716 case BO_Rem:
11717 Combine = IntRange::rem;
11718 break;
11719
11720 // The default behavior is okay for these.
11721 case BO_Xor:
11722 case BO_Or:
11723 break;
11724 }
11725
11726 // Combine the two ranges, but limit the result to the type in which we
11727 // performed the computation.
11728 QualType T = GetExprType(E);
11729 unsigned opWidth = C.getIntWidth(T);
11730 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
11731 InConstantContext, Approximate);
11732 if (!L)
11733 return std::nullopt;
11734
11735 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
11736 InConstantContext, Approximate);
11737 if (!R)
11738 return std::nullopt;
11739
11740 IntRange C = Combine(*L, *R);
11741 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11742 C.Width = std::min(C.Width, MaxWidth);
11743 return C;
11744 }
11745
11746 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11747 switch (UO->getOpcode()) {
11748 // Boolean-valued operations are white-listed.
11749 case UO_LNot:
11750 return IntRange::forBoolType();
11751
11752 // Operations with opaque sources are black-listed.
11753 case UO_Deref:
11754 case UO_AddrOf: // should be impossible
11755 return IntRange::forValueOfType(C, GetExprType(E));
11756
11757 case UO_Minus: {
11758 if (E->getType()->isUnsignedIntegerType()) {
11759 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11760 Approximate);
11761 }
11762
11763 std::optional<IntRange> SubRange = TryGetExprRange(
11764 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11765
11766 if (!SubRange)
11767 return std::nullopt;
11768
11769 // If the range was previously non-negative, we need an extra bit for the
11770 // sign bit. Otherwise, we need an extra bit because the negation of the
11771 // most-negative value is one bit wider than that value.
11772 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
11773 }
11774
11775 case UO_Not: {
11776 if (E->getType()->isUnsignedIntegerType()) {
11777 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11778 Approximate);
11779 }
11780
11781 std::optional<IntRange> SubRange = TryGetExprRange(
11782 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11783
11784 if (!SubRange)
11785 return std::nullopt;
11786
11787 // The width increments by 1 if the sub-expression cannot be negative
11788 // since it now can be.
11789 return IntRange(
11790 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
11791 false);
11792 }
11793
11794 default:
11795 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11796 Approximate);
11797 }
11798 }
11799
11800 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11801 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11802 Approximate);
11803
11804 if (const auto *BitField = E->getSourceBitField())
11805 return IntRange(BitField->getBitWidthValue(),
11806 BitField->getType()->isUnsignedIntegerOrEnumerationType());
11807
11808 if (GetExprType(E)->isVoidType())
11809 return std::nullopt;
11810
11811 return IntRange::forValueOfType(C, GetExprType(E));
11812}
11813
11814static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11815 bool InConstantContext,
11816 bool Approximate) {
11817 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11818 Approximate);
11819}
11820
11821/// Checks whether the given value, which currently has the given
11822/// source semantics, has the same value when coerced through the
11823/// target semantics.
11824static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11825 const llvm::fltSemantics &Src,
11826 const llvm::fltSemantics &Tgt) {
11827 llvm::APFloat truncated = value;
11828
11829 bool ignored;
11830 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11831 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11832
11833 return truncated.bitwiseIsEqual(value);
11834}
11835
11836/// Checks whether the given value, which currently has the given
11837/// source semantics, has the same value when coerced through the
11838/// target semantics.
11839///
11840/// The value might be a vector of floats (or a complex number).
11841static bool IsSameFloatAfterCast(const APValue &value,
11842 const llvm::fltSemantics &Src,
11843 const llvm::fltSemantics &Tgt) {
11844 if (value.isFloat())
11845 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11846
11847 if (value.isVector()) {
11848 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11849 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11850 return false;
11851 return true;
11852 }
11853
11854 if (value.isMatrix()) {
11855 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
11856 if (!IsSameFloatAfterCast(value.getMatrixElt(i), Src, Tgt))
11857 return false;
11858 return true;
11859 }
11860
11861 assert(value.isComplexFloat());
11862 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11863 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11864}
11865
11866static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11867 bool IsListInit = false);
11868
11869static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
11870 // Suppress cases where we are comparing against an enum constant.
11871 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11872 if (isa<EnumConstantDecl>(DR->getDecl()))
11873 return true;
11874
11875 // Suppress cases where the value is expanded from a macro, unless that macro
11876 // is how a language represents a boolean literal. This is the case in both C
11877 // and Objective-C.
11878 SourceLocation BeginLoc = E->getBeginLoc();
11879 if (BeginLoc.isMacroID()) {
11880 StringRef MacroName = Lexer::getImmediateMacroName(
11881 BeginLoc, S.getSourceManager(), S.getLangOpts());
11882 return MacroName != "YES" && MacroName != "NO" &&
11883 MacroName != "true" && MacroName != "false";
11884 }
11885
11886 return false;
11887}
11888
11889static bool isKnownToHaveUnsignedValue(const Expr *E) {
11890 return E->getType()->isIntegerType() &&
11891 (!E->getType()->isSignedIntegerType() ||
11893}
11894
11895namespace {
11896/// The promoted range of values of a type. In general this has the
11897/// following structure:
11898///
11899/// |-----------| . . . |-----------|
11900/// ^ ^ ^ ^
11901/// Min HoleMin HoleMax Max
11902///
11903/// ... where there is only a hole if a signed type is promoted to unsigned
11904/// (in which case Min and Max are the smallest and largest representable
11905/// values).
11906struct PromotedRange {
11907 // Min, or HoleMax if there is a hole.
11908 llvm::APSInt PromotedMin;
11909 // Max, or HoleMin if there is a hole.
11910 llvm::APSInt PromotedMax;
11911
11912 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11913 if (R.Width == 0)
11914 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11915 else if (R.Width >= BitWidth && !Unsigned) {
11916 // Promotion made the type *narrower*. This happens when promoting
11917 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11918 // Treat all values of 'signed int' as being in range for now.
11919 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11920 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11921 } else {
11922 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11923 .extOrTrunc(BitWidth);
11924 PromotedMin.setIsUnsigned(Unsigned);
11925
11926 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11927 .extOrTrunc(BitWidth);
11928 PromotedMax.setIsUnsigned(Unsigned);
11929 }
11930 }
11931
11932 // Determine whether this range is contiguous (has no hole).
11933 bool isContiguous() const { return PromotedMin <= PromotedMax; }
11934
11935 // Where a constant value is within the range.
11936 enum ComparisonResult {
11937 LT = 0x1,
11938 LE = 0x2,
11939 GT = 0x4,
11940 GE = 0x8,
11941 EQ = 0x10,
11942 NE = 0x20,
11943 InRangeFlag = 0x40,
11944
11945 Less = LE | LT | NE,
11946 Min = LE | InRangeFlag,
11947 InRange = InRangeFlag,
11948 Max = GE | InRangeFlag,
11949 Greater = GE | GT | NE,
11950
11951 OnlyValue = LE | GE | EQ | InRangeFlag,
11952 InHole = NE
11953 };
11954
11955 ComparisonResult compare(const llvm::APSInt &Value) const {
11956 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11957 Value.isUnsigned() == PromotedMin.isUnsigned());
11958 if (!isContiguous()) {
11959 assert(Value.isUnsigned() && "discontiguous range for signed compare");
11960 if (Value.isMinValue()) return Min;
11961 if (Value.isMaxValue()) return Max;
11962 if (Value >= PromotedMin) return InRange;
11963 if (Value <= PromotedMax) return InRange;
11964 return InHole;
11965 }
11966
11967 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11968 case -1: return Less;
11969 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11970 case 1:
11971 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11972 case -1: return InRange;
11973 case 0: return Max;
11974 case 1: return Greater;
11975 }
11976 }
11977
11978 llvm_unreachable("impossible compare result");
11979 }
11980
11981 static std::optional<StringRef>
11982 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11983 if (Op == BO_Cmp) {
11984 ComparisonResult LTFlag = LT, GTFlag = GT;
11985 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11986
11987 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11988 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11989 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11990 return std::nullopt;
11991 }
11992
11993 ComparisonResult TrueFlag, FalseFlag;
11994 if (Op == BO_EQ) {
11995 TrueFlag = EQ;
11996 FalseFlag = NE;
11997 } else if (Op == BO_NE) {
11998 TrueFlag = NE;
11999 FalseFlag = EQ;
12000 } else {
12001 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12002 TrueFlag = LT;
12003 FalseFlag = GE;
12004 } else {
12005 TrueFlag = GT;
12006 FalseFlag = LE;
12007 }
12008 if (Op == BO_GE || Op == BO_LE)
12009 std::swap(TrueFlag, FalseFlag);
12010 }
12011 if (R & TrueFlag)
12012 return StringRef("true");
12013 if (R & FalseFlag)
12014 return StringRef("false");
12015 return std::nullopt;
12016 }
12017};
12018}
12019
12020static bool HasEnumType(const Expr *E) {
12021 // Strip off implicit integral promotions.
12022 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12023 if (ICE->getCastKind() != CK_IntegralCast &&
12024 ICE->getCastKind() != CK_NoOp)
12025 break;
12026 E = ICE->getSubExpr();
12027 }
12028
12029 return E->getType()->isEnumeralType();
12030}
12031
12032static int classifyConstantValue(Expr *Constant) {
12033 // The values of this enumeration are used in the diagnostics
12034 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12035 enum ConstantValueKind {
12036 Miscellaneous = 0,
12037 LiteralTrue,
12038 LiteralFalse
12039 };
12040 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12041 return BL->getValue() ? ConstantValueKind::LiteralTrue
12042 : ConstantValueKind::LiteralFalse;
12043 return ConstantValueKind::Miscellaneous;
12044}
12045
12047 Expr *Constant, Expr *Other,
12048 const llvm::APSInt &Value,
12049 bool RhsConstant) {
12051 return false;
12052
12053 Expr *OriginalOther = Other;
12054
12055 Constant = Constant->IgnoreParenImpCasts();
12056 Other = Other->IgnoreParenImpCasts();
12057
12058 // Suppress warnings on tautological comparisons between values of the same
12059 // enumeration type. There are only two ways we could warn on this:
12060 // - If the constant is outside the range of representable values of
12061 // the enumeration. In such a case, we should warn about the cast
12062 // to enumeration type, not about the comparison.
12063 // - If the constant is the maximum / minimum in-range value. For an
12064 // enumeratin type, such comparisons can be meaningful and useful.
12065 if (Constant->getType()->isEnumeralType() &&
12066 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12067 return false;
12068
12069 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12070 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
12071 if (!OtherValueRange)
12072 return false;
12073
12074 QualType OtherT = Other->getType();
12075 if (const auto *AT = OtherT->getAs<AtomicType>())
12076 OtherT = AT->getValueType();
12077 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12078
12079 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12080 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12081 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12082 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
12083 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12084
12085 // Whether we're treating Other as being a bool because of the form of
12086 // expression despite it having another type (typically 'int' in C).
12087 bool OtherIsBooleanDespiteType =
12088 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12089 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12090 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12091
12092 // Check if all values in the range of possible values of this expression
12093 // lead to the same comparison outcome.
12094 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12095 Value.isUnsigned());
12096 auto Cmp = OtherPromotedValueRange.compare(Value);
12097 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12098 if (!Result)
12099 return false;
12100
12101 // Also consider the range determined by the type alone. This allows us to
12102 // classify the warning under the proper diagnostic group.
12103 bool TautologicalTypeCompare = false;
12104 {
12105 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12106 Value.isUnsigned());
12107 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12108 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12109 RhsConstant)) {
12110 TautologicalTypeCompare = true;
12111 Cmp = TypeCmp;
12112 Result = TypeResult;
12113 }
12114 }
12115
12116 // Don't warn if the non-constant operand actually always evaluates to the
12117 // same value.
12118 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12119 return false;
12120
12121 // Suppress the diagnostic for an in-range comparison if the constant comes
12122 // from a macro or enumerator. We don't want to diagnose
12123 //
12124 // some_long_value <= INT_MAX
12125 //
12126 // when sizeof(int) == sizeof(long).
12127 bool InRange = Cmp & PromotedRange::InRangeFlag;
12128 if (InRange && IsEnumConstOrFromMacro(S, Constant))
12129 return false;
12130
12131 // A comparison of an unsigned bit-field against 0 is really a type problem,
12132 // even though at the type level the bit-field might promote to 'signed int'.
12133 if (Other->refersToBitField() && InRange && Value == 0 &&
12134 Other->getType()->isUnsignedIntegerOrEnumerationType())
12135 TautologicalTypeCompare = true;
12136
12137 // If this is a comparison to an enum constant, include that
12138 // constant in the diagnostic.
12139 const EnumConstantDecl *ED = nullptr;
12140 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
12141 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12142
12143 // Should be enough for uint128 (39 decimal digits)
12144 SmallString<64> PrettySourceValue;
12145 llvm::raw_svector_ostream OS(PrettySourceValue);
12146 if (ED) {
12147 OS << '\'' << *ED << "' (" << Value << ")";
12148 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12149 Constant->IgnoreParenImpCasts())) {
12150 OS << (BL->getValue() ? "YES" : "NO");
12151 } else {
12152 OS << Value;
12153 }
12154
12155 if (!TautologicalTypeCompare) {
12156 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12157 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12158 << E->getOpcodeStr() << OS.str() << *Result
12159 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12160 return true;
12161 }
12162
12163 if (IsObjCSignedCharBool) {
12165 S.PDiag(diag::warn_tautological_compare_objc_bool)
12166 << OS.str() << *Result);
12167 return true;
12168 }
12169
12170 // FIXME: We use a somewhat different formatting for the in-range cases and
12171 // cases involving boolean values for historical reasons. We should pick a
12172 // consistent way of presenting these diagnostics.
12173 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12174
12176 E->getOperatorLoc(), E,
12177 S.PDiag(!InRange ? diag::warn_out_of_range_compare
12178 : diag::warn_tautological_bool_compare)
12179 << OS.str() << classifyConstantValue(Constant) << OtherT
12180 << OtherIsBooleanDespiteType << *Result
12181 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12182 } else {
12183 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12184 unsigned Diag =
12185 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12186 ? (HasEnumType(OriginalOther)
12187 ? diag::warn_unsigned_enum_always_true_comparison
12188 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12189 : diag::warn_unsigned_always_true_comparison)
12190 : diag::warn_tautological_constant_compare;
12191
12192 S.Diag(E->getOperatorLoc(), Diag)
12193 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12194 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12195 }
12196
12197 return true;
12198}
12199
12200/// Analyze the operands of the given comparison. Implements the
12201/// fallback case from AnalyzeComparison.
12206
12207/// Implements -Wsign-compare.
12208///
12209/// \param E the binary operator to check for warnings
12211 // The type the comparison is being performed in.
12212 QualType T = E->getLHS()->getType();
12213
12214 // Only analyze comparison operators where both sides have been converted to
12215 // the same type.
12216 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12217 return AnalyzeImpConvsInComparison(S, E);
12218
12219 // Don't analyze value-dependent comparisons directly.
12220 if (E->isValueDependent())
12221 return AnalyzeImpConvsInComparison(S, E);
12222
12223 Expr *LHS = E->getLHS();
12224 Expr *RHS = E->getRHS();
12225
12226 if (T->isIntegralType(S.Context)) {
12227 std::optional<llvm::APSInt> RHSValue =
12229 std::optional<llvm::APSInt> LHSValue =
12231
12232 // We don't care about expressions whose result is a constant.
12233 if (RHSValue && LHSValue)
12234 return AnalyzeImpConvsInComparison(S, E);
12235
12236 // We only care about expressions where just one side is literal
12237 if ((bool)RHSValue ^ (bool)LHSValue) {
12238 // Is the constant on the RHS or LHS?
12239 const bool RhsConstant = (bool)RHSValue;
12240 Expr *Const = RhsConstant ? RHS : LHS;
12241 Expr *Other = RhsConstant ? LHS : RHS;
12242 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12243
12244 // Check whether an integer constant comparison results in a value
12245 // of 'true' or 'false'.
12246 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12247 return AnalyzeImpConvsInComparison(S, E);
12248 }
12249 }
12250
12251 if (!T->hasUnsignedIntegerRepresentation()) {
12252 // We don't do anything special if this isn't an unsigned integral
12253 // comparison: we're only interested in integral comparisons, and
12254 // signed comparisons only happen in cases we don't care to warn about.
12255 return AnalyzeImpConvsInComparison(S, E);
12256 }
12257
12258 LHS = LHS->IgnoreParenImpCasts();
12259 RHS = RHS->IgnoreParenImpCasts();
12260
12261 if (!S.getLangOpts().CPlusPlus) {
12262 // Avoid warning about comparison of integers with different signs when
12263 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12264 // the type of `E`.
12265 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12266 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12267 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12268 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12269 }
12270
12271 // Check to see if one of the (unmodified) operands is of different
12272 // signedness.
12273 Expr *signedOperand, *unsignedOperand;
12275 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12276 "unsigned comparison between two signed integer expressions?");
12277 signedOperand = LHS;
12278 unsignedOperand = RHS;
12279 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12280 signedOperand = RHS;
12281 unsignedOperand = LHS;
12282 } else {
12283 return AnalyzeImpConvsInComparison(S, E);
12284 }
12285
12286 // Otherwise, calculate the effective range of the signed operand.
12287 std::optional<IntRange> signedRange =
12289 /*Approximate=*/true);
12290 if (!signedRange)
12291 return;
12292
12293 // Go ahead and analyze implicit conversions in the operands. Note
12294 // that we skip the implicit conversions on both sides.
12297
12298 // If the signed range is non-negative, -Wsign-compare won't fire.
12299 if (signedRange->NonNegative)
12300 return;
12301
12302 // For (in)equality comparisons, if the unsigned operand is a
12303 // constant which cannot collide with a overflowed signed operand,
12304 // then reinterpreting the signed operand as unsigned will not
12305 // change the result of the comparison.
12306 if (E->isEqualityOp()) {
12307 unsigned comparisonWidth = S.Context.getIntWidth(T);
12308 std::optional<IntRange> unsignedRange = TryGetExprRange(
12309 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
12310 /*Approximate=*/true);
12311 if (!unsignedRange)
12312 return;
12313
12314 // We should never be unable to prove that the unsigned operand is
12315 // non-negative.
12316 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12317
12318 if (unsignedRange->Width < comparisonWidth)
12319 return;
12320 }
12321
12323 S.PDiag(diag::warn_mixed_sign_comparison)
12324 << LHS->getType() << RHS->getType()
12325 << LHS->getSourceRange() << RHS->getSourceRange());
12326}
12327
12328/// Analyzes an attempt to assign the given value to a bitfield.
12329///
12330/// Returns true if there was something fishy about the attempt.
12332 SourceLocation InitLoc) {
12333 assert(Bitfield->isBitField());
12334 if (Bitfield->isInvalidDecl())
12335 return false;
12336
12337 // White-list bool bitfields.
12338 QualType BitfieldType = Bitfield->getType();
12339 if (BitfieldType->isBooleanType())
12340 return false;
12341
12342 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12343 // If the underlying enum type was not explicitly specified as an unsigned
12344 // type and the enum contain only positive values, MSVC++ will cause an
12345 // inconsistency by storing this as a signed type.
12346 if (S.getLangOpts().CPlusPlus11 &&
12347 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12348 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12349 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12350 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12351 << BitfieldEnumDecl;
12352 }
12353 }
12354
12355 // Ignore value- or type-dependent expressions.
12356 if (Bitfield->getBitWidth()->isValueDependent() ||
12357 Bitfield->getBitWidth()->isTypeDependent() ||
12358 Init->isValueDependent() ||
12359 Init->isTypeDependent())
12360 return false;
12361
12362 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12363 unsigned FieldWidth = Bitfield->getBitWidthValue();
12364
12365 Expr::EvalResult Result;
12366 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12368 // The RHS is not constant. If the RHS has an enum type, make sure the
12369 // bitfield is wide enough to hold all the values of the enum without
12370 // truncation.
12371 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12372 const PreferredTypeAttr *PTAttr = nullptr;
12373 if (!ED) {
12374 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12375 if (PTAttr)
12376 ED = PTAttr->getType()->getAsEnumDecl();
12377 }
12378 if (ED) {
12379 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12380
12381 // Enum types are implicitly signed on Windows, so check if there are any
12382 // negative enumerators to see if the enum was intended to be signed or
12383 // not.
12384 bool SignedEnum = ED->getNumNegativeBits() > 0;
12385
12386 // Check for surprising sign changes when assigning enum values to a
12387 // bitfield of different signedness. If the bitfield is signed and we
12388 // have exactly the right number of bits to store this unsigned enum,
12389 // suggest changing the enum to an unsigned type. This typically happens
12390 // on Windows where unfixed enums always use an underlying type of 'int'.
12391 unsigned DiagID = 0;
12392 if (SignedEnum && !SignedBitfield) {
12393 DiagID =
12394 PTAttr == nullptr
12395 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12396 : diag::
12397 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12398 } else if (SignedBitfield && !SignedEnum &&
12399 ED->getNumPositiveBits() == FieldWidth) {
12400 DiagID =
12401 PTAttr == nullptr
12402 ? diag::warn_signed_bitfield_enum_conversion
12403 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12404 }
12405 if (DiagID) {
12406 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12407 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12408 SourceRange TypeRange =
12409 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12410 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12411 << SignedEnum << TypeRange;
12412 if (PTAttr)
12413 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12414 << ED;
12415 }
12416
12417 // Compute the required bitwidth. If the enum has negative values, we need
12418 // one more bit than the normal number of positive bits to represent the
12419 // sign bit.
12420 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12421 ED->getNumNegativeBits())
12422 : ED->getNumPositiveBits();
12423
12424 // Check the bitwidth.
12425 if (BitsNeeded > FieldWidth) {
12426 Expr *WidthExpr = Bitfield->getBitWidth();
12427 auto DiagID =
12428 PTAttr == nullptr
12429 ? diag::warn_bitfield_too_small_for_enum
12430 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12431 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12432 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12433 << BitsNeeded << ED << WidthExpr->getSourceRange();
12434 if (PTAttr)
12435 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12436 << ED;
12437 }
12438 }
12439
12440 return false;
12441 }
12442
12443 llvm::APSInt Value = Result.Val.getInt();
12444
12445 unsigned OriginalWidth = Value.getBitWidth();
12446
12447 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12448 // false positives where the user is demonstrating they intend to use the
12449 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12450 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12451 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12452 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12453 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12454 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
12455 S.findMacroSpelling(MaybeMacroLoc, "true"))
12456 return false;
12457 }
12458
12459 if (!Value.isSigned() || Value.isNegative())
12460 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12461 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12462 OriginalWidth = Value.getSignificantBits();
12463
12464 if (OriginalWidth <= FieldWidth)
12465 return false;
12466
12467 // Compute the value which the bitfield will contain.
12468 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12469 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12470
12471 // Check whether the stored value is equal to the original value.
12472 TruncatedValue = TruncatedValue.extend(OriginalWidth);
12473 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12474 return false;
12475
12476 std::string PrettyValue = toString(Value, 10);
12477 std::string PrettyTrunc = toString(TruncatedValue, 10);
12478
12479 S.Diag(InitLoc, OneAssignedToOneBitBitfield
12480 ? diag::warn_impcast_single_bit_bitield_precision_constant
12481 : diag::warn_impcast_bitfield_precision_constant)
12482 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12483 << Init->getSourceRange();
12484
12485 return true;
12486}
12487
12488/// Analyze the given simple or compound assignment for warning-worthy
12489/// operations.
12491 // Just recurse on the LHS.
12493
12494 // We want to recurse on the RHS as normal unless we're assigning to
12495 // a bitfield.
12496 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12497 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12498 E->getOperatorLoc())) {
12499 // Recurse, ignoring any implicit conversions on the RHS.
12501 E->getOperatorLoc());
12502 }
12503 }
12504
12505 // Set context flag for overflow behavior type assignment analysis, use RAII
12506 // pattern to handle nested assignments.
12507 llvm::SaveAndRestore OBTAssignmentContext(
12509
12511
12512 // Diagnose implicitly sequentially-consistent atomic assignment.
12513 if (E->getLHS()->getType()->isAtomicType())
12514 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12515}
12516
12517/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12518static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12519 QualType T, SourceLocation CContext, unsigned diag,
12520 bool PruneControlFlow = false) {
12521 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12522 // address space annotations isn't really useful. The warnings aren't because
12523 // you're converting a `private int` to `unsigned int`, it is because you're
12524 // conerting `int` to `unsigned int`.
12525 if (SourceType.hasAddressSpace())
12526 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
12527 if (T.hasAddressSpace())
12529 if (PruneControlFlow) {
12531 S.PDiag(diag)
12532 << SourceType << T << E->getSourceRange()
12533 << SourceRange(CContext));
12534 return;
12535 }
12536 S.Diag(E->getExprLoc(), diag)
12537 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12538}
12539
12540/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12541static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
12542 SourceLocation CContext, unsigned diag,
12543 bool PruneControlFlow = false) {
12544 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
12545}
12546
12547/// Diagnose an implicit cast from a floating point value to an integer value.
12548static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
12549 SourceLocation CContext) {
12550 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12551 bool PruneWarnings = S.inTemplateInstantiation();
12552
12553 const Expr *InnerE = E->IgnoreParenImpCasts();
12554 // We also want to warn on, e.g., "int i = -1.234"
12555 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
12556 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12557 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12558
12559 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12560
12561 llvm::APFloat Value(0.0);
12562 bool IsConstant =
12564 if (!IsConstant) {
12565 if (S.ObjC().isSignedCharBool(T)) {
12567 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12568 << E->getType());
12569 }
12570
12571 return DiagnoseImpCast(S, E, T, CContext,
12572 diag::warn_impcast_float_integer, PruneWarnings);
12573 }
12574
12575 bool isExact = false;
12576
12577 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12578 T->hasUnsignedIntegerRepresentation());
12579 llvm::APFloat::opStatus Result = Value.convertToInteger(
12580 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12581
12582 // FIXME: Force the precision of the source value down so we don't print
12583 // digits which are usually useless (we don't really care here if we
12584 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12585 // would automatically print the shortest representation, but it's a bit
12586 // tricky to implement.
12587 SmallString<16> PrettySourceValue;
12588 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12589 precision = (precision * 59 + 195) / 196;
12590 Value.toString(PrettySourceValue, precision);
12591
12592 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
12594 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12595 << PrettySourceValue);
12596 }
12597
12598 if (Result == llvm::APFloat::opOK && isExact) {
12599 if (IsLiteral) return;
12600 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12601 PruneWarnings);
12602 }
12603
12604 // Conversion of a floating-point value to a non-bool integer where the
12605 // integral part cannot be represented by the integer type is undefined.
12606 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12607 return DiagnoseImpCast(
12608 S, E, T, CContext,
12609 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12610 : diag::warn_impcast_float_to_integer_out_of_range,
12611 PruneWarnings);
12612
12613 unsigned DiagID = 0;
12614 if (IsLiteral) {
12615 // Warn on floating point literal to integer.
12616 DiagID = diag::warn_impcast_literal_float_to_integer;
12617 } else if (IntegerValue == 0) {
12618 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
12619 return DiagnoseImpCast(S, E, T, CContext,
12620 diag::warn_impcast_float_integer, PruneWarnings);
12621 }
12622 // Warn on non-zero to zero conversion.
12623 DiagID = diag::warn_impcast_float_to_integer_zero;
12624 } else {
12625 if (IntegerValue.isUnsigned()) {
12626 if (!IntegerValue.isMaxValue()) {
12627 return DiagnoseImpCast(S, E, T, CContext,
12628 diag::warn_impcast_float_integer, PruneWarnings);
12629 }
12630 } else { // IntegerValue.isSigned()
12631 if (!IntegerValue.isMaxSignedValue() &&
12632 !IntegerValue.isMinSignedValue()) {
12633 return DiagnoseImpCast(S, E, T, CContext,
12634 diag::warn_impcast_float_integer, PruneWarnings);
12635 }
12636 }
12637 // Warn on evaluatable floating point expression to integer conversion.
12638 DiagID = diag::warn_impcast_float_to_integer;
12639 }
12640
12641 SmallString<16> PrettyTargetValue;
12642 if (IsBool)
12643 PrettyTargetValue = Value.isZero() ? "false" : "true";
12644 else
12645 IntegerValue.toString(PrettyTargetValue);
12646
12647 if (PruneWarnings) {
12649 S.PDiag(DiagID)
12650 << E->getType() << T.getUnqualifiedType()
12651 << PrettySourceValue << PrettyTargetValue
12652 << E->getSourceRange() << SourceRange(CContext));
12653 } else {
12654 S.Diag(E->getExprLoc(), DiagID)
12655 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12656 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12657 }
12658}
12659
12660/// Analyze the given compound assignment for the possible losing of
12661/// floating-point precision.
12663 assert(isa<CompoundAssignOperator>(E) &&
12664 "Must be compound assignment operation");
12665 // Recurse on the LHS and RHS in here
12668
12669 if (E->getLHS()->getType()->isAtomicType())
12670 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12671
12672 // Now check the outermost expression
12673 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12674 const auto *RBT = cast<CompoundAssignOperator>(E)
12675 ->getComputationResultType()
12676 ->getAs<BuiltinType>();
12677
12678 // The below checks assume source is floating point.
12679 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12680
12681 // If source is floating point but target is an integer.
12682 if (ResultBT->isInteger())
12683 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12684 E->getExprLoc(), diag::warn_impcast_float_integer);
12685
12686 if (!ResultBT->isFloatingPoint())
12687 return;
12688
12689 // If both source and target are floating points, warn about losing precision.
12691 QualType(ResultBT, 0), QualType(RBT, 0));
12692 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12693 // warn about dropping FP rank.
12694 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12695 diag::warn_impcast_float_result_precision);
12696}
12697
12698static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12699 IntRange Range) {
12700 if (!Range.Width) return "0";
12701
12702 llvm::APSInt ValueInRange = Value;
12703 ValueInRange.setIsSigned(!Range.NonNegative);
12704 ValueInRange = ValueInRange.trunc(Range.Width);
12705 return toString(ValueInRange, 10);
12706}
12707
12708static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
12709 bool ToBool) {
12710 if (!isa<ImplicitCastExpr>(Ex))
12711 return false;
12712
12713 const Expr *InnerE = Ex->IgnoreParenImpCasts();
12715 const Type *Source =
12717 if (Target->isDependentType())
12718 return false;
12719
12720 const auto *FloatCandidateBT =
12721 dyn_cast<BuiltinType>(ToBool ? Source : Target);
12722 const Type *BoolCandidateType = ToBool ? Target : Source;
12723
12724 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12725 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12726}
12727
12728static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
12729 SourceLocation CC) {
12730 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
12731 const Expr *CurrA = TheCall->getArg(I);
12732 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12733 continue;
12734
12735 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
12736 S, TheCall->getArg(I - 1), false));
12737 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
12738 S, TheCall->getArg(I + 1), false));
12739 if (IsSwapped) {
12740 // Warn on this floating-point to bool conversion.
12742 CurrA->getType(), CC,
12743 diag::warn_impcast_floating_point_to_bool);
12744 }
12745 }
12746}
12747
12749 SourceLocation CC) {
12750 // Don't warn on functions which have return type nullptr_t.
12751 if (isa<CallExpr>(E))
12752 return;
12753
12754 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12755 const Expr *NewE = E->IgnoreParenImpCasts();
12756 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
12757 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12758 if (!IsGNUNullExpr && !HasNullPtrType)
12759 return;
12760
12761 // Return if target type is a safe conversion.
12762 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12763 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12764 return;
12765
12766 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12767 E->getExprLoc()))
12768 return;
12769
12771
12772 // Venture through the macro stacks to get to the source of macro arguments.
12773 // The new location is a better location than the complete location that was
12774 // passed in.
12775 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12777
12778 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12779 if (IsGNUNullExpr && Loc.isMacroID()) {
12780 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12781 Loc, S.SourceMgr, S.getLangOpts());
12782 if (MacroName == "NULL")
12784 }
12785
12786 // Only warn if the null and context location are in the same macro expansion.
12787 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12788 return;
12789
12790 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12791 << HasNullPtrType << T << SourceRange(CC)
12793 S.getFixItZeroLiteralForType(T, Loc));
12794}
12795
12796// Helper function to filter out cases for constant width constant conversion.
12797// Don't warn on char array initialization or for non-decimal values.
12799 SourceLocation CC) {
12800 // If initializing from a constant, and the constant starts with '0',
12801 // then it is a binary, octal, or hexadecimal. Allow these constants
12802 // to fill all the bits, even if there is a sign change.
12803 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12804 const char FirstLiteralCharacter =
12805 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12806 if (FirstLiteralCharacter == '0')
12807 return false;
12808 }
12809
12810 // If the CC location points to a '{', and the type is char, then assume
12811 // assume it is an array initialization.
12812 if (CC.isValid() && T->isCharType()) {
12813 const char FirstContextCharacter =
12815 if (FirstContextCharacter == '{')
12816 return false;
12817 }
12818
12819 return true;
12820}
12821
12823 const auto *IL = dyn_cast<IntegerLiteral>(E);
12824 if (!IL) {
12825 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12826 if (UO->getOpcode() == UO_Minus)
12827 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12828 }
12829 }
12830
12831 return IL;
12832}
12833
12835 E = E->IgnoreParenImpCasts();
12836 SourceLocation ExprLoc = E->getExprLoc();
12837
12838 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12839 BinaryOperator::Opcode Opc = BO->getOpcode();
12840 Expr::EvalResult Result;
12841 // Do not diagnose unsigned shifts.
12842 if (Opc == BO_Shl) {
12843 const auto *LHS = getIntegerLiteral(BO->getLHS());
12844 const auto *RHS = getIntegerLiteral(BO->getRHS());
12845 if (LHS && LHS->getValue() == 0)
12846 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12847 else if (!E->isValueDependent() && LHS && RHS &&
12848 RHS->getValue().isNonNegative() &&
12850 S.Diag(ExprLoc, diag::warn_left_shift_always)
12851 << (Result.Val.getInt() != 0);
12852 else if (E->getType()->isSignedIntegerType())
12853 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
12856 ") != 0");
12857 }
12858 }
12859
12860 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12861 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12862 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12863 if (!LHS || !RHS)
12864 return;
12865 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12866 (RHS->getValue() == 0 || RHS->getValue() == 1))
12867 // Do not diagnose common idioms.
12868 return;
12869 if (LHS->getValue() != 0 && RHS->getValue() != 0)
12870 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12871 }
12872}
12873
12875 const Type *Target, Expr *E,
12876 QualType T,
12877 SourceLocation CC) {
12878 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
12879 Source != Target);
12880
12881 // Lone surrogates have a distinct representation in UTF-32.
12882 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
12883 // so don't warn on such conversion.
12884 if (Source->isChar16Type() && Target->isChar32Type())
12885 return;
12886
12887 Expr::EvalResult Result;
12890 llvm::APSInt Value(32);
12891 Value = Result.Val.getInt();
12892 bool IsASCII = Value <= 0x7F;
12893 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
12894 bool ConversionPreservesSemantics =
12895 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
12896
12897 if (!ConversionPreservesSemantics) {
12898 auto IsSingleCodeUnitCP = [](const QualType &T,
12899 const llvm::APSInt &Value) {
12900 if (T->isChar8Type())
12901 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
12902 if (T->isChar16Type())
12903 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
12904 assert(T->isChar32Type());
12905 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
12906 };
12907
12908 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
12909 << E->getType() << T
12910 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
12911 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
12912 }
12913 } else {
12914 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
12916 DiagnoseImpCast(S, E, T, CC,
12917 LosesPrecision ? diag::warn_impcast_unicode_precision
12918 : diag::warn_impcast_unicode_char_type);
12919 }
12920}
12921
12923 From = Context.getCanonicalType(From);
12924 To = Context.getCanonicalType(To);
12925 QualType MaybePointee = From->getPointeeType();
12926 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12927 From = MaybePointee;
12928 MaybePointee = To->getPointeeType();
12929 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12930 To = MaybePointee;
12931
12932 if (const auto *FromFn = From->getAs<FunctionType>()) {
12933 if (const auto *ToFn = To->getAs<FunctionType>()) {
12934 if (FromFn->getCFIUncheckedCalleeAttr() &&
12935 !ToFn->getCFIUncheckedCalleeAttr())
12936 return true;
12937 }
12938 }
12939 return false;
12940}
12941
12943 bool *ICContext, bool IsListInit) {
12944 if (E->isTypeDependent() || E->isValueDependent()) return;
12945
12946 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
12947 const Type *Target = Context.getCanonicalType(T).getTypePtr();
12948 if (Source == Target) return;
12949 if (Target->isDependentType()) return;
12950
12951 // If the conversion context location is invalid don't complain. We also
12952 // don't want to emit a warning if the issue occurs from the expansion of
12953 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12954 // delay this check as long as possible. Once we detect we are in that
12955 // scenario, we just return.
12956 if (CC.isInvalid())
12957 return;
12958
12959 if (Source->isAtomicType())
12960 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12961
12962 // Diagnose implicit casts to bool.
12963 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12964 if (isa<StringLiteral>(E))
12965 // Warn on string literal to bool. Checks for string literals in logical
12966 // and expressions, for instance, assert(0 && "error here"), are
12967 // prevented by a check in AnalyzeImplicitConversions().
12968 return DiagnoseImpCast(*this, E, T, CC,
12969 diag::warn_impcast_string_literal_to_bool);
12972 // This covers the literal expressions that evaluate to Objective-C
12973 // objects.
12974 return DiagnoseImpCast(*this, E, T, CC,
12975 diag::warn_impcast_objective_c_literal_to_bool);
12976 }
12977 if (Source->isPointerType() || Source->canDecayToPointerType()) {
12978 // Warn on pointer to bool conversion that is always true.
12980 SourceRange(CC));
12981 }
12982 }
12983
12985
12986 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12987 // is a typedef for signed char (macOS), then that constant value has to be 1
12988 // or 0.
12989 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
12992 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12994 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12995 << toString(Result.Val.getInt(), 10));
12996 }
12997 return;
12998 }
12999 }
13000
13001 // Check implicit casts from Objective-C collection literals to specialized
13002 // collection types, e.g., NSArray<NSString *> *.
13003 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13004 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
13005 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13006 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
13007
13008 // Strip vector types.
13009 if (isa<VectorType>(Source)) {
13010 if (Target->isSveVLSBuiltinType() &&
13011 (ARM().areCompatibleSveTypes(QualType(Target, 0),
13012 QualType(Source, 0)) ||
13013 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
13014 QualType(Source, 0))))
13015 return;
13016
13017 if (Target->isRVVVLSBuiltinType() &&
13018 (Context.areCompatibleRVVTypes(QualType(Target, 0),
13019 QualType(Source, 0)) ||
13020 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
13021 QualType(Source, 0))))
13022 return;
13023
13024 if (!isa<VectorType>(Target)) {
13025 if (SourceMgr.isInSystemMacro(CC))
13026 return;
13027 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
13028 }
13029 if (getLangOpts().HLSL &&
13030 Target->castAs<VectorType>()->getNumElements() <
13031 Source->castAs<VectorType>()->getNumElements()) {
13032 // Diagnose vector truncation but don't return. We may also want to
13033 // diagnose an element conversion.
13034 DiagnoseImpCast(*this, E, T, CC,
13035 diag::warn_hlsl_impcast_vector_truncation);
13036 }
13037
13038 // If the vector cast is cast between two vectors of the same size, it is
13039 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13040 if (!getLangOpts().HLSL &&
13041 Context.getTypeSize(Source) == Context.getTypeSize(Target))
13042 return;
13043
13044 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13045 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13046 }
13047 if (const auto *VecTy = dyn_cast<VectorType>(Target))
13048 Target = VecTy->getElementType().getTypePtr();
13049
13050 // Strip matrix types.
13051 if (isa<ConstantMatrixType>(Source)) {
13052 if (Target->isScalarType())
13053 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_matrix_scalar);
13054
13057 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13058 // Diagnose Matrix truncation but don't return. We may also want to
13059 // diagnose an element conversion.
13060 DiagnoseImpCast(*this, E, T, CC,
13061 diag::warn_hlsl_impcast_matrix_truncation);
13062 }
13063
13064 Source = cast<ConstantMatrixType>(Source)->getElementType().getTypePtr();
13065 Target = cast<ConstantMatrixType>(Target)->getElementType().getTypePtr();
13066 }
13067 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Target))
13068 Target = MatTy->getElementType().getTypePtr();
13069
13070 // Strip complex types.
13071 if (isa<ComplexType>(Source)) {
13072 if (!isa<ComplexType>(Target)) {
13073 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13074 return;
13075
13076 return DiagnoseImpCast(*this, E, T, CC,
13078 ? diag::err_impcast_complex_scalar
13079 : diag::warn_impcast_complex_scalar);
13080 }
13081
13082 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13083 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13084 }
13085
13086 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13087 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13088
13089 // Strip SVE vector types
13090 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13091 // Need the original target type for vector type checks
13092 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13093 // Handle conversion from scalable to fixed when msve-vector-bits is
13094 // specified
13095 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
13096 QualType(Source, 0)) ||
13097 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
13098 QualType(Source, 0)))
13099 return;
13100
13101 // If the vector cast is cast between two vectors of the same size, it is
13102 // a bitcast, not a conversion.
13103 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
13104 return;
13105
13106 Source = SourceBT->getSveEltType(Context).getTypePtr();
13107 }
13108
13109 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13110 Target = TargetBT->getSveEltType(Context).getTypePtr();
13111
13112 // If the source is floating point...
13113 if (SourceBT && SourceBT->isFloatingPoint()) {
13114 // ...and the target is floating point...
13115 if (TargetBT && TargetBT->isFloatingPoint()) {
13116 // ...then warn if we're dropping FP rank.
13117
13119 QualType(SourceBT, 0), QualType(TargetBT, 0));
13120 if (Order > 0) {
13121 // Don't warn about float constants that are precisely
13122 // representable in the target type.
13123 Expr::EvalResult result;
13124 if (E->EvaluateAsRValue(result, Context)) {
13125 // Value might be a float, a float vector, or a float complex.
13127 result.Val,
13128 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13129 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13130 return;
13131 }
13132
13133 if (SourceMgr.isInSystemMacro(CC))
13134 return;
13135
13136 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
13137 }
13138 // ... or possibly if we're increasing rank, too
13139 else if (Order < 0) {
13140 if (SourceMgr.isInSystemMacro(CC))
13141 return;
13142
13143 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
13144 }
13145 return;
13146 }
13147
13148 // If the target is integral, always warn.
13149 if (TargetBT && TargetBT->isInteger()) {
13150 if (SourceMgr.isInSystemMacro(CC))
13151 return;
13152
13153 DiagnoseFloatingImpCast(*this, E, T, CC);
13154 }
13155
13156 // Detect the case where a call result is converted from floating-point to
13157 // to bool, and the final argument to the call is converted from bool, to
13158 // discover this typo:
13159 //
13160 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13161 //
13162 // FIXME: This is an incredibly special case; is there some more general
13163 // way to detect this class of misplaced-parentheses bug?
13164 if (Target->isBooleanType() && isa<CallExpr>(E)) {
13165 // Check last argument of function call to see if it is an
13166 // implicit cast from a type matching the type the result
13167 // is being cast to.
13168 CallExpr *CEx = cast<CallExpr>(E);
13169 if (unsigned NumArgs = CEx->getNumArgs()) {
13170 Expr *LastA = CEx->getArg(NumArgs - 1);
13171 Expr *InnerE = LastA->IgnoreParenImpCasts();
13172 if (isa<ImplicitCastExpr>(LastA) &&
13173 InnerE->getType()->isBooleanType()) {
13174 // Warn on this floating-point to bool conversion
13175 DiagnoseImpCast(*this, E, T, CC,
13176 diag::warn_impcast_floating_point_to_bool);
13177 }
13178 }
13179 }
13180 return;
13181 }
13182
13183 // Valid casts involving fixed point types should be accounted for here.
13184 if (Source->isFixedPointType()) {
13185 if (Target->isUnsaturatedFixedPointType()) {
13189 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13190 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
13191 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
13192 if (Value > MaxVal || Value < MinVal) {
13194 PDiag(diag::warn_impcast_fixed_point_range)
13195 << Value.toString() << T
13196 << E->getSourceRange()
13197 << clang::SourceRange(CC));
13198 return;
13199 }
13200 }
13201 } else if (Target->isIntegerType()) {
13205 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13206
13207 bool Overflowed;
13208 llvm::APSInt IntResult = FXResult.convertToInt(
13209 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
13210 &Overflowed);
13211
13212 if (Overflowed) {
13214 PDiag(diag::warn_impcast_fixed_point_range)
13215 << FXResult.toString() << T
13216 << E->getSourceRange()
13217 << clang::SourceRange(CC));
13218 return;
13219 }
13220 }
13221 }
13222 } else if (Target->isUnsaturatedFixedPointType()) {
13223 if (Source->isIntegerType()) {
13227 llvm::APSInt Value = Result.Val.getInt();
13228
13229 bool Overflowed;
13230 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13231 Value, Context.getFixedPointSemantics(T), &Overflowed);
13232
13233 if (Overflowed) {
13235 PDiag(diag::warn_impcast_fixed_point_range)
13236 << toString(Value, /*Radix=*/10) << T
13237 << E->getSourceRange()
13238 << clang::SourceRange(CC));
13239 return;
13240 }
13241 }
13242 }
13243 }
13244
13245 // If we are casting an integer type to a floating point type without
13246 // initialization-list syntax, we might lose accuracy if the floating
13247 // point type has a narrower significand than the integer type.
13248 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13249 TargetBT->isFloatingType() && !IsListInit) {
13250 // Determine the number of precision bits in the source integer type.
13251 std::optional<IntRange> SourceRange =
13253 /*Approximate=*/true);
13254 if (!SourceRange)
13255 return;
13256 unsigned int SourcePrecision = SourceRange->Width;
13257
13258 // Determine the number of precision bits in the
13259 // target floating point type.
13260 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13261 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13262
13263 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13264 SourcePrecision > TargetPrecision) {
13265
13266 if (std::optional<llvm::APSInt> SourceInt =
13268 // If the source integer is a constant, convert it to the target
13269 // floating point type. Issue a warning if the value changes
13270 // during the whole conversion.
13271 llvm::APFloat TargetFloatValue(
13272 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13273 llvm::APFloat::opStatus ConversionStatus =
13274 TargetFloatValue.convertFromAPInt(
13275 *SourceInt, SourceBT->isSignedInteger(),
13276 llvm::APFloat::rmNearestTiesToEven);
13277
13278 if (ConversionStatus != llvm::APFloat::opOK) {
13279 SmallString<32> PrettySourceValue;
13280 SourceInt->toString(PrettySourceValue, 10);
13281 SmallString<32> PrettyTargetValue;
13282 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13283
13285 E->getExprLoc(), E,
13286 PDiag(diag::warn_impcast_integer_float_precision_constant)
13287 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13288 << E->getSourceRange() << clang::SourceRange(CC));
13289 }
13290 } else {
13291 // Otherwise, the implicit conversion may lose precision.
13292 DiagnoseImpCast(*this, E, T, CC,
13293 diag::warn_impcast_integer_float_precision);
13294 }
13295 }
13296 }
13297
13298 DiagnoseNullConversion(*this, E, T, CC);
13299
13301
13302 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13303 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
13304 return;
13305 }
13306
13307 if (Target->isBooleanType())
13308 DiagnoseIntInBoolContext(*this, E);
13309
13311 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
13312 << QualType(Source, 0) << QualType(Target, 0);
13313 }
13314
13315 if (!Source->isIntegerType() || !Target->isIntegerType())
13316 return;
13317
13318 // TODO: remove this early return once the false positives for constant->bool
13319 // in templates, macros, etc, are reduced or removed.
13320 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13321 return;
13322
13323 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
13324 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13326 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13327 << E->getType());
13328 }
13329 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13330 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
13331 if (!LikelySourceRange)
13332 return;
13333
13334 IntRange SourceTypeRange =
13335 IntRange::forTargetOfCanonicalType(Context, Source);
13336 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
13337
13338 if (LikelySourceRange->Width > TargetRange.Width) {
13339 // Check if target is a wrapping OBT - if so, don't warn about constant
13340 // conversion as this type may be used intentionally with implicit
13341 // truncation, especially during assignments.
13342 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13343 if (TargetOBT->isWrapKind()) {
13344 return;
13345 }
13346 }
13347
13348 // Check if source expression has an explicit __ob_wrap cast because if so,
13349 // wrapping was explicitly requested and we shouldn't warn
13350 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
13351 if (SourceOBT->isWrapKind()) {
13352 return;
13353 }
13354 }
13355
13356 // If the source is a constant, use a default-on diagnostic.
13357 // TODO: this should happen for bitfield stores, too.
13361 llvm::APSInt Value(32);
13362 Value = Result.Val.getInt();
13363
13364 if (SourceMgr.isInSystemMacro(CC))
13365 return;
13366
13367 std::string PrettySourceValue = toString(Value, 10);
13368 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13369
13371 PDiag(diag::warn_impcast_integer_precision_constant)
13372 << PrettySourceValue << PrettyTargetValue
13373 << E->getType() << T << E->getSourceRange()
13374 << SourceRange(CC));
13375 return;
13376 }
13377
13378 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13379 if (SourceMgr.isInSystemMacro(CC))
13380 return;
13381
13382 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
13383 if (UO->getOpcode() == UO_Minus)
13384 return DiagnoseImpCast(
13385 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
13386 }
13387
13388 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
13389 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
13390 /* pruneControlFlow */ true);
13391 return DiagnoseImpCast(*this, E, T, CC,
13392 diag::warn_impcast_integer_precision);
13393 }
13394
13395 if (TargetRange.Width > SourceTypeRange.Width) {
13396 if (auto *UO = dyn_cast<UnaryOperator>(E))
13397 if (UO->getOpcode() == UO_Minus)
13398 if (Source->isUnsignedIntegerType()) {
13399 if (Target->isUnsignedIntegerType())
13400 return DiagnoseImpCast(*this, E, T, CC,
13401 diag::warn_impcast_high_order_zero_bits);
13402 if (Target->isSignedIntegerType())
13403 return DiagnoseImpCast(*this, E, T, CC,
13404 diag::warn_impcast_nonnegative_result);
13405 }
13406 }
13407
13408 if (TargetRange.Width == LikelySourceRange->Width &&
13409 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13410 Source->isSignedIntegerType()) {
13411 // Warn when doing a signed to signed conversion, warn if the positive
13412 // source value is exactly the width of the target type, which will
13413 // cause a negative value to be stored.
13414
13417 !SourceMgr.isInSystemMacro(CC)) {
13418 llvm::APSInt Value = Result.Val.getInt();
13419 if (isSameWidthConstantConversion(*this, E, T, CC)) {
13420 std::string PrettySourceValue = toString(Value, 10);
13421 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13422
13423 Diag(E->getExprLoc(),
13424 PDiag(diag::warn_impcast_integer_precision_constant)
13425 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13426 << E->getSourceRange() << SourceRange(CC));
13427 return;
13428 }
13429 }
13430
13431 // Fall through for non-constants to give a sign conversion warning.
13432 }
13433
13434 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
13435 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13436 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13437 LikelySourceRange->Width == TargetRange.Width))) {
13438 if (SourceMgr.isInSystemMacro(CC))
13439 return;
13440
13441 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13442 TargetBT->isInteger() &&
13443 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13444 return;
13445 }
13446
13447 unsigned DiagID = diag::warn_impcast_integer_sign;
13448
13449 // Traditionally, gcc has warned about this under -Wsign-compare.
13450 // We also want to warn about it in -Wconversion.
13451 // So if -Wconversion is off, use a completely identical diagnostic
13452 // in the sign-compare group.
13453 // The conditional-checking code will
13454 if (ICContext) {
13455 DiagID = diag::warn_impcast_integer_sign_conditional;
13456 *ICContext = true;
13457 }
13458
13459 DiagnoseImpCast(*this, E, T, CC, DiagID);
13460 }
13461
13462 // If we're implicitly converting from an integer into an enumeration, that
13463 // is valid in C but invalid in C++.
13464 QualType SourceType = E->getEnumCoercedType(Context);
13465 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13466 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
13467 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
13468
13469 // Diagnose conversions between different enumeration types.
13470 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13471 // type, to give us better diagnostics.
13472 Source = Context.getCanonicalType(SourceType).getTypePtr();
13473
13474 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13475 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13476 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13477 TargetEnum->getDecl()->hasNameForLinkage() &&
13478 SourceEnum != TargetEnum) {
13479 if (SourceMgr.isInSystemMacro(CC))
13480 return;
13481
13482 return DiagnoseImpCast(*this, E, SourceType, T, CC,
13483 diag::warn_impcast_different_enum_types);
13484 }
13485}
13486
13488 SourceLocation CC, QualType T);
13489
13491 SourceLocation CC, bool &ICContext) {
13492 E = E->IgnoreParenImpCasts();
13493 // Diagnose incomplete type for second or third operand in C.
13494 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13495 S.RequireCompleteExprType(E, diag::err_incomplete_type);
13496
13497 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13498 return CheckConditionalOperator(S, CO, CC, T);
13499
13501 if (E->getType() != T)
13502 return S.CheckImplicitConversion(E, T, CC, &ICContext);
13503}
13504
13506 SourceLocation CC, QualType T) {
13508
13509 Expr *TrueExpr = E->getTrueExpr();
13510 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13511 TrueExpr = BCO->getCommon();
13512
13513 bool Suspicious = false;
13514 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13515 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13516
13517 if (T->isBooleanType())
13519
13520 // If -Wconversion would have warned about either of the candidates
13521 // for a signedness conversion to the context type...
13522 if (!Suspicious) return;
13523
13524 // ...but it's currently ignored...
13525 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13526 return;
13527
13528 // ...then check whether it would have warned about either of the
13529 // candidates for a signedness conversion to the condition type.
13530 if (E->getType() == T) return;
13531
13532 Suspicious = false;
13533 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
13534 &Suspicious);
13535 if (!Suspicious)
13537 E->getType(), CC, &Suspicious);
13538}
13539
13540/// Check conversion of given expression to boolean.
13541/// Input argument E is a logical expression.
13543 // Run the bool-like conversion checks only for C since there bools are
13544 // still not used as the return type from "boolean" operators or as the input
13545 // type for conditional operators.
13546 if (S.getLangOpts().CPlusPlus)
13547 return;
13549 return;
13551}
13552
13553namespace {
13554struct AnalyzeImplicitConversionsWorkItem {
13555 Expr *E;
13556 SourceLocation CC;
13557 bool IsListInit;
13558};
13559}
13560
13562 Sema &S, Expr *E, QualType T, SourceLocation CC,
13563 bool ExtraCheckForImplicitConversion,
13565 E = E->IgnoreParenImpCasts();
13566 WorkList.push_back({E, CC, false});
13567
13568 if (ExtraCheckForImplicitConversion && E->getType() != T)
13569 S.CheckImplicitConversion(E, T, CC);
13570}
13571
13572/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13573/// that should be visited are added to WorkList.
13575 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13577 Expr *OrigE = Item.E;
13578 SourceLocation CC = Item.CC;
13579
13580 QualType T = OrigE->getType();
13581 Expr *E = OrigE->IgnoreParenImpCasts();
13582
13583 // Propagate whether we are in a C++ list initialization expression.
13584 // If so, we do not issue warnings for implicit int-float conversion
13585 // precision loss, because C++11 narrowing already handles it.
13586 //
13587 // HLSL's initialization lists are special, so they shouldn't observe the C++
13588 // behavior here.
13589 bool IsListInit =
13590 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
13591 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
13592
13593 if (E->isTypeDependent() || E->isValueDependent())
13594 return;
13595
13596 Expr *SourceExpr = E;
13597 // Examine, but don't traverse into the source expression of an
13598 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13599 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13600 // evaluate it in the context of checking the specific conversion to T though.
13601 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13602 if (auto *Src = OVE->getSourceExpr())
13603 SourceExpr = Src;
13604
13605 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13606 if (UO->getOpcode() == UO_Not &&
13607 UO->getSubExpr()->isKnownToHaveBooleanValue())
13608 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13609 << OrigE->getSourceRange() << T->isBooleanType()
13610 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13611
13612 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
13613 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13614 BO->getLHS()->isKnownToHaveBooleanValue() &&
13615 BO->getRHS()->isKnownToHaveBooleanValue() &&
13616 BO->getLHS()->HasSideEffects(S.Context) &&
13617 BO->getRHS()->HasSideEffects(S.Context)) {
13619 const LangOptions &LO = S.getLangOpts();
13620 SourceLocation BLoc = BO->getOperatorLoc();
13621 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
13622 StringRef SR = clang::Lexer::getSourceText(
13623 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
13624 // To reduce false positives, only issue the diagnostic if the operator
13625 // is explicitly spelled as a punctuator. This suppresses the diagnostic
13626 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
13627 // in C, along with other macro spellings the user might invent.
13628 if (SR.str() == "&" || SR.str() == "|") {
13629
13630 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13631 << (BO->getOpcode() == BO_And ? "&" : "|")
13632 << OrigE->getSourceRange()
13634 BO->getOperatorLoc(),
13635 (BO->getOpcode() == BO_And ? "&&" : "||"));
13636 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13637 }
13638 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
13639 /// Analyze the given comma operator. The basic idea behind the analysis
13640 /// is to analyze the left and right operands slightly differently. The
13641 /// left operand needs to check whether the operand itself has an implicit
13642 /// conversion, but not whether the left operand induces an implicit
13643 /// conversion for the entire comma expression itself. This is similar to
13644 /// how CheckConditionalOperand behaves; it's as-if the correct operand
13645 /// were directly used for the implicit conversion check.
13646 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
13647 /*ExtraCheckForImplicitConversion=*/false, WorkList);
13648 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
13649 /*ExtraCheckForImplicitConversion=*/true, WorkList);
13650 return;
13651 }
13652 }
13653
13654 // For conditional operators, we analyze the arguments as if they
13655 // were being fed directly into the output.
13656 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13657 CheckConditionalOperator(S, CO, CC, T);
13658 return;
13659 }
13660
13661 // Check implicit argument conversions for function calls.
13662 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
13664
13665 // Go ahead and check any implicit conversions we might have skipped.
13666 // The non-canonical typecheck is just an optimization;
13667 // CheckImplicitConversion will filter out dead implicit conversions.
13668 if (SourceExpr->getType() != T)
13669 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
13670
13671 // Now continue drilling into this expression.
13672
13673 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13674 // The bound subexpressions in a PseudoObjectExpr are not reachable
13675 // as transitive children.
13676 // FIXME: Use a more uniform representation for this.
13677 for (auto *SE : POE->semantics())
13678 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13679 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13680 }
13681
13682 // Skip past explicit casts.
13683 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13684 E = CE->getSubExpr();
13685 // In the special case of a C++ function-style cast with braces,
13686 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
13687 // initializer. This InitListExpr basically belongs to the cast itself, so
13688 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
13690 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
13691 if (InitListE->getNumInits() == 1) {
13692 E = InitListE->getInit(0);
13693 }
13694 }
13695 }
13696 E = E->IgnoreParenImpCasts();
13697 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13698 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13699 WorkList.push_back({E, CC, IsListInit});
13700 return;
13701 }
13702
13703 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
13704 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
13705 // The base expression is only used to initialize the parameter for
13706 // arguments to `inout` parameters, so we only traverse down the base
13707 // expression for `inout` cases.
13708 if (OutArgE->isInOut())
13709 WorkList.push_back(
13710 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
13711 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
13712 return;
13713 }
13714
13715 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13716 // Do a somewhat different check with comparison operators.
13717 if (BO->isComparisonOp())
13718 return AnalyzeComparison(S, BO);
13719
13720 // And with simple assignments.
13721 if (BO->getOpcode() == BO_Assign)
13722 return AnalyzeAssignment(S, BO);
13723 // And with compound assignments.
13724 if (BO->isAssignmentOp())
13725 return AnalyzeCompoundAssignment(S, BO);
13726 }
13727
13728 // These break the otherwise-useful invariant below. Fortunately,
13729 // we don't really need to recurse into them, because any internal
13730 // expressions should have been analyzed already when they were
13731 // built into statements.
13732 if (isa<StmtExpr>(E)) return;
13733
13734 // Don't descend into unevaluated contexts.
13735 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13736
13737 // Now just recurse over the expression's children.
13738 CC = E->getExprLoc();
13739 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13740 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13741 for (Stmt *SubStmt : E->children()) {
13742 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13743 if (!ChildExpr)
13744 continue;
13745
13746 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
13747 if (ChildExpr == CSE->getOperand())
13748 // Do not recurse over a CoroutineSuspendExpr's operand.
13749 // The operand is also a subexpression of getCommonExpr(), and
13750 // recursing into it directly would produce duplicate diagnostics.
13751 continue;
13752
13753 if (IsLogicalAndOperator &&
13755 // Ignore checking string literals that are in logical and operators.
13756 // This is a common pattern for asserts.
13757 continue;
13758 WorkList.push_back({ChildExpr, CC, IsListInit});
13759 }
13760
13761 if (BO && BO->isLogicalOp()) {
13762 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13763 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13764 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13765
13766 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13767 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13768 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13769 }
13770
13771 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13772 if (U->getOpcode() == UO_LNot) {
13773 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13774 } else if (U->getOpcode() != UO_AddrOf) {
13775 if (U->getSubExpr()->getType()->isAtomicType())
13776 S.Diag(U->getSubExpr()->getBeginLoc(),
13777 diag::warn_atomic_implicit_seq_cst);
13778 }
13779 }
13780}
13781
13782/// AnalyzeImplicitConversions - Find and report any interesting
13783/// implicit conversions in the given expression. There are a couple
13784/// of competing diagnostics here, -Wconversion and -Wsign-compare.
13786 bool IsListInit/*= false*/) {
13788 WorkList.push_back({OrigE, CC, IsListInit});
13789 while (!WorkList.empty())
13790 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13791}
13792
13793// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13794// Returns true when emitting a warning about taking the address of a reference.
13795static bool CheckForReference(Sema &SemaRef, const Expr *E,
13796 const PartialDiagnostic &PD) {
13797 E = E->IgnoreParenImpCasts();
13798
13799 const FunctionDecl *FD = nullptr;
13800
13801 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13802 if (!DRE->getDecl()->getType()->isReferenceType())
13803 return false;
13804 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13805 if (!M->getMemberDecl()->getType()->isReferenceType())
13806 return false;
13807 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13808 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13809 return false;
13810 FD = Call->getDirectCallee();
13811 } else {
13812 return false;
13813 }
13814
13815 SemaRef.Diag(E->getExprLoc(), PD);
13816
13817 // If possible, point to location of function.
13818 if (FD) {
13819 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13820 }
13821
13822 return true;
13823}
13824
13825// Returns true if the SourceLocation is expanded from any macro body.
13826// Returns false if the SourceLocation is invalid, is from not in a macro
13827// expansion, or is from expanded from a top-level macro argument.
13829 if (Loc.isInvalid())
13830 return false;
13831
13832 while (Loc.isMacroID()) {
13833 if (SM.isMacroBodyExpansion(Loc))
13834 return true;
13835 Loc = SM.getImmediateMacroCallerLoc(Loc);
13836 }
13837
13838 return false;
13839}
13840
13843 bool IsEqual, SourceRange Range) {
13844 if (!E)
13845 return;
13846
13847 // Don't warn inside macros.
13848 if (E->getExprLoc().isMacroID()) {
13850 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13851 IsInAnyMacroBody(SM, Range.getBegin()))
13852 return;
13853 }
13854 E = E->IgnoreImpCasts();
13855
13856 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13857
13858 if (isa<CXXThisExpr>(E)) {
13859 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13860 : diag::warn_this_bool_conversion;
13861 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13862 return;
13863 }
13864
13865 bool IsAddressOf = false;
13866
13867 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
13868 if (UO->getOpcode() != UO_AddrOf)
13869 return;
13870 IsAddressOf = true;
13871 E = UO->getSubExpr();
13872 }
13873
13874 if (IsAddressOf) {
13875 unsigned DiagID = IsCompare
13876 ? diag::warn_address_of_reference_null_compare
13877 : diag::warn_address_of_reference_bool_conversion;
13878 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13879 << IsEqual;
13880 if (CheckForReference(*this, E, PD)) {
13881 return;
13882 }
13883 }
13884
13885 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13886 bool IsParam = isa<NonNullAttr>(NonnullAttr);
13887 std::string Str;
13888 llvm::raw_string_ostream S(Str);
13889 E->printPretty(S, nullptr, getPrintingPolicy());
13890 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13891 : diag::warn_cast_nonnull_to_bool;
13892 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13893 << E->getSourceRange() << Range << IsEqual;
13894 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13895 };
13896
13897 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13898 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13899 if (auto *Callee = Call->getDirectCallee()) {
13900 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13901 ComplainAboutNonnullParamOrCall(A);
13902 return;
13903 }
13904 }
13905 }
13906
13907 // Complain if we are converting a lambda expression to a boolean value
13908 // outside of instantiation.
13909 if (!inTemplateInstantiation()) {
13910 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
13911 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
13912 MRecordDecl && MRecordDecl->isLambda()) {
13913 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
13914 << /*LambdaPointerConversionOperatorType=*/3
13915 << MRecordDecl->getSourceRange() << Range << IsEqual;
13916 return;
13917 }
13918 }
13919 }
13920
13921 // Expect to find a single Decl. Skip anything more complicated.
13922 ValueDecl *D = nullptr;
13923 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13924 D = R->getDecl();
13925 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13926 D = M->getMemberDecl();
13927 }
13928
13929 // Weak Decls can be null.
13930 if (!D || D->isWeak())
13931 return;
13932
13933 // Check for parameter decl with nonnull attribute
13934 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13935 if (getCurFunction() &&
13936 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13937 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13938 ComplainAboutNonnullParamOrCall(A);
13939 return;
13940 }
13941
13942 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13943 // Skip function template not specialized yet.
13945 return;
13946 auto ParamIter = llvm::find(FD->parameters(), PV);
13947 assert(ParamIter != FD->param_end());
13948 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13949
13950 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13951 if (!NonNull->args_size()) {
13952 ComplainAboutNonnullParamOrCall(NonNull);
13953 return;
13954 }
13955
13956 for (const ParamIdx &ArgNo : NonNull->args()) {
13957 if (ArgNo.getASTIndex() == ParamNo) {
13958 ComplainAboutNonnullParamOrCall(NonNull);
13959 return;
13960 }
13961 }
13962 }
13963 }
13964 }
13965 }
13966
13967 QualType T = D->getType();
13968 const bool IsArray = T->isArrayType();
13969 const bool IsFunction = T->isFunctionType();
13970
13971 // Address of function is used to silence the function warning.
13972 if (IsAddressOf && IsFunction) {
13973 return;
13974 }
13975
13976 // Found nothing.
13977 if (!IsAddressOf && !IsFunction && !IsArray)
13978 return;
13979
13980 // Pretty print the expression for the diagnostic.
13981 std::string Str;
13982 llvm::raw_string_ostream S(Str);
13983 E->printPretty(S, nullptr, getPrintingPolicy());
13984
13985 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13986 : diag::warn_impcast_pointer_to_bool;
13987 enum {
13988 AddressOf,
13989 FunctionPointer,
13990 ArrayPointer
13991 } DiagType;
13992 if (IsAddressOf)
13993 DiagType = AddressOf;
13994 else if (IsFunction)
13995 DiagType = FunctionPointer;
13996 else if (IsArray)
13997 DiagType = ArrayPointer;
13998 else
13999 llvm_unreachable("Could not determine diagnostic.");
14000 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14001 << Range << IsEqual;
14002
14003 if (!IsFunction)
14004 return;
14005
14006 // Suggest '&' to silence the function warning.
14007 Diag(E->getExprLoc(), diag::note_function_warning_silence)
14009
14010 // Check to see if '()' fixit should be emitted.
14011 QualType ReturnType;
14012 UnresolvedSet<4> NonTemplateOverloads;
14013 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14014 if (ReturnType.isNull())
14015 return;
14016
14017 if (IsCompare) {
14018 // There are two cases here. If there is null constant, the only suggest
14019 // for a pointer return type. If the null is 0, then suggest if the return
14020 // type is a pointer or an integer type.
14021 if (!ReturnType->isPointerType()) {
14022 if (NullKind == Expr::NPCK_ZeroExpression ||
14023 NullKind == Expr::NPCK_ZeroLiteral) {
14024 if (!ReturnType->isIntegerType())
14025 return;
14026 } else {
14027 return;
14028 }
14029 }
14030 } else { // !IsCompare
14031 // For function to bool, only suggest if the function pointer has bool
14032 // return type.
14033 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14034 return;
14035 }
14036 Diag(E->getExprLoc(), diag::note_function_to_function_call)
14038}
14039
14041 SourceLocation CC) {
14042 QualType Source = E->getType();
14043 QualType Target = T;
14044
14045 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14046 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14047 // Overflow behavior type is being stripped - issue warning
14048 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14049 Target->isUnsignedIntegerType()) {
14050 // For unsigned wrap to unsigned conversions, use pedantic version
14051 unsigned DiagId =
14053 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14054 : diag::warn_impcast_overflow_behavior_pedantic;
14055 DiagnoseImpCast(*this, E, T, CC, DiagId);
14056 } else {
14057 unsigned DiagId = InOverflowBehaviorAssignmentContext
14058 ? diag::warn_impcast_overflow_behavior_assignment
14059 : diag::warn_impcast_overflow_behavior;
14060 DiagnoseImpCast(*this, E, T, CC, DiagId);
14061 }
14062 }
14063 }
14064
14065 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14066 if (TargetOBT->isWrapKind()) {
14067 return true;
14068 }
14069 }
14070
14071 return false;
14072}
14073
14074void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14075 // Don't diagnose in unevaluated contexts.
14077 return;
14078
14079 // Don't diagnose for value- or type-dependent expressions.
14080 if (E->isTypeDependent() || E->isValueDependent())
14081 return;
14082
14083 // Check for array bounds violations in cases where the check isn't triggered
14084 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14085 // ArraySubscriptExpr is on the RHS of a variable initialization.
14086 CheckArrayAccess(E);
14087
14088 // This is not the right CC for (e.g.) a variable initialization.
14089 AnalyzeImplicitConversions(*this, E, CC);
14090}
14091
14092void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14093 ::CheckBoolLikeConversion(*this, E, CC);
14094}
14095
14096void Sema::CheckForIntOverflow (const Expr *E) {
14097 // Use a work list to deal with nested struct initializers.
14098 SmallVector<const Expr *, 2> Exprs(1, E);
14099
14100 do {
14101 const Expr *OriginalE = Exprs.pop_back_val();
14102 const Expr *E = OriginalE->IgnoreParenCasts();
14103
14106 continue;
14107 }
14108
14109 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
14110 Exprs.append(InitList->inits().begin(), InitList->inits().end());
14111 else if (isa<ObjCBoxedExpr>(OriginalE))
14113 else if (const auto *Call = dyn_cast<CallExpr>(E))
14114 Exprs.append(Call->arg_begin(), Call->arg_end());
14115 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
14116 Exprs.append(Message->arg_begin(), Message->arg_end());
14117 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
14118 Exprs.append(Construct->arg_begin(), Construct->arg_end());
14119 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
14120 Exprs.push_back(Temporary->getSubExpr());
14121 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
14122 Exprs.push_back(Array->getIdx());
14123 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
14124 Exprs.push_back(Compound->getInitializer());
14125 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
14126 New && New->isArray()) {
14127 if (auto ArraySize = New->getArraySize())
14128 Exprs.push_back(*ArraySize);
14129 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
14130 Exprs.push_back(MTE->getSubExpr());
14131 } while (!Exprs.empty());
14132}
14133
14134namespace {
14135
14136/// Visitor for expressions which looks for unsequenced operations on the
14137/// same object.
14138class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14139 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14140
14141 /// A tree of sequenced regions within an expression. Two regions are
14142 /// unsequenced if one is an ancestor or a descendent of the other. When we
14143 /// finish processing an expression with sequencing, such as a comma
14144 /// expression, we fold its tree nodes into its parent, since they are
14145 /// unsequenced with respect to nodes we will visit later.
14146 class SequenceTree {
14147 struct Value {
14148 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14149 unsigned Parent : 31;
14150 LLVM_PREFERRED_TYPE(bool)
14151 unsigned Merged : 1;
14152 };
14153 SmallVector<Value, 8> Values;
14154
14155 public:
14156 /// A region within an expression which may be sequenced with respect
14157 /// to some other region.
14158 class Seq {
14159 friend class SequenceTree;
14160
14161 unsigned Index;
14162
14163 explicit Seq(unsigned N) : Index(N) {}
14164
14165 public:
14166 Seq() : Index(0) {}
14167 };
14168
14169 SequenceTree() { Values.push_back(Value(0)); }
14170 Seq root() const { return Seq(0); }
14171
14172 /// Create a new sequence of operations, which is an unsequenced
14173 /// subset of \p Parent. This sequence of operations is sequenced with
14174 /// respect to other children of \p Parent.
14175 Seq allocate(Seq Parent) {
14176 Values.push_back(Value(Parent.Index));
14177 return Seq(Values.size() - 1);
14178 }
14179
14180 /// Merge a sequence of operations into its parent.
14181 void merge(Seq S) {
14182 Values[S.Index].Merged = true;
14183 }
14184
14185 /// Determine whether two operations are unsequenced. This operation
14186 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14187 /// should have been merged into its parent as appropriate.
14188 bool isUnsequenced(Seq Cur, Seq Old) {
14189 unsigned C = representative(Cur.Index);
14190 unsigned Target = representative(Old.Index);
14191 while (C >= Target) {
14192 if (C == Target)
14193 return true;
14194 C = Values[C].Parent;
14195 }
14196 return false;
14197 }
14198
14199 private:
14200 /// Pick a representative for a sequence.
14201 unsigned representative(unsigned K) {
14202 if (Values[K].Merged)
14203 // Perform path compression as we go.
14204 return Values[K].Parent = representative(Values[K].Parent);
14205 return K;
14206 }
14207 };
14208
14209 /// An object for which we can track unsequenced uses.
14210 using Object = const NamedDecl *;
14211
14212 /// Different flavors of object usage which we track. We only track the
14213 /// least-sequenced usage of each kind.
14214 enum UsageKind {
14215 /// A read of an object. Multiple unsequenced reads are OK.
14216 UK_Use,
14217
14218 /// A modification of an object which is sequenced before the value
14219 /// computation of the expression, such as ++n in C++.
14220 UK_ModAsValue,
14221
14222 /// A modification of an object which is not sequenced before the value
14223 /// computation of the expression, such as n++.
14224 UK_ModAsSideEffect,
14225
14226 UK_Count = UK_ModAsSideEffect + 1
14227 };
14228
14229 /// Bundle together a sequencing region and the expression corresponding
14230 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14231 struct Usage {
14232 const Expr *UsageExpr = nullptr;
14233 SequenceTree::Seq Seq;
14234
14235 Usage() = default;
14236 };
14237
14238 struct UsageInfo {
14239 Usage Uses[UK_Count];
14240
14241 /// Have we issued a diagnostic for this object already?
14242 bool Diagnosed = false;
14243
14244 UsageInfo();
14245 };
14246 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14247
14248 Sema &SemaRef;
14249
14250 /// Sequenced regions within the expression.
14251 SequenceTree Tree;
14252
14253 /// Declaration modifications and references which we have seen.
14254 UsageInfoMap UsageMap;
14255
14256 /// The region we are currently within.
14257 SequenceTree::Seq Region;
14258
14259 /// Filled in with declarations which were modified as a side-effect
14260 /// (that is, post-increment operations).
14261 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14262
14263 /// Expressions to check later. We defer checking these to reduce
14264 /// stack usage.
14265 SmallVectorImpl<const Expr *> &WorkList;
14266
14267 /// RAII object wrapping the visitation of a sequenced subexpression of an
14268 /// expression. At the end of this process, the side-effects of the evaluation
14269 /// become sequenced with respect to the value computation of the result, so
14270 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14271 /// UK_ModAsValue.
14272 struct SequencedSubexpression {
14273 SequencedSubexpression(SequenceChecker &Self)
14274 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14275 Self.ModAsSideEffect = &ModAsSideEffect;
14276 }
14277
14278 ~SequencedSubexpression() {
14279 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14280 // Add a new usage with usage kind UK_ModAsValue, and then restore
14281 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14282 // the previous one was empty).
14283 UsageInfo &UI = Self.UsageMap[M.first];
14284 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14285 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14286 SideEffectUsage = M.second;
14287 }
14288 Self.ModAsSideEffect = OldModAsSideEffect;
14289 }
14290
14291 SequenceChecker &Self;
14292 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14293 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14294 };
14295
14296 /// RAII object wrapping the visitation of a subexpression which we might
14297 /// choose to evaluate as a constant. If any subexpression is evaluated and
14298 /// found to be non-constant, this allows us to suppress the evaluation of
14299 /// the outer expression.
14300 class EvaluationTracker {
14301 public:
14302 EvaluationTracker(SequenceChecker &Self)
14303 : Self(Self), Prev(Self.EvalTracker) {
14304 Self.EvalTracker = this;
14305 }
14306
14307 ~EvaluationTracker() {
14308 Self.EvalTracker = Prev;
14309 if (Prev)
14310 Prev->EvalOK &= EvalOK;
14311 }
14312
14313 bool evaluate(const Expr *E, bool &Result) {
14314 if (!EvalOK || E->isValueDependent())
14315 return false;
14316 EvalOK = E->EvaluateAsBooleanCondition(
14317 Result, Self.SemaRef.Context,
14318 Self.SemaRef.isConstantEvaluatedContext());
14319 return EvalOK;
14320 }
14321
14322 private:
14323 SequenceChecker &Self;
14324 EvaluationTracker *Prev;
14325 bool EvalOK = true;
14326 } *EvalTracker = nullptr;
14327
14328 /// Find the object which is produced by the specified expression,
14329 /// if any.
14330 Object getObject(const Expr *E, bool Mod) const {
14331 E = E->IgnoreParenCasts();
14332 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14333 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14334 return getObject(UO->getSubExpr(), Mod);
14335 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14336 if (BO->getOpcode() == BO_Comma)
14337 return getObject(BO->getRHS(), Mod);
14338 if (Mod && BO->isAssignmentOp())
14339 return getObject(BO->getLHS(), Mod);
14340 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14341 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14342 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14343 return ME->getMemberDecl();
14344 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14345 // FIXME: If this is a reference, map through to its value.
14346 return DRE->getDecl();
14347 return nullptr;
14348 }
14349
14350 /// Note that an object \p O was modified or used by an expression
14351 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14352 /// the object \p O as obtained via the \p UsageMap.
14353 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14354 // Get the old usage for the given object and usage kind.
14355 Usage &U = UI.Uses[UK];
14356 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14357 // If we have a modification as side effect and are in a sequenced
14358 // subexpression, save the old Usage so that we can restore it later
14359 // in SequencedSubexpression::~SequencedSubexpression.
14360 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14361 ModAsSideEffect->push_back(std::make_pair(O, U));
14362 // Then record the new usage with the current sequencing region.
14363 U.UsageExpr = UsageExpr;
14364 U.Seq = Region;
14365 }
14366 }
14367
14368 /// Check whether a modification or use of an object \p O in an expression
14369 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14370 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14371 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14372 /// usage and false we are checking for a mod-use unsequenced usage.
14373 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14374 UsageKind OtherKind, bool IsModMod) {
14375 if (UI.Diagnosed)
14376 return;
14377
14378 const Usage &U = UI.Uses[OtherKind];
14379 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14380 return;
14381
14382 const Expr *Mod = U.UsageExpr;
14383 const Expr *ModOrUse = UsageExpr;
14384 if (OtherKind == UK_Use)
14385 std::swap(Mod, ModOrUse);
14386
14387 SemaRef.DiagRuntimeBehavior(
14388 Mod->getExprLoc(), {Mod, ModOrUse},
14389 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14390 : diag::warn_unsequenced_mod_use)
14391 << O << SourceRange(ModOrUse->getExprLoc()));
14392 UI.Diagnosed = true;
14393 }
14394
14395 // A note on note{Pre, Post}{Use, Mod}:
14396 //
14397 // (It helps to follow the algorithm with an expression such as
14398 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14399 // operations before C++17 and both are well-defined in C++17).
14400 //
14401 // When visiting a node which uses/modify an object we first call notePreUse
14402 // or notePreMod before visiting its sub-expression(s). At this point the
14403 // children of the current node have not yet been visited and so the eventual
14404 // uses/modifications resulting from the children of the current node have not
14405 // been recorded yet.
14406 //
14407 // We then visit the children of the current node. After that notePostUse or
14408 // notePostMod is called. These will 1) detect an unsequenced modification
14409 // as side effect (as in "k++ + k") and 2) add a new usage with the
14410 // appropriate usage kind.
14411 //
14412 // We also have to be careful that some operation sequences modification as
14413 // side effect as well (for example: || or ,). To account for this we wrap
14414 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14415 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14416 // which record usages which are modifications as side effect, and then
14417 // downgrade them (or more accurately restore the previous usage which was a
14418 // modification as side effect) when exiting the scope of the sequenced
14419 // subexpression.
14420
14421 void notePreUse(Object O, const Expr *UseExpr) {
14422 UsageInfo &UI = UsageMap[O];
14423 // Uses conflict with other modifications.
14424 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14425 }
14426
14427 void notePostUse(Object O, const Expr *UseExpr) {
14428 UsageInfo &UI = UsageMap[O];
14429 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14430 /*IsModMod=*/false);
14431 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14432 }
14433
14434 void notePreMod(Object O, const Expr *ModExpr) {
14435 UsageInfo &UI = UsageMap[O];
14436 // Modifications conflict with other modifications and with uses.
14437 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14438 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14439 }
14440
14441 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14442 UsageInfo &UI = UsageMap[O];
14443 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14444 /*IsModMod=*/true);
14445 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14446 }
14447
14448public:
14449 SequenceChecker(Sema &S, const Expr *E,
14450 SmallVectorImpl<const Expr *> &WorkList)
14451 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14452 Visit(E);
14453 // Silence a -Wunused-private-field since WorkList is now unused.
14454 // TODO: Evaluate if it can be used, and if not remove it.
14455 (void)this->WorkList;
14456 }
14457
14458 void VisitStmt(const Stmt *S) {
14459 // Skip all statements which aren't expressions for now.
14460 }
14461
14462 void VisitExpr(const Expr *E) {
14463 // By default, just recurse to evaluated subexpressions.
14464 Base::VisitStmt(E);
14465 }
14466
14467 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14468 for (auto *Sub : CSE->children()) {
14469 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
14470 if (!ChildExpr)
14471 continue;
14472
14473 if (ChildExpr == CSE->getOperand())
14474 // Do not recurse over a CoroutineSuspendExpr's operand.
14475 // The operand is also a subexpression of getCommonExpr(), and
14476 // recursing into it directly could confuse object management
14477 // for the sake of sequence tracking.
14478 continue;
14479
14480 Visit(Sub);
14481 }
14482 }
14483
14484 void VisitCastExpr(const CastExpr *E) {
14485 Object O = Object();
14486 if (E->getCastKind() == CK_LValueToRValue)
14487 O = getObject(E->getSubExpr(), false);
14488
14489 if (O)
14490 notePreUse(O, E);
14491 VisitExpr(E);
14492 if (O)
14493 notePostUse(O, E);
14494 }
14495
14496 void VisitSequencedExpressions(const Expr *SequencedBefore,
14497 const Expr *SequencedAfter) {
14498 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14499 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14500 SequenceTree::Seq OldRegion = Region;
14501
14502 {
14503 SequencedSubexpression SeqBefore(*this);
14504 Region = BeforeRegion;
14505 Visit(SequencedBefore);
14506 }
14507
14508 Region = AfterRegion;
14509 Visit(SequencedAfter);
14510
14511 Region = OldRegion;
14512
14513 Tree.merge(BeforeRegion);
14514 Tree.merge(AfterRegion);
14515 }
14516
14517 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14518 // C++17 [expr.sub]p1:
14519 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14520 // expression E1 is sequenced before the expression E2.
14521 if (SemaRef.getLangOpts().CPlusPlus17)
14522 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14523 else {
14524 Visit(ASE->getLHS());
14525 Visit(ASE->getRHS());
14526 }
14527 }
14528
14529 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14530 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14531 void VisitBinPtrMem(const BinaryOperator *BO) {
14532 // C++17 [expr.mptr.oper]p4:
14533 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14534 // the expression E1 is sequenced before the expression E2.
14535 if (SemaRef.getLangOpts().CPlusPlus17)
14536 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14537 else {
14538 Visit(BO->getLHS());
14539 Visit(BO->getRHS());
14540 }
14541 }
14542
14543 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14544 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14545 void VisitBinShlShr(const BinaryOperator *BO) {
14546 // C++17 [expr.shift]p4:
14547 // The expression E1 is sequenced before the expression E2.
14548 if (SemaRef.getLangOpts().CPlusPlus17)
14549 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14550 else {
14551 Visit(BO->getLHS());
14552 Visit(BO->getRHS());
14553 }
14554 }
14555
14556 void VisitBinComma(const BinaryOperator *BO) {
14557 // C++11 [expr.comma]p1:
14558 // Every value computation and side effect associated with the left
14559 // expression is sequenced before every value computation and side
14560 // effect associated with the right expression.
14561 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14562 }
14563
14564 void VisitBinAssign(const BinaryOperator *BO) {
14565 SequenceTree::Seq RHSRegion;
14566 SequenceTree::Seq LHSRegion;
14567 if (SemaRef.getLangOpts().CPlusPlus17) {
14568 RHSRegion = Tree.allocate(Region);
14569 LHSRegion = Tree.allocate(Region);
14570 } else {
14571 RHSRegion = Region;
14572 LHSRegion = Region;
14573 }
14574 SequenceTree::Seq OldRegion = Region;
14575
14576 // C++11 [expr.ass]p1:
14577 // [...] the assignment is sequenced after the value computation
14578 // of the right and left operands, [...]
14579 //
14580 // so check it before inspecting the operands and update the
14581 // map afterwards.
14582 Object O = getObject(BO->getLHS(), /*Mod=*/true);
14583 if (O)
14584 notePreMod(O, BO);
14585
14586 if (SemaRef.getLangOpts().CPlusPlus17) {
14587 // C++17 [expr.ass]p1:
14588 // [...] The right operand is sequenced before the left operand. [...]
14589 {
14590 SequencedSubexpression SeqBefore(*this);
14591 Region = RHSRegion;
14592 Visit(BO->getRHS());
14593 }
14594
14595 Region = LHSRegion;
14596 Visit(BO->getLHS());
14597
14598 if (O && isa<CompoundAssignOperator>(BO))
14599 notePostUse(O, BO);
14600
14601 } else {
14602 // C++11 does not specify any sequencing between the LHS and RHS.
14603 Region = LHSRegion;
14604 Visit(BO->getLHS());
14605
14606 if (O && isa<CompoundAssignOperator>(BO))
14607 notePostUse(O, BO);
14608
14609 Region = RHSRegion;
14610 Visit(BO->getRHS());
14611 }
14612
14613 // C++11 [expr.ass]p1:
14614 // the assignment is sequenced [...] before the value computation of the
14615 // assignment expression.
14616 // C11 6.5.16/3 has no such rule.
14617 Region = OldRegion;
14618 if (O)
14619 notePostMod(O, BO,
14620 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14621 : UK_ModAsSideEffect);
14622 if (SemaRef.getLangOpts().CPlusPlus17) {
14623 Tree.merge(RHSRegion);
14624 Tree.merge(LHSRegion);
14625 }
14626 }
14627
14628 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14629 VisitBinAssign(CAO);
14630 }
14631
14632 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14633 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14634 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14635 Object O = getObject(UO->getSubExpr(), true);
14636 if (!O)
14637 return VisitExpr(UO);
14638
14639 notePreMod(O, UO);
14640 Visit(UO->getSubExpr());
14641 // C++11 [expr.pre.incr]p1:
14642 // the expression ++x is equivalent to x+=1
14643 notePostMod(O, UO,
14644 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14645 : UK_ModAsSideEffect);
14646 }
14647
14648 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14649 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14650 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14651 Object O = getObject(UO->getSubExpr(), true);
14652 if (!O)
14653 return VisitExpr(UO);
14654
14655 notePreMod(O, UO);
14656 Visit(UO->getSubExpr());
14657 notePostMod(O, UO, UK_ModAsSideEffect);
14658 }
14659
14660 void VisitBinLOr(const BinaryOperator *BO) {
14661 // C++11 [expr.log.or]p2:
14662 // If the second expression is evaluated, every value computation and
14663 // side effect associated with the first expression is sequenced before
14664 // every value computation and side effect associated with the
14665 // second expression.
14666 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14667 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14668 SequenceTree::Seq OldRegion = Region;
14669
14670 EvaluationTracker Eval(*this);
14671 {
14672 SequencedSubexpression Sequenced(*this);
14673 Region = LHSRegion;
14674 Visit(BO->getLHS());
14675 }
14676
14677 // C++11 [expr.log.or]p1:
14678 // [...] the second operand is not evaluated if the first operand
14679 // evaluates to true.
14680 bool EvalResult = false;
14681 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14682 bool ShouldVisitRHS = !EvalOK || !EvalResult;
14683 if (ShouldVisitRHS) {
14684 Region = RHSRegion;
14685 Visit(BO->getRHS());
14686 }
14687
14688 Region = OldRegion;
14689 Tree.merge(LHSRegion);
14690 Tree.merge(RHSRegion);
14691 }
14692
14693 void VisitBinLAnd(const BinaryOperator *BO) {
14694 // C++11 [expr.log.and]p2:
14695 // If the second expression is evaluated, every value computation and
14696 // side effect associated with the first expression is sequenced before
14697 // every value computation and side effect associated with the
14698 // second expression.
14699 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14700 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14701 SequenceTree::Seq OldRegion = Region;
14702
14703 EvaluationTracker Eval(*this);
14704 {
14705 SequencedSubexpression Sequenced(*this);
14706 Region = LHSRegion;
14707 Visit(BO->getLHS());
14708 }
14709
14710 // C++11 [expr.log.and]p1:
14711 // [...] the second operand is not evaluated if the first operand is false.
14712 bool EvalResult = false;
14713 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14714 bool ShouldVisitRHS = !EvalOK || EvalResult;
14715 if (ShouldVisitRHS) {
14716 Region = RHSRegion;
14717 Visit(BO->getRHS());
14718 }
14719
14720 Region = OldRegion;
14721 Tree.merge(LHSRegion);
14722 Tree.merge(RHSRegion);
14723 }
14724
14725 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14726 // C++11 [expr.cond]p1:
14727 // [...] Every value computation and side effect associated with the first
14728 // expression is sequenced before every value computation and side effect
14729 // associated with the second or third expression.
14730 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14731
14732 // No sequencing is specified between the true and false expression.
14733 // However since exactly one of both is going to be evaluated we can
14734 // consider them to be sequenced. This is needed to avoid warning on
14735 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14736 // both the true and false expressions because we can't evaluate x.
14737 // This will still allow us to detect an expression like (pre C++17)
14738 // "(x ? y += 1 : y += 2) = y".
14739 //
14740 // We don't wrap the visitation of the true and false expression with
14741 // SequencedSubexpression because we don't want to downgrade modifications
14742 // as side effect in the true and false expressions after the visition
14743 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14744 // not warn between the two "y++", but we should warn between the "y++"
14745 // and the "y".
14746 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14747 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14748 SequenceTree::Seq OldRegion = Region;
14749
14750 EvaluationTracker Eval(*this);
14751 {
14752 SequencedSubexpression Sequenced(*this);
14753 Region = ConditionRegion;
14754 Visit(CO->getCond());
14755 }
14756
14757 // C++11 [expr.cond]p1:
14758 // [...] The first expression is contextually converted to bool (Clause 4).
14759 // It is evaluated and if it is true, the result of the conditional
14760 // expression is the value of the second expression, otherwise that of the
14761 // third expression. Only one of the second and third expressions is
14762 // evaluated. [...]
14763 bool EvalResult = false;
14764 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14765 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
14766 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
14767 if (ShouldVisitTrueExpr) {
14768 Region = TrueRegion;
14769 Visit(CO->getTrueExpr());
14770 }
14771 if (ShouldVisitFalseExpr) {
14772 Region = FalseRegion;
14773 Visit(CO->getFalseExpr());
14774 }
14775
14776 Region = OldRegion;
14777 Tree.merge(ConditionRegion);
14778 Tree.merge(TrueRegion);
14779 Tree.merge(FalseRegion);
14780 }
14781
14782 void VisitCallExpr(const CallExpr *CE) {
14783 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14784
14785 if (CE->isUnevaluatedBuiltinCall(Context))
14786 return;
14787
14788 // C++11 [intro.execution]p15:
14789 // When calling a function [...], every value computation and side effect
14790 // associated with any argument expression, or with the postfix expression
14791 // designating the called function, is sequenced before execution of every
14792 // expression or statement in the body of the function [and thus before
14793 // the value computation of its result].
14794 SequencedSubexpression Sequenced(*this);
14795 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14796 // C++17 [expr.call]p5
14797 // The postfix-expression is sequenced before each expression in the
14798 // expression-list and any default argument. [...]
14799 SequenceTree::Seq CalleeRegion;
14800 SequenceTree::Seq OtherRegion;
14801 if (SemaRef.getLangOpts().CPlusPlus17) {
14802 CalleeRegion = Tree.allocate(Region);
14803 OtherRegion = Tree.allocate(Region);
14804 } else {
14805 CalleeRegion = Region;
14806 OtherRegion = Region;
14807 }
14808 SequenceTree::Seq OldRegion = Region;
14809
14810 // Visit the callee expression first.
14811 Region = CalleeRegion;
14812 if (SemaRef.getLangOpts().CPlusPlus17) {
14813 SequencedSubexpression Sequenced(*this);
14814 Visit(CE->getCallee());
14815 } else {
14816 Visit(CE->getCallee());
14817 }
14818
14819 // Then visit the argument expressions.
14820 Region = OtherRegion;
14821 for (const Expr *Argument : CE->arguments())
14822 Visit(Argument);
14823
14824 Region = OldRegion;
14825 if (SemaRef.getLangOpts().CPlusPlus17) {
14826 Tree.merge(CalleeRegion);
14827 Tree.merge(OtherRegion);
14828 }
14829 });
14830 }
14831
14832 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14833 // C++17 [over.match.oper]p2:
14834 // [...] the operator notation is first transformed to the equivalent
14835 // function-call notation as summarized in Table 12 (where @ denotes one
14836 // of the operators covered in the specified subclause). However, the
14837 // operands are sequenced in the order prescribed for the built-in
14838 // operator (Clause 8).
14839 //
14840 // From the above only overloaded binary operators and overloaded call
14841 // operators have sequencing rules in C++17 that we need to handle
14842 // separately.
14843 if (!SemaRef.getLangOpts().CPlusPlus17 ||
14844 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14845 return VisitCallExpr(CXXOCE);
14846
14847 enum {
14848 NoSequencing,
14849 LHSBeforeRHS,
14850 RHSBeforeLHS,
14851 LHSBeforeRest
14852 } SequencingKind;
14853 switch (CXXOCE->getOperator()) {
14854 case OO_Equal:
14855 case OO_PlusEqual:
14856 case OO_MinusEqual:
14857 case OO_StarEqual:
14858 case OO_SlashEqual:
14859 case OO_PercentEqual:
14860 case OO_CaretEqual:
14861 case OO_AmpEqual:
14862 case OO_PipeEqual:
14863 case OO_LessLessEqual:
14864 case OO_GreaterGreaterEqual:
14865 SequencingKind = RHSBeforeLHS;
14866 break;
14867
14868 case OO_LessLess:
14869 case OO_GreaterGreater:
14870 case OO_AmpAmp:
14871 case OO_PipePipe:
14872 case OO_Comma:
14873 case OO_ArrowStar:
14874 case OO_Subscript:
14875 SequencingKind = LHSBeforeRHS;
14876 break;
14877
14878 case OO_Call:
14879 SequencingKind = LHSBeforeRest;
14880 break;
14881
14882 default:
14883 SequencingKind = NoSequencing;
14884 break;
14885 }
14886
14887 if (SequencingKind == NoSequencing)
14888 return VisitCallExpr(CXXOCE);
14889
14890 // This is a call, so all subexpressions are sequenced before the result.
14891 SequencedSubexpression Sequenced(*this);
14892
14893 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14894 assert(SemaRef.getLangOpts().CPlusPlus17 &&
14895 "Should only get there with C++17 and above!");
14896 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14897 "Should only get there with an overloaded binary operator"
14898 " or an overloaded call operator!");
14899
14900 if (SequencingKind == LHSBeforeRest) {
14901 assert(CXXOCE->getOperator() == OO_Call &&
14902 "We should only have an overloaded call operator here!");
14903
14904 // This is very similar to VisitCallExpr, except that we only have the
14905 // C++17 case. The postfix-expression is the first argument of the
14906 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14907 // are in the following arguments.
14908 //
14909 // Note that we intentionally do not visit the callee expression since
14910 // it is just a decayed reference to a function.
14911 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14912 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14913 SequenceTree::Seq OldRegion = Region;
14914
14915 assert(CXXOCE->getNumArgs() >= 1 &&
14916 "An overloaded call operator must have at least one argument"
14917 " for the postfix-expression!");
14918 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14919 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14920 CXXOCE->getNumArgs() - 1);
14921
14922 // Visit the postfix-expression first.
14923 {
14924 Region = PostfixExprRegion;
14925 SequencedSubexpression Sequenced(*this);
14926 Visit(PostfixExpr);
14927 }
14928
14929 // Then visit the argument expressions.
14930 Region = ArgsRegion;
14931 for (const Expr *Arg : Args)
14932 Visit(Arg);
14933
14934 Region = OldRegion;
14935 Tree.merge(PostfixExprRegion);
14936 Tree.merge(ArgsRegion);
14937 } else {
14938 assert(CXXOCE->getNumArgs() == 2 &&
14939 "Should only have two arguments here!");
14940 assert((SequencingKind == LHSBeforeRHS ||
14941 SequencingKind == RHSBeforeLHS) &&
14942 "Unexpected sequencing kind!");
14943
14944 // We do not visit the callee expression since it is just a decayed
14945 // reference to a function.
14946 const Expr *E1 = CXXOCE->getArg(0);
14947 const Expr *E2 = CXXOCE->getArg(1);
14948 if (SequencingKind == RHSBeforeLHS)
14949 std::swap(E1, E2);
14950
14951 return VisitSequencedExpressions(E1, E2);
14952 }
14953 });
14954 }
14955
14956 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14957 // This is a call, so all subexpressions are sequenced before the result.
14958 SequencedSubexpression Sequenced(*this);
14959
14960 if (!CCE->isListInitialization())
14961 return VisitExpr(CCE);
14962
14963 // In C++11, list initializations are sequenced.
14964 SequenceExpressionsInOrder(
14965 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
14966 }
14967
14968 void VisitInitListExpr(const InitListExpr *ILE) {
14969 if (!SemaRef.getLangOpts().CPlusPlus11)
14970 return VisitExpr(ILE);
14971
14972 // In C++11, list initializations are sequenced.
14973 SequenceExpressionsInOrder(ILE->inits());
14974 }
14975
14976 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
14977 // C++20 parenthesized list initializations are sequenced. See C++20
14978 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
14979 SequenceExpressionsInOrder(PLIE->getInitExprs());
14980 }
14981
14982private:
14983 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
14985 SequenceTree::Seq Parent = Region;
14986 for (const Expr *E : ExpressionList) {
14987 if (!E)
14988 continue;
14989 Region = Tree.allocate(Parent);
14990 Elts.push_back(Region);
14991 Visit(E);
14992 }
14993
14994 // Forget that the initializers are sequenced.
14995 Region = Parent;
14996 for (unsigned I = 0; I < Elts.size(); ++I)
14997 Tree.merge(Elts[I]);
14998 }
14999};
15000
15001SequenceChecker::UsageInfo::UsageInfo() = default;
15002
15003} // namespace
15004
15005void Sema::CheckUnsequencedOperations(const Expr *E) {
15006 SmallVector<const Expr *, 8> WorkList;
15007 WorkList.push_back(E);
15008 while (!WorkList.empty()) {
15009 const Expr *Item = WorkList.pop_back_val();
15010 SequenceChecker(*this, Item, WorkList);
15011 }
15012}
15013
15014void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15015 bool IsConstexpr) {
15016 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15017 IsConstexpr || isa<ConstantExpr>(E));
15018 CheckImplicitConversions(E, CheckLoc);
15019 if (!E->isInstantiationDependent())
15020 CheckUnsequencedOperations(E);
15021 if (!IsConstexpr && !E->isValueDependent())
15022 CheckForIntOverflow(E);
15023}
15024
15025void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15026 FieldDecl *BitField,
15027 Expr *Init) {
15028 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
15029}
15030
15032 SourceLocation Loc) {
15033 if (!PType->isVariablyModifiedType())
15034 return;
15035 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
15036 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
15037 return;
15038 }
15039 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
15040 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
15041 return;
15042 }
15043 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
15044 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
15045 return;
15046 }
15047
15048 const ArrayType *AT = S.Context.getAsArrayType(PType);
15049 if (!AT)
15050 return;
15051
15054 return;
15055 }
15056
15057 S.Diag(Loc, diag::err_array_star_in_function_definition);
15058}
15059
15061 bool CheckParameterNames) {
15062 bool HasInvalidParm = false;
15063 for (ParmVarDecl *Param : Parameters) {
15064 assert(Param && "null in a parameter list");
15065 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15066 // function declarator that is part of a function definition of
15067 // that function shall not have incomplete type.
15068 //
15069 // C++23 [dcl.fct.def.general]/p2
15070 // The type of a parameter [...] for a function definition
15071 // shall not be a (possibly cv-qualified) class type that is incomplete
15072 // or abstract within the function body unless the function is deleted.
15073 if (!Param->isInvalidDecl() &&
15074 (RequireCompleteType(Param->getLocation(), Param->getType(),
15075 diag::err_typecheck_decl_incomplete_type) ||
15076 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
15077 diag::err_abstract_type_in_decl,
15079 Param->setInvalidDecl();
15080 HasInvalidParm = true;
15081 }
15082
15083 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15084 // declaration of each parameter shall include an identifier.
15085 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15086 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15087 // Diagnose this as an extension in C17 and earlier.
15088 if (!getLangOpts().C23)
15089 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
15090 }
15091
15092 // C99 6.7.5.3p12:
15093 // If the function declarator is not part of a definition of that
15094 // function, parameters may have incomplete type and may use the [*]
15095 // notation in their sequences of declarator specifiers to specify
15096 // variable length array types.
15097 QualType PType = Param->getOriginalType();
15098 // FIXME: This diagnostic should point the '[*]' if source-location
15099 // information is added for it.
15100 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15101
15102 // If the parameter is a c++ class type and it has to be destructed in the
15103 // callee function, declare the destructor so that it can be called by the
15104 // callee function. Do not perform any direct access check on the dtor here.
15105 if (!Param->isInvalidDecl()) {
15106 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15107 if (!ClassDecl->isInvalidDecl() &&
15108 !ClassDecl->hasIrrelevantDestructor() &&
15109 !ClassDecl->isDependentContext() &&
15110 ClassDecl->isParamDestroyedInCallee()) {
15112 MarkFunctionReferenced(Param->getLocation(), Destructor);
15113 DiagnoseUseOfDecl(Destructor, Param->getLocation());
15114 }
15115 }
15116 }
15117
15118 // Parameters with the pass_object_size attribute only need to be marked
15119 // constant at function definitions. Because we lack information about
15120 // whether we're on a declaration or definition when we're instantiating the
15121 // attribute, we need to check for constness here.
15122 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15123 if (!Param->getType().isConstQualified())
15124 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15125 << Attr->getSpelling() << 1;
15126
15127 // Check for parameter names shadowing fields from the class.
15128 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15129 // The owning context for the parameter should be the function, but we
15130 // want to see if this function's declaration context is a record.
15131 DeclContext *DC = Param->getDeclContext();
15132 if (DC && DC->isFunctionOrMethod()) {
15133 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15134 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15135 RD, /*DeclIsField*/ false);
15136 }
15137 }
15138
15139 if (!Param->isInvalidDecl() &&
15140 Param->getOriginalType()->isWebAssemblyTableType()) {
15141 Param->setInvalidDecl();
15142 HasInvalidParm = true;
15143 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
15144 }
15145 }
15146
15147 return HasInvalidParm;
15148}
15149
15150std::optional<std::pair<
15152 *E,
15154 &Ctx);
15155
15156/// Compute the alignment and offset of the base class object given the
15157/// derived-to-base cast expression and the alignment and offset of the derived
15158/// class object.
15159static std::pair<CharUnits, CharUnits>
15161 CharUnits BaseAlignment, CharUnits Offset,
15162 ASTContext &Ctx) {
15163 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15164 ++PathI) {
15165 const CXXBaseSpecifier *Base = *PathI;
15166 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15167 if (Base->isVirtual()) {
15168 // The complete object may have a lower alignment than the non-virtual
15169 // alignment of the base, in which case the base may be misaligned. Choose
15170 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15171 // conservative lower bound of the complete object alignment.
15172 CharUnits NonVirtualAlignment =
15174 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15175 Offset = CharUnits::Zero();
15176 } else {
15177 const ASTRecordLayout &RL =
15178 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15179 Offset += RL.getBaseClassOffset(BaseDecl);
15180 }
15181 DerivedType = Base->getType();
15182 }
15183
15184 return std::make_pair(BaseAlignment, Offset);
15185}
15186
15187/// Compute the alignment and offset of a binary additive operator.
15188static std::optional<std::pair<CharUnits, CharUnits>>
15190 bool IsSub, ASTContext &Ctx) {
15191 QualType PointeeType = PtrE->getType()->getPointeeType();
15192
15193 if (!PointeeType->isConstantSizeType())
15194 return std::nullopt;
15195
15196 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15197
15198 if (!P)
15199 return std::nullopt;
15200
15201 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15202 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15203 CharUnits Offset = EltSize * IdxRes->getExtValue();
15204 if (IsSub)
15205 Offset = -Offset;
15206 return std::make_pair(P->first, P->second + Offset);
15207 }
15208
15209 // If the integer expression isn't a constant expression, compute the lower
15210 // bound of the alignment using the alignment and offset of the pointer
15211 // expression and the element size.
15212 return std::make_pair(
15213 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15214 CharUnits::Zero());
15215}
15216
15217/// This helper function takes an lvalue expression and returns the alignment of
15218/// a VarDecl and a constant offset from the VarDecl.
15219std::optional<std::pair<
15220 CharUnits,
15222 ASTContext &Ctx) {
15223 E = E->IgnoreParens();
15224 switch (E->getStmtClass()) {
15225 default:
15226 break;
15227 case Stmt::CStyleCastExprClass:
15228 case Stmt::CXXStaticCastExprClass:
15229 case Stmt::ImplicitCastExprClass: {
15230 auto *CE = cast<CastExpr>(E);
15231 const Expr *From = CE->getSubExpr();
15232 switch (CE->getCastKind()) {
15233 default:
15234 break;
15235 case CK_NoOp:
15236 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15237 case CK_UncheckedDerivedToBase:
15238 case CK_DerivedToBase: {
15239 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15240 if (!P)
15241 break;
15242 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15243 P->second, Ctx);
15244 }
15245 }
15246 break;
15247 }
15248 case Stmt::ArraySubscriptExprClass: {
15249 auto *ASE = cast<ArraySubscriptExpr>(E);
15251 false, Ctx);
15252 }
15253 case Stmt::DeclRefExprClass: {
15254 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15255 // FIXME: If VD is captured by copy or is an escaping __block variable,
15256 // use the alignment of VD's type.
15257 if (!VD->getType()->isReferenceType()) {
15258 // Dependent alignment cannot be resolved -> bail out.
15259 if (VD->hasDependentAlignment())
15260 break;
15261 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15262 }
15263 if (VD->hasInit())
15264 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15265 }
15266 break;
15267 }
15268 case Stmt::MemberExprClass: {
15269 auto *ME = cast<MemberExpr>(E);
15270 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15271 if (!FD || FD->getType()->isReferenceType() ||
15272 FD->getParent()->isInvalidDecl())
15273 break;
15274 std::optional<std::pair<CharUnits, CharUnits>> P;
15275 if (ME->isArrow())
15276 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15277 else
15278 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15279 if (!P)
15280 break;
15281 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15282 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15283 return std::make_pair(P->first,
15284 P->second + CharUnits::fromQuantity(Offset));
15285 }
15286 case Stmt::UnaryOperatorClass: {
15287 auto *UO = cast<UnaryOperator>(E);
15288 switch (UO->getOpcode()) {
15289 default:
15290 break;
15291 case UO_Deref:
15293 }
15294 break;
15295 }
15296 case Stmt::BinaryOperatorClass: {
15297 auto *BO = cast<BinaryOperator>(E);
15298 auto Opcode = BO->getOpcode();
15299 switch (Opcode) {
15300 default:
15301 break;
15302 case BO_Comma:
15304 }
15305 break;
15306 }
15307 }
15308 return std::nullopt;
15309}
15310
15311/// This helper function takes a pointer expression and returns the alignment of
15312/// a VarDecl and a constant offset from the VarDecl.
15313std::optional<std::pair<
15315 *E,
15317 &Ctx) {
15318 E = E->IgnoreParens();
15319 switch (E->getStmtClass()) {
15320 default:
15321 break;
15322 case Stmt::CStyleCastExprClass:
15323 case Stmt::CXXStaticCastExprClass:
15324 case Stmt::ImplicitCastExprClass: {
15325 auto *CE = cast<CastExpr>(E);
15326 const Expr *From = CE->getSubExpr();
15327 switch (CE->getCastKind()) {
15328 default:
15329 break;
15330 case CK_NoOp:
15331 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15332 case CK_ArrayToPointerDecay:
15333 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15334 case CK_UncheckedDerivedToBase:
15335 case CK_DerivedToBase: {
15336 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15337 if (!P)
15338 break;
15340 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15341 }
15342 }
15343 break;
15344 }
15345 case Stmt::CXXThisExprClass: {
15346 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15348 return std::make_pair(Alignment, CharUnits::Zero());
15349 }
15350 case Stmt::UnaryOperatorClass: {
15351 auto *UO = cast<UnaryOperator>(E);
15352 if (UO->getOpcode() == UO_AddrOf)
15354 break;
15355 }
15356 case Stmt::BinaryOperatorClass: {
15357 auto *BO = cast<BinaryOperator>(E);
15358 auto Opcode = BO->getOpcode();
15359 switch (Opcode) {
15360 default:
15361 break;
15362 case BO_Add:
15363 case BO_Sub: {
15364 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15365 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15366 std::swap(LHS, RHS);
15367 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15368 Ctx);
15369 }
15370 case BO_Comma:
15371 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15372 }
15373 break;
15374 }
15375 }
15376 return std::nullopt;
15377}
15378
15380 // See if we can compute the alignment of a VarDecl and an offset from it.
15381 std::optional<std::pair<CharUnits, CharUnits>> P =
15383
15384 if (P)
15385 return P->first.alignmentAtOffset(P->second);
15386
15387 // If that failed, return the type's alignment.
15389}
15390
15392 // This is actually a lot of work to potentially be doing on every
15393 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15394 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15395 return;
15396
15397 // Ignore dependent types.
15398 if (T->isDependentType() || Op->getType()->isDependentType())
15399 return;
15400
15401 // Require that the destination be a pointer type.
15402 const PointerType *DestPtr = T->getAs<PointerType>();
15403 if (!DestPtr) return;
15404
15405 // If the destination has alignment 1, we're done.
15406 QualType DestPointee = DestPtr->getPointeeType();
15407 if (DestPointee->isIncompleteType()) return;
15408 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15409 if (DestAlign.isOne()) return;
15410
15411 // Require that the source be a pointer type.
15412 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15413 if (!SrcPtr) return;
15414 QualType SrcPointee = SrcPtr->getPointeeType();
15415
15416 // Explicitly allow casts from cv void*. We already implicitly
15417 // allowed casts to cv void*, since they have alignment 1.
15418 // Also allow casts involving incomplete types, which implicitly
15419 // includes 'void'.
15420 if (SrcPointee->isIncompleteType()) return;
15421
15422 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15423
15424 if (SrcAlign >= DestAlign) return;
15425
15426 Diag(TRange.getBegin(), diag::warn_cast_align)
15427 << Op->getType() << T
15428 << static_cast<unsigned>(SrcAlign.getQuantity())
15429 << static_cast<unsigned>(DestAlign.getQuantity())
15430 << TRange << Op->getSourceRange();
15431}
15432
15433void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15434 const ArraySubscriptExpr *ASE,
15435 bool AllowOnePastEnd, bool IndexNegated) {
15436 // Already diagnosed by the constant evaluator.
15438 return;
15439
15440 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15441 if (IndexExpr->isValueDependent())
15442 return;
15443
15444 const Type *EffectiveType =
15446 BaseExpr = BaseExpr->IgnoreParenCasts();
15447 const ConstantArrayType *ArrayTy =
15448 Context.getAsConstantArrayType(BaseExpr->getType());
15449
15451 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15452
15453 const Type *BaseType =
15454 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15455 bool IsUnboundedArray =
15456 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15457 Context, StrictFlexArraysLevel,
15458 /*IgnoreTemplateOrMacroSubstitution=*/true);
15459 if (EffectiveType->isDependentType() ||
15460 (!IsUnboundedArray && BaseType->isDependentType()))
15461 return;
15462
15464 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15465 return;
15466
15467 llvm::APSInt index = Result.Val.getInt();
15468 if (IndexNegated) {
15469 index.setIsUnsigned(false);
15470 index = -index;
15471 }
15472
15473 if (IsUnboundedArray) {
15474 if (EffectiveType->isFunctionType())
15475 return;
15476 if (index.isUnsigned() || !index.isNegative()) {
15477 const auto &ASTC = getASTContext();
15478 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15479 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15480 if (index.getBitWidth() < AddrBits)
15481 index = index.zext(AddrBits);
15482 std::optional<CharUnits> ElemCharUnits =
15483 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15484 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15485 // pointer) bounds-checking isn't meaningful.
15486 if (!ElemCharUnits || ElemCharUnits->isZero())
15487 return;
15488 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15489 // If index has more active bits than address space, we already know
15490 // we have a bounds violation to warn about. Otherwise, compute
15491 // address of (index + 1)th element, and warn about bounds violation
15492 // only if that address exceeds address space.
15493 if (index.getActiveBits() <= AddrBits) {
15494 bool Overflow;
15495 llvm::APInt Product(index);
15496 Product += 1;
15497 Product = Product.umul_ov(ElemBytes, Overflow);
15498 if (!Overflow && Product.getActiveBits() <= AddrBits)
15499 return;
15500 }
15501
15502 // Need to compute max possible elements in address space, since that
15503 // is included in diag message.
15504 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15505 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15506 MaxElems += 1;
15507 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15508 MaxElems = MaxElems.udiv(ElemBytes);
15509
15510 unsigned DiagID =
15511 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15512 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15513
15514 // Diag message shows element size in bits and in "bytes" (platform-
15515 // dependent CharUnits)
15516 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15517 PDiag(DiagID) << index << AddrBits
15518 << (unsigned)ASTC.toBits(*ElemCharUnits)
15519 << ElemBytes << MaxElems
15520 << MaxElems.getZExtValue()
15521 << IndexExpr->getSourceRange());
15522
15523 const NamedDecl *ND = nullptr;
15524 // Try harder to find a NamedDecl to point at in the note.
15525 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15526 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15527 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15528 ND = DRE->getDecl();
15529 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15530 ND = ME->getMemberDecl();
15531
15532 if (ND)
15533 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15534 PDiag(diag::note_array_declared_here) << ND);
15535 }
15536 return;
15537 }
15538
15539 if (index.isUnsigned() || !index.isNegative()) {
15540 // It is possible that the type of the base expression after
15541 // IgnoreParenCasts is incomplete, even though the type of the base
15542 // expression before IgnoreParenCasts is complete (see PR39746 for an
15543 // example). In this case we have no information about whether the array
15544 // access exceeds the array bounds. However we can still diagnose an array
15545 // access which precedes the array bounds.
15546 if (BaseType->isIncompleteType())
15547 return;
15548
15549 llvm::APInt size = ArrayTy->getSize();
15550
15551 if (BaseType != EffectiveType) {
15552 // Make sure we're comparing apples to apples when comparing index to
15553 // size.
15554 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15555 uint64_t array_typesize = Context.getTypeSize(BaseType);
15556
15557 // Handle ptrarith_typesize being zero, such as when casting to void*.
15558 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
15559 if (!ptrarith_typesize)
15560 ptrarith_typesize = Context.getCharWidth();
15561
15562 if (ptrarith_typesize != array_typesize) {
15563 // There's a cast to a different size type involved.
15564 uint64_t ratio = array_typesize / ptrarith_typesize;
15565
15566 // TODO: Be smarter about handling cases where array_typesize is not a
15567 // multiple of ptrarith_typesize.
15568 if (ptrarith_typesize * ratio == array_typesize)
15569 size *= llvm::APInt(size.getBitWidth(), ratio);
15570 }
15571 }
15572
15573 if (size.getBitWidth() > index.getBitWidth())
15574 index = index.zext(size.getBitWidth());
15575 else if (size.getBitWidth() < index.getBitWidth())
15576 size = size.zext(index.getBitWidth());
15577
15578 // For array subscripting the index must be less than size, but for pointer
15579 // arithmetic also allow the index (offset) to be equal to size since
15580 // computing the next address after the end of the array is legal and
15581 // commonly done e.g. in C++ iterators and range-based for loops.
15582 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15583 return;
15584
15585 // Suppress the warning if the subscript expression (as identified by the
15586 // ']' location) and the index expression are both from macro expansions
15587 // within a system header.
15588 if (ASE) {
15589 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15590 ASE->getRBracketLoc());
15591 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15592 SourceLocation IndexLoc =
15593 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15594 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15595 return;
15596 }
15597 }
15598
15599 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15600 : diag::warn_ptr_arith_exceeds_bounds;
15601 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
15602 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
15603
15604 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15605 PDiag(DiagID)
15606 << index << ArrayTy->desugar() << CastMsg
15607 << CastMsgTy << IndexExpr->getSourceRange());
15608 } else {
15609 unsigned DiagID = diag::warn_array_index_precedes_bounds;
15610 if (!ASE) {
15611 DiagID = diag::warn_ptr_arith_precedes_bounds;
15612 if (index.isNegative()) index = -index;
15613 }
15614
15615 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15616 PDiag(DiagID) << index << IndexExpr->getSourceRange());
15617 }
15618
15619 const NamedDecl *ND = nullptr;
15620 // Try harder to find a NamedDecl to point at in the note.
15621 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15622 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15623 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15624 ND = DRE->getDecl();
15625 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15626 ND = ME->getMemberDecl();
15627
15628 if (ND)
15629 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15630 PDiag(diag::note_array_declared_here) << ND);
15631}
15632
15633void Sema::CheckArrayAccess(const Expr *expr) {
15634 int AllowOnePastEnd = 0;
15635 while (expr) {
15636 expr = expr->IgnoreParenImpCasts();
15637 switch (expr->getStmtClass()) {
15638 case Stmt::ArraySubscriptExprClass: {
15639 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15640 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15641 AllowOnePastEnd > 0);
15642 expr = ASE->getBase();
15643 break;
15644 }
15645 case Stmt::MemberExprClass: {
15646 expr = cast<MemberExpr>(expr)->getBase();
15647 break;
15648 }
15649 case Stmt::CXXMemberCallExprClass: {
15650 expr = cast<CXXMemberCallExpr>(expr)->getImplicitObjectArgument();
15651 break;
15652 }
15653 case Stmt::ArraySectionExprClass: {
15654 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
15655 // FIXME: We should probably be checking all of the elements to the
15656 // 'length' here as well.
15657 if (ASE->getLowerBound())
15658 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15659 /*ASE=*/nullptr, AllowOnePastEnd > 0);
15660 return;
15661 }
15662 case Stmt::UnaryOperatorClass: {
15663 // Only unwrap the * and & unary operators
15664 const UnaryOperator *UO = cast<UnaryOperator>(expr);
15665 expr = UO->getSubExpr();
15666 switch (UO->getOpcode()) {
15667 case UO_AddrOf:
15668 AllowOnePastEnd++;
15669 break;
15670 case UO_Deref:
15671 AllowOnePastEnd--;
15672 break;
15673 default:
15674 return;
15675 }
15676 break;
15677 }
15678 case Stmt::ConditionalOperatorClass: {
15679 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15680 if (const Expr *lhs = cond->getLHS())
15681 CheckArrayAccess(lhs);
15682 if (const Expr *rhs = cond->getRHS())
15683 CheckArrayAccess(rhs);
15684 return;
15685 }
15686 case Stmt::CXXOperatorCallExprClass: {
15687 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15688 for (const auto *Arg : OCE->arguments())
15689 CheckArrayAccess(Arg);
15690 return;
15691 }
15692 default:
15693 return;
15694 }
15695 }
15696}
15697
15699 Expr *RHS, bool isProperty) {
15700 // Check if RHS is an Objective-C object literal, which also can get
15701 // immediately zapped in a weak reference. Note that we explicitly
15702 // allow ObjCStringLiterals, since those are designed to never really die.
15703 RHS = RHS->IgnoreParenImpCasts();
15704
15705 // This enum needs to match with the 'select' in
15706 // warn_objc_arc_literal_assign (off-by-1).
15708 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
15709 return false;
15710
15711 S.Diag(Loc, diag::warn_arc_literal_assign)
15712 << (unsigned) Kind
15713 << (isProperty ? 0 : 1)
15714 << RHS->getSourceRange();
15715
15716 return true;
15717}
15718
15721 Expr *RHS, bool isProperty) {
15722 // Strip off any implicit cast added to get to the one ARC-specific.
15723 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15724 if (cast->getCastKind() == CK_ARCConsumeObject) {
15725 S.Diag(Loc, diag::warn_arc_retained_assign)
15727 << (isProperty ? 0 : 1)
15728 << RHS->getSourceRange();
15729 return true;
15730 }
15731 RHS = cast->getSubExpr();
15732 }
15733
15734 if (LT == Qualifiers::OCL_Weak &&
15735 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15736 return true;
15737
15738 return false;
15739}
15740
15742 QualType LHS, Expr *RHS) {
15744
15746 return false;
15747
15748 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15749 return true;
15750
15751 return false;
15752}
15753
15755 Expr *LHS, Expr *RHS) {
15756 QualType LHSType;
15757 // PropertyRef on LHS type need be directly obtained from
15758 // its declaration as it has a PseudoType.
15760 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15761 if (PRE && !PRE->isImplicitProperty()) {
15762 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15763 if (PD)
15764 LHSType = PD->getType();
15765 }
15766
15767 if (LHSType.isNull())
15768 LHSType = LHS->getType();
15769
15771
15772 if (LT == Qualifiers::OCL_Weak) {
15773 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15775 }
15776
15777 if (checkUnsafeAssigns(Loc, LHSType, RHS))
15778 return;
15779
15780 // FIXME. Check for other life times.
15781 if (LT != Qualifiers::OCL_None)
15782 return;
15783
15784 if (PRE) {
15785 if (PRE->isImplicitProperty())
15786 return;
15787 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15788 if (!PD)
15789 return;
15790
15791 unsigned Attributes = PD->getPropertyAttributes();
15792 if (Attributes & ObjCPropertyAttribute::kind_assign) {
15793 // when 'assign' attribute was not explicitly specified
15794 // by user, ignore it and rely on property type itself
15795 // for lifetime info.
15796 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15797 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15798 LHSType->isObjCRetainableType())
15799 return;
15800
15801 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15802 if (cast->getCastKind() == CK_ARCConsumeObject) {
15803 Diag(Loc, diag::warn_arc_retained_property_assign)
15804 << RHS->getSourceRange();
15805 return;
15806 }
15807 RHS = cast->getSubExpr();
15808 }
15809 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15810 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15811 return;
15812 }
15813 }
15814}
15815
15816//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15817
15818static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15819 SourceLocation StmtLoc,
15820 const NullStmt *Body) {
15821 // Do not warn if the body is a macro that expands to nothing, e.g:
15822 //
15823 // #define CALL(x)
15824 // if (condition)
15825 // CALL(0);
15826 if (Body->hasLeadingEmptyMacro())
15827 return false;
15828
15829 // Get line numbers of statement and body.
15830 bool StmtLineInvalid;
15831 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15832 &StmtLineInvalid);
15833 if (StmtLineInvalid)
15834 return false;
15835
15836 bool BodyLineInvalid;
15837 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15838 &BodyLineInvalid);
15839 if (BodyLineInvalid)
15840 return false;
15841
15842 // Warn if null statement and body are on the same line.
15843 if (StmtLine != BodyLine)
15844 return false;
15845
15846 return true;
15847}
15848
15850 const Stmt *Body,
15851 unsigned DiagID) {
15852 // Since this is a syntactic check, don't emit diagnostic for template
15853 // instantiations, this just adds noise.
15855 return;
15856
15857 // The body should be a null statement.
15858 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15859 if (!NBody)
15860 return;
15861
15862 // Do the usual checks.
15863 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15864 return;
15865
15866 Diag(NBody->getSemiLoc(), DiagID);
15867 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15868}
15869
15871 const Stmt *PossibleBody) {
15872 assert(!CurrentInstantiationScope); // Ensured by caller
15873
15874 SourceLocation StmtLoc;
15875 const Stmt *Body;
15876 unsigned DiagID;
15877 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15878 StmtLoc = FS->getRParenLoc();
15879 Body = FS->getBody();
15880 DiagID = diag::warn_empty_for_body;
15881 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15882 StmtLoc = WS->getRParenLoc();
15883 Body = WS->getBody();
15884 DiagID = diag::warn_empty_while_body;
15885 } else
15886 return; // Neither `for' nor `while'.
15887
15888 // The body should be a null statement.
15889 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15890 if (!NBody)
15891 return;
15892
15893 // Skip expensive checks if diagnostic is disabled.
15894 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15895 return;
15896
15897 // Do the usual checks.
15898 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15899 return;
15900
15901 // `for(...);' and `while(...);' are popular idioms, so in order to keep
15902 // noise level low, emit diagnostics only if for/while is followed by a
15903 // CompoundStmt, e.g.:
15904 // for (int i = 0; i < n; i++);
15905 // {
15906 // a(i);
15907 // }
15908 // or if for/while is followed by a statement with more indentation
15909 // than for/while itself:
15910 // for (int i = 0; i < n; i++);
15911 // a(i);
15912 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15913 if (!ProbableTypo) {
15914 bool BodyColInvalid;
15915 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15916 PossibleBody->getBeginLoc(), &BodyColInvalid);
15917 if (BodyColInvalid)
15918 return;
15919
15920 bool StmtColInvalid;
15921 unsigned StmtCol =
15922 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15923 if (StmtColInvalid)
15924 return;
15925
15926 if (BodyCol > StmtCol)
15927 ProbableTypo = true;
15928 }
15929
15930 if (ProbableTypo) {
15931 Diag(NBody->getSemiLoc(), DiagID);
15932 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15933 }
15934}
15935
15936//===--- CHECK: Warn on self move with std::move. -------------------------===//
15937
15938void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15939 SourceLocation OpLoc) {
15940 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15941 return;
15942
15944 return;
15945
15946 // Strip parens and casts away.
15947 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15948 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15949
15950 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
15951 // which we can treat as an inlined std::move
15952 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
15953 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
15954 RHSExpr = CE->getArg(0);
15955 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
15956 CXXSCE && CXXSCE->isXValue())
15957 RHSExpr = CXXSCE->getSubExpr();
15958 else
15959 return;
15960
15961 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15962 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15963
15964 // Two DeclRefExpr's, check that the decls are the same.
15965 if (LHSDeclRef && RHSDeclRef) {
15966 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15967 return;
15968 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15969 RHSDeclRef->getDecl()->getCanonicalDecl())
15970 return;
15971
15972 auto D = Diag(OpLoc, diag::warn_self_move)
15973 << LHSExpr->getType() << LHSExpr->getSourceRange()
15974 << RHSExpr->getSourceRange();
15975 if (const FieldDecl *F =
15977 D << 1 << F
15978 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15979 else
15980 D << 0;
15981 return;
15982 }
15983
15984 // Member variables require a different approach to check for self moves.
15985 // MemberExpr's are the same if every nested MemberExpr refers to the same
15986 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15987 // the base Expr's are CXXThisExpr's.
15988 const Expr *LHSBase = LHSExpr;
15989 const Expr *RHSBase = RHSExpr;
15990 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15991 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15992 if (!LHSME || !RHSME)
15993 return;
15994
15995 while (LHSME && RHSME) {
15996 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15997 RHSME->getMemberDecl()->getCanonicalDecl())
15998 return;
15999
16000 LHSBase = LHSME->getBase();
16001 RHSBase = RHSME->getBase();
16002 LHSME = dyn_cast<MemberExpr>(LHSBase);
16003 RHSME = dyn_cast<MemberExpr>(RHSBase);
16004 }
16005
16006 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16007 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16008 if (LHSDeclRef && RHSDeclRef) {
16009 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16010 return;
16011 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16012 RHSDeclRef->getDecl()->getCanonicalDecl())
16013 return;
16014
16015 Diag(OpLoc, diag::warn_self_move)
16016 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16017 << RHSExpr->getSourceRange();
16018 return;
16019 }
16020
16021 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16022 Diag(OpLoc, diag::warn_self_move)
16023 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16024 << RHSExpr->getSourceRange();
16025}
16026
16027//===--- Layout compatibility ----------------------------------------------//
16028
16029static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16030
16031/// Check if two enumeration types are layout-compatible.
16032static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16033 const EnumDecl *ED2) {
16034 // C++11 [dcl.enum] p8:
16035 // Two enumeration types are layout-compatible if they have the same
16036 // underlying type.
16037 return ED1->isComplete() && ED2->isComplete() &&
16038 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16039}
16040
16041/// Check if two fields are layout-compatible.
16042/// Can be used on union members, which are exempt from alignment requirement
16043/// of common initial sequence.
16044static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16045 const FieldDecl *Field2,
16046 bool AreUnionMembers = false) {
16047#ifndef NDEBUG
16048 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16049 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16050 assert(((Field1Parent->isStructureOrClassType() &&
16051 Field2Parent->isStructureOrClassType()) ||
16052 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16053 "Can't evaluate layout compatibility between a struct field and a "
16054 "union field.");
16055 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16056 (AreUnionMembers && Field1Parent->isUnionType())) &&
16057 "AreUnionMembers should be 'true' for union fields (only).");
16058#endif
16059
16060 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16061 return false;
16062
16063 if (Field1->isBitField() != Field2->isBitField())
16064 return false;
16065
16066 if (Field1->isBitField()) {
16067 // Make sure that the bit-fields are the same length.
16068 unsigned Bits1 = Field1->getBitWidthValue();
16069 unsigned Bits2 = Field2->getBitWidthValue();
16070
16071 if (Bits1 != Bits2)
16072 return false;
16073 }
16074
16075 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16076 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16077 return false;
16078
16079 if (!AreUnionMembers &&
16080 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16081 return false;
16082
16083 return true;
16084}
16085
16086/// Check if two standard-layout structs are layout-compatible.
16087/// (C++11 [class.mem] p17)
16088static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16089 const RecordDecl *RD2) {
16090 // Get to the class where the fields are declared
16091 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
16092 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16093
16094 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
16095 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16096
16097 // Check the fields.
16098 return llvm::equal(RD1->fields(), RD2->fields(),
16099 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16100 return isLayoutCompatible(C, F1, F2);
16101 });
16102}
16103
16104/// Check if two standard-layout unions are layout-compatible.
16105/// (C++11 [class.mem] p18)
16106static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16107 const RecordDecl *RD2) {
16108 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16109 RD2->fields());
16110
16111 for (auto *Field1 : RD1->fields()) {
16112 auto I = UnmatchedFields.begin();
16113 auto E = UnmatchedFields.end();
16114
16115 for ( ; I != E; ++I) {
16116 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
16117 bool Result = UnmatchedFields.erase(*I);
16118 (void) Result;
16119 assert(Result);
16120 break;
16121 }
16122 }
16123 if (I == E)
16124 return false;
16125 }
16126
16127 return UnmatchedFields.empty();
16128}
16129
16130static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16131 const RecordDecl *RD2) {
16132 if (RD1->isUnion() != RD2->isUnion())
16133 return false;
16134
16135 if (RD1->isUnion())
16136 return isLayoutCompatibleUnion(C, RD1, RD2);
16137 else
16138 return isLayoutCompatibleStruct(C, RD1, RD2);
16139}
16140
16141/// Check if two types are layout-compatible in C++11 sense.
16142static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16143 if (T1.isNull() || T2.isNull())
16144 return false;
16145
16146 // C++20 [basic.types] p11:
16147 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16148 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16149 // or layout-compatible standard-layout class types (11.4).
16152
16153 if (C.hasSameType(T1, T2))
16154 return true;
16155
16156 const Type::TypeClass TC1 = T1->getTypeClass();
16157 const Type::TypeClass TC2 = T2->getTypeClass();
16158
16159 if (TC1 != TC2)
16160 return false;
16161
16162 if (TC1 == Type::Enum)
16163 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
16164 if (TC1 == Type::Record) {
16165 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16166 return false;
16167
16169 T2->castAsRecordDecl());
16170 }
16171
16172 return false;
16173}
16174
16176 return isLayoutCompatible(getASTContext(), T1, T2);
16177}
16178
16179//===-------------- Pointer interconvertibility ----------------------------//
16180
16182 const TypeSourceInfo *Derived) {
16183 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16184 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16185
16186 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16187 getASTContext().hasSameType(BaseT, DerivedT))
16188 return true;
16189
16190 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
16191 return false;
16192
16193 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16194 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16195 return true;
16196
16197 return false;
16198}
16199
16200//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16201
16202/// Given a type tag expression find the type tag itself.
16203///
16204/// \param TypeExpr Type tag expression, as it appears in user's code.
16205///
16206/// \param VD Declaration of an identifier that appears in a type tag.
16207///
16208/// \param MagicValue Type tag magic value.
16209///
16210/// \param isConstantEvaluated whether the evalaution should be performed in
16211
16212/// constant context.
16213static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16214 const ValueDecl **VD, uint64_t *MagicValue,
16215 bool isConstantEvaluated) {
16216 while(true) {
16217 if (!TypeExpr)
16218 return false;
16219
16220 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16221
16222 switch (TypeExpr->getStmtClass()) {
16223 case Stmt::UnaryOperatorClass: {
16224 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16225 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16226 TypeExpr = UO->getSubExpr();
16227 continue;
16228 }
16229 return false;
16230 }
16231
16232 case Stmt::DeclRefExprClass: {
16233 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16234 *VD = DRE->getDecl();
16235 return true;
16236 }
16237
16238 case Stmt::IntegerLiteralClass: {
16239 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16240 llvm::APInt MagicValueAPInt = IL->getValue();
16241 if (MagicValueAPInt.getActiveBits() <= 64) {
16242 *MagicValue = MagicValueAPInt.getZExtValue();
16243 return true;
16244 } else
16245 return false;
16246 }
16247
16248 case Stmt::BinaryConditionalOperatorClass:
16249 case Stmt::ConditionalOperatorClass: {
16250 const AbstractConditionalOperator *ACO =
16252 bool Result;
16253 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16254 isConstantEvaluated)) {
16255 if (Result)
16256 TypeExpr = ACO->getTrueExpr();
16257 else
16258 TypeExpr = ACO->getFalseExpr();
16259 continue;
16260 }
16261 return false;
16262 }
16263
16264 case Stmt::BinaryOperatorClass: {
16265 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16266 if (BO->getOpcode() == BO_Comma) {
16267 TypeExpr = BO->getRHS();
16268 continue;
16269 }
16270 return false;
16271 }
16272
16273 default:
16274 return false;
16275 }
16276 }
16277}
16278
16279/// Retrieve the C type corresponding to type tag TypeExpr.
16280///
16281/// \param TypeExpr Expression that specifies a type tag.
16282///
16283/// \param MagicValues Registered magic values.
16284///
16285/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16286/// kind.
16287///
16288/// \param TypeInfo Information about the corresponding C type.
16289///
16290/// \param isConstantEvaluated whether the evalaution should be performed in
16291/// constant context.
16292///
16293/// \returns true if the corresponding C type was found.
16295 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16296 const ASTContext &Ctx,
16297 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16298 *MagicValues,
16299 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16300 bool isConstantEvaluated) {
16301 FoundWrongKind = false;
16302
16303 // Variable declaration that has type_tag_for_datatype attribute.
16304 const ValueDecl *VD = nullptr;
16305
16306 uint64_t MagicValue;
16307
16308 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16309 return false;
16310
16311 if (VD) {
16312 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16313 if (I->getArgumentKind() != ArgumentKind) {
16314 FoundWrongKind = true;
16315 return false;
16316 }
16317 TypeInfo.Type = I->getMatchingCType();
16318 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16319 TypeInfo.MustBeNull = I->getMustBeNull();
16320 return true;
16321 }
16322 return false;
16323 }
16324
16325 if (!MagicValues)
16326 return false;
16327
16328 llvm::DenseMap<Sema::TypeTagMagicValue,
16330 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16331 if (I == MagicValues->end())
16332 return false;
16333
16334 TypeInfo = I->second;
16335 return true;
16336}
16337
16339 uint64_t MagicValue, QualType Type,
16340 bool LayoutCompatible,
16341 bool MustBeNull) {
16342 if (!TypeTagForDatatypeMagicValues)
16343 TypeTagForDatatypeMagicValues.reset(
16344 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16345
16346 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16347 (*TypeTagForDatatypeMagicValues)[Magic] =
16348 TypeTagData(Type, LayoutCompatible, MustBeNull);
16349}
16350
16351static bool IsSameCharType(QualType T1, QualType T2) {
16352 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16353 if (!BT1)
16354 return false;
16355
16356 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16357 if (!BT2)
16358 return false;
16359
16360 BuiltinType::Kind T1Kind = BT1->getKind();
16361 BuiltinType::Kind T2Kind = BT2->getKind();
16362
16363 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16364 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16365 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16366 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16367}
16368
16369void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16370 const ArrayRef<const Expr *> ExprArgs,
16371 SourceLocation CallSiteLoc) {
16372 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16373 bool IsPointerAttr = Attr->getIsPointer();
16374
16375 // Retrieve the argument representing the 'type_tag'.
16376 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16377 if (TypeTagIdxAST >= ExprArgs.size()) {
16378 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16379 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16380 return;
16381 }
16382 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16383 bool FoundWrongKind;
16384 TypeTagData TypeInfo;
16385 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16386 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16387 TypeInfo, isConstantEvaluatedContext())) {
16388 if (FoundWrongKind)
16389 Diag(TypeTagExpr->getExprLoc(),
16390 diag::warn_type_tag_for_datatype_wrong_kind)
16391 << TypeTagExpr->getSourceRange();
16392 return;
16393 }
16394
16395 // Retrieve the argument representing the 'arg_idx'.
16396 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16397 if (ArgumentIdxAST >= ExprArgs.size()) {
16398 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16399 << 1 << Attr->getArgumentIdx().getSourceIndex();
16400 return;
16401 }
16402 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16403 if (IsPointerAttr) {
16404 // Skip implicit cast of pointer to `void *' (as a function argument).
16405 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16406 if (ICE->getType()->isVoidPointerType() &&
16407 ICE->getCastKind() == CK_BitCast)
16408 ArgumentExpr = ICE->getSubExpr();
16409 }
16410 QualType ArgumentType = ArgumentExpr->getType();
16411
16412 // Passing a `void*' pointer shouldn't trigger a warning.
16413 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16414 return;
16415
16416 if (TypeInfo.MustBeNull) {
16417 // Type tag with matching void type requires a null pointer.
16418 if (!ArgumentExpr->isNullPointerConstant(Context,
16420 Diag(ArgumentExpr->getExprLoc(),
16421 diag::warn_type_safety_null_pointer_required)
16422 << ArgumentKind->getName()
16423 << ArgumentExpr->getSourceRange()
16424 << TypeTagExpr->getSourceRange();
16425 }
16426 return;
16427 }
16428
16429 QualType RequiredType = TypeInfo.Type;
16430 if (IsPointerAttr)
16431 RequiredType = Context.getPointerType(RequiredType);
16432
16433 bool mismatch = false;
16434 if (!TypeInfo.LayoutCompatible) {
16435 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16436
16437 // C++11 [basic.fundamental] p1:
16438 // Plain char, signed char, and unsigned char are three distinct types.
16439 //
16440 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16441 // char' depending on the current char signedness mode.
16442 if (mismatch)
16443 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16444 RequiredType->getPointeeType())) ||
16445 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16446 mismatch = false;
16447 } else
16448 if (IsPointerAttr)
16449 mismatch = !isLayoutCompatible(Context,
16450 ArgumentType->getPointeeType(),
16451 RequiredType->getPointeeType());
16452 else
16453 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16454
16455 if (mismatch)
16456 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16457 << ArgumentType << ArgumentKind
16458 << TypeInfo.LayoutCompatible << RequiredType
16459 << ArgumentExpr->getSourceRange()
16460 << TypeTagExpr->getSourceRange();
16461}
16462
16463void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16464 CharUnits Alignment) {
16465 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
16466 Alignment);
16467}
16468
16470 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16471 const NamedDecl *ND = m.RD;
16472 if (ND->getName().empty()) {
16473 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16474 ND = TD;
16475 }
16476 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16477 << m.MD << ND << m.E->getSourceRange();
16478 }
16480}
16481
16483 E = E->IgnoreParens();
16484 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16485 return;
16486 if (isa<UnaryOperator>(E) &&
16487 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16488 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16489 if (isa<MemberExpr>(Op)) {
16490 auto &MisalignedMembersForExpr =
16492 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
16493 if (MA != MisalignedMembersForExpr.end() &&
16494 (T->isDependentType() || T->isIntegerType() ||
16495 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16496 Context.getTypeAlignInChars(
16497 T->getPointeeType()) <= MA->Alignment))))
16498 MisalignedMembersForExpr.erase(MA);
16499 }
16500 }
16501}
16502
16504 Expr *E,
16505 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16506 Action) {
16507 const auto *ME = dyn_cast<MemberExpr>(E);
16508 if (!ME)
16509 return;
16510
16511 // No need to check expressions with an __unaligned-qualified type.
16512 if (E->getType().getQualifiers().hasUnaligned())
16513 return;
16514
16515 // For a chain of MemberExpr like "a.b.c.d" this list
16516 // will keep FieldDecl's like [d, c, b].
16517 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16518 const MemberExpr *TopME = nullptr;
16519 bool AnyIsPacked = false;
16520 do {
16521 QualType BaseType = ME->getBase()->getType();
16522 if (BaseType->isDependentType())
16523 return;
16524 if (ME->isArrow())
16525 BaseType = BaseType->getPointeeType();
16526 auto *RD = BaseType->castAsRecordDecl();
16527 if (RD->isInvalidDecl())
16528 return;
16529
16530 ValueDecl *MD = ME->getMemberDecl();
16531 auto *FD = dyn_cast<FieldDecl>(MD);
16532 // We do not care about non-data members.
16533 if (!FD || FD->isInvalidDecl())
16534 return;
16535
16536 AnyIsPacked =
16537 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16538 ReverseMemberChain.push_back(FD);
16539
16540 TopME = ME;
16541 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16542 } while (ME);
16543 assert(TopME && "We did not compute a topmost MemberExpr!");
16544
16545 // Not the scope of this diagnostic.
16546 if (!AnyIsPacked)
16547 return;
16548
16549 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16550 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16551 // TODO: The innermost base of the member expression may be too complicated.
16552 // For now, just disregard these cases. This is left for future
16553 // improvement.
16554 if (!DRE && !isa<CXXThisExpr>(TopBase))
16555 return;
16556
16557 // Alignment expected by the whole expression.
16558 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16559
16560 // No need to do anything else with this case.
16561 if (ExpectedAlignment.isOne())
16562 return;
16563
16564 // Synthesize offset of the whole access.
16565 CharUnits Offset;
16566 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16567 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16568
16569 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16570 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16571 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
16572
16573 // The base expression of the innermost MemberExpr may give
16574 // stronger guarantees than the class containing the member.
16575 if (DRE && !TopME->isArrow()) {
16576 const ValueDecl *VD = DRE->getDecl();
16577 if (!VD->getType()->isReferenceType())
16578 CompleteObjectAlignment =
16579 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16580 }
16581
16582 // Check if the synthesized offset fulfills the alignment.
16583 if (!Offset.isMultipleOf(ExpectedAlignment) ||
16584 // It may fulfill the offset it but the effective alignment may still be
16585 // lower than the expected expression alignment.
16586 CompleteObjectAlignment < ExpectedAlignment) {
16587 // If this happens, we want to determine a sensible culprit of this.
16588 // Intuitively, watching the chain of member expressions from right to
16589 // left, we start with the required alignment (as required by the field
16590 // type) but some packed attribute in that chain has reduced the alignment.
16591 // It may happen that another packed structure increases it again. But if
16592 // we are here such increase has not been enough. So pointing the first
16593 // FieldDecl that either is packed or else its RecordDecl is,
16594 // seems reasonable.
16595 FieldDecl *FD = nullptr;
16596 CharUnits Alignment;
16597 for (FieldDecl *FDI : ReverseMemberChain) {
16598 if (FDI->hasAttr<PackedAttr>() ||
16599 FDI->getParent()->hasAttr<PackedAttr>()) {
16600 FD = FDI;
16601 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
16602 Context.getTypeAlignInChars(
16603 Context.getCanonicalTagType(FD->getParent())));
16604 break;
16605 }
16606 }
16607 assert(FD && "We did not find a packed FieldDecl!");
16608 Action(E, FD->getParent(), FD, Alignment);
16609 }
16610}
16611
16612void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16613 using namespace std::placeholders;
16614
16616 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16617 _2, _3, _4));
16618}
16619
16621 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16622 if (checkArgCount(TheCall, 1))
16623 return true;
16624
16625 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
16626 if (A.isInvalid())
16627 return true;
16628
16629 TheCall->setArg(0, A.get());
16630 QualType TyA = A.get()->getType();
16631
16632 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
16633 ArgTyRestr, 1))
16634 return true;
16635
16636 TheCall->setType(TyA);
16637 return false;
16638}
16639
16640bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
16641 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16642 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
16643 TheCall->setType(*Res);
16644 return false;
16645 }
16646 return true;
16647}
16648
16650 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
16651 if (!Res)
16652 return true;
16653
16654 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
16655 TheCall->setType(VecTy0->getElementType());
16656 else
16657 TheCall->setType(*Res);
16658
16659 return false;
16660}
16661
16663 SourceLocation Loc) {
16665 R = RHS->getEnumCoercedType(S.Context);
16666 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
16668 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
16669 << LHS->getSourceRange() << RHS->getSourceRange()
16670 << /*Arithmetic Between*/ 0 << L << R;
16671 }
16672 return false;
16673}
16674
16675/// Check if all arguments have the same type. If the types don't match, emit an
16676/// error message and return true. Otherwise return false.
16677///
16678/// For scalars we directly compare their unqualified types. But even if we
16679/// compare unqualified vector types, a difference in qualifiers in the element
16680/// types can make the vector types be considered not equal. For example,
16681/// vector of 4 'const float' values vs vector of 4 'float' values.
16682/// So we compare unqualified types of their elements and number of elements.
16684 ArrayRef<Expr *> Args) {
16685 assert(!Args.empty() && "Should have at least one argument.");
16686
16687 Expr *Arg0 = Args.front();
16688 QualType Ty0 = Arg0->getType();
16689
16690 auto EmitError = [&](Expr *ArgI) {
16691 SemaRef.Diag(Arg0->getBeginLoc(),
16692 diag::err_typecheck_call_different_arg_types)
16693 << Arg0->getType() << ArgI->getType();
16694 };
16695
16696 // Compare scalar types.
16697 if (!Ty0->isVectorType()) {
16698 for (Expr *ArgI : Args.drop_front())
16699 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
16700 EmitError(ArgI);
16701 return true;
16702 }
16703
16704 return false;
16705 }
16706
16707 // Compare vector types.
16708 const auto *Vec0 = Ty0->castAs<VectorType>();
16709 for (Expr *ArgI : Args.drop_front()) {
16710 const auto *VecI = ArgI->getType()->getAs<VectorType>();
16711 if (!VecI ||
16712 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
16713 VecI->getElementType()) ||
16714 Vec0->getNumElements() != VecI->getNumElements()) {
16715 EmitError(ArgI);
16716 return true;
16717 }
16718 }
16719
16720 return false;
16721}
16722
16723std::optional<QualType>
16725 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16726 if (checkArgCount(TheCall, 2))
16727 return std::nullopt;
16728
16730 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
16731 return std::nullopt;
16732
16733 Expr *Args[2];
16734 for (int I = 0; I < 2; ++I) {
16735 ExprResult Converted =
16736 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16737 if (Converted.isInvalid())
16738 return std::nullopt;
16739 Args[I] = Converted.get();
16740 }
16741
16742 SourceLocation LocA = Args[0]->getBeginLoc();
16743 QualType TyA = Args[0]->getType();
16744
16745 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
16746 return std::nullopt;
16747
16748 if (checkBuiltinVectorMathArgTypes(*this, Args))
16749 return std::nullopt;
16750
16751 TheCall->setArg(0, Args[0]);
16752 TheCall->setArg(1, Args[1]);
16753 return TyA;
16754}
16755
16757 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16758 if (checkArgCount(TheCall, 3))
16759 return true;
16760
16761 SourceLocation Loc = TheCall->getExprLoc();
16762 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
16763 TheCall->getArg(1), Loc) ||
16764 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
16765 TheCall->getArg(2), Loc))
16766 return true;
16767
16768 Expr *Args[3];
16769 for (int I = 0; I < 3; ++I) {
16770 ExprResult Converted =
16771 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16772 if (Converted.isInvalid())
16773 return true;
16774 Args[I] = Converted.get();
16775 }
16776
16777 int ArgOrdinal = 1;
16778 for (Expr *Arg : Args) {
16779 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
16780 ArgTyRestr, ArgOrdinal++))
16781 return true;
16782 }
16783
16784 if (checkBuiltinVectorMathArgTypes(*this, Args))
16785 return true;
16786
16787 for (int I = 0; I < 3; ++I)
16788 TheCall->setArg(I, Args[I]);
16789
16790 TheCall->setType(Args[0]->getType());
16791 return false;
16792}
16793
16794bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16795 if (checkArgCount(TheCall, 1))
16796 return true;
16797
16798 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16799 if (A.isInvalid())
16800 return true;
16801
16802 TheCall->setArg(0, A.get());
16803 return false;
16804}
16805
16806bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
16807 if (checkArgCount(TheCall, 1))
16808 return true;
16809
16810 ExprResult Arg = TheCall->getArg(0);
16811 QualType TyArg = Arg.get()->getType();
16812
16813 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
16814 return Diag(TheCall->getArg(0)->getBeginLoc(),
16815 diag::err_builtin_invalid_arg_type)
16816 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
16817
16818 TheCall->setType(TyArg);
16819 return false;
16820}
16821
16822ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
16823 ExprResult CallResult) {
16824 if (checkArgCount(TheCall, 1))
16825 return ExprError();
16826
16827 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16828 if (MatrixArg.isInvalid())
16829 return MatrixArg;
16830 Expr *Matrix = MatrixArg.get();
16831
16832 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16833 if (!MType) {
16834 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16835 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
16836 << Matrix->getType();
16837 return ExprError();
16838 }
16839
16840 // Create returned matrix type by swapping rows and columns of the argument
16841 // matrix type.
16842 QualType ResultType = Context.getConstantMatrixType(
16843 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16844
16845 // Change the return type to the type of the returned matrix.
16846 TheCall->setType(ResultType);
16847
16848 // Update call argument to use the possibly converted matrix argument.
16849 TheCall->setArg(0, Matrix);
16850 return CallResult;
16851}
16852
16853// Get and verify the matrix dimensions.
16854static std::optional<unsigned>
16856 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
16857 if (!Value) {
16858 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16859 << Name;
16860 return {};
16861 }
16862 uint64_t Dim = Value->getZExtValue();
16863 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
16864 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16865 << Name << S.Context.getLangOpts().MaxMatrixDimension;
16866 return {};
16867 }
16868 return Dim;
16869}
16870
16871ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16872 ExprResult CallResult) {
16873 if (!getLangOpts().MatrixTypes) {
16874 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16875 return ExprError();
16876 }
16877
16878 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
16880 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
16881 << /*column*/ 1 << /*load*/ 0;
16882 return ExprError();
16883 }
16884
16885 if (checkArgCount(TheCall, 4))
16886 return ExprError();
16887
16888 unsigned PtrArgIdx = 0;
16889 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16890 Expr *RowsExpr = TheCall->getArg(1);
16891 Expr *ColumnsExpr = TheCall->getArg(2);
16892 Expr *StrideExpr = TheCall->getArg(3);
16893
16894 bool ArgError = false;
16895
16896 // Check pointer argument.
16897 {
16899 if (PtrConv.isInvalid())
16900 return PtrConv;
16901 PtrExpr = PtrConv.get();
16902 TheCall->setArg(0, PtrExpr);
16903 if (PtrExpr->isTypeDependent()) {
16904 TheCall->setType(Context.DependentTy);
16905 return TheCall;
16906 }
16907 }
16908
16909 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16910 QualType ElementTy;
16911 if (!PtrTy) {
16912 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16913 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
16914 << PtrExpr->getType();
16915 ArgError = true;
16916 } else {
16917 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16918
16920 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16921 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
16922 << /* no fp */ 0 << PtrExpr->getType();
16923 ArgError = true;
16924 }
16925 }
16926
16927 // Apply default Lvalue conversions and convert the expression to size_t.
16928 auto ApplyArgumentConversions = [this](Expr *E) {
16930 if (Conv.isInvalid())
16931 return Conv;
16932
16933 return tryConvertExprToType(Conv.get(), Context.getSizeType());
16934 };
16935
16936 // Apply conversion to row and column expressions.
16937 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16938 if (!RowsConv.isInvalid()) {
16939 RowsExpr = RowsConv.get();
16940 TheCall->setArg(1, RowsExpr);
16941 } else
16942 RowsExpr = nullptr;
16943
16944 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16945 if (!ColumnsConv.isInvalid()) {
16946 ColumnsExpr = ColumnsConv.get();
16947 TheCall->setArg(2, ColumnsExpr);
16948 } else
16949 ColumnsExpr = nullptr;
16950
16951 // If any part of the result matrix type is still pending, just use
16952 // Context.DependentTy, until all parts are resolved.
16953 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16954 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16955 TheCall->setType(Context.DependentTy);
16956 return CallResult;
16957 }
16958
16959 // Check row and column dimensions.
16960 std::optional<unsigned> MaybeRows;
16961 if (RowsExpr)
16962 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16963
16964 std::optional<unsigned> MaybeColumns;
16965 if (ColumnsExpr)
16966 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16967
16968 // Check stride argument.
16969 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16970 if (StrideConv.isInvalid())
16971 return ExprError();
16972 StrideExpr = StrideConv.get();
16973 TheCall->setArg(3, StrideExpr);
16974
16975 if (MaybeRows) {
16976 if (std::optional<llvm::APSInt> Value =
16977 StrideExpr->getIntegerConstantExpr(Context)) {
16978 uint64_t Stride = Value->getZExtValue();
16979 if (Stride < *MaybeRows) {
16980 Diag(StrideExpr->getBeginLoc(),
16981 diag::err_builtin_matrix_stride_too_small);
16982 ArgError = true;
16983 }
16984 }
16985 }
16986
16987 if (ArgError || !MaybeRows || !MaybeColumns)
16988 return ExprError();
16989
16990 TheCall->setType(
16991 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16992 return CallResult;
16993}
16994
16995ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16996 ExprResult CallResult) {
16997 if (!getLangOpts().MatrixTypes) {
16998 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16999 return ExprError();
17000 }
17001
17002 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17004 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17005 << /*column*/ 1 << /*store*/ 1;
17006 return ExprError();
17007 }
17008
17009 if (checkArgCount(TheCall, 3))
17010 return ExprError();
17011
17012 unsigned PtrArgIdx = 1;
17013 Expr *MatrixExpr = TheCall->getArg(0);
17014 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17015 Expr *StrideExpr = TheCall->getArg(2);
17016
17017 bool ArgError = false;
17018
17019 {
17020 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17021 if (MatrixConv.isInvalid())
17022 return MatrixConv;
17023 MatrixExpr = MatrixConv.get();
17024 TheCall->setArg(0, MatrixExpr);
17025 }
17026 if (MatrixExpr->isTypeDependent()) {
17027 TheCall->setType(Context.DependentTy);
17028 return TheCall;
17029 }
17030
17031 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17032 if (!MatrixTy) {
17033 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17034 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17035 ArgError = true;
17036 }
17037
17038 {
17040 if (PtrConv.isInvalid())
17041 return PtrConv;
17042 PtrExpr = PtrConv.get();
17043 TheCall->setArg(1, PtrExpr);
17044 if (PtrExpr->isTypeDependent()) {
17045 TheCall->setType(Context.DependentTy);
17046 return TheCall;
17047 }
17048 }
17049
17050 // Check pointer argument.
17051 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17052 if (!PtrTy) {
17053 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17054 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17055 << PtrExpr->getType();
17056 ArgError = true;
17057 } else {
17058 QualType ElementTy = PtrTy->getPointeeType();
17059 if (ElementTy.isConstQualified()) {
17060 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17061 ArgError = true;
17062 }
17063 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17064 if (MatrixTy &&
17065 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17066 Diag(PtrExpr->getBeginLoc(),
17067 diag::err_builtin_matrix_pointer_arg_mismatch)
17068 << ElementTy << MatrixTy->getElementType();
17069 ArgError = true;
17070 }
17071 }
17072
17073 // Apply default Lvalue conversions and convert the stride expression to
17074 // size_t.
17075 {
17076 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17077 if (StrideConv.isInvalid())
17078 return StrideConv;
17079
17080 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17081 if (StrideConv.isInvalid())
17082 return StrideConv;
17083 StrideExpr = StrideConv.get();
17084 TheCall->setArg(2, StrideExpr);
17085 }
17086
17087 // Check stride argument.
17088 if (MatrixTy) {
17089 if (std::optional<llvm::APSInt> Value =
17090 StrideExpr->getIntegerConstantExpr(Context)) {
17091 uint64_t Stride = Value->getZExtValue();
17092 if (Stride < MatrixTy->getNumRows()) {
17093 Diag(StrideExpr->getBeginLoc(),
17094 diag::err_builtin_matrix_stride_too_small);
17095 ArgError = true;
17096 }
17097 }
17098 }
17099
17100 if (ArgError)
17101 return ExprError();
17102
17103 return CallResult;
17104}
17105
17107 const NamedDecl *Callee) {
17108 // This warning does not make sense in code that has no runtime behavior.
17110 return;
17111
17112 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17113
17114 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17115 return;
17116
17117 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17118 // all TCBs the callee is a part of.
17119 llvm::StringSet<> CalleeTCBs;
17120 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17121 CalleeTCBs.insert(A->getTCBName());
17122 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17123 CalleeTCBs.insert(A->getTCBName());
17124
17125 // Go through the TCBs the caller is a part of and emit warnings if Caller
17126 // is in a TCB that the Callee is not.
17127 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17128 StringRef CallerTCB = A->getTCBName();
17129 if (CalleeTCBs.count(CallerTCB) == 0) {
17130 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17131 << Callee << CallerTCB;
17132 }
17133 }
17134}
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:797
Builtin::Context & BuiltinInfo
Definition ASTContext.h:799
const LangOptions & getLangOpts() const
Definition ASTContext.h:951
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:850
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:916
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:3730
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3744
QualType getElementType() const
Definition TypeBase.h:3742
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:3550
This class is used for builtin types like 'int'.
Definition TypeBase.h:3172
bool isInteger() const
Definition TypeBase.h:3233
bool isFloatingPoint() const
Definition TypeBase.h:3245
bool isSignedInteger() const
Definition TypeBase.h:3237
bool isUnsignedInteger() const
Definition TypeBase.h:3241
Kind getKind() const
Definition TypeBase.h:3220
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:3624
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:3768
QualType desugar() const
Definition TypeBase.h:3869
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3824
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:4395
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4417
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:5655
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:3423
Represents an enum.
Definition Decl.h:4013
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4245
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4186
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:4211
@ 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:3670
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:4050
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:4275
Represents a member of a struct/union/class.
Definition Decl.h:3160
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3263
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp: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:3396
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3276
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
llvm::APFloat getValue() const
Definition Expr.h:1669
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2880
Represents a function declaration or definition.
Definition Decl.h:2000
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4554
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3763
param_iterator param_end()
Definition Decl.h:2787
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3866
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
param_iterator param_begin()
Definition Decl.h:2786
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp: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:2929
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:5315
unsigned getNumParams() const
Definition TypeBase.h:5593
QualType getParamType(unsigned i) const
Definition TypeBase.h:5595
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5719
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5604
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5714
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5600
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4511
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4820
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4816
QualType getReturnType() const
Definition TypeBase.h:4851
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:1030
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1066
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:1113
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
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4366
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:3661
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:1695
bool hasLeadingEmptyMacro() const
Definition Stmt.h:1709
SourceLocation getSemiLoc() const
Definition Stmt.h:1706
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:614
ObjCPropertyDecl * getExplicitProperty() const
Definition ExprObjC.h:703
bool isImplicitProperty() const
Definition ExprObjC.h:700
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:52
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:277
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2185
Represents a parameter to a function.
Definition Decl.h:1790
Pointer-authentication qualifiers.
Definition TypeBase.h:152
@ MaxDiscriminator
The maximum supported pointer-authentication discriminator.
Definition TypeBase.h:232
bool isAddressDiscriminated() const
Definition TypeBase.h:265
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3336
QualType getPointeeType() const
Definition TypeBase.h:3346
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:5170
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8472
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2911
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:8388
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8514
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8428
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:8440
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8482
void removeLocalVolatile()
Definition TypeBase.h:8504
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1185
void removeLocalConst()
Definition TypeBase.h:8496
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8461
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8509
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1683
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8434
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:4327
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4413
field_range fields() const
Definition Decl.h:4530
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4405
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:107
void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg)
Definition SemaPPC.cpp:30
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition SemaPPC.cpp:389
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:10370
ContextualImplicitConverter(bool Suppress=false, bool SuppressConversion=false)
Definition Sema.h:10375
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:1440
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:13114
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1133
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:2660
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9382
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9390
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9427
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:6979
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:2069
SemaHexagon & Hexagon()
Definition Sema.h:1480
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:1674
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:1570
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:1300
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:1510
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1365
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:756
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2629
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:1204
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:2736
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low, int High, bool RangeIsError=true)
BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr TheCall is a constant express...
bool IsLayoutCompatible(QualType T1, QualType T2) const
const LangOptions & getLangOpts() const
Definition Sema.h: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:1455
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:1470
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:1298
static const uint64_t MaximumAlignment
Definition Sema.h:1227
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:956
SemaHLSL & HLSL()
Definition Sema.h:1475
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1495
SemaRISCV & RISCV()
Definition Sema.h:1540
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:2802
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7012
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1686
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:1333
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:2709
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15490
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:2315
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:1438
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:1520
FormatArgumentPassingKind
Definition Sema.h:2639
@ FAPK_Elsewhere
Definition Sema.h:2643
@ FAPK_Fixed
Definition Sema.h:2640
@ FAPK_Variadic
Definition Sema.h:2641
@ FAPK_VAList
Definition Sema.h:2642
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:8228
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:14026
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:2631
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:1530
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:1259
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:1560
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:1303
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:787
DiagnosticsEngine & Diags
Definition Sema.h:1302
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:1505
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:625
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:6279
SemaSPIRV & SPIRV()
Definition Sema.h:1545
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:1485
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6467
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:1565
SemaARM & ARM()
Definition Sema.h:1445
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:1485
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:3838
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3818
bool isUnion() const
Definition Decl.h:3928
Exposes information about the current target.
Definition TargetInfo.h:226
virtual bool supportsCpuSupports() const
virtual bool validateCpuIs(StringRef Name) const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
IntType getSizeType() const
Definition TargetInfo.h:388
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:6226
A container of type source information.
Definition TypeBase.h:8359
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:8370
The base class of the type hierarchy.
Definition TypeBase.h:1839
bool isBlockPointerType() const
Definition TypeBase.h:8645
bool isVoidType() const
Definition TypeBase.h:8991
bool isBooleanType() const
Definition TypeBase.h:9128
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2253
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9178
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:788
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2230
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2307
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2137
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:9158
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:2083
bool isVoidPointerType() const
Definition Type.cpp:713
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2469
bool isArrayType() const
Definition TypeBase.h:8724
bool isCharType() const
Definition Type.cpp:2157
bool isFunctionPointerType() const
Definition TypeBase.h:8692
bool isPointerType() const
Definition TypeBase.h:8625
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9035
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9285
bool isReferenceType() const
Definition TypeBase.h:8649
bool isEnumeralType() const
Definition TypeBase.h:8756
bool isScalarType() const
Definition TypeBase.h:9097
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:1922
bool isVariableArrayType() const
Definition TypeBase.h:8736
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2651
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool isExtVectorType() const
Definition TypeBase.h:8768
bool isExtVectorBoolType() const
Definition TypeBase.h:8772
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2690
bool isBitIntType() const
Definition TypeBase.h:8900
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8960
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8748
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2790
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:2274
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3127
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2601
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9171
bool isAtomicType() const
Definition TypeBase.h:8817
bool isFunctionProtoType() const
Definition TypeBase.h:2607
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3143
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:2808
bool isUnscopedEnumerationType() const
Definition Type.cpp:2150
bool isObjCObjectType() const
Definition TypeBase.h:8808
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9271
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9134
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2516
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:2479
bool isFunctionType() const
Definition TypeBase.h:8621
bool isObjCObjectPointerType() const
Definition TypeBase.h:8804
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2349
bool isStructureOrClassType() const
Definition Type.cpp:707
bool isVectorType() const
Definition TypeBase.h:8764
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2357
bool isFloatingType() const
Definition Type.cpp:2341
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:2284
bool isAnyPointerType() const
Definition TypeBase.h:8633
TypeClass getTypeClass() const
Definition TypeBase.h:2391
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2417
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9218
bool isNullPtrType() const
Definition TypeBase.h:9028
bool isRecordType() const
Definition TypeBase.h:8752
bool isObjCRetainableType() const
Definition Type.cpp:5364
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5094
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2613
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2678
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h: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:4183
unsigned getNumElements() const
Definition TypeBase.h:4198
QualType getElementType() const
Definition TypeBase.h:4197
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2689
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
std::optional< ConversionSpecifier > getStandardSpecifier() const
const OptionalAmount & getFieldWidth() const
bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const
const LengthModifier & getLengthModifier() const
bool hasValidLengthModifier(const TargetInfo &Target, const LangOptions &LO) const
std::optional< LengthModifier > getCorrectedLengthModifier() const
ArgType getArgType(ASTContext &Ctx) const
Class representing optional flags with location and representation information.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
const OptionalFlag & isPrivate() const
const OptionalAmount & getPrecision() const
const OptionalFlag & hasSpacePrefix() const
const OptionalFlag & isSensitive() const
const OptionalFlag & isLeftJustified() const
const OptionalFlag & hasLeadingZeros() const
const OptionalFlag & hasAlternativeForm() const
const PrintfConversionSpecifier & getConversionSpecifier() const
const OptionalFlag & hasPlusPrefix() const
const OptionalFlag & hasThousandsGrouping() const
ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const
Returns the builtin type that a data argument paired with this format specifier should have.
const OptionalFlag & isPublic() const
const ScanfConversionSpecifier & getConversionSpecifier() const
ArgType getArgType(ASTContext &Ctx) const
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
#define bool
Definition gpuintrin.h:32
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition SPIR.cpp:35
Definition SPIR.cpp:47
Common components of both fprintf and fscanf format strings.
bool parseFormatStringHasFormattingSpecifiers(const char *Begin, const char *End, const LangOptions &LO, const TargetInfo &Target)
Return true if the given string has at least one formatting specifier.
bool ParsePrintfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target, bool isFreeBSDKPrintf)
bool ParseScanfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
bool ParseFormatStringHasSArg(const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
Pieces specific to fprintf format strings.
Pieces specific to fscanf format strings.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< PointerType > pointerType
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
ComparisonResult
Indicates the result of a tentative comparison.
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition Types.cpp:216
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ After
Like System, but searched after the system directories.
@ FixIt
Parse and apply any fixits to the source.
bool GT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1334
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1319
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1312
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1326
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2532
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1280
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1341
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:4144
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5935
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5928
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1746
unsigned long uint64_t
long int64_t
#define false
Definition stdbool.h:26
#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:5400
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:13296
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13322
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13312
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13263
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6873
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2651
#define log2(__x)
Definition tgmath.h:970